editar informacion como admin de vivienda

This commit is contained in:
Mariela 2022-09-01 01:31:20 -06:00
parent 4ee53476e5
commit b0791c2ed5
8 changed files with 518 additions and 51 deletions

View File

@ -330,6 +330,18 @@ export class AppController {
);
}
@Put('user/changePassword/:id')
changePassword(
@Param('id') id: string,
@Body('password') password: string,
) {
return this.appService.changePassword(
id,
password,
);
}
// #==== API Communities
@Post('community/createCommunity')
createCommunity(

View File

@ -396,6 +396,16 @@ export class AppService {
}
changePassword(id: string, password: string) {
const pattern = { cmd: 'changePassword' };
const payload = { id: id, password: password };
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
// ====================== COMMUNITIES ===============================
changeStatusCommunity(pId: string, pStatus: string) {
const pattern = { cmd: 'changeStatus' };

View File

@ -7,20 +7,20 @@ export type UserDocument = User & Document;
@Schema({ collection: 'users'})
export class User {
@Prop({index: true})
dni!: string;
@Prop()
dni: string;
@Prop({required: true})
@Prop()
name: string;
@Prop({required: true})
@Prop()
last_name: string;
@Prop({required: true, unique: true})
@Prop()
email: string;
@Prop({required: true, unique: true})
phone: number;
@Prop()
phone: string;
@Prop()
password: string;

View File

@ -72,7 +72,7 @@ export class UsersController {
@MessagePattern({ cmd: 'updateUser' })
update(@Payload() user: UserDocument) {
return this.userService.update(user._id, user);
return this.userService.update(user['id'], user);
}
@MessagePattern({ cmd: 'updateGuard' })
@ -165,4 +165,13 @@ export class UsersController {
let pstatus = body['status'];
return this.userService.changeStatus(pid, pstatus);
}
@MessagePattern({ cmd: 'changePassword' })
changePassword(@Payload() body: string) {
let pid = body['id'];
let password = body['password'];
return this.userService.changePassword(pid, password);
}
}

View File

@ -117,10 +117,10 @@ export class UsersService {
}
async update(id: string, user: UserDocument) {
console.log(id)
console.log(user)
return this.userModel.findOneAndUpdate({ _id: id }, user, {
return this.userModel.findOneAndUpdate({ _id: id }, {
name: user['name'], last_name: user['last_name'],
dni: user['dni'], email: user['email'], phone: user['phone']
}, {
new: true,
});
}
@ -179,7 +179,6 @@ export class UsersService {
}
});
});
return userReturn;
}
@ -197,19 +196,14 @@ export class UsersService {
return this.userModel.find({ user_type: 2 }).exec();
}
//find inquilinos
async findTenants(): Promise<User[]> {
return this.userModel.find({ user_type: 3 }).exec();
}
//find inquilinos
async findTenantsCommunity(pcommunity_id: string) {
//let tenants = await this.findCommunityTenants(pcommunity_id);
return await this.userModel.find({ community_id: pcommunity_id, user_type: 4 })
}
@ -335,5 +329,14 @@ export class UsersService {
await this.userModel.updateMany({community_id: community_id, user_type:'3' }, {"$set":{"community_id": '', "status": '-1'} });
return this.userModel.updateMany({ community_id: community_id, user_type: '4' }, { "$set": { "community_id": '', "status": '-1' } });
}
async changePassword(id: string, password: string) {
return this.userModel.findOneAndUpdate({ _id: id }, { password: password }, {
new: true,
});
}
}

View File

@ -22,6 +22,7 @@
"chart.js": "3.3.2",
"classnames": "^2.2.6",
"cors": "^2.8.5",
"md5": "^2.3.0",
"primeflex": "3.1.0",
"primeicons": "^5.0.0",
"primereact": "7.2.0",
@ -4677,6 +4678,14 @@
"resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz",
"integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA=="
},
"node_modules/charenc": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz",
"integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==",
"engines": {
"node": "*"
}
},
"node_modules/chart.js": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-3.3.2.tgz",
@ -5384,6 +5393,14 @@
"semver": "bin/semver"
}
},
"node_modules/crypt": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz",
"integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==",
"engines": {
"node": "*"
}
},
"node_modules/crypto-browserify": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz",
@ -10589,6 +10606,16 @@
"node": ">=0.10.0"
}
},
"node_modules/md5": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz",
"integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==",
"dependencies": {
"charenc": "0.0.2",
"crypt": "0.0.2",
"is-buffer": "~1.1.6"
}
},
"node_modules/md5.js": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz",
@ -21618,6 +21645,11 @@
"resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz",
"integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA=="
},
"charenc": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz",
"integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA=="
},
"chart.js": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-3.3.2.tgz",
@ -22179,6 +22211,11 @@
}
}
},
"crypt": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz",
"integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow=="
},
"crypto-browserify": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz",
@ -26217,6 +26254,16 @@
"object-visit": "^1.0.0"
}
},
"md5": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz",
"integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==",
"requires": {
"charenc": "0.0.2",
"crypt": "0.0.2",
"is-buffer": "~1.1.6"
}
},
"md5.js": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz",

