Merge pull request #186 from DeimosPr4/US-05-ModificarAdministradordeSistema

modificar admin del administrador
This commit is contained in:
Eduardo Quiros 2022-08-23 05:07:44 +00:00 committed by GitHub
commit c5173895fd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 472 additions and 70 deletions

View File

@ -241,6 +241,20 @@ export class AppController {
return this.appService.changeStatusUser(pId, pStatus); return this.appService.changeStatusUser(pId, pStatus);
} }
@Post('user/updateAdminSystem')
updateAdminSystem(
//Nombre, Apellidos, Correo electrónico, Cédula, Teléfono
@Body('_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,
) {
return this.appService.updateAdminSystem(_id, dni, name, last_name, email, phone);
}
// #==== API Communities // #==== API Communities
@Post('community/createCommunity') @Post('community/createCommunity')
createCommunity( createCommunity(

View File

@ -287,6 +287,19 @@ export class AppService {
.pipe(map((message: string) => ({ message }))); .pipe(map((message: string) => ({ message })));
} }
updateAdminSystem(_id: string, dni: string, name: string,
last_name: string, email: string, phone: number
) {
const pattern = { cmd: 'updateAdminSystem' };
const payload = {
_id: _id, dni: dni, name: name, last_name: last_name,
email: email, phone: phone
};
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
//GET parameter from API //GET parameter from API
findCommunityAdmin(community_id: string) { findCommunityAdmin(community_id: string) {
const pattern = { cmd: 'findCommunityAdmin' }; const pattern = { cmd: 'findCommunityAdmin' };

View File

@ -72,7 +72,7 @@ export class UsersController {
@MessagePattern({ cmd: 'updateUser' }) @MessagePattern({ cmd: 'updateUser' })
update(@Payload() user: UserDocument) { update(@Payload() user: UserDocument) {
return this.userService.update(user.id, user); return this.userService.update(user._id, user);
} }
@MessagePattern({ cmd: 'updateGuard' }) @MessagePattern({ cmd: 'updateGuard' })
@ -85,7 +85,10 @@ export class UsersController {
let dni = id['dni']; let dni = id['dni'];
return this.userService.remove(dni); return this.userService.remove(dni);
} }
@MessagePattern({ cmd: 'updateAdminSystem' })
updateAdminSystem(@Payload() user: UserDocument) {
return this.userService.updateAdminSystem(user._id, user);
}
//inicio de sesion //inicio de sesion
@MessagePattern({ cmd: 'loginUser' }) @MessagePattern({ cmd: 'loginUser' })
findLogin(@Payload() body: string) { findLogin(@Payload() body: string) {

View File

@ -103,6 +103,15 @@ export class UsersService {
}); });
} }
async updateAdminSystem(id: string, user: UserDocument) {
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,
});
}
/* async remove(id: string) { /* async remove(id: string) {
return this.userModel.findByIdAndRemove({ _id: id }).exec(); return this.userModel.findByIdAndRemove({ _id: id }).exec();
}*/ }*/

View File

