Merge branch 'dev' into US-09-Activar/DesactivarAdministradoresdeSistema

This commit is contained in:
Mariela 2022-08-02 19:09:58 -06:00
commit 823cba4c3f
19 changed files with 1440 additions and 45 deletions

View File

@ -102,16 +102,27 @@ export class AppController {
allUsersAdminComunidad() {
return this.appService.allUsersAdminComunidad();
}
@Get('user/findGuards/:community')
findGuardsCommunity(@Param('community_id') community_id: string) {
return this.appService.findGuardsCommunity(community_id);
}
@Get('user/findTenants/:community_id')
allUsersTenants(@Param('community_id') paramCommunity_id: string) {
return this.appService.findTenantsCommunity(paramCommunity_id);
}
@Get('user/find/:dni')
findUser(@Param('dni') paramUserDNI: string) {
return this.appService.findUser(paramUserDNI);
}
@Get('user/findUserById/:id')
findUserById(@Param('id') id: string) {
return this.appService.findUserById(id);
}
@Delete('user/deleteAdminSystem/:id')
deleteAdminSystem(@Param('id') id: string) {
return this.appService.deleteAdminSystem(id);
@ -162,7 +173,13 @@ export class AppController {
findCommunityAdmin(@Body('community_id') community_id: string) {
return this.appService.findCommunityAdmin(community_id);
}
@Post('community/changeStatus')
changeStatus(
@Body('id') pId: string,
@Body('status') pStatus: string,
) {
return this.appService.changeStatus(pId, pStatus);
}
// #==== API Common Areas
@Post('commonArea/createCommonArea')
createCommonArea(
@ -191,6 +208,17 @@ export class AppController {
return this.appService.findCommonArea(paramCommonAreaId);
}
@Get('commonArea/findByCommunity/:community_id')
findByCommunity(@Param('community_id') paramCommunityId: string) {
return this.appService.findByCommunity(paramCommunityId);
}
@Delete('commonArea/deleteCommonArea/:id')
deleteCommonArea(@Param('id') id: string) {
return this.appService.deleteCommonArea(id);
}
// #==== API GUEST
//#API userService - create user
@Post('guest/createGuest')

View File

@ -119,6 +119,17 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
allUsersTenants() {
const pattern = { cmd: 'findTenants' };
const payload = {};
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(
map((message: string) => ({ message })),
);
}
//GET parameter from API
findUser(paramUserDNI: string) {
const pattern = { cmd: 'findUserDNI' };
@ -136,6 +147,13 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
findTenantsCommunity(community_id: string) {
const pattern = { cmd: 'findTenantsCommunity' };
const payload = { community_id: community_id };
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
deleteAdminSystem(id: string) {
const pattern = { cmd: 'deleteAdminSystem' };
@ -161,6 +179,24 @@ export class AppService {
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
changeStatus(pId: string, pStatus: string) {
const pattern = { cmd: 'changeStatus' };
const payload = { id: pId, status: pStatus };
return this.clientCommunityApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
//GET parameter from API
findUserById(id: string) {
const pattern = { cmd: 'findById' };
const payload = { id: id };
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
// ====================== COMMUNITIES ===============================
@ -248,6 +284,26 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
//GET parameter from API
findByCommunity(paramCommunityId: string) {
const pattern = { cmd: 'findByCommunity' };
const payload = { community_id: paramCommunityId };
return this.clientCommonAreaApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
//DELETE parameter from API
deleteCommonArea(paramCommonAreaId: string) {
const pattern = { cmd: 'removeCommonArea' };
const payload = { id: paramCommonAreaId };
return this.clientCommonAreaApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
// ====================== GUESTS ===============================
//POST parameter from API

View File

@ -30,7 +30,13 @@ export class CommonAreasController {
@MessagePattern({ cmd: 'removeCommonArea' })
remove(@Payload() id: string) {
let _id = id['_id'];
let _id = id['id'];
return this.commonAreasService.remove(_id);
}
@MessagePattern({ cmd: 'findByCommunity' })
findByCommunity(@Payload() id: string) {
let _community_id = id['community_id'];
return this.commonAreasService.findByCommunity(_community_id);
}
}

View File

@ -35,5 +35,10 @@ export class CommonAreasService {
return this.commonAreaModel.findOneAndUpdate({ _id: id }, {status: '-1'}, {
new: true,
});
};
async findByCommunity(community_id: string): Promise<CommonArea[]> {
return this.commonAreaModel.find({ community_id: community_id }).exec();
}
}

View File

@ -19,6 +19,9 @@ export class CommonArea {
@Prop()
bookable: number; //saber si es necesario reservarlo o no
@Prop()
status: string;
@Prop()
community_id: string;
}

View File

@ -45,4 +45,14 @@ export class CommunitiesController {
let _id = id['_id'];
return this.communitiesService.remove(_id);
}
//cambiar de estado
@MessagePattern({ cmd: 'changeStatus' })
changeStatus(@Payload() body: string) {
let pid = body['id'];
let pstatus = body['status'];
console.log(pid);
console.log(pstatus);
return this.communitiesService.changeStatus(pid,pstatus);
}
}

View File

@ -61,6 +61,12 @@ export class CommunitiesService {
});
}
async changeStatus(id: string, status: string) {
return this.communityModel.findOneAndUpdate({ _id: id }, {status: status}, {
new: true,
});
}
async findCommunityAdmin(community: string, user_type: string) {
const pattern = { cmd: 'findOneCommunityUser' };
const payload = { community_id: community, user_type: user_type };

View File

@ -36,6 +36,9 @@ export class User {
@Prop()
community_id?: string;
@Prop()
number_house?: string;
}
export const UserSchema = SchemaFactory.createForClass(User);

View File

@ -40,12 +40,30 @@ export class UsersController {
return this.userService.findOneByDNI(dni);
}
@MessagePattern({ cmd: 'findById' })
findById(@Payload() id: string) {
let _id = id['id'];
return this.userService.findOne(_id);
}
@MessagePattern({ cmd: 'findGuardsCommunity' })
findGuardsCommunity(@Payload() community_id: string) {
let pcommunity_id = community_id['community_id'];
return this.userService.findGuardsCommunity(pcommunity_id);
}
@MessagePattern({ cmd: 'findTenantsCommunity' })
findTenantsCommunity(@Payload() community_id: string) {
let pcommunity_id = community_id['community_id'];
return this.userService.findTenantsCommunity(pcommunity_id);
}
@MessagePattern({ cmd: 'findTenants' })
findTenants() {
return this.userService.findTenants();
}
@MessagePattern({ cmd: 'updateUser' })
update(@Payload() user: UserDocument) {
return this.userService.update(user.id, user);

View File

@ -25,24 +25,26 @@ export class UsersService {
async createAdminCommunity(user: UserDocument) {
let password = user.password;
let passwordEncriptada = Md5.init(user.password);
user.password = passwordEncriptada;
let password = user.password;
let passwordEncriptada = Md5.init(user.password);
user.password = passwordEncriptada;
this.userModel.create(user)
this.userModel.create(user)
let community = await this.findCommunity(user.community_id);
user.community_id = community['name'];
let community = await this.findCommunity(user.community_id);
user.community_id = community['name'];
const pattern = { cmd: 'emailCreateUserAdminCommunity' };
const payload = { email: user['email'], password: password, name: user['name'],
date_entry: user['date_entry'], community_name: community['name'] };
return this.clientNotificationtApp
.send<string>(pattern, payload)
.pipe(
map((message: string) => ({ message })),
);
const pattern = { cmd: 'emailCreateUserAdminCommunity' };
const payload = {
email: user['email'], password: password, name: user['name'],
date_entry: user['date_entry'], community_name: community['name']
};
return this.clientNotificationtApp
.send<string>(pattern, payload)
.pipe(
map((message: string) => ({ message })),
);
}
async findCommunity(community_id: string) {
@ -123,6 +125,36 @@ export class UsersService {
return this.userModel.find({ user_type: 2 }).exec();
}
//find inquilinos
async findTenants(): Promise<User[]> {
return this.userModel.find({ user_type: 3 }).exec();
}
//find inquilinos
async findTenantsCommunity(pcommunity_id: string) {
//let tenants = await this.findCommunityTenants(pcommunity_id);
return await this.userModel.find({ community_id: pcommunity_id, user_type: 4 })
.then(async (users) => {
if (users) {
await Promise.all(
users.map(async (u) => {
//buscar al usuario con el id de la comunidad anexado
let number_house = await this.findNumHouseTenant(pcommunity_id, u['_id']);
u['number_house'] = number_house;
return u;
}),
)
}
return users;
})
}
async testSendMail(user: UserDocument) {
let passwordEncriptada = Md5.init(user.password);
user.password = passwordEncriptada;
@ -170,5 +202,26 @@ export class UsersService {
});
}
async findNumHouseTenant(community_id: string, tenant_id: string) {
const pattern = { cmd: 'findOneCommunity' }
const payload = { _id: community_id }
let callback = await this.clientCommunityApp
.send<string>(pattern, payload)
.pipe(
map((response: string) => ({ response }))
)
const finalValue = await lastValueFrom(callback);
const response = finalValue['response'];
const houses = response['houses'];
let num_house = "";
await houses.forEach(async house => {
if (tenant_id == house.tenants.tenant_id) {
num_house = house.number_house;
}
})
return num_house;
}
}

View File

@ -27,6 +27,7 @@
"prismjs": "1.9.0",
"react": "^17.0.1",
"react-app-polyfill": "^1.0.6",
"react-cookie": "^4.1.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1",
@ -2475,6 +2476,11 @@
"@babel/types": "^7.3.0"
}
},
"node_modules/@types/cookie": {
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.3.3.tgz",
"integrity": "sha512-LKVP3cgXBT9RYj+t+9FDKwS5tdI+rPBXaNSkma7hvqy35lc7mAokC2zsqWJH0LaqIt3B962nuYI77hsJoT1gow=="
},
"node_modules/@types/eslint-visitor-keys": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@types/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz",
@ -2489,6 +2495,15 @@
"@types/node": "*"
}
},
"node_modules/@types/hoist-non-react-statics": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz",
"integrity": "sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==",
"dependencies": {
"@types/react": "*",
"hoist-non-react-statics": "^3.3.0"
}
},
"node_modules/@types/istanbul-lib-coverage": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz",
@ -2531,11 +2546,31 @@
"resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz",
"integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA=="
},
"node_modules/@types/prop-types": {
"version": "15.7.5",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz",
"integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w=="
},
"node_modules/@types/q": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@types/q/-/q-1.5.5.tgz",
"integrity": "sha512-L28j2FcJfSZOnL1WBjDYp2vUHCeIFlyYI/53EwD/rKUBQ7MtUUfbQWiyKJGpcnv4/WgrhWsFKrcPstcAt/J0tQ=="
},
"node_modules/@types/react": {
"version": "18.0.15",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.0.15.tgz",
"integrity": "sha512-iz3BtLuIYH1uWdsv6wXYdhozhqj20oD4/Hk2DNXIn1kFsmp9x8d9QB6FnPhfkbhd2PgEONt9Q1x/ebkwjfFLow==",
"dependencies": {
"@types/prop-types": "*",
"@types/scheduler": "*",
"csstype": "^3.0.2"
}
},
"node_modules/@types/scheduler": {
"version": "0.16.2",
"resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.2.tgz",
"integrity": "sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew=="
},
"node_modules/@types/stack-utils": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-1.0.1.tgz",
@ -13402,6 +13437,19 @@
"node": ">=6"
}
},
"node_modules/react-cookie": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/react-cookie/-/react-cookie-4.1.1.tgz",
"integrity": "sha512-ffn7Y7G4bXiFbnE+dKhHhbP+b8I34mH9jqnm8Llhj89zF4nPxPutxHT1suUqMeCEhLDBI7InYwf1tpaSoK5w8A==",
"dependencies": {
"@types/hoist-non-react-statics": "^3.0.1",
"hoist-non-react-statics": "^3.0.0",
"universal-cookie": "^4.0.0"
},
"peerDependencies": {
"react": ">= 16.3.0"
}
},
"node_modules/react-dev-utils": {
"version": "10.2.1",
"resolved": "https://registry.npmjs.org/react-dev-utils/-/react-dev-utils-10.2.1.tgz",
@ -16599,6 +16647,23 @@
"imurmurhash": "^0.1.4"
}
},
"node_modules/universal-cookie": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/universal-cookie/-/universal-cookie-4.0.4.tgz",
"integrity": "sha512-lbRVHoOMtItjWbM7TwDLdl8wug7izB0tq3/YVKhT/ahB4VDvWMyvnADfnJI8y6fSvsjh51Ix7lTGC6Tn4rMPhw==",
"dependencies": {
"@types/cookie": "^0.3.3",
"cookie": "^0.4.0"
}
},
"node_modules/universal-cookie/node_modules/cookie": {
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz",
"integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
@ -19769,6 +19834,11 @@
"@babel/types": "^7.3.0"
}
},
"@types/cookie": {
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.3.3.tgz",
"integrity": "sha512-LKVP3cgXBT9RYj+t+9FDKwS5tdI+rPBXaNSkma7hvqy35lc7mAokC2zsqWJH0LaqIt3B962nuYI77hsJoT1gow=="
},
"@types/eslint-visitor-keys": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@types/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz",
@ -19783,6 +19853,15 @@
"@types/node": "*"
}
},
"@types/hoist-non-react-statics": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz",
"integrity": "sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==",
"requires": {
"@types/react": "*",
"hoist-non-react-statics": "^3.3.0"
}
},
"@types/istanbul-lib-coverage": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz",
@ -19825,11 +19904,31 @@
"resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz",
"integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA=="
},
"@types/prop-types": {
"version": "15.7.5",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz",
"integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w=="
},
"@types/q": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@types/q/-/q-1.5.5.tgz",
"integrity": "sha512-L28j2FcJfSZOnL1WBjDYp2vUHCeIFlyYI/53EwD/rKUBQ7MtUUfbQWiyKJGpcnv4/WgrhWsFKrcPstcAt/J0tQ=="
},
"@types/react": {
"version": "18.0.15",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.0.15.tgz",
"integrity": "sha512-iz3BtLuIYH1uWdsv6wXYdhozhqj20oD4/Hk2DNXIn1kFsmp9x8d9QB6FnPhfkbhd2PgEONt9Q1x/ebkwjfFLow==",
"requires": {
"@types/prop-types": "*",
"@types/scheduler": "*",
"csstype": "^3.0.2"
}
},
"@types/scheduler": {
"version": "0.16.2",
"resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.2.tgz",
"integrity": "sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew=="
},
"@types/stack-utils": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-1.0.1.tgz",
@ -28396,6 +28495,16 @@
"whatwg-fetch": "^3.0.0"
}
},
"react-cookie": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/react-cookie/-/react-cookie-4.1.1.tgz",
"integrity": "sha512-ffn7Y7G4bXiFbnE+dKhHhbP+b8I34mH9jqnm8Llhj89zF4nPxPutxHT1suUqMeCEhLDBI7InYwf1tpaSoK5w8A==",
"requires": {
"@types/hoist-non-react-statics": "^3.0.1",
"hoist-non-react-statics": "^3.0.0",
"universal-cookie": "^4.0.0"
}
},
"react-dev-utils": {
"version": "10.2.1",
"resolved": "https://registry.npmjs.org/react-dev-utils/-/react-dev-utils-10.2.1.tgz",
@ -30926,6 +31035,22 @@
"imurmurhash": "^0.1.4"
}
},
"universal-cookie": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/universal-cookie/-/universal-cookie-4.0.4.tgz",
"integrity": "sha512-lbRVHoOMtItjWbM7TwDLdl8wug7izB0tq3/YVKhT/ahB4VDvWMyvnADfnJI8y6fSvsjh51Ix7lTGC6Tn4rMPhw==",
"requires": {
"@types/cookie": "^0.3.3",
"cookie": "^0.4.0"
},
"dependencies": {
"cookie": {
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz",
"integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA=="
}
}
},
"universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",

