Merge branch 'dev' of github.com:DeimosPr4/katoikia-app into movil

This commit is contained in:
Maria Sanchez 2022-08-23 11:58:44 -06:00
commit b8d9bd0a4a
21 changed files with 1696 additions and 395 deletions

View File

@ -82,6 +82,35 @@ export class AppController {
);
}
@Post('user/createTenant')
createTenant(
@Body('dni') dni: string,
@Body('name') name: string,
@Body('last_name') last_name: string,
@Body('email') email: string,
@Body('phone') phone: number,
@Body('user_type') user_type: string,
@Body('status') status: string,
@Body('date_entry') date_entry: Date,
@Body('community_id') community_id: string,
@Body('number_house') number_house: string,
) {
return this.appService.createTenant(
dni,
name,
last_name,
email,
phone,
user_type,
status,
date_entry,
community_id,
number_house,
);
}
@Put('user/updateGuard/:id')
updateGuard(
@Param('id') id: string,
@ -195,9 +224,13 @@ export class AppController {
return this.appService.deleteAdminCommunity(id);
}
@Delete('user/deleteTenant/:id')
deleteTenant(@Param('id') id: string) {
return this.appService.deleteTenant(id);
@Put('user/deleteTenant/:id')
deleteTenant(
@Param('id') id: string,
@Body('community_id') community_id: string,
@Body('number_house') number_house: string
) {
return this.appService.deleteTenant(id, community_id, number_house);
}
@Post('user/changeStatus')
@ -208,6 +241,40 @@ export class AppController {
return this.appService.changeStatusUser(pId, pStatus);
}
@Put('user/updateAdminCommunity/:id')
updateAdminCommunity(
@Param('id') id: string,
@Body('dni') dni: string,
@Body('name') name: string,
@Body('last_name') last_name: string,
@Body('email') email: string,
@Body('phone') phone: number,
@Body('community_id') community_id: string,
) {
return this.appService.updateAdminCommunity(
id,
dni,
name,
last_name,
email,
phone,
community_id,
);
}
@Post('user/updateAdminSystem')
updateAdminSystem(
//Nombre, Apellidos, Correo electrónico, Cédula, Teléfono
@Body('_id') _id: string,
@Body('dni') dni: string,
@Body('name') name: string,
@Body('last_name') last_name: string,
@Body('email') email: string,
@Body('phone') phone: number,
) {
return this.appService.updateAdminSystem(_id, dni, name, last_name, email, phone);
}
// #==== API Communities
@Post('community/createCommunity')
createCommunity(
@ -261,7 +328,21 @@ export class AppController {
return this.appService.changeStatusCommunity(pId, pStatus);
}
@Get('community/findHousesCommunity/:id')
findHousesCommunity(
@Param('id') community_id: string,
) {
return this.appService.findHousesCommunity(community_id);
}
@Post('community/saveTenant')
saveTenant(
@Body('community_id') community_id: string,
@Body('number_house') number_house: string,
@Body('tenant_id') tenant_id: string,
) {
return this.appService.saveTenant(community_id, number_house, tenant_id);
}
// #==== API Common Areas
@Post('commonArea/createCommonArea')
createCommonArea(
@ -438,6 +519,11 @@ export class AppController {
return this.appService.findPost(paramPost);
}
@Delete('post/deletePost/:id')
deletePost(@Param('id') id: string) {
return this.appService.deletePost(id);
}
// #==== API Comment
@Post('post/createComment')

View File

@ -1,6 +1,7 @@
import { Injectable, Inject } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { map } from 'rxjs/operators';
import { lastValueFrom } from 'rxjs';
@Injectable()
export class AppService {
@ -55,6 +56,37 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
createTenant(
dni: string,
name: string,
last_name: string,
email: string,
phone: number,
user_type: string,
status: string,
date_entry: Date,
community_id: string,
number_house: string,
) {
const pattern = { cmd: 'createTenant' };
const payload = {
dni: dni,
name: name,
last_name: last_name,
email: email,
phone: phone,
password: this.generatePassword(),
user_type: user_type,
status: status,
date_entry: date_entry,
community_id: community_id,
number_house: number_house,
};
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
updateUser(
_id: string,
dni: string,
@ -120,7 +152,29 @@ export class AppService {
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
updateAdminCommunity(
id: string,
dni: string,
name: string,
last_name: string,
email: string,
phone: number,
community_id: string,
) {
const pattern = { cmd: 'updateAdminCommunity' };
const payload = {
_id: id,
dni: dni,
name: name,
last_name: last_name,
email: email,
phone: phone,
community_id: community_id,
};
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
//POST parameter from API
createAdminSystem(dni: string, name: string, last_name: string, email: string, phone: number
, user_type: string, status: string, date_entry: Date) {
@ -239,9 +293,9 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
deleteTenant(id: string) {
deleteTenant(id: string, community_id: string, number_house: string) {
const pattern = { cmd: 'deleteTenant' };
const payload = { id: id };
const payload = { _id: id, community_id: community_id, number_house: number_house };
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
@ -255,6 +309,19 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
updateAdminSystem(_id: string, dni: string, name: string,
last_name: string, email: string, phone: number
) {
const pattern = { cmd: 'updateAdminSystem' };
const payload = {
_id: _id, dni: dni, name: name, last_name: last_name,
email: email, phone: phone
};
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
//GET parameter from API
findCommunityAdmin(community_id: string) {
const pattern = { cmd: 'findCommunityAdmin' };
@ -337,6 +404,31 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
async findHousesCommunity(community_id: string) {
const pattern = { cmd: 'findOneCommunity' }
const payload = { _id: community_id }
let callback = await this.clientCommunityApp
.send<string>(pattern, payload)
.pipe(
map((response: string) => ({ response }))
)
const finalValue = await lastValueFrom(callback);
const response = finalValue['response'];
const houses = response['houses'];
return houses;
}
saveTenant(id: string, number_house: string, tenant_id: string) {
const pattern = { cmd: 'saveTenant' };
const payload = { _id: id, number_house: number_house, tenant_id: tenant_id };
return this.clientCommunityApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
// ====================== COMMON AREAS ===============================
//POST parameter from API
createCommonArea(
@ -557,6 +649,15 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
//DELETE
deletePost(paramPostId: string) {
const pattern = { cmd: 'removePost' };
const payload = { id: paramPostId };
return this.clientPostApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
// ====================== COMMNENT POSTS ===============================
//Comment parameter from API

View File

@ -53,4 +53,22 @@ export class CommunitiesController {
let pstatus = body['status'];
return this.communitiesService.changeStatus(pid,pstatus);
}
@MessagePattern({ cmd: 'saveTenant' })
saveTenant(@Payload() body: string) {
let id = body['_id'];
let tenant_id = body['tenant_id'];
let number_house = body['number_house'];
return this.communitiesService.saveTenant(id, number_house, tenant_id);
}
@MessagePattern({ cmd: 'deleteTenant' })
deleteTenant(@Payload() body: string) {
let id = body['_id'];
let tenant_id = body['tenant_id'];
let number_house = body['number_house'];
return this.communitiesService.deleteTenant(id, number_house, tenant_id);
}
}

View File

@ -6,6 +6,7 @@ import { RpcException, ClientProxy } from '@nestjs/microservices';
import { from, lastValueFrom, map, scan, mergeMap } from 'rxjs';
import { Admin } from 'src/schemas/admin.entity';
import { appendFileSync } from 'fs';
import { Tenant, TenantSchema } from 'src/schemas/tenant.schema';
@Injectable()
export class CommunitiesService {
@ -78,4 +79,44 @@ export class CommunitiesService {
const finalValue = await lastValueFrom(callback);
return finalValue['response'];
}
async saveTenant(id: string, number_house: string, ptenant_id: string) {
let community = await this.findOne(id);
await community.houses.map(house => {
if (house.number_house == number_house) {
if (house.tenants) {
house.tenants.tenant_id = ptenant_id
} else {
let tenant = new Tenant()
tenant.tenant_id = ptenant_id;
house.tenants = tenant;
}
house.state = "ocupada"
}
return house;
})
return await this.communityModel.findOneAndUpdate({ _id: id }, community, {
new: true,
});
}
async deleteTenant(id: string, number_house: string, tenant_id: string) {
let community = await this.findOne(id);
await community.houses.map(house => {
if (house.number_house === number_house) {
house.tenants.tenant_id = "";
house.state = "desocupada"
}
return house;
})
return await this.communityModel.findOneAndUpdate({ _id: id }, community, {
new: true,
});
}
}

View File

@ -1,7 +1,7 @@
# mail
MAIL_HOST=smtp.gmail.com
MAIL_USER=mbonilla.guti@gmail.com
MAIL_PASSWORD=laofghlofgffmyry
MAIL_USER=katoikiap4@gmail.com
MAIL_PASSWORD=snxwbncohehilkkz
MAIL_FROM=noreply@example.com
# optional

View File

@ -12,7 +12,7 @@ export class EmailController {
sendMail(@Payload() toEmail: string) {
var response = this.mailService.sendMail({
to: toEmail['email'],
from: 'mbonilla.guti@gmail.com',
from: 'katoikiap4@gmail.com',
subject: 'Plain Text Email ✔',
text: 'Welcome NestJS Email Sending Tutorial',
});
@ -25,7 +25,7 @@ export class EmailController {
const image = "images/email.png";
var response = await this.mailService.sendMail({
to: user["email"],
from: "mbonilla.guti@gmail.com",
from: "katoikiap4@gmail.com",
subject: 'HTML Dynamic Template',
template: 'templateEmail',
context: {
@ -51,7 +51,7 @@ export class EmailController {
const logo = "images/Logo Katoikia.png";
var response = await this.mailService.sendMail({
to: user["email"],
from: "mbonilla.guti@gmail.com",
from: "katoikiap4@gmail.com",
subject: 'Usuario registrado',
template: 'emailCreateUserAdminCommunity',
context: {
@ -77,4 +77,39 @@ export class EmailController {
});
return response;
}
@MessagePattern({ cmd: 'emailCreateUserTenant' })
async emailCreateUserTenant(@Payload() user: any) {
const url = "http://localhost:3000/";
const image = "images/email.png";
const logo = "images/Logo Katoikia.png";
var response = await this.mailService.sendMail({
to: user["email"],
from: "katoikiap4@gmail.com",
subject: 'Usuario registrado',
template: 'emailCreateUserTenant',
context: {
name: user["name"],
password: user["password"],
date_entry: user["date_entry"],
email: user["email"],
community_name: user['community_name'],
number_house: user['number_house']
},
attachments: [
{
filename: 'email.png',
path: __dirname + '/mails/images/email.png',
cid: 'image_email' //my mistake was putting "cid:logo@cid" here!
},
{
filename: 'Logo_Katoikia.png',
path: __dirname + '/mails/images/Logo_Katoikia.png',
cid: 'logoKatoikia' //my mistake was putting "cid:logo@cid" here!
}
]
});
return response;
}
}

View File

@ -432,7 +432,7 @@
<td style="text-align: left; padding-left: 5px; padding-right: 5px">
<h3 class="heading">Información de contacto</h3>
<ul>
<li><span href="mailto:katoikiaapp@gmail.com" class="text">katoikiaapp@gmail.com</span></li>
<li><span href="mailto:katoikiap4@gmail.com" class="text">katoikiap4@gmail.com</span></li>
</ul>
</td>
</tr>

View File

@ -438,8 +438,8 @@
<td style="text-align: left; padding-left: 5px; padding-right: 5px">
<h3 class="heading">Información de contacto</h3>
<ul>
<li><span href="mailto:katoikiaapp@gmail.com"
class="text">katoikiaapp@gmail.com</span></li>
<li><span href="mailto:katoikiap4@gmail.com"
class="text">katoikiap4@gmail.com</span></li>
</ul>
</td>
</tr>

View File

@ -0,0 +1,459 @@
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta charset="utf-8"> <!-- utf-8 works for most cases -->
<meta name="viewport" content="width=device-width"> <!-- Forcing initial-scale shouldn't be necessary -->
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Use the latest (edge) version of IE rendering engine -->
<meta name="x-apple-disable-message-reformatting"> <!-- Disable auto-scale in iOS 10 Mail entirely -->
<title></title> <!-- The title tag shows in email notifications, like Android 4.4. -->
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css"
integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
<!-- CSS Reset : BEGIN -->
<style>
html,
body {
margin: 0 auto !important;
padding: 0 !important;
height: 100% !important;
width: 100% !important;
background: #f1f1f1;
}
/* What it does: Stops email clients resizing small text. */
* {
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}
/* What it does: Centers email on Android 4.4 */
div[style*="margin: 16px 0"] {
margin: 0 !important;
}
/* What it does: Stops Outlook from adding extra spacing to tables. */
table,
td {
mso-table-lspace: 0pt !important;
mso-table-rspace: 0pt !important;
}
/* What it does: Fixes webkit padding issue. */
table {
border-spacing: 0 !important;
border-collapse: collapse !important;
table-layout: fixed !important;
margin: 0 auto !important;
}
/* What it does: Uses a better rendering method when resizing images in IE. */
img {
-ms-interpolation-mode: bicubic;
}
/* What it does: Prevents Windows 10 Mail from underlining links despite inline CSS. Styles for underlined links should be inline. */
a {
text-decoration: none;
}
/* What it does: A work-around for email clients meddling in triggered links. */
*[x-apple-data-detectors],
/* iOS */
.unstyle-auto-detected-links *,
.aBn {
border-bottom: 0 !important;
cursor: default !important;
color: inherit !important;
text-decoration: none !important;
font-size: inherit !important;
font-family: inherit !important;
font-weight: inherit !important;
line-height: inherit !important;
}
/* What it does: Prevents Gmail from displaying a download button on large, non-linked images. */
.a6S {
display: none !important;
opacity: 0.01 !important;
}
/* What it does: Prevents Gmail from changing the text color in conversation threads. */
.im {
color: inherit !important;
}
/* If the above doesn't work, add a .g-img class to any image in question. */
img.g-img+div {
display: none !important;
}
/* What it does: Removes right gutter in Gmail iOS app: https://github.com/TedGoas/Cerberus/issues/89 */
/* Create one of these media queries for each additional viewport size you'd like to fix */
/* iPhone 4, 4S, 5, 5S, 5C, and 5SE */
@media only screen and (min-device-width: 320px) and (max-device-width: 374px) {
u~div .email-container {
min-width: 320px !important;
}
}
/* iPhone 6, 6S, 7, 8, and X */
@media only screen and (min-device-width: 375px) and (max-device-width: 413px) {
u~div .email-container {
min-width: 375px !important;
}
}
/* iPhone 6+, 7+, and 8+ */
@media only screen and (min-device-width: 414px) {
u~div .email-container {
min-width: 414px !important;
}
}
</style>
<!-- CSS Reset : END -->
<!-- Progressive Enhancements : BEGIN -->
<style>
.primary {
background: #D7A86E;
}
.bg_white {
background: #ffffff;
}
.bg_light {
background: #fafafa;
}
.bg_black {
background: #000000;
}
.bg_dark {
background: rgba(0, 0, 0, .8);
}
.email-section {
padding: 2.5em;
}
/*BUTTON*/
.btn {
padding: 10px 15px;
display: inline-block;
}
.btn.btn-primary {
border-radius: 5px;
background: #D7A86E;
color: #ffffff;
}
.btn.btn-white {
border-radius: 5px;
background: #ffffff;
color: #000000;
}
.btn.btn-white-outline {
border-radius: 5px;
background: transparent;
border: 1px solid #fff;
color: #fff;
}
.btn.btn-black-outline {
border-radius: 0px;
background: transparent;
border: 2px solid #000;
color: #000;
font-weight: 700;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'Lato', sans-serif;
color: #000000;
margin-top: 0;
font-weight: 400;
margin-bottom: 12px;
}
body {
font-family: 'Lato', sans-serif;
font-weight: 400;
font-size: 15px;
line-height: 1.8;
color: rgba(0, 0, 0, 0.808);
}
a {
color: #D7A86E;
}
table {}
/*LOGO*/
.logo h1 {
margin: 0;
}
.logo h1 a {
color: #D7A86E;
font-size: 24px;
font-weight: 700;
font-family: 'Lato', sans-serif;
}
/*HERO*/
.hero {
position: relative;
z-index: 0;
}
.hero .text {
color: rgba(0, 0, 0, 0.884);
}
.hero .text h2 {
color: #000;
font-size: 40px;
margin-bottom: 0;
font-weight: 400;
line-height: 1.4;
}
.hero .text h3 {
font-size: 24px;
font-weight: 300;
}
.hero .text h2 span {
font-weight: 600;
color: #D7A86E;
}
/*HEADING SECTION*/
.heading-section {}
.heading-section h2 {
color: #000000;
font-size: 28px;
margin-top: 0;
line-height: 1.4;
font-weight: 400;
}
.heading-section .subheading {
margin-bottom: 20px !important;
display: inline-block;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 2px;
color: rgba(0, 0, 0, .4);
position: relative;
}
.heading-section .subheading::after {
position: absolute;
left: 0;
right: 0;
bottom: -10px;
content: '';
width: 100%;
height: 2px;
background: #D7A86E;
margin: 0 auto;
}
.heading-section-white {
color: rgba(255, 255, 255, .8);
}
.heading-section-white h2 {
line-height: 1;
padding-bottom: 0;
}
.heading-section-white h2 {
color: #ffffff;
}
.heading-section-white .subheading {
margin-bottom: 0;
display: inline-block;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 2px;
color: rgba(255, 255, 255, .4);
}
ul.social {
padding: 0;
}
ul.social li {
display: inline-block;
margin-right: 10px;
}
/*FOOTER*/
.footer {
border-top: 1px solid rgba(0, 0, 0, .05);
color: rgba(0, 0, 0, .5);
}
.footer .heading {
color: #000;
font-size: 20px;
}
.footer ul {
margin: 0;
padding: 0;
}
.footer ul li {
list-style: none;
margin-bottom: 10px;
}
.footer ul li a {
color: rgba(0, 0, 0, 1);
}
@media screen and (max-width: 500px) {}
</style>
</head>
<body width="100%" style="margin: 0; padding: 0 !important; mso-line-height-rule: exactly; background-color: #f1f1f1;">
<center style="width: 100%; background-color: #f1f1f1;">
<div
style="display: none; font-size: 1px;max-height: 0px; max-width: 0px; opacity: 0; overflow: hidden; mso-hide: all; font-family: sans-serif;">
&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;
</div>
<div style="max-width: 600px; margin: 0 auto;" class="email-container">
<!-- BEGIN BODY -->
<table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%"
style="margin: auto;">
<tr>
<td valign="top" class="bg_white" style="padding: 1em 2.5em 0 2.5em;">
<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td class="logo" style="text-align: right;">
<img src="cid:logoKatoikia" alt="Logo Katoikia"
style="width: 60px; max-width: 60px; height: auto; margin: auto; display: block; float: right;">
</td>
<td class="logo" style="text-align: left;">
<h1><a href="#">Katoikia</a></h1>
</td>
</tr>
</table>
</td>
</tr><!-- end tr -->
<tr>
<td valign="middle" class="hero bg_white" style="padding: 3em 0 2em 0;">
<img src="cid:image_email" alt="Logo Katoikia"
style="width: 150px; max-width: 300px; height: auto; margin: auto; display: block;">
</td>
</tr><!-- end tr -->
<tr>
<td valign="middle" class="hero bg_white" style="padding: 2em 0 4em 0;">
<table>
<tr>
<td>
<div class="text" style="padding: 0 2.5em; text-align: center;">
<h2> Hola , {{ name }} <i class="fa-regular fa-face-smile-wink"
style="color:#D7A86E; font-size: 0.8em; margin-left: 20px;"></i></h2>
<h3>Ha sido registrado como un Inquilino en Katoikia </h3>
<h4><i class="fa-solid fa-calendar-day"
style="color:#D7A86E; margin-right: 10px;"></i> Fecha de registro
{{date_entry}}</h4>
</div>
<div class="text" style="padding: 0 4em; text-align: left;">
<p>Fue asignado en la comunidad "{{community_name}}" en la vivienda #{{number_house}}</p>
</div>
<div class="text" style="padding: 0 4em; text-align: left;">
<h3>Estas son sus credenciales:</h3>
<p><i class="fa-regular fa-envelope" style="color:#D7A86E; margin-right: 10px;"></i> Correo electronico: {{email}}</p>
<p><i class="fa-solid fa-key" style="color:#D7A86E; margin-right: 10px;"></i> Password: {{password}}</p>
</div>
<div class="text" style="padding: 0 2.5em; text-align: center;">
<h3>Ahora puede ingresar con sus credenciales en la app móvil</h3>
</div>
</td>
</tr>
</table>
</td>
</tr><!-- end tr -->
<!-- 1 Column Text + Button : END -->
</table>
<table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%"
style="margin: auto;">
<td valign="middle" class="bg_light footer email-section">
<table>
<tr>
<td valign="top" width="33.333%" style="padding-top: 20px">
<table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td style="text-align: left; padding-right: 10px">
<h3 class="heading">Acerca de</h3>
<p>Katoikia es su compañero más cercano para poder estar en contacto con sus vecinos y conocer sobre los mejores anuncios sobre su comunidad.</p>
</td>
</tr>
</table>
</td>
<td valign="top" width="33.333%" style="padding-top: 20px">
<table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td style="text-align: left; padding-left: 5px; padding-right: 5px">
<h3 class="heading">Información de contacto</h3>
<ul>
<li><span href="mailto:katoikiap4@gmail.com" class="text">katoikiap4@gmail.com</span></li>
</ul>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<!-- end: tr -->
<tr>
<td class="bg_light" style="text-align: center">
<p><a href="http://localhost:3000" style="color: rgba(0, 0, 0, 0.8)">katoikiaapp.org</a></p>
</td>
</table>
</div>
</center>
</body>
</html>

View File

@ -1 +0,0 @@
export class CreateNotificationDto {}

View File

@ -1,6 +0,0 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateNotificationDto } from './create-notification.dto';
export class UpdateNotificationDto extends PartialType(CreateNotificationDto) {
id: number;
}

View File

@ -1,38 +0,0 @@
import { Controller } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices';
import { NotificationsService } from './notifications.service';
import { CreateNotificationDto } from './dto/create-notification.dto';
import { UpdateNotificationDto } from './dto/update-notification.dto';
@Controller()
export class NotificationsController {
constructor(private readonly notificationsService: NotificationsService) {}
@MessagePattern({ cmd: 'createNotification' })
create(@Payload() createNotificationDto: CreateNotificationDto) {
return this.notificationsService.create(createNotificationDto);
}
@MessagePattern({ cmd: 'findAllNotifications' })
findAll() {
return this.notificationsService.findAll();
}
@MessagePattern({ cmd: 'findOneNotification' })
findOne(@Payload() id: number) {
return this.notificationsService.findOne(id);
}
@MessagePattern({ cmd: 'updateNotification' })
update(@Payload() updateNotificationDto: UpdateNotificationDto) {
return this.notificationsService.update(
updateNotificationDto.id,
updateNotificationDto,
);
}
@MessagePattern({ cmd: 'removeNotification' })
remove(@Payload() id: number) {
return this.notificationsService.remove(id);
}
}

View File

@ -1,9 +0,0 @@
import { Module } from '@nestjs/common';
import { NotificationsService } from './notifications.service';
import { NotificationsController } from './notifications.controller';
@Module({
controllers: [NotificationsController],
providers: [NotificationsService],
})
export class NotificationsModule {}

View File

@ -1,26 +0,0 @@
import { Injectable } from '@nestjs/common';
import { CreateNotificationDto } from './dto/create-notification.dto';
import { UpdateNotificationDto } from './dto/update-notification.dto';
@Injectable()
export class NotificationsService {
create(createNotificationDto: CreateNotificationDto) {
return 'This action adds a new notification';
}
findAll() {
return `This action returns all notifications`;
}
findOne(id: number) {
return `This action returns a #${id} notification`;
}
update(id: number, updateNotificationDto: UpdateNotificationDto) {
return `This action updates a #${id} notification`;
}
remove(id: number) {
return `This action removes a #${id} notification`;
}
}

View File

@ -1 +0,0 @@
export class Notification {}

View File

@ -29,6 +29,12 @@ export class UsersController {
return this.userService.createAdminCommunity(user);
}
@MessagePattern({ cmd: 'createTenant' })
createTenant(@Payload() user: UserDocument) {
return this.userService.createTenant(user);
}
@MessagePattern({ cmd: 'findAllUsers' })
findAll() {
return this.userService.findAll();
@ -66,7 +72,7 @@ export class UsersController {
@MessagePattern({ cmd: 'updateUser' })
update(@Payload() user: UserDocument) {
return this.userService.update(user.id, user);
return this.userService.update(user._id, user);
}
@MessagePattern({ cmd: 'updateGuard' })
@ -74,12 +80,20 @@ export class UsersController {
return this.userService.update(guard.id, guard);
}
@MessagePattern({ cmd: 'updateAdminCommunity' })
updateAdminCommunity(@Payload() user: UserDocument) {
return this.userService.update(user._id, user);
}
@MessagePattern({ cmd: 'removeUser' })
remove(@Payload() id: string) {
let dni = id['dni'];
return this.userService.remove(dni);
}
@MessagePattern({ cmd: 'updateAdminSystem' })
updateAdminSystem(@Payload() user: UserDocument) {
return this.userService.updateAdminSystem(user._id, user);
}
//inicio de sesion
@MessagePattern({ cmd: 'loginUser' })
findLogin(@Payload() body: string) {
@ -127,7 +141,10 @@ export class UsersController {
@MessagePattern({ cmd: 'deleteTenant' })
deleteTenant(@Payload() user: any) {
return this.userService.deleteTenant(user['id']);
let tenant_id = user['_id'];
return this.userService.deleteTenant(tenant_id,
user['community_id'],
user['number_house']);
}
@MessagePattern({ cmd: 'changeStatus' })

View File

@ -24,6 +24,31 @@ export class UsersService {
}
async createTenant(user: UserDocument) {
let password = user.password;
let passwordEncriptada = Md5.init(user.password);
user.password = passwordEncriptada;
let userCreated = await this.userModel.create(user);
await this.saveTenantNumHouse(user.community_id, user.number_house, userCreated['_id']);
let community = await this.findCommunity(user.community_id);
user.community_id = community['name'];
const pattern = { cmd: 'emailCreateUserTenant' };
const payload = {
email: user['email'], password: password, name: user['name'],
date_entry: user['date_entry'], community_name: community['name'],
number_house: user['number_house']
};
return this.clientNotificationtApp
.send<string>(pattern, payload)
.pipe(
map((message: string) => ({ message })),
);
}
async createAdminCommunity(user: UserDocument) {
let password = user.password;
let passwordEncriptada = Md5.init(user.password);
@ -78,6 +103,15 @@ export class UsersService {
});
}
async updateAdminSystem(id: string, user: UserDocument) {
return this.userModel.findOneAndUpdate({ _id: id }, {
name: user['name'], last_name: user['last_name'],
dni:user['dni'], email: user['email'], phone: user['phone']
}, {
new: true,
});
}
/* async remove(id: string) {
return this.userModel.findByIdAndRemove({ _id: id }).exec();
}*/
@ -145,7 +179,6 @@ export class UsersService {
return await this.userModel.find({ community_id: pcommunity_id, user_type: 4 })
}
async testSendMail(user: UserDocument) {
let passwordEncriptada = Md5.init(user.password);
user.password = passwordEncriptada;
@ -182,10 +215,18 @@ export class UsersService {
});
}
async deleteTenant(id: string) {
return this.userModel.findOneAndUpdate({ _id: id }, { status: '-1' }, {
async deleteTenant(tenant_id: string, community_id: string, number_house: string) {
try{
await this.userModel.findOneAndUpdate({ _id: tenant_id }, { status: '-1', number_house:''}, {
new: true,
});
return await this.deleteTenantNumHouse(community_id, number_house, tenant_id);
} catch(error){
console.log(error)
return error;
}
}
async validateEmail(email: string) {
@ -231,5 +272,28 @@ export class UsersService {
new: true,
});
}
async saveTenantNumHouse(community_id: string, number_house: string, tenant_id: string) {
const pattern = { cmd: 'saveTenant' }
const payload = { _id: community_id, number_house: number_house, tenant_id: tenant_id }
return await this.clientCommunityApp
.send<string>(pattern, payload)
.pipe(
map((response: string) => ({ response }))
)
}
async deleteTenantNumHouse(community_id: string, number_house: string, tenant_id: string) {
const pattern = { cmd: 'deleteTenant' }
const payload = { _id: community_id, number_house: number_house, tenant_id: tenant_id }
return await this.clientCommunityApp
.send<string>(pattern, payload)
.pipe(
map((response: string) => ({ response }))
)
}
}

View File

@ -49,6 +49,7 @@ const AdministradoresComunidad = () => {
const dt = useRef(null);
const [changeStatusAdminCommunityDialog, setChangeStatusAdminCommunityDialog] = useState(false);
const [saveButtonTitle, setSaveButtonTitle] = useState("Registrar");
async function listaAdmin() {
@ -224,19 +225,39 @@ const AdministradoresComunidad = () => {
);
}
const saveAdminCommunity = () => {
if (adminCommunity.name && adminCommunity.dni && adminCommunity.last_name && adminCommunity.email && adminCommunity.phone) {
const findIndexById = (id) => {
let index = -1;
for (let i = 0; i < listaAdmins.length; i++) {
if (listaAdmins[i]._id === id) {
index = i;
break;
}
}
return index;
}
const findRepeated = (name, value) => {
let _administrators = [...listaAdmins];
let _adminCommunity = { ...adminCommunity };
_adminCommunity.community_id = communityId;
console.log(_adminCommunity)
console.log(communityId)
let value_filtered = _administrators.filter(item => item[`${name}`] === value);
return value_filtered.length
}
const saveAdminCommunity = () => {
let _administrators = [...listaAdmins];
let _admin = { ...adminCommunity };
_admin.community_id = communityId;
if (adminCommunity._id === null) {
if (adminCommunity.name && adminCommunity.dni &&
adminCommunity.last_name && adminCommunity.email &&
adminCommunity.phone) {
fetch('http://localhost:4000/user/createAdminCommunity', {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(_adminCommunity),
body: JSON.stringify(_admin),
headers: {
'Content-Type': 'application/json'
}
@ -253,8 +274,8 @@ const AdministradoresComunidad = () => {
// _adminCommunity.community_id = communitiesList.find(c => c._id === _adminCommunity.community_id).name
_administrators.push(_adminCommunity);
toast.current.show({ severity: 'success', summary: 'Registro exitoso', detail: 'Administrador de Comunidad de vivienda Creada', life: 3000 });
_administrators.push(_admin);
toast.current.show({ severity: 'success', summary: 'Exito', detail: 'Administrador de Comunidad de vivienda Creada', life: 3000 });
setListaAdmins(_administrators);
@ -268,8 +289,40 @@ const AdministradoresComunidad = () => {
} else {
setSubmitted(true);
}
} else {
console.log(`Actualizando admnistrador de comunidad: ${_admin}`)
_admin.community_id = communityId;
console.log(`Actualizando admnistrador de comunidad: ${_admin}`)
fetch(`http://localhost:4000/user/updateAdminCommunity/${_admin._id}`, {
cache: 'no-cache',
method: 'PUT',
body: JSON.stringify(_admin),
headers: {
'Content-Type': 'application/json',
},
}).then((response) => {
if (response.status !== 200)
console.log(`Hubo un error en el servicio: ${response.status}`)
else return response.json()
}).then(() => {
toast.current.show({
severity: 'success',
summary: 'Éxito',
detail: 'Administrador de comunidad actualizado',
life: 3000,
})
toast.current.show({ severity: 'success', summary: 'Exito', detail: 'Administrador de Comunidad de vivienda Actualizada', life: 3000 });
listaAdmin();
setCommunityId('');
setAdminCommunity(emptyAdminCommunity);
})
}
}
const hideDeleteAdminCommunityDialog = () => {
@ -298,6 +351,19 @@ const AdministradoresComunidad = () => {
setChangeStatusAdminCommunityDialog(true);
};
const editAdmin = (admin) => {
setAdminCommunity(admin);
setSaveButtonTitle('Actualizar');
setCommunityId(admin.community_id)
}
const cancelEdit = () => {
setAdminCommunity(emptyAdminCommunity);
setSaveButtonTitle('Registrar');
setCommunityId('');
}
const actionsAdminCommunity = (rowData) => {
let icono = '';
let text = '';
@ -310,15 +376,22 @@ const AdministradoresComunidad = () => {
}
return (
<div className="actions">
<Button
icon="pi pi-pencil"
className="p-button-rounded p-button-success mt-2 mx-2"
onClick={() => editAdmin(rowData)}
title="Editar"
/>
<Button
icon={`${icono}`}
className="p-button-rounded p-button-warning mt-2 mx-2"
onClick={() => confirmChangeStatuAdminCommunity(rowData)}
title={`${text}`}
/>
<Button
icon="pi pi-trash"
className="p-button-rounded p-button-danger mt-2"
className="p-button-rounded p-button-danger mt-2 mx-2"
onClick={() => confirmDeleteAdminCommunity(rowData)}
/>
</div>
@ -503,7 +576,7 @@ const AdministradoresComunidad = () => {
<Column field="phone" header={headerPhone} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column field="community_name" sortable header={headerCommuntiy} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column field="status" sortable header={headerStatus} body={statusBodyTemplate} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column style={{ flexGrow: 1, flexBasis: '130px', minWidth: '130px' }} body={actionsAdminCommunity}></Column>
<Column style={{ flexGrow: 1, flexBasis: '80px', minWidth: '80px' }} body={actionsAdminCommunity}></Column>
</DataTable>
<Dialog visible={deleteAdminCommunityDialog} style={{ width: '450px' }} header="Confirmar" modal footer={deleteAdminCommunityDialogFooter} onHide={hideDeleteAdminCommunityDialog}>
<div className="flex align-items-center justify-content-center">
@ -548,7 +621,7 @@ const AdministradoresComunidad = () => {
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-home"></i>
<i className="pi pi-user"></i>
</span>
<InputText id="name" value={adminCommunity.name} onChange={(e) => onInputChange(e, 'name')} required autoFocus className={classNames({ 'p-invalid': submitted && adminCommunity.name === '' })} />
</div>
@ -560,7 +633,7 @@ const AdministradoresComunidad = () => {
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-home"></i>
<i className="pi pi-user"></i>
</span>
<InputText id="last_name" value={adminCommunity.last_name} onChange={(e) => onInputChange(e, 'last_name')} required autoFocus className={classNames({ 'p-invalid': submitted && adminCommunity.last_name === '' })} />
</div>
@ -572,12 +645,18 @@ const AdministradoresComunidad = () => {
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-home"></i>
<i className="pi pi-at"></i>
</span>
<InputText id="email" value={adminCommunity.email} onChange={(e) => onInputChange(e, 'email')} required autoFocus className={classNames({ 'p-invalid': submitted && adminCommunity.email === '' })} />
<InputText id="email" value={adminCommunity.email}
onChange={(e) => onInputChange(e, 'email')} required autoFocus
className={classNames({ 'p-invalid': submitted &&
(adminCommunity.email === '' || findRepeated('email', adminCommunity.email) > 0) })} />
</div>
{submitted && adminCommunity.email === '' && <small className="p-invalid">Correo electrónico
es requirido.</small>}
{submitted && findRepeated('email', adminCommunity.email) > 0 &&
<small className="p-invalid">Correo electrónico se encuentra repetido.</small>
}
</div>
</div>
<div className="field col-12 md:col-6">
@ -585,11 +664,17 @@ const AdministradoresComunidad = () => {
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-home"></i>
<i className="pi pi-id-card"></i>
</span>
<InputText id="dni" value={adminCommunity.dni} onChange={(e) => onInputChange(e, 'dni')} required autoFocus className={classNames({ 'p-invalid': submitted && adminCommunity.dni === '' })} />
<InputText id="dni" value={adminCommunity.dni}
onChange={(e) => onInputChange(e, 'dni')} required autoFocus
className={classNames({ 'p-invalid': submitted
&& (adminCommunity.dni === '' || findRepeated('dni', adminCommunity.dni) > 0)})} />
</div>
{submitted && adminCommunity.email === '' && <small className="p-invalid">Identificación es requirida.</small>}
{submitted && adminCommunity.dni === '' && <small className="p-invalid">Identificación es requirida.</small>}
{submitted && findRepeated('dni', adminCommunity.dni) > 0 &&
<small className="p-invalid">Identificación se encuentra repetida.</small>
}
</div>
</div>
<div className="field col-12 md:col-6">
@ -617,7 +702,23 @@ const AdministradoresComunidad = () => {
{submitted && !communityId && <small className="p-invalid">Comunidad es requirida.</small>}
</div>
</div>
<Button label="Registrar" onClick={saveAdminCommunity} />
<div style={{
display: "flex",
justifyContent: "center",
gap: "10px",
width: "100%"
}}>
<Button
label={`${saveButtonTitle}`}
onClick={saveAdminCommunity}
/>
{saveButtonTitle === 'Actualizar' && (
<Button
label="Cancelar"
onClick={cancelEdit}
className="p-button-danger" />)}
</div>
</div>
</div>
</div>

View File

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

View File

@ -93,6 +93,16 @@ const Inquilinos = () => {
)
}
async function getHouses() {
let response = await fetch(
`http://localhost:4000/community/findHousesCommunity/${cookies.community_id}`,
{ method: 'GET' },
)
let resList = await response.json()
setHousesList(await resList)
}
useEffect(() => {
tenantsList()
}, [])
@ -112,7 +122,7 @@ const Inquilinos = () => {
_tenant.password = _tenant.email;
console.log(`Registrando nuevo inquilino: ${_tenant}`)
fetch(`http://localhost:4000/user/createUser`, {
fetch(`http://localhost:4000/user/createTenant`, {
cache: 'no-cache',
method: 'POST',
body: JSON.stringify(_tenant),
@ -125,7 +135,12 @@ const Inquilinos = () => {
console.log(`Hubo un error en el servicio: ${response.status}`)
else return response.json()
})
.then(() => {
.then((data) => {
if (_tenant.status === '1') {
_tenant.status_text = 'Activo'
} else if (_tenant.status === '0') {
_tenant.status_text = 'Inactivo'
}
_tenants.push(_tenant)
toast.current.show({
severity: 'success',
@ -133,6 +148,7 @@ const Inquilinos = () => {
detail: 'Inquilino creado',
life: 3000,
})
setTenants(_tenants)
setTenant(emptyTenant)
setHouseNumber('')
@ -168,6 +184,31 @@ const Inquilinos = () => {
}
const deleteTenant = () => {
let _tenant = {
community_id: tenant.community_id,
number_house: tenant.number_house
};
fetch('http://localhost:4000/user/deleteTenant/' + tenant._id, {
cache: 'no-cache',
method: 'PUT',
body: JSON.stringify(_tenant),
headers: {
'Content-Type': 'application/json'
}
})
.then(
function (response) {
if (response.status != 201)
console.log('Ocurrió un error con el servicio: ' + response.status);
else
return response.json();
}
)
.then(
function (response) {
let _tenants = tenants.filter((val) => val._id !== tenant._id)
setTenants(_tenants)
setDeleteTenantDialog(false)
@ -178,9 +219,36 @@ const Inquilinos = () => {
life: 3000,
})
}
)
.catch(
err => {
console.log('Ocurrió un error con el fetch', err)
toast.current.show({ severity: 'danger', summary: 'Error', detail: 'Inquilino no se pudo eliminar', life: 3000 });
}
);
}
const deleteSelectedTenants = () => {
let _tenants = tenants.filter((val) => !selectedTentants.includes(val))
let _tenants = tenants.filter(
(val) => !selectedTentants.includes(val)
);
selectedTentants.map((item) => {
let _tenant = {
community_id: item.community_id,
number_house: item.number_house
};
fetch('http://localhost:4000/user/deleteTenant/' + item._id, {
cache: 'no-cache',
method: 'PUT',
body: JSON.stringify(_tenant),
headers: {
'Content-Type': 'application/json',
},
});
});
setTenants(_tenants)
setDeleteTenantsDialog(false)
setSelectedTenants(null)
@ -806,7 +874,7 @@ const Inquilinos = () => {
</span>
<InputText id="dni" value={tenant.dni} onChange={(e) => onInputChange(e, 'dni')} required autoFocus className={classNames({ 'p-invalid': submitted && tenant.dni === '' })} />
</div>
{submitted && tenant.email === '' && <small className="p-invalid">Identificación es requerida.</small>}
{submitted && tenant.dni === '' && <small className="p-invalid">Identificación es requerida.</small>}
</div>
</div>
<div className="field col-12 md:col-6">
@ -858,7 +926,7 @@ const Inquilinos = () => {
/>
{saveButtonTitle === 'Actualizar' && (
<Button
label="Cancel"
label="Cancelar"
onClick={cancelEdit}
className="p-button-danger" />)}
</div>

View File

@ -11,13 +11,9 @@ import { Toolbar } from 'primereact/toolbar';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHome, faUserAlt } from '@fortawesome/free-solid-svg-icons';
import { faCommentAlt } from '@fortawesome/free-solid-svg-icons';
import { faPhoneAlt } from '@fortawesome/free-solid-svg-icons';
import { faAt } from '@fortawesome/free-solid-svg-icons';
import { faIdCardAlt } from '@fortawesome/free-solid-svg-icons';
import { faEllipsis } from '@fortawesome/free-solid-svg-icons';
import { faHomeAlt } from '@fortawesome/free-solid-svg-icons';
import { Dropdown } from 'primereact/dropdown';
import classNames from 'classnames';
const RegistroComunicado = () => {
let emptyComunicado = {
@ -31,10 +27,10 @@ const RegistroComunicado = () => {
listaComunis();
}, [])
const [comunicado, setComunicado] = useState(emptyComunicado);
const [comunicados,setComuicados]=useState([]);
const [comunicados, setComunicados] = useState([]);
const [comunicadoId, setComunicadoId] = useState(null);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [submitted, setSubmitted] = useState(false);
const toast = useRef(null);
const dt = useRef(null);
@ -42,13 +38,15 @@ const RegistroComunicado = () => {
const [globalFilter, setGlobalFilter] = useState(null);
async function listaComunis() {
let comunicadosA=await fetch('http://localhost:4000/post/allPosts', {method:'GET'});
let comunicadosRes= await comunicadosA.json();
setComuicados(comunicadosRes.message);
console.log(comunicadosRes.message);
let comunicadosResponse = await fetch('http://localhost:4000/post/allPosts', { method: 'GET' });
const comunicadosJson = await comunicadosResponse.json();
const comunicadosCommunity = comunicadosJson.message.filter((comunicado) => {
return comunicado.community_id === cookies.community_id;
})
setComunicados(comunicadosCommunity);
console.log(comunicadosCommunity);
}
const saveComunicado = () => {
var data = {
post: document.getElementById('txt_comunicado').value,
@ -63,28 +61,20 @@ const RegistroComunicado = () => {
headers: {
'Content-Type': 'application/json'
}
})
.then(
function (response) {
}).then((response) => {
if (response.status != 201)
console.log('Ocurrió un error con el servicio: ' + response.status);
else
return response.json();
}
)
.then(
function (response) {
}).then((_response) => {
}
)
.catch(
}).catch(
err => console.log('Ocurrió un error con el fetch', err)
);
}
const header = (
<React.Fragment>
<div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
<h5 className="m-0">Comunicados de la comunidad</h5>
<span className="block mt-2 md:mt-0 p-input-icon-left">
@ -121,11 +111,65 @@ const rightToolbarTemplate = () => {
)
}
const actions = (rowData) => {
return (
<div className="actions">
<Button
icon='pi pi-trash'
className='p-button-rounded p-button-danger mt-2 mx-2'
onClick={() => confirmDelete(rowData)}
title='Eliminar Inquilino'
/>
</div>
)
}
const confirmDelete = (post) => {
setComunicado(post);
setShowDeleteDialog(true);
}
const deleteDialogFooter = (
<>
<Button label="Cancelar" icon="pi pi-times" className="p-button-secondary" onClick={() => setShowDeleteDialog(false)} />
<Button label="Eliminar" icon="pi pi-check" className="p-button-danger" onClick={() => deleteComunicado()} />
</>
);
const deleteComunicado = () => {
fetch(`http://localhost:4000/post/deletePost/${comunicado._id}`, {
cache: 'no-cache',
method: 'DELETE',
headers: { 'Content-Type': 'application/json' }
}).then((response) => {
if (response.status != 200)
console.log('Ocurrió un error con el servicio: ' + response.status);
else
return response.json();
}).then((_response) => {
setShowDeleteDialog(false);
listaComunis();
setComunicado(emptyComunicado);
}).catch(err => console.log('Ocurrió un error con el fetch', err));
}
return (
<div className="grid">
<div className="col-12">
<Toast ref={toast} />
<div className="card">
<Dialog
header="Eliminar comunicado"
visible={showDeleteDialog}
style={{ width: '450px' }}
modal={true} onHide={() => setShowDeleteDialog(false)}
footer={deleteDialogFooter}
>
<div className="flex align-items-center justify-content-center">
<i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} />
{comunicado && <span>¿Estás seguro que desea eliminar el aviso "<b>{comunicado.post}</b>"?</span>}
</div>
</Dialog>
<Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate}></Toolbar>
<DataTable ref={dt} value={comunicados} dataKey="_id" paginator rows={5}
scrollable scrollHeight="400px" scrollDirection="both" header={header}
@ -135,7 +179,13 @@ const rightToolbarTemplate = () => {
globalFilter={globalFilter} emptyMessage="No hay administradores de comunidades registrados.">
<Column selectionMode="multiple" headerStyle={{ width: '3rem' }}></Column>
<Column field="post" sortable header={headerPost} style={{ flexGrow: 1, flexBasis: '160px', minWidth: '160px', wordBreak: 'break-word' }}></Column>
<Column
style={{
flexGrow: 1,
flexBasis: '80px',
minWidth: '80px'
}}
body={actions} />
</DataTable>
</div>
</div>