Merge pull request #128 from DeimosPr4/126-agregar-formateo-en-forma-de-un-pre-commit-hook

agregar formateo en forma de un pre commit hook
This commit is contained in:
Eduardo Quiros 2022-07-24 22:44:33 -06:00 committed by GitHub
commit 5277da52a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
152 changed files with 14669 additions and 8202 deletions

25
.jsbeautifyrc Normal file
View File

@ -0,0 +1,25 @@
{
"editorconfig": false,
"indent_size": 2,
"end_with_newline": true,
"html": {
"brace_style": "collapse",
"indent_char": " ",
"indent_scripts": "normal",
"indent_inner_html": true,
"indent_empty_lines": false,
"wrap_line_length": 120,
"wrap_attributes": "force-expand-multiline",
"unformatted": [
"sub",
"sup",
"b",
"i",
"u",
"em",
"strong"
],
"preserve_newlines": true,
"max_preserve_newlines": 2
}
}

4
.prettierignore Normal file
View File

@ -0,0 +1,4 @@
node_modules/*
e2e/*
dist/*
src/assets/scss/bootstrap/*

11
.prettierrc Normal file
View File

@ -0,0 +1,11 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": true,
"arrowParens": "always",
"jsxBracketSameLine": false,
"semi": true
}

View File

@ -1,5 +1,5 @@
import { Controller, Get, Post, Body, Param, Delete } 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 {
constructor(private readonly appService: AppService) {} constructor(private readonly appService: AppService) {}
@ -16,8 +16,17 @@ export class AppController {
@Body('status') status: string, @Body('status') status: string,
@Body('date_entry') date_entry: Date, @Body('date_entry') date_entry: Date,
) { ) {
return this.appService.createAdminSystem(dni, name, last_name, email, phone, password, return this.appService.createAdminSystem(
user_type, status, date_entry); dni,
name,
last_name,
email,
phone,
password,
user_type,
status,
date_entry,
);
} }
@Post('user/createGuard') @Post('user/createGuard')
@ -32,10 +41,20 @@ export class AppController {
@Body('user_type') user_type: string, @Body('user_type') user_type: string,
@Body('status') status: string, @Body('status') status: string,
@Body('date_entry') date_entry: Date, @Body('date_entry') date_entry: Date,
@Body('community_id') community_id:string @Body('community_id') community_id: string,
) { ) {
return this.appService.createGuard(dni, name, last_name, email, phone, password, return this.appService.createGuard(
user_type, status, date_entry,community_id); dni,
name,
last_name,
email,
phone,
password,
user_type,
status,
date_entry,
community_id,
);
} }
@Post('user/createUser') @Post('user/createUser')
@ -51,8 +70,18 @@ export class AppController {
@Body('date_entry') date_entry: Date, @Body('date_entry') date_entry: Date,
@Body('community_id') community_id: string, @Body('community_id') community_id: string,
) { ) {
return this.appService.createUser(dni, name, last_name, email, phone, password, return this.appService.createUser(
user_type, status, date_entry, community_id); dni,
name,
last_name,
email,
phone,
password,
user_type,
status,
date_entry,
community_id,
);
} }
@Get('user/allUsers') @Get('user/allUsers')
@ -78,24 +107,17 @@ export class AppController {
return this.appService.allUsersAdminComunidad(); return this.appService.allUsersAdminComunidad();
} }
@Get('user/findGuards/:community') @Get('user/findGuards/:community')
findGuardsCommunity( findGuardsCommunity(@Param('community_id') community_id: string) {
@Param('community_id') community_id: string
) {
return this.appService.findGuardsCommunity(community_id); return this.appService.findGuardsCommunity(community_id);
} }
@Get('user/find/:dni') @Get('user/find/:dni')
findUser( findUser(@Param('dni') paramUserDNI: string) {
@Param('dni') paramUserDNI: string
) {
return this.appService.findUser(paramUserDNI); return this.appService.findUser(paramUserDNI);
} }
@Delete('user/deleteAdminSystem/:id') @Delete('user/deleteAdminSystem/:id')
deleteAdminSystem( deleteAdminSystem(@Param('id') id: string) {
@Param('id') id: string,
) {
return this.appService.deleteAdminSystem(id); return this.appService.deleteAdminSystem(id);
} }
@ -111,11 +133,18 @@ export class AppController {
@Body('status') status: string, @Body('status') status: string,
@Body('date_entry') date_entry: Date, @Body('date_entry') date_entry: Date,
@Body('houses') houses: [], @Body('houses') houses: [],
) { ) {
return this.appService.createCommunity(name, province, canton, return this.appService.createCommunity(
district, num_houses, phone, name,
status, date_entry, houses); province,
canton,
district,
num_houses,
phone,
status,
date_entry,
houses,
);
} }
@Get('community/allCommunities') @Get('community/allCommunities')
@ -124,25 +153,17 @@ export class AppController {
} }
@Get('community/findCommunity/:id') @Get('community/findCommunity/:id')
findCommunity( findCommunity(@Param('id') paramCommunityId: string) {
@Param('id') paramCommunityId: string
) {
return this.appService.findCommunity(paramCommunityId); return this.appService.findCommunity(paramCommunityId);
} }
@Get('community/findCommunityName/:id') @Get('community/findCommunityName/:id')
findCommunityName( findCommunityName(@Param('id') paramCommunityId: string) {
@Param('id') paramCommunityId: string
) {
return this.appService.findCommunityName(paramCommunityId); return this.appService.findCommunityName(paramCommunityId);
} }
@Post('community/findCommunityAdmin') @Post('community/findCommunityAdmin')
findCommunityAdmin( findCommunityAdmin(@Body('community_id') community_id: string) {
@Body('community_id') community_id: string,
) {
return this.appService.findCommunityAdmin(community_id); return this.appService.findCommunityAdmin(community_id);
} }
@ -155,22 +176,22 @@ export class AppController {
@Body('bookable') bookable: number, @Body('bookable') bookable: number,
@Body('community_id') community_id: string, @Body('community_id') community_id: string,
) { ) {
return this.appService.createCommonArea(
return this.appService.createCommonArea(name, hourMin, hourMax, name,
bookable, community_id); hourMin,
hourMax,
bookable,
community_id,
);
} }
@Get('commonArea/allCommonAreas') @Get('commonArea/allCommonAreas')
allCommonAreas() { allCommonAreas() {
return this.appService.allCommonAreas(); return this.appService.allCommonAreas();
} }
@Get('commonArea/findCommonArea/:id') @Get('commonArea/findCommonArea/:id')
findCommonArea( findCommonArea(@Param('id') paramCommonAreaId: string) {
@Param('id') paramCommonAreaId: string
) {
return this.appService.findCommonArea(paramCommonAreaId); return this.appService.findCommonArea(paramCommonAreaId);
} }
@ -186,7 +207,15 @@ export class AppController {
@Body('status') status: string, @Body('status') status: string,
@Body('date_entry') date_entry: Date, @Body('date_entry') date_entry: Date,
) { ) {
return this.appService.createGuest(name, last_name, dni, number_plate, phone, status, date_entry); return this.appService.createGuest(
name,
last_name,
dni,
number_plate,
phone,
status,
date_entry,
);
} }
@Get('guest/allGuests') @Get('guest/allGuests')
@ -195,13 +224,10 @@ export class AppController {
} }
@Get('guest/find/:dni') @Get('guest/find/:dni')
findGuest( findGuest(@Param('dni') paramGuestDNI: string) {
@Param('dni') paramGuestDNI: string
) {
return this.appService.findGuest(paramGuestDNI); return this.appService.findGuest(paramGuestDNI);
} }
// #==== API Payment // #==== API Payment
@Post('payment/createPayment') @Post('payment/createPayment')
@ -214,8 +240,15 @@ export class AppController {
@Body('user_id') user_id: string, @Body('user_id') user_id: string,
@Body('communty_id') communty_id: string, @Body('communty_id') communty_id: string,
) { ) {
return this.appService.createPayment(date_payment, mount, description, return this.appService.createPayment(
period, status, user_id, communty_id); date_payment,
mount,
description,
period,
status,
user_id,
communty_id,
);
} }
@Get('payment/allPayments') @Get('payment/allPayments')
@ -224,9 +257,7 @@ export class AppController {
} }
@Get('payment/find/:dni') @Get('payment/find/:dni')
findPayment( findPayment(@Param('dni') paramPaymentDNI: string) {
@Param('dni') paramPaymentDNI: string
) {
return this.appService.findPayment(paramPaymentDNI); return this.appService.findPayment(paramPaymentDNI);
} }
@ -241,8 +272,14 @@ export class AppController {
@Body('user_id') user_id: string, @Body('user_id') user_id: string,
@Body('common_area_id') common_area_id: string, @Body('common_area_id') common_area_id: string,
) { ) {
return this.appService.createReservation(start_time, finish_time, status, return this.appService.createReservation(
date_entry, user_id, common_area_id); start_time,
finish_time,
status,
date_entry,
user_id,
common_area_id,
);
} }
@Get('reservation/allReservations') @Get('reservation/allReservations')
@ -251,13 +288,10 @@ export class AppController {
} }
@Get('reservation/find/:id') @Get('reservation/find/:id')
findReservation( findReservation(@Param('id') paramReservation: string) {
@Param('id') paramReservation: string
) {
return this.appService.findReservation(paramReservation); return this.appService.findReservation(paramReservation);
} }
// #==== API Post // #==== API Post
@Post('post/createPost') @Post('post/createPost')
@ -276,13 +310,10 @@ export class AppController {
} }
@Get('post/find/:id') @Get('post/find/:id')
findPost( findPost(@Param('id') paramPost: string) {
@Param('id') paramPost: string
) {
return this.appService.findPost(paramPost); return this.appService.findPost(paramPost);
} }
// #==== API Comment // #==== API Comment
@Post('post/createComment') @Post('post/createComment')
@ -301,14 +332,10 @@ export class AppController {
} }
@Get('post/findComment/:id') @Get('post/findComment/:id')
findComment( findComment(@Param('id') paramComment: string) {
@Param('id') paramComment: string
) {
return this.appService.findComment(paramComment); return this.appService.findComment(paramComment);
} }
// #==== API Report // #==== API Report
@Post('report/createReport') @Post('report/createReport')
@ -318,7 +345,12 @@ export class AppController {
@Body('date_entry') date_entry: Date, @Body('date_entry') date_entry: Date,
@Body('user_id') user_id: string, @Body('user_id') user_id: string,
) { ) {
return this.appService.createReport(action, description, date_entry, user_id); return this.appService.createReport(
action,
description,
date_entry,
user_id,
);
} }
@Get('report/allReports') @Get('report/allReports')
@ -327,26 +359,16 @@ export class AppController {
} }
@Get('report/find/:id') @Get('report/find/:id')
findReport( findReport(@Param('id') paramReport: string) {
@Param('id') paramReport: string
) {
return this.appService.findReport(paramReport); return this.appService.findReport(paramReport);
} }
@Post('email/sendMail') @Post('email/sendMail')
senMail( senMail(@Body('email') email: string) {
@Body('email') email: string,
) {
return this.appService.sendMail(email); return this.appService.sendMail(email);
} }
@Post('email/html') @Post('email/html')
html( html(@Body('email') email: string, @Body('name') name: string) {
@Body('email') email: string,
@Body('name') name: string,
) {
return this.appService.html(email, name); return this.appService.html(email, name);
} }
} }

View File

@ -1,99 +1,99 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { AppController } from './app.controller'; import { AppController } from './app.controller';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
import { AppService } from './app.service'; import { AppService } from './app.service';
@Module({ @Module({
imports: [ imports: [
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_USUARIOS", name: 'SERVICIO_USUARIOS',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3001 port: 3001,
} },
} },
]), ]),
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_COMUNIDADES", name: 'SERVICIO_COMUNIDADES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3002 port: 3002,
} },
} },
]), ]),
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_AREAS_COMUNES", name: 'SERVICIO_AREAS_COMUNES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3003 port: 3003,
} },
} },
]), ]),
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_INVITADOS", name: 'SERVICIO_INVITADOS',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3004 port: 3004,
} },
} },
]), ]),
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_PAGOS", name: 'SERVICIO_PAGOS',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3005 port: 3005,
} },
} },
]), ]),
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_RESERVACIONES", name: 'SERVICIO_RESERVACIONES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3006 port: 3006,
} },
} },
]), ]),
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_POSTS", name: 'SERVICIO_POSTS',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3007 port: 3007,
} },
} },
]), ]),
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_REPORTES", name: 'SERVICIO_REPORTES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3008 port: 3008,
} },
} },
]), ]),
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_NOTIFICACIONES", name: 'SERVICIO_NOTIFICACIONES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3009 port: 3009,
} },
} },
]), ]),
], ],
controllers: [AppController], controllers: [AppController],

View File

@ -1,68 +1,115 @@
import { Injectable, Inject } from '@nestjs/common'; import { Injectable, Inject } from '@nestjs/common';
import { ClientProxy } from "@nestjs/microservices"; import { ClientProxy } from '@nestjs/microservices';
import { map } from "rxjs/operators"; import { map } from 'rxjs/operators';
@Injectable() @Injectable()
export class AppService { export class AppService {
constructor( constructor(
@Inject('SERVICIO_USUARIOS') private readonly clientUserApp: ClientProxy, @Inject('SERVICIO_USUARIOS') private readonly clientUserApp: ClientProxy,
@Inject('SERVICIO_COMUNIDADES') private readonly clientCommunityApp: ClientProxy, @Inject('SERVICIO_COMUNIDADES')
@Inject('SERVICIO_AREAS_COMUNES') private readonly clientCommonAreaApp: ClientProxy, private readonly clientCommunityApp: ClientProxy,
@Inject('SERVICIO_AREAS_COMUNES')
private readonly clientCommonAreaApp: ClientProxy,
@Inject('SERVICIO_INVITADOS') private readonly clientGuestApp: ClientProxy, @Inject('SERVICIO_INVITADOS') private readonly clientGuestApp: ClientProxy,
@Inject('SERVICIO_PAGOS') private readonly clientPaymentApp: ClientProxy, @Inject('SERVICIO_PAGOS') private readonly clientPaymentApp: ClientProxy,
@Inject('SERVICIO_RESERVACIONES') private readonly clientReservationApp: ClientProxy, @Inject('SERVICIO_RESERVACIONES')
private readonly clientReservationApp: ClientProxy,
@Inject('SERVICIO_POSTS') private readonly clientPostApp: ClientProxy, @Inject('SERVICIO_POSTS') private readonly clientPostApp: ClientProxy,
@Inject('SERVICIO_REPORTES') private readonly clientReportApp: ClientProxy, @Inject('SERVICIO_REPORTES') private readonly clientReportApp: ClientProxy,
@Inject('SERVICIO_NOTIFICACIONES') private readonly clientNotificationtApp: ClientProxy, @Inject('SERVICIO_NOTIFICACIONES')
private readonly clientNotificationtApp: ClientProxy,
) {} ) {}
// ====================== USERS =============================== // ====================== USERS ===============================
//POST parameter from API //POST parameter from API
createUser(dni: string, name: string, last_name: string, email: string, phone: number createUser(
, password: string, user_type: string, status: string, date_entry: Date, community_id: string) { 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: 'createUser' }; const pattern = { cmd: 'createUser' };
const payload = { const payload = {
dni: dni, name: name, last_name: last_name, email: email, phone: phone, dni: dni,
password: password, user_type: user_type, status: status, date_entry: date_entry, name: name,
community_id: community_id 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 return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
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(
, password: string, user_type: string, status: string, date_entry: Date) { dni: string,
name: string,
last_name: string,
email: string,
phone: number,
password: string,
user_type: string,
status: string,
date_entry: Date,
) {
const pattern = { cmd: 'createAdminSystem' }; const pattern = { cmd: 'createAdminSystem' };
const payload = { const payload = {
dni: dni, name: name, last_name: last_name, email: email, phone: phone, dni: dni,
password: password, user_type: user_type, status: status, date_entry: date_entry name: name,
last_name: last_name,
email: email,
phone: phone,
password: password,
user_type: user_type,
status: status,
date_entry: date_entry,
}; };
return this.clientUserApp return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
createGuard(dni: string, name: string, last_name: string, email: string, phone: number createGuard(
, password: string, user_type: string, status: string, date_entry: Date, community_id: string) { 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: 'createGuard' }; const pattern = { cmd: 'createGuard' };
const payload = { const payload = {
dni: dni, name: name, last_name: last_name, email: email, phone: phone, dni: dni,
password: password, user_type: user_type, status: status, date_entry: date_entry, community_id name: name,
last_name: last_name,
email: email,
phone: phone,
password: password,
user_type: user_type,
status: status,
date_entry: date_entry,
community_id,
}; };
return this.clientUserApp return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allUsers() { allUsers() {
@ -70,9 +117,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientUserApp return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allUsersAdminSistema() { allUsersAdminSistema() {
@ -80,9 +125,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientUserApp return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allUsersAdminComunidad() { allUsersAdminComunidad() {
@ -90,9 +133,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientUserApp return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
//GET parameter from API //GET parameter from API
@ -101,9 +142,7 @@ export class AppService {
const payload = { dni: paramUserDNI }; const payload = { dni: paramUserDNI };
return this.clientUserApp return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
findGuardsCommunity(community_id: string) { findGuardsCommunity(community_id: string) {
@ -111,20 +150,15 @@ export class AppService {
const payload = { community_id: community_id }; const payload = { community_id: community_id };
return this.clientUserApp return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
deleteAdminSystem(id: string) { deleteAdminSystem(id: string) {
const pattern = { cmd: 'deleteAdminSystem' }; const pattern = { cmd: 'deleteAdminSystem' };
const payload = { id: id }; const payload = { id: id };
return this.clientUserApp return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
inicioSesion(pEmail: string, pPassword: string) { inicioSesion(pEmail: string, pPassword: string) {
@ -132,38 +166,47 @@ export class AppService {
const payload = { email: pEmail, password: pPassword }; const payload = { email: pEmail, password: pPassword };
return this.clientUserApp return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
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' };
const payload = { community_id: community_id }; const payload = { community_id: community_id };
return this.clientCommunityApp return this.clientCommunityApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
// ====================== COMMUNITIES =============================== // ====================== COMMUNITIES ===============================
//POST parameter from API //POST parameter from API
createCommunity(name: string, province: string, canton: string, district: string createCommunity(
, num_houses: number, phone: string, status: string, date_entry: Date, houses: []) { name: string,
province: string,
canton: string,
district: string,
num_houses: number,
phone: string,
status: string,
date_entry: Date,
houses: [],
) {
const pattern = { cmd: 'createCommunity' }; const pattern = { cmd: 'createCommunity' };
const payload = { const payload = {
name: name, province: province, canton: canton, district: district, num_houses: num_houses, name: name,
phone: phone, status: status, date_entry: date_entry, houses: houses province: province,
canton: canton,
district: district,
num_houses: num_houses,
phone: phone,
status: status,
date_entry: date_entry,
houses: houses,
}; };
return this.clientCommunityApp return this.clientCommunityApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allCommunities() { allCommunities() {
@ -171,9 +214,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientCommunityApp return this.clientCommunityApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
//GET parameter from API //GET parameter from API
@ -182,9 +223,7 @@ export class AppService {
const payload = { id: paramCommunityId }; const payload = { id: paramCommunityId };
return this.clientCommunityApp return this.clientCommunityApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
findCommunityName(paramCommunityId: string) { findCommunityName(paramCommunityId: string) {
@ -192,27 +231,29 @@ export class AppService {
const payload = { id: paramCommunityId }; const payload = { id: paramCommunityId };
return this.clientCommunityApp return this.clientCommunityApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
// ====================== COMMON AREAS =============================== // ====================== COMMON AREAS ===============================
//POST parameter from API //POST parameter from API
createCommonArea(name: string, hourMin: string, hourMax: string, createCommonArea(
bookable: number, community_id: string) { name: string,
hourMin: string,
hourMax: string,
bookable: number,
community_id: string,
) {
const pattern = { cmd: 'createCommonArea' }; const pattern = { cmd: 'createCommonArea' };
const payload = { const payload = {
name: name, hourMin: hourMin, hourMax: hourMax, bookable: bookable, name: name,
community_id: community_id hourMin: hourMin,
hourMax: hourMax,
bookable: bookable,
community_id: community_id,
}; };
return this.clientCommonAreaApp return this.clientCommonAreaApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allCommonAreas() { allCommonAreas() {
@ -220,9 +261,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientCommonAreaApp return this.clientCommonAreaApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
//GET parameter from API //GET parameter from API
@ -231,28 +270,34 @@ export class AppService {
const payload = { id: paramCommonAreaId }; const payload = { id: paramCommonAreaId };
return this.clientCommonAreaApp return this.clientCommonAreaApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
// ====================== GUESTS =============================== // ====================== GUESTS ===============================
//POST parameter from API //POST parameter from API
createGuest(name: string, last_name: string, dni: string, number_plate: string, phone: number createGuest(
, status: string, date_entry: Date) { name: string,
last_name: string,
dni: string,
number_plate: string,
phone: number,
status: string,
date_entry: Date,
) {
const pattern = { cmd: 'createGuest' }; const pattern = { cmd: 'createGuest' };
const payload = { const payload = {
name: name, last_name: last_name, dni: dni, number_plate: number_plate, phone: phone, name: name,
status: status, date_entry: date_entry last_name: last_name,
dni: dni,
number_plate: number_plate,
phone: phone,
status: status,
date_entry: date_entry,
}; };
return this.clientGuestApp return this.clientGuestApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allGuests() { allGuests() {
@ -260,9 +305,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientGuestApp return this.clientGuestApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
//GET parameter from API //GET parameter from API
@ -271,26 +314,34 @@ export class AppService {
const payload = { dni: paramGuestDNI }; const payload = { dni: paramGuestDNI };
return this.clientGuestApp return this.clientGuestApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
// ====================== PAYMENTS =============================== // ====================== PAYMENTS ===============================
//POST parameter from API //POST parameter from API
createPayment(date_payment: Date, mount: number, description: string, period: string createPayment(
, status: string, user_id: string, communty_id: string) { date_payment: Date,
mount: number,
description: string,
period: string,
status: string,
user_id: string,
communty_id: string,
) {
const pattern = { cmd: 'createPayment' }; const pattern = { cmd: 'createPayment' };
const payload = { const payload = {
date_payment: date_payment, mount: mount, description: description, date_payment: date_payment,
period: period, status: status, user_id: user_id, communty_id: communty_id mount: mount,
description: description,
period: period,
status: status,
user_id: user_id,
communty_id: communty_id,
}; };
return this.clientPaymentApp return this.clientPaymentApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allPayments() { allPayments() {
@ -298,9 +349,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientPaymentApp return this.clientPaymentApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
//GET parameter from API //GET parameter from API
@ -309,27 +358,32 @@ export class AppService {
const payload = { id: paramPaymentId }; const payload = { id: paramPaymentId };
return this.clientPaymentApp return this.clientPaymentApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
// ====================== RESERVATIONS =============================== // ====================== RESERVATIONS ===============================
//POST parameter from API //POST parameter from API
createReservation(start_time: string, finish_time: string, status: string, createReservation(
date_entry: Date, user_id: string, common_area_id: string) { start_time: string,
finish_time: string,
status: string,
date_entry: Date,
user_id: string,
common_area_id: string,
) {
const pattern = { cmd: 'createReservation' }; const pattern = { cmd: 'createReservation' };
const payload = { const payload = {
start_time: start_time, finish_time: finish_time, status: status, start_time: start_time,
date_entry: date_entry, user_id: user_id, common_area_id: common_area_id finish_time: finish_time,
status: status,
date_entry: date_entry,
user_id: user_id,
common_area_id: common_area_id,
}; };
return this.clientReservationApp return this.clientReservationApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allReservations() { allReservations() {
@ -337,9 +391,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientReservationApp return this.clientReservationApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
//GET parameter from API //GET parameter from API
@ -348,27 +400,28 @@ export class AppService {
const payload = { id: paramReservationId }; const payload = { id: paramReservationId };
return this.clientReservationApp return this.clientReservationApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
// ====================== POSTS =============================== // ====================== POSTS ===============================
//POST parameter from API //POST parameter from API
createPost(post: string, date_entry: Date, user_id: string, createPost(
community_id: string) { post: string,
date_entry: Date,
user_id: string,
community_id: string,
) {
const pattern = { cmd: 'createPost' }; const pattern = { cmd: 'createPost' };
const payload = { const payload = {
post: post, date_entry: date_entry, user_id: user_id, post: post,
community_id: community_id date_entry: date_entry,
user_id: user_id,
community_id: community_id,
}; };
return this.clientPostApp return this.clientPostApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allPosts() { allPosts() {
@ -376,9 +429,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientPostApp return this.clientPostApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
//GET parameter from API //GET parameter from API
@ -387,26 +438,28 @@ export class AppService {
const payload = { id: paramPostId }; const payload = { id: paramPostId };
return this.clientPostApp return this.clientPostApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
// ====================== COMMNENT POSTS =============================== // ====================== COMMNENT POSTS ===============================
//Comment parameter from API //Comment parameter from API
createComment(comment: string, date_entry: Date, user_id: string, createComment(
post_id: string) { comment: string,
date_entry: Date,
user_id: string,
post_id: string,
) {
const pattern = { cmd: 'createComment' }; const pattern = { cmd: 'createComment' };
const payload = { const payload = {
comment: comment, date_entry: date_entry, user_id: user_id, comment: comment,
post_id: post_id date_entry: date_entry,
user_id: user_id,
post_id: post_id,
}; };
return this.clientPostApp return this.clientPostApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allComments() { allComments() {
@ -414,9 +467,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientPostApp return this.clientPostApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
//GET parameter from API //GET parameter from API
@ -425,26 +476,28 @@ export class AppService {
const payload = { id: paramCommentId }; const payload = { id: paramCommentId };
return this.clientPostApp return this.clientPostApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
// ====================== REPORTS =============================== // ====================== REPORTS ===============================
//Report parameter from API //Report parameter from API
createReport(action: string, description: string, date_entry: Date, createReport(
user_id: string) { action: string,
description: string,
date_entry: Date,
user_id: string,
) {
const pattern = { cmd: 'createReport' }; const pattern = { cmd: 'createReport' };
const payload = { const payload = {
action: action, description: description, date_entry: date_entry, action: action,
user_id: user_id description: description,
date_entry: date_entry,
user_id: user_id,
}; };
return this.clientReportApp return this.clientReportApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
allReports() { allReports() {
@ -452,9 +505,7 @@ export class AppService {
const payload = {}; const payload = {};
return this.clientReportApp return this.clientReportApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
//GET parameter from API //GET parameter from API
@ -463,20 +514,15 @@ export class AppService {
const payload = { id: paramReportId }; const payload = { id: paramReportId };
return this.clientReportApp return this.clientReportApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
sendMail(email: string) { sendMail(email: string) {
const pattern = { cmd: 'sendMail' }; const pattern = { cmd: 'sendMail' };
const payload = { email: email }; const payload = { email: email };
return this.clientNotificationtApp return this.clientNotificationtApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
html(email: string, name: string) { html(email: string, name: string) {
@ -484,8 +530,6 @@ export class AppService {
const payload = { email: email, name: name }; const payload = { email: email, name: name };
return this.clientNotificationtApp return this.clientNotificationtApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
} }

2161
package-lock.json generated

File diff suppressed because it is too large Load Diff

28
package.json Normal file
View File

@ -0,0 +1,28 @@
{
"devDependencies": {
"husky": "^8.0.1",
"js-beautify": "^1.14.4",
"lint-staged": "^13.0.3",
"prettier": "^2.7.1"
},
"scripts": {
"format": "npm run format:prettier && npm run format:html",
"format:prettier": "prettier --config .prettierrc \"**/src/**/*.{ts,css,less,scss,js}\" --write",
"format:html": "js-beautify --config .jsbeautifyrc --type 'html' --file '**/src/**/*.html' --replace"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{ts,css,less,scss,js}": [
"prettier --config .prettierrc --write",
"git add"
],
"*.html": [
"js-beautify --config .jsbeautifyrc --type 'html' --replace",
"git add"
]
}
}

View File

