Merge pull request #177 from DeimosPr4/172-issue-arreglar-registro-inquilino

172 issue arreglar registro inquilino
This commit is contained in:
Eduardo Quiros 2022-08-21 10:42:57 +00:00 committed by GitHub
commit de69d9f4ab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 207 additions and 220 deletions

View File

@ -160,6 +160,10 @@ export class AppController {
return this.appService.deleteAdminCommunity(id); return this.appService.deleteAdminCommunity(id);
} }
@Delete('user/deleteTenant/:id')
deleteTenant(@Param('id') id: string) {
return this.appService.deleteTenant(id);
}
@Post('user/changeStatus') @Post('user/changeStatus')
changeStatusUser( changeStatusUser(

View File

@ -54,8 +54,8 @@ export class AppService {
} }
updateUser( updateUser(
dni: string, dni: string,
name: string, name: string,
last_name: string, last_name: string,
email: string, email: string,
phone: number, phone: number,
@ -201,6 +201,14 @@ export class AppService {
.pipe(map((message: string) => ({ message }))); .pipe(map((message: string) => ({ message })));
} }
deleteTenant(id: string) {
const pattern = { cmd: 'deleteTenant' };
const payload = { id: id };
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
inicioSesion(pEmail: string, pPassword: string) { inicioSesion(pEmail: string, pPassword: string) {
const pattern = { cmd: 'loginUser' }; const pattern = { cmd: 'loginUser' };
const payload = { email: pEmail, password: pPassword }; const payload = { email: pEmail, password: pPassword };

View File

@ -2,3 +2,8 @@
[[commands]] [[commands]]
package = "devshell.cli" package = "devshell.cli"
help = "Per project developer environments" help = "Per project developer environments"
[[commands]]
package = "nodejs"
help = "Node.js"

View File

@ -5,6 +5,7 @@
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "servicio-comunidad-viviendas",
"version": "0.0.1", "version": "0.0.1",
"license": "UNLICENSED", "license": "UNLICENSED",
"dependencies": { "dependencies": {

View File

@ -115,13 +115,15 @@ export class UsersController {
return this.userService.deleteAdminSystem(user['id']); return this.userService.deleteAdminSystem(user['id']);
} }
@MessagePattern({ cmd: 'deleteAdminCommunity' }) @MessagePattern({ cmd: 'deleteAdminCommunity' })
deleteAdminCommunity(@Payload() user: any) { deleteAdminCommunity(@Payload() user: any) {
return this.userService.deleteAdminCommunity(user['id']); return this.userService.deleteAdminCommunity(user['id']);
} }
@MessagePattern({ cmd: 'deleteTenant' })
deleteTenant(@Payload() user: any) {
return this.userService.deleteTenant(user['id']);
}
@MessagePattern({ cmd: 'changeStatus' }) @MessagePattern({ cmd: 'changeStatus' })
changeStatus(@Payload() body: string) { changeStatus(@Payload() body: string) {

View File

@ -14,8 +14,8 @@ export class UsersService {
@InjectModel(User.name) private readonly userModel: Model<UserDocument>, @InjectModel(User.name) private readonly userModel: Model<UserDocument>,
@Inject('SERVICIO_NOTIFICACIONES') private readonly clientNotificationtApp: ClientProxy, @Inject('SERVICIO_NOTIFICACIONES') private readonly clientNotificationtApp: ClientProxy,
@Inject('SERVICIO_COMUNIDADES') private readonly clientCommunityApp: ClientProxy, @Inject('SERVICIO_COMUNIDADES') private readonly clientCommunityApp: ClientProxy,
) { } ) { }
private publicKey: string; private publicKey: string;
async create(user: UserDocument): Promise<User> { async create(user: UserDocument): Promise<User> {
let passwordEncriptada = Md5.init(user.password); let passwordEncriptada = Md5.init(user.password);
@ -78,14 +78,14 @@ export class UsersService {
}); });
} }
/* async remove(id: string) { /* async remove(id: string) {
return this.userModel.findByIdAndRemove({ _id: id }).exec(); return this.userModel.findByIdAndRemove({ _id: id }).exec();
}*/ }*/
async remove(id: string) { async remove(id: string) {
return this.userModel.findOneAndUpdate({ _id: id }, {status: '-1'}, { return this.userModel.findOneAndUpdate({ _id: id }, { status: '-1' }, {
new: true, new: true,
}); });
} }
//inicio de sesion //inicio de sesion
@ -99,8 +99,12 @@ export class UsersService {
reject(err); reject(err);
} else { } else {
let passwordEncriptada = Md5.init(password); let passwordEncriptada = Md5.init(password);
if (res[0].password == passwordEncriptada) { if (res.length > 0) {
resolve(res[0]); if (res[0].password == passwordEncriptada) {
resolve(res[0]);
} else {
resolve(null);
}
} else { } else {
resolve(null); resolve(null);
} }
@ -180,16 +184,21 @@ export class UsersService {
} }
async deleteAdminSystem(id: string) { async deleteAdminSystem(id: string) {
return this.userModel.findOneAndUpdate({ _id: id }, {status: '-1'}, { return this.userModel.findOneAndUpdate({ _id: id }, { status: '-1' }, {
new: true, new: true,
}); });
} }
deleteAdminCommunity(id: string) { deleteAdminCommunity(id: string) {
return this.userModel.findOneAndUpdate({ _id: id }, {status: '-1'}, { return this.userModel.findOneAndUpdate({ _id: id }, { status: '-1' }, {
new: true, new: true,
}); });
}
async deleteTenant(id: string) {
return this.userModel.findOneAndUpdate({ _id: id }, { status: '-1' }, {
new: true,
});
} }
async validateEmail(email: string) { async validateEmail(email: string) {
@ -223,17 +232,17 @@ export class UsersService {
const houses = response['houses']; const houses = response['houses'];
let num_house = ""; let num_house = "";
await houses.forEach(async house => { await houses.forEach(async house => {
if (tenant_id == house.tenants.tenant_id) { if (tenant_id == house.tenants.tenant_id) {
num_house = house.number_house; num_house = house.number_house;
} }
}) })
return num_house; return num_house;
} }
async changeStatus(id: string, status: string) { async changeStatus(id: string, status: string) {
return this.userModel.findOneAndUpdate({ _id: id }, {status: status}, { return this.userModel.findOneAndUpdate({ _id: id }, { status: status }, {
new: true, new: true,
}); });
} }
} }

View File

@ -33,7 +33,6 @@ 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 RegistroComunicado from './components/RegistroComunicado'; import RegistroComunicado from './components/RegistroComunicado';
import "../node_modules/bootstrap/dist/css/bootstrap.min.css"; import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

View File

@ -15,9 +15,10 @@ import { faIdCardAlt } from '@fortawesome/free-solid-svg-icons'
import { faHashtag } from '@fortawesome/free-solid-svg-icons' import { faHashtag } from '@fortawesome/free-solid-svg-icons'
import { faCircleQuestion } from '@fortawesome/free-solid-svg-icons' import { faCircleQuestion } from '@fortawesome/free-solid-svg-icons'
import { useCookies } from 'react-cookie' import { useCookies } from 'react-cookie'
import classNames from 'classnames';
const Inquilinos = () => { const Inquilinos = () => {
let emptyTenant = { const emptyTenant = {
_id: null, _id: null,
dni: '', dni: '',
name: '', name: '',
@ -40,15 +41,14 @@ const Inquilinos = () => {
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 [community, setCommunity] = useState([])
const [communityId, setCommunityId] = useState(null) const [houseNumber, setHouseNumber] = useState([])
const [housesList, setHousesList] = useState([])
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] = useCookies()
const [cookies, setCookie] = useCookies() const [changeStatusTenantDialog, setChangeStatusTenantDialog] = useState(false)
const [changeStatusTenantDialog, setChangeStatusTenantDialog] =
useState(false)
async function tenantsList() { async function tenantsList() {
await fetch( await fetch(
@ -74,15 +74,21 @@ const Inquilinos = () => {
}) })
} }
async function getCommunites() { async function getCommunity() {
let response = await fetch( let response = await fetch(
'http://localhost:4000/community/allCommunities', `http://localhost:4000/community/findCommunityName/${cookies.community_id}`,
{ method: 'GET' }, { method: 'GET' },
) )
let resList = await response.json() const responseJson = await response.json()
let list = await resList.message const result = await responseJson.message
list = await list.filter((val) => val.status !== -1) setCommunity(await result)
setCommunitiesList(await list) const houses = await result.houses.filter((house) =>
house.state === "desocupada"
)
setHousesList(houses.map((house) => ({
label: house.number_house, value: house.number_house
}))
)
} }
useEffect(() => { useEffect(() => {
@ -90,46 +96,45 @@ const Inquilinos = () => {
}, [tenantsList]) }, [tenantsList])
useEffect(() => { useEffect(() => {
getCommunites() getCommunity()
}, []) }, [])
const cList = communitiesList.map((item) => ({ const saveTenant = () => {
label: item.name, if (tenant.email && tenant.number_house && tenant.dni
value: item._id, && tenant.name && tenant.last_name && tenant.phone) {
})) let _tenants = [...tenants]
let _tenant = { ...tenant }
_tenant.community_id = cookies.community_id;
_tenant.number_house = houseNumber;
_tenant.password = _tenant.email;
console.log(_tenant)
function registrarInquilino() { fetch(`http://localhost:4000/user/createUser`, {
let newTenant = { cache: 'no-cache',
_id: null, method: 'POST',
dni: '', body: JSON.stringify(_tenant),
name: '', headers: {
last_name: '', 'Content-Type': 'application/json',
email: document.getElementById('correo_electronico').value, },
phone: '', })
password: '', .then((response) => {
community_id: document.getElementById('numero_vivienda').value, if (response.status !== 201)
community_name: '', console.log(`Hubo un error en el servicio: ${response.status}`)
number_house: 'Sin número de vivienda', else return response.json()
date_entry: new Date(), })
user_type: '3', .then(() => {
status: '1', _tenants.push(_tenant)
status_text: '', toast.current.show({
} severity: 'success',
summary: 'Éxito',
fetch('http://localhost:3000/api/createUser', { detail: 'Inquilino creado',
method: 'POST', life: 3000,
cache: 'no-cache', })
body: JSON.stringify(newTenant), setTenants(_tenants)
headers: { setTenant(emptyTenant)
'Content-Type': 'application/json', })
}, .catch((error) => console.log(`Ocurrió un error: ${error}`))
}).then((response) => { } else setSubmitted(true)
if (response.ok) {
alert('Inquilino registrado correctamente')
} else {
alert('Error al registrar inquilino')
}
})
} }
const deleteTenant = () => { const deleteTenant = () => {
@ -418,6 +423,19 @@ const Inquilinos = () => {
) )
} }
const onInputChange = (e, name) => {
const value = (e.target && e.target.value) || ''
let _tenant = { ...tenant }
_tenant[`${name}`] = value
setTenant(_tenant)
}
const handleHouses = (e) => {
const getHouseNumber = e.target.value;
setHouseNumber(getHouseNumber);
console.log(getHouseNumber);
}
return ( return (
<div className='grid'> <div className='grid'>
<div className='col-12'> <div className='col-12'>
@ -595,30 +613,96 @@ 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>Registro de un administrador de una comunidad de viviendas</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='correo_electronico'>Correo electrónico</label> <label htmlFor="name">Nombre</label>
<InputText <div className="p-0 col-12 md:col-12">
required <div className="p-inputgroup">
type='email' <span className="p-inputgroup-addon p-button p-icon-input-khaki">
className='form-control' <i className="pi pi-home"></i>
id='correo_electronico' </span>
/> <InputText type="text" id="name" value={tenant.name} onChange={(e) => onInputChange(e, 'name')} required autoFocus className={classNames({ 'p-invalid': submitted && tenant.name === '' })} />
</div>
{submitted && tenant.name === '' && <small className="p-invalid">Nombre es requerido.</small>}
</div>
</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="name">Apellido(s)</label>
<Dropdown <div className="p-0 col-12 md:col-12">
required <div className="p-inputgroup">
id='numero_vivienda' <span className="p-inputgroup-addon p-button p-icon-input-khaki">
value={communityId} <i className="pi pi-home"></i>
options={cList} </span>
onChange={(e) => setCommunityId(e.value)} <InputText type="text" id="last_name" value={tenant.last_name} onChange={(e) => onInputChange(e, 'last_name')} required autoFocus className={classNames({ 'p-invalid': submitted && tenant.last_name === '' })} />
/> </div>
{submitted && tenant.last_name === '' && <small className="p-invalid">Apellidos son requeridos.</small>}
</div>
</div> </div>
<Button label='Registrar' onClick={registrarInquilino} /> <div className="field col-12 md:col-6">
<label htmlFor="name">Correo Electrónico</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 type='email' id="email" value={tenant.email} onChange={(e) => onInputChange(e, 'email')} required autoFocus className={classNames({ 'p-invalid': submitted && tenant.email === '' })} />
</div>
{submitted && tenant.email === '' && <small className="p-invalid">Correo electrónico es requerido.</small>}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="dni">Identificación</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="dni" value={tenant.dni} onChange={(e) => onInputChange(e, 'dni')} required autoFocus className={classNames({ 'p-invalid': submitted && tenant.dni === '' })} />
</div>
{submitted && tenant.email === '' && <small className="p-invalid">Identificación es requerida.</small>}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="phone">Número de teléfono</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-phone"></i>
</span>
<InputText id="phone" value={tenant.phone} onChange={(e) => onInputChange(e, 'phone')} type='tel' required autoFocus className={classNames({ 'p-invalid': submitted && tenant.phone === '' })} />
</div>
{submitted
&& tenant.phone === ''
&& <small className="p-invalid">Número de teléfono es requerido.</small>}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="number_house">Casa a asignar: </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>
<Dropdown
placeholder="--Seleccione la Casa a Asignar--"
id="number_house"
value={houseNumber}
options={housesList}
onChange={handleHouses}
required autoFocus
className={
classNames({ 'p-invalid': submitted && !houseNumber })}
/>
</div>
{submitted
&& !houseNumber
&& <small className="p-invalid">Casa es requerida.</small>}
</div>
</div>
<Button label="Registrar" onClick={saveTenant} />
</div> </div>
</div> </div>
</div> </div>

View File

@ -1,125 +0,0 @@
import { Button } from 'primereact/button'
import { InputText } from 'primereact/inputtext'
import React, { useState } from 'react'
import { useCookies } from 'react-cookie'
const InquilinosCompletar = () => {
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)