Merge pull request #121 from DeimosPr4/UH-eliminarAdminSistema

UH-eliminar administrador del sistema
This commit is contained in:
Eduardo Quiros 2022-07-22 02:41:52 -06:00 committed by GitHub
commit 4f92903768
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 245 additions and 46 deletions

View File

@ -1,4 +1,4 @@
import { Controller, Get, Post, Body, Param } from '@nestjs/common'; import { Controller, Get, Post, Body, Param, Delete } from '@nestjs/common';
import { AppService } from "./app.service"; import { AppService } from "./app.service";
@Controller() @Controller()
export class AppController { export class AppController {
@ -92,6 +92,13 @@ export class AppController {
} }
@Delete('user/deleteAdminSystem/:id')
deleteAdminSystem(
@Param('id') id: string,
) {
return this.appService.deleteAdminSystem(id);
}
// #==== API Communities // #==== API Communities
@Post('community/createCommunity') @Post('community/createCommunity')
createCommunity( createCommunity(
@ -342,6 +349,4 @@ export class AppController {
return this.appService.html(email, name); return this.appService.html(email, name);
} }
} }

View File

@ -116,6 +116,17 @@ export class AppService {
); );
} }
deleteAdminSystem(id: string) {
const pattern = { cmd: 'deleteAdminSystem' };
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

@ -84,6 +84,12 @@ export class UsersController {
return this.userService.findCommunityUser(user["community_id"], user["user_type"]); return this.userService.findCommunityUser(user["community_id"], user["user_type"]);
} }
@MessagePattern({ cmd: 'deleteAdminSystem' })
deleteAdminSystem(@Payload() user: any) {
console.log("entró")
return this.userService.deleteAdminSystem(user["id"]);
}
} }

View File

@ -82,12 +82,12 @@ export class UsersService {
async findGuardsCommunity(pcommunity_id: string): Promise<User[]> { async findGuardsCommunity(pcommunity_id: string): Promise<User[]> {
return this.userModel.find({ user_type: 4 }).exec(); return this.userModel.find({ user_type: 4 }).exec();
} }
//find admin de comunidad //find admin de comunidad
async allUsersAdminComunidad(): Promise<User[]> { async allUsersAdminComunidad(): Promise<User[]> {
return this.userModel.find({ user_type: 2 }).exec(); return this.userModel.find({ user_type: 2 }).exec();
} }
async testSendMail(user: UserDocument) { async testSendMail(user: UserDocument) {
let passwordEncriptada = Md5.init(user.password); let passwordEncriptada = Md5.init(user.password);
user.password = passwordEncriptada; user.password = passwordEncriptada;
@ -105,11 +105,12 @@ export class UsersService {
); );
} }
async findCommunityUser(community_id: string, user_type: number): Promise<User> { async findCommunityUser(community_id: string, user_type: number): Promise<User> {
return this.userModel.findOne({ community_id: community_id, user_type: user_type }).exec(); return this.userModel.findOne({ community_id: community_id, user_type: user_type }).exec();
} }
async deleteAdminSystem(id: string) {
return this.userModel.deleteOne({_id: id}).exec();
}
} }

View File

