Merge pull request #145 from DeimosPr4/US-listarInquilinos

US-Listar Inqullinos
This commit is contained in:
Eduardo Quiros 2022-08-02 05:16:44 +00:00 committed by GitHub
commit a0a342f5dd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 408 additions and 34 deletions

View File

@ -102,11 +102,17 @@ export class AppController {
allUsersAdminComunidad() { allUsersAdminComunidad() {
return this.appService.allUsersAdminComunidad(); return this.appService.allUsersAdminComunidad();
} }
@Get('user/findGuards/:community') @Get('user/findGuards/:community')
findGuardsCommunity(@Param('community_id') community_id: string) { findGuardsCommunity(@Param('community_id') community_id: string) {
return this.appService.findGuardsCommunity(community_id); 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') @Get('user/find/:dni')
findUser(@Param('dni') paramUserDNI: string) { findUser(@Param('dni') paramUserDNI: string) {
return this.appService.findUser(paramUserDNI); return this.appService.findUser(paramUserDNI);

View File

@ -119,6 +119,17 @@ export class AppService {
.pipe(map((message: string) => ({ message }))); .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 //GET parameter from API
findUser(paramUserDNI: string) { findUser(paramUserDNI: string) {
const pattern = { cmd: 'findUserDNI' }; const pattern = { cmd: 'findUserDNI' };
@ -136,6 +147,13 @@ export class AppService {
.pipe(map((message: string) => ({ message }))); .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) { deleteAdminSystem(id: string) {
const pattern = { cmd: 'deleteAdminSystem' }; const pattern = { cmd: 'deleteAdminSystem' };

View File

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

View File

@ -46,6 +46,18 @@ export class UsersController {
return this.userService.findGuardsCommunity(pcommunity_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' }) @MessagePattern({ cmd: 'updateUser' })
update(@Payload() user: UserDocument) { update(@Payload() user: UserDocument) {
return this.userService.update(user.id, user); return this.userService.update(user.id, user);

View File

@ -25,24 +25,26 @@ export class UsersService {
async createAdminCommunity(user: UserDocument) { async createAdminCommunity(user: UserDocument) {
let password = user.password; let password = user.password;
let passwordEncriptada = Md5.init(user.password); let passwordEncriptada = Md5.init(user.password);
user.password = passwordEncriptada; user.password = passwordEncriptada;
this.userModel.create(user) this.userModel.create(user)
let community = await this.findCommunity(user.community_id); let community = await this.findCommunity(user.community_id);
user.community_id = community['name']; user.community_id = community['name'];
const pattern = { cmd: 'emailCreateUserAdminCommunity' }; const pattern = { cmd: 'emailCreateUserAdminCommunity' };
const payload = { email: user['email'], password: password, name: user['name'], const payload = {
date_entry: user['date_entry'], community_name: community['name'] }; email: user['email'], password: password, name: user['name'],
return this.clientNotificationtApp date_entry: user['date_entry'], community_name: community['name']
.send<string>(pattern, payload) };
.pipe( return this.clientNotificationtApp
map((message: string) => ({ message })), .send<string>(pattern, payload)
); .pipe(
map((message: string) => ({ message })),
);
} }
async findCommunity(community_id: string) { async findCommunity(community_id: string) {
@ -123,6 +125,36 @@ export class UsersService {
return this.userModel.find({ user_type: 2 }).exec(); 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) { async testSendMail(user: UserDocument) {
let passwordEncriptada = Md5.init(user.password); let passwordEncriptada = Md5.init(user.password);
user.password = passwordEncriptada; 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

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

View File

@ -1,23 +1,95 @@
import { Button } from 'primereact/button'; 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 { Dropdown } from 'primereact/dropdown';
import { InputText } from 'primereact/inputtext'; import { Toast } from 'primereact/toast';
import React, { useEffect, useState } from 'react'; 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 = () => { 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 [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() { async function getCommunites() {
let response = await fetch( let response = await fetch('http://localhost:4000/community/allCommunities', { method: 'GET' });
'http://localhost:4000/community/allCommunities', let resList = await response.json();
{ method: 'GET' }, let list = await resList.message;
);
let list = await response.json(); setCommunitiesList(await list);
setCommunitiesList(list.message);
} }
useEffect(() => {
tenantsList();
}, [])
useEffect(() => { useEffect(() => {
getCommunites(); getCommunites();
}, []); }, [])
const cList = communitiesList.map((item) => ({
label: item.name,
value: item._id,
}))
function registrarInquilino() { function registrarInquilino() {
let data = { let data = {
dni: document.getElementById('identificacion').value, 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 ( return (
<div className="grid"> <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="col-12">
<div className="card"> <div className="card">
<h5 className="card-header">Registrar Inquilino</h5> <h5 className="card-header">Registrar Inquilino</h5>
@ -79,11 +363,7 @@ const Inquilinos = () => {
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-12 md:col-6">
<label htmlFor="numero_vivienda">Número de Vivienda</label> <label htmlFor="numero_vivienda">Número de Vivienda</label>
<Dropdown <Dropdown id="numero_vivienda" value={communityId} options={cList} />
id="numero_vivienda"
value={communityIdList[0]}
options={communitiesList}
/>
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-12 md:col-6">
<label htmlFor="identificacion">Identificación</label> <label htmlFor="identificacion">Identificación</label>

View File

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