@ -6,7 +6,9 @@ import { BooksModule } from './books/books.module';
@Module({ @Module({
imports: [ imports: [
MongooseModule.forRoot(`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_books?retryWrites=true&w=majority`), MongooseModule.forRoot(
`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_books?retryWrites=true&w=majority`,
),
BooksModule, BooksModule,
], ],
controllers: [AppController], controllers: [AppController],

View File

@ -9,6 +9,6 @@ import { Book, BookSchema } from './schemas/book.schema';
MongooseModule.forFeature([{ name: Book.name, schema: BookSchema }]), MongooseModule.forFeature([{ name: Book.name, schema: BookSchema }]),
], ],
controllers: [BooksController], controllers: [BooksController],
providers: [BooksService] providers: [BooksService],
}) })
export class BooksModule {} export class BooksModule {}

View File

@ -1,7 +1,5 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
export class CreateBookDto { export class CreateBookDto {
@ApiProperty({ @ApiProperty({
example: 'Nest.js: A Progressive Node.js Framework (English Edition)', example: 'Nest.js: A Progressive Node.js Framework (English Edition)',

View File

@ -1,23 +1,25 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { CommonAreasModule } from './common_areas/common_areas.module'; import { CommonAreasModule } from './common_areas/common_areas.module';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
@Module({ @Module({
imports: [ imports: [
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_AREAS_COMUNES", name: 'SERVICIO_AREAS_COMUNES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3003 port: 3003,
} },
} },
]), ]),
MongooseModule.forRoot(`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_areas_comunes?retryWrites=true&w=majority`), MongooseModule.forRoot(
CommonAreasModule], `mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_areas_comunes?retryWrites=true&w=majority`,
),
CommonAreasModule,
],
controllers: [], controllers: [],
providers: [], providers: [],
}) })

View File

@ -6,9 +6,11 @@ import { MongooseModule } from '@nestjs/mongoose';
import { CommonArea, CommonAreaSchema } from '../schemas/common_area.schema'; import { CommonArea, CommonAreaSchema } from '../schemas/common_area.schema';
@Module({ @Module({
imports: [ imports: [
MongooseModule.forFeature([{ name: CommonArea.name, schema: CommonAreaSchema }]), MongooseModule.forFeature([
{ name: CommonArea.name, schema: CommonAreaSchema },
]),
], ],
controllers: [CommonAreasController], controllers: [CommonAreasController],
providers: [CommonAreasService] providers: [CommonAreasService],
}) })
export class CommonAreasModule {} export class CommonAreasModule {}

View File

@ -5,9 +5,9 @@ import { Model } from 'mongoose';
@Injectable() @Injectable()
export class CommonAreasService { export class CommonAreasService {
constructor( constructor(
@InjectModel(CommonArea.name) private readonly commonAreaModel: Model<CommonAreaDocument>, @InjectModel(CommonArea.name)
private readonly commonAreaModel: Model<CommonAreaDocument>,
) {} ) {}
async create(commonArea: CommonAreaDocument): Promise<CommonArea> { async create(commonArea: CommonAreaDocument): Promise<CommonArea> {

View File

@ -1,7 +1,7 @@
import { NestFactory } from "@nestjs/core"; import { NestFactory } from '@nestjs/core';
import { Transport } from "@nestjs/microservices"; import { Transport } from '@nestjs/microservices';
import { AppModule } from "./app.module"; import { AppModule } from './app.module';
import { Logger } from "@nestjs/common"; import { Logger } from '@nestjs/common';
const logger = new Logger(); const logger = new Logger();
@ -9,10 +9,12 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, { const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3003 port: 3003,
} },
}); });
app.listen().then(() => logger.log("Microservice Áreas Comunes is listening" )); app
.listen()
.then(() => logger.log('Microservice Áreas Comunes is listening'));
} }
bootstrap(); bootstrap();

View File

@ -1,15 +1,12 @@
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose'; import { Document } from 'mongoose';
import { Timestamp } from 'rxjs'; import { Timestamp } from 'rxjs';
import { TimerOptions } from 'timers'; import { TimerOptions } from 'timers';
export type CommonAreaDocument = CommonArea & Document; export type CommonAreaDocument = CommonArea & Document;
@Schema({ collection: 'common_areas' }) @Schema({ collection: 'common_areas' })
export class CommonArea { export class CommonArea {
@Prop() @Prop()
name: string; name: string;

View File

@ -1,23 +1,25 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { CommunitiesModule } from './communities/communities.module'; import { CommunitiesModule } from './communities/communities.module';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
@Module({ @Module({
imports: [ imports: [
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_COMUNIDADES", name: 'SERVICIO_COMUNIDADES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3002 port: 3002,
} },
} },
]), ]),
MongooseModule.forRoot(`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_comunidades?retryWrites=true&w=majority`), MongooseModule.forRoot(
CommunitiesModule], `mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_comunidades?retryWrites=true&w=majority`,
),
CommunitiesModule,
],
controllers: [], controllers: [],
providers: [], providers: [],
}) })

View File

@ -2,26 +2,27 @@ import { Module } from '@nestjs/common';
import { CommunitiesService } from './communities.service'; import { CommunitiesService } from './communities.service';
import { CommunitiesController } from './communities.controller'; import { CommunitiesController } from './communities.controller';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
import { Community, CommunitySchema } from '../schemas/community.schema'; import { Community, CommunitySchema } from '../schemas/community.schema';
@Module({ @Module({
imports: [ imports: [
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_USUARIOS", name: 'SERVICIO_USUARIOS',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3001 port: 3001,
} },
} },
]),
MongooseModule.forFeature([
{ name: Community.name, schema: CommunitySchema },
]), ]),
MongooseModule.forFeature([{ name: Community.name, schema: CommunitySchema }]),
], ],
controllers: [CommunitiesController], controllers: [CommunitiesController],
providers: [CommunitiesService] providers: [CommunitiesService],
}) })
export class CommunitiesModule {} export class CommunitiesModule {}

View File

@ -7,14 +7,12 @@ import { from, lastValueFrom, map, scan, mergeMap } from 'rxjs';
import { Admin } from 'src/schemas/admin.entity'; import { Admin } from 'src/schemas/admin.entity';
import { appendFileSync } from 'fs'; import { appendFileSync } from 'fs';
@Injectable() @Injectable()
export class CommunitiesService { export class CommunitiesService {
constructor( constructor(
@InjectModel(Community.name) private readonly communityModel: Model<CommunityDocument>, @InjectModel(Community.name)
private readonly communityModel: Model<CommunityDocument>,
@Inject('SERVICIO_USUARIOS') private readonly clientUserApp: ClientProxy, @Inject('SERVICIO_USUARIOS') private readonly clientUserApp: ClientProxy,
) {} ) {}
async create(community: CommunityDocument): Promise<Community> { async create(community: CommunityDocument): Promise<Community> {
@ -22,25 +20,26 @@ export class CommunitiesService {
} }
async findAll(): Promise<Community[]> { async findAll(): Promise<Community[]> {
return await this.communityModel return await this.communityModel
.find() .find()
.setOptions({ sanitizeFilter: true }) .setOptions({ sanitizeFilter: true })
.exec() .exec()
.then(async community => { .then(async (community) => {
if (community) { if (community) {
await Promise.all(community.map(async c => { await Promise.all(
community.map(async (c) => {
//buscar al usuario con el id de la comunidad anexado //buscar al usuario con el id de la comunidad anexado
let admin = await this.findCommunityAdmin(c["_id"], "2") let admin = await this.findCommunityAdmin(c['_id'], '2');
if (admin) { if (admin) {
c["id_admin"] = admin["_id"] c['id_admin'] = admin['_id'];
c["name_admin"] = admin["name"] c['name_admin'] = admin['name'];
} }
return c return c;
})) }),
);
} }
return community; return community;
}) });
} }
findOne(id: string): Promise<Community> { findOne(id: string): Promise<Community> {
@ -61,17 +60,14 @@ export class CommunitiesService {
} }
async findCommunityAdmin(community: string, user_type: string) { async findCommunityAdmin(community: string, user_type: string) {
const pattern = { cmd: 'findOneCommunityUser' } const pattern = { cmd: 'findOneCommunityUser' };
const payload = { community_id: community, user_type: user_type } const payload = { community_id: community, user_type: user_type };
let callback = await this.clientUserApp let callback = await this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((response: string) => ({ response })));
map((response: string) => ({ response }))
)
const finalValue = await lastValueFrom(callback); const finalValue = await lastValueFrom(callback);
return finalValue['response']; return finalValue['response'];
} }
} }

View File

@ -1,7 +1,7 @@
import { NestFactory } from "@nestjs/core"; import { NestFactory } from '@nestjs/core';
import { Transport } from "@nestjs/microservices"; import { Transport } from '@nestjs/microservices';
import { AppModule } from "./app.module"; import { AppModule } from './app.module';
import { Logger } from "@nestjs/common"; import { Logger } from '@nestjs/common';
const logger = new Logger(); const logger = new Logger();
@ -9,10 +9,14 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, { const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3002 port: 3002,
} },
}); });
app.listen().then(() => logger.log("Microservice Comunidades de vivienda is listening" )); app
.listen()
.then(() =>
logger.log('Microservice Comunidades de vivienda is listening'),
);
} }
bootstrap(); bootstrap();

View File

@ -2,7 +2,6 @@ import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose'; import { Document } from 'mongoose';
import { House, HouseSchema } from './house.schema'; import { House, HouseSchema } from './house.schema';
export type CommunityDocument = Community & Document; export type CommunityDocument = Community & Document;
@Schema({ collection: 'communities' }) @Schema({ collection: 'communities' })
@ -39,8 +38,6 @@ export class Community {
@Prop({ type: [HouseSchema] }) @Prop({ type: [HouseSchema] })
houses: Array<House>; houses: Array<House>;
} }
export const CommunitySchema = SchemaFactory.createForClass(Community); export const CommunitySchema = SchemaFactory.createForClass(Community);

View File

@ -4,14 +4,12 @@ import { Document } from 'mongoose';
import { empty } from 'rxjs'; import { empty } from 'rxjs';
import { Tenant, TenantSchema } from './tenant.schema'; import { Tenant, TenantSchema } from './tenant.schema';
@Schema() @Schema()
export class House extends Document { export class House extends Document {
@Prop({ default: " " }) @Prop({ default: ' ' })
number_house: string; number_house: string;
@Prop({ default: "desocupada" }) @Prop({ default: 'desocupada' })
state: string; state: string;
@Prop({ type: TenantSchema }) @Prop({ type: TenantSchema })

View File

@ -1,7 +1,5 @@
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
@Schema() @Schema()
export class Tenant { export class Tenant {
@Prop({ default: '' }) @Prop({ default: '' })

View File

@ -1,23 +1,27 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
import { PostsModule } from './posts/posts.module'; import { PostsModule } from './posts/posts.module';
import { PostCommentsModule } from './post-comments/post-comments.module'; import { PostCommentsModule } from './post-comments/post-comments.module';
@Module({ @Module({
imports: [ ClientsModule.register([ imports: [
ClientsModule.register([
{ {
name: "SERVICIO_POSTS", name: 'SERVICIO_POSTS',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3007 port: 3007,
} },
} },
]), ]),
MongooseModule.forRoot(`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_posts?retryWrites=true&w=majority`), MongooseModule.forRoot(
`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_posts?retryWrites=true&w=majority`,
),
PostsModule, PostsModule,
PostCommentsModule], PostCommentsModule,
],
controllers: [], controllers: [],
providers: [], providers: [],
}) })

View File

@ -1,7 +1,7 @@
import { NestFactory } from "@nestjs/core"; import { NestFactory } from '@nestjs/core';
import { Transport } from "@nestjs/microservices"; import { Transport } from '@nestjs/microservices';
import { AppModule } from "./app.module"; import { AppModule } from './app.module';
import { Logger } from "@nestjs/common"; import { Logger } from '@nestjs/common';
const logger = new Logger(); const logger = new Logger();
@ -9,10 +9,10 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, { const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3007 port: 3007,
} },
}); });
app.listen().then(() => logger.log("Microservice Comunicados is listening" )); app.listen().then(() => logger.log('Microservice Comunicados is listening'));
} }
bootstrap(); bootstrap();

View File

@ -3,7 +3,6 @@ import { MessagePattern, Payload } from '@nestjs/microservices';
import { PostCommentsService } from './post-comments.service'; import { PostCommentsService } from './post-comments.service';
import { Comment, CommentDocument } from '../schemas/post-comment.schema'; import { Comment, CommentDocument } from '../schemas/post-comment.schema';
@Controller() @Controller()
export class PostCommentsController { export class PostCommentsController {
constructor(private readonly postCommentsService: PostCommentsService) {} constructor(private readonly postCommentsService: PostCommentsService) {}

View File

@ -9,6 +9,6 @@ import { Comment, CommentSchema } from '../schemas/post-comment.schema';
MongooseModule.forFeature([{ name: Comment.name, schema: CommentSchema }]), MongooseModule.forFeature([{ name: Comment.name, schema: CommentSchema }]),
], ],
controllers: [PostCommentsController], controllers: [PostCommentsController],
providers: [PostCommentsService] providers: [PostCommentsService],
}) })
export class PostCommentsModule {} export class PostCommentsModule {}

View File

@ -3,11 +3,11 @@ import { Comment, CommentDocument } from '../schemas/post-comment.schema';
import { Model } from 'mongoose'; import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
@Injectable() @Injectable()
export class PostCommentsService { export class PostCommentsService {
constructor( constructor(
@InjectModel(Comment.name) private readonly commentModel: Model<CommentDocument>, @InjectModel(Comment.name)
private readonly commentModel: Model<CommentDocument>,
) {} ) {}
async create(comment: CommentDocument): Promise<Comment> { async create(comment: CommentDocument): Promise<Comment> {
@ -15,10 +15,7 @@ export class PostCommentsService {
} }
async findAll(): Promise<Comment[]> { async findAll(): Promise<Comment[]> {
return this.commentModel return this.commentModel.find().setOptions({ sanitizeFilter: true }).exec();
.find()
.setOptions({ sanitizeFilter: true })
.exec();
} }
async findOne(id: string): Promise<Comment> { async findOne(id: string): Promise<Comment> {

View File

@ -3,7 +3,6 @@ import { MessagePattern, Payload } from '@nestjs/microservices';
import { PostsService } from './posts.service'; import { PostsService } from './posts.service';
import { Post, PostDocument } from '../schemas/post.schema'; import { Post, PostDocument } from '../schemas/post.schema';
@Controller() @Controller()
export class PostsController { export class PostsController {
constructor(private readonly postsService: PostsService) {} constructor(private readonly postsService: PostsService) {}

View File

@ -9,6 +9,6 @@ import { MongooseModule } from '@nestjs/mongoose';
MongooseModule.forFeature([{ name: Post.name, schema: PostSchema }]), MongooseModule.forFeature([{ name: Post.name, schema: PostSchema }]),
], ],
controllers: [PostsController], controllers: [PostsController],
providers: [PostsService] providers: [PostsService],
}) })
export class PostsModule {} export class PostsModule {}

View File

@ -14,10 +14,7 @@ export class PostsService {
} }
async findAll(): Promise<Post[]> { async findAll(): Promise<Post[]> {
return this.postModel return this.postModel.find().setOptions({ sanitizeFilter: true }).exec();
.find()
.setOptions({ sanitizeFilter: true })
.exec();
} }
async findOne(id: string): Promise<Post> { async findOne(id: string): Promise<Post> {

View File

@ -1,12 +1,10 @@
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document, ObjectId } from 'mongoose'; import { Document, ObjectId } from 'mongoose';
export type CommentDocument = Comment & Document; export type CommentDocument = Comment & Document;
@Schema({ collection: 'comments' }) @Schema({ collection: 'comments' })
export class Comment { export class Comment {
@Prop() @Prop()
comment: string; comment: string;
@ -14,12 +12,10 @@ export class Comment {
date_entry: Date; date_entry: Date;
@Prop() @Prop()
user_id: string user_id: string;
@Prop() @Prop()
post_id: string; post_id: string;
} }
export const CommentSchema = SchemaFactory.createForClass(Comment); export const CommentSchema = SchemaFactory.createForClass(Comment);

View File

@ -1,12 +1,10 @@
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document, ObjectId } from 'mongoose'; import { Document, ObjectId } from 'mongoose';
export type PostDocument = Post & Document; export type PostDocument = Post & Document;
@Schema({ collection: 'posts' }) @Schema({ collection: 'posts' })
export class Post { export class Post {
@Prop() @Prop()
post: string; post: string;
@ -14,11 +12,10 @@ export class Post {
date_entry: Date; date_entry: Date;
@Prop() @Prop()
user_id: string user_id: string;
@Prop() @Prop()
community_id: string // id de la comunidad community_id: string; // id de la comunidad
} }
export const PostSchema = SchemaFactory.createForClass(Post); export const PostSchema = SchemaFactory.createForClass(Post);

View File

@ -1,23 +1,25 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { GuestsModule } from './guests/guests.module'; import { GuestsModule } from './guests/guests.module';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
@Module({ @Module({
imports: [ imports: [
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_INVITADOS", name: 'SERVICIO_INVITADOS',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3004 port: 3004,
} },
} },
]), ]),
MongooseModule.forRoot(`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_invitados?retryWrites=true&w=majority`), MongooseModule.forRoot(
GuestsModule], `mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_invitados?retryWrites=true&w=majority`,
),
GuestsModule,
],
controllers: [], controllers: [],
providers: [], providers: [],
}) })

View File

@ -8,6 +8,6 @@ import { Guest, GuestSchema } from 'src/schemas/guest.schema';
MongooseModule.forFeature([{ name: Guest.name, schema: GuestSchema }]), MongooseModule.forFeature([{ name: Guest.name, schema: GuestSchema }]),
], ],
controllers: [GuestsController], controllers: [GuestsController],
providers: [GuestsService] providers: [GuestsService],
}) })
export class GuestsModule {} export class GuestsModule {}

View File

@ -14,18 +14,13 @@ export class GuestsService {
} }
async findAll(): Promise<Guest[]> { async findAll(): Promise<Guest[]> {
return this.guestModel return this.guestModel.find().setOptions({ sanitizeFilter: true }).exec();
.find()
.setOptions({ sanitizeFilter: true })
.exec();
} }
findOneId(id: string): Promise<Guest> { findOneId(id: string): Promise<Guest> {
return this.guestModel.findOne({ _id: id }).exec(); return this.guestModel.findOne({ _id: id }).exec();
} }
findOne(id: string): Promise<Guest> { findOne(id: string): Promise<Guest> {
return this.guestModel.findOne({ dni: id }).exec(); return this.guestModel.findOne({ dni: id }).exec();
} }

View File

@ -1,7 +1,7 @@
import { NestFactory } from "@nestjs/core"; import { NestFactory } from '@nestjs/core';
import { Transport } from "@nestjs/microservices"; import { Transport } from '@nestjs/microservices';
import { AppModule } from "./app.module"; import { AppModule } from './app.module';
import { Logger } from "@nestjs/common"; import { Logger } from '@nestjs/common';
const logger = new Logger(); const logger = new Logger();
@ -9,10 +9,10 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, { const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3004 port: 3004,
} },
}); });
app.listen().then(() => logger.log("Microservice Invitados is listening" )); app.listen().then(() => logger.log('Microservice Invitados is listening'));
} }
bootstrap(); bootstrap();

View File

@ -1,12 +1,10 @@
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose'; import { Document } from 'mongoose';
export type GuestDocument = Guest & Document; export type GuestDocument = Guest & Document;
@Schema({ collection: 'guests' }) @Schema({ collection: 'guests' })
export class Guest { export class Guest {
@Prop() @Prop()
name: string; name: string;
@ -36,5 +34,4 @@ export class Guest {
// ver los invitados de x comunidad // ver los invitados de x comunidad
} }
export const GuestSchema = SchemaFactory.createForClass(Guest); export const GuestSchema = SchemaFactory.createForClass(Guest);

View File

@ -6,6 +6,6 @@ export class AppController {
@Get() @Get()
getHello(): string { getHello(): string {
return "hola"; return 'hola';
} }
} }

View File

@ -1,14 +1,13 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { AppController } from './app.controller'; import { AppController } from './app.controller';
import { MailerModule } from '@nestjs-modules/mailer'; import { MailerModule } from '@nestjs-modules/mailer';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
import { AuthModule } from './auth/auth.module'; import { AuthModule } from './auth/auth.module';
import { EmailController } from './email.controller'; import { EmailController } from './email.controller';
import { join } from 'path'; import { join } from 'path';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter'; import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';
import { ConfigModule, ConfigService } from '@nestjs/config'; import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({ @Module({
imports: [ imports: [
MailerModule.forRootAsync({ MailerModule.forRootAsync({
@ -42,15 +41,16 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
}), }),
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_NOTIFICACIONES", name: 'SERVICIO_NOTIFICACIONES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3009 port: 3009,
} },
} },
]), ]),
AuthModule], AuthModule,
],
controllers: [AppController, EmailController], controllers: [AppController, EmailController],
providers: [], providers: [],
}) })

View File

@ -3,7 +3,6 @@ import { User } from './../user/user.entity';
@Injectable() @Injectable()
export class AuthService { export class AuthService {
async signUp(user: User) { async signUp(user: User) {
const token = Math.floor(1000 + Math.random() * 9000).toString(); const token = Math.floor(1000 + Math.random() * 9000).toString();
// create user in db // create user in db

View File

@ -10,10 +10,9 @@ export class EmailController {
@MessagePattern({ cmd: 'sendMail' }) @MessagePattern({ cmd: 'sendMail' })
sendMail(@Payload() toEmail: string) { sendMail(@Payload() toEmail: string) {
var response = this.mailService.sendMail({ var response = this.mailService.sendMail({
to: toEmail["email"], to: toEmail['email'],
from: "mbonilla.guti@gmail.com", from: 'mbonilla.guti@gmail.com',
subject: 'Plain Text Email ✔', subject: 'Plain Text Email ✔',
text: 'Welcome NestJS Email Sending Tutorial', text: 'Welcome NestJS Email Sending Tutorial',
}); });
@ -22,24 +21,24 @@ export class EmailController {
@MessagePattern({ cmd: 'html' }) @MessagePattern({ cmd: 'html' })
async postHTMLEmail(@Payload() user: any) { async postHTMLEmail(@Payload() user: any) {
const url = "http://localhost:3000/"; const url = 'http://localhost:3000/';
const image = "images/email.ong"; const image = 'images/email.ong';
var response = await this.mailService.sendMail({ var response = await this.mailService.sendMail({
to: user["email"], to: user['email'],
from: "mbonilla.guti@gmail.com", from: 'mbonilla.guti@gmail.com',
subject: 'HTML Dynamic Template', subject: 'HTML Dynamic Template',
template: 'templateEmail', template: 'templateEmail',
context: { context: {
name: user["name"], name: user['name'],
url url,
}, },
attachments: [ attachments: [
{ {
filename: 'email.png', filename: 'email.png',
path: __dirname + '/mails/images/email.png', path: __dirname + '/mails/images/email.png',
cid: 'logo' //my mistake was putting "cid:logo@cid" here! cid: 'logo', //my mistake was putting "cid:logo@cid" here!
} },
] ],
}); });
return response; return response;
} }

View File

@ -1,7 +1,7 @@
import { NestFactory } from "@nestjs/core"; import { NestFactory } from '@nestjs/core';
import { Transport } from "@nestjs/microservices"; import { Transport } from '@nestjs/microservices';
import { AppModule } from "./app.module"; import { AppModule } from './app.module';
import { Logger } from "@nestjs/common"; import { Logger } from '@nestjs/common';
const logger = new Logger(); const logger = new Logger();
@ -9,10 +9,12 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, { const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3009 port: 3009,
} },
}); });
app.listen().then(() => logger.log("Microservice Notificaciones is listening" )); app
.listen()
.then(() => logger.log('Microservice Notificaciones is listening'));
} }
bootstrap(); bootstrap();

View File

@ -25,7 +25,10 @@ export class NotificationsController {
@MessagePattern({ cmd: 'updateNotification' }) @MessagePattern({ cmd: 'updateNotification' })
update(@Payload() updateNotificationDto: UpdateNotificationDto) { update(@Payload() updateNotificationDto: UpdateNotificationDto) {
return this.notificationsService.update(updateNotificationDto.id, updateNotificationDto); return this.notificationsService.update(
updateNotificationDto.id,
updateNotificationDto,
);
} }
@MessagePattern({ cmd: 'removeNotification' }) @MessagePattern({ cmd: 'removeNotification' })

View File

@ -4,6 +4,6 @@ import { NotificationsController } from './notifications.controller';
@Module({ @Module({
controllers: [NotificationsController], controllers: [NotificationsController],
providers: [NotificationsService] providers: [NotificationsService],
}) })
export class NotificationsModule {} export class NotificationsModule {}

View File

@ -1,23 +1,25 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { PaymentsModule } from './payments/payments.module'; import { PaymentsModule } from './payments/payments.module';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
@Module({ @Module({
imports: [ imports: [
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_PAGOS", name: 'SERVICIO_PAGOS',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3005 port: 3005,
} },
} },
]), ]),
MongooseModule.forRoot(`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_pagos?retryWrites=true&w=majority`), MongooseModule.forRoot(
PaymentsModule], `mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_pagos?retryWrites=true&w=majority`,
),
PaymentsModule,
],
controllers: [], controllers: [],
providers: [], providers: [],
}) })

View File

@ -1,7 +1,7 @@
import { NestFactory } from "@nestjs/core"; import { NestFactory } from '@nestjs/core';
import { Transport } from "@nestjs/microservices"; import { Transport } from '@nestjs/microservices';
import { AppModule } from "./app.module"; import { AppModule } from './app.module';
import { Logger } from "@nestjs/common"; import { Logger } from '@nestjs/common';
const logger = new Logger(); const logger = new Logger();
@ -9,10 +9,10 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, { const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3005 port: 3005,
} },
}); });
app.listen().then(() => logger.log("Microservice Invitados is listening" )); app.listen().then(() => logger.log('Microservice Invitados is listening'));
} }
bootstrap(); bootstrap();

View File

@ -4,12 +4,11 @@ import { PaymentsController } from './payments.controller';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { Payment, PaymentSchema } from 'src/schemas/payment.schema'; import { Payment, PaymentSchema } from 'src/schemas/payment.schema';
@Module({ @Module({
imports: [ imports: [
MongooseModule.forFeature([{ name: Payment.name, schema: PaymentSchema }]), MongooseModule.forFeature([{ name: Payment.name, schema: PaymentSchema }]),
], ],
controllers: [PaymentsController], controllers: [PaymentsController],
providers: [PaymentsService] providers: [PaymentsService],
}) })
export class PaymentsModule {} export class PaymentsModule {}

View File

@ -3,11 +3,11 @@ import { Payment, PaymentDocument } from 'src/schemas/payment.schema';
import { Model } from 'mongoose'; import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
@Injectable() @Injectable()
export class PaymentsService { export class PaymentsService {
constructor( constructor(
@InjectModel(Payment.name) private readonly paymentModel: Model<PaymentDocument>, @InjectModel(Payment.name)
private readonly paymentModel: Model<PaymentDocument>,
) {} ) {}
async create(payment: PaymentDocument): Promise<Payment> { async create(payment: PaymentDocument): Promise<Payment> {
@ -15,18 +15,13 @@ export class PaymentsService {
} }
async findAll(): Promise<Payment[]> { async findAll(): Promise<Payment[]> {
return this.paymentModel return this.paymentModel.find().setOptions({ sanitizeFilter: true }).exec();
.find()
.setOptions({ sanitizeFilter: true })
.exec();
} }
findOneId(id: string): Promise<Payment> { findOneId(id: string): Promise<Payment> {
return this.paymentModel.findOne({ _id: id }).exec(); return this.paymentModel.findOne({ _id: id }).exec();
} }
findByUser(id: string): Promise<Payment> { findByUser(id: string): Promise<Payment> {
return this.paymentModel.findOne({ user_id: id }).exec(); return this.paymentModel.findOne({ user_id: id }).exec();
} }

View File

@ -1,13 +1,10 @@
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose'; import { Document } from 'mongoose';
export type PaymentDocument = Payment & Document; export type PaymentDocument = Payment & Document;
@Schema({ collection: 'payments' }) @Schema({ collection: 'payments' })
export class Payment { export class Payment {
@Prop() @Prop()
date_payment: Date; date_payment: Date;

View File

@ -1,24 +1,25 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ReportsModule } from './reports/reports.module'; import { ReportsModule } from './reports/reports.module';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
@Module({ @Module({
imports: [ imports: [
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_REPORTES", name: 'SERVICIO_REPORTES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3008 port: 3008,
} },
} },
]), ]),
MongooseModule.forRoot(`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_reportes?retryWrites=true&w=majority`), MongooseModule.forRoot(
ReportsModule], `mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_reportes?retryWrites=true&w=majority`,
),
ReportsModule,
],
controllers: [], controllers: [],
providers: [], providers: [],
}) })