@ -1,22 +1,46 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState, useRef } from 'react';
import { InputText } from 'primereact/inputtext'; import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button'; import { Button } from 'primereact/button';
import { DataTable } from 'primereact/datatable'; import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column'; import { Column } from 'primereact/column';
import { Toast } from 'primereact/toast';
import { Dialog } from 'primereact/dialog';
import { Toolbar } from 'primereact/toolbar';
const AdministradoresSistema = () => { const AdministradoresSistema = () => {
const [pokemones,setPokemones]=useState([]); const [administrators, setAdministrators] = useState([]);
const [urlFetch,setUrlFetch]=useState('http://localhost:4000/user/findAdminSistema/'); const [urlFetch, setUrlFetch] = useState('http://localhost:4000/user/findAdminSistema/');
async function fetchP(){ const [sysadmin, setSysAdmin] = useState(emptySysAdmin);
let nombres=await fetch(urlFetch, {method:'GET'}); const [selectedAdministrators, setSelectedAdministrators] = useState(null);
let pokemonesRes= await nombres.json(); const [globalFilter, setGlobalFilter] = useState(null);
setPokemones(pokemonesRes.message); const [deleteAdminSystemDialog, setDeleteAdminSystemDialog] = useState(false);
console.log(pokemones); const [deleteAdminsSystemDialog, setDeleteAdminsSystemDialog] = useState(false);
} const toast = useRef(null);
useEffect(()=>{ const dt = useRef(null);
fetchP();
},[])
let emptySysAdmin = {
_id: null,
dni: '',
name: '',
last_name: '',
email: '',
phone: '',
password: '',
user_type: '1',
status: ''
};
async function fetchP() {
let nombres = await fetch(urlFetch, { method: 'GET' });
let adminRes = await nombres.json();
setAdministrators(adminRes.message);
console.log(administrators);
}
useEffect(() => {
fetchP();
}, [])
function registrarAdmin() { function registrarAdmin() {
var data = { var data = {
@ -29,9 +53,9 @@ const AdministradoresSistema = () => {
user_type: "1", //1 es admin user_type: "1", //1 es admin
status: "1" status: "1"
}; };
// console.log(data); // console.log(data);
fetch('http://localhost:4000/user/createAdminSystem/', { fetch('http://localhost:4000/user/createAdminSystem/', {
cache: 'no-cache', cache: 'no-cache',
method: 'POST', method: 'POST',
body: JSON.stringify(data), body: JSON.stringify(data),
@ -39,36 +63,185 @@ const AdministradoresSistema = () => {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}) })
.then( .then(
function (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(
function (response) {
let _administrators = [...administrators];
let _admin = { ...response.message };;
_administrators.push(_admin);
setAdministrators(_administrators)
}
)
.catch(
err => console.log('Ocurrió un error con el fetch', err)
);
}
const hideDeleteAdminSystemDialog = () => {
setDeleteAdminSystemDialog(false);
}
const hideDeleteAdminsSystemsDialog = () => {
setDeleteAdminsSystemDialog(false);
}
const confirmDeleteAdminSystem = (sysAdmin) => {
setSysAdmin(sysAdmin);
setDeleteAdminSystemDialog(true);
}
const confirmDeleteSelected = () => {
setDeleteAdminsSystemDialog(true);
}
const deleteSysAdmin = () => {
fetch('http://localhost:4000/user/deleteAdminSystem/' + sysadmin._id, {
cache: 'no-cache',
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
} }
) })
.then( .then(
function (response) { function (response) {
fetchP(); if (response.status != 201)
} console.log('Ocurrió un error con el servicio: ' + response.status);
) else
.catch( return response.json();
err => console.log('Ocurrió un error con el fetch', err) }
)
.then(
function (response) {
let _sysadmin = administrators.filter(val => val._id !== sysadmin._id);
setAdministrators(_sysadmin);
setDeleteAdminSystemDialog(false);
setSysAdmin(emptySysAdmin);
toast.current.show({ severity: 'success', summary: 'Exito', detail: 'Administrador del Sistema Eliminado', life: 3000 });
}
)
.catch(
err => {
console.log('Ocurrió un error con el fetch', err)
toast.current.show({ severity: 'danger', summary: 'Error', detail: 'Administrador del Sistema no se pudo eliminar', life: 3000 });
}
);
}
const deleteSelectedAdminsSystem = () => {
let _administrators = administrators.filter(val => !selectedAdministrators.includes(val));
selectedAdministrators.map((item) => {
fetch('http://localhost:4000/user/deleteAdminSystem/' + item._id, {
cache: 'no-cache',
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
})
setAdministrators(_administrators);
setDeleteAdminsSystemDialog(false);
setSelectedAdministrators(null);
toast.current.show({ severity: 'success', summary: 'Successful', detail: 'Products Deleted', life: 3000 });
}
const actionsAdmin = (rowData) => {
return (
<div className="actions">
<Button icon="pi pi-trash" className="p-button-rounded p-button-danger mt-2" onClick={() => confirmDeleteAdminSystem(rowData)} />
</div>
); );
} }
const leftToolbarTemplate = () => {
return (
<React.Fragment>
<div className="my-2">
<Button label="Eliminar" icon="pi pi-trash" className="p-button-danger" onClick={confirmDeleteSelected} disabled={!selectedAdministrators || !selectedAdministrators.length} />
</div>
</React.Fragment>
)
}
const rightToolbarTemplate = () => {
return (
<React.Fragment>
<Button label="Exportar" icon="pi pi-upload" className="p-button-help" />
</React.Fragment>
)
}
const header = (
<div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
<h5 className="m-0">Administradores del sistema</h5>
<span className="block mt-2 md:mt-0 p-input-icon-left">
<i className="pi pi-search" />
<InputText type="search" onInput={(e) => setGlobalFilter(e.target.value)} placeholder="Buscar..." />
</span>
</div>
);
const deleteAdminSystemDialogFooter = (
<>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteAdminSystemDialog} />
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSysAdmin} />
</>
);
const deleteAdminsSystemDialogFooter = (
<>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteAdminsSystemsDialog} />
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSelectedAdminsSystem} />
</>
);
return ( return (
<div className="grid"> <div className="grid">
<div className="col-12"> <div className="col-12">
<Toast ref={toast} />
<div className="card"> <div className="card">
<h5>Administradores del sistema</h5> < Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate}></Toolbar>
<DataTable value={pokemones} scrollable scrollHeight="400px" scrollDirection="both" className="mt-3">
<Column field="name" header="Nombre" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> <DataTable ref={dt} value={administrators} dataKey="_id" paginator rows={5} selection={selectedAdministrators} onSelectionChange={(e) => setSelectedAdministrators(e.value)}
<Column field="last_name" header="Apellidos" style={{ flexGrow: 1, flexBasis: '160px' }} alignFrozen="left"></Column> scrollable scrollHeight="400px" scrollDirection="both" header={header}
<Column field="dni" header="Identificación" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> rowsPerPageOptions={[5, 10, 25]} className="datatable-responsive mt-3"
<Column field="email" header="Correo electrónico" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
<Column field="phone" header="Telefóno" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} administradores del sistema"
globalFilter={globalFilter} emptyMessage="No hay administradores del sistema registrados."
>
<Column selectionMode="multiple" headerStyle={{ width: '3rem' }}></Column>
<Column field="name" sortable header="👩🏻‍💼👨🏻‍💼 Nombre" style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column field="last_name" sortable header="👩🏻‍💼👨🏻‍💼 Apellidos" style={{ flexGrow: 1,flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }} alignFrozen="left"></Column>
<Column field="dni" sortable header="💳 Identificación" style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column field="email" sortable header="📧 Correo electrónico" style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column field="phone" sortable header="📞 Telefóno" style={{ flexGrow: 1,flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column header="Acciones" style={{ flexGrow: 1,flexBasis: '60px' }} body={actionsAdmin}></Column>
</DataTable> </DataTable>
<Dialog visible={deleteAdminSystemDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteAdminSystemDialogFooter} onHide={hideDeleteAdminSystemDialog}>
<div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} />
{sysadmin && <span>¿Estás seguro que desea eliminar a <b>{sysadmin.name}</b>?</span>}
</div>
</Dialog>
<Dialog visible={deleteAdminsSystemDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteAdminsSystemDialogFooter} onHide={hideDeleteAdminsSystemsDialog}>
<div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} />
{sysadmin && <span>¿Está seguro eliminar los adminsitradores del sistema seleccionados?</span>}
</div>
</Dialog>
</div> </div>
</div> </div>
<div className="col-12"> <div className="col-12">
@ -105,4 +278,7 @@ const AdministradoresSistema = () => {
) )
} }
export default React.memo(AdministradoresSistema); const comparisonFn = function (prevProps, nextProps) {
return prevProps.location.pathname === nextProps.location.pathname;
};
export default React.memo(AdministradoresSistema, comparisonFn);

