Merge branch 'dev' of github.com:DeimosPr4/katoikia-app into 201-issue-restablecer-contraseña

This commit is contained in:
Eduardo Quiros 2022-08-31 16:36:18 -06:00
commit 9d1e10565b
No known key found for this signature in database
GPG Key ID: B77F36C3F12720B4
12 changed files with 851 additions and 202 deletions

View File

@ -1,4 +1,5 @@
import { Controller, Get, Post, Put, Body, Param, Delete } from '@nestjs/common';
import { Console } from 'console';
import { AppService } from './app.service';
@Controller()
export class AppController {
@ -305,6 +306,30 @@ export class AppController {
return this.appService.updateAdminSystem(_id, dni, name, last_name, email, phone);
}
@Put('user/updateTenant/:id')
updateTenant(
@Param('id') id: string,
@Body('dni') dni: string,
@Body('name') name: string,
@Body('last_name') last_name: string,
@Body('email') email: string,
@Body('phone') phone: number,
@Body('community_id') community_id: string,
@Body('number_house') number_house: string,
) {
return this.appService.updateTenant(
id,
dni,
name,
last_name,
email,
phone,
community_id,
number_house,
);
}
// #==== API Communities
@Post('community/createCommunity')
createCommunity(
@ -369,8 +394,9 @@ export class AppController {
saveTenant(
@Body('community_id') community_id: string,
@Body('number_house') number_house: string,
@Body('tenant_id') tenant_id: string,
@Body('_id') tenant_id: string,
) {
console.log(community_id + ' ' + number_house + ' ' + tenant_id)
return this.appService.saveTenant(community_id, number_house, tenant_id);
}
@ -425,6 +451,23 @@ export class AppController {
return this.appService.changeStatusCommonArea(pId, pStatus);
}
@Post('commonArea/updateCommonArea')
updateCommonArea(
@Body('_id') id: string,
@Body('name') name: string,
@Body('hourMin') hourMin: string,
@Body('hourMax') hourMax: string,
@Body('bookable') bookable: number,
@Body('community_id') community_id: string,
) {
return this.appService.updateCommonArea(
id,
name,
hourMin,
hourMax,
bookable,
community_id,);
}
// #==== API GUEST
//#API userService - create user
@Post('guest/createGuest')

View File

@ -175,6 +175,36 @@ export class AppService {
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
async updateTenant(
_id: string,
dni: string,
name: string,
last_name: string,
email: string,
phone: number,
community_id: string,
number_house: string,
) {
await this.saveTenant(community_id, number_house, _id);
const pattern = { cmd: 'updateTenant' };
const payload = {
id: _id,
dni: dni,
name: name,
last_name: last_name,
email: email,
phone: phone,
community_id: community_id,
number_house: number_house,
};
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
//POST parameter from API
createAdminSystem(dni: string, name: string, last_name: string, email: string, phone: number
, user_type: string, status: string, date_entry: Date) {
@ -521,7 +551,27 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
updateCommonArea(
id: string,
name: string,
hourMin: string,
hourMax: string,
bookable: number,
community_id: string,
) {
const pattern = { cmd: 'updateCommonArea' };
const payload = {
id: id,
name: name,
hourMin: hourMin,
hourMax: hourMax,
bookable: bookable,
community_id: community_id,
};
return this.clientCommonAreaApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
// ====================== GUESTS ===============================
//POST parameter from API
@ -770,4 +820,19 @@ export class AppService {
return pass;
}
async saveTenantNumHouse(community_id: string, number_house: string, tenant_id: string) {
const pattern = { cmd: 'saveTenantNumHouse' }
const payload = { _id: community_id, number_house: number_house, tenant_id: tenant_id }
return await this.clientCommunityApp
.send<string>(pattern, payload)
.pipe(
map((response: string) => ({ response }))
)
}
}

View File

@ -26,6 +26,7 @@ export class CommonAreasService {
}
update(id: string, commonArea: CommonAreaDocument) {
console.log(commonArea);
return this.commonAreaModel.findOneAndUpdate({ _id: id }, commonArea, {
new: true,
});

View File

@ -57,7 +57,6 @@ export class CommunitiesController {
@MessagePattern({ cmd: 'saveTenant' })
saveTenant(@Payload() body: string) {
let id = body['_id'];
let tenant_id = body['tenant_id'];
let number_house = body['number_house'];

View File

@ -88,7 +88,6 @@ export class CommunitiesService {
await community.houses.map(house => {
if (house.number_house == number_house) {
if (house.tenants) {
house.tenants.tenant_id = ptenant_id
} else {
let tenant = new Tenant()
@ -109,6 +108,7 @@ export class CommunitiesService {
await community.houses.map(house => {
if (house.number_house === number_house) {
if(house.tenants)
house.tenants.tenant_id = "";
house.state = "desocupada"
}

View File

@ -77,7 +77,7 @@ export class UsersController {
@MessagePattern({ cmd: 'updateGuard' })
updateGuard(@Payload() guard: UserDocument) {
return this.userService.update(guard.id, guard);
return this.userService.update(guard._id, guard);
}
@MessagePattern({ cmd: 'updateAdminCommunity' })
@ -85,6 +85,11 @@ export class UsersController {
return this.userService.update(user._id, user);
}
@MessagePattern({ cmd: 'updateTenant' })
updateTenant(@Payload() tenant: UserDocument) {
return this.userService.updateTenant(tenant.id, tenant);
}
@MessagePattern({ cmd: 'removeUser' })
remove(@Payload() id: string) {
let dni = id['dni'];

View File

@ -29,7 +29,7 @@ export class UsersService {
let passwordEncriptada = Md5.init(user.password);
user.password = passwordEncriptada;
let userCreated = await this.userModel.create(user);
await this.saveTenantNumHouse(user.community_id, user.number_house, userCreated['_id']);
await this.saveTenant(user.community_id, user.number_house, userCreated['_id']);
let community = await this.findCommunity(user.community_id);
user.community_id = community['name'];
@ -117,6 +117,9 @@ export class UsersService {
}
async update(id: string, user: UserDocument) {
console.log(id)
console.log(user)
return this.userModel.findOneAndUpdate({ _id: id }, user, {
new: true,
});
@ -131,6 +134,18 @@ export class UsersService {
});
}
async updateTenant(id: string, user: UserDocument) {
await this.saveTenant(user.community_id, user.number_house, user.id);
return await this.userModel.findOneAndUpdate({ _id: id }, {
name: user['name'], last_name: user['last_name'],
dni: user['dni'], email: user['email'], phone: user['phone'],
number_house: user['number_house']
}, {
new: true,
});
}
/* async remove(id: string) {
return this.userModel.findByIdAndRemove({ _id: id }).exec();
}*/
@ -293,7 +308,7 @@ export class UsersService {
}
async saveTenantNumHouse(community_id: string, number_house: string, tenant_id: string) {
async saveTenant(community_id: string, number_house: string, tenant_id: string) {
const pattern = { cmd: 'saveTenant' }
const payload = { _id: community_id, number_house: number_house, tenant_id: tenant_id }

View File

@ -58,6 +58,7 @@ import { useCookies } from "react-cookie";
import LogInUser from './components/LogInUser';
import Page404 from './components/Page404'
import Reservaciones from './components/Reservaciones';
import PerfilAdminComunidad from './components/PerfilAdminComunidad';
const App = () => {
@ -472,6 +473,7 @@ const App = () => {
<Route path="/reservaciones" component={Reservaciones} />
<Route path="/registroComunicado" component={RegistroComunicado} />
<Route path="/invitadosComunidad" component={InvitadosComunidad} />
<Route path="/pefilAdminComunidad" component={PerfilAdminComunidad} />
</>
)
} else {

View File

@ -88,10 +88,11 @@ export const AppTopbar = (props) => {
</button>
</li> */}
<li className='mx-2' hidden={!logged}>
<button className="p-link layout-topbar-button" >
<a href="/pefilAdminComunidad"> <button className="p-link layout-topbar-button" >
<i className="pi pi-user" />
<span>Perfil</span>
</button>
</button></a>
</li>
<li className='mx-2' hidden={!logged}>
<button className="p-link layout-topbar-button" onClick={cerrarSesion} >

View File

@ -8,7 +8,7 @@ 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 { faClock, faHome, faHomeAlt, 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';
@ -41,11 +41,10 @@ const AreasComunes = () => {
const [submitted, setSubmitted] = useState(false);
const toast = useRef(null);
const dt = useRef(null);
const [cookies, setCookie] = useCookies();
const [changeStatusAreaDialog, setChangeStatusAreaDialog] = useState(false);
const [areaDialog, setAreaDialog] = useState(false);
const [saveButtonTitle, setSaveButtonTitle] = useState("Registrar")
async function getCommonAreas() {
await fetch(`http://localhost:4000/commonArea/findByCommunity/${cookies.community_id}`, { method: 'GET' })
@ -57,7 +56,7 @@ const AreasComunes = () => {
if (item.bookable == '1') {
item.bookable_text = 'Necesaria';
} else {
item.bookable_text = 'No es necesarioa';
item.bookable_text = 'No es necesaria';
}
if (item.status == '1') {
@ -69,7 +68,6 @@ const AreasComunes = () => {
}
})
}
data = data.filter(
(val) => val.status != -1,
)
@ -81,17 +79,27 @@ const AreasComunes = () => {
getCommonAreas();
}, []);
const findIndexById = (id) => {
let index = -1;
for (let i = 0; i < commonAreaList.length; i++) {
if (commonAreaList[i]._id === id) {
index = i;
break;
}
}
return index;
}
const saveCommonArea = () => {
let _common_areas = [...commonAreaList];
let _common_area = { ...commonArea };
_common_area.community_id = cookies.community_id;
if (
commonArea.name &&
commonArea.hourMin < commonArea.hourMax
) {
let _common_areas = [...commonAreaList];
let _common_area = { ...commonArea };
_common_area.community_id = cookies.community_id;
// console.log(houses)
fetch('http://localhost:4000/commonArea/createCommonArea', {
if (commonArea._id) {
fetch('http://localhost:4000/commonArea/updateCommonArea', {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(_common_area),
@ -108,6 +116,8 @@ const AreasComunes = () => {
return data.message;
})
.then((data) => {
const index = findIndexById(commonArea._id);
if (data) {
if (data.bookable == '1') {
data.bookable_text = 'Necesaria';
@ -123,15 +133,16 @@ const AreasComunes = () => {
data.status_text = 'Eliminado';
}
}
_common_areas.push(data);
_common_areas[index] = _common_area;
toast.current.show({
severity: 'success',
summary: 'Registro exitoso',
detail: 'Área Común Creada',
summary: 'Actualización exitosa',
detail: 'Área Común Actualizada',
life: 3000,
});
setCommonAreaList(_common_areas);
setAreaDialog(false);
setCommonArea(emptyCommonArea);
})
.catch((err) => {
@ -144,12 +155,71 @@ const AreasComunes = () => {
});
});
} else {
// console.log(houses)
fetch('http://localhost:4000/commonArea/createCommonArea', {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(_common_area),
headers: {
'Content-Type': 'application/json',
},
})
.then(function (response) {
if (response.status != 201 && response.status != 200)
console.log('Ocurrió un error con el servicio: ' + response.status);
else return response.json();
})
.then(function (data) {
return data.message;
})
.then((data) => {
if (data) {
if (data.bookable == '1') {
data.bookable_text = 'Necesaria';
} else {
data.bookable_text = 'No es necesaria';
}
if (data.status == '1') {
data.status_text = 'Activo';
} else if (data.status == '0') {
data.status_text = 'Inactivo';
} else {
data.status_text = 'Eliminado';
}
}
_common_areas.push(_common_area);
toast.current.show({
severity: 'success',
summary: 'Registro exitoso',
detail: 'Área Común Registrado',
life: 3000,
});
setCommonAreaList(_common_areas);
setAreaDialog(false);
setCommonArea(emptyCommonArea);
})
.catch((err) => {
console.log('Ocurrió un error con el fetch', err);
toast.current.show({
severity: 'danger',
summary: 'Error',
detail: 'No se pudo registrar el área común',
life: 3000
});
});
}
} else {
setSubmitted(true);
}
};
const deleteCommonArea = () => {
fetch('http://localhost:4000/commonArea/deleteCommonArea/' + commonArea._id, {
cache: 'no-cache',
@ -283,8 +353,6 @@ const AreasComunes = () => {
setDeleteCommonAreasDialog(true);
};
const hideChangeStatusAreaDialog = () => {
setChangeStatusAreaDialog(false);
};
@ -294,6 +362,27 @@ const AreasComunes = () => {
setChangeStatusAreaDialog(true);
};
const hideAreaDialog = () => {
setSubmitted(false);
setAreaDialog(false);
setCommonArea(emptyCommonArea);
setSaveButtonTitle('Registrar');
};
const openNewArea = () => {
setCommonArea(emptyCommonArea);
setAreaDialog(true);
setSubmitted(false);
};
const editArea = (area) => {
setCommonArea({ ...area });
setAreaDialog(true);
setSaveButtonTitle('Actualizar');
};
const actionsCommonArea = (rowData) => {
let icono = '';
let text = '';
@ -307,15 +396,21 @@ const AreasComunes = () => {
return (
<div className="actions">
<Button
icon="pi pi-pencil"
className="p-button-rounded p-button-success my-2 mx-2"
onClick={() => editArea(rowData)}
title="Editar Área Común"
/>
<Button
icon={`${icono}`}
className="p-button-rounded p-button-warning mt-2 mx-2"
className="p-button-rounded p-button-warning my-2 mx-2"
onClick={() => confirmChangeStatusArea(rowData)}
title={`${text}`}
/>
<Button
icon="pi pi-trash"
className="p-button-rounded p-button-danger mt-2"
className="p-button-rounded p-button-danger my-2 mx-2"
onClick={() => confirmDeleteCommonArea(rowData)}
/>
</div>
@ -335,6 +430,32 @@ const AreasComunes = () => {
setCommonArea(_commonArea);
};
const onTimeChange = (e, name) => {
e.target.value.split(':')[1] = "00";
const val = (e.target && e.target.value.split(':')[0]) || '';
let _area = { ...commonArea };
document.getElementById(`${name}`).value = val + ":00";
_area[`${name}`] = val + ":00";
setCommonArea(_area);
};
const areaDialogFooter = (
<>
<Button
label={`${saveButtonTitle}`}
icon="pi pi-check"
className="p-button-primary"
onClick={saveCommonArea}
/>
<Button
label="Cerrar"
icon="pi pi-times"
className="p-button-text"
onClick={hideAreaDialog}
/>
</>
);
const deleteCommonAreaDialogFooter = (
<>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteCommonAreaDialog} />
@ -370,7 +491,18 @@ const AreasComunes = () => {
return (
<React.Fragment>
<div className="my-2">
<Button label="Eliminar" icon="pi pi-trash" className="p-button-danger" onClick={confirmDeleteSelected} disabled={!selectedCommonAreas || !selectedCommonAreas.length} />
<Button
label="Agregar Área Común"
icon="pi pi-plus"
className="p-button-primary mr-2"
onClick={openNewArea}
/>
<Button label="Eliminar"
icon="pi pi-trash"
className="p-button-danger"
onClick={confirmDeleteSelected}
disabled={!selectedCommonAreas || !selectedCommonAreas.length}
/>
</div>
</React.Fragment>
)
@ -401,7 +533,7 @@ const AreasComunes = () => {
const headerName = (
<>
<p>{' '}
<FontAwesomeIcon icon={faUserAlt} style={{ color: "#C08135" }} /> {' '}
<FontAwesomeIcon icon={faHomeAlt} style={{ color: "#C08135" }} /> {' '}
Nombre
</p>
</>
@ -411,7 +543,7 @@ const AreasComunes = () => {
<>
<p>
{' '}
<FontAwesomeIcon icon={faUserAlt} style={{ color: "#D7A86E" }} />{' '}
<FontAwesomeIcon icon={faClock} style={{ color: "#D7A86E" }} />{' '}
Hora de apertura
</p>
</>
@ -420,7 +552,7 @@ const AreasComunes = () => {
const headerHourMax = (
<>
<p> {' '}
<FontAwesomeIcon icon={faIdCardAlt} style={{ color: "#C08135" }} />{' '}
<FontAwesomeIcon icon={faClock} style={{ color: "#C08135" }} />{' '}
Hora de cierre
</p>
</>
@ -488,26 +620,154 @@ const AreasComunes = () => {
}
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"
<DataTable ref={dt} value={commonAreaList} dataKey="_id" paginator rows={10} selection={selectedCommonAreas} onSelectionChange={(e) => setSelectedCommonAreas(e.value)}
scrollable scrollHeight="700px" scrollDirection="both" header={header}
rowsPerPageOptions={[10, 20, 30]} 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="hourMin" sortable header={headerHourMin} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }} alignFrozen="left"></Column>
<Column field="hourMax" sortable 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>
<Column style={{ flexGrow: 1, flexBasis: '80px', minWidth: '80px' }} body={actionsCommonArea}></Column>
</DataTable>
<Dialog
visible={areaDialog}
style={{ width: '650px' }}
header="Agregar Área Común"
modal
className="p-fluid"
footer={areaDialogFooter}
onHide={hideAreaDialog}
>
{commonArea && (
<div className="p-fluid formgrid grid">
<div className="field col-12 md:col-12">
<label htmlFor="name">Nombre</label>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-home"></i>
</span>
<InputText id="name"
type="text"
onChange={(e) => onInputChange(e, 'name')}
value={commonArea.name}
required
autoFocus
className={classNames({
'p-invalid': submitted && commonArea.name === '',
})}
/>
</div>
{submitted && commonArea.name === '' && (
<small className="p-invalid">Nombre es requirido.</small>
)}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="hourMin">Hora apertura</label>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-clock"></i>
</span>
<InputText id="hourMin"
type="time"
min="00:00" max="23:59"
step="3600"
onChange={(e) => onTimeChange(e, 'hourMin')}
value={commonArea.hourMin}
required
autoFocus
className={classNames({
'p-invalid': submitted && compareTimesMinRequired(commonArea.hourMax, commonArea.hourMin),
})}
/>
</div>
{submitted && compareTimesMinRequired(commonArea.hourMax, commonArea.hourMin) && (
<small className="p-invalid">La hora de apertura debe ser menor que la hora de cierre.</small>
)}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="hourMax">Hora de cierre</label>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-clock"></i>
</span>
<InputText id="hourMax"
type="time"
min="00:00"
max="23:59"
step="3600"
onChange={(e) => onTimeChange(e, 'hourMax')}
value={commonArea.hourMax}
required
autoFocus
className={classNames({
'p-invalid': submitted && compareTimesMinRequired(commonArea.hourMax, commonArea.hourMin),
})}
/>
</div>
{submitted && compareTimesMinRequired(commonArea.hourMax, commonArea.hourMin) && (
<small className="p-invalid">La hora de cierre debe ser mayor que la hora de apertura</small>
)}
</div>
</div>
<div className="field col-12 md:col-12">
<label htmlFor="bookable">¿Necesita Reservación?</label>
<div className="formgrid grid align-items-end" style={{ marginTop: '12px', width: '300px' }}>
<div className="field-radiobutton col-6">
<RadioButton
inputId="bookable1"
name="bookable"
value="1"
onChange={onBookableChange}
checked={commonArea.bookable === 1}
/>
<label htmlFor="bookable1">
<span className="p-icon-input-khaki">
<i className="pi pi-check status status-1"></i> Sí
</span>
</label>
</div>
<div className="field-radiobutton col-6">
<RadioButton
inputId="bookable2"
name="bookable"
value="0"
onChange={onBookableChange}
checked={commonArea.bookable === 0}
/>
<label htmlFor="bookable2">
<span className="p-icon-input-khaki">
<i className="pi pi-times status status-0"></i> No
</span>
</label>
</div>
</div>
</div>
</div>
)}
</Dialog>
<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' }} />
@ -542,123 +802,6 @@ const AreasComunes = () => {
</Dialog>
</div>
</div>
<div className="col-12">
<div className="card">
<h5>Registro de área común</h5>
<div className="p-fluid formgrid grid">
<div className="field col-12 md:col-6">
<label htmlFor="name">Nombre</label>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-home"></i>
</span>
<InputText id="name"
type="text"
onChange={(e) => onInputChange(e, 'name')}
value={commonArea.name}
required
autoFocus
className={classNames({
'p-invalid': submitted && commonArea.name === '',
})}
/>
</div>
{submitted && commonArea.name === '' && (
<small className="p-invalid">Nombre es requirido.</small>
)}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="hourMin">Hora apertura</label>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-home"></i>
</span>
<InputText id="hourMin"
type="time"
min="00:00" max="23:59"
step="3600000"
onChange={(e) => onInputChange(e, 'hourMin')}
value={commonArea.hourMin}
required
autoFocus
className={classNames({
'p-invalid': submitted && compareTimesMinRequired(commonArea.hourMax, commonArea.hourMin),
})}
/>
</div>
{submitted && compareTimesMinRequired(commonArea.hourMax, commonArea.hourMin) && (
<small className="p-invalid">La hora de apertura debe ser menor que la hora de cierre.</small>
)}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="hourMax">Hora de cierre</label>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-home"></i>
</span>
<InputText id="hourMax"
type="time"
min="00:00" max="23:59"
step="3600000"
onChange={(e) => onInputChange(e, 'hourMax')}
value={commonArea.hourMax}
required
autoFocus
className={classNames({
'p-invalid': submitted && compareTimesMinRequired(commonArea.hourMax, commonArea.hourMin),
})}
/>
</div>
{submitted && compareTimesMinRequired(commonArea.hourMax, commonArea.hourMin) && (
<small className="p-invalid">La hora de cierre debe ser mayor que la hora de apertura</small>
)}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="bookable">¿Necesita Reservación?</label>
<div className="formgrid grid align-items-end" style={{ marginTop: '12px', width: '300px' }}>
<div className="field-radiobutton col-6">
<RadioButton
inputId="bookable1"
name="bookable"
value="1"
onChange={onBookableChange}
checked={commonArea.bookable === '1'}
/>
<label htmlFor="bookable1">
<span className="p-icon-input-khaki">
<i className="pi pi-check status status-1"></i> Sí
</span>
</label>
</div>
<div className="field-radiobutton col-6">
<RadioButton
inputId="bookable2"
name="bookable"
value="0"
onChange={onBookableChange}
checked={commonArea.bookable === '0'}
/>
<label htmlFor="bookable2">
<span className="p-icon-input-khaki">
<i className="pi pi-times status status-0"></i> No
</span>
</label>
</div>
</div>
</div>
<Button label="Registrar" onClick={saveCommonArea}></Button>
</div>
</div>
</div>
</div>
);

View File

@ -72,6 +72,9 @@ const Inquilinos = () => {
item.number_house = 'Sin vivienda asignada'
}
})
data = data.filter(
(val) => val.status != -1,
);
setTenants(data)
})
}
@ -156,9 +159,9 @@ const Inquilinos = () => {
.catch((error) => console.log(`Ocurrió un error: ${error}`))
} else setSubmitted(true)
} else {
let _tenant = { ..._tenant, number_house: houseNumber };
let _tenant = { ...tenant, number_house: houseNumber };
console.log(`Actualizando inquilino: ${_tenant}`)
fetch(`http://localhost:4000/user/updateUser/${tenant._id}`, {
fetch(`http://localhost:4000/user/updateTenant/${tenant._id}`, {
cache: 'no-cache',
method: 'PUT',
body: JSON.stringify(_tenant),
@ -170,6 +173,17 @@ const Inquilinos = () => {
console.log(`Hubo un error en el servicio: ${response.status}`)
else return response.json()
}).then(() => {
fetch('http://localhost:4000/community/saveTenant',
{
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(_tenant),
headers: {
'Content-Type': 'application/json',
}
});
toast.current.show({
severity: 'success',
summary: 'Éxito',

View File

@ -0,0 +1,361 @@
import React, { useEffect, useState, useRef } from 'react';
import { useCookies } from "react-cookie";
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
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 { faHashtag } from '@fortawesome/free-solid-svg-icons';
import { faCircleQuestion } from '@fortawesome/free-solid-svg-icons';
const PerfilAdminComunidad = () => {
let emptyAdminCommunity = {
_id: null,
dni: '',
name: '',
last_name: '',
email: '',
phone: '',
password: '',
confirmPassword: '',
community_id: '',
community_name: '',
user_type: '2',
date_entry: new Date(),
status: '1',
status_text: '',
};
let emptyCommunity = {
_id: null,
name: '',
province: '',
canton: '',
district: '',
phone: '',
num_houses: 0,
status: '1',
status_text: '',
date_entry: new Date(),
houses: [],
};
const [admin, setAdmin] = useState(emptyAdminCommunity);
const [community, setCommunity] = useState(emptyCommunity);
const [cookies, setCookie] = useCookies();
const [globalFilter, setGlobalFilter] = useState(null);
//para el perfil de la comunidad
const [tenants, setTenants] = useState([]);
const [commonAreaList, setCommonAreaList] = useState([]);
const [provincesList, setProvincesList] = useState([]);
const [cantonsList, setCantonsList] = useState([]);
const [districtsList, setDistrictsList] = useState([]);
async function getProvinces() {
const response = await fetch('assets/demo/data/provincias.json', {
method: 'GET',
});
return await response.json();
}
async function getCantons() {
const response = await fetch('assets/demo/data/cantones.json', {
method: 'GET',
});
return await response.json();
}
async function getDistricts() {
const response = await fetch('assets/demo/data/distritos.json', {
method: 'GET',
});
return await response.json();
}
async function getAdmin() {
await fetch('http://localhost:4000/user/findUserById/' + cookies.id, { method: 'GET' })
.then((response) => response.json())
.then(data => {
let item = data.message;
setAdmin(item);
if (item.community_id || item.community_id != '') {
getCommunity()
} else {
item.community_name = "Sin Comunidad Asignada";
}
})
}
useEffect(() => {
getAdmin();
}, [])
async function getCommunity() {
let pList = await getProvinces();
let cList = await getCantons();
let dList = await getDistricts();
await fetch(`http://localhost:4000/community/findCommunityName/${cookies.community_id}`, { method: 'GET' })
.then((response2) => response2.json())
.then(data => data.message)
.then(data => {
data.province = pList.find((p) => p.code === data.province).name;
data.canton = cList.find((p) => p.code === data.canton).name;
data.district = dList.find((p) => p.code === data.district).name;
setCommunity(data)
})
}
useEffect(() => {
getCommunity();
}, [])
async function tenantsList(id) {
await fetch(`http://localhost:4000/user/findTenants/${id}`, { method: 'GET' })
.then((response) => response.json())
.then(data => data.message)
.then(data => {
data = data.filter(
(val) => val.status != -1,
)
setTenants(data)
});
}
useEffect(() => {
tenantsList(cookies.community_id);
}, [])
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'];
}
return name;
}
const headerNumberHouses = (
<>
<p>
{' '}
<FontAwesomeIcon icon={faHashtag} style={{ color: '#D7A86E' }} />{' '}
Código de vivienda
</p>
</>
);
const headerTenant = (
<>
<p>
{' '}
<FontAwesomeIcon icon={faUserAlt} style={{ color: '#C08135' }} />{' '}
Inquilino
</p>
</>
);
const tenantsBodyTemplate = (rowData) => {
let tenants = rowData.tenants;
let name = 'Sin inquilino';
if (rowData.tenants) {
name = findNameTenant(tenants.tenant_id);
}
return (
<>
{name}
</>
)
}
return (
<>
<div className="grid justify-content-center">
<div className="col-6" >
<div className="card">
<div className='container text-center'>
<div className='row my-4'>
<div className=" col-12 md:col-12">
<h3>Información Básica</h3>
</div>
<div className=" col-6 md:col-6">
<i className="pi pi-home icon-khaki"></i>
<p><strong>Nombre Completo</strong></p>
<div className="p-0 col-12 md:col-12" style={{ margin: '0 auto' }}>
<div className="p-inputgroup justify-content-evenly">
<p>{admin.name + ' ' + admin.last_name}</p>
</div>
</div>
</div>
<div className=" col-6 md:col-6">
<i className="pi pi-id-card icon-khaki"></i>
<p><strong>Identificación</strong></p>
<div className="p-0 col-12 md:col-12" style={{ margin: '0 auto' }}>
<div className="p-inputgroup justify-content-evenly">
<p>{admin.dni}</p>
</div>
</div>
</div>
</div>
<div className='row my-4'>
<div className=" col-12 md:col-12">
<h3>Contacto</h3>
</div>
<div className=" col-6 md:col-6">
<i className="pi pi-at icon-khaki"></i>
<p><strong>Correo Electrónico</strong></p>
<div className="p-0 col-12 md:col-12" style={{ margin: '0 auto' }}>
<div className="p-inputgroup justify-content-evenly">
<p>{admin.email}</p>
</div>
</div>
</div>
<div className=" col-6 md:col-6">
<i className="pi pi-phone icon-khaki"></i>
<p><strong>Número de teléfono</strong></p>
<div className="p-0 col-12 md:col-12" style={{ margin: '0 auto' }}>
<div className="p-inputgroup justify-content-evenly">
<p>{admin.phone}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div className='col-6'>
{community && (
<div className="card">
<div className='container text-center'>
<div className='row my-4'>
<div className=" col-12 md:col-12">
<h3>Comunidad Asignada</h3>
</div>
<div className=" col-4 md:col-4">
<i className="pi pi-home icon-khaki"></i>
<p><strong>Nombre</strong></p>
<div className="p-0 col-12 md:col-12" style={{ margin: '0 auto' }}>
<div className="p-inputgroup align-items-center justify-content-evenly">
<p>{community.name}</p>
</div>
</div>
</div>
<div className="col-4 md:col-4">
<i className="pi pi-phone icon-khaki"></i>
<p><strong>Teléfono Administrativo</strong></p>
<div className="p-0 col-12 md:col-12" style={{ margin: '0 auto' }}>
<div className="p-inputgroup align-items-center justify-content-evenly">
<p>{community.phone}</p>
</div>
</div>
</div>
<div className=" col-4 col-md-4 md:col-4">
<i className="pi pi-map-marker icon-khaki"></i>
<p><strong>Ubicación</strong></p>
<div className="p-0 col-10 md:col-10">
<div className="p-inputgroup align-items-center justify-content-evenly">
<p>{community.province}, {community.canton}, {community.district}</p>
</div>
</div>
</div>
</div>
<div className='row my-5'>
<div className=" col-12 md:col-12">
<h3>Viviendas de la Comunidad</h3>
</div>
<div className=" col-12 md:col-12">
<i className="pi pi-hashtag icon-khaki"></i>
<p><strong>Cantidad de Viviendas</strong></p>
<div className="p-0 col-2 md:col-2" style={{ margin: '0 auto' }}>
<div className="p-inputgroup justify-content-evenly">
<p>{community.num_houses}</p>
</div>
</div>
</div>
</div>
</div>
</div>
)}
</div>
</div>
<div className='grid justify-content-center'>
<div className='col-6'>
{community && (
<div className="card">
<div className='container text-center'>
<div className='row my-5'>
<div className=" col-12 md:col-12">
<h3> Viviendas</h3>
<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>
</div>
)}
</div>
</div>
</>
)
}
export default React.memo(PerfilAdminComunidad)