View File

@ -1,7 +1,7 @@
import { NestFactory } from "@nestjs/core"; import { NestFactory } from '@nestjs/core';
import { Transport } from "@nestjs/microservices"; import { Transport } from '@nestjs/microservices';
import { AppModule } from "./app.module"; import { AppModule } from './app.module';
import { Logger } from "@nestjs/common"; import { Logger } from '@nestjs/common';
const logger = new Logger(); const logger = new Logger();
@ -9,10 +9,10 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, { const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3008 port: 3008,
} },
}); });
app.listen().then(() => logger.log("Microservice Reportes is listening" )); app.listen().then(() => logger.log('Microservice Reportes is listening'));
} }
bootstrap(); bootstrap();

View File

@ -7,7 +7,6 @@ import { Report, ReportDocument } from '../schemas/report.schema';
export class ReportsController { export class ReportsController {
constructor(private readonly reportsService: ReportsService) {} constructor(private readonly reportsService: ReportsService) {}
@MessagePattern({ cmd: 'createReport' }) @MessagePattern({ cmd: 'createReport' })
create(@Payload() report: ReportDocument) { create(@Payload() report: ReportDocument) {
return this.reportsService.create(report); return this.reportsService.create(report);

View File

@ -9,6 +9,6 @@ import { Report, ReportSchema } from '../schemas/report.schema';
MongooseModule.forFeature([{ name: Report.name, schema: ReportSchema }]), MongooseModule.forFeature([{ name: Report.name, schema: ReportSchema }]),
], ],
controllers: [ReportsController], controllers: [ReportsController],
providers: [ReportsService] providers: [ReportsService],
}) })
export class ReportsModule {} export class ReportsModule {}

View File

@ -1,34 +1,30 @@
import { Injectable, Inject } from '@nestjs/common'; import { Injectable, Inject } from '@nestjs/common';
import { ClientProxy } from "@nestjs/microservices"; import { ClientProxy } from '@nestjs/microservices';
import { Model } from 'mongoose'; import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
import { Report, ReportDocument } from '../schemas/report.schema'; import { Report, ReportDocument } from '../schemas/report.schema';
import { map } from "rxjs/operators"; import { map } from 'rxjs/operators';
@Injectable() @Injectable()
export class ReportsService { export class ReportsService {
constructor( constructor(
@InjectModel(Report.name) private readonly reportModel: Model<ReportDocument>, @InjectModel(Report.name)
private readonly reportModel: Model<ReportDocument>,
// ) //
) { } {}
async create(report: ReportDocument): Promise<Report> { async create(report: ReportDocument): Promise<Report> {
return this.reportModel.create(report); return this.reportModel.create(report);
} }
async findAll(): Promise<Report[]> { async findAll(): Promise<Report[]> {
return this.reportModel return this.reportModel.find().setOptions({ sanitizeFilter: true }).exec();
.find()
.setOptions({ sanitizeFilter: true })
.exec();
} }
async findOne(id: string): Promise<Report> { async findOne(id: string): Promise<Report> {
return this.reportModel.findOne({ _id: id }).exec(); return this.reportModel.findOne({ _id: id }).exec();
} }
async update(id: string, report: ReportDocument) { async update(id: string, report: ReportDocument) {
return this.reportModel.findOneAndUpdate({ _id: id }, report, { return this.reportModel.findOneAndUpdate({ _id: id }, report, {
new: true, new: true,

View File

@ -1,12 +1,10 @@
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document, ObjectId } from 'mongoose'; import { Document, ObjectId } from 'mongoose';
export type ReportDocument = Report & Document; export type ReportDocument = Report & Document;
@Schema({ collection: 'reports' }) @Schema({ collection: 'reports' })
export class Report { export class Report {
@Prop() @Prop()
action: string; action: string;
@ -17,8 +15,7 @@ export class Report {
date_entry: Date; date_entry: Date;
@Prop() @Prop()
user_id: string user_id: string;
} }
export const ReportSchema = SchemaFactory.createForClass(Report); export const ReportSchema = SchemaFactory.createForClass(Report);

View File

@ -1,22 +1,25 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ReservationsModule } from './reservations/reservations.module'; import { ReservationsModule } from './reservations/reservations.module';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
@Module({ @Module({
imports: [ imports: [
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_RESERVACIONES", name: 'SERVICIO_RESERVACIONES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3006 port: 3006,
} },
} },
]), ]),
MongooseModule.forRoot(`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_reservaciones?retryWrites=true&w=majority`), MongooseModule.forRoot(
ReservationsModule], `mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_reservaciones?retryWrites=true&w=majority`,
),
ReservationsModule,
],
controllers: [], controllers: [],
providers: [], providers: [],
}) })

View File

@ -1,7 +1,7 @@
import { NestFactory } from "@nestjs/core"; import { NestFactory } from '@nestjs/core';
import { Transport } from "@nestjs/microservices"; import { Transport } from '@nestjs/microservices';
import { AppModule } from "./app.module"; import { AppModule } from './app.module';
import { Logger } from "@nestjs/common"; import { Logger } from '@nestjs/common';
const logger = new Logger(); const logger = new Logger();
@ -9,10 +9,12 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, { const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3006 port: 3006,
} },
}); });
app.listen().then(() => logger.log("Microservice Reservaciones is listening" )); app
.listen()
.then(() => logger.log('Microservice Reservaciones is listening'));
} }
bootstrap(); bootstrap();

View File

@ -1,7 +1,10 @@
import { Controller } from '@nestjs/common'; import { Controller } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices'; import { MessagePattern, Payload } from '@nestjs/microservices';
import { ReservationsService } from './reservations.service'; import { ReservationsService } from './reservations.service';
import { Reservation, ReservationDocument } from '../schemas/reservation.schema'; import {
Reservation,
ReservationDocument,
} from '../schemas/reservation.schema';
@Controller() @Controller()
export class ReservationsController { export class ReservationsController {

View File

@ -7,9 +7,11 @@ import { Reservation, ReservationSchema} from '../schemas/reservation.schema';
@Module({ @Module({
imports: [ imports: [
MongooseModule.forFeature([{ name: Reservation.name, schema: ReservationSchema }]), MongooseModule.forFeature([
{ name: Reservation.name, schema: ReservationSchema },
]),
], ],
controllers: [ReservationsController], controllers: [ReservationsController],
providers: [ReservationsService] providers: [ReservationsService],
}) })
export class ReservationsModule {} export class ReservationsModule {}

View File

@ -1,12 +1,16 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { Reservation, ReservationDocument} from '../schemas/reservation.schema'; import {
Reservation,
ReservationDocument,
} from '../schemas/reservation.schema';
import { Model } from 'mongoose'; import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
@Injectable() @Injectable()
export class ReservationsService { export class ReservationsService {
constructor( constructor(
@InjectModel(Reservation.name) private readonly reservationModel: Model<ReservationDocument>, @InjectModel(Reservation.name)
private readonly reservationModel: Model<ReservationDocument>,
) {} ) {}
create(reservation: ReservationDocument) { create(reservation: ReservationDocument) {

View File

@ -1,12 +1,10 @@
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document, ObjectId } from 'mongoose'; import { Document, ObjectId } from 'mongoose';
export type ReservationDocument = Reservation & Document; export type ReservationDocument = Reservation & Document;
@Schema({ collection: 'reservations' }) @Schema({ collection: 'reservations' })
export class Reservation { export class Reservation {
@Prop() @Prop()
start_time: string; start_time: string;
@ -23,8 +21,7 @@ export class Reservation {
common_area_id: string; common_area_id: string;
@Prop() @Prop()
user_id: string user_id: string;
} }
export const ReservationSchema = SchemaFactory.createForClass(Reservation); export const ReservationSchema = SchemaFactory.createForClass(Reservation);

View File

@ -1,22 +1,25 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
import { UsersModule } from './users/users.module'; import { UsersModule } from './users/users.module';
@Module({ @Module({
imports: [ imports: [
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_USUARIOS", name: 'SERVICIO_USUARIOS',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3001 port: 3001,
} },
} },
]), ]),
MongooseModule.forRoot(`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_usuarios?retryWrites=true&w=majority`), MongooseModule.forRoot(
UsersModule], `mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_usuarios?retryWrites=true&w=majority`,
),
UsersModule,
],
controllers: [], controllers: [],
providers: [], providers: [],
}) })

View File

@ -1,7 +1,7 @@
import { NestFactory } from "@nestjs/core"; import { NestFactory } from '@nestjs/core';
import { Transport } from "@nestjs/microservices"; import { Transport } from '@nestjs/microservices';
import { AppModule } from "./app.module"; import { AppModule } from './app.module';
import { Logger } from "@nestjs/common"; import { Logger } from '@nestjs/common';
const logger = new Logger(); const logger = new Logger();
@ -9,10 +9,10 @@ async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, { const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3001 port: 3001,
} },
}); });
app.listen().then(() => logger.log("Microservice Usuarios is listening" )); app.listen().then(() => logger.log('Microservice Usuarios is listening'));
} }
bootstrap(); bootstrap();

View File

@ -1,14 +1,10 @@
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose'; import { Document } from 'mongoose';
export type UserDocument = User & Document; export type UserDocument = User & Document;
@Schema({ collection: 'users' }) @Schema({ collection: 'users' })
export class User { export class User {
@Prop() @Prop()
dni: string; dni: string;
@ -36,11 +32,8 @@ export class User {
@Prop() @Prop()
date_entry: Date; date_entry: Date;
@Prop() @Prop()
community_id?: string; community_id?: string;
} }
export const UserSchema = SchemaFactory.createForClass(User); export const UserSchema = SchemaFactory.createForClass(User);

View File

@ -22,7 +22,6 @@ export class UsersController {
return this.userService.create(user); return this.userService.create(user);
} }
@MessagePattern({ cmd: 'findAllUsers' }) @MessagePattern({ cmd: 'findAllUsers' })
findAll() { findAll() {
return this.userService.findAll(); return this.userService.findAll();
@ -40,7 +39,6 @@ export class UsersController {
return this.userService.findGuardsCommunity(pcommunity_id); return this.userService.findGuardsCommunity(pcommunity_id);
} }
@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);
@ -81,15 +79,16 @@ export class UsersController {
//buscar usuario de una comunidad //buscar usuario de una comunidad
@MessagePattern({ cmd: 'findOneCommunityUser' }) @MessagePattern({ cmd: 'findOneCommunityUser' })
findCommunityUser(@Payload() user: any) { findCommunityUser(@Payload() user: any) {
return this.userService.findCommunityUser(user["community_id"], user["user_type"]); return this.userService.findCommunityUser(
user['community_id'],
user['user_type'],
);
} }
@MessagePattern({ cmd: 'deleteAdminSystem' }) @MessagePattern({ cmd: 'deleteAdminSystem' })
deleteAdminSystem(@Payload() user: any) { deleteAdminSystem(@Payload() user: any) {
console.log("entró") console.log('entró');
return this.userService.deleteAdminSystem(user["id"]); return this.userService.deleteAdminSystem(user['id']);
} }
} }

View File

@ -4,23 +4,23 @@ import { MongooseModule } from '@nestjs/mongoose';
import { UsersController } from './users.controller'; import { UsersController } from './users.controller';
import { User, UserSchema } from '../schemas/user.schema'; import { User, UserSchema } from '../schemas/user.schema';
import { ClientsModule, Transport } from "@nestjs/microservices"; import { ClientsModule, Transport } from '@nestjs/microservices';
@Module({ @Module({
imports: [ imports: [
ClientsModule.register([ ClientsModule.register([
{ {
name: "SERVICIO_NOTIFICACIONES", name: 'SERVICIO_NOTIFICACIONES',
transport: Transport.TCP, transport: Transport.TCP,
options: { options: {
host: "127.0.0.1", host: '127.0.0.1',
port: 3009 port: 3009,
} },
} },
]), ]),
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]), MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
], ],
controllers: [UsersController], controllers: [UsersController],
providers: [UsersService] providers: [UsersService],
}) })
export class UsersModule {} export class UsersModule {}

View File