View File

@ -27,6 +27,7 @@
"prismjs": "1.9.0",
"react": "^17.0.1",
"react-app-polyfill": "^1.0.6",
"react-cookie": "^4.1.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1",

View File

@ -89,8 +89,8 @@
}
.p-icon-input-khaki {
border-top-right-radius: 0!important;
border-bottom-right-radius: 0!important;
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
border-color: #C08135;
}
@ -7118,3 +7118,42 @@
.p-button.p-button-danger:enabled:focus {
box-shadow: 0 0 0 2px #ffffff, 0 0 0 4px #f7a2a2, 0 1px 2px 0 black;
}
.icon-khaki {
color: var(--primary-color);
}
.row {
display: flex;
}
.status {
border-radius: var(--border-radius);
padding: 0.25em 0.5rem;
text-transform: uppercase;
font-weight: 700;
font-size: 12px;
letter-spacing: 0.3px;
}
.status.status-1 {
background: #c8e6c9!important;
color: #256029!important;
}
.status.status-0 {
background: #ffcdd2;
color: #c63737;
}
.status.status-2 {
background: #feedaf;
color: #8a5340;
}
.status.status--1 {
background: #565656;
color: #f7f9f7;
}

View File

@ -51,6 +51,7 @@ import './assets/layout/layout.scss';
import './App.scss';
import LogIn from './components/LogIn';
import { PrimeIcons } from 'primereact/api';
import AreasComunes from './components/AreasComunes';
const App = () => {
const [layoutMode, setLayoutMode] = useState('static');
@ -183,11 +184,20 @@ const App = () => {
to: '/guardasSeguridad',
},
{
label: 'Comunidadades',
label: 'Comunidades',
icon: PrimeIcons.BUILDING,
to: '/comunidadesViviendas',
},
{ label: 'Inquilinos', icon: PrimeIcons.USER, to: '/inquilinos' },
{
label: 'Inquilinos',
icon: PrimeIcons.USER,
to: '/inquilinos'
},
{
label: 'Áreas Comunes de Comunidad',
icon: PrimeIcons.BUILDING,
to: '/areasComunes',
},
{ label: 'Log in', icon: 'pi pi-fw pi-id-card', to: '/logIn' },
],
},
@ -411,6 +421,7 @@ const App = () => {
<Route path="/guardasSeguridad" component={GuardasSeguridad} />
<Route path="/comunidadesViviendas" component={Communities} />
<Route path="/inquilinos" component={Inquilinos} />
<Route path="/areasComunes" component={AreasComunes} />
<Route path="/logIn" component={LogIn} />
</div>

View File

@ -75,7 +75,6 @@ const AdministradoresComunidad = () => {
let response = await fetch('http://localhost:4000/community/allCommunities', { method: 'GET' });
let resList = await response.json();
let list = await resList.message;
console.log(list);
setCommunitiesList(await list);
}
@ -323,7 +322,7 @@ const AdministradoresComunidad = () => {
<>
<p> {' '}
<FontAwesomeIcon icon={faAt} style={{ color: "#D7A86E" }} />{' '}
Correo Electrónic
Correo Electrónico
</p>
</>
)

View File

@ -0,0 +1,350 @@
import React, { useEffect, useState, useRef } from 'react';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';
import { Dropdown } from 'primereact/dropdown';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Toast } from 'primereact/toast';
import { Dialog } from 'primereact/dialog';
import { Toolbar } from 'primereact/toolbar';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHome, faUserAlt } from '@fortawesome/free-solid-svg-icons';
import { faCircleQuestion } from '@fortawesome/free-solid-svg-icons';
import { faAt } from '@fortawesome/free-solid-svg-icons';
import { faIdCardAlt } from '@fortawesome/free-solid-svg-icons';
import { faClipboardCheck } from '@fortawesome/free-solid-svg-icons';
import classNames from 'classnames';
import { useCookies } from "react-cookie";
const AreasComunes = () => {
let emptyCommonArea = {
_id: null,
dni: '',
name: '',
hourMin: '',
hourMax: '',
community_id: '',
bookable: '1',
bookable_text: '',
status: '1',
status_text: '',
};
const [commonAreaList, setCommonAreaList] = useState([]);
const [commonArea, setCommonArea] = useState(emptyCommonArea);
const [selectedCommonAreas, setSelectedCommonAreas] = useState(null);
const [globalFilter, setGlobalFilter] = useState(null);
const [deleteCommonAreaDialog, setDeleteCommonAreaDialog] = useState(false);
const [deleteCommonAreasDialog, setDeleteCommonAreasDialog] = useState(false);
const [submitted, setSubmitted] = useState(false);
const toast = useRef(null);
const dt = useRef(null);
const [cookies, setCookie] = useCookies();
async function getCommonAreas() {
await fetch(`http://localhost:4000/commonArea/findByCommunity/${cookies.community_id}`, { method: 'GET' })
.then((response) => response.json())
.then(data => data.message)
.then(data => {
if (data) {
data.map(item => {
if (item.bookable == '1') {
item.bookable_text = 'Necesaria';
} else {
item.bookable_text = 'No es necesarioa';
}
if (item.status == '1') {
item.status_text = 'Activo';
} else if (item.status == '0') {
item.status_text = 'Inactivo';
} else {
item.status_text = 'Eliminado';
}
})
}
data = data.filter(
(val) => val.status != -1,
)
setCommonAreaList(data);
});
}
useEffect(() => {
getCommonAreas();
}, []);
const deleteCommonArea = () => {
fetch('http://localhost:4000/commonArea/deleteCommonArea/' + commonArea._id, {
cache: 'no-cache',
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(
function (response) {
if (response.status != 201)
console.log('Ocurrió un error con el servicio: ' + response.status);
else
return response.json();
}
)
.then(
function (response) {
let _common_areas = commonAreaList.filter(
(val) => val._id !== commonArea._id,
);
_common_areas = _common_areas.filter(
(val) => val.status != -1,
)
setCommonAreaList(_common_areas);
setDeleteCommonAreaDialog(false);
setCommonArea(emptyCommonArea);
toast.current.show({
severity: 'success',
summary: 'Área Común Eliminada',
life: 3000,
});
}
)
.catch(
err => {
console.log('Ocurrió un error con el fetch', err)
toast.current.show({ severity: 'danger', summary: 'Error', detail: 'Área Común no se pudo eliminar', life: 3000 });
}
);
};
const deleteSelectedCommonAreas = () => {
let _common_areas = commonAreaList.filter(
(val) => !selectedCommonAreas.includes(val),
);
selectedCommonAreas.map((item) => {
fetch('http://localhost:4000/commonArea/deleteCommonArea/' + item._id, {
cache: 'no-cache',
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
});
_common_areas = _common_areas.filter(
(val) => val.status != -1,
)
setCommonAreaList(_common_areas);
setDeleteCommonAreasDialog(false);
setSelectedCommonAreas(null);
toast.current.show({
severity: 'success',
summary: 'Éxito',
detail: 'Áreas Comúnes Eliminadas',
life: 3000,
});
};
const hideDeleteCommonAreaDialog = () => {
setDeleteCommonAreaDialog(false);
}
const hideDeleteCommonAreasDialog = () => {
setDeleteCommonAreasDialog(false);
}
const confirmDeleteCommonArea = (commonArea) => {
setCommonArea(commonArea);
setDeleteCommonAreaDialog(true);
}
const confirmDeleteSelected = () => {
setDeleteCommonAreasDialog(true);
};
const actionsCommonArea = (rowData) => {
return (
<div className="actions">
<Button
icon="pi pi-trash"
className="p-button-rounded p-button-danger mt-2"
onClick={() => confirmDeleteCommonArea(rowData)}
/>
</div>
);
};
const deleteCommonAreaDialogFooter = (
<>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteCommonAreaDialog} />
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteCommonArea} />
</>
);
const deleteCommonAreasDialogFooter = (
<>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteCommonAreasDialog} />
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSelectedCommonAreas} />
</>
);
const leftToolbarTemplate = () => {
return (
<React.Fragment>
<div className="my-2">
<Button label="Eliminar" icon="pi pi-trash" className="p-button-danger" onClick={confirmDeleteSelected} disabled={!selectedCommonAreas || !selectedCommonAreas.length} />
</div>
</React.Fragment>
)
}
const rightToolbarTemplate = () => {
return (
<React.Fragment>
<Button label="Exportar" icon="pi pi-upload" className="p-button-help" />
</React.Fragment>
)
}
const header = (
<React.Fragment>
<div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
<h5 className="m-0">Áreas Comunes</h5>
<span className="block mt-2 md:mt-0 p-input-icon-left">
<i className="pi pi-search" />
<InputText type="search" onInput={(e) => setGlobalFilter(e.target.value)} placeholder="Buscar..." />
</span>
</div>
</React.Fragment>
);
const headerName = (
<>
<p>{' '}
<FontAwesomeIcon icon={faUserAlt} style={{ color: "#C08135" }} /> {' '}
Nombre
</p>
</>
)
const headerHourMin = (
<>
<p>
{' '}
<FontAwesomeIcon icon={faUserAlt} style={{ color: "#D7A86E" }} />{' '}
Hora de apertura
</p>
</>
)
const headerHourMax = (
<>
<p> {' '}
<FontAwesomeIcon icon={faIdCardAlt} style={{ color: "#C08135" }} />{' '}
Hora de cierre
</p>
</>
)
const headerBookable = (
<>
<p> {' '}
<FontAwesomeIcon icon={faClipboardCheck} style={{ color: "#D7A86E" }} />{' '}
Reservación
</p>
</>
)
const headerStatus = (
<>
<p> {' '}
<FontAwesomeIcon icon={faCircleQuestion} style={{ color: "#C08135" }} />{' '}
Estado
</p>
</>
)
const bookableBodyTemplate = (rowData) => {
let class_color = '';
if(rowData.bookable == '1') {
class_color = '0';
} else {
class_color = '1';
}
return (
<>
<span
className={`status status-${class_color}`}
>
{rowData.bookable_text}
</span>
</>
);
};
const statusBodyTemplate = (rowData) => {
return (
<>
<span
className={`status status-${rowData.status}`}
>
{rowData.status_text}
</span>
</>
);
};
return (
<div className="grid">
<div className="col-12">
<Toast ref={toast} />
<div className="card">
<Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate}></Toolbar>
<DataTable ref={dt} value={commonAreaList} dataKey="_id" paginator rows={5} selection={selectedCommonAreas} onSelectionChange={(e) => setSelectedCommonAreas(e.value)}
scrollable scrollHeight="400px" scrollDirection="both" header={header}
rowsPerPageOptions={[5, 10, 25]} className="datatable-responsive mt-3"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} áreas comunes"
globalFilter={globalFilter} emptyMessage="No hay áreas comunes registrados.">
<Column selectionMode="multiple" headerStyle={{ width: '3rem' }}></Column>
<Column field="name" sortable header={headerName} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column field="hourMin" header={headerHourMin} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }} alignFrozen="left"></Column>
<Column field="hourMax" header={headerHourMax} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}> </Column>
<Column field="bookable" sortable header={headerBookable} body={bookableBodyTemplate} style={{ flexGrow: 1, flexBasis: '200px', minWidth: '200px', wordBreak: 'break-word' }}></Column>
<Column field="status" sortable header={headerStatus} body={statusBodyTemplate} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column style={{ flexGrow: 1, flexBasis: '130px', minWidth: '130px' }} body={actionsCommonArea}></Column>
</DataTable>
<Dialog visible={deleteCommonAreaDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteCommonAreaDialogFooter} onHide={hideDeleteCommonAreaDialog}>
<div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} />
{commonArea && <span>¿Estás seguro que desea eliminar a <b>{commonArea.name}</b>?</span>}
</div>
</Dialog>
<Dialog visible={deleteCommonAreasDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteCommonAreasDialogFooter} onHide={hideDeleteCommonAreasDialog}>
<div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} />
{selectedCommonAreas && <span>¿Está seguro eliminar las áreas comunes seleccionadas?</span>}
</div>
</Dialog>
</div>
</div>
</div>
);
};
export default React.memo(AreasComunes);