View File

@ -22,6 +22,7 @@
"chart.js": "3.3.2",
"classnames": "^2.2.6",
"cors": "^2.8.5",
"md5": "^2.3.0",
"primeflex": "3.1.0",
"primeicons": "^5.0.0",
"primereact": "7.2.0",

View File

@ -8,6 +8,13 @@ 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';
import { Button } from 'primereact/button';
import { Toast } from 'primereact/toast';
import { Dialog } from 'primereact/dialog';
import { Toolbar } from 'primereact/toolbar';
import { InputText } from 'primereact/inputtext';
import classNames from 'classnames';
import md5 from 'md5';
const PerfilAdminComunidad = () => {
@ -42,6 +49,13 @@ const PerfilAdminComunidad = () => {
houses: [],
};
let emptyNewPassword = {
_id: null,
passwordOld: '',
passwordNew: '',
passwordConfirm: ''
}
const [admin, setAdmin] = useState(emptyAdminCommunity);
const [community, setCommunity] = useState(emptyCommunity);
const [cookies, setCookie] = useCookies();
@ -52,6 +66,13 @@ const PerfilAdminComunidad = () => {
const [provincesList, setProvincesList] = useState([]);
const [cantonsList, setCantonsList] = useState([]);
const [districtsList, setDistrictsList] = useState([]);
const [editAdminDialog, setEditAdminDialog] = useState(false);
const [editPasswordDialog, setEditPasswordDialog] = useState(false);
const [submitted, setSubmitted] = useState(false);
const toast = useRef(null);
const [newPassword, setNewPassword] = useState(emptyNewPassword);
async function getProvinces() {
const response = await fetch('assets/demo/data/provincias.json', {
@ -68,7 +89,6 @@ const PerfilAdminComunidad = () => {
return await response.json();
}
async function getDistricts() {
const response = await fetch('assets/demo/data/distritos.json', {
method: 'GET',
@ -76,10 +96,6 @@ const PerfilAdminComunidad = () => {
return await response.json();
}
async function getAdmin() {
await fetch('http://localhost:4000/user/findUserById/' + cookies.id, { method: 'GET' })
.then((response) => response.json())
@ -100,6 +116,7 @@ const PerfilAdminComunidad = () => {
getAdmin();
}, [])
async function getCommunity() {
let pList = await getProvinces();
let cList = await getCantons();
@ -135,7 +152,106 @@ const PerfilAdminComunidad = () => {
tenantsList(cookies.community_id);
}, [])
const saveAdmin = () => {
let _admin = { ...admin };
_admin.community_id = cookies.community_id;
if (_admin.name && _admin.dni &&
_admin.last_name && _admin.email &&
_admin.phone) {
console.log(`Actualizando admnistrador de comunidad: ${_admin}`)
_admin.community_id = cookies.community_id;
console.log(`Actualizando admnistrador de comunidad: ${_admin}`)
fetch(`http://localhost:4000/user/updateAdminCommunity/${_admin._id}`, {
cache: 'no-cache',
method: 'PUT',
body: JSON.stringify(_admin),
headers: {
'Content-Type': 'application/json',
},
}).then((response) => {
if (response.status !== 200)
console.log(`Hubo un error en el servicio: ${response.status}`)
else return response.json()
}).then((response) => {
toast.current.show({
severity: 'success',
summary: 'Éxito',
detail: 'Administrador de comunidad actualizado',
life: 3000,
})
setAdmin(response.message);
setEditAdminDialog(false);
})
} else {
setSubmitted(true);
}
}
const savePassword = () => {
let _admin = { ...admin };
let _newPassword = { ...newPassword };
if (_newPassword.passwordOld && _newPassword.passwordNew &&
_newPassword.passwordNew === _newPassword.passwordConfirm) {
_admin.password = md5(_newPassword.passwordNew);
console.log(`Actualizando admnistrador de comunidad: ${_admin}`)
fetch(`http://localhost:4000/user/changePassword/${_admin._id}`, {
cache: 'no-cache',
method: 'PUT',
body: JSON.stringify(_admin),
headers: {
'Content-Type': 'application/json',
},
}).then((response) => {
if (response.status !== 200)
console.log(`Hubo un error en el servicio: ${response.status}`)
else return response.json()
}).then((response) => {
toast.current.show({
severity: 'success',
summary: 'Éxito',
detail: 'Administrador de comunidad actualizado',
life: 3000,
})
setAdmin(_admin);
setEditPasswordDialog(false);
})
} else {
setSubmitted(true);
}
}
const findRepeated = async (name, value) => {
let _administrators;
await fetch('http://localhost:4000/user/findAdminComunidad/', { method: 'GET' })
.then((response) => response.json())
.then((data) => data.message)
.then(data => {
data = data.filter(
(val) => val.status != -1,
);
_administrators = data;
});
let value_filtered = await _administrators.filter(item => item[`${name}`] === value);
return value_filtered.length;
}
function findNameTenant(tenant_id) {
let name = '';
@ -148,6 +264,105 @@ const PerfilAdminComunidad = () => {
return name;
}
const onInputChange = (e, name) => {
const val = (e.target && e.target.value) || '';
let _admin = { ...admin };
_admin[`${name}`] = val;
setAdmin(_admin);
}
const onInputChangePassword = (e, name) => {
const val = (e.target && e.target.value) || '';
let _pass = { ...newPassword };
_pass[`${name}`] = val;
setNewPassword(_pass);
}
const editAdmin = (admin) => {
setAdmin(admin);
setEditAdminDialog(true);
}
const editPassword = () => {
setNewPassword(emptyNewPassword);
setEditPasswordDialog(true);
}
const hideEditAdminDialog = () => {
setSubmitted(false);
setEditAdminDialog(false);
}
const hideEditPasswordDialog = () => {
setSubmitted(false);
setEditPasswordDialog(false);
}
const actionsAdminCommunity = (rowData) => {
return (
<>
<div className='container my-2'>
<div className='row justify-content-end'>
<div className='col-3'>
<Button
icon="pi pi-pencil"
className="p-button-rounded p-button-primary mt-2 mx-2"
onClick={() => editAdmin(rowData)}
label="Editar Mis Datos"
/>
</div>
<div className='col-3'>
<Button
icon="pi pi-pencil"
className="p-button-rounded p-button-primary mt-2 mx-2"
onClick={() => editPassword(rowData)}
label="Modificar Contraseña"
/>
</div>
</div>
</div>
</>
)
}
const editAdminDialogFooter = (
<>
<Button
label="Guardar Cambios"
icon="pi pi-check"
className="p-button-primary"
onClick={saveAdmin}
/>
<Button
label="Cancelar"
icon="pi pi-check"
className="p-button-text"
onClick={hideEditAdminDialog}
/>
</>
);
const editPasswordDialogFooter = (
<>
<Button
label="Guardar Cambios"
icon="pi pi-check"
className="p-button-primary"
onClick={savePassword}
/>
<Button
label="Cancelar"
icon="pi pi-check"
className="p-button-text"
onClick={hideEditPasswordDialog}
/>
</>
);
const headerNumberHouses = (
<>
<p>
@ -183,11 +398,180 @@ const PerfilAdminComunidad = () => {
)
}
return (
<>
<div className="grid">
<Toast ref={toast} />
{actionsAdminCommunity(admin)}
<Dialog
visible={editAdminDialog}
style={{ width: '650px' }}
header="Actualizar mi información"
modal
className="p-fluid"
footer={editAdminDialogFooter}
onHide={hideEditAdminDialog}>
<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-user"></i>
</span>
<InputText id="name" value={admin.name} onChange={(e) => onInputChange(e, 'name')} required autoFocus className={classNames({ 'p-invalid': submitted && admin.name === '' })} />
</div>
{submitted && admin.name === '' && <small className="p-invalid">Nombre es requirido.</small>}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="name">Apellido(s)</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-user"></i>
</span>
<InputText id="last_name" value={admin.last_name} onChange={(e) => onInputChange(e, 'last_name')} required autoFocus className={classNames({ 'p-invalid': submitted && admin.last_name === '' })} />
</div>
{submitted && admin.last_name === '' && <small className="p-invalid">Apellidos es requirido.</small>}
</div>
</div>
<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-at"></i>
</span>
<InputText id="email" value={admin.email}
onChange={(e) => onInputChange(e, 'email')} required autoFocus
className={classNames({
'p-invalid': submitted &&
(admin.email === '' || findRepeated('email', admin.email) > 0)
})} />
</div>
{submitted && admin.email === '' && <small className="p-invalid">Correo electrónico
es requirido.</small>}
{submitted && findRepeated('email', admin.email) > 0 &&
<small className="p-invalid">Correo electrónico se encuentra repetido.</small>
}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="name">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-id-card"></i>
</span>
<InputText id="dni" value={admin.dni}
onChange={(e) => onInputChange(e, 'dni')} required autoFocus
className={classNames({
'p-invalid': submitted
&& (admin.dni === '' || findRepeated('dni', admin.dni) > 0)
})} />
</div>
{submitted && admin.dni === '' && <small className="p-invalid">Identificación es requirida.</small>}
{submitted && findRepeated('dni', admin.dni) > 0 &&
<small className="p-invalid">Identificación se encuentra repetida.</small>
}
</div>
</div>
<div className="field col-12 md:col-6">
<label htmlFor="name">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={admin.phone} onChange={(e) => onInputChange(e, 'phone')} required autoFocus className={classNames({ 'p-invalid': submitted && admin.phone === '' })} />
</div>
{submitted && admin.phone === '' && <small className="p-invalid">Número de teléfono es requirida.</small>}
</div>
</div>
</div>
</Dialog>
<Dialog
visible={editPasswordDialog}
style={{ width: '650px' }}
header="Actualizar contraseña"
modal
className="p-fluid"
footer={editPasswordDialogFooter}
onHide={hideEditPasswordDialog}>
<div className="p-fluid formgrid grid">
<div className="field col-12 md:col-12">
<label htmlFor="name">Contraseña Actual</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-lock"></i>
</span>
<InputText id="passwordOld" value={newPassword.passwordOld}
onChange={(e) => onInputChangePassword(e, 'passwordOld')}
required autoFocus
className={classNames({
'p-invalid': submitted
&& newPassword.passwordOld === ''
&& admin.password !== md5(newPassword.passwordOld)
})} />
</div>
{submitted && newPassword.passwordOld === ''
&& <small className="p-invalid">Contraseña Actual es requirida.</small>}
{submitted && admin.password != md5(newPassword.passwordOld)
&& <small className="p-invalid">Contraseña Actual no coincide con la actual.</small>}
</div>
</div>
<div className="field col-12 md:col-12">
<label htmlFor="name">Contraseña Nueva</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-lock"></i>
</span>
<InputText id="passwordNew" value={newPassword.passwordNew}
onChange={(e) => onInputChangePassword(e, 'passwordNew')}
required autoFocus
className={classNames({
'p-invalid': submitted
&& newPassword.passwordNew === ''
&& admin.password === md5(newPassword.passwordNew)
})} />
</div>
{submitted && newPassword.passwordNew === ''
&& <small className="p-invalid">Contraseña Nueva es requirida.</small>}
</div>
</div>
<div className="field col-12 md:col-12">
<label htmlFor="name">Contraseña Nueva</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-lock"></i>
</span>
<InputText id="passwordConfirm"
value={newPassword.passwordConfirm}
onChange={(e) => onInputChangePassword(e, 'passwordConfirm')}
required autoFocus
className={classNames({ 'p-invalid': submitted && newPassword.passwordConfirm !== newPassword.passwordNew })} />
</div>
{submitted
&& newPassword.passwordConfirm !== newPassword.passwordNew
&& newPassword.passwordConfirm === ''
&& <small className="p-invalid">No coincide con la nueva contraseña.</small>}
</div>
</div>
</div>
</Dialog>
</div>
<div className="grid justify-content-center">
<div className="col-6" >
<div className="col-5" >
<div className="card">
<div className='container text-center'>
<div className='row my-4'>
@ -239,8 +623,9 @@ const PerfilAdminComunidad = () => {
</div>
</div>
</div>
<div className='col-6'>
<div className='col-7'>
{community && (
<div className="card">
<div className='container text-center'>
@ -259,7 +644,7 @@ const PerfilAdminComunidad = () => {
</div>
<div className="col-4 md:col-4">
<i className="pi pi-phone icon-khaki"></i>
<p><strong>Teléfono Administrativo</strong></p>
<p><strong>Teléfono</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">
@ -272,8 +657,8 @@ const PerfilAdminComunidad = () => {
<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">
<div>
<div className="p-inputgroup justify-content-evenly">
<p>{community.province}, {community.canton}, {community.district}</p>
</div>