@ -2,19 +2,17 @@ import { Injectable, Inject } from '@nestjs/common';
import { Model } from 'mongoose'; import { Model } from 'mongoose';
import { User, UserDocument } from '../schemas/user.schema'; import { User, UserDocument } from '../schemas/user.schema';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
import { Md5 } from "md5-typescript"; import { Md5 } from 'md5-typescript';
import { map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import { RpcException, ClientProxy } from '@nestjs/microservices'; import { RpcException, ClientProxy } from '@nestjs/microservices';
@Injectable() @Injectable()
export class UsersService { export class UsersService {
constructor( constructor(
@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,
) {} ) {}
private publicKey: string; private publicKey: string;
async create(user: UserDocument): Promise<User> { async create(user: UserDocument): Promise<User> {
@ -24,10 +22,7 @@ export class UsersService {
} }
async findAll(): Promise<User[]> { async findAll(): Promise<User[]> {
return this.userModel return this.userModel.find().setOptions({ sanitizeFilter: true }).exec();
.find()
.setOptions({ sanitizeFilter: true })
.exec();
} }
async findOne(id: string): Promise<User> { async findOne(id: string): Promise<User> {
return this.userModel.findOne({ _id: id }).exec(); return this.userModel.findOne({ _id: id }).exec();
@ -56,13 +51,11 @@ export class UsersService {
repo.find({ email: email }).exec((err, res) => { repo.find({ email: email }).exec((err, res) => {
if (err) { if (err) {
reject(err); reject(err);
} } else {
else {
let passwordEncriptada = Md5.init(password); let passwordEncriptada = Md5.init(password);
if (res[0].password == passwordEncriptada) { if (res[0].password == passwordEncriptada) {
resolve(res[0]); resolve(res[0]);
} } else {
else {
resolve(null); resolve(null);
} }
} }
@ -77,7 +70,6 @@ export class UsersService {
return this.userModel.find({ user_type: 1 }).exec(); return this.userModel.find({ user_type: 1 }).exec();
} }
//find admin del sistema //find admin del sistema
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();
@ -87,11 +79,10 @@ export class UsersService {
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;
this.userModel.create(user) this.userModel.create(user);
/*.then(() => { /*.then(() => {
} );*/ } );*/
@ -100,17 +91,19 @@ export class UsersService {
const payload = { email: user['email'], name: user['name'] }; const payload = { email: user['email'], name: user['name'] };
return this.clientNotificationtApp return this.clientNotificationtApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe( .pipe(map((message: string) => ({ message })));
map((message: string) => ({ message })),
);
} }
async findCommunityUser(community_id: string, user_type: number): Promise<User> { async findCommunityUser(
return this.userModel.findOne({ community_id: community_id, user_type: user_type }).exec(); community_id: string,
user_type: number,
): Promise<User> {
return this.userModel
.findOne({ community_id: community_id, user_type: user_type })
.exec();
} }
async deleteAdminSystem(id: string) { async deleteAdminSystem(id: string) {
return this.userModel.deleteOne({ _id: id }).exec(); return this.userModel.deleteOne({ _id: id }).exec();
} }
} }

View File

@ -54,7 +54,7 @@ import {PrimeIcons} from 'primereact/api';
const App = () => { const App = () => {
const [layoutMode, setLayoutMode] = useState('static'); const [layoutMode, setLayoutMode] = useState('static');
const [layoutColorMode, setLayoutColorMode] = useState('light') const [layoutColorMode, setLayoutColorMode] = useState('light');
const [inputStyle, setInputStyle] = useState('outlined'); const [inputStyle, setInputStyle] = useState('outlined');
const [ripple, setRipple] = useState(true); const [ripple, setRipple] = useState(true);
const [staticMenuInactive, setStaticMenuInactive] = useState(false); const [staticMenuInactive, setStaticMenuInactive] = useState(false);
@ -71,32 +71,34 @@ const App = () => {
useEffect(() => { useEffect(() => {
if (mobileMenuActive) { if (mobileMenuActive) {
addClass(document.body, "body-overflow-hidden"); addClass(document.body, 'body-overflow-hidden');
} else { } else {
removeClass(document.body, "body-overflow-hidden"); removeClass(document.body, 'body-overflow-hidden');
} }
}, [mobileMenuActive]); }, [mobileMenuActive]);
useEffect(() => { useEffect(() => {
copyTooltipRef && copyTooltipRef.current && copyTooltipRef.current.updateTargetEvents(); copyTooltipRef &&
copyTooltipRef.current &&
copyTooltipRef.current.updateTargetEvents();
}, [location]); }, [location]);
const onInputStyleChange = (inputStyle) => { const onInputStyleChange = (inputStyle) => {
setInputStyle(inputStyle); setInputStyle(inputStyle);
} };
const onRipple = (e) => { const onRipple = (e) => {
PrimeReact.ripple = e.value; PrimeReact.ripple = e.value;
setRipple(e.value) setRipple(e.value);
} };
const onLayoutModeChange = (mode) => { const onLayoutModeChange = (mode) => {
setLayoutMode(mode) setLayoutMode(mode);
} };
const onColorModeChange = (mode) => { const onColorModeChange = (mode) => {
setLayoutColorMode(mode) setLayoutColorMode(mode);
} };
const onWrapperClick = (event) => { const onWrapperClick = (event) => {
if (!menuClick) { if (!menuClick) {
@ -110,7 +112,7 @@ const App = () => {
mobileTopbarMenuClick = false; mobileTopbarMenuClick = false;
menuClick = false; menuClick = false;
} };
const onToggleMenuClick = (event) => { const onToggleMenuClick = (event) => {
menuClick = true; menuClick = true;
@ -123,186 +125,254 @@ const App = () => {
setOverlayMenuActive((prevState) => !prevState); setOverlayMenuActive((prevState) => !prevState);
setMobileMenuActive(false); setMobileMenuActive(false);
} } else if (layoutMode === 'static') {
else if (layoutMode === 'static') {
setStaticMenuInactive((prevState) => !prevState); setStaticMenuInactive((prevState) => !prevState);
} }
} } else {
else {
setMobileMenuActive((prevState) => !prevState); setMobileMenuActive((prevState) => !prevState);
} }
event.preventDefault(); event.preventDefault();
} };
const onSidebarClick = () => { const onSidebarClick = () => {
menuClick = true; menuClick = true;
} };
const onMobileTopbarMenuClick = (event) => { const onMobileTopbarMenuClick = (event) => {
mobileTopbarMenuClick = true; mobileTopbarMenuClick = true;
setMobileTopbarMenuActive((prevState) => !prevState); setMobileTopbarMenuActive((prevState) => !prevState);
event.preventDefault(); event.preventDefault();
} };
const onMobileSubTopbarMenuClick = (event) => { const onMobileSubTopbarMenuClick = (event) => {
mobileTopbarMenuClick = true; mobileTopbarMenuClick = true;
event.preventDefault(); event.preventDefault();
} };
const onMenuItemClick = (event) => { const onMenuItemClick = (event) => {
if (!event.item.items) { if (!event.item.items) {
setOverlayMenuActive(false); setOverlayMenuActive(false);
setMobileMenuActive(false); setMobileMenuActive(false);
} }
} };
const isDesktop = () => { const isDesktop = () => {
return window.innerWidth >= 992; return window.innerWidth >= 992;
} };
const menu = [ const menu = [
{ {
label: 'Home', label: 'Home',
items: [ items: [
{ label: 'Dashboard', icon: 'pi pi-fw pi-home', to: '/' }, { label: 'Dashboard', icon: 'pi pi-fw pi-home', to: '/' },
{label: 'Administradores del sistema', icon: PrimeIcons.USERS, to: '/administradoresSistema'}, {
{label: 'Administradores de comunidad', icon: PrimeIcons.USERS, to: '/administradoresComunidad'}, label: 'Administradores del sistema',
{label: 'Guardas de seguridad', icon: PrimeIcons.LOCK, to: '/guardasSeguridad'}, icon: PrimeIcons.USERS,
{label: 'Comunidadades', icon: PrimeIcons.BUILDING, to: '/comunidadesViviendas'}, to: '/administradoresSistema',
{label: 'Inquilinos', icon: PrimeIcons.USER, to: '/inquilinos'},
{label: 'Log in', icon: 'pi pi-fw pi-id-card', to: '/logIn'}
]
}, },
{ {
label: 'UI Components', icon: 'pi pi-fw pi-sitemap', label: 'Administradores de comunidad',
icon: PrimeIcons.USERS,
to: '/administradoresComunidad',
},
{
label: 'Guardas de seguridad',
icon: PrimeIcons.LOCK,
to: '/guardasSeguridad',
},
{
label: 'Comunidadades',
icon: PrimeIcons.BUILDING,
to: '/comunidadesViviendas',
},
{ label: 'Inquilinos', icon: PrimeIcons.USER, to: '/inquilinos' },
{ label: 'Log in', icon: 'pi pi-fw pi-id-card', to: '/logIn' },
],
},
{
label: 'UI Components',
icon: 'pi pi-fw pi-sitemap',
items: [ items: [
{ label: 'Form Layout', icon: 'pi pi-fw pi-id-card', to: '/formlayout' }, {
label: 'Form Layout',
icon: 'pi pi-fw pi-id-card',
to: '/formlayout',
},
{ label: 'Input', icon: 'pi pi-fw pi-check-square', to: '/input' }, { label: 'Input', icon: 'pi pi-fw pi-check-square', to: '/input' },
{ label: "Float Label", icon: "pi pi-fw pi-bookmark", to: "/floatlabel" }, {
{ label: "Invalid State", icon: "pi pi-fw pi-exclamation-circle", to: "invalidstate" }, label: 'Float Label',
icon: 'pi pi-fw pi-bookmark',
to: '/floatlabel',
},
{
label: 'Invalid State',
icon: 'pi pi-fw pi-exclamation-circle',
to: 'invalidstate',
},
{ label: 'Button', icon: 'pi pi-fw pi-mobile', to: '/button' }, { label: 'Button', icon: 'pi pi-fw pi-mobile', to: '/button' },
{ label: 'Table', icon: 'pi pi-fw pi-table', to: '/table' }, { label: 'Table', icon: 'pi pi-fw pi-table', to: '/table' },
{ label: 'List', icon: 'pi pi-fw pi-list', to: '/list' }, { label: 'List', icon: 'pi pi-fw pi-list', to: '/list' },
{ label: 'Tree', icon: 'pi pi-fw pi-share-alt', to: '/tree' }, { label: 'Tree', icon: 'pi pi-fw pi-share-alt', to: '/tree' },
{ label: 'Panel', icon: 'pi pi-fw pi-tablet', to: '/panel' }, { label: 'Panel', icon: 'pi pi-fw pi-tablet', to: '/panel' },
{ label: 'Overlay', icon: 'pi pi-fw pi-clone', to: '/overlay' }, { label: 'Overlay', icon: 'pi pi-fw pi-clone', to: '/overlay' },
{ label: "Media", icon: "pi pi-fw pi-image", to: "/media" }, { label: 'Media', icon: 'pi pi-fw pi-image', to: '/media' },
{ label: 'Menu', icon: 'pi pi-fw pi-bars', to: '/menu' }, { label: 'Menu', icon: 'pi pi-fw pi-bars', to: '/menu' },
{ label: 'Message', icon: 'pi pi-fw pi-comment', to: '/messages' }, { label: 'Message', icon: 'pi pi-fw pi-comment', to: '/messages' },
{ label: 'File', icon: 'pi pi-fw pi-file', to: '/file' }, { label: 'File', icon: 'pi pi-fw pi-file', to: '/file' },
{ label: 'Chart', icon: 'pi pi-fw pi-chart-bar', to: '/chart' }, { label: 'Chart', icon: 'pi pi-fw pi-chart-bar', to: '/chart' },
{ label: 'Misc', icon: 'pi pi-fw pi-circle-off', to: '/misc' }, { label: 'Misc', icon: 'pi pi-fw pi-circle-off', to: '/misc' },
] ],
}, },
{ {
label: 'UI Blocks', label: 'UI Blocks',
items: [ items: [
{ label: 'Free Blocks', icon: 'pi pi-fw pi-eye', to: '/blocks', badge: "NEW" }, {
{ label: 'All Blocks', icon: 'pi pi-fw pi-globe', url: 'https://www.primefaces.org/primeblocks-react' } label: 'Free Blocks',
] icon: 'pi pi-fw pi-eye',
to: '/blocks',
badge: 'NEW',
},
{
label: 'All Blocks',
icon: 'pi pi-fw pi-globe',
url: 'https://www.primefaces.org/primeblocks-react',
},
],
}, },
{ {
label: 'Icons', label: 'Icons',
items: [ items: [{ label: 'PrimeIcons', icon: 'pi pi-fw pi-prime', to: '/icons' }],
{ label: 'PrimeIcons', icon: 'pi pi-fw pi-prime', to: '/icons' }
]
}, },
{ {
label: 'Pages', icon: 'pi pi-fw pi-clone', label: 'Pages',
icon: 'pi pi-fw pi-clone',
items: [ items: [
{ label: 'Crud', icon: 'pi pi-fw pi-user-edit', to: '/crud' }, { label: 'Crud', icon: 'pi pi-fw pi-user-edit', to: '/crud' },
{ label: 'Timeline', icon: 'pi pi-fw pi-calendar', to: '/timeline' }, { label: 'Timeline', icon: 'pi pi-fw pi-calendar', to: '/timeline' },
{ label: 'Empty', icon: 'pi pi-fw pi-circle-off', to: '/empty' } { label: 'Empty', icon: 'pi pi-fw pi-circle-off', to: '/empty' },
] ],
}, },
{ {
label: 'Menu Hierarchy', icon: 'pi pi-fw pi-search', label: 'Menu Hierarchy',
icon: 'pi pi-fw pi-search',
items: [ items: [
{ {
label: 'Submenu 1', icon: 'pi pi-fw pi-bookmark', label: 'Submenu 1',
icon: 'pi pi-fw pi-bookmark',
items: [ items: [
{ {
label: 'Submenu 1.1', icon: 'pi pi-fw pi-bookmark', label: 'Submenu 1.1',
icon: 'pi pi-fw pi-bookmark',
items: [ items: [
{ label: 'Submenu 1.1.1', icon: 'pi pi-fw pi-bookmark' }, { label: 'Submenu 1.1.1', icon: 'pi pi-fw pi-bookmark' },
{ label: 'Submenu 1.1.2', icon: 'pi pi-fw pi-bookmark' }, { label: 'Submenu 1.1.2', icon: 'pi pi-fw pi-bookmark' },
{ label: 'Submenu 1.1.3', icon: 'pi pi-fw pi-bookmark' }, { label: 'Submenu 1.1.3', icon: 'pi pi-fw pi-bookmark' },
] ],
}, },
{ {
label: 'Submenu 1.2', icon: 'pi pi-fw pi-bookmark', label: 'Submenu 1.2',
icon: 'pi pi-fw pi-bookmark',
items: [ items: [
{ label: 'Submenu 1.2.1', icon: 'pi pi-fw pi-bookmark' }, { label: 'Submenu 1.2.1', icon: 'pi pi-fw pi-bookmark' },
{ label: 'Submenu 1.2.2', icon: 'pi pi-fw pi-bookmark' } { label: 'Submenu 1.2.2', icon: 'pi pi-fw pi-bookmark' },
] ],
}, },
] ],
}, },
{ {
label: 'Submenu 2', icon: 'pi pi-fw pi-bookmark', label: 'Submenu 2',
icon: 'pi pi-fw pi-bookmark',
items: [ items: [
{ {
label: 'Submenu 2.1', icon: 'pi pi-fw pi-bookmark', label: 'Submenu 2.1',
icon: 'pi pi-fw pi-bookmark',
items: [ items: [
{ label: 'Submenu 2.1.1', icon: 'pi pi-fw pi-bookmark' }, { label: 'Submenu 2.1.1', icon: 'pi pi-fw pi-bookmark' },
{ label: 'Submenu 2.1.2', icon: 'pi pi-fw pi-bookmark' }, { label: 'Submenu 2.1.2', icon: 'pi pi-fw pi-bookmark' },
{ label: 'Submenu 2.1.3', icon: 'pi pi-fw pi-bookmark' }, { label: 'Submenu 2.1.3', icon: 'pi pi-fw pi-bookmark' },
] ],
}, },
{ {
label: 'Submenu 2.2', icon: 'pi pi-fw pi-bookmark', label: 'Submenu 2.2',
icon: 'pi pi-fw pi-bookmark',
items: [ items: [
{ label: 'Submenu 2.2.1', icon: 'pi pi-fw pi-bookmark' }, { label: 'Submenu 2.2.1', icon: 'pi pi-fw pi-bookmark' },
{ label: 'Submenu 2.2.2', icon: 'pi pi-fw pi-bookmark' } { label: 'Submenu 2.2.2', icon: 'pi pi-fw pi-bookmark' },
] ],
} },
] ],
} },
] ],
} },
]; ];
const addClass = (element, className) => { const addClass = (element, className) => {
if (element.classList) if (element.classList) element.classList.add(className);
element.classList.add(className); else element.className += ' ' + className;
else };
element.className += ' ' + className;
}
const removeClass = (element, className) => { const removeClass = (element, className) => {
if (element.classList) if (element.classList) element.classList.remove(className);
element.classList.remove(className);
else else
element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); element.className = element.className.replace(
} new RegExp(
'(^|\\b)' + className.split(' ').join('|') + '(\\b|$)',
'gi',
),
' ',
);
};
const wrapperClass = classNames('layout-wrapper', { const wrapperClass = classNames('layout-wrapper', {
'layout-overlay': layoutMode === 'overlay', 'layout-overlay': layoutMode === 'overlay',
'layout-static': layoutMode === 'static', 'layout-static': layoutMode === 'static',
'layout-static-sidebar-inactive': staticMenuInactive && layoutMode === 'static', 'layout-static-sidebar-inactive':
'layout-overlay-sidebar-active': overlayMenuActive && layoutMode === 'overlay', staticMenuInactive && layoutMode === 'static',
'layout-overlay-sidebar-active':
overlayMenuActive && layoutMode === 'overlay',
'layout-mobile-sidebar-active': mobileMenuActive, 'layout-mobile-sidebar-active': mobileMenuActive,
'p-input-filled': inputStyle === 'filled', 'p-input-filled': inputStyle === 'filled',
'p-ripple-disabled': ripple === false, 'p-ripple-disabled': ripple === false,
'layout-theme-light': layoutColorMode === 'light' 'layout-theme-light': layoutColorMode === 'light',
}); });
return ( return (
<div className={wrapperClass} onClick={onWrapperClick}> <div className={wrapperClass} onClick={onWrapperClick}>
<Tooltip ref={copyTooltipRef} target=".block-action-copy" position="bottom" content="Copied to clipboard" event="focus" /> <Tooltip
ref={copyTooltipRef}
target=".block-action-copy"
position="bottom"
content="Copied to clipboard"
event="focus"
/>
<AppTopbar onToggleMenuClick={onToggleMenuClick} layoutColorMode={layoutColorMode} <AppTopbar
mobileTopbarMenuActive={mobileTopbarMenuActive} onMobileTopbarMenuClick={onMobileTopbarMenuClick} onMobileSubTopbarMenuClick={onMobileSubTopbarMenuClick} /> onToggleMenuClick={onToggleMenuClick}
layoutColorMode={layoutColorMode}
mobileTopbarMenuActive={mobileTopbarMenuActive}
onMobileTopbarMenuClick={onMobileTopbarMenuClick}
onMobileSubTopbarMenuClick={onMobileSubTopbarMenuClick}
/>
<div className="layout-sidebar" onClick={onSidebarClick}> <div className="layout-sidebar" onClick={onSidebarClick}>
<AppMenu model={menu} onMenuItemClick={onMenuItemClick} layoutColorMode={layoutColorMode} /> <AppMenu
model={menu}
onMenuItemClick={onMenuItemClick}
layoutColorMode={layoutColorMode}
/>
</div> </div>
<div className="layout-main-container"> <div className="layout-main-container">
<div className="layout-main"> <div className="layout-main">
<Route path="/" exact render={() => <Dashboard colorMode={layoutColorMode} location={location} />} /> <Route
path="/"
exact
render={() => (
<Dashboard colorMode={layoutColorMode} location={location} />
)}
/>
<Route path="/formlayout" component={FormLayoutDemo} /> <Route path="/formlayout" component={FormLayoutDemo} />
<Route path="/input" component={InputDemo} /> <Route path="/input" component={InputDemo} />
<Route path="/floatlabel" component={FloatLabelDemo} /> <Route path="/floatlabel" component={FloatLabelDemo} />
@ -319,14 +389,25 @@ const App = () => {
<Route path="/blocks" component={BlocksDemo} /> <Route path="/blocks" component={BlocksDemo} />
<Route path="/icons" component={IconsDemo} /> <Route path="/icons" component={IconsDemo} />
<Route path="/file" component={FileDemo} /> <Route path="/file" component={FileDemo} />
<Route path="/chart" render={() => <ChartDemo colorMode={layoutColorMode} location={location} />} /> <Route
path="/chart"
render={() => (
<ChartDemo colorMode={layoutColorMode} location={location} />
)}
/>
<Route path="/misc" component={MiscDemo} /> <Route path="/misc" component={MiscDemo} />
<Route path="/timeline" component={TimelineDemo} /> <Route path="/timeline" component={TimelineDemo} />
<Route path="/crud" component={Crud} /> <Route path="/crud" component={Crud} />
<Route path="/empty" component={EmptyPage} /> <Route path="/empty" component={EmptyPage} />
<Route path="/documentation" component={Documentation} /> <Route path="/documentation" component={Documentation} />
<Route path="/administradoresSistema" component={AdministradoresSistema} /> <Route
<Route path="/administradoresComunidad" component={AdministradoresComunidad} /> path="/administradoresSistema"
component={AdministradoresSistema}
/>
<Route
path="/administradoresComunidad"
component={AdministradoresComunidad}
/>
<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} />
@ -336,17 +417,27 @@ const App = () => {
<AppFooter layoutColorMode={layoutColorMode} /> <AppFooter layoutColorMode={layoutColorMode} />
</div> </div>
<AppConfig rippleEffect={ripple} onRippleEffect={onRipple} inputStyle={inputStyle} onInputStyleChange={onInputStyleChange} <AppConfig
layoutMode={layoutMode} onLayoutModeChange={onLayoutModeChange} layoutColorMode={layoutColorMode} onColorModeChange={onColorModeChange} /> rippleEffect={ripple}
onRippleEffect={onRipple}
inputStyle={inputStyle}
onInputStyleChange={onInputStyleChange}
layoutMode={layoutMode}
onLayoutModeChange={onLayoutModeChange}
layoutColorMode={layoutColorMode}
onColorModeChange={onColorModeChange}
/>
<CSSTransition classNames="layout-mask" timeout={{ enter: 200, exit: 200 }} in={mobileMenuActive} unmountOnExit> <CSSTransition
classNames="layout-mask"
timeout={{ enter: 200, exit: 200 }}
in={mobileMenuActive}
unmountOnExit
>
<div className="layout-mask p-component-overlay"></div> <div className="layout-mask p-component-overlay"></div>
</CSSTransition> </CSSTransition>
</div> </div>
); );
};
}
export default App; export default App;

View File

@ -1 +0,0 @@

View File

@ -2,10 +2,9 @@ import React, { useCallback, useEffect, useRef, useState } from 'react';
import { RadioButton } from 'primereact/radiobutton'; import { RadioButton } from 'primereact/radiobutton';
import { InputSwitch } from 'primereact/inputswitch'; import { InputSwitch } from 'primereact/inputswitch';
import classNames from 'classnames'; import classNames from 'classnames';
import { Button } from "primereact/button"; import { Button } from 'primereact/button';
export const AppConfig = (props) => { export const AppConfig = (props) => {
const [active, setActive] = useState(false); const [active, setActive] = useState(false);
const [scale, setScale] = useState(14); const [scale, setScale] = useState(14);
const [scales] = useState([12, 13, 14, 15, 16]); const [scales] = useState([12, 13, 14, 15, 16]);
@ -20,11 +19,14 @@ export const AppConfig = (props) => {
} }
}, []); }, []);
const hideConfigurator = useCallback((event) => { const hideConfigurator = useCallback(
(event) => {
setActive(false); setActive(false);
unbindOutsideClickListener(); unbindOutsideClickListener();
event.preventDefault(); event.preventDefault();
}, [unbindOutsideClickListener]); },
[unbindOutsideClickListener],
);
const bindOutsideClickListener = useCallback(() => { const bindOutsideClickListener = useCallback(() => {
if (!outsideClickListener.current) { if (!outsideClickListener.current) {
@ -39,36 +41,38 @@ export const AppConfig = (props) => {
useEffect(() => { useEffect(() => {
if (active) { if (active) {
bindOutsideClickListener() bindOutsideClickListener();
} } else {
else { unbindOutsideClickListener();
unbindOutsideClickListener()
} }
}, [active, bindOutsideClickListener, unbindOutsideClickListener]); }, [active, bindOutsideClickListener, unbindOutsideClickListener]);
const isOutsideClicked = (event) => { const isOutsideClicked = (event) => {
return !(config.current.isSameNode(event.target) || config.current.contains(event.target)); return !(
} config.current.isSameNode(event.target) ||
config.current.contains(event.target)
);
};
const decrementScale = () => { const decrementScale = () => {
setScale((prevState) => --prevState); setScale((prevState) => --prevState);
} };
const incrementScale = () => { const incrementScale = () => {
setScale((prevState) => ++prevState); setScale((prevState) => ++prevState);
} };
useEffect(() => { useEffect(() => {
document.documentElement.style.fontSize = scale + 'px'; document.documentElement.style.fontSize = scale + 'px';
}, [scale]) }, [scale]);
const toggleConfigurator = (event) => { const toggleConfigurator = (event) => {
setActive(prevState => !prevState); setActive((prevState) => !prevState);
} };
const configClassName = classNames('layout-config', { const configClassName = classNames('layout-config', {
'layout-config-active': active 'layout-config-active': active,
}) });
const replaceLink = useCallback((linkElement, href, callback) => { const replaceLink = useCallback((linkElement, href, callback) => {
if (isIE()) { if (isIE()) {
@ -77,15 +81,17 @@ export const AppConfig = (props) => {
if (callback) { if (callback) {
callback(); callback();
} }
} } else {
else {
const id = linkElement.getAttribute('id'); const id = linkElement.getAttribute('id');
const cloneLinkElement = linkElement.cloneNode(true); const cloneLinkElement = linkElement.cloneNode(true);
cloneLinkElement.setAttribute('href', href); cloneLinkElement.setAttribute('href', href);
cloneLinkElement.setAttribute('id', id + '-clone'); cloneLinkElement.setAttribute('id', id + '-clone');
linkElement.parentNode.insertBefore(cloneLinkElement, linkElement.nextSibling); linkElement.parentNode.insertBefore(
cloneLinkElement,
linkElement.nextSibling,
);
cloneLinkElement.addEventListener('load', () => { cloneLinkElement.addEventListener('load', () => {
linkElement.remove(); linkElement.remove();
@ -96,66 +102,115 @@ export const AppConfig = (props) => {
} }
}); });
} }
}, []) }, []);
useEffect(() => { useEffect(() => {
let themeElement = document.getElementById('theme-link'); let themeElement = document.getElementById('theme-link');
const themeHref = 'assets/themes/' + theme + '/theme.css'; const themeHref = 'assets/themes/' + theme + '/theme.css';
replaceLink(themeElement, themeHref); replaceLink(themeElement, themeHref);
}, [theme, replaceLink]);
}, [theme, replaceLink])
const isIE = () => { const isIE = () => {
return /(MSIE|Trident\/|Edge\/)/i.test(window.navigator.userAgent) return /(MSIE|Trident\/|Edge\/)/i.test(window.navigator.userAgent);
} };
const changeTheme = (e, theme, scheme) => { const changeTheme = (e, theme, scheme) => {
props.onColorModeChange(scheme); props.onColorModeChange(scheme);
setTheme(theme); setTheme(theme);
} };
return ( return (
<div ref={config} className={configClassName} id={"layout-config"}> <div ref={config} className={configClassName} id={'layout-config'}>
<button className="layout-config-button p-link" id="layout-config-button" onClick={toggleConfigurator}> <button
className="layout-config-button p-link"
id="layout-config-button"
onClick={toggleConfigurator}
>
<i className="pi pi-cog"></i> <i className="pi pi-cog"></i>
</button> </button>
<Button className="p-button-danger layout-config-close p-button-rounded p-button-text" icon="pi pi-times" onClick={hideConfigurator} /> <Button
className="p-button-danger layout-config-close p-button-rounded p-button-text"
icon="pi pi-times"
onClick={hideConfigurator}
/>
<div className="layout-config-content"> <div className="layout-config-content">
<h5 className="mt-0">Component Scale</h5> <h5 className="mt-0">Component Scale</h5>
<div className="config-scale"> <div className="config-scale">
<Button icon="pi pi-minus" onClick={decrementScale} className="p-button-text" disabled={scale === scales[0]} /> <Button
{ icon="pi pi-minus"
scales.map((item) => { onClick={decrementScale}
return <i className={classNames('pi pi-circle-on', { 'scale-active': item === scale })} key={item} /> className="p-button-text"
}) disabled={scale === scales[0]}
} />
<Button icon="pi pi-plus" onClick={incrementScale} className="p-button-text" disabled={scale === scales[scales.length - 1]} /> {scales.map((item) => {
return (
<i
className={classNames('pi pi-circle-on', {
'scale-active': item === scale,
})}
key={item}
/>
);
})}
<Button
icon="pi pi-plus"
onClick={incrementScale}
className="p-button-text"
disabled={scale === scales[scales.length - 1]}
/>
</div> </div>
<h5>Input Style</h5> <h5>Input Style</h5>
<div className="p-formgroup-inline"> <div className="p-formgroup-inline">
<div className="field-radiobutton"> <div className="field-radiobutton">
<RadioButton inputId="input_outlined" name="inputstyle" value="outlined" onChange={(e) => props.onInputStyleChange(e.value)} checked={props.inputStyle === 'outlined'} /> <RadioButton
inputId="input_outlined"
name="inputstyle"
value="outlined"
onChange={(e) => props.onInputStyleChange(e.value)}
checked={props.inputStyle === 'outlined'}
/>
<label htmlFor="input_outlined">Outlined</label> <label htmlFor="input_outlined">Outlined</label>
</div> </div>
<div className="field-radiobutton"> <div className="field-radiobutton">
<RadioButton inputId="input_filled" name="inputstyle" value="filled" onChange={(e) => props.onInputStyleChange(e.value)} checked={props.inputStyle === 'filled'} /> <RadioButton
inputId="input_filled"
name="inputstyle"
value="filled"
onChange={(e) => props.onInputStyleChange(e.value)}
checked={props.inputStyle === 'filled'}
/>
<label htmlFor="input_filled">Filled</label> <label htmlFor="input_filled">Filled</label>
</div> </div>
</div> </div>
<h5>Ripple Effect</h5> <h5>Ripple Effect</h5>
<InputSwitch checked={props.rippleEffect} onChange={props.onRippleEffect} /> <InputSwitch
checked={props.rippleEffect}
onChange={props.onRippleEffect}
/>
<h5>Menu Type</h5> <h5>Menu Type</h5>
<div className="p-formgroup-inline"> <div className="p-formgroup-inline">
<div className="field-radiobutton"> <div className="field-radiobutton">
<RadioButton inputId="static" name="layoutMode" value="static" onChange={(e) => props.onLayoutModeChange(e.value)} checked={props.layoutMode === 'static'} /> <RadioButton
inputId="static"
name="layoutMode"
value="static"
onChange={(e) => props.onLayoutModeChange(e.value)}
checked={props.layoutMode === 'static'}
/>
<label htmlFor="static">Static</label> <label htmlFor="static">Static</label>
</div> </div>
<div className="field-radiobutton"> <div className="field-radiobutton">
<RadioButton inputId="overlay" name="layoutMode" value="overlay" onChange={(e) => props.onLayoutModeChange(e.value)} checked={props.layoutMode === 'overlay'} /> <RadioButton
inputId="overlay"
name="layoutMode"
value="overlay"
onChange={(e) => props.onLayoutModeChange(e.value)}
checked={props.layoutMode === 'overlay'}
/>
<label htmlFor="overlay">Overlay</label> <label htmlFor="overlay">Overlay</label>
</div> </div>
</div> </div>
@ -164,23 +219,49 @@ export const AppConfig = (props) => {
<h6 className="mt-0">Bootstrap</h6> <h6 className="mt-0">Bootstrap</h6>
<div className="grid free-themes"> <div className="grid free-themes">
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'bootstrap4-light-blue', 'light')}> <button
<img src="assets/layout/images/themes/bootstrap4-light-blue.svg" alt="Bootstrap Light Blue" /> className="p-link"
onClick={(e) => changeTheme(e, 'bootstrap4-light-blue', 'light')}
>
<img
src="assets/layout/images/themes/bootstrap4-light-blue.svg"
alt="Bootstrap Light Blue"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'bootstrap4-light-purple', 'light')}> <button
<img src="assets/layout/images/themes/bootstrap4-light-purple.svg" alt="Bootstrap Light Purple" /> className="p-link"
onClick={(e) =>
changeTheme(e, 'bootstrap4-light-purple', 'light')
}
>
<img
src="assets/layout/images/themes/bootstrap4-light-purple.svg"
alt="Bootstrap Light Purple"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'bootstrap4-dark-blue', 'dark')}> <button
<img src="assets/layout/images/themes/bootstrap4-dark-blue.svg" alt="Bootstrap Dark Blue" /> className="p-link"
onClick={(e) => changeTheme(e, 'bootstrap4-dark-blue', 'dark')}
>
<img
src="assets/layout/images/themes/bootstrap4-dark-blue.svg"
alt="Bootstrap Dark Blue"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'bootstrap4-dark-purple', 'dark')}> <button
<img src="assets/layout/images/themes/bootstrap4-dark-purple.svg" alt="Bootstrap Dark Purple" /> className="p-link"
onClick={(e) => changeTheme(e, 'bootstrap4-dark-purple', 'dark')}
>
<img
src="assets/layout/images/themes/bootstrap4-dark-purple.svg"
alt="Bootstrap Dark Purple"
/>
</button> </button>
</div> </div>
</div> </div>
@ -188,28 +269,58 @@ export const AppConfig = (props) => {
<h6>Material Design</h6> <h6>Material Design</h6>
<div className="grid free-themes"> <div className="grid free-themes">
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'md-light-indigo', 'light')}> <button
<img src="assets/layout/images/themes/md-light-indigo.svg" alt="Material Light Indigo" /> className="p-link"
onClick={(e) => changeTheme(e, 'md-light-indigo', 'light')}
>
<img
src="assets/layout/images/themes/md-light-indigo.svg"
alt="Material Light Indigo"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'md-light-indigo', 'light')}> <button
<img src="assets/layout/images/themes/md-light-indigo.svg" alt="Material Light Indigo" /> className="p-link"
onClick={(e) => changeTheme(e, 'md-light-indigo', 'light')}
>
<img
src="assets/layout/images/themes/md-light-indigo.svg"
alt="Material Light Indigo"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'md-light-deeppurple', 'light')}> <button
<img src="assets/layout/images/themes/md-light-deeppurple.svg" alt="Material Light DeepPurple" /> className="p-link"
onClick={(e) => changeTheme(e, 'md-light-deeppurple', 'light')}
>
<img
src="assets/layout/images/themes/md-light-deeppurple.svg"
alt="Material Light DeepPurple"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'md-dark-indigo', 'dark')}> <button
<img src="assets/layout/images/themes/md-dark-indigo.svg" alt="Material Dark Indigo" /> className="p-link"
onClick={(e) => changeTheme(e, 'md-dark-indigo', 'dark')}
>
<img
src="assets/layout/images/themes/md-dark-indigo.svg"
alt="Material Dark Indigo"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'md-dark-deeppurple', 'dark')}> <button
<img src="assets/layout/images/themes/md-dark-deeppurple.svg" alt="Material Dark DeepPurple" /> className="p-link"
onClick={(e) => changeTheme(e, 'md-dark-deeppurple', 'dark')}
>
<img
src="assets/layout/images/themes/md-dark-deeppurple.svg"
alt="Material Dark DeepPurple"
/>
</button> </button>
</div> </div>
</div> </div>
@ -217,23 +328,47 @@ export const AppConfig = (props) => {
<h6>Material Design Compact</h6> <h6>Material Design Compact</h6>
<div className="grid free-themes"> <div className="grid free-themes">
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'mdc-light-indigo', 'light')}> <button
<img src="assets/layout/images/themes/md-light-indigo.svg" alt="Material Light Indigo" /> className="p-link"
onClick={(e) => changeTheme(e, 'mdc-light-indigo', 'light')}
>
<img
src="assets/layout/images/themes/md-light-indigo.svg"
alt="Material Light Indigo"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'mdc-light-deeppurple', 'light')}> <button
<img src="assets/layout/images/themes/md-light-deeppurple.svg" alt="Material Light DeepPurple" /> className="p-link"
onClick={(e) => changeTheme(e, 'mdc-light-deeppurple', 'light')}
>
<img
src="assets/layout/images/themes/md-light-deeppurple.svg"
alt="Material Light DeepPurple"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'mdc-dark-indigo', 'dark')}> <button
<img src="assets/layout/images/themes/md-dark-indigo.svg" alt="Material Dark Indigo" /> className="p-link"
onClick={(e) => changeTheme(e, 'mdc-dark-indigo', 'dark')}
>
<img
src="assets/layout/images/themes/md-dark-indigo.svg"
alt="Material Dark Indigo"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'mdc-dark-deeppurple', 'dark')}> <button
<img src="assets/layout/images/themes/md-dark-deeppurple.svg" alt="Material Dark DeepPurple" /> className="p-link"
onClick={(e) => changeTheme(e, 'mdc-dark-deeppurple', 'dark')}
>
<img
src="assets/layout/images/themes/md-dark-deeppurple.svg"
alt="Material Dark DeepPurple"
/>
</button> </button>
</div> </div>
</div> </div>
@ -241,8 +376,14 @@ export const AppConfig = (props) => {
<h6>Tailwind</h6> <h6>Tailwind</h6>
<div className="grid free-themes"> <div className="grid free-themes">
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'tailwind-light', 'light')}> <button
<img src="assets/layout/images/themes/tailwind-light.png" alt="Tailwind Light" /> className="p-link"
onClick={(e) => changeTheme(e, 'tailwind-light', 'light')}
>
<img
src="assets/layout/images/themes/tailwind-light.png"
alt="Tailwind Light"
/>
</button> </button>
</div> </div>
</div> </div>
@ -250,8 +391,14 @@ export const AppConfig = (props) => {
<h6>Fluent UI</h6> <h6>Fluent UI</h6>
<div className="grid free-themes"> <div className="grid free-themes">
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'fluent-light', 'light')}> <button
<img src="assets/layout/images/themes/fluent-light.png" alt="Fluent Light" /> className="p-link"
onClick={(e) => changeTheme(e, 'fluent-light', 'light')}
>
<img
src="assets/layout/images/themes/fluent-light.png"
alt="Fluent Light"
/>
</button> </button>
</div> </div>
</div> </div>
@ -259,48 +406,102 @@ export const AppConfig = (props) => {
<h6>PrimeOne Design - 2022</h6> <h6>PrimeOne Design - 2022</h6>
<div className="grid free-themes"> <div className="grid free-themes">
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={(e) => changeTheme(e, 'khaki', 'light')}> <button
<img src="assets/layout/images/themes/lara-light-indigo.png" alt="Khaki" /> className="p-link"
onClick={(e) => changeTheme(e, 'khaki', 'light')}
>
<img
src="assets/layout/images/themes/lara-light-indigo.png"
alt="Khaki"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={(e) => changeTheme(e, 'lara-light-indigo', 'light')}> <button
<img src="assets/layout/images/themes/lara-light-indigo.png" alt="Lara Light Indigo" /> className="p-link"
onClick={(e) => changeTheme(e, 'lara-light-indigo', 'light')}
>
<img
src="assets/layout/images/themes/lara-light-indigo.png"
alt="Lara Light Indigo"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={(e) => changeTheme(e, 'lara-light-blue', 'light')}> <button
<img src="assets/layout/images/themes/lara-light-blue.png" alt="Lara Light Blue" /> className="p-link"
onClick={(e) => changeTheme(e, 'lara-light-blue', 'light')}
>
<img
src="assets/layout/images/themes/lara-light-blue.png"
alt="Lara Light Blue"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={(e) => changeTheme(e, 'lara-light-purple', 'light')}> <button
<img src="assets/layout/images/themes/lara-light-purple.png" alt="Lara Light Purple" /> className="p-link"
onClick={(e) => changeTheme(e, 'lara-light-purple', 'light')}
>
<img
src="assets/layout/images/themes/lara-light-purple.png"
alt="Lara Light Purple"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={(e) => changeTheme(e, 'lara-light-teal', 'light')}> <button
<img src="assets/layout/images/themes/lara-light-teal.png" alt="Lara Light Teal" /> className="p-link"
onClick={(e) => changeTheme(e, 'lara-light-teal', 'light')}
>
<img
src="assets/layout/images/themes/lara-light-teal.png"
alt="Lara Light Teal"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={(e) => changeTheme(e, 'lara-dark-indigo', 'dark')}> <button
<img src="assets/layout/images/themes/lara-dark-indigo.png" alt="Lara Dark Indigo" /> className="p-link"
onClick={(e) => changeTheme(e, 'lara-dark-indigo', 'dark')}
>
<img
src="assets/layout/images/themes/lara-dark-indigo.png"
alt="Lara Dark Indigo"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={(e) => changeTheme(e, 'lara-dark-blue', 'dark')}> <button
<img src="assets/layout/images/themes/lara-dark-blue.png" alt="Lara Dark Blue" /> className="p-link"
onClick={(e) => changeTheme(e, 'lara-dark-blue', 'dark')}
>
<img
src="assets/layout/images/themes/lara-dark-blue.png"
alt="Lara Dark Blue"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={(e) => changeTheme(e, 'lara-dark-purple', 'dark')}> <button
<img src="assets/layout/images/themes/lara-dark-purple.png" alt="Lara Dark Purple" /> className="p-link"
onClick={(e) => changeTheme(e, 'lara-dark-purple', 'dark')}
>
<img
src="assets/layout/images/themes/lara-dark-purple.png"
alt="Lara Dark Purple"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={(e) => changeTheme(e, 'lara-dark-teal', 'dark')}> <button
<img src="assets/layout/images/themes/lara-dark-teal.png" alt="Lara Dark Teal" /> className="p-link"
onClick={(e) => changeTheme(e, 'lara-dark-teal', 'dark')}
>
<img
src="assets/layout/images/themes/lara-dark-teal.png"
alt="Lara Dark Teal"
/>
</button> </button>
</div> </div>
</div> </div>
@ -308,68 +509,139 @@ export const AppConfig = (props) => {
<h6>PrimeOne Design - 2021</h6> <h6>PrimeOne Design - 2021</h6>
<div className="grid free-themes"> <div className="grid free-themes">
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'saga-blue', 'light')}> <button
<img src="assets/layout/images/themes/saga-blue.png" alt="Saga Blue" /> className="p-link"
onClick={(e) => changeTheme(e, 'saga-blue', 'light')}
>
<img
src="assets/layout/images/themes/saga-blue.png"
alt="Saga Blue"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'saga-green', 'light')}> <button
<img src="assets/layout/images/themes/saga-green.png" alt="Saga Green" /> className="p-link"
onClick={(e) => changeTheme(e, 'saga-green', 'light')}
>
<img
src="assets/layout/images/themes/saga-green.png"
alt="Saga Green"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'saga-orange', 'light')}> <button
<img src="assets/layout/images/themes/saga-orange.png" alt="Saga Orange" /> className="p-link"
onClick={(e) => changeTheme(e, 'saga-orange', 'light')}
>
<img
src="assets/layout/images/themes/saga-orange.png"
alt="Saga Orange"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'saga-purple', 'light')}> <button
<img src="assets/layout/images/themes/saga-purple.png" alt="Saga Purple" /> className="p-link"
onClick={(e) => changeTheme(e, 'saga-purple', 'light')}
>
<img
src="assets/layout/images/themes/saga-purple.png"
alt="Saga Purple"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'vela-blue', 'dim')}> <button
<img src="assets/layout/images/themes/vela-blue.png" alt="Vela Blue" /> className="p-link"
onClick={(e) => changeTheme(e, 'vela-blue', 'dim')}
>
<img
src="assets/layout/images/themes/vela-blue.png"
alt="Vela Blue"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'vela-green', 'dim')}> <button
<img src="assets/layout/images/themes/vela-green.png" alt="Vela Green" /> className="p-link"
onClick={(e) => changeTheme(e, 'vela-green', 'dim')}
>
<img
src="assets/layout/images/themes/vela-green.png"
alt="Vela Green"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'vela-orange', 'dim')}> <button
<img src="assets/layout/images/themes/vela-orange.png" alt="Vela Orange" /> className="p-link"
onClick={(e) => changeTheme(e, 'vela-orange', 'dim')}
>
<img
src="assets/layout/images/themes/vela-orange.png"
alt="Vela Orange"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'vela-purple', 'dim')}> <button
<img src="assets/layout/images/themes/vela-purple.png" alt="Vela Purple" /> className="p-link"
onClick={(e) => changeTheme(e, 'vela-purple', 'dim')}
>
<img
src="assets/layout/images/themes/vela-purple.png"
alt="Vela Purple"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'arya-blue', 'dark')}> <button
<img src="assets/layout/images/themes/arya-blue.png" alt="Arya Blue" /> className="p-link"
onClick={(e) => changeTheme(e, 'arya-blue', 'dark')}
>
<img
src="assets/layout/images/themes/arya-blue.png"
alt="Arya Blue"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'arya-green', 'dark')}> <button
<img src="assets/layout/images/themes/arya-green.png" alt="Arya Green" /> className="p-link"
onClick={(e) => changeTheme(e, 'arya-green', 'dark')}
>
<img
src="assets/layout/images/themes/arya-green.png"
alt="Arya Green"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'arya-orange', 'dark')}> <button
<img src="assets/layout/images/themes/arya-orange.png" alt="Arya Orange" /> className="p-link"
onClick={(e) => changeTheme(e, 'arya-orange', 'dark')}
>
<img
src="assets/layout/images/themes/arya-orange.png"
alt="Arya Orange"
/>
</button> </button>
</div> </div>
<div className="col-3 text-center"> <div className="col-3 text-center">
<button className="p-link" onClick={e => changeTheme(e, 'arya-purple', 'dark')}> <button
<img src="assets/layout/images/themes/arya-purple.png" alt="Arya Purple" /> className="p-link"
onClick={(e) => changeTheme(e, 'arya-purple', 'dark')}
>
<img
src="assets/layout/images/themes/arya-purple.png"
alt="Arya Purple"
/>
</button> </button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
); );
} };