View File

@ -9,10 +9,11 @@ import classNames from 'classnames';
import { Dialog } from 'primereact/dialog';
import { Toolbar } from 'primereact/toolbar';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHome } from '@fortawesome/free-solid-svg-icons';
import { faHome, faUserAlt } from '@fortawesome/free-solid-svg-icons';
import { faMapLocationDot } from '@fortawesome/free-solid-svg-icons';
import { faPhoneAlt } from '@fortawesome/free-solid-svg-icons';
import { faEllipsis } from '@fortawesome/free-solid-svg-icons';
import { faHashtag } from '@fortawesome/free-solid-svg-icons';
const Communities = () => {
let emptyCommunity = {
@ -44,9 +45,19 @@ const Communities = () => {
const [globalFilter, setGlobalFilter] = useState(null);
const [deleteCommunityDialog, setDeleteCommunityDialog] = useState(false);
const [deleteCommunitiesDialog, setDeleteCommunitiesDialog] = useState(false);
const [editCommunityDialog, setEditCommunityDialog] = useState(false);
const toast = useRef(null);
const dt = useRef(null);
//para el perfil de la comunidad
const [tenants, setTenants] = useState([]);
const [communityDialog, setCommunityDialog] = useState(false);
const p = provincesList.map((item) => ({
label: item.name,
value: item.code,
@ -165,6 +176,20 @@ const Communities = () => {
getCommunites();
}, []);
async function tenantsList(id) {
await fetch(`http://localhost:4000/user/findTenants/${id}`, { method: 'GET' })
.then((response) => response.json())
.then(data => data.message)
.then(data => {
setTenants(data)
});
}
useEffect(() => {
tenantsList(community._id);
}, [])
const saveCommunity = () => {
if (
community.name &&
@ -233,6 +258,20 @@ const Communities = () => {
}
};
function findNameTenant(tenant_id) {
let name = '';
if (tenant_id == '') {
name = 'Sin inquilino';
} else {
let tenant = tenants.find(t => t._id == tenant_id )
name = tenant['name'] + ' ' + tenant['last_name'];
}
console.log(name);
return name;
}
const onInputChange = (e, name) => {
const val = (e.target && e.target.value) || '';
let _community = { ...community };
@ -241,6 +280,11 @@ const Communities = () => {
setCommunity(_community);
};
const hideCommunityDialog = () => {
setSubmitted(false);
setCommunityDialog(false);
};
const hideDeleteCommunityDialog = () => {
setDeleteCommunityDialog(false);
};
@ -258,6 +302,106 @@ const Communities = () => {
setDeleteCommunitiesDialog(true);
};
const infoCommunity = async (community) => {
await tenantsList(community._id);
setCommunity({ ...community });
setCommunityDialog(true);
};
const editCommunity = (community) => {
setCommunity({ ...community });
setEditCommunityDialog(true);
};
const hideEditCommunityDialog = () => {
setEditCommunityDialog(false);
};
const confirmEditCommunity = (community) => {
setCommunity(community);
setEditCommunityDialog(true);
};
//desactivar o activar una comunidad
const cambiarDesactivarEstadoCommunity = () => {
var data = {
id: community._id,
status: "0",
};
console.log(data);
fetch('http://localhost:4000/community/changeStatus', {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(
function (response) {
if (response.status != 201)
console.log('Ocurrió un error con el servicio: ' + response.status);
else
return response.json();
}
)
.then(
function (response) {
setEditCommunityDialog(false);
toast.current.show({
severity: 'success',
summary: 'Éxito',
detail: 'Comunidad de Viviendas Actualizada',
life: 3000,
});
}
)
.catch(
err => console.log('Ocurrió un error con el fetch', err)
);
}
//desactivar o activar una comunidad
const cambiarActivarEstadoCommunity = () => {
var data = {
id: community._id,
status: "1",
};
console.log(data);
fetch('http://localhost:4000/community/changeStatus', {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(
function (response) {
if (response.status != 201)
console.log('Ocurrió un error con el servicio: ' + response.status);
else
return response.json();
}
)
.then(
function (response) {
setEditCommunityDialog(false);
toast.current.show({
severity: 'success',
summary: 'Éxito',
detail: 'Comunidad de Viviendas Actualizada',
life: 3000,
});
}
)
.catch(
err => console.log('Ocurrió un error con el fetch', err)
);
}
const deleteCommunity = () => {
/* fetch('http://localhost:4000/community/deleteCommunity/' + community._id, {
cache: 'no-cache',
@ -330,9 +474,24 @@ const Communities = () => {
const actionsCommunity = (rowData) => {
return (
<div className="actions">
<Button
icon="pi pi-eye"
className="p-button-rounded p-button-success mt-2 mx-2"
onClick={() => confirmEditCommunity(rowData)}
/>
<Button
icon="pi pi-eye-slash"
className="p-button-rounded p-button-danger mt-2 mx-2"
onClick={() => confirmEditCommunity(rowData)}
/>
<Button
icon="pi pi-exclamation-circle"
className="p-button-rounded p-button-primary mt-2 mx-2"
onClick={() => infoCommunity(rowData)}
/>
<Button
icon="pi pi-trash"
className="p-button-rounded p-button-danger mt-2"
className="p-button-rounded p-button-danger mt-2 mx-2"
onClick={() => confirmDeleteCommunity(rowData)}
/>
</div>
@ -381,6 +540,18 @@ const Communities = () => {
</div>
);
const communityDialogFooter = (
<>
<Button
label="Cerrar"
icon="pi pi-times"
className="p-button-text"
onClick={hideCommunityDialog}
/>
</>
);
const deleteCommunityDialogFooter = (
<>
<Button
@ -414,6 +585,39 @@ const Communities = () => {
/>
</>
);
const editDesactivarCommunityDialogFooter = (
<>
<Button
label="No"
icon="pi pi-times"
className="p-button-text"
onClick={hideEditCommunityDialog}
/>
<Button
label="Yes"
icon="pi pi-check"
className="p-button-text"
onClick={cambiarDesactivarEstadoCommunity}
/>
</>
);
const editActivarCommunityDialogFooter = (
<>
<Button
label="No"
icon="pi pi-times"
className="p-button-text"
onClick={hideEditCommunityDialog}
/>
<Button
label="Yes"
icon="pi pi-check"
className="p-button-text"
onClick={cambiarActivarEstadoCommunity}
/>
</>
);
const headerName = (
<>
@ -477,7 +681,7 @@ const Communities = () => {
<>
<p>
{' '}
<FontAwesomeIcon icon={faPhoneAlt} style={{ color: '#D7A86E' }} />{' '}
<FontAwesomeIcon icon={faHashtag} style={{ color: '#D7A86E' }} />{' '}
Número de viviendas
</p>
</>
@ -493,6 +697,30 @@ const Communities = () => {
</>
);
//ver perfil comunidad
const headerTenant = (
<>
<p>
{' '}
<FontAwesomeIcon icon={faUserAlt} style={{ color: '#C08135' }} />{' '}
Inquilinos
</p>
</>
);
const tenantsBodyTemplate = (rowData) => {
let tenants = rowData.tenants;
let name = findNameTenant(tenants.tenant_id);
console.log(name);
return (
<>
{name}
</>
)
};
return (
<div className="grid">
<div className="col-12">
@ -564,10 +792,181 @@ const Communities = () => {
<Column
field="name_admin"
sortable
header={headerAdministrator}
style={{ flexGrow: 1, flexBasis: '180px' }}
></Column>
<Column body={actionsCommunity}></Column>
<Column
body={actionsCommunity}
style={{ flexGrow: 1, flexBasis: '180px' }}
></Column>
</DataTable>
<Dialog
visible={communityDialog}
style={{ width: '650px' }}
header="Información de la Comunidad"
modal
className="p-fluid"
footer={communityDialogFooter}
onHide={hideCommunityDialog}>
<div className='container text-center'>
<div className='row my-4'>
<div className=" col-12 md:col-12">
<p>Nombre</p>
<div className="p-0 col-2 md:col-2" style={{ margin: '0 auto' }}>
<div className="p-inputgroup align-items-center justify-content-evenly">
<i className="pi pi-home icon-khaki"></i>
<p>{community.name}</p>
</div>
</div>
</div>
</div>
<div className='row my-5'>
<div className=" col-6 md:col-6">
<p>Administrador</p>
<div className="p-0 col-6 md:col-6" style={{ margin: '0 auto' }}>
<div className="p-inputgroup align-items-center justify-content-evenly">
<i className="pi pi-user icon-khaki"></i>
<p>{community.name_admin}</p>
</div>
</div>
</div>
<div className=" col-6 md:col-6">
<p>Teléfono Administrativo</p>
<div className="p-0 col-6 md:col-6" style={{ margin: '0 auto' }}>
<div className="p-inputgroup align-items-center justify-content-evenly">
<i className="pi pi-phone icon-khaki"></i>
<p>{community.phone}</p>
</div>
</div>
</div>
</div>
<div className='row my-5'>
<div className=" col-4 col-md-4 md:col-4">
<p>Provincia</p>
<div className="p-0 col-10 md:col-10">
<div className="p-inputgroup align-items-center justify-content-evenly">
<i className="pi pi-map-marker icon-khaki"></i>
<p>{community.province}</p>
</div>
</div>
</div>
<div className=" col-4 md:col-4">
<p>Cantón</p>
<div className="p-0 col-10 md:col-10">
<div className="p-inputgroup align-items-center justify-content-evenly">
<i className="pi pi-map-marker icon-khaki"></i>
<p>{community.canton}</p>
</div>
</div>
</div>
<div className=" col-4 md:col-4">
<p>Distrito</p>
<div className="p-0 col-10 md:col-10">
<div className="p-inputgroup align-items-center justify-content-evenly">
<i className="pi pi-map-marker icon-khaki"></i>
<p>{community.district}</p>
</div>
</div>
</div>
</div>
<div className='row my-5'>
<div className=" col-12 md:col-12">
<p>Número de Viviendas</p>
<div className="p-0 col-2 md:col-2" style={{ margin: '0 auto' }}>
<div className="p-inputgroup justify-content-evenly">
<i className="pi pi-hashtag icon-khaki"></i>
<p>{community.num_houses}</p>
</div>
</div>
</div>
</div>
<div className='row my-5'>
<div className=" col-12 md:col-12">
<p> <i className="pi pi-home icon-khaki"></i> Viviendas</p>
<div className="p-0 col-12 md:col-12" style={{ margin: '0 auto' }}>
<div className="p-inputgroup justify-content-evenly">
<DataTable
value={community.houses}
paginator
rows={5}
scrollable
scrollHeight="200px"
scrollDirection="both"
rowsPerPageOptions={[5, 10, 25]}
className="datatable-responsive mt-3"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} viviendas"
globalFilter={globalFilter}
>
<Column
field="number_house"
header={headerNumberHouses}
style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px' }}
></Column>
<Column
field="tenants"
header={headerTenant}
body={tenantsBodyTemplate}
style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px' }}
></Column>
</DataTable>
</div>
</div>
</div>
</div>
</div>
</Dialog>
<Dialog
visible={editCommunityDialog}
style={{ width: '450px' }}
header="Confirmar"
modal
footer={editActivarCommunityDialogFooter}
onHide={hideEditCommunityDialog}
>
<div className="flex align-items-center justify-content-center">
<i
className="pi pi-exclamation-triangle mr-3"
style={{ fontSize: '2rem' }}
/>
{community && (
<span>
¿Estás seguro que desea cambiar estado a <b>{community.name}</b>?
</span>
)}
</div>
</Dialog>
<Dialog
visible={editCommunityDialog}
style={{ width: '450px' }}
header="Confirmar"
modal
footer={editDesactivarCommunityDialogFooter}
onHide={hideEditCommunityDialog}
>
<div className="flex align-items-center justify-content-center">
<i
className="pi pi-exclamation-triangle mr-3"
style={{ fontSize: '2rem' }}
/>
{community && (
<span>
¿Estás seguro que desea cambiar estado a <b>{community.name}</b>?
</span>
)}
</div>
</Dialog>
<Dialog
visible={deleteCommunityDialog}
style={{ width: '450px' }}

View File

@ -1,23 +1,95 @@
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext'
import React, { useEffect, useState, useRef } from 'react'
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Dropdown } from 'primereact/dropdown';
import { InputText } from 'primereact/inputtext';
import React, { useEffect, useState } from 'react';
import { Toast } from 'primereact/toast';
import { Dialog } from 'primereact/dialog';
import { Toolbar } from 'primereact/toolbar';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faHome } from '@fortawesome/free-solid-svg-icons';
import { faUserAlt } from '@fortawesome/free-solid-svg-icons';
import { faPhoneAlt } from '@fortawesome/free-solid-svg-icons';
import { faAt } from '@fortawesome/free-solid-svg-icons';
import { faIdCardAlt } from '@fortawesome/free-solid-svg-icons';
import { faEllipsis } from '@fortawesome/free-solid-svg-icons';
import { faHashtag } from '@fortawesome/free-solid-svg-icons';
import { useCookies } from "react-cookie";
const Inquilinos = () => {
let emptyTenant = {
_id: null,
dni: '',
name: '',
last_name: '',
email: '',
phone: '',
password: '',
community_id: '',
community_name: '',
number_house: 'Sin número de vivienda',
user_type: '4',
date_entry: new Date(),
status: '1'
};
const [tenants, setTenants] = useState([]);
const [tenant, setTenant] = useState(emptyTenant);
const [selectedTentants, setSelectedTenants] = useState(null);
const [globalFilter, setGlobalFilter] = useState(null);
const [deleteTenantDialog, setDeleteTenantDialog] = useState(false);
const [deleteTenantsDialog, setDeleteTenantsDialog,] = useState(false);
const [communitiesList, setCommunitiesList] = useState([]);
const communityIdList = communitiesList.map((community) => community.id);
const [communityId, setCommunityId] = useState(null);
const [submitted, setSubmitted] = useState(false);
const toast = useRef(null);
const dt = useRef(null);
const [cookies, setCookie] = useCookies();
async function tenantsList() {
await fetch(`http://localhost:4000/user/findTenants/${cookies.community_id}`, { method: 'GET' })
.then((response) => response.json())
.then(data => data.message)
.then(data => {
data.map((item) => {
if(item.number_house ==""){
item.number_house = "Sin vivienda asignada";
}
})
setTenants(data)
});
}
async function getCommunites() {
let response = await fetch(
'http://localhost:4000/community/allCommunities',
{ method: 'GET' },
);
let list = await response.json();
setCommunitiesList(list.message);
let response = await fetch('http://localhost:4000/community/allCommunities', { method: 'GET' });
let resList = await response.json();
let list = await resList.message;
setCommunitiesList(await list);
}
useEffect(() => {
tenantsList();
}, [])
useEffect(() => {
getCommunites();
}, []);
}, [])
const cList = communitiesList.map((item) => ({
label: item.name,
value: item._id,
}))
function registrarInquilino() {
let data = {
dni: document.getElementById('identificacion').value,
@ -47,8 +119,220 @@ const Inquilinos = () => {
});
}
const deleteTenant = () => {
/* fetch('http://localhost:4000/community/deleteCommunity/' + community._id, {
cache: 'no-cache',
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(
function (response) {
if (response.status != 201)
console.log('Ocurrió un error con el servicio: ' + response.status);
else
return response.json();
}
)
.then(
function (response) {
let _community = communities.filter(val => val._id !== community._id);
setCommunities(_community);
setDeleteCommunityDialog(false);
setCommunity(emptyCommunity);
toast.current.show({ severity: 'success', summary: 'Exito', detail: 'Comunidad de Viviendas Eliminada', life: 3000 });
}
)
.catch(
err => {
console.log('Ocurrió un error con el fetch', err)
toast.current.show({ severity: 'danger', summary: 'Error', detail: 'Comunidad de Viviendas no se pudo eliminar', life: 3000 });
}
);
*/
let _tenants = tenants.filter(
(val) => val._id !== tenant._id,
);
setTenants(_tenants);
setDeleteTenantDialog(false);
setTenant(emptyTenant);
toast.current.show({
severity: 'success',
summary: 'Inquilino Eliminado',
life: 3000,
});
};
const deleteSelectedTenants = () => {
let _tenants = tenants.filter(
(val) => !selectedTentants.includes(val),
);
/* selectedCommunities.map((item) => {
fetch('http://localhost:4000/user/deleteCommunity/' + item._id, {
cache: 'no-cache',
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
})*/
setTenants(_tenants);
setDeleteTenantsDialog(false);
setSelectedTenants(null);
toast.current.show({
severity: 'success',
summary: 'Éxito',
detail: 'Inquilinos Eliminados',
life: 3000,
});
};
const hideDeleteTenantDialog = () => {
setDeleteTenantDialog(false);
}
const hideDeleteTenantsDialog = () => {
setDeleteTenantsDialog(false);
}
const confirmDeleteTenant = (tenant) => {
setTenant(tenant);
setDeleteTenantDialog(true);
}
const confirmDeleteSelected = () => {
setDeleteTenantsDialog(true);
};
const actionsTenant = (rowData) => {
return (
<div className="actions">
<Button icon="pi pi-trash" className="p-button-rounded p-button-danger mt-2" onClick={() => confirmDeleteTenant(rowData)} />
</div>
);
}
const leftToolbarTemplate = () => {
return (
<React.Fragment>
<div className="my-2">
<Button label="Eliminar" icon="pi pi-trash" className="p-button-danger" onClick={confirmDeleteSelected} disabled={!selectedTentants || !selectedTentants.length} />
</div>
</React.Fragment>
)
}
const rightToolbarTemplate = () => {
return (
<React.Fragment>
<Button label="Exportar" icon="pi pi-upload" className="p-button-help" />
</React.Fragment>
)
}
const header = (
<div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
<h5 className="m-0">Inquilinos</h5>
<span className="block mt-2 md:mt-0 p-input-icon-left">
<i className="pi pi-search" />
<InputText type="search" onInput={(e) => setGlobalFilter(e.target.value)} placeholder="Buscar..." />
</span>
</div>
);
const deleteTenantDialogFooter = (
<>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteTenantDialog} />
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteTenant} />
</>
);
const deleteTenantsDialogFooter = (
<>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteTenantsDialog} />
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSelectedTenants} />
</>
);
const headerName = (
<>
<p> <FontAwesomeIcon icon={faUserAlt} style={{ color: "#C08135" }} /> Nombre</p>
</>
)
const headerLastName = (
<>
<p> <FontAwesomeIcon icon={faUserAlt} style={{ color: "#D7A86E" }} /> Apellidos</p>
</>
)
const headerDNI = (
<>
<p> <FontAwesomeIcon icon={faIdCardAlt} style={{ color: "#C08135" }} /> Identificación</p>
</>
)
const headerEmail = (
<>
<p> <FontAwesomeIcon icon={faAt} style={{ color: "#D7A86E" }} /> Correo Electrónico</p>
</>
)
const headerPhone = (
<>
<p> <FontAwesomeIcon icon={faPhoneAlt} style={{ color: "#C08135" }} /> Teléfono</p>
</>
)
const headerNumberHouse = (
<>
<p> <FontAwesomeIcon icon={faHashtag} style={{ color: "#C08135" }} /> Número de vivienda</p>
</>
)
return (
<div className="grid">
<div className="col-12">
<Toast ref={toast} />
<div className="card">
<Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate}></Toolbar>
<DataTable ref={dt} value={tenants} dataKey="_id" paginator rows={5} selection={selectedTentants} onSelectionChange={(e) => setSelectedTenants(e.value)}
scrollable scrollHeight="400px" scrollDirection="both" header={header}
rowsPerPageOptions={[5, 10, 25]} className="datatable-responsive mt-3"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} inquilinos"
globalFilter={globalFilter} emptyMessage="No hay inquilinos en esta comunidad registrados.">
<Column selectionMode="multiple" headerStyle={{ width: '3rem' }}></Column>
<Column field="name" sortable header={headerName} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column field="last_name" sortable header={headerLastName} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }} alignFrozen="left"></Column>
<Column field="dni" sortable header={headerDNI} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}>
</Column>
<Column field="email" sortable header={headerEmail} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column field="phone" header={headerPhone} style={{ flexGrow: 1, flexBasis: '80px', minWidth: '80px', wordBreak: 'break-word' }}></Column>
<Column field="number_house" sortable header={headerNumberHouse} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word', justifyContent: 'center' }}></Column>
<Column style={{ flexGrow: 1, flexBasis: '130px', minWidth: '130px' }} body={actionsTenant}></Column>
</DataTable>
<Dialog visible={deleteTenantDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteTenantDialogFooter} onHide={hideDeleteTenantDialog}>
<div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} />
{tenant && <span>¿Estás seguro que desea eliminar a <b>{tenant.name}</b>?</span>}
</div>
</Dialog>
<Dialog visible={deleteTenantsDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteTenantsDialogFooter} onHide={hideDeleteTenantsDialog}>
<div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} />
{selectedTentants && <span>¿Está seguro eliminar los Inquilinos seleccionados?</span>}
</div>
</Dialog>
</div>
</div>
<div className="col-12">
<div className="card">
<h5 className="card-header">Registrar Inquilino</h5>
@ -79,11 +363,7 @@ const Inquilinos = () => {
</div>
<div className="field col-12 md:col-6">
<label htmlFor="numero_vivienda">Número de Vivienda</label>
<Dropdown
id="numero_vivienda"
value={communityIdList[0]}
options={communitiesList}
/>
<Dropdown id="numero_vivienda" value={communityId} options={cList} />
</div>
<div className="field col-12 md:col-6">
<label htmlFor="identificacion">Identificación</label>

View File

@ -5,11 +5,14 @@ import App from './App';
//import * as serviceWorker from './serviceWorker';
import { HashRouter } from 'react-router-dom';
import ScrollToTop from './ScrollToTop';
import { CookiesProvider } from "react-cookie";
ReactDOM.render(
<HashRouter>
<ScrollToTop>
<App></App>
<CookiesProvider>
<App></App>
</CookiesProvider>
</ScrollToTop>
</HashRouter>,
document.getElementById('root'),