@ -12,8 +12,25 @@ 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 { faCircleQuestion } from '@fortawesome/free-solid-svg-icons'; import { faCircleQuestion } from '@fortawesome/free-solid-svg-icons';
import classNames from 'classnames';
const AdministradoresSistema = () => { const AdministradoresSistema = () => {
let emptySysAdmin = {
_id: null,
dni: '',
name: '',
last_name: '',
email: '',
phone: '',
password: '',
user_type: '1',
status: '1',
status_text: '',
};
const [administrators, setAdministrators] = useState([]); const [administrators, setAdministrators] = useState([]);
const [urlFetch, setUrlFetch] = useState( const [urlFetch, setUrlFetch] = useState(
'http://localhost:4000/user/findAdminSistema/', 'http://localhost:4000/user/findAdminSistema/',
@ -30,19 +47,12 @@ const AdministradoresSistema = () => {
const [changeStatusAdminSystemDialog, setChangeStatusAdminSystemDialog] = useState(false); const [changeStatusAdminSystemDialog, setChangeStatusAdminSystemDialog] = useState(false);
const [changeStatusAdminsSystemDialog, setChangeStatusAdminsSystemDialog] = const [changeStatusAdminsSystemDialog, setChangeStatusAdminsSystemDialog] =
useState(false); useState(false);
const [adminDialog, setAdminDialog] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [editAdminDialog, setEditAdminDialog] = useState(false);
const [saveButtonTitle, setSaveButtonTitle] = useState("Registrar")
let emptySysAdmin = {
_id: null,
dni: '',
name: '',
last_name: '',
email: '',
phone: '',
password: '',
user_type: '1',
status: '1',
status_text: '',
};
async function fetchP() { async function fetchP() {
let nombres = await fetch(urlFetch, { method: 'GET' }); let nombres = await fetch(urlFetch, { method: 'GET' });
@ -55,7 +65,7 @@ const AdministradoresSistema = () => {
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';
} }
}) })
setAdministrators(await data); setAdministrators(await data);
} }
@ -64,46 +74,123 @@ const AdministradoresSistema = () => {
fetchP(); fetchP();
}, []) }, [])
function registrarAdmin() { const findIndexById = (id) => {
var data = { let index = -1;
dni: document.getElementById('identificacion').value, for (let i = 0; i < administrators.length; i++) {
name: document.getElementById('nombre').value, if (administrators[i]._id === id) {
last_name: document.getElementById('apellidos').value, index = i;
email: document.getElementById('correo_electronico').value, break;
phone: document.getElementById('telefono').value,
password: document.getElementById('correo_electronico').value,
user_type: "1", //1 es admin
status: "1"
};
setSysAdmin(data)
fetch('http://localhost:4000/user/createAdminSystem/', {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
} }
}) }
.then( return index;
function (response) {
if (response.status != 201) }
console.log('Ocurrió un error con el servicio: ' + response.status);
else const findRepeated = (name, value) => {
return response.json(); let _administrators = [...administrators];
let value_filtered = _administrators.filter(item => item[`${name}`] === value);
return value_filtered.length
}
function guardarAdmin() {
let _administrators = [...administrators];
let _admin = { ...sysadmin };
if (_admin.name && _admin.dni && _admin.last_name && _admin.email &&
_admin.phone) {
if (findRepeated('email', _admin.email) || findRepeated('dni', _admin.dni)) {
setSubmitted(true);
} else {
if (_admin._id) {
fetch('http://localhost:4000/user/updateAdminSystem/', {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(_admin),
headers: {
'Content-Type': 'application/json'
}
})
.then(
function (response) {
if (response.status != 201)
console.log('Ocurrió un error con el servicio: ' + response.status);
else
return response.json();
}
)
.then(
function (response) {
const index = findIndexById(sysadmin._id);
_administrators[index] = _admin;
toast.current.show({
severity: 'success',
summary: 'Exito',
detail: 'Administrador Actualizado',
life: 3000,
});
setAdministrators(_administrators)
setEditAdminDialog(false);
setSysAdmin(emptySysAdmin);
}
)
.catch(
err => console.log('Ocurrió un error con el fetch', err)
);
} else {
fetch('http://localhost:4000/user/createAdminSystem/', {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(_admin),
headers: {
'Content-Type': 'application/json'
}
})
.then(
function (response) {
if (response.status != 201)
console.log('Ocurrió un error con el servicio: ' + response.status);
else
return response.json();
}
)
.then(
function (response) {
_administrators.push(_admin);
setAdministrators(_administrators)
}
)
.catch(
err => console.log('Ocurrió un error con el fetch', err)
);
} }
) }
.then(
function (response) {
let _administrators = [...administrators];
let _admin = { ...sysadmin };
_administrators.push(_admin);
setAdministrators(_administrators)
} } else {
) setSubmitted(true);
.catch(
err => console.log('Ocurrió un error con el fetch', err) }
);
} }
const cambiarStatusUser = () => { const cambiarStatusUser = () => {
@ -177,6 +264,31 @@ const AdministradoresSistema = () => {
setChangeStatusAdminSystemDialog(true); setChangeStatusAdminSystemDialog(true);
}; };
const hideAdminDialog = () => {
setSubmitted(false);
setAdminDialog(false);
setSysAdmin(emptySysAdmin);
};
const infoAdmin = (sysadmin) => {
setSysAdmin({ ...sysadmin });
setAdminDialog(true);
};
const cancelEdit = () => {
setSaveButtonTitle('Registrar');
setSubmitted(false);
setSysAdmin(emptySysAdmin);
}
const editAdmin = (sysadmin) => {
setSysAdmin({ ...sysadmin });
setSaveButtonTitle('Actualizar');
};
const deleteSysAdmin = () => { const deleteSysAdmin = () => {
fetch('http://localhost:4000/user/deleteAdminSystem/' + sysadmin._id, { fetch('http://localhost:4000/user/deleteAdminSystem/' + sysadmin._id, {
cache: 'no-cache', cache: 'no-cache',
@ -259,6 +371,21 @@ const AdministradoresSistema = () => {
return ( return (
<div className="actions"> <div className="actions">
<Button
icon="pi pi-exclamation-circle"
className="p-button-rounded p-button-info mt-2 mx-2"
onClick={() => infoAdmin(rowData)}
title="Ver información del Administrador"
/>
<Button
icon="pi pi-pencil"
className="p-button-rounded p-button-success mt-2 mx-2"
onClick={() => editAdmin(rowData)}
title="Editar Administrador"
/>
<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"
@ -370,6 +497,36 @@ const AdministradoresSistema = () => {
</> </>
); );
const editAdminDialogFooter = (
<>
<Button
label="No"
icon="pi pi-times"
className="p-button-text"
onClick={hideChangeStatusAdminDialog}
/>
<Button
label="Yes"
icon="pi pi-check"
className="p-button-text"
onClick={editAdmin}
/>
</>
);
const adminDialogFooter = (
<>
<Button
label="Cerrar"
icon="pi pi-times"
className="p-button-text"
onClick={hideAdminDialog}
/>
</>
);
const headerName = ( const headerName = (
<> <>
<p> <p>
@ -418,7 +575,7 @@ const AdministradoresSistema = () => {
</p> </p>
</> </>
); );
const headerStatus = ( const headerStatus = (
<> <>
<p> {' '} <p> {' '}
@ -440,6 +597,23 @@ const AdministradoresSistema = () => {
); );
}; };
const onInputChange = (e, name) => {
const val = (e.target && e.target.value) || '';
let _admin = { ...sysadmin };
_admin[`${name}`] = val;
setSysAdmin(_admin);
};
const onInputNumberChange = (e, name) => {
const val = e.value || 0;
let _admin = { ...sysadmin };
_admin[`${name}`] = val;
setSysAdmin(_admin);
};
return ( return (
<div className="grid"> <div className="grid">
<div className="col-12"> <div className="col-12">
@ -541,6 +715,84 @@ const AdministradoresSistema = () => {
body={actionsAdmin} body={actionsAdmin}
></Column> ></Column>
</DataTable> </DataTable>
<Dialog
visible={adminDialog}
style={{ width: '650px' }}
header="Información del Admin del Sistema"
modal
className="p-fluid"
footer={adminDialogFooter}
onHide={hideAdminDialog}
>
{sysadmin && (
<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-user 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>{sysadmin.name}</p>
</div>
</div>
</div>
<div className=" col-6 md:col-6">
<i className="pi pi-user icon-khaki"></i>
<p><strong>Apellido(s)</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>{sysadmin.last_name}</p>
</div>
</div>
</div>
</div>
<div className='row my-5'>
<div className=" col-12 md:col-12">
<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 align-items-center justify-content-evenly">
<p>{sysadmin.dni}</p>
</div>
</div>
</div>
</div>
<div className='row my-5'>
<div className=" col-12 md:col-12">
<h3>Contacto</h3>
</div>
<div className=" col-6 col-md-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">
<div className="p-inputgroup align-items-center justify-content-evenly">
<p>{sysadmin.email}</p>
</div>
</div>
</div>
<div className=" col-6 md:col-6">
<i className="pi pi-phone icon-khaki"></i>
<p><strong>Teléfono</strong></p>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup align-items-center justify-content-evenly">
<p>{sysadmin.phone}</p>
</div>
</div>
</div>
</div>
</div>
)}
</Dialog>
<Dialog <Dialog
visible={deleteAdminSystemDialog} visible={deleteAdminSystemDialog}
style={{ width: '450px' }} style={{ width: '450px' }}
@ -602,35 +854,146 @@ const AdministradoresSistema = () => {
)} )}
</div> </div>
</Dialog> </Dialog>
</div> </div>
</div> </div>
<div className="col-12"> <div className="col-12">
<div className="card"> <div className="card">
<h5>Registro de un administrador del sistema</h5> <h5>Mantenimiento Administrador del Sistema</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-6 md:col-6">
<label htmlFor="nombre">Nombre</label> <label htmlFor="name">Nombre</label>
<InputText id="nombre" type="text" />
<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={sysadmin.name}
onChange={(e) => onInputChange(e, 'name')}
required
autoFocus
className={classNames({
'p-invalid': submitted && sysadmin.name === '',
})}
/>
</div>
{submitted && sysadmin.name === '' &&
<small className="p-invalid">Nombre es requirido.</small>}
</div>
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-6 md:col-6">
<label htmlFor="apellidos">Apellido(s)</label> <label htmlFor="last_name">Apellido(s)</label>
<InputText id="apellidos" type="text" /> <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={sysadmin.last_name}
onChange={(e) => onInputChange(e, 'last_name')}
required
autoFocus
className={classNames({
'p-invalid': submitted && sysadmin.last_name === '',
})}
/>
</div>
{submitted && sysadmin.last_name === '' && (
<small className="p-invalid">Apellido(s) es requerido.</small>
)}
</div>
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-6 md:col-6">
<label htmlFor="correo_electronico">Correo electrónico</label> <label htmlFor="correo_electronico">Correo electrónico</label>
<InputText id="correo_electronico" type="email" /> <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 type="email" id="correo_electronico" value={sysadmin.email}
onChange={(e) => onInputChange(e, 'email')}
required
autoFocus
className={classNames({
'p-invalid': submitted && (sysadmin.email === '' || findRepeated('email', sysadmin.email) > 0),
})}
/>
</div>
{submitted && sysadmin.email === '' && (
<small className="p-invalid">Correo electrónico es requerido.</small>
)}
{submitted && findRepeated('email', sysadmin.email) > 0 &&
<small className="p-invalid">Correo electrónico se encuentra repetido.</small>
}
</div>
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-6 md:col-6">
<label htmlFor="identificacion">Identificación</label> <label htmlFor="dni">Identificación</label>
<InputText id="identificacion" type="text" /> <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 type="text" id="dni" value={sysadmin.dni}
onChange={(e) => onInputChange(e, 'dni')}
required
autoFocus
className={classNames({
'p-invalid': submitted && (sysadmin.dni === '' || findRepeated('dni', sysadmin.dni) > 0),
})}
/>
</div>
{submitted && sysadmin.dni === '' && (
<small className="p-invalid">Identificación es requerida.</small>
)}
{submitted && findRepeated('dni', sysadmin.dni) > 0 &&
<small className="p-invalid">Identificación se encuentra repetida.</small>
}
</div>
</div> </div>
<div className="field col-12"> <div className="field col-12">
<label htmlFor="telefono">Teléfono</label> <label htmlFor="phone">Teléfono</label>
<InputText type="tel" id="telefono" pattern="[0-9]{8}" /> <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 type="tel" id="phone" pattern="[0-9]{8}"
value={sysadmin.phone}
onChange={(e) => onInputChange(e, 'phone')}
required
autoFocus
className={classNames({
'p-invalid': submitted && sysadmin.phone === '',
})}
/>
</div>
{submitted && sysadmin.phone === '' && (
<small className="p-invalid">Teléfono es requerido.</small>
)}
</div>
</div> </div>
<Button label="Registrar" onClick={registrarAdmin}></Button> <div style={{
display: "flex",
justifyContent: "center",
gap: "10px",
width: "100%"
}}>
<Button
label={`${saveButtonTitle}`}
onClick={guardarAdmin}
/>
{saveButtonTitle === 'Actualizar' && (
<Button
label="Cancelar"
onClick={cancelEdit}
className="p-button-danger" />)}
</div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
); );

View File

@ -926,7 +926,7 @@ const Inquilinos = () => {
/> />
{saveButtonTitle === 'Actualizar' && ( {saveButtonTitle === 'Actualizar' && (
<Button <Button
label="Cancel" label="Cancelar"
onClick={cancelEdit} onClick={cancelEdit}
className="p-button-danger" />)} className="p-button-danger" />)}
</div> </div>