View File

@ -1,12 +1,20 @@
import React from 'react'; import React from 'react';
export const AppFooter = (props) => { export const AppFooter = (props) => {
return ( return (
<div className="layout-footer"> <div className="layout-footer">
<img src={props.layoutColorMode === 'light' ? 'assets/layout/images/logo-dark.svg' : 'assets/layout/images/logo-white.svg'} alt="Logo" height="20" className="mr-2" /> <img
src={
props.layoutColorMode === 'light'
? 'assets/layout/images/logo-dark.svg'
: 'assets/layout/images/logo-white.svg'
}
alt="Logo"
height="20"
className="mr-2"
/>
by by
<span className="font-medium ml-2">PrimeReact</span> <span className="font-medium ml-2">PrimeReact</span>
</div> </div>
); );
} };

View File

@ -2,12 +2,11 @@ import React, { useState } from 'react';
import { NavLink } from 'react-router-dom'; import { NavLink } from 'react-router-dom';
import { CSSTransition } from 'react-transition-group'; import { CSSTransition } from 'react-transition-group';
import classNames from 'classnames'; import classNames from 'classnames';
import {Ripple} from "primereact/ripple"; import { Ripple } from 'primereact/ripple';
import { Badge } from 'primereact/badge'; import { Badge } from 'primereact/badge';
const AppSubmenu = (props) => { const AppSubmenu = (props) => {
const [activeIndex, setActiveIndex] = useState(null);
const [activeIndex, setActiveIndex] = useState(null)
const onMenuItemClick = (event, item, index) => { const onMenuItemClick = (event, item, index) => {
//avoid processing disabled items //avoid processing disabled items
@ -21,29 +20,29 @@ const AppSubmenu = (props) => {
item.command({ originalEvent: event, item: item }); item.command({ originalEvent: event, item: item });
} }
if (index === activeIndex) if (index === activeIndex) setActiveIndex(null);
setActiveIndex(null); else setActiveIndex(index);
else
setActiveIndex(index);
if (props.onMenuItemClick) { if (props.onMenuItemClick) {
props.onMenuItemClick({ props.onMenuItemClick({
originalEvent: event, originalEvent: event,
item: item item: item,
}); });
} }
} };
const onKeyDown = (event) => { const onKeyDown = (event) => {
if (event.code === 'Enter' || event.code === 'Space') { if (event.code === 'Enter' || event.code === 'Space') {
event.preventDefault(); event.preventDefault();
event.target.click(); event.target.click();
} }
} };
const renderLinkContent = (item) => { const renderLinkContent = (item) => {
let submenuIcon = item.items && <i className="pi pi-fw pi-angle-down menuitem-toggle-icon"></i>; let submenuIcon = item.items && (
let badge = item.badge && <Badge value={item.badge} /> <i className="pi pi-fw pi-angle-down menuitem-toggle-icon"></i>
);
let badge = item.badge && <Badge value={item.badge} />;
return ( return (
<React.Fragment> <React.Fragment>
@ -54,65 +53,124 @@ const AppSubmenu = (props) => {
<Ripple /> <Ripple />
</React.Fragment> </React.Fragment>
); );
} };
const renderLink = (item, i) => { const renderLink = (item, i) => {
let content = renderLinkContent(item); let content = renderLinkContent(item);
if (item.to) { if (item.to) {
return ( return (
<NavLink aria-label={item.label} onKeyDown={onKeyDown} role="menuitem" className="p-ripple" activeClassName="router-link-active router-link-exact-active" to={item.to} onClick={(e) => onMenuItemClick(e, item, i)} exact target={item.target}> <NavLink
aria-label={item.label}
onKeyDown={onKeyDown}
role="menuitem"
className="p-ripple"
activeClassName="router-link-active router-link-exact-active"
to={item.to}
onClick={(e) => onMenuItemClick(e, item, i)}
exact
target={item.target}
>
{content} {content}
</NavLink> </NavLink>
) );
} } else {
else {
return ( return (
<a tabIndex="0" aria-label={item.label} onKeyDown={onKeyDown} role="menuitem" href={item.url} className="p-ripple" onClick={(e) => onMenuItemClick(e, item, i)} target={item.target}> <a
tabIndex="0"
aria-label={item.label}
onKeyDown={onKeyDown}
role="menuitem"
href={item.url}
className="p-ripple"
onClick={(e) => onMenuItemClick(e, item, i)}
target={item.target}
>
{content} {content}
</a> </a>
); );
} }
} };
let items = props.items && props.items.map((item, i) => { let items =
props.items &&
props.items.map((item, i) => {
let active = activeIndex === i; let active = activeIndex === i;
let styleClass = classNames(item.badgeStyleClass, {'layout-menuitem-category': props.root, 'active-menuitem': active && !item.to }); let styleClass = classNames(item.badgeStyleClass, {
'layout-menuitem-category': props.root,
'active-menuitem': active && !item.to,
});
if (props.root) { if (props.root) {
return ( return (
<li className={styleClass} key={i} role="none"> <li className={styleClass} key={i} role="none">
{props.root === true && <React.Fragment> {props.root === true && (
<div className="layout-menuitem-root-text" aria-label={item.label}>{item.label}</div> <React.Fragment>
<AppSubmenu items={item.items} onMenuItemClick={props.onMenuItemClick} /> <div
</React.Fragment>} className="layout-menuitem-root-text"
aria-label={item.label}
>
{item.label}
</div>
<AppSubmenu
items={item.items}
onMenuItemClick={props.onMenuItemClick}
/>
</React.Fragment>
)}
</li> </li>
); );
} } else {
else {
return ( return (
<li className={styleClass} key={i} role="none"> <li className={styleClass} key={i} role="none">
{renderLink(item, i)} {renderLink(item, i)}
<CSSTransition classNames="layout-submenu-wrapper" timeout={{ enter: 1000, exit: 450 }} in={active} unmountOnExit> <CSSTransition
<AppSubmenu items={item.items} onMenuItemClick={props.onMenuItemClick} /> classNames="layout-submenu-wrapper"
timeout={{ enter: 1000, exit: 450 }}
in={active}
unmountOnExit
>
<AppSubmenu
items={item.items}
onMenuItemClick={props.onMenuItemClick}
/>
</CSSTransition> </CSSTransition>
</li> </li>
); );
} }
}); });
return items ? <ul className={props.className} role="menu">{items}</ul> : null; return items ? (
} <ul className={props.className} role="menu">
{items}
</ul>
) : null;
};
export const AppMenu = (props) => { export const AppMenu = (props) => {
return ( return (
<div className="layout-menu-container"> <div className="layout-menu-container">
<AppSubmenu items={props.model} className="layout-menu" onMenuItemClick={props.onMenuItemClick} root={true} role="menu" /> <AppSubmenu
<a href="https://www.primefaces.org/primeblocks-react" className="block mt-3"> items={props.model}
<img alt="primeblocks" className="w-full" className="layout-menu"
src={props.layoutColorMode === 'light' ? 'assets/layout/images/banner-primeblocks.png' : 'assets/layout/images/banner-primeblocks-dark.png'}/> onMenuItemClick={props.onMenuItemClick}
root={true}
role="menu"
/>
<a
href="https://www.primefaces.org/primeblocks-react"
className="block mt-3"
>
<img
alt="primeblocks"
className="w-full"
src={
props.layoutColorMode === 'light'
? 'assets/layout/images/banner-primeblocks.png'
: 'assets/layout/images/banner-primeblocks-dark.png'
}
/>
</a> </a>
</div> </div>
); );
} };

View File

@ -3,7 +3,6 @@ import { Link } from 'react-router-dom';
import classNames from 'classnames'; import classNames from 'classnames';
export const AppTopbar = (props) => { export const AppTopbar = (props) => {
return ( return (
<div className="layout-topbar"> <div className="layout-topbar">
<Link to="/" className="layout-topbar-logo"> <Link to="/" className="layout-topbar-logo">
@ -15,7 +14,10 @@ export const AppTopbar = (props) => {
<i className="pi pi-bars"/> <i className="pi pi-bars"/>
</button> */} </button> */}
<button type="button" className="p-link layout-topbar-menu-button layout-topbar-button" > <button
type="button"
className="p-link layout-topbar-menu-button layout-topbar-button"
>
<i className="pi pi-ellipsis-v" /> <i className="pi pi-ellipsis-v" />
</button> </button>
@ -41,4 +43,4 @@ export const AppTopbar = (props) => {
</ul> </ul>
</div> </div>
); );
} };

View File

@ -3,13 +3,12 @@ import { classNames } from 'primereact/utils';
import { CodeHighlight } from './templates/CodeHighlight'; import { CodeHighlight } from './templates/CodeHighlight';
const BlockViewer = (props) => { const BlockViewer = (props) => {
const [blockView, setBlockView] = useState('PREVIEW');
const [blockView, setBlockView] = useState('PREVIEW')
const copyCode = async (event) => { const copyCode = async (event) => {
await navigator.clipboard.writeText(props.code); await navigator.clipboard.writeText(props.code);
event.preventDefault(); event.preventDefault();
} };
return ( return (
<div className="block-viewer"> <div className="block-viewer">
@ -20,30 +19,47 @@ const BlockViewer = (props) => {
{props.new && <span className="badge-new">New</span>} {props.new && <span className="badge-new">New</span>}
</span> </span>
<div className="block-actions"> <div className="block-actions">
<button tabIndex="0" className={classNames('p-link', { 'block-action-active': blockView === 'PREVIEW' })} onClick={() => setBlockView('PREVIEW')}><span>Preview</span></button> <button
<button className={classNames('p-link', { 'block-action-active': blockView === 'CODE' })} onClick={() => setBlockView('CODE')} > tabIndex="0"
className={classNames('p-link', {
'block-action-active': blockView === 'PREVIEW',
})}
onClick={() => setBlockView('PREVIEW')}
>
<span>Preview</span>
</button>
<button
className={classNames('p-link', {
'block-action-active': blockView === 'CODE',
})}
onClick={() => setBlockView('CODE')}
>
<span>Code</span> <span>Code</span>
</button> </button>
<button tabIndex="0" className="p-link block-action-copy" onClick={copyCode}> <button
tabIndex="0"
className="p-link block-action-copy"
onClick={copyCode}
>
<i className="pi pi-copy"></i> <i className="pi pi-copy"></i>
</button> </button>
</div> </div>
</div> </div>
<div className="block-content"> <div className="block-content">
{blockView === 'PREVIEW' && {blockView === 'PREVIEW' && (
<div className={props.containerClassName} style={props.previewStyle}> <div
className={props.containerClassName}
style={props.previewStyle}
>
{props.children} {props.children}
</div>} </div>
)}
{blockView === 'CODE' && {blockView === 'CODE' && <CodeHighlight>{props.code}</CodeHighlight>}
<CodeHighlight>
{props.code}
</CodeHighlight>
}
</div> </div>
</div> </div>
</div> </div>
) );
} };
export default BlockViewer; export default BlockViewer;

View File

@ -2,14 +2,13 @@ import { useEffect } from 'react';
import { useLocation, withRouter } from 'react-router-dom'; import { useLocation, withRouter } from 'react-router-dom';
const ScrollToTop = (props) => { const ScrollToTop = (props) => {
let location = useLocation(); let location = useLocation();
useEffect(() => { useEffect(() => {
window.scrollTo(0, 0) window.scrollTo(0, 0);
}, [location]); }, [location]);
return props.children; return props.children;
} };
export default withRouter(ScrollToTop); export default withRouter(ScrollToTop);

View File

@ -2,94 +2,94 @@
.product-badge, .product-badge,
.order-badge { .order-badge {
border-radius: var(--border-radius); border-radius: var(--border-radius);
padding: .25em .5rem; padding: 0.25em 0.5rem;
text-transform: uppercase; text-transform: uppercase;
font-weight: 700; font-weight: 700;
font-size: 12px; font-size: 12px;
letter-spacing: .3px; letter-spacing: 0.3px;
} }
.customer-badge { .customer-badge {
&.status-qualified { &.status-qualified {
background: #C8E6C9; background: #c8e6c9;
color: #256029; color: #256029;
} }
&.status-unqualified { &.status-unqualified {
background: #FFCDD2; background: #ffcdd2;
color: #C63737; color: #c63737;
} }
&.status-negotiation { &.status-negotiation {
background: #FEEDAF; background: #feedaf;
color: #8A5340; color: #8a5340;
} }
&.status-new { &.status-new {
background: #B3E5FC; background: #b3e5fc;
color: #23547B; color: #23547b;
} }
&.status-renewal { &.status-renewal {
background: #ECCFFF; background: #eccfff;
color: #694382; color: #694382;
} }
&.status-proposal { &.status-proposal {
background: #FFD8B2; background: #ffd8b2;
color: #805B36; color: #805b36;
} }
} }
.product-badge { .product-badge {
border-radius: var(--border-radius); border-radius: var(--border-radius);
padding: .25em .5rem; padding: 0.25em 0.5rem;
text-transform: uppercase; text-transform: uppercase;
font-weight: 700; font-weight: 700;
font-size: 12px; font-size: 12px;
letter-spacing: .3px; letter-spacing: 0.3px;
&.status-instock { &.status-instock {
background: #C8E6C9; background: #c8e6c9;
color: #256029; color: #256029;
} }
&.status-outofstock { &.status-outofstock {
background: #FFCDD2; background: #ffcdd2;
color: #C63737; color: #c63737;
} }
&.status-lowstock { &.status-lowstock {
background: #FEEDAF; background: #feedaf;
color: #8A5340; color: #8a5340;
} }
} }
.order-badge { .order-badge {
border-radius: var(--border-radius); border-radius: var(--border-radius);
padding: .25em .5rem; padding: 0.25em 0.5rem;
text-transform: uppercase; text-transform: uppercase;
font-weight: 700; font-weight: 700;
font-size: 12px; font-size: 12px;
letter-spacing: .3px; letter-spacing: 0.3px;
&.order-delivered { &.order-delivered {
background: #C8E6C9; background: #c8e6c9;
color: #256029; color: #256029;
} }
&.order-cancelled { &.order-cancelled {
background: #FFCDD2; background: #ffcdd2;
color: #C63737; color: #c63737;
} }
&.order-pending { &.order-pending {
background: #FEEDAF; background: #feedaf;
color: #8A5340; color: #8a5340;
} }
&.order-returned { &.order-returned {
background: #ECCFFF; background: #eccfff;
color: #694382; color: #694382;
} }
} }

View File

@ -21,12 +21,12 @@
.badge-free { .badge-free {
border-radius: 4px; border-radius: 4px;
padding: .25rem .5rem; padding: 0.25rem 0.5rem;
background-color: var(--orange-500); background-color: var(--orange-500);
color: white; color: white;
margin-left: 1rem; margin-left: 1rem;
font-weight: 700; font-weight: 700;
font-size: .875rem; font-size: 0.875rem;
} }
} }
@ -37,15 +37,16 @@
user-select: none; user-select: none;
margin-left: 1rem; margin-left: 1rem;
a,button { a,
button {
display: flex; display: flex;
align-items: center; align-items: center;
margin-right: .75rem; margin-right: 0.75rem;
padding: .5rem 1rem; padding: 0.5rem 1rem;
border-radius: 4px; border-radius: 4px;
font-weight: 600; font-weight: 600;
border: 1px solid transparent; border: 1px solid transparent;
transition: background-color .2s; transition: background-color 0.2s;
cursor: pointer; cursor: pointer;
&:last-child { &:last-child {
@ -70,12 +71,12 @@
} }
&.block-action-disabled { &.block-action-disabled {
opacity: .6; opacity: 0.6;
cursor: auto !important; cursor: auto !important;
} }
i { i {
margin-right: .5rem; margin-right: 0.5rem;
} }
} }
} }
@ -90,10 +91,11 @@
overflow: hidden; overflow: hidden;
} }
pre[class*="language-"] { pre[class*='language-'] {
margin: 0 !important; margin: 0 !important;
&:before, &:after { &:before,
&:after {
display: none !important; display: none !important;
} }
@ -109,16 +111,16 @@
.token { .token {
&.tag, &.tag,
&.keyword { &.keyword {
color: #2196F3 !important; color: #2196f3 !important;
} }
&.attr-name, &.attr-name,
&.attr-string { &.attr-string {
color: #2196F3 !important; color: #2196f3 !important;
} }
&.attr-value { &.attr-value {
color: #4CAF50 !important; color: #4caf50 !important;
} }
&.punctuation { &.punctuation {

View File

@ -1,5 +1,5 @@
.docs { .docs {
i:not([class~="pi"]) { i:not([class~='pi']) {
background-color: transparent; background-color: transparent;
color: #2196f3; color: #2196f3;
font-family: Monaco, courier, monospace; font-family: Monaco, courier, monospace;
@ -7,7 +7,7 @@
font-size: 12px; font-size: 12px;
font-weight: 500; font-weight: 500;
padding: 0 4px; padding: 0 4px;
letter-spacing: .5px; letter-spacing: 0.5px;
font-weight: 600; font-weight: 600;
margin: 0 2px; margin: 0 2px;
display: inline-flex; display: inline-flex;
@ -17,8 +17,9 @@
font-weight: 500; font-weight: 500;
} }
pre[class*="language-"] { pre[class*='language-'] {
&:before, &:after { &:before,
&:after {
display: none !important; display: none !important;
} }
@ -34,16 +35,16 @@
.token { .token {
&.tag, &.tag,
&.keyword { &.keyword {
color: #2196F3 !important; color: #2196f3 !important;
} }
&.attr-name, &.attr-name,
&.attr-string { &.attr-string {
color: #2196F3 !important; color: #2196f3 !important;
} }
&.attr-value { &.attr-value {
color: #4CAF50 !important; color: #4caf50 !important;
} }
&.punctuation { &.punctuation {

View File

@ -11,6 +11,6 @@
.image-text { .image-text {
vertical-align: middle; vertical-align: middle;
margin-left: .5rem; margin-left: 0.5rem;
} }
} }

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,4 @@
/* General */ /* General */
$fontSize: 10px; $fontSize: 10px;
$borderRadius: 12px; $borderRadius: 12px;
$transitionDuration:.2s; $transitionDuration: 0.2s;

View File

@ -1,3 +1,3 @@
@import "./_variables"; @import './_variables';
@import "./sass/_layout"; @import './sass/_layout';
@import "./_overrides"; @import './_overrides';

View File

@ -9,7 +9,8 @@
transform: translateX(100%); transform: translateX(100%);
transition: transform $transitionDuration; transition: transform $transitionDuration;
backface-visibility: hidden; backface-visibility: hidden;
box-shadow: 0px 3px 5px rgba(0,0,0,.02), 0px 0px 2px rgba(0,0,0,.05), 0px 1px 4px rgba(0,0,0,.08) !important; box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.02), 0px 0px 2px rgba(0, 0, 0, 0.05),
0px 1px 4px rgba(0, 0, 0, 0.08) !important;
color: var(--text-color); color: var(--text-color);
background-color: var(--surface-overlay); background-color: var(--surface-overlay);
border-top-left-radius: 12px; border-top-left-radius: 12px;
@ -68,12 +69,12 @@
margin: 1rem 0 2rem 0; margin: 1rem 0 2rem 0;
.p-button { .p-button {
margin-right: .5rem; margin-right: 0.5rem;
} }
i { i {
margin-right: .5rem; margin-right: 0.5rem;
font-size: .75rem; font-size: 0.75rem;
color: var(--text-color-secondary); color: var(--text-color-secondary);
&.scale-active { &.scale-active {
@ -87,7 +88,7 @@
img { img {
width: 2rem; width: 2rem;
border-radius: 4px; border-radius: 4px;
transition: transform .2s; transition: transform 0.2s;
display: block; display: block;
&:hover { &:hover {
@ -96,8 +97,8 @@
} }
span { span {
font-size: .75rem; font-size: 0.75rem;
margin-top: .25rem; margin-top: 0.25rem;
} }
} }
} }

View File

@ -1,11 +1,11 @@
@import "./_mixins"; @import './_mixins';
@import "./_splash"; @import './_splash';
@import "./_main"; @import './_main';
@import "./_topbar"; @import './_topbar';
@import "./_menu"; @import './_menu';
@import "./_config"; @import './_config';
@import "./_content"; @import './_content';
@import "./_footer"; @import './_footer';
@import "./_responsive"; @import './_responsive';
@import "./_utils"; @import './_utils';
@import "./_typography"; @import './_typography';

View File

@ -18,7 +18,8 @@ body {
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
} }
a, button { a,
button {
text-decoration: none; text-decoration: none;
color: var(--primary-color); color: var(--primary-color);
} }

View File

@ -11,7 +11,8 @@
background-color: var(--surface-overlay); background-color: var(--surface-overlay);
border-radius: 12px; border-radius: 12px;
padding: 1.5rem; padding: 1.5rem;
box-shadow: 0px 3px 5px rgba(0,0,0,.02), 0px 0px 2px rgba(0,0,0,.05), 0px 1px 4px rgba(0,0,0,.08) box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.02), 0px 0px 2px rgba(0, 0, 0, 0.05),
0px 1px 4px rgba(0, 0, 0, 0.08);
} }
.layout-menu { .layout-menu {
@ -21,7 +22,7 @@
li { li {
&.layout-menuitem-category { &.layout-menuitem-category {
margin-top: .75rem; margin-top: 0.75rem;
&:first-child { &:first-child {
margin-top: 0; margin-top: 0;
@ -32,8 +33,8 @@
text-transform: uppercase; text-transform: uppercase;
color: var(--surface-900); color: var(--surface-900);
font-weight: 600; font-weight: 600;
margin-bottom: .5rem; margin-bottom: 0.5rem;
font-size: .875rem; font-size: 0.875rem;
} }
a { a {
@ -44,8 +45,8 @@
color: var(--text-color); color: var(--text-color);
transition: color $transitionDuration; transition: color $transitionDuration;
border-radius: $borderRadius; border-radius: $borderRadius;
padding: .75rem 1rem; padding: 0.75rem 1rem;
transition: background-color .15s; transition: background-color 0.15s;
span { span {
margin-left: 0.5rem; margin-left: 0.5rem;

View File

@ -1,13 +1,13 @@
@mixin focused() { @mixin focused() {
outline: 0 none; outline: 0 none;
outline-offset: 0; outline-offset: 0;
transition: box-shadow .2s; transition: box-shadow 0.2s;
box-shadow: var(--focus-ring); box-shadow: var(--focus-ring);
} }
@mixin focused-inset() { @mixin focused-inset() {
outline: 0 none; outline: 0 none;
outline-offset: 0; outline-offset: 0;
transition: box-shadow .2s; transition: box-shadow 0.2s;
box-shadow: inset var(--focus-ring); box-shadow: inset var(--focus-ring);
} }

View File

@ -15,7 +15,8 @@
left: calc(50vw - 75px); left: calc(50vw - 75px);
} }
.preloader-content:before, .preloader-content:after{ .preloader-content:before,
.preloader-content:after {
content: ''; content: '';
border: 1em solid var(--primary-color); border: 1em solid var(--primary-color);
border-radius: 50%; border-radius: 50%;

View File

@ -10,7 +10,8 @@
transition: left $transitionDuration; transition: left $transitionDuration;
display: flex; display: flex;
align-items: center; align-items: center;
box-shadow: 0px 3px 5px rgba(0,0,0,.02), 0px 0px 2px rgba(0,0,0,.05), 0px 1px 4px rgba(0,0,0,.08); box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.02), 0px 0px 2px rgba(0, 0, 0, 0.05),
0px 1px 4px rgba(0, 0, 0, 0.08);
.layout-topbar-logo { .layout-topbar-logo {
display: flex; display: flex;
@ -23,7 +24,7 @@
img { img {
height: 2.5rem; height: 2.5rem;
margin-right: .5rem; margin-right: 0.5rem;
} }
&:focus { &:focus {
@ -111,7 +112,8 @@
position: absolute; position: absolute;
flex-direction: column; flex-direction: column;
background-color: var(--surface-overlay); background-color: var(--surface-overlay);
box-shadow: 0px 3px 5px rgba(0,0,0,.02), 0px 0px 2px rgba(0,0,0,.05), 0px 1px 4px rgba(0,0,0,.08); box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.02),
0px 0px 2px rgba(0, 0, 0, 0.05), 0px 1px 4px rgba(0, 0, 0, 0.08);
border-radius: 12px; border-radius: 12px;
padding: 1rem; padding: 1rem;
right: 2rem; right: 2rem;
@ -122,7 +124,7 @@
animation: scalein 0.15s linear; animation: scalein 0.15s linear;
&.layout-topbar-menu-mobile-active { &.layout-topbar-menu-mobile-active {
display: block display: block;
} }
.layout-topbar-button { .layout-topbar-button {
@ -136,7 +138,7 @@
i { i {
font-size: 1rem; font-size: 1rem;
margin-right: .5rem; margin-right: 0.5rem;
} }
span { span {

View File

@ -1,4 +1,9 @@
h1, h2, h3, h4, h5, h6 { h1,
h2,
h3,
h4,
h5,
h6 {
margin: 1.5rem 0 1rem 0; margin: 1.5rem 0 1rem 0;
font-family: inherit; font-family: inherit;
font-weight: 500; font-weight: 500;
@ -35,8 +40,8 @@ h6 {
} }
mark { mark {
background: #FFF8E1; background: #fff8e1;
padding: .25rem .4rem; padding: 0.25rem 0.4rem;
border-radius: $borderRadius; border-radius: $borderRadius;
font-family: monospace; font-family: monospace;
} }
@ -44,7 +49,7 @@ mark {
blockquote { blockquote {
margin: 1rem 0; margin: 1rem 0;
padding: 0 2rem; padding: 0 2rem;
border-left: 4px solid #90A4AE; border-left: 4px solid #90a4ae;
} }
hr { hr {

View File

@ -3,7 +3,8 @@
padding: 1.5rem; padding: 1.5rem;
margin-bottom: 1rem; margin-bottom: 1rem;
border-radius: $borderRadius; border-radius: $borderRadius;
box-shadow: 0px 3px 5px rgba(0,0,0,.02), 0px 0px 2px rgba(0,0,0,.05), 0px 1px 4px rgba(0,0,0,.08) !important; box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.02), 0px 0px 2px rgba(0, 0, 0, 0.05),
0px 1px 4px rgba(0, 0, 0, 0.08) !important;
&.card-w-title { &.card-w-title {
padding-bottom: 2rem; padding-bottom: 2rem;

View File

@ -6,7 +6,7 @@ import { Column } from 'primereact/column';
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, faUserAlt } from '@fortawesome/free-solid-svg-icons'; import { faHome, 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';
@ -14,16 +14,17 @@ import { faIdCardAlt } from '@fortawesome/free-solid-svg-icons';
import { faEllipsis } from '@fortawesome/free-solid-svg-icons'; import { faEllipsis } from '@fortawesome/free-solid-svg-icons';
import { faHomeAlt } from '@fortawesome/free-solid-svg-icons'; import { faHomeAlt } from '@fortawesome/free-solid-svg-icons';
const AdministradoresComunidad = () => { const AdministradoresComunidad = () => {
const [listaAdmins, setListaAdmins] = useState([]); const [listaAdmins, setListaAdmins] = useState([]);
const [listaAdminComunidad, setListaAdminComunidad] = useState([]); const [listaAdminComunidad, setListaAdminComunidad] = useState([]);
const [adminCommunity, setAdminCommunity] = useState(emptyAdminCommunity); const [adminCommunity, setAdminCommunity] = useState(emptyAdminCommunity);
const [selectedAdminsCommunities, setSelectedAdminsCommunities] = useState(null); const [selectedAdminsCommunities, setSelectedAdminsCommunities] =
useState(null);
const [globalFilter, setGlobalFilter] = useState(null); const [globalFilter, setGlobalFilter] = useState(null);
const [deleteAdminCommunityDialog, setDeleteAdminCommunityDialog] = useState(false); const [deleteAdminCommunityDialog, setDeleteAdminCommunityDialog] =
const [deleteAdminsCommunitiesDialog, setDeleteAdminsCommunitiesDialog] = useState(false); useState(false);
const [deleteAdminsCommunitiesDialog, setDeleteAdminsCommunitiesDialog] =
useState(false);
const toast = useRef(null); const toast = useRef(null);
const dt = useRef(null); const dt = useRef(null);
@ -38,47 +39,56 @@ const AdministradoresComunidad = () => {
community_id: '', community_id: '',
community_name: '', community_name: '',
user_type: '2', user_type: '2',
status: '' status: '',
}; };
async function listaAdmin() { async function listaAdmin() {
let nombres = await fetch('http://localhost:4000/user/findAdminComunidad/', { method: 'GET' }) let nombres = await fetch(
'http://localhost:4000/user/findAdminComunidad/',
{ method: 'GET' },
)
.then((response) => response.json()) .then((response) => response.json())
.then((data) => { .then((data) => {
return Promise.all(data.message.map(item => { return Promise.all(
data.message.map((item) => {
//item.full_name returns the repositorie name //item.full_name returns the repositorie name
return fetch(`http://localhost:4000/community/findCommunityName/${item.community_id}`, { method: 'GET' }) return fetch(
`http://localhost:4000/community/findCommunityName/${item.community_id}`,
{ method: 'GET' },
)
.then((response2) => response2.json()) .then((response2) => response2.json())
.then(data => { .then((data) => {
console.log(data.message.name); console.log(data.message.name);
item.community_name = data.message.name item.community_name = data.message.name;
return item return item;
}) });
})); }),
}).then(data => setListaAdmins(data)
); );
})
.then((data) => setListaAdmins(data));
} }
async function nombreComunidad(id) { async function nombreComunidad(id) {
let nombres = await fetch('http://localhost:4000/community/findCommunityName/' + id, { method: 'GET' }); let nombres = await fetch(
'http://localhost:4000/community/findCommunityName/' + id,
{ method: 'GET' },
);
let nombresRes = await nombres.json(); let nombresRes = await nombres.json();
return await nombresRes.message['name']; return await nombresRes.message['name'];
} }
async function setNameCommunities() { async function setNameCommunities() {
Promise.all(listaAdmins.map(async function (administrador) { Promise.all(
listaAdmins.map(async function (administrador) {
// await listaComunidades(administrador.community_id); // await listaComunidades(administrador.community_id);
administrador.community_id = await listaAdminComunidad.name; administrador.community_id = await listaAdminComunidad.name;
})) }),
);
} }
useEffect(() => { useEffect(() => {
listaAdmin(); listaAdmin();
}, []);
}, [])
const deleteAdminCommunity = () => { const deleteAdminCommunity = () => {
/* fetch('http://localhost:4000/community/deleteCommunity/' + community._id, { /* fetch('http://localhost:4000/community/deleteCommunity/' + community._id, {
@ -113,15 +123,23 @@ const AdministradoresComunidad = () => {
} }
); );
*/ */
let _administrators = listaAdmins.filter(val => val._id !== adminCommunity._id); let _administrators = listaAdmins.filter(
(val) => val._id !== adminCommunity._id,
);
setListaAdmins(_administrators); setListaAdmins(_administrators);
setDeleteAdminCommunityDialog(false); setDeleteAdminCommunityDialog(false);
setAdminCommunity(emptyAdminCommunity); setAdminCommunity(emptyAdminCommunity);
toast.current.show({ severity: 'success', summary: 'Administrador de Comunidad Eliminada', life: 3000 }); toast.current.show({
} severity: 'success',
summary: 'Administrador de Comunidad Eliminada',
life: 3000,
});
};
const deleteSelectedAdminsCommunity = () => { const deleteSelectedAdminsCommunity = () => {
let _admins = listaAdmins.filter(val => !selectedAdminsCommunities.includes(val)); let _admins = listaAdmins.filter(
(val) => !selectedAdminsCommunities.includes(val),
);
/* selectedCommunities.map((item) => { /* selectedCommunities.map((item) => {
fetch('http://localhost:4000/user/deleteCommunity/' + item._id, { fetch('http://localhost:4000/user/deleteCommunity/' + item._id, {
cache: 'no-cache', cache: 'no-cache',
@ -134,282 +152,512 @@ const AdministradoresComunidad = () => {
setListaAdmins(_admins); setListaAdmins(_admins);
setDeleteAdminsCommunitiesDialog(false); setDeleteAdminsCommunitiesDialog(false);
setSelectedAdminsCommunities(null); setSelectedAdminsCommunities(null);
toast.current.show({ severity: 'success', summary: 'Éxito', detail: 'Administradores de Comunidad de Viviendas Eliminado', life: 3000 }); toast.current.show({
} severity: 'success',
summary: 'Éxito',
detail: 'Administradores de Comunidad de Viviendas Eliminado',
life: 3000,
});
};
const hideDeleteAdminCommunityDialog = () => { const hideDeleteAdminCommunityDialog = () => {
setDeleteAdminCommunityDialog(false); setDeleteAdminCommunityDialog(false);
} };
const hideDeleteAdminsCommunitysDialog = () => { const hideDeleteAdminsCommunitysDialog = () => {
setDeleteAdminsCommunitiesDialog(false); setDeleteAdminsCommunitiesDialog(false);
} };
const confirmDeleteAdminCommunity = (adminCommunity) => { const confirmDeleteAdminCommunity = (adminCommunity) => {
setAdminCommunity(adminCommunity); setAdminCommunity(adminCommunity);
setDeleteAdminCommunityDialog(true); setDeleteAdminCommunityDialog(true);
} };
const confirmDeleteSelected = () => { const confirmDeleteSelected = () => {
setDeleteAdminsCommunitiesDialog(true); setDeleteAdminsCommunitiesDialog(true);
} };
const actionsAdminCommunity = (rowData) => { const actionsAdminCommunity = (rowData) => {
return ( return (
<div className="actions"> <div className="actions">
<Button icon="pi pi-trash" className="p-button-rounded p-button-danger mt-2" onClick={() => confirmDeleteAdminCommunity(rowData)} /> <Button
icon="pi pi-trash"
className="p-button-rounded p-button-danger mt-2"
onClick={() => confirmDeleteAdminCommunity(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={!selectedAdminsCommunities || !selectedAdminsCommunities.length} /> <Button
label="Eliminar"
icon="pi pi-trash"
className="p-button-danger"
onClick={confirmDeleteSelected}
disabled={
!selectedAdminsCommunities || !selectedAdminsCommunities.length
}
/>
</div> </div>
</React.Fragment> </React.Fragment>
) );
} };
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">Administradores de Comunidades</h5> <h5 className="m-0">Administradores de Comunidades</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 deleteAdminCommunityDialogFooter = ( const deleteAdminCommunityDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteAdminCommunityDialog} /> <Button
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteAdminCommunity} /> label="No"
icon="pi pi-times"
className="p-button-text"
onClick={hideDeleteAdminCommunityDialog}
/>
<Button
label="Yes"
icon="pi pi-check"
className="p-button-text"
onClick={deleteAdminCommunity}
/>
</> </>
); );
const deleteAdminsCommunityDialogFooter = ( const deleteAdminsCommunityDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteAdminsCommunitysDialog} /> <Button
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSelectedAdminsCommunity} /> label="No"
icon="pi pi-times"
className="p-button-text"
onClick={hideDeleteAdminsCommunitysDialog}
/>
<Button
label="Yes"
icon="pi pi-check"
className="p-button-text"
onClick={deleteSelectedAdminsCommunity}
/>
</> </>
); );
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 headerCommuntiy = ( const headerCommuntiy = (
<> <>
<p> <FontAwesomeIcon icon={faHomeAlt} style={{ color: "#D7A86E" }} /> Comunidad</p> <p>
{' '}
<FontAwesomeIcon icon={faHomeAlt} style={{ color: '#D7A86E' }} />{' '}
Comunidad
</p>
</> </>
) );
const headerOptions = ( const headerOptions = (
<> <>
<p><FontAwesomeIcon icon={faEllipsis} size="2x" style={{ color: "#C08135" }} /></p> <p>
<FontAwesomeIcon
icon={faEllipsis}
size="2x"
style={{ color: '#C08135' }}
/>
</p>
</> </>
) );
const hideDeleteAdminSystemDialog = () => { const hideDeleteAdminSystemDialog = () => {
setDeleteAdminSystemDialog(false); setDeleteAdminSystemDialog(false);
} };
const hideDeleteAdminsSystemsDialog = () => { const hideDeleteAdminsSystemsDialog = () => {
setDeleteAdminsSystemDialog(false); setDeleteAdminsSystemDialog(false);
} };
const confirmDeleteAdminSystem = (sysAdmin) => { const confirmDeleteAdminSystem = (sysAdmin) => {
setSysAdmin(sysAdmin); setSysAdmin(sysAdmin);
setDeleteAdminSystemDialog(true); setDeleteAdminSystemDialog(true);
} };
const confirmDeleteSelected = () => { const confirmDeleteSelected = () => {
setDeleteAdminsSystemDialog(true); setDeleteAdminsSystemDialog(true);
} };
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',
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'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 _sysadmin = listaAdmins.filter((val) => val._id !== sysadmin._id);
.then(
function (response) {
let _sysadmin = listaAdmins.filter(val => val._id !== sysadmin._id);
setListaAdmins(_sysadmin); setListaAdmins(_sysadmin);
setDeleteAdminSystemDialog(false); setDeleteAdminSystemDialog(false);
setSysAdmin(emptySysAdmin); setSysAdmin(emptySysAdmin);
toast.current.show({ severity: 'success', summary: 'Exito', detail: 'Administrador del Sistema Eliminado', life: 3000 }); toast.current.show({
} severity: 'success',
) summary: 'Exito',
.catch( detail: 'Administrador del Sistema Eliminado',
err => { life: 3000,
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 }); })
} .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 = () => { const deleteSelectedAdminsSystem = () => {
let _administrators = listaAdmins.filter(val => !selectedAdministrators.includes(val)); let _administrators = listaAdmins.filter(
(val) => !selectedAdministrators.includes(val),
);
selectedAdministrators.map((item) => { selectedAdministrators.map((item) => {
fetch('http://localhost:4000/user/deleteAdminSystem/' + item._id, { fetch('http://localhost:4000/user/deleteAdminSystem/' + item._id, {
cache: 'no-cache', cache: 'no-cache',
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json',
} },
}) });
}) });
setListaAdmins(_administrators); setListaAdmins(_administrators);
setDeleteAdminsSystemDialog(false); setDeleteAdminsSystemDialog(false);
setSelectedAdministrators(null); setSelectedAdministrators(null);
toast.current.show({ severity: 'success', summary: 'Successful', detail: 'Products Deleted', life: 3000 }); toast.current.show({
} severity: 'success',
summary: 'Successful',
detail: 'Products Deleted',
life: 3000,
});
};
const actionsAdmin = (rowData) => { const actionsAdmin = (rowData) => {
return ( return (
<div className="actions"> <div className="actions">
<Button icon="pi pi-trash" className="p-button-rounded p-button-danger mt-2" onClick={() => confirmDeleteAdminSystem(rowData)} /> <Button
icon="pi pi-trash"
className="p-button-rounded p-button-danger mt-2"
onClick={() => confirmDeleteAdminSystem(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={!selectedAdministrators || !selectedAdministrators.length} /> <Button
label="Eliminar"
icon="pi pi-trash"
className="p-button-danger"
onClick={confirmDeleteSelected}
disabled={!selectedAdministrators || !selectedAdministrators.length}
/>
</div> </div>
</React.Fragment> </React.Fragment>
) );
} };
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">Administradores del sistema <i class="fal fa-user"></i></h5> <h5 className="m-0">
Administradores del sistema <i class="fal fa-user"></i>
</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 deleteAdminSystemDialogFooter = ( const deleteAdminSystemDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteAdminSystemDialog} /> <Button
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSysAdmin} /> 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 = ( const deleteAdminsSystemDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteAdminsSystemsDialog} /> <Button
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSelectedAdminsSystem} /> 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} /> <Toast ref={toast} />
<div className="card"> <div className="card">
<Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate}></Toolbar> <Toolbar
<DataTable ref={dt} value={listaAdmins} dataKey="_id" paginator rows={5} selection={selectedAdminsCommunities} onSelectionChange={(e) => setSelectedAdminsCommunities(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}
></Toolbar>
<DataTable
ref={dt}
value={listaAdmins}
dataKey="_id"
paginator
rows={5}
selection={selectedAdminsCommunities}
onSelectionChange={(e) => setSelectedAdminsCommunities(e.value)}
scrollable
scrollHeight="400px"
scrollDirection="both"
header={header}
rowsPerPageOptions={[5, 10, 25]}
className="datatable-responsive mt-3"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown" paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} administradores de comunidades de viviendas" currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} administradores de comunidades de viviendas"
globalFilter={globalFilter} emptyMessage="No hay administradores de comunidades registrados."> globalFilter={globalFilter}
<Column selectionMode="multiple" headerStyle={{ width: '3rem' }}></Column> emptyMessage="No hay administradores de comunidades registrados."
<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
<Column field="dni" sortable header={headerDNI} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}> selectionMode="multiple"
</Column> headerStyle={{ width: '3rem' }}
<Column field="email" sortable header={headerEmail} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column> ></Column>
<Column field="phone" sortable header={headerPhone} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column> <Column
<Column field="community_name" header={headerCommuntiy} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column> field="name"
<Column header={headerOptions} style={{ flexGrow: 1, flexBasis: '130px', minWidth: '130px' }} body={actionsAdminCommunity}></Column> 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"
sortable
header={headerPhone}
style={{
flexGrow: 1,
flexBasis: '160px',
minWidth: '160px',
wordBreak: 'break-word',
}}
></Column>
<Column
field="community_name"
header={headerCommuntiy}
style={{
flexGrow: 1,
flexBasis: '160px',
minWidth: '160px',
wordBreak: 'break-word',
}}
></Column>
<Column
header={headerOptions}
style={{ flexGrow: 1, flexBasis: '130px', minWidth: '130px' }}
body={actionsAdminCommunity}
></Column>
</DataTable> </DataTable>
<Dialog visible={deleteAdminCommunityDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteAdminCommunityDialogFooter} onHide={hideDeleteAdminCommunityDialog}> <Dialog
visible={deleteAdminCommunityDialog}
style={{ width: '450px' }}
header="Confirmar"
modal
footer={deleteAdminCommunityDialogFooter}
onHide={hideDeleteAdminCommunityDialog}
>
<div className="flex align-items-center justify-content-center"> <div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> <i
{adminCommunity && <span>¿Estás seguro que desea eliminar a <b>{adminCommunity.name}</b>?</span>} className="pi pi-exclamation-triangle mr-3"
style={{ fontSize: '2rem' }}
/>
{adminCommunity && (
<span>
¿Estás seguro que desea eliminar a{' '}
<b>{adminCommunity.name}</b>?
</span>
)}
</div> </div>
</Dialog> </Dialog>
<Dialog visible={deleteAdminsCommunitiesDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteAdminsCommunityDialogFooter} onHide={hideDeleteAdminsCommunitysDialog}> <Dialog
visible={deleteAdminsCommunitiesDialog}
style={{ width: '450px' }}
header="Confirmar"
modal
footer={deleteAdminsCommunityDialogFooter}
onHide={hideDeleteAdminsCommunitysDialog}
>
<div className="flex align-items-center justify-content-center"> <div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> <i
{selectedAdminsCommunities && <span>¿Está seguro eliminar los administradores de las comunidades de viviendas seleccionados?</span>} className="pi pi-exclamation-triangle mr-3"
style={{ fontSize: '2rem' }}
/>
{selectedAdminsCommunities && (
<span>
¿Está seguro eliminar los administradores de las comunidades
de viviendas seleccionados?
</span>
)}
</div> </div>
</Dialog> </Dialog>
</div> </div>
</div> </div>
</div> </div>
) );
} };
export default React.memo(AdministradoresComunidad); export default React.memo(AdministradoresComunidad);

View File

@ -6,23 +6,24 @@ import { Column } from 'primereact/column';
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 { 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 { faEllipsis } from '@fortawesome/free-solid-svg-icons'; import { faEllipsis } from '@fortawesome/free-solid-svg-icons';
const AdministradoresSistema = () => { const AdministradoresSistema = () => {
const [administrators, setAdministrators] = useState([]); const [administrators, setAdministrators] = useState([]);
const [urlFetch, setUrlFetch] = useState('http://localhost:4000/user/findAdminSistema/'); const [urlFetch, setUrlFetch] = useState(
'http://localhost:4000/user/findAdminSistema/',
);
const [sysadmin, setSysAdmin] = useState(emptySysAdmin); const [sysadmin, setSysAdmin] = useState(emptySysAdmin);
const [selectedAdministrators, setSelectedAdministrators] = useState(null); const [selectedAdministrators, setSelectedAdministrators] = useState(null);
const [globalFilter, setGlobalFilter] = useState(null); const [globalFilter, setGlobalFilter] = useState(null);
const [deleteAdminSystemDialog, setDeleteAdminSystemDialog] = useState(false); const [deleteAdminSystemDialog, setDeleteAdminSystemDialog] = useState(false);
const [deleteAdminsSystemDialog, setDeleteAdminsSystemDialog] = useState(false); const [deleteAdminsSystemDialog, setDeleteAdminsSystemDialog] =
useState(false);
const toast = useRef(null); const toast = useRef(null);
const dt = useRef(null); const dt = useRef(null);
@ -35,7 +36,7 @@ const AdministradoresSistema = () => {
phone: '', phone: '',
password: '', password: '',
user_type: '1', user_type: '1',
status: '' status: '',
}; };
async function fetchP() { async function fetchP() {
@ -46,7 +47,7 @@ const AdministradoresSistema = () => {
} }
useEffect(() => { useEffect(() => {
fetchP(); fetchP();
}, []) }, []);
function registrarAdmin() { function registrarAdmin() {
var data = { var data = {
@ -56,8 +57,8 @@ const AdministradoresSistema = () => {
email: document.getElementById('correo_electronico').value, email: document.getElementById('correo_electronico').value,
phone: document.getElementById('telefono').value, phone: document.getElementById('telefono').value,
password: document.getElementById('correo_electronico').value, password: document.getElementById('correo_electronico').value,
user_type: "1", //1 es admin user_type: '1', //1 es admin
status: "1" status: '1',
}; };
// console.log(data); // console.log(data);
@ -66,216 +67,384 @@ const AdministradoresSistema = () => {
method: 'POST', method: 'POST',
body: JSON.stringify(data), body: JSON.stringify(data),
headers: { headers: {
'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) {
)
.then(
function (response) {
let _administrators = [...administrators]; let _administrators = [...administrators];
let _admin = { ...response.message };; let _admin = { ...response.message };
_administrators.push(_admin); _administrators.push(_admin);
setAdministrators(_administrators) setAdministrators(_administrators);
})
.catch((err) => console.log('Ocurrió un error con el fetch', err));
} }
)
.catch(
err => console.log('Ocurrió un error con el fetch', err)
);
}
const hideDeleteAdminSystemDialog = () => { const hideDeleteAdminSystemDialog = () => {
setDeleteAdminSystemDialog(false); setDeleteAdminSystemDialog(false);
} };
const hideDeleteAdminsSystemsDialog = () => { const hideDeleteAdminsSystemsDialog = () => {
setDeleteAdminsSystemDialog(false); setDeleteAdminsSystemDialog(false);
} };
const confirmDeleteAdminSystem = (sysAdmin) => { const confirmDeleteAdminSystem = (sysAdmin) => {
setSysAdmin(sysAdmin); setSysAdmin(sysAdmin);
setDeleteAdminSystemDialog(true); setDeleteAdminSystemDialog(true);
} };
const confirmDeleteSelected = () => { const confirmDeleteSelected = () => {
setDeleteAdminsSystemDialog(true); setDeleteAdminsSystemDialog(true);
} };
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',
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'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 _sysadmin = administrators.filter(
.then( (val) => val._id !== sysadmin._id,
function (response) { );
let _sysadmin = administrators.filter(val => val._id !== sysadmin._id);
setAdministrators(_sysadmin); setAdministrators(_sysadmin);
setDeleteAdminSystemDialog(false); setDeleteAdminSystemDialog(false);
setSysAdmin(emptySysAdmin); setSysAdmin(emptySysAdmin);
toast.current.show({ severity: 'success', summary: 'Éxito', detail: 'Administrador del Sistema Eliminado', life: 3000 }); toast.current.show({
} severity: 'success',
) summary: 'Éxito',
.catch( detail: 'Administrador del Sistema Eliminado',
err => { life: 3000,
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 }); })
} .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 = () => { const deleteSelectedAdminsSystem = () => {
let _administrators = administrators.filter(val => !selectedAdministrators.includes(val)); let _administrators = administrators.filter(
(val) => !selectedAdministrators.includes(val),
);
selectedAdministrators.map((item) => { selectedAdministrators.map((item) => {
fetch('http://localhost:4000/user/deleteAdminSystem/' + item._id, { fetch('http://localhost:4000/user/deleteAdminSystem/' + item._id, {
cache: 'no-cache', cache: 'no-cache',
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json',
} },
}) });
}) });
setAdministrators(_administrators); setAdministrators(_administrators);
setDeleteAdminsSystemDialog(false); setDeleteAdminsSystemDialog(false);
setSelectedAdministrators(null); setSelectedAdministrators(null);
toast.current.show({ severity: 'success', summary: 'Éxito', detail: 'Administradores del Sistema Eliminados', life: 3000 }); toast.current.show({
} severity: 'success',
summary: 'Éxito',
detail: 'Administradores del Sistema Eliminados',
life: 3000,
});
};
const actionsAdmin = (rowData) => { const actionsAdmin = (rowData) => {
return ( return (
<div className="actions"> <div className="actions">
<Button icon="pi pi-trash" className="p-button-rounded p-button-danger mt-2" onClick={() => confirmDeleteAdminSystem(rowData)} /> <Button
icon="pi pi-trash"
className="p-button-rounded p-button-danger mt-2"
onClick={() => confirmDeleteAdminSystem(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={!selectedAdministrators || !selectedAdministrators.length} /> <Button
label="Eliminar"
icon="pi pi-trash"
className="p-button-danger"
onClick={confirmDeleteSelected}
disabled={!selectedAdministrators || !selectedAdministrators.length}
/>
</div> </div>
</React.Fragment> </React.Fragment>
) );
} };
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">Administradores del sistema <i class="fal fa-user"></i></h5> <h5 className="m-0">
Administradores del sistema <i class="fal fa-user"></i>
</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 deleteAdminSystemDialogFooter = ( const deleteAdminSystemDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteAdminSystemDialog} /> <Button
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSysAdmin} /> 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 = ( const deleteAdminsSystemDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteAdminsSystemsDialog} /> <Button
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSelectedAdminsSystem} /> 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}
/>
</> </>
); );
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 headerOptions = ( const headerOptions = (
<> <>
<p>Opciones <FontAwesomeIcon icon={faEllipsis} style={{color: "#D7A86E"}} /></p> <p>
Opciones{' '}
<FontAwesomeIcon icon={faEllipsis} style={{ color: '#D7A86E' }} />
</p>
</> </>
) );
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={administrators} dataKey="_id" paginator rows={5} selection={selectedAdministrators} onSelectionChange={(e) => setSelectedAdministrators(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}
></Toolbar>
<DataTable
ref={dt}
value={administrators}
dataKey="_id"
paginator
rows={5}
selection={selectedAdministrators}
onSelectionChange={(e) => setSelectedAdministrators(e.value)}
scrollable
scrollHeight="400px"
scrollDirection="both"
header={header}
rowsPerPageOptions={[5, 10, 25]}
className="datatable-responsive mt-3"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown" paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} administradores del sistema" currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} administradores del sistema"
globalFilter={globalFilter} emptyMessage="No hay administradores del sistema registrados."> globalFilter={globalFilter}
<Column selectionMode="multiple" headerStyle={{ width: '3rem' }}></Column> emptyMessage="No hay administradores del sistema registrados."
<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
<Column field="dni" sortable header={headerDNI} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}> selectionMode="multiple"
</Column> headerStyle={{ width: '3rem' }}
<Column field="email" sortable header={headerEmail} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column> ></Column>
<Column field="phone" sortable header={headerPhone} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column> <Column
<Column header={headerOptions} style={{ flexGrow: 1, flexBasis: '130px', minWidth: '130px' }} body={actionsAdmin}></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"
sortable
header={headerPhone}
style={{
flexGrow: 1,
flexBasis: '160px',
minWidth: '160px',
wordBreak: 'break-word',
}}
></Column>
<Column
header={headerOptions}
style={{ flexGrow: 1, flexBasis: '130px', minWidth: '130px' }}
body={actionsAdmin}
></Column>
</DataTable> </DataTable>
<Dialog visible={deleteAdminSystemDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteAdminSystemDialogFooter} onHide={hideDeleteAdminSystemDialog}> <Dialog
visible={deleteAdminSystemDialog}
style={{ width: '450px' }}
header="Confirmar"
modal
footer={deleteAdminSystemDialogFooter}
onHide={hideDeleteAdminSystemDialog}
>
<div className="flex align-items-center justify-content-center"> <div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> <i
{sysadmin && <span>¿Estás seguro que desea eliminar a <b>{sysadmin.name}</b>?</span>} 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> </div>
</Dialog> </Dialog>
<Dialog visible={deleteAdminsSystemDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteAdminsSystemDialogFooter} onHide={hideDeleteAdminsSystemsDialog}> <Dialog
visible={deleteAdminsSystemDialog}
style={{ width: '450px' }}
header="Confirmar"
modal
footer={deleteAdminsSystemDialogFooter}
onHide={hideDeleteAdminsSystemsDialog}
>
<div className="flex align-items-center justify-content-center"> <div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> <i
{selectedAdministrators && <span>¿Está seguro eliminar los adminsitradores del sistema seleccionados?</span>} className="pi pi-exclamation-triangle mr-3"
style={{ fontSize: '2rem' }}
/>
{selectedAdministrators && (
<span>
¿Está seguro eliminar los adminsitradores del sistema
seleccionados?
</span>
)}
</div> </div>
</Dialog> </Dialog>
</div> </div>
@ -309,8 +478,8 @@ const AdministradoresSistema = () => {
</div> </div>
</div> </div>
</div> </div>
) );
} };
const comparisonFn = function (prevProps, nextProps) { const comparisonFn = function (prevProps, nextProps) {
return prevProps.location.pathname === nextProps.location.pathname; return prevProps.location.pathname === nextProps.location.pathname;

View File

@ -8,14 +8,13 @@ import { Toast } from 'primereact/toast';
import classNames from 'classnames'; import classNames from 'classnames';
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 { faHome } from '@fortawesome/free-solid-svg-icons';
import { faMapLocationDot } from '@fortawesome/free-solid-svg-icons'; import { faMapLocationDot } from '@fortawesome/free-solid-svg-icons';
import { faPhoneAlt } from '@fortawesome/free-solid-svg-icons'; import { faPhoneAlt } from '@fortawesome/free-solid-svg-icons';
import { faEllipsis } from '@fortawesome/free-solid-svg-icons'; import { faEllipsis } from '@fortawesome/free-solid-svg-icons';
const Communities = () => { const Communities = () => {
let emptyCommunity = { let emptyCommunity = {
_id: null, _id: null,
name: '', name: '',
@ -29,7 +28,6 @@ const Communities = () => {
houses: [], houses: [],
}; };
const [communitiesList, setCommunitiesList] = useState([]); const [communitiesList, setCommunitiesList] = useState([]);
const [community, setCommunity] = useState(emptyCommunity); const [community, setCommunity] = useState(emptyCommunity);
@ -49,43 +47,39 @@ const Communities = () => {
const toast = useRef(null); const toast = useRef(null);
const dt = useRef(null); const dt = useRef(null);
const p = provincesList.map((item) => ({ const p = provincesList.map((item) => ({
label: item.name, label: item.name,
value: item.code value: item.code,
})) }));
const c = cantonsList.map((item) => ({ const c = cantonsList.map((item) => ({
label: item.name, label: item.name,
value: item.code, value: item.code,
parent: item.parentCode parent: item.parentCode,
})) }));
const d = districtsList.map((item) => ({ const d = districtsList.map((item) => ({
label: item.name, label: item.name,
value: item.code, value: item.code,
parent: item.parentCode parent: item.parentCode,
})) }));
useEffect(() => { useEffect(() => {
fillProvinces(); fillProvinces();
}, []);
}, [])
useEffect(() => { useEffect(() => {
fillCantons(); fillCantons();
}, [provinciaId]) }, [provinciaId]);
useEffect(() => { useEffect(() => {
fillDistricts(); fillDistricts();
}, [cantonId]) }, [cantonId]);
async function getProvinces() { async function getProvinces() {
const response = await fetch('assets/demo/data/provincias.json', { method: 'GET' }); const response = await fetch('assets/demo/data/provincias.json', {
method: 'GET',
});
return await response.json(); return await response.json();
} }
@ -95,7 +89,9 @@ const Communities = () => {
} }
async function getCantons() { async function getCantons() {
const response = await fetch('assets/demo/data/cantones.json', { method: 'GET' }); const response = await fetch('assets/demo/data/cantones.json', {
method: 'GET',
});
return await response.json(); return await response.json();
} }
@ -108,7 +104,9 @@ const Communities = () => {
} }
async function getDistricts() { async function getDistricts() {
const response = await fetch('assets/demo/data/distritos.json', { method: 'GET' }); const response = await fetch('assets/demo/data/distritos.json', {
method: 'GET',
});
return await response.json(); return await response.json();
} }
@ -123,61 +121,66 @@ const Communities = () => {
const handleProvinces = (event) => { const handleProvinces = (event) => {
const getprovinciaId = event.target.value; const getprovinciaId = event.target.value;
setProvinciaId(getprovinciaId); setProvinciaId(getprovinciaId);
} };
const handleCanton = (event) => { const handleCanton = (event) => {
const getCantonId = event.target.value; const getCantonId = event.target.value;
setCantonId(getCantonId); setCantonId(getCantonId);
} };
const handleDistrict = (event) => { const handleDistrict = (event) => {
const getDistrictId = event.target.value; const getDistrictId = event.target.value;
setDistrictId(getDistrictId); setDistrictId(getDistrictId);
} };
const handleCodeHouses = (event) => { const handleCodeHouses = (event) => {
const getcodehouse = event.target.value; const getcodehouse = event.target.value;
setCodeHouses(getcodehouse); setCodeHouses(getcodehouse);
} };
async function getCommunites() { async function getCommunites() {
let response = await fetch('http://localhost:4000/community/allCommunities', { method: 'GET' }); let response = await fetch(
'http://localhost:4000/community/allCommunities',
{ method: 'GET' },
);
let resJson = await response.json(); let resJson = await response.json();
let pList = await getProvinces(); let pList = await getProvinces();
let cList = await getCantons(); let cList = await getCantons();
let dList = await getDistricts(); let dList = await getDistricts();
await resJson.message.map((item) => { await resJson.message.map((item) => {
item.province = pList.find(p => p.code === item.province).name item.province = pList.find((p) => p.code === item.province).name;
item.canton = cList.find(p => p.code === item.canton).name item.canton = cList.find((p) => p.code === item.canton).name;
item.district = dList.find(p => p.code === item.district).name item.district = dList.find((p) => p.code === item.district).name;
if (!item.id_admin) { if (!item.id_admin) {
item.name_admin = "Sin Administrador" item.name_admin = 'Sin Administrador';
} }
}) });
setCommunitiesList(await resJson.message); setCommunitiesList(await resJson.message);
} }
useEffect(() => { useEffect(() => {
getCommunites(); getCommunites();
}, []) }, []);
const saveCommunity = () => { const saveCommunity = () => {
if (
if (community.name && community.num_houses > 0 && provinciaId && cantonId && districtId && community.phone) { community.name &&
community.num_houses > 0 &&
provinciaId &&
cantonId &&
districtId &&
community.phone
) {
let _communities = [...communitiesList]; let _communities = [...communitiesList];
let _community = { ...community }; let _community = { ...community };
_community.province = provinciaId; _community.province = provinciaId;
_community.canton = cantonId; _community.canton = cantonId;
_community.district = districtId; _community.district = districtId;
for (let i = 0; i < _community.num_houses; i++) { for (let i = 0; i < _community.num_houses; i++) {
_community.houses.push({ _community.houses.push({
number_house: codeHouses + (i + 1), number_house: codeHouses + (i + 1),
}) });
} }
// console.log(houses) // console.log(houses)
fetch('http://localhost:4000/community/createCommunity', { fetch('http://localhost:4000/community/createCommunity', {
@ -185,48 +188,47 @@ const Communities = () => {
method: 'POST', method: 'POST',
body: JSON.stringify(_community), body: JSON.stringify(_community),
headers: { headers: {
'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(() => { .then(() => {
_community.province = provincesList.find(
_community.province = provincesList.find(p => p.code === _community.province).name (p) => p.code === _community.province,
_community.canton = cantonsList.find(p => p.code === _community.canton).name ).name;
_community.district = districtsList.find(p => p.code === _community.district).name _community.canton = cantonsList.find(
(p) => p.code === _community.canton,
).name;
_community.district = districtsList.find(
(p) => p.code === _community.district,
).name;
_communities.push(_community); _communities.push(_community);
toast.current.show({ severity: 'success', summary: 'Registro exitoso', detail: 'Comunidad de vivienda Creada', life: 3000 }); toast.current.show({
severity: 'success',
summary: 'Registro exitoso',
detail: 'Comunidad de vivienda Creada',
life: 3000,
});
setCommunitiesList(_communities); setCommunitiesList(_communities);
setProvinciaId(''); setProvinciaId('');
setCantonId(''); setCantonId('');
setDistrictId(''); setDistrictId('');
setCodeHouses(''); setCodeHouses('');
setCommunity(emptyCommunity); setCommunity(emptyCommunity);
}) })
.catch( .catch((err) => console.log('Ocurrió un error con el fetch', err));
err => console.log('Ocurrió un error con el fetch', err)
);
} else { } else {
setSubmitted(true); setSubmitted(true);
}
} }
};
const onInputChange = (e, name) => { const onInputChange = (e, name) => {
const val = (e.target && e.target.value) || ''; const val = (e.target && e.target.value) || '';
@ -234,28 +236,26 @@ const Communities = () => {
_community[`${name}`] = val; _community[`${name}`] = val;
setCommunity(_community); setCommunity(_community);
} };
const hideDeleteCommunityDialog = () => { const hideDeleteCommunityDialog = () => {
setDeleteCommunityDialog(false); setDeleteCommunityDialog(false);
} };
const hideDeleteCommunitiesDialog = () => { const hideDeleteCommunitiesDialog = () => {
setDeleteCommunitiesDialog(false); setDeleteCommunitiesDialog(false);
} };
const confirmDeleteCommunity = (community) => { const confirmDeleteCommunity = (community) => {
setCommunity(community); setCommunity(community);
setDeleteCommunityDialog(true); setDeleteCommunityDialog(true);
} };
const confirmDeleteSelected = () => { const confirmDeleteSelected = () => {
setDeleteCommunitiesDialog(true); setDeleteCommunitiesDialog(true);
} };
const deleteCommunity = () => { const deleteCommunity = () => {
/* fetch('http://localhost:4000/community/deleteCommunity/' + community._id, { /* fetch('http://localhost:4000/community/deleteCommunity/' + community._id, {
cache: 'no-cache', cache: 'no-cache',
method: 'DELETE', method: 'DELETE',
@ -288,15 +288,22 @@ const Communities = () => {
} }
); );
*/ */
let _community = communitiesList.filter(val => val._id !== community._id); let _community = communitiesList.filter((val) => val._id !== community._id);
setCommunitiesList(_community); setCommunitiesList(_community);
setDeleteCommunityDialog(false); setDeleteCommunityDialog(false);
setCommunity(emptyCommunity); setCommunity(emptyCommunity);
toast.current.show({ severity: 'success', summary: 'Éxito', detail: 'Comunidad de Viviendas Eliminada', life: 3000 }); toast.current.show({
} severity: 'success',
summary: 'Éxito',
detail: 'Comunidad de Viviendas Eliminada',
life: 3000,
});
};
const deleteSelectedCommunities = () => { const deleteSelectedCommunities = () => {
let _communities = communitiesList.filter(val => !selectedCommunities.includes(val)); let _communities = communitiesList.filter(
(val) => !selectedCommunities.includes(val),
);
/* selectedCommunities.map((item) => { /* selectedCommunities.map((item) => {
fetch('http://localhost:4000/user/deleteCommunity/' + item._id, { fetch('http://localhost:4000/user/deleteCommunity/' + item._id, {
cache: 'no-cache', cache: 'no-cache',
@ -309,140 +316,298 @@ const Communities = () => {
setCommunitiesList(_communities); setCommunitiesList(_communities);
setDeleteCommunitiesDialog(false); setDeleteCommunitiesDialog(false);
setSelectedCommunities(null); setSelectedCommunities(null);
toast.current.show({ severity: 'success', summary: 'Éxito', detail: 'Comunidades de Viviendas Eliminadas', life: 3000 }); toast.current.show({
} severity: 'success',
summary: 'Éxito',
detail: 'Comunidades de Viviendas Eliminadas',
life: 3000,
});
};
const actionsCommunity = (rowData) => { const actionsCommunity = (rowData) => {
return ( return (
<div className="actions"> <div className="actions">
<Button icon="pi pi-trash" className="p-button-rounded p-button-danger mt-2" onClick={() => confirmDeleteCommunity(rowData)} /> <Button
icon="pi pi-trash"
className="p-button-rounded p-button-danger mt-2"
onClick={() => confirmDeleteCommunity(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={!selectedCommunities || !selectedCommunities.length} /> <Button
label="Eliminar"
icon="pi pi-trash"
className="p-button-danger"
onClick={confirmDeleteSelected}
disabled={!selectedCommunities || !selectedCommunities.length}
/>
</div> </div>
</React.Fragment> </React.Fragment>
) );
} };
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">Comunidade de Viviendas</h5> <h5 className="m-0">Comunidade de Viviendas</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 deleteCommunityDialogFooter = ( const deleteCommunityDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteCommunityDialog} /> <Button
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteCommunity} /> label="No"
icon="pi pi-times"
className="p-button-text"
onClick={hideDeleteCommunityDialog}
/>
<Button
label="Yes"
icon="pi pi-check"
className="p-button-text"
onClick={deleteCommunity}
/>
</> </>
); );
const deleteCommutitiesDialogFooter = ( const deleteCommutitiesDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteCommunitiesDialog} /> <Button
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSelectedCommunities} /> label="No"
icon="pi pi-times"
className="p-button-text"
onClick={hideDeleteCommunitiesDialog}
/>
<Button
label="Yes"
icon="pi pi-check"
className="p-button-text"
onClick={deleteSelectedCommunities}
/>
</> </>
); );
const headerName = ( const headerName = (
<> <>
<p> <FontAwesomeIcon icon={faHome} style={{ color: "#C08135" }} /> Nombre</p> <p>
{' '}
<FontAwesomeIcon icon={faHome} style={{ color: '#C08135' }} /> Nombre
</p>
</> </>
) );
const headerProvince = ( const headerProvince = (
<> <>
<p> <FontAwesomeIcon icon={faMapLocationDot} style={{ color: "#D7A86E" }} /> Pronvincia</p> <p>
{' '}
<FontAwesomeIcon
icon={faMapLocationDot}
style={{ color: '#D7A86E' }}
/>{' '}
Pronvincia
</p>
</> </>
) );
const headerCanton = ( const headerCanton = (
<> <>
<p> <FontAwesomeIcon icon={faMapLocationDot} style={{ color: "#C08135" }} /> Cantón</p> <p>
{' '}
<FontAwesomeIcon
icon={faMapLocationDot}
style={{ color: '#C08135' }}
/>{' '}
Cantón
</p>
</> </>
) );
const headerDistrict = ( const headerDistrict = (
<> <>
<p> <FontAwesomeIcon icon={faMapLocationDot} style={{ color: "#D7A86E" }} /> Distrito</p> <p>
{' '}
<FontAwesomeIcon
icon={faMapLocationDot}
style={{ color: '#D7A86E' }}
/>{' '}
Distrito
</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 headerNumberHouses = ( const headerNumberHouses = (
<> <>
<p> <FontAwesomeIcon icon={faPhoneAlt} style={{ color: "#D7A86E" }} /> Número de viviendas</p> <p>
{' '}
<FontAwesomeIcon icon={faPhoneAlt} style={{ color: '#D7A86E' }} />{' '}
Número de viviendas
</p>
</> </>
) );
const headerAdministrator = ( const headerAdministrator = (
<> <>
<p> <FontAwesomeIcon icon={faPhoneAlt} style={{ color: "#C08135" }} /> Administrador</p> <p>
{' '}
<FontAwesomeIcon icon={faPhoneAlt} style={{ color: '#C08135' }} />{' '}
Administrador
</p>
</> </>
) );
const headerOptions = ( const headerOptions = (
<> <>
<p>Opciones <FontAwesomeIcon icon={faEllipsis} style={{ color: "#D7A86E" }} /></p> <p>
Opciones{' '}
<FontAwesomeIcon icon={faEllipsis} style={{ color: '#D7A86E' }} />
</p>
</> </>
) );
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={communitiesList} dataKey="_id" paginator rows={5} selection={selectedCommunities} onSelectionChange={(e) => setSelectedCommunities(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}
></Toolbar>
<DataTable
ref={dt}
value={communitiesList}
dataKey="_id"
paginator
rows={5}
selection={selectedCommunities}
onSelectionChange={(e) => setSelectedCommunities(e.value)}
scrollable
scrollHeight="400px"
scrollDirection="both"
header={header}
rowsPerPageOptions={[5, 10, 25]}
className="datatable-responsive mt-3"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown" paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} comunidades de viviendas" currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} comunidades de viviendas"
globalFilter={globalFilter} emptyMessage="No hay comunidades de viviendas registrados."> globalFilter={globalFilter}
<Column selectionMode="multiple" headerStyle={{ width: '3rem' }}></Column> emptyMessage="No hay comunidades de viviendas registrados."
<Column field="name" header={headerName} style={{ flexGrow: 1, flexBasis: '160px' }}></Column> >
<Column field="province" header={headerProvince} style={{ flexGrow: 1, flexBasis: '160px' }}></Column> <Column
<Column field="canton" header={headerCanton} style={{ flexGrow: 1, flexBasis: '160px' }}></Column> selectionMode="multiple"
<Column field="district" header={headerDistrict} style={{ flexGrow: 1, flexBasis: '160px' }}></Column> headerStyle={{ width: '3rem' }}
<Column field="phone" header={headerPhone} style={{ flexGrow: 1, flexBasis: '180px' }}></Column> ></Column>
<Column field="num_houses" header={headerNumberHouses} style={{ flexGrow: 1, flexBasis: '180px' }}></Column> <Column
<Column field="name_admin" header={headerAdministrator} style={{ flexGrow: 1, flexBasis: '180px' }}></Column> field="name"
header={headerName}
style={{ flexGrow: 1, flexBasis: '160px' }}
></Column>
<Column
field="province"
header={headerProvince}
style={{ flexGrow: 1, flexBasis: '160px' }}
></Column>
<Column
field="canton"
header={headerCanton}
style={{ flexGrow: 1, flexBasis: '160px' }}
></Column>
<Column
field="district"
header={headerDistrict}
style={{ flexGrow: 1, flexBasis: '160px' }}
></Column>
<Column
field="phone"
header={headerPhone}
style={{ flexGrow: 1, flexBasis: '180px' }}
></Column>
<Column
field="num_houses"
header={headerNumberHouses}
style={{ flexGrow: 1, flexBasis: '180px' }}
></Column>
<Column
field="name_admin"
header={headerAdministrator}
style={{ flexGrow: 1, flexBasis: '180px' }}
></Column>
<Column header={headerOptions} body={actionsCommunity}></Column> <Column header={headerOptions} body={actionsCommunity}></Column>
</DataTable> </DataTable>
<Dialog visible={deleteCommunityDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteCommunityDialogFooter} onHide={hideDeleteCommunityDialog}> <Dialog
visible={deleteCommunityDialog}
style={{ width: '450px' }}
header="Confirmar"
modal
footer={deleteCommunityDialogFooter}
onHide={hideDeleteCommunityDialog}
>
<div className="flex align-items-center justify-content-center"> <div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> <i
{community && <span>¿Estás seguro que desea eliminar a <b>{community.name}</b>?</span>} className="pi pi-exclamation-triangle mr-3"
style={{ fontSize: '2rem' }}
/>
{community && (
<span>
¿Estás seguro que desea eliminar a <b>{community.name}</b>?
</span>
)}
</div> </div>
</Dialog> </Dialog>
<Dialog visible={deleteCommunitiesDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteCommutitiesDialogFooter} onHide={hideDeleteCommunitiesDialog}> <Dialog
visible={deleteCommunitiesDialog}
style={{ width: '450px' }}
header="Confirmar"
modal
footer={deleteCommutitiesDialogFooter}
onHide={hideDeleteCommunitiesDialog}
>
<div className="flex align-items-center justify-content-center"> <div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> <i
{selectedCommunities && <span>¿Está seguro eliminar los adminsitradores del sistema seleccionados?</span>} className="pi pi-exclamation-triangle mr-3"
style={{ fontSize: '2rem' }}
/>
{selectedCommunities && (
<span>
¿Está seguro eliminar los adminsitradores del sistema
seleccionados?
</span>
)}
</div> </div>
</Dialog> </Dialog>
</div> </div>
@ -458,9 +623,20 @@ const Communities = () => {
<span className="p-inputgroup-addon p-button p-icon-input-khaki"> <span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-home"></i> <i className="pi pi-home"></i>
</span> </span>
<InputText id="name" value={community.name} onChange={(e) => onInputChange(e, 'name')} required autoFocus className={classNames({ 'p-invalid': submitted && community.name === '' })} /> <InputText
id="name"
value={community.name}
onChange={(e) => onInputChange(e, 'name')}
required
autoFocus
className={classNames({
'p-invalid': submitted && community.name === '',
})}
/>
</div> </div>
{submitted && community.name === '' && <small className="p-invalid">Nombre es requirido.</small>} {submitted && community.name === '' && (
<small className="p-invalid">Nombre es requirido.</small>
)}
</div> </div>
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-12 md:col-6">
@ -470,9 +646,21 @@ const Communities = () => {
<span className="p-inputgroup-addon p-button p-icon-input-khaki"> <span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-map-marker"></i> <i className="pi pi-map-marker"></i>
</span> </span>
<Dropdown placeholder="--Seleccione Provincia--" value={provinciaId} options={p} onChange={handleProvinces} required autoFocus className={classNames({ 'p-invalid': submitted && !provinciaId })} /> <Dropdown
placeholder="--Seleccione Provincia--"
value={provinciaId}
options={p}
onChange={handleProvinces}
required
autoFocus
className={classNames({
'p-invalid': submitted && !provinciaId,
})}
/>
</div> </div>
{submitted && !provinciaId && <small className="p-invalid">Provincia es requirido.</small>} {submitted && !provinciaId && (
<small className="p-invalid">Provincia es requirido.</small>
)}
</div> </div>
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-12 md:col-6">
@ -482,9 +670,21 @@ const Communities = () => {
<span className="p-inputgroup-addon p-button p-icon-input-khaki"> <span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-map-marker"></i> <i className="pi pi-map-marker"></i>
</span> </span>
<Dropdown placeholder="--Seleccione Cantón--" value={cantonId} options={c} onChange={handleCanton} required autoFocus className={classNames({ 'p-invalid': submitted && !cantonId })} /> <Dropdown
placeholder="--Seleccione Cantón--"
value={cantonId}
options={c}
onChange={handleCanton}
required
autoFocus
className={classNames({
'p-invalid': submitted && !cantonId,
})}
/>
</div> </div>
{submitted && !cantonId && <small className="p-invalid">Cantón es requirido.</small>} {submitted && !cantonId && (
<small className="p-invalid">Cantón es requirido.</small>
)}
</div> </div>
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-12 md:col-6">
@ -494,9 +694,21 @@ const Communities = () => {
<span className="p-inputgroup-addon p-button p-icon-input-khaki"> <span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-map-marker"></i> <i className="pi pi-map-marker"></i>
</span> </span>
<Dropdown placeholder="--Seleccione Distrito--" value={districtId} options={d} onChange={handleDistrict} required autoFocus className={classNames({ 'p-invalid': submitted && !districtId })} /> <Dropdown
placeholder="--Seleccione Distrito--"
value={districtId}
options={d}
onChange={handleDistrict}
required
autoFocus
className={classNames({
'p-invalid': submitted && !districtId,
})}
/>
</div> </div>
{submitted && !districtId && <small className="p-invalid">Distrito es requirido.</small>} {submitted && !districtId && (
<small className="p-invalid">Distrito es requirido.</small>
)}
</div> </div>
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-12 md:col-6">
@ -506,9 +718,22 @@ const Communities = () => {
<span className="p-inputgroup-addon p-button p-icon-input-khaki"> <span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-phone"></i> <i className="pi pi-phone"></i>
</span> </span>
<InputText id="phone" value={community.phone} onChange={(e) => onInputChange(e, 'phone')} required autoFocus className={classNames({ 'p-invalid': submitted && community.phone === '' })} /> <InputText
id="phone"
value={community.phone}
onChange={(e) => onInputChange(e, 'phone')}
required
autoFocus
className={classNames({
'p-invalid': submitted && community.phone === '',
})}
/>
</div> </div>
{submitted && community.phone === '' && <small className="p-invalid">Número de teléfono es requirido.</small>} {submitted && community.phone === '' && (
<small className="p-invalid">
Número de teléfono es requirido.
</small>
)}
</div> </div>
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-12 md:col-6">
@ -518,34 +743,62 @@ const Communities = () => {
<span className="p-inputgroup-addon p-button p-icon-input-khaki"> <span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-hashtag"></i> <i className="pi pi-hashtag"></i>
</span> </span>
<InputText id="num_houses" value={community.num_houses} onChange={(e) => onInputChange(e, 'num_houses')} required autoFocus className={classNames({ 'p-invalid': submitted && community.num_houses < 1 })} /> <InputText
id="num_houses"
value={community.num_houses}
onChange={(e) => onInputChange(e, 'num_houses')}
required
autoFocus
className={classNames({
'p-invalid': submitted && community.num_houses < 1,
})}
/>
</div> </div>
{submitted && community.num_houses < 1 && <small className="p-invalid">Número de viviendas es requirido y debe ser mayor que 0.</small>} {submitted && community.num_houses < 1 && (
<small className="p-invalid">
Número de viviendas es requirido y debe ser mayor que 0.
</small>
)}
</div> </div>
</div> </div>
<div className="field col-12 md:col-6"> <div className="field col-12 md:col-6">
<label htmlFor="numHouse">Ingrese el prefijo para el código de las viviendas</label> <label htmlFor="numHouse">
Ingrese el prefijo para el código de las viviendas
</label>
<div className="p-0 col-12 md:col-12"> <div className="p-0 col-12 md:col-12">
<div className="p-inputgroup"> <div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki"> <span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-hashtag"></i> <i className="pi pi-hashtag"></i>
</span> </span>
<InputText id="code_houses" value={codeHouses} onChange={handleCodeHouses} autoFocus className={classNames({ 'p-invalid': submitted && codeHouses === '' })} /> <InputText
id="code_houses"
value={codeHouses}
onChange={handleCodeHouses}
autoFocus
className={classNames({
'p-invalid': submitted && codeHouses === '',
})}
/>
</div> </div>
{submitted && codeHouses === '' && <small className="p-invalid">El código para las viviendas es requirido.</small>} {submitted && codeHouses === '' && (
<small className="p-invalid">
El código para las viviendas es requirido.
</small>
)}
</div> </div>
</div> </div>
<div className="col-12 md:col-12 py-2"> <div className="col-12 md:col-12 py-2">
<Button label="Registrar" icon="pi pi-check" onClick={saveCommunity}></Button> <Button
label="Registrar"
icon="pi pi-check"
onClick={saveCommunity}
></Button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
);
};
)
}
export default React.memo(Communities); export default React.memo(Communities);

View File

@ -5,9 +5,10 @@ import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column'; import { Column } from 'primereact/column';
const GuardasSeguridad = () => { const GuardasSeguridad = () => {
const [pokemones, setPokemones] = useState([]); const [pokemones, setPokemones] = useState([]);
const [urlFetch,setUrlFetch]=useState('http://localhost:4000/user/findGuards/62be68215692582bbfd77134'); const [urlFetch, setUrlFetch] = useState(
'http://localhost:4000/user/findGuards/62be68215692582bbfd77134',
);
async function fetchP() { async function fetchP() {
let nombres = await fetch(urlFetch, { method: 'GET' }); let nombres = await fetch(urlFetch, { method: 'GET' });
let pokemonesRes = await nombres.json(); let pokemonesRes = await nombres.json();
@ -16,7 +17,7 @@ const GuardasSeguridad = () => {
} }
useEffect(() => { useEffect(() => {
fetchP(); fetchP();
},[]) }, []);
function registrarGuarda() { function registrarGuarda() {
var data = { var data = {
@ -26,21 +27,21 @@ const GuardasSeguridad = () => {
email: document.getElementById('correo_electronico').value, email: document.getElementById('correo_electronico').value,
phone: document.getElementById('telefono').value, phone: document.getElementById('telefono').value,
password: document.getElementById('correo_electronico').value, password: document.getElementById('correo_electronico').value,
user_type: "4", //4 es guarda user_type: '4', //4 es guarda
status: "1", status: '1',
community_id:"62be68215692582bbfd77134" community_id: '62be68215692582bbfd77134',
}; };
var data2 = { var data2 = {
dni: "98765", dni: '98765',
name: "Danielito", name: 'Danielito',
last_name: "Rodriguez", last_name: 'Rodriguez',
email: "danirodriguez@gmail.com", email: 'danirodriguez@gmail.com',
phone: 84664515, phone: 84664515,
password: "1203", password: '1203',
user_type: "2", user_type: '2',
status: "4", status: '4',
community_id:"62be68215692582bbfd77134" community_id: '62be68215692582bbfd77134',
} };
console.log(data2); console.log(data2);
fetch('http://localhost:4000/user/createGuard', { fetch('http://localhost:4000/user/createGuard', {
@ -49,25 +50,18 @@ const GuardasSeguridad = () => {
mode: 'cors', mode: 'cors',
body: JSON.stringify(data2), body: JSON.stringify(data2),
headers: { headers: {
'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) {
)
.then(
function (response) {
fetchP(); fetchP();
} })
) .catch((err) => console.log('Ocurrió un error con el fetch', err));
.catch(
err => console.log('Ocurrió un error con el fetch', err)
);
} }
return ( return (
@ -75,12 +69,39 @@ const GuardasSeguridad = () => {
<div className="col-12"> <div className="col-12">
<div className="card"> <div className="card">
<h5>Guardas de seguridad</h5> <h5>Guardas de seguridad</h5>
<DataTable value={pokemones} scrollable scrollHeight="400px" scrollDirection="both" className="mt-3"> <DataTable
<Column field="name" header="Nombre" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> value={pokemones}
<Column field="last_name" header="Apellidos" style={{ flexGrow: 1, flexBasis: '160px' }} alignFrozen="left"></Column> scrollable
<Column field="dni" header="Identificación" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> scrollHeight="400px"
<Column field="email" header="Correo electrónico" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> scrollDirection="both"
<Column field="phone" header="Telefóno" style={{ flexGrow: 1, flexBasis: '160px' }}></Column> className="mt-3"
>
<Column
field="name"
header="Nombre"
style={{ flexGrow: 1, flexBasis: '160px' }}
></Column>
<Column
field="last_name"
header="Apellidos"
style={{ flexGrow: 1, flexBasis: '160px' }}
alignFrozen="left"
></Column>
<Column
field="dni"
header="Identificación"
style={{ flexGrow: 1, flexBasis: '160px' }}
></Column>
<Column
field="email"
header="Correo electrónico"
style={{ flexGrow: 1, flexBasis: '160px' }}
></Column>
<Column
field="phone"
header="Telefóno"
style={{ flexGrow: 1, flexBasis: '160px' }}
></Column>
</DataTable> </DataTable>
</div> </div>
</div> </div>
@ -113,9 +134,7 @@ const GuardasSeguridad = () => {
</div> </div>
</div> </div>
</div> </div>
);
};
)
}
export default React.memo(GuardasSeguridad); export default React.memo(GuardasSeguridad);

View File

@ -1,27 +1,30 @@
import { Button } from 'primereact/button'; import { Button } from 'primereact/button';
import { Dropdown } from 'primereact/dropdown'; import { Dropdown } from 'primereact/dropdown';
import { InputText } from 'primereact/inputtext' import { InputText } from 'primereact/inputtext';
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react';
const Inquilinos = () => { const Inquilinos = () => {
const [communitiesList, setCommunitiesList] = useState([]); const [communitiesList, setCommunitiesList] = useState([]);
const communityIdList = communitiesList.map(community => community.id); const communityIdList = communitiesList.map((community) => community.id);
async function getCommunites() { async function getCommunites() {
let response = await fetch('http://localhost:4000/community/allCommunities', { method: 'GET' }); let response = await fetch(
'http://localhost:4000/community/allCommunities',
{ method: 'GET' },
);
let list = await response.json(); let list = await response.json();
setCommunitiesList(list.message); setCommunitiesList(list.message);
} }
useEffect(() => { useEffect(() => {
getCommunites(); getCommunites();
}, []) }, []);
function registrarInquilino() { function registrarInquilino() {
let data = { let data = {
email: document.getElementById('correo_electronico').value, email: document.getElementById('correo_electronico').value,
community_id: document.getElementById('numero_vivienda').value, community_id: document.getElementById('numero_vivienda').value,
user_type: '3', user_type: '3',
status: '1', status: '1',
} };
fetch('http://localhost:3000/api/createUser', { fetch('http://localhost:3000/api/createUser', {
method: 'POST', method: 'POST',
@ -32,11 +35,11 @@ const Inquilinos = () => {
}, },
}).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');
} }
}) });
} }
return ( return (
@ -47,18 +50,26 @@ const Inquilinos = () => {
<div className="p-fluid formgrid grid"> <div className="p-fluid formgrid grid">
<div className="p-field col-12 md:col-6"> <div className="p-field col-12 md:col-6">
<label htmlFor="correo_electronico">Correo electrónico</label> <label htmlFor="correo_electronico">Correo electrónico</label>
<InputText type="email" className="form-control" id="correo_electronico" /> <InputText
type="email"
className="form-control"
id="correo_electronico"
/>
</div> </div>
<div className="p-field col-12 md:col-6"> <div className="p-field col-12 md:col-6">
<label htmlFor="numero_vivienda">Número de Vivienda</label> <label htmlFor="numero_vivienda">Número de Vivienda</label>
<Dropdown id="numero_vivienda" value={communityIdList[0]} options={communitiesList} /> <Dropdown
id="numero_vivienda"
value={communityIdList[0]}
options={communitiesList}
/>
</div> </div>
<Button label="Registrar" onClick={registrarInquilino} /> <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

@ -2,7 +2,6 @@ import React from 'react';
import { InputText } from 'primereact/inputtext'; import { InputText } from 'primereact/inputtext';
const LogIn = () => { const LogIn = () => {
return ( return (
<div className="grid"> <div className="grid">
<div className="col-12"> <div className="col-12">
@ -23,11 +22,9 @@ const LogIn = () => {
</div> </div>
</div> </div>
</div> </div>
) );
} };
export default LogIn export default LogIn;
/* image 1 */ /* image 1 */

View File

@ -3,7 +3,7 @@ import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import App from './App'; import App from './App';
//import * as serviceWorker from './serviceWorker'; //import * as serviceWorker from './serviceWorker';
import { HashRouter } from 'react-router-dom' import { HashRouter } from 'react-router-dom';
import ScrollToTop from './ScrollToTop'; import ScrollToTop from './ScrollToTop';
ReactDOM.render( ReactDOM.render(
@ -12,7 +12,7 @@ ReactDOM.render(
<App></App> <App></App>
</ScrollToTop> </ScrollToTop>
</HashRouter>, </HashRouter>,
document.getElementById('root') document.getElementById('root'),
); );
// If you want your app to work offline and load faster, you can change // If you want your app to work offline and load faster, you can change

View File

@ -24,7 +24,7 @@ const Crud = () => {
price: 0, price: 0,
quantity: 0, quantity: 0,
rating: 0, rating: 0,
inventoryStatus: 'INSTOCK' inventoryStatus: 'INSTOCK',
}; };
const [products, setProducts] = useState(null); const [products, setProducts] = useState(null);
@ -40,31 +40,34 @@ const Crud = () => {
useEffect(() => { useEffect(() => {
const productService = new ProductService(); const productService = new ProductService();
productService.getProducts().then(data => setProducts(data)); productService.getProducts().then((data) => setProducts(data));
}, []); }, []);
const formatCurrency = (value) => { const formatCurrency = (value) => {
return value.toLocaleString('en-US', { style: 'currency', currency: 'USD' }); return value.toLocaleString('en-US', {
} style: 'currency',
currency: 'USD',
});
};
const openNew = () => { const openNew = () => {
setProduct(emptyProduct); setProduct(emptyProduct);
setSubmitted(false); setSubmitted(false);
setProductDialog(true); setProductDialog(true);
} };
const hideDialog = () => { const hideDialog = () => {
setSubmitted(false); setSubmitted(false);
setProductDialog(false); setProductDialog(false);
} };
const hideDeleteProductDialog = () => { const hideDeleteProductDialog = () => {
setDeleteProductDialog(false); setDeleteProductDialog(false);
} };
const hideDeleteProductsDialog = () => { const hideDeleteProductsDialog = () => {
setDeleteProductsDialog(false); setDeleteProductsDialog(false);
} };
const saveProduct = () => { const saveProduct = () => {
setSubmitted(true); setSubmitted(true);
@ -76,38 +79,52 @@ const Crud = () => {
const index = findIndexById(product.id); const index = findIndexById(product.id);
_products[index] = _product; _products[index] = _product;
toast.current.show({ severity: 'success', summary: 'Successful', detail: 'Product Updated', life: 3000 }); toast.current.show({
} severity: 'success',
else { summary: 'Successful',
detail: 'Product Updated',
life: 3000,
});
} else {
_product.id = createId(); _product.id = createId();
_product.image = 'product-placeholder.svg'; _product.image = 'product-placeholder.svg';
_products.push(_product); _products.push(_product);
toast.current.show({ severity: 'success', summary: 'Successful', detail: 'Product Created', life: 3000 }); toast.current.show({
severity: 'success',
summary: 'Successful',
detail: 'Product Created',
life: 3000,
});
} }
setProducts(_products); setProducts(_products);
setProductDialog(false); setProductDialog(false);
setProduct(emptyProduct); setProduct(emptyProduct);
} }
} };
const editProduct = (product) => { const editProduct = (product) => {
setProduct({ ...product }); setProduct({ ...product });
setProductDialog(true); setProductDialog(true);
} };
const confirmDeleteProduct = (product) => { const confirmDeleteProduct = (product) => {
setProduct(product); setProduct(product);
setDeleteProductDialog(true); setDeleteProductDialog(true);
} };
const deleteProduct = () => { const deleteProduct = () => {
let _products = products.filter(val => val.id !== product.id); let _products = products.filter((val) => val.id !== product.id);
setProducts(_products); setProducts(_products);
setDeleteProductDialog(false); setDeleteProductDialog(false);
setProduct(emptyProduct); setProduct(emptyProduct);
toast.current.show({ severity: 'success', summary: 'Successful', detail: 'Product Deleted', life: 3000 }); toast.current.show({
} severity: 'success',
summary: 'Successful',
detail: 'Product Deleted',
life: 3000,
});
};
const findIndexById = (id) => { const findIndexById = (id) => {
let index = -1; let index = -1;
@ -119,38 +136,44 @@ const Crud = () => {
} }
return index; return index;
} };
const createId = () => { const createId = () => {
let id = ''; let id = '';
let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 5; i++) { for (let i = 0; i < 5; i++) {
id += chars.charAt(Math.floor(Math.random() * chars.length)); id += chars.charAt(Math.floor(Math.random() * chars.length));
} }
return id; return id;
} };
const exportCSV = () => { const exportCSV = () => {
dt.current.exportCSV(); dt.current.exportCSV();
} };
const confirmDeleteSelected = () => { const confirmDeleteSelected = () => {
setDeleteProductsDialog(true); setDeleteProductsDialog(true);
} };
const deleteSelectedProducts = () => { const deleteSelectedProducts = () => {
let _products = products.filter(val => !selectedProducts.includes(val)); let _products = products.filter((val) => !selectedProducts.includes(val));
setProducts(_products); setProducts(_products);
setDeleteProductsDialog(false); setDeleteProductsDialog(false);
setSelectedProducts(null); setSelectedProducts(null);
toast.current.show({ severity: 'success', summary: 'Successful', detail: 'Products Deleted', life: 3000 }); toast.current.show({
} severity: 'success',
summary: 'Successful',
detail: 'Products Deleted',
life: 3000,
});
};
const onCategoryChange = (e) => { const onCategoryChange = (e) => {
let _product = { ...product }; let _product = { ...product };
_product['category'] = e.value; _product['category'] = e.value;
setProduct(_product); setProduct(_product);
} };
const onInputChange = (e, name) => { const onInputChange = (e, name) => {
const val = (e.target && e.target.value) || ''; const val = (e.target && e.target.value) || '';
@ -158,7 +181,7 @@ const Crud = () => {
_product[`${name}`] = val; _product[`${name}`] = val;
setProduct(_product); setProduct(_product);
} };
const onInputNumberChange = (e, name) => { const onInputNumberChange = (e, name) => {
const val = e.value || 0; const val = e.value || 0;
@ -166,27 +189,50 @@ const Crud = () => {
_product[`${name}`] = val; _product[`${name}`] = val;
setProduct(_product); setProduct(_product);
} };
const leftToolbarTemplate = () => { const leftToolbarTemplate = () => {
return ( return (
<React.Fragment> <React.Fragment>
<div className="my-2"> <div className="my-2">
<Button label="New" icon="pi pi-plus" className="p-button-success mr-2" onClick={openNew} /> <Button
<Button label="Delete" icon="pi pi-trash" className="p-button-danger" onClick={confirmDeleteSelected} disabled={!selectedProducts || !selectedProducts.length} /> label="New"
icon="pi pi-plus"
className="p-button-success mr-2"
onClick={openNew}
/>
<Button
label="Delete"
icon="pi pi-trash"
className="p-button-danger"
onClick={confirmDeleteSelected}
disabled={!selectedProducts || !selectedProducts.length}
/>
</div> </div>
</React.Fragment> </React.Fragment>
) );
} };
const rightToolbarTemplate = () => { const rightToolbarTemplate = () => {
return ( return (
<React.Fragment> <React.Fragment>
<FileUpload mode="basic" accept="image/*" maxFileSize={1000000} label="Import" chooseLabel="Import" className="mr-2 inline-block" /> <FileUpload
<Button label="Export" icon="pi pi-upload" className="p-button-help" onClick={exportCSV} /> mode="basic"
accept="image/*"
maxFileSize={1000000}
label="Import"
chooseLabel="Import"
className="mr-2 inline-block"
/>
<Button
label="Export"
icon="pi pi-upload"
className="p-button-help"
onClick={exportCSV}
/>
</React.Fragment> </React.Fragment>
) );
} };
const codeBodyTemplate = (rowData) => { const codeBodyTemplate = (rowData) => {
return ( return (
@ -195,7 +241,7 @@ const Crud = () => {
{rowData.code} {rowData.code}
</> </>
); );
} };
const nameBodyTemplate = (rowData) => { const nameBodyTemplate = (rowData) => {
return ( return (
@ -204,16 +250,21 @@ const Crud = () => {
{rowData.name} {rowData.name}
</> </>
); );
} };
const imageBodyTemplate = (rowData) => { const imageBodyTemplate = (rowData) => {
return ( return (
<> <>
<span className="p-column-title">Image</span> <span className="p-column-title">Image</span>
<img src={`assets/demo/images/product/${rowData.image}`} alt={rowData.image} className="shadow-2" width="100" /> <img
src={`assets/demo/images/product/${rowData.image}`}
alt={rowData.image}
className="shadow-2"
width="100"
/>
</> </>
) );
} };
const priceBodyTemplate = (rowData) => { const priceBodyTemplate = (rowData) => {
return ( return (
@ -222,7 +273,7 @@ const Crud = () => {
{formatCurrency(rowData.price)} {formatCurrency(rowData.price)}
</> </>
); );
} };
const categoryBodyTemplate = (rowData) => { const categoryBodyTemplate = (rowData) => {
return ( return (
@ -231,7 +282,7 @@ const Crud = () => {
{rowData.category} {rowData.category}
</> </>
); );
} };
const ratingBodyTemplate = (rowData) => { const ratingBodyTemplate = (rowData) => {
return ( return (
@ -240,52 +291,98 @@ const Crud = () => {
<Rating value={rowData.rating} readonly cancel={false} /> <Rating value={rowData.rating} readonly cancel={false} />
</> </>
); );
} };
const statusBodyTemplate = (rowData) => { const statusBodyTemplate = (rowData) => {
return ( return (
<> <>
<span className="p-column-title">Hi Status</span> <span className="p-column-title">Hi Status</span>
<span className={`product-badge status-${rowData.inventoryStatus.toLowerCase()}`}>{rowData.inventoryStatus}</span> <span
className={`product-badge status-${rowData.inventoryStatus.toLowerCase()}`}
>
{rowData.inventoryStatus}
</span>
</> </>
) );
} };
const actionBodyTemplate = (rowData) => { const actionBodyTemplate = (rowData) => {
return ( return (
<div className="actions"> <div className="actions">
<Button icon="pi pi-pencil" className="p-button-rounded p-button-success mr-2" onClick={() => editProduct(rowData)} /> <Button
<Button icon="pi pi-trash" className="p-button-rounded p-button-warning mt-2" onClick={() => confirmDeleteProduct(rowData)} /> icon="pi pi-pencil"
className="p-button-rounded p-button-success mr-2"
onClick={() => editProduct(rowData)}
/>
<Button
icon="pi pi-trash"
className="p-button-rounded p-button-warning mt-2"
onClick={() => confirmDeleteProduct(rowData)}
/>
</div> </div>
); );
} };
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">Manage Products</h5> <h5 className="m-0">Manage Products</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="Search..." /> <InputText
type="search"
onInput={(e) => setGlobalFilter(e.target.value)}
placeholder="Search..."
/>
</span> </span>
</div> </div>
); );
const productDialogFooter = ( const productDialogFooter = (
<> <>
<Button label="Cancel" icon="pi pi-times" className="p-button-text" onClick={hideDialog} /> <Button
<Button label="Save" icon="pi pi-check" className="p-button-text" onClick={saveProduct} /> label="Cancel"
icon="pi pi-times"
className="p-button-text"
onClick={hideDialog}
/>
<Button
label="Save"
icon="pi pi-check"
className="p-button-text"
onClick={saveProduct}
/>
</> </>
); );
const deleteProductDialogFooter = ( const deleteProductDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteProductDialog} /> <Button
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteProduct} /> label="No"
icon="pi pi-times"
className="p-button-text"
onClick={hideDeleteProductDialog}
/>
<Button
label="Yes"
icon="pi pi-check"
className="p-button-text"
onClick={deleteProduct}
/>
</> </>
); );
const deleteProductsDialogFooter = ( const deleteProductsDialogFooter = (
<> <>
<Button label="No" icon="pi pi-times" className="p-button-text" onClick={hideDeleteProductsDialog} /> <Button
<Button label="Yes" icon="pi pi-check" className="p-button-text" onClick={deleteSelectedProducts} /> label="No"
icon="pi pi-times"
className="p-button-text"
onClick={hideDeleteProductsDialog}
/>
<Button
label="Yes"
icon="pi pi-check"
className="p-button-text"
onClick={deleteSelectedProducts}
/>
</> </>
); );
@ -294,53 +391,169 @@ const Crud = () => {
<div className="col-12"> <div className="col-12">
<div className="card"> <div className="card">
<Toast ref={toast} /> <Toast ref={toast} />
<Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate}></Toolbar> <Toolbar
className="mb-4"
left={leftToolbarTemplate}
right={rightToolbarTemplate}
></Toolbar>
<DataTable ref={dt} value={products} selection={selectedProducts} onSelectionChange={(e) => setSelectedProducts(e.value)} <DataTable
dataKey="id" paginator rows={10} rowsPerPageOptions={[5, 10, 25]} className="datatable-responsive" ref={dt}
value={products}
selection={selectedProducts}
onSelectionChange={(e) => setSelectedProducts(e.value)}
dataKey="id"
paginator
rows={10}
rowsPerPageOptions={[5, 10, 25]}
className="datatable-responsive"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown" paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} products" currentPageReportTemplate="Showing {first} to {last} of {totalRecords} products"
globalFilter={globalFilter} emptyMessage="No products found." header={header} responsiveLayout="scroll"> globalFilter={globalFilter}
<Column selectionMode="multiple" headerStyle={{ width: '3rem'}}></Column> emptyMessage="No products found."
<Column field="code" header="Code" sortable body={codeBodyTemplate} headerStyle={{ width: '14%', minWidth: '10rem' }}></Column> header={header}
<Column field="name" header="Name" sortable body={nameBodyTemplate} headerStyle={{ width: '14%', minWidth: '10rem' }}></Column> responsiveLayout="scroll"
<Column header="Image" body={imageBodyTemplate} headerStyle={{ width: '14%', minWidth: '10rem' }}></Column> >
<Column field="price" header="Price" body={priceBodyTemplate} sortable headerStyle={{ width: '14%', minWidth: '8rem' }}></Column> <Column
<Column field="category" header="Category" sortable body={categoryBodyTemplate} headerStyle={{ width: '14%', minWidth: '10rem' }}></Column> selectionMode="multiple"
<Column field="rating" header="Reviews" body={ratingBodyTemplate} sortable headerStyle={{ width: '14%', minWidth: '10rem' }}></Column> headerStyle={{ width: '3rem' }}
<Column field="inventoryStatus" header="Status" body={statusBodyTemplate} sortable headerStyle={{ width: '14%', minWidth: '10rem' }}></Column> ></Column>
<Column
field="code"
header="Code"
sortable
body={codeBodyTemplate}
headerStyle={{ width: '14%', minWidth: '10rem' }}
></Column>
<Column
field="name"
header="Name"
sortable
body={nameBodyTemplate}
headerStyle={{ width: '14%', minWidth: '10rem' }}
></Column>
<Column
header="Image"
body={imageBodyTemplate}
headerStyle={{ width: '14%', minWidth: '10rem' }}
></Column>
<Column
field="price"
header="Price"
body={priceBodyTemplate}
sortable
headerStyle={{ width: '14%', minWidth: '8rem' }}
></Column>
<Column
field="category"
header="Category"
sortable
body={categoryBodyTemplate}
headerStyle={{ width: '14%', minWidth: '10rem' }}
></Column>
<Column
field="rating"
header="Reviews"
body={ratingBodyTemplate}
sortable
headerStyle={{ width: '14%', minWidth: '10rem' }}
></Column>
<Column
field="inventoryStatus"
header="Status"
body={statusBodyTemplate}
sortable
headerStyle={{ width: '14%', minWidth: '10rem' }}
></Column>
<Column body={actionBodyTemplate}></Column> <Column body={actionBodyTemplate}></Column>
</DataTable> </DataTable>
<Dialog visible={productDialog} style={{ width: '450px' }} header="Product Details" modal className="p-fluid" footer={productDialogFooter} onHide={hideDialog}> <Dialog
{product.image && <img src={`assets/demo/images/product/${product.image}`} alt={product.image} width="150" className="mt-0 mx-auto mb-5 block shadow-2" />} visible={productDialog}
style={{ width: '450px' }}
header="Product Details"
modal
className="p-fluid"
footer={productDialogFooter}
onHide={hideDialog}
>
{product.image && (
<img
src={`assets/demo/images/product/${product.image}`}
alt={product.image}
width="150"
className="mt-0 mx-auto mb-5 block shadow-2"
/>
)}
<div className="field"> <div className="field">
<label htmlFor="name">Name</label> <label htmlFor="name">Name</label>
<InputText id="name" value={product.name} onChange={(e) => onInputChange(e, 'name')} required autoFocus className={classNames({ 'p-invalid': submitted && !product.name })} /> <InputText
{submitted && !product.name && <small className="p-invalid">Name is required.</small>} id="name"
value={product.name}
onChange={(e) => onInputChange(e, 'name')}
required
autoFocus
className={classNames({
'p-invalid': submitted && !product.name,
})}
/>
{submitted && !product.name && (
<small className="p-invalid">Name is required.</small>
)}
</div> </div>
<div className="field"> <div className="field">
<label htmlFor="description">Description</label> <label htmlFor="description">Description</label>
<InputTextarea id="description" value={product.description} onChange={(e) => onInputChange(e, 'description')} required rows={3} cols={20} /> <InputTextarea
id="description"
value={product.description}
onChange={(e) => onInputChange(e, 'description')}
required
rows={3}
cols={20}
/>
</div> </div>
<div className="field"> <div className="field">
<label className="mb-3">Category</label> <label className="mb-3">Category</label>
<div className="formgrid grid"> <div className="formgrid grid">
<div className="field-radiobutton col-6"> <div className="field-radiobutton col-6">
<RadioButton inputId="category1" name="category" value="Accessories" onChange={onCategoryChange} checked={product.category === 'Accessories'} /> <RadioButton
inputId="category1"
name="category"
value="Accessories"
onChange={onCategoryChange}
checked={product.category === 'Accessories'}
/>
<label htmlFor="category1">Accessories</label> <label htmlFor="category1">Accessories</label>
</div> </div>
<div className="field-radiobutton col-6"> <div className="field-radiobutton col-6">
<RadioButton inputId="category2" name="category" value="Clothing" onChange={onCategoryChange} checked={product.category === 'Clothing'} /> <RadioButton
inputId="category2"
name="category"
value="Clothing"
onChange={onCategoryChange}
checked={product.category === 'Clothing'}
/>
<label htmlFor="category2">Clothing</label> <label htmlFor="category2">Clothing</label>
</div> </div>
<div className="field-radiobutton col-6"> <div className="field-radiobutton col-6">
<RadioButton inputId="category3" name="category" value="Electronics" onChange={onCategoryChange} checked={product.category === 'Electronics'} /> <RadioButton
inputId="category3"
name="category"
value="Electronics"
onChange={onCategoryChange}
checked={product.category === 'Electronics'}
/>
<label htmlFor="category3">Electronics</label> <label htmlFor="category3">Electronics</label>
</div> </div>
<div className="field-radiobutton col-6"> <div className="field-radiobutton col-6">
<RadioButton inputId="category4" name="category" value="Fitness" onChange={onCategoryChange} checked={product.category === 'Fitness'} /> <RadioButton
inputId="category4"
name="category"
value="Fitness"
onChange={onCategoryChange}
checked={product.category === 'Fitness'}
/>
<label htmlFor="category4">Fitness</label> <label htmlFor="category4">Fitness</label>
</div> </div>
</div> </div>
@ -349,33 +562,73 @@ const Crud = () => {
<div className="formgrid grid"> <div className="formgrid grid">
<div className="field col"> <div className="field col">
<label htmlFor="price">Price</label> <label htmlFor="price">Price</label>
<InputNumber id="price" value={product.price} onValueChange={(e) => onInputNumberChange(e, 'price')} mode="currency" currency="USD" locale="en-US" /> <InputNumber
id="price"
value={product.price}
onValueChange={(e) => onInputNumberChange(e, 'price')}
mode="currency"
currency="USD"
locale="en-US"
/>
</div> </div>
<div className="field col"> <div className="field col">
<label htmlFor="quantity">Quantity</label> <label htmlFor="quantity">Quantity</label>
<InputNumber id="quantity" value={product.quantity} onValueChange={(e) => onInputNumberChange(e, 'quantity')} integeronly /> <InputNumber
id="quantity"
value={product.quantity}
onValueChange={(e) => onInputNumberChange(e, 'quantity')}
integeronly
/>
</div> </div>
</div> </div>
</Dialog> </Dialog>
<Dialog visible={deleteProductDialog} style={{ width: '450px' }} header="Confirm" modal footer={deleteProductDialogFooter} onHide={hideDeleteProductDialog}> <Dialog
visible={deleteProductDialog}
style={{ width: '450px' }}
header="Confirm"
modal
footer={deleteProductDialogFooter}
onHide={hideDeleteProductDialog}
>
<div className="flex align-items-center justify-content-center"> <div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> <i
{product && <span>Are you sure you want to delete <b>{product.name}</b>?</span>} className="pi pi-exclamation-triangle mr-3"
style={{ fontSize: '2rem' }}
/>
{product && (
<span>
Are you sure you want to delete <b>{product.name}</b>?
</span>
)}
</div> </div>
</Dialog> </Dialog>
<Dialog visible={deleteProductsDialog} style={{ width: '450px' }} header="Confirm" modal footer={deleteProductsDialogFooter} onHide={hideDeleteProductsDialog}> <Dialog
visible={deleteProductsDialog}
style={{ width: '450px' }}
header="Confirm"
modal
footer={deleteProductsDialogFooter}
onHide={hideDeleteProductsDialog}
>
<div className="flex align-items-center justify-content-center"> <div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> <i
{product && <span>Are you sure you want to delete the selected products?</span>} className="pi pi-exclamation-triangle mr-3"
style={{ fontSize: '2rem' }}
/>
{product && (
<span>
Are you sure you want to delete the selected products?
</span>
)}
</div> </div>
</Dialog> </Dialog>
</div> </div>
</div> </div>
</div> </div>
); );
} };
const comparisonFn = function (prevProps, nextProps) { const comparisonFn = function (prevProps, nextProps) {
return prevProps.location.pathname === nextProps.location.pathname; return prevProps.location.pathname === nextProps.location.pathname;

Some files were not shown because too many files have changed in this diff Show More