View File

@ -238,7 +238,7 @@ const Communities = () => {
<Column field="province" header="📍 Provincia" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> <Column field="province" header="📍 Provincia" style={{ flexGrow: 1, flexBasis: '160px' }}></Column>
<Column field="canton" header="📍 Cantón" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> <Column field="canton" header="📍 Cantón" style={{ flexGrow: 1, flexBasis: '160px' }}></Column>
<Column field="district" header="📍 Distrito" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> <Column field="district" header="📍 Distrito" style={{ flexGrow: 1, flexBasis: '160px' }}></Column>
<Column field="phone" header="☎️ Telefóno" style={{ flexGrow: 1, flexBasis: '180px' }}></Column> <Column field="phone" header="📞 Telefóno" style={{ flexGrow: 1, flexBasis: '180px' }}></Column>
<Column field="num_houses" header="#️⃣ Número de viviendas" style={{ flexGrow: 1, flexBasis: '180px' }}></Column> <Column field="num_houses" header="#️⃣ Número de viviendas" style={{ flexGrow: 1, flexBasis: '180px' }}></Column>
<Column field="name_admin" header="👩🏻‍💼👨🏻‍💼 Administrador" style={{ flexGrow: 1, flexBasis: '180px' }}></Column> <Column field="name_admin" header="👩🏻‍💼👨🏻‍💼 Administrador" style={{ flexGrow: 1, flexBasis: '180px' }}></Column>
</DataTable> </DataTable>