Merge pull request #157 from DeimosPr4/156-issue-separar-página-de-formulario-de-registro-de-inquilinos

separar página de formulario de registro de inquilinos
This commit is contained in:
Eduardo Quiros 2022-08-07 19:51:47 +00:00 committed by GitHub
commit b63fe2b7ec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 706 additions and 319 deletions

12
.envrc Normal file
View File

@ -0,0 +1,12 @@
#!/usr/bin/env bash
# ^ added for shellcheck and file-type detection
# Watch & reload direnv on change
watch_file devshell.toml
if [[ $(type -t use_flake) != function ]]; then
echo "ERROR: use_flake function missing."
echo "Please update direnv to v2.30.0 or later."
exit 1
fi
use flake

View File

@ -29,24 +29,3 @@ jobs:
cd ./api-gateway cd ./api-gateway
npm ci npm ci
npm run build --if-present npm run build --if-present
build-web:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x, 16.x, 18.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps:
- name: checkout
uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Test
env:
NODE_OPTIONS: '--openssl-legacy-provider'
run: |
cd ./web-ui/web-react/
npm ci
npm run build --if-present

View File

@ -1,4 +1,4 @@
import { Controller, Get, Post, Body, Param, Delete } from '@nestjs/common'; import { Controller, Get, Post, Put, Body, Param, Delete } from '@nestjs/common';
import { AppService } from './app.service'; import { AppService } from './app.service';
@Controller() @Controller()
export class AppController { export class AppController {
@ -80,6 +80,33 @@ export class AppController {
); );
} }
@Put('user/updateUser')
updateUser(
@Body('dni') dni: string,
@Body('name') name: string,
@Body('last_name') last_name: string,
@Body('email') email: string,
@Body('phone') phone: number,
@Body('password') password: string,
@Body('user_type') user_type: string,
@Body('status') status: string,
@Body('date_entry') date_entry: Date,
@Body('community_id') community_id: string,
) {
return this.appService.updateUser(
dni,
name,
last_name,
email,
phone,
password,
user_type,
status,
date_entry,
community_id,
);
}
@Get('user/allUsers') @Get('user/allUsers')
allUsers() { allUsers() {
return this.appService.allUsers(); return this.appService.allUsers();

View File

@ -53,6 +53,36 @@ export class AppService {
.pipe(map((message: string) => ({ message }))); .pipe(map((message: string) => ({ message })));
} }
updateUser(
dni: string,
name: string,
last_name: string,
email: string,
phone: number,
password: string,
user_type: string,
status: string,
date_entry: Date,
community_id: string,
) {
const pattern = { cmd: 'updateUser' };
const payload = {
dni: dni,
name: name,
last_name: last_name,
email: email,
phone: phone,
password: password,
user_type: user_type,
status: status,
date_entry: date_entry,
community_id: community_id,
};
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
//POST parameter from API //POST parameter from API
createAdminSystem(dni: string, name: string, last_name: string, email: string, phone: number createAdminSystem(dni: string, name: string, last_name: string, email: string, phone: number
, user_type: string, status: string, date_entry: Date) { , user_type: string, status: string, date_entry: Date) {

4
devshell.toml Normal file
View File

@ -0,0 +1,4 @@
# https://numtide.github.io/devshell
[[commands]]
package = "devshell.cli"
help = "Per project developer environments"

92
flake.lock Normal file
View File

@ -0,0 +1,92 @@
{
"nodes": {
"devshell": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
},
"locked": {
"lastModified": 1658746384,
"narHash": "sha256-CCJcoMOcXyZFrV1ag4XMTpAPjLWb4Anbv+ktXFI1ry0=",
"owner": "numtide",
"repo": "devshell",
"rev": "0ffc7937bb5e8141af03d462b468bd071eb18e1b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "devshell",
"type": "github"
}
},
"flake-utils": {
"locked": {
"lastModified": 1642700792,
"narHash": "sha256-XqHrk7hFb+zBvRg6Ghl+AZDq03ov6OshJLiSWOoX5es=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "846b2ae0fc4cc943637d3d1def4454213e203cba",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_2": {
"locked": {
"lastModified": 1656928814,
"narHash": "sha256-RIFfgBuKz6Hp89yRr7+NR5tzIAbn52h8vT6vXkYjZoM=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "7e2a3b3dfd9af950a856d66b0a7d01e3c18aa249",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1643381941,
"narHash": "sha256-pHTwvnN4tTsEKkWlXQ8JMY423epos8wUOhthpwJjtpc=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "5efc8ca954272c4376ac929f4c5ffefcc20551d5",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1659782844,
"narHash": "sha256-tM/qhHFE61puBxh9ebP3BIG1fkRAT4rHqD3jCM0HXGY=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "c85e56bb060291eac3fb3c75d4e0e64f6836fcfe",
"type": "github"
},
"original": {
"id": "nixpkgs",
"type": "indirect"
}
},
"root": {
"inputs": {
"devshell": "devshell",
"flake-utils": "flake-utils_2",
"nixpkgs": "nixpkgs_2"
}
}
},
"root": "root",
"version": 7
}

20
flake.nix Normal file
View File

@ -0,0 +1,20 @@
{
description = "virtual environments";
inputs.devshell.url = "github:numtide/devshell";
inputs.flake-utils.url = "github:numtide/flake-utils";
outputs = { self, flake-utils, devshell, nixpkgs }:
flake-utils.lib.eachDefaultSystem (system: {
devShell =
let pkgs = import nixpkgs {
inherit system;
overlays = [ devshell.overlay ];
};
in
pkgs.devshell.mkShell {
imports = [ (pkgs.devshell.importTOML ./devshell.toml) ];
};
});
}

View File

@ -33,6 +33,7 @@ import AdministradoresComunidad from './components/AdministradoresComunidad';
import GuardasSeguridad from './components/GuardasSeguridad'; import GuardasSeguridad from './components/GuardasSeguridad';
import Communities from './components/ComunidadViviendas'; import Communities from './components/ComunidadViviendas';
import Inquilinos from './components/Inquilinos'; import Inquilinos from './components/Inquilinos';
import InquilinosCompletar from "./components/InquilinosCompletar.js";
import Crud from './pages/Crud'; import Crud from './pages/Crud';
import EmptyPage from './pages/EmptyPage'; import EmptyPage from './pages/EmptyPage';
@ -421,6 +422,7 @@ const App = () => {
<Route path="/guardasSeguridad" component={GuardasSeguridad} /> <Route path="/guardasSeguridad" component={GuardasSeguridad} />
<Route path="/comunidadesViviendas" component={Communities} /> <Route path="/comunidadesViviendas" component={Communities} />
<Route path="/inquilinos" component={Inquilinos} /> <Route path="/inquilinos" component={Inquilinos} />
<Route path="/InquilinosCompletar" component={InquilinosCompletar} />
<Route path="/areasComunes" component={AreasComunes} /> <Route path="/areasComunes" component={AreasComunes} />
<Route path="/logIn" component={LogIn} /> <Route path="/logIn" component={LogIn} />
</div> </div>

View File

@ -1,27 +1,22 @@
import { Button } from 'primereact/button'; import { Button } from 'primereact/button'
import { InputText } from 'primereact/inputtext' import { InputText } from 'primereact/inputtext'
import React, { useEffect, useState, useRef } from 'react' import React, { useEffect, useRef, useState } from 'react'
import { DataTable } from 'primereact/datatable'; import { DataTable } from 'primereact/datatable'
import { Column } from 'primereact/column'; import { Column } from 'primereact/column'
import { Dropdown } from 'primereact/dropdown'; import { Dropdown } from 'primereact/dropdown'
import { Toast } from 'primereact/toast'; import { Toast } from 'primereact/toast'
import { Dialog } from 'primereact/dialog'; import { Dialog } from 'primereact/dialog'
import { Toolbar } from 'primereact/toolbar'; import { Toolbar } from 'primereact/toolbar'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faHome } from '@fortawesome/free-solid-svg-icons'; import { faUserAlt } from '@fortawesome/free-solid-svg-icons'
import { faUserAlt } from '@fortawesome/free-solid-svg-icons'; import { faPhoneAlt } from '@fortawesome/free-solid-svg-icons'
import { faPhoneAlt } from '@fortawesome/free-solid-svg-icons'; import { faAt } from '@fortawesome/free-solid-svg-icons'
import { faAt } from '@fortawesome/free-solid-svg-icons'; import { faIdCardAlt } from '@fortawesome/free-solid-svg-icons'
import { faIdCardAlt } from '@fortawesome/free-solid-svg-icons'; import { faHashtag } from '@fortawesome/free-solid-svg-icons'
import { faEllipsis } from '@fortawesome/free-solid-svg-icons'; import { faCircleQuestion } from '@fortawesome/free-solid-svg-icons'
import { faHashtag } from '@fortawesome/free-solid-svg-icons'; import { useCookies } from 'react-cookie'
import { faCircleQuestion } from '@fortawesome/free-solid-svg-icons';
import { useCookies } from "react-cookie";
const Inquilinos = () => { const Inquilinos = () => {
let emptyTenant = { let emptyTenant = {
_id: null, _id: null,
dni: '', dni: '',
@ -37,66 +32,65 @@ const Inquilinos = () => {
date_entry: new Date(), date_entry: new Date(),
status: '1', status: '1',
status_text: '', status_text: '',
}; }
const [tenants, setTenants] = useState([]); const [tenants, setTenants] = useState([])
const [tenant, setTenant] = useState(emptyTenant); const [tenant, setTenant] = useState(emptyTenant)
const [selectedTentants, setSelectedTenants] = useState(null); const [selectedTentants, setSelectedTenants] = useState(null)
const [globalFilter, setGlobalFilter] = useState(null); const [globalFilter, setGlobalFilter] = useState(null)
const [deleteTenantDialog, setDeleteTenantDialog] = useState(false); const [deleteTenantDialog, setDeleteTenantDialog] = useState(false)
const [deleteTenantsDialog, setDeleteTenantsDialog,] = useState(false); const [deleteTenantsDialog, setDeleteTenantsDialog] = useState(false)
const [communitiesList, setCommunitiesList] = useState([]); const [communitiesList, setCommunitiesList] = useState([])
const [communityId, setCommunityId] = useState(null); const [communityId, setCommunityId] = useState(null)
const [submitted, setSubmitted] = useState(false); const [submitted, setSubmitted] = useState(false)
const toast = useRef(null); const toast = useRef(null)
const dt = useRef(null); const dt = useRef(null)
const [cookies, setCookie] = useCookies();
const [changeStatusTenantDialog, setChangeStatusTenantDialog] = useState(false);
const [cookies, setCookie] = useCookies()
const [changeStatusTenantDialog, setChangeStatusTenantDialog] =
useState(false)
async function tenantsList() { async function tenantsList() {
await fetch(`http://localhost:4000/user/findTenants/${cookies.community_id}`, { method: 'GET' }) await fetch(
`http://localhost:4000/user/findTenants/${cookies.community_id}`,
{ method: 'GET' },
)
.then((response) => response.json()) .then((response) => response.json())
.then(data => data.message) .then((data) => data.message)
.then(data => { .then((data) => {
data = data.filter( data = data.filter((val) => val.status !== -1)
(val) => val.status != -1,
)
data.map((item) => { data.map((item) => {
if (item.status == '1') { if (item.status === '1') {
item.status_text = 'Activo'; item.status_text = 'Activo'
} else if (item.status == '0') { } else if (item.status === '0') {
item.status_text = 'Inactivo'; item.status_text = 'Inactivo'
} }
if (item.number_house === '') {
if (item.number_house == "") { item.number_house = 'Sin vivienda asignada'
item.number_house = "Sin vivienda asignada";
} }
}) })
setTenants(data) setTenants(data)
}); })
} }
async function getCommunites() { async function getCommunites() {
let response = await fetch('http://localhost:4000/community/allCommunities', { method: 'GET' }); let response = await fetch(
let resList = await response.json(); 'http://localhost:4000/community/allCommunities',
let list = await resList.message; { method: 'GET' },
list = await list.filter(
(val) => val.status != -1,
) )
setCommunitiesList(await list); let resList = await response.json()
let list = await resList.message
list = await list.filter((val) => val.status !== -1)
setCommunitiesList(await list)
} }
useEffect(() => { useEffect(() => {
tenantsList(); tenantsList()
}, []) }, [tenantsList])
useEffect(() => { useEffect(() => {
getCommunites(); getCommunites()
}, []) }, [])
const cList = communitiesList.map((item) => ({ const cList = communitiesList.map((item) => ({
@ -105,206 +99,167 @@ const Inquilinos = () => {
})) }))
function registrarInquilino() { function registrarInquilino() {
let data = { let newTenant = {
dni: document.getElementById('identificacion').value, _id: null,
name: document.getElementById('nombre').value, dni: '',
last_name: document.getElementById('apellidos').value, name: '',
phone: document.getElementById('telefono').value, last_name: '',
email: document.getElementById('correo_electronico').value, email: document.getElementById('correo_electronico').value,
phone: '',
password: '',
community_id: document.getElementById('numero_vivienda').value, community_id: document.getElementById('numero_vivienda').value,
password: document.getElementById('password').value, community_name: '',
number_house: 'Sin número de vivienda',
date_entry: new Date(),
user_type: '3', user_type: '3',
status: '1', status: '1',
}; status_text: '',
}
fetch('http://localhost:3000/api/createUser', { fetch('http://localhost:3000/api/createUser', {
method: 'POST', method: 'POST',
cache: 'no-cache', cache: 'no-cache',
body: JSON.stringify(data), body: JSON.stringify(newTenant),
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
}).then((response) => { }).then((response) => {
if (response.ok) { if (response.ok) {
alert('Inquilino registrado correctamente'); alert('Inquilino registrado correctamente')
} else { } else {
alert('Error al registrar inquilino'); alert('Error al registrar inquilino')
} }
}); })
} }
const deleteTenant = () => { const deleteTenant = () => {
/* fetch('http://localhost:4000/community/deleteCommunity/' + community._id, { let _tenants = tenants.filter((val) => val._id !== tenant._id)
cache: 'no-cache', setTenants(_tenants)
method: 'DELETE', setDeleteTenantDialog(false)
headers: { setTenant(emptyTenant)
'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({ toast.current.show({
severity: 'success', severity: 'success',
summary: 'Inquilino Eliminado', summary: 'Inquilino Eliminado',
life: 3000, life: 3000,
}); })
}; }
const deleteSelectedTenants = () => { const deleteSelectedTenants = () => {
let _tenants = tenants.filter( let _tenants = tenants.filter((val) => !selectedTentants.includes(val))
(val) => !selectedTentants.includes(val), setTenants(_tenants)
); setDeleteTenantsDialog(false)
/* selectedCommunities.map((item) => { setSelectedTenants(null)
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({ toast.current.show({
severity: 'success', severity: 'success',
summary: 'Éxito', summary: 'Éxito',
detail: 'Inquilinos Eliminados', detail: 'Inquilinos Eliminados',
life: 3000, life: 3000,
}); })
}; }
const cambiarStatusUser = () => { const cambiarStatusUser = () => {
if (tenant.status == '1') { if (tenant.status === '1') {
tenant.status = '0'; tenant.status = '0'
tenant.status_text = 'Inactivo'; tenant.status_text = 'Inactivo'
} else if (tenant.status === '0') {
} else if (tenant.status == '0') { tenant.status = '1'
tenant.status = '1'; tenant.status_text = 'Activo'
tenant.status_text = 'Activo';
} }
var data = { var data = {
id: tenant._id, id: tenant._id,
status: tenant.status, status: tenant.status,
}; }
fetch('http://localhost:4000/user/changeStatus', { fetch('http://localhost:4000/user/changeStatus', {
cache: 'no-cache', cache: 'no-cache',
method: 'POST', method: 'POST',
body: JSON.stringify(data), body: JSON.stringify(data),
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json',
} },
}) })
.then( .then((response) => {
function (response) { if (response.status !== 201) {
if (response.status != 201) console.log('Ocurrió un error con el servicio: ' + response.status)
console.log('Ocurrió un error con el servicio: ' + response.status); } else {
else return response.json()
return response.json();
} }
) })
.then( .then(() => {
function (response) { setChangeStatusTenantDialog(false)
setChangeStatusTenantDialog(false); toast.current.show({
toast.current.show({ severity: 'success',
severity: 'success', summary: 'Éxito',
summary: 'Éxito', detail: 'Inquilino Actualizado',
detail: 'Inquilino Actualizado', life: 3000,
life: 3000, })
}); })
} .catch((err) => console.log('Ocurrió un error con el fetch', err))
)
.catch(
err => console.log('Ocurrió un error con el fetch', err)
);
} }
const hideDeleteTenantDialog = () => { const hideDeleteTenantDialog = () => {
setDeleteTenantDialog(false); setDeleteTenantDialog(false)
} }
const hideDeleteTenantsDialog = () => { const hideDeleteTenantsDialog = () => {
setDeleteTenantsDialog(false); setDeleteTenantsDialog(false)
} }
const confirmDeleteTenant = (tenant) => { const confirmDeleteTenant = (tenant) => {
setTenant(tenant); setTenant(tenant)
setDeleteTenantDialog(true); setDeleteTenantDialog(true)
} }
const confirmDeleteSelected = () => { const confirmDeleteSelected = () => {
setDeleteTenantsDialog(true); setDeleteTenantsDialog(true)
}; }
const hideChangeStatusTenantDialog = () => { const hideChangeStatusTenantDialog = () => {
setChangeStatusTenantDialog(false); setChangeStatusTenantDialog(false)
}; }
const confirmChangeStatusTenant = (tenant) => { const confirmChangeStatusTenant = (tenant) => {
setTenant(tenant); setTenant(tenant)
setChangeStatusTenantDialog(true); setChangeStatusTenantDialog(true)
}; }
const actionsTenant = (rowData) => { const actionsTenant = (rowData) => {
let icono = ''; let icono = ''
let text = ''; let text = ''
if (rowData.status == '0') { if (rowData.status === '0') {
icono = "pi pi-eye"; icono = 'pi pi-eye'
text = "Activar Inquilino" text = 'Activar Inquilino'
} else if (rowData.status == '1') { } else if (rowData.status === '1') {
icono = "pi pi-eye-slash"; icono = 'pi pi-eye-slash'
text = "Inactivar Inquilino" text = 'Inactivar Inquilino'
} }
return ( return (
<div className="actions"> <div className='actions'>
<Button <Button
icon={`${icono}`} icon={`${icono}`}
className="p-button-rounded p-button-warning mt-2 mx-2" className='p-button-rounded p-button-warning mt-2 mx-2'
onClick={() => confirmChangeStatusTenant(rowData)} onClick={() => confirmChangeStatusTenant(rowData)}
title={`${text}`} title={`${text}`}
/> />
<Button icon="pi pi-trash" <Button
className="p-button-rounded p-button-danger mt-2 mx-2" icon='pi pi-trash'
onClick={() => confirmDeleteTenant(rowData)} /> className='p-button-rounded p-button-danger mt-2 mx-2'
onClick={() => confirmDeleteTenant(rowData)}
/>
</div> </div>
); )
} }
const leftToolbarTemplate = () => { const leftToolbarTemplate = () => {
return ( return (
<React.Fragment> <React.Fragment>
<div className="my-2"> <div className='my-2'>
<Button label="Eliminar" icon="pi pi-trash" className="p-button-danger" onClick={confirmDeleteSelected} disabled={!selectedTentants || !selectedTentants.length} /> <Button
label='Eliminar'
icon='pi pi-trash'
className='p-button-danger'
onClick={confirmDeleteSelected}
disabled={!selectedTentants || !selectedTentants.length}
/>
</div> </div>
</React.Fragment> </React.Fragment>
) )
@ -313,95 +268,141 @@ const Inquilinos = () => {
const rightToolbarTemplate = () => { const rightToolbarTemplate = () => {
return ( return (
<React.Fragment> <React.Fragment>
<Button label="Exportar" icon="pi pi-upload" className="p-button-help" /> <Button
label='Exportar'
icon='pi pi-upload'
className='p-button-help'
/>
</React.Fragment> </React.Fragment>
) )
} }
const header = ( const header = (
<div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center"> <div className='flex flex-column md:flex-row md:justify-content-between md:align-items-center'>
<h5 className="m-0">Inquilinos</h5> <h5 className='m-0'>Inquilinos</h5>
<span className="block mt-2 md:mt-0 p-input-icon-left"> <span className='block mt-2 md:mt-0 p-input-icon-left'>
<i className="pi pi-search" /> <i className='pi pi-search' />
<InputText type="search" onInput={(e) => setGlobalFilter(e.target.value)} placeholder="Buscar..." /> <InputText
type='search'
onInput={(e) => setGlobalFilter(e.target.value)}
placeholder='Buscar...'
/>
</span> </span>
</div> </div>
); )
const deleteTenantDialogFooter = ( const deleteTenantDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteTenantDialog} /> <Button
<Button label="Sí" icon="pi pi-check" className="p-button-text" onClick={deleteTenant} /> label='No'
icon='pi pi-times'
className='p-button-text'
onClick={hideDeleteTenantDialog}
/>
<Button
label='Sí'
icon='pi pi-check'
className='p-button-text'
onClick={deleteTenant}
/>
</> </>
); )
const deleteTenantsDialogFooter = ( const deleteTenantsDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteTenantsDialog} /> <Button
<Button label="Sí" icon="pi pi-check" className="p-button-text" onClick={deleteSelectedTenants} /> label='No'
icon='pi pi-times'
className='p-button-text'
onClick={hideDeleteTenantsDialog}
/>
<Button
label='Sí'
icon='pi pi-check'
className='p-button-text'
onClick={deleteSelectedTenants}
/>
</> </>
); )
const changeStatusTenantDialogFooter = ( const changeStatusTenantDialogFooter = (
<> <>
<Button <Button
label="No" label='No'
icon="pi pi-times" icon='pi pi-times'
className="p-button-text" className='p-button-text'
onClick={hideChangeStatusTenantDialog} onClick={hideChangeStatusTenantDialog}
/> />
<Button <Button
label="Sí" label='Sí'
icon="pi pi-check" icon='pi pi-check'
className="p-button-text" className='p-button-text'
onClick={cambiarStatusUser} onClick={cambiarStatusUser}
/> />
</> </>
); )
const headerName = ( const headerName = (
<> <>
<p> <FontAwesomeIcon icon={faUserAlt} style={{ color: "#C08135" }} /> Nombre</p> <p>
<FontAwesomeIcon icon={faUserAlt} style={{ color: '#C08135' }} /> Nombre
</p>
</> </>
) )
const headerLastName = ( const headerLastName = (
<> <>
<p> <FontAwesomeIcon icon={faUserAlt} style={{ color: "#D7A86E" }} /> Apellidos</p> <p>
<FontAwesomeIcon icon={faUserAlt} style={{ color: '#D7A86E' }} />{' '}
Apellidos
</p>
</> </>
) )
const headerDNI = ( const headerDNI = (
<> <>
<p> <FontAwesomeIcon icon={faIdCardAlt} style={{ color: "#C08135" }} /> Identificación</p> <p>
<FontAwesomeIcon icon={faIdCardAlt} style={{ color: '#C08135' }} />{' '}
Identificación
</p>
</> </>
) )
const headerEmail = ( const headerEmail = (
<> <>
<p> <FontAwesomeIcon icon={faAt} style={{ color: "#D7A86E" }} /> Correo Electrónico</p> <p>
<FontAwesomeIcon icon={faAt} style={{ color: '#D7A86E' }} /> Correo
Electrónico
</p>
</> </>
) )
const headerPhone = ( const headerPhone = (
<> <>
<p> <FontAwesomeIcon icon={faPhoneAlt} style={{ color: "#C08135" }} /> Teléfono</p> <p>
<FontAwesomeIcon icon={faPhoneAlt} style={{ color: '#C08135' }} />{' '}
Teléfono
</p>
</> </>
) )
const headerNumberHouse = ( const headerNumberHouse = (
<> <>
<p> <FontAwesomeIcon icon={faHashtag} style={{ color: "#C08135" }} /> Número de vivienda</p> <p>
<FontAwesomeIcon icon={faHashtag} style={{ color: '#C08135' }} /> Número
de vivienda
</p>
</> </>
) )
const headerStatus = ( const headerStatus = (
<> <>
<p> {' '} <p>
<FontAwesomeIcon icon={faCircleQuestion} style={{ color: "#D7A86E" }} />{' '} {' '}
<FontAwesomeIcon
icon={faCircleQuestion}
style={{ color: '#D7A86E' }}
/>{' '}
Estado Estado
</p> </p>
</> </>
@ -410,67 +411,179 @@ const Inquilinos = () => {
const statusBodyTemplate = (rowData) => { const statusBodyTemplate = (rowData) => {
return ( return (
<> <>
<span <span className={`status status-${rowData.status}`}>
className={`status status-${rowData.status}`}
>
{rowData.status_text} {rowData.status_text}
</span> </span>
</> </>
); )
}; }
return ( return (
<div className="grid"> <div className='grid'>
<div className="col-12"> <div className='col-12'>
<Toast ref={toast} /> <Toast ref={toast} />
<div className="card"> <div className='card'>
<Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate}></Toolbar> <Toolbar
<DataTable ref={dt} value={tenants} dataKey="_id" paginator rows={5} selection={selectedTentants} onSelectionChange={(e) => setSelectedTenants(e.value)} className='mb-4'
scrollable scrollHeight="400px" scrollDirection="both" header={header} left={leftToolbarTemplate}
rowsPerPageOptions={[5, 10, 25]} className="datatable-responsive mt-3" right={rightToolbarTemplate}
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown" ></Toolbar>
currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} inquilinos" <DataTable
globalFilter={globalFilter} emptyMessage="No hay inquilinos en esta comunidad registrados."> ref={dt}
<Column selectionMode="multiple" headerStyle={{ width: '3rem' }}></Column> value={tenants}
<Column field="name" sortable header={headerName} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column> dataKey='_id'
<Column field="last_name" sortable header={headerLastName} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }} alignFrozen="left"></Column> paginator
<Column field="dni" sortable header={headerDNI} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}> rows={5}
</Column> selection={selectedTentants}
<Column field="email" sortable header={headerEmail} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column> onSelectionChange={(e) => setSelectedTenants(e.value)}
<Column field="phone" header={headerPhone} style={{ flexGrow: 1, flexBasis: '80px', minWidth: '80px', wordBreak: 'break-word' }}></Column> scrollable
<Column field="number_house" sortable header={headerNumberHouse} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word', justifyContent: 'center' }}></Column> 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 <Column
field="status" 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
field='status'
sortable sortable
header={headerStatus} header={headerStatus}
body={statusBodyTemplate} body={statusBodyTemplate}
style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}> style={{
</Column> flexGrow: 1,
<Column style={{ flexGrow: 1, flexBasis: '80px', minWidth: '80px' }} body={actionsTenant}></Column> flexBasis: '160px',
minWidth: '160px',
wordBreak: 'break-word',
}}
></Column>
<Column
style={{ flexGrow: 1, flexBasis: '80px', minWidth: '80px' }}
body={actionsTenant}
></Column>
</DataTable> </DataTable>
<Dialog visible={deleteTenantDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteTenantDialogFooter} onHide={hideDeleteTenantDialog}> <Dialog
<div className="flex align-items-center justify-content-center"> visible={deleteTenantDialog}
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> style={{ width: '450px' }}
{tenant && <span>¿Estás seguro que desea eliminar a <b>{tenant.name}</b>?</span>} 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> </div>
</Dialog> </Dialog>
<Dialog visible={deleteTenantsDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteTenantsDialogFooter} onHide={hideDeleteTenantsDialog}> <Dialog
<div className="flex align-items-center justify-content-center"> visible={deleteTenantsDialog}
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> style={{ width: '450px' }}
{selectedTentants && <span>¿Está seguro eliminar los inquilinos seleccionados?</span>} 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> </div>
</Dialog> </Dialog>
<Dialog <Dialog
visible={changeStatusTenantDialog} visible={changeStatusTenantDialog}
style={{ width: '450px' }} style={{ width: '450px' }}
header="Confirmar" header='Confirmar'
modal modal
footer={changeStatusTenantDialogFooter} footer={changeStatusTenantDialogFooter}
onHide={hideChangeStatusTenantDialog} onHide={hideChangeStatusTenantDialog}
> >
<div className="flex align-items-center justify-content-center"> <div className='flex align-items-center justify-content-center'>
<i <i
className="pi pi-exclamation-triangle mr-3" className='pi pi-exclamation-triangle mr-3'
style={{ fontSize: '2rem' }} style={{ fontSize: '2rem' }}
/> />
{tenant && ( {tenant && (
@ -482,52 +595,35 @@ const Inquilinos = () => {
</Dialog> </Dialog>
</div> </div>
</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>
<div className="p-fluid formgrid grid"> <div className='p-fluid formgrid grid'>
<div className="field col-12 md:col-6"> <div className='field col-12 md:col-6'>
<label htmlFor="nombre">Nombre</label> <label htmlFor='correo_electronico'>Correo electrónico</label>
<InputText type="text" className="form-control" id="nombre" />
</div>
<div className="field col-12 md:col-6">
<label htmlFor="apellidos">Apellido(s)</label>
<InputText type="text" className="form-control" id="apellidos" />
</div>
<div className="field col-12 md:col-6">
<label htmlFor="identificacion">Identificación</label>
<InputText <InputText
type="text" required
className="form-control" type='email'
id="identificacion" className='form-control'
id='correo_electronico'
/> />
</div> </div>
<div className="field col-12 md:col-6"> <div className='field col-12 md:col-6'>
<label htmlFor="correo_electronico">Correo electrónico</label> <label htmlFor='numero_vivienda'>Número de Vivienda</label>
<InputText <Dropdown
type="email" required
className="form-control" id='numero_vivienda'
id="correo_electronico" value={communityId}
options={cList}
onChange={(e) => setCommunityId(e.value)}
/> />
</div> </div>
<div className="field col-12 md:col-6"> <Button label='Registrar' onClick={registrarInquilino} />
<label htmlFor="numero_vivienda">Número de Vivienda</label>
<Dropdown id="numero_vivienda" value={communityId} options={cList} />
</div>
<div className="field col-12 md:col-6">
<label htmlFor="identificacion">Identificación</label>
<InputText
type="password"
className="form-control"
id="identificacion"
/>
</div>
<Button label="Registrar" onClick={registrarInquilino} />
</div> </div>
</div> </div>
</div> </div>
</div> </div>
); )
}; }
export default React.memo(Inquilinos); export default React.memo(Inquilinos)

View File

@ -0,0 +1,125 @@
import { Button } from 'primereact/button'
import { InputText } from 'primereact/inputtext'
import React, { useState } from 'react'
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',
status_text: '',
}
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 [communityId, setCommunityId] = useState(null)
const [submitted, setSubmitted] = useState(false)
const [cookies, setCookie] = useCookies()
const [changeStatusTenantDialog, setChangeStatusTenantDialog] =
useState(false)
function finalizarRegistro() {
let data = {
dni: document.getElementById('identificacion').value,
name: document.getElementById('nombre').value,
last_name: document.getElementById('apellidos').value,
phone: document.getElementById('telefono').value,
email: document.getElementById('correo_electronico').value,
community_id: document.getElementById('numero_vivienda').value,
password: document.getElementById('password').value,
user_type: '3',
status: '1',
}
fetch('http://localhost:3000/api/createUser', {
method: 'PUT',
cache: 'no-cache',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
}).then((response) => {
if (response.ok) {
alert('Inquilino registrado correctamente')
} else {
alert('Error al registrar inquilino')
}
})
}
return (
<div className='grid'>
<div className='col-12'>
<div className='card'>
<h5 className='card-header'>Finalizar Registro</h5>
<div className='p-fluid formgrid grid'>
<div className='field col-12 md:col-6'>
<label htmlFor='nombre'>Nombre</label>
<InputText
required
type='text'
className='form-control'
id='nombre'
/>
</div>
<div className='field col-12 md:col-6'>
<label htmlFor='apellidos'>Apellido(s)</label>
<InputText
required
type='text'
className='form-control'
id='apellidos'
/>
</div>
<div className='field col-12 md:col-6'>
<label htmlFor='identificacion'>Identificación</label>
<InputText
required
type='text'
className='form-control'
id='identificacion'
/>
</div>
<div className='field col-12 md:col-6'>
<label htmlFor='correo_electronico'>Correo electrónico</label>
<InputText
required
type='email'
className='form-control'
id='correo_electronico'
/>
</div>
<div className='field col-12 md:col-6'>
<label htmlFor='password'>Password</label>
<InputText
required
type='password'
className='form-control'
id='password'
/>
</div>
<Button label='Registrar' onClick={finalizarRegistro} />
</div>
</div>
</div>
</div>
)
}
export default React.memo(InquilinosCompletar)