Merge branch 'dev' of github.com:DeimosPr4/katoikia-app into 69-us-37-eliminar-comunicado-de-administrador-de-comunidad

This commit is contained in:
Eduardo Quiros 2022-08-23 00:13:35 -06:00
commit d42ffc2893
No known key found for this signature in database
GPG Key ID: B77F36C3F12720B4
19 changed files with 1298 additions and 188 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') @Put('user/updateGuard/:id')
updateGuard( updateGuard(
@Param('id') id: string, @Param('id') id: string,
@ -195,9 +224,13 @@ export class AppController {
return this.appService.deleteAdminCommunity(id); return this.appService.deleteAdminCommunity(id);
} }
@Delete('user/deleteTenant/:id') @Put('user/deleteTenant/:id')
deleteTenant(@Param('id') id: string) { deleteTenant(
return this.appService.deleteTenant(id); @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') @Post('user/changeStatus')
@ -208,6 +241,20 @@ export class AppController {
return this.appService.changeStatusUser(pId, pStatus); return this.appService.changeStatusUser(pId, pStatus);
} }
@Post('user/updateAdminSystem')
updateAdminSystem(
//Nombre, Apellidos, Correo electrónico, Cédula, Teléfono
@Body('_id') _id: string,
@Body('dni') dni: string,
@Body('name') name: string,
@Body('last_name') last_name: string,
@Body('email') email: string,
@Body('phone') phone: number,
) {
return this.appService.updateAdminSystem(_id, dni, name, last_name, email, phone);
}
// #==== API Communities // #==== API Communities
@Post('community/createCommunity') @Post('community/createCommunity')
createCommunity( createCommunity(
@ -261,7 +308,21 @@ export class AppController {
return this.appService.changeStatusCommunity(pId, pStatus); 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 // #==== API Common Areas
@Post('commonArea/createCommonArea') @Post('commonArea/createCommonArea')
createCommonArea( createCommonArea(

View File

@ -1,6 +1,7 @@
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';
import { lastValueFrom } from 'rxjs';
@Injectable() @Injectable()
export class AppService { export class AppService {
@ -55,6 +56,37 @@ export class AppService {
.pipe(map((message: string) => ({ message }))); .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( updateUser(
_id: string, _id: string,
dni: string, dni: string,
@ -239,9 +271,9 @@ export class AppService {
.pipe(map((message: string) => ({ message }))); .pipe(map((message: string) => ({ message })));
} }
deleteTenant(id: string) { deleteTenant(id: string, community_id: string, number_house: string) {
const pattern = { cmd: 'deleteTenant' }; const pattern = { cmd: 'deleteTenant' };
const payload = { id: id }; const payload = { _id: id, community_id: community_id, number_house: number_house };
return this.clientUserApp return this.clientUserApp
.send<string>(pattern, payload) .send<string>(pattern, payload)
.pipe(map((message: string) => ({ message }))); .pipe(map((message: string) => ({ message })));
@ -255,6 +287,19 @@ export class AppService {
.pipe(map((message: string) => ({ message }))); .pipe(map((message: string) => ({ message })));
} }
updateAdminSystem(_id: string, dni: string, name: string,
last_name: string, email: string, phone: number
) {
const pattern = { cmd: 'updateAdminSystem' };
const payload = {
_id: _id, dni: dni, name: name, last_name: last_name,
email: email, phone: phone
};
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
//GET parameter from API //GET parameter from API
findCommunityAdmin(community_id: string) { findCommunityAdmin(community_id: string) {
const pattern = { cmd: 'findCommunityAdmin' }; const pattern = { cmd: 'findCommunityAdmin' };
@ -337,6 +382,31 @@ export class AppService {
.pipe(map((message: string) => ({ message }))); .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 =============================== // ====================== COMMON AREAS ===============================
//POST parameter from API //POST parameter from API
createCommonArea( createCommonArea(

View File

@ -53,4 +53,22 @@ export class CommunitiesController {
let pstatus = body['status']; let pstatus = body['status'];
return this.communitiesService.changeStatus(pid,pstatus); 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 { 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';
import { Tenant, TenantSchema } from 'src/schemas/tenant.schema';
@Injectable() @Injectable()
export class CommunitiesService { export class CommunitiesService {
@ -13,7 +14,7 @@ export class CommunitiesService {
@InjectModel(Community.name) @InjectModel(Community.name)
private readonly communityModel: Model<CommunityDocument>, 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> {
return this.communityModel.create(community); return this.communityModel.create(community);
@ -56,13 +57,13 @@ export class CommunitiesService {
} }
async remove(id: string) { async remove(id: string) {
return this.communityModel.findOneAndUpdate({ _id: id }, {status: '-1'}, { return this.communityModel.findOneAndUpdate({ _id: id }, { status: '-1' }, {
new: true, new: true,
}); });
} }
async changeStatus(id: string, status: string) { async changeStatus(id: string, status: string) {
return this.communityModel.findOneAndUpdate({ _id: id }, {status: status}, { return this.communityModel.findOneAndUpdate({ _id: id }, { status: status }, {
new: true, new: true,
}); });
} }
@ -78,4 +79,44 @@ export class CommunitiesService {
const finalValue = await lastValueFrom(callback); const finalValue = await lastValueFrom(callback);
return finalValue['response']; 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
MAIL_HOST=smtp.gmail.com MAIL_HOST=smtp.gmail.com
MAIL_USER=mbonilla.guti@gmail.com MAIL_USER=katoikiap4@gmail.com
MAIL_PASSWORD=laofghlofgffmyry MAIL_PASSWORD=snxwbncohehilkkz
MAIL_FROM=noreply@example.com MAIL_FROM=noreply@example.com
# optional # optional

View File

@ -12,7 +12,7 @@ export class EmailController {
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: 'katoikiap4@gmail.com',
subject: 'Plain Text Email ✔', subject: 'Plain Text Email ✔',
text: 'Welcome NestJS Email Sending Tutorial', text: 'Welcome NestJS Email Sending Tutorial',
}); });
@ -25,7 +25,7 @@ export class EmailController {
const image = "images/email.png"; const image = "images/email.png";
var response = await this.mailService.sendMail({ var response = await this.mailService.sendMail({
to: user["email"], to: user["email"],
from: "mbonilla.guti@gmail.com", from: "katoikiap4@gmail.com",
subject: 'HTML Dynamic Template', subject: 'HTML Dynamic Template',
template: 'templateEmail', template: 'templateEmail',
context: { context: {
@ -51,7 +51,7 @@ export class EmailController {
const logo = "images/Logo Katoikia.png"; const logo = "images/Logo Katoikia.png";
var response = await this.mailService.sendMail({ var response = await this.mailService.sendMail({
to: user["email"], to: user["email"],
from: "mbonilla.guti@gmail.com", from: "katoikiap4@gmail.com",
subject: 'Usuario registrado', subject: 'Usuario registrado',
template: 'emailCreateUserAdminCommunity', template: 'emailCreateUserAdminCommunity',
context: { context: {
@ -77,4 +77,39 @@ export class EmailController {
}); });
return response; 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"> <td style="text-align: left; padding-left: 5px; padding-right: 5px">
<h3 class="heading">Información de contacto</h3> <h3 class="heading">Información de contacto</h3>
<ul> <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> </ul>
</td> </td>
</tr> </tr>

View File

@ -438,8 +438,8 @@
<td style="text-align: left; padding-left: 5px; padding-right: 5px"> <td style="text-align: left; padding-left: 5px; padding-right: 5px">
<h3 class="heading">Información de contacto</h3> <h3 class="heading">Información de contacto</h3>
<ul> <ul>
<li><span href="mailto:katoikiaapp@gmail.com" <li><span href="mailto:katoikiap4@gmail.com"
class="text">katoikiaapp@gmail.com</span></li> class="text">katoikiap4@gmail.com</span></li>
</ul> </ul>
</td> </td>
</tr> </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); return this.userService.createAdminCommunity(user);
} }
@MessagePattern({ cmd: 'createTenant' })
createTenant(@Payload() user: UserDocument) {
return this.userService.createTenant(user);
}
@MessagePattern({ cmd: 'findAllUsers' }) @MessagePattern({ cmd: 'findAllUsers' })
findAll() { findAll() {
return this.userService.findAll(); return this.userService.findAll();
@ -66,7 +72,7 @@ export class UsersController {
@MessagePattern({ cmd: 'updateUser' }) @MessagePattern({ cmd: 'updateUser' })
update(@Payload() user: UserDocument) { update(@Payload() user: UserDocument) {
return this.userService.update(user.id, user); return this.userService.update(user._id, user);
} }
@MessagePattern({ cmd: 'updateGuard' }) @MessagePattern({ cmd: 'updateGuard' })
@ -79,7 +85,10 @@ export class UsersController {
let dni = id['dni']; let dni = id['dni'];
return this.userService.remove(dni); return this.userService.remove(dni);
} }
@MessagePattern({ cmd: 'updateAdminSystem' })
updateAdminSystem(@Payload() user: UserDocument) {
return this.userService.updateAdminSystem(user._id, user);
}
//inicio de sesion //inicio de sesion
@MessagePattern({ cmd: 'loginUser' }) @MessagePattern({ cmd: 'loginUser' })
findLogin(@Payload() body: string) { findLogin(@Payload() body: string) {
@ -127,7 +136,10 @@ export class UsersController {
@MessagePattern({ cmd: 'deleteTenant' }) @MessagePattern({ cmd: 'deleteTenant' })
deleteTenant(@Payload() user: any) { 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' }) @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) { async createAdminCommunity(user: UserDocument) {
let password = user.password; let password = user.password;
let passwordEncriptada = Md5.init(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) { /* async remove(id: string) {
return this.userModel.findByIdAndRemove({ _id: id }).exec(); 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 }) return await this.userModel.find({ community_id: pcommunity_id, user_type: 4 })
} }
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;
@ -171,7 +204,7 @@ export class UsersService {
} }
async deleteAdminSystem(id: string) { async deleteAdminSystem(id: string) {
return this.userModel.findOneAndUpdate({ _id: id }, { status: '-1' }, { return this.userModel.findOneAndUpdate({ _id: id }, { status: '-1'}, {
new: true, new: true,
}); });
} }
@ -182,10 +215,18 @@ export class UsersService {
}); });
} }
async deleteTenant(id: string) { async deleteTenant(tenant_id: string, community_id: string, number_house: string) {
return this.userModel.findOneAndUpdate({ _id: id }, { status: '-1' }, {
try{
await this.userModel.findOneAndUpdate({ _id: tenant_id }, { status: '-1', number_house:''}, {
new: true, new: true,
}); });
return await this.deleteTenantNumHouse(community_id, number_house, tenant_id);
} catch(error){
console.log(error)
return error;
}
} }
async validateEmail(email: string) { async validateEmail(email: string) {
@ -231,5 +272,28 @@ export class UsersService {
new: true, 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

@ -12,8 +12,25 @@ import { faPhoneAlt } from '@fortawesome/free-solid-svg-icons';
import { faAt } from '@fortawesome/free-solid-svg-icons'; import { faAt } from '@fortawesome/free-solid-svg-icons';
import { faIdCardAlt } from '@fortawesome/free-solid-svg-icons'; import { faIdCardAlt } from '@fortawesome/free-solid-svg-icons';
import { faCircleQuestion } from '@fortawesome/free-solid-svg-icons'; import { faCircleQuestion } from '@fortawesome/free-solid-svg-icons';
import classNames from 'classnames';
const AdministradoresSistema = () => { const AdministradoresSistema = () => {
let emptySysAdmin = {
_id: null,
dni: '',
name: '',
last_name: '',
email: '',
phone: '',
password: '',
user_type: '1',
status: '1',
status_text: '',
};
const [administrators, setAdministrators] = useState([]); const [administrators, setAdministrators] = useState([]);
const [urlFetch, setUrlFetch] = useState( const [urlFetch, setUrlFetch] = useState(
'http://localhost:4000/user/findAdminSistema/', 'http://localhost:4000/user/findAdminSistema/',
@ -30,19 +47,12 @@ const AdministradoresSistema = () => {
const [changeStatusAdminSystemDialog, setChangeStatusAdminSystemDialog] = useState(false); const [changeStatusAdminSystemDialog, setChangeStatusAdminSystemDialog] = useState(false);
const [changeStatusAdminsSystemDialog, setChangeStatusAdminsSystemDialog] = const [changeStatusAdminsSystemDialog, setChangeStatusAdminsSystemDialog] =
useState(false); useState(false);
const [adminDialog, setAdminDialog] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [editAdminDialog, setEditAdminDialog] = useState(false);
const [saveButtonTitle, setSaveButtonTitle] = useState("Registrar")
let emptySysAdmin = {
_id: null,
dni: '',
name: '',
last_name: '',
email: '',
phone: '',
password: '',
user_type: '1',
status: '1',
status_text: '',
};
async function fetchP() { async function fetchP() {
let nombres = await fetch(urlFetch, { method: 'GET' }); let nombres = await fetch(urlFetch, { method: 'GET' });
@ -64,23 +74,90 @@ const AdministradoresSistema = () => {
fetchP(); fetchP();
}, []) }, [])
function registrarAdmin() { const findIndexById = (id) => {
var data = { let index = -1;
dni: document.getElementById('identificacion').value, for (let i = 0; i < administrators.length; i++) {
name: document.getElementById('nombre').value, if (administrators[i]._id === id) {
last_name: document.getElementById('apellidos').value, index = i;
email: document.getElementById('correo_electronico').value, break;
phone: document.getElementById('telefono').value, }
password: document.getElementById('correo_electronico').value, }
user_type: "1", //1 es admin return index;
status: "1"
};
setSysAdmin(data)
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', cache: 'no-cache',
method: 'POST', 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: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
@ -95,8 +172,6 @@ const AdministradoresSistema = () => {
) )
.then( .then(
function (response) { function (response) {
let _administrators = [...administrators];
let _admin = { ...sysadmin };
_administrators.push(_admin); _administrators.push(_admin);
setAdministrators(_administrators) setAdministrators(_administrators)
} }
@ -105,6 +180,18 @@ const AdministradoresSistema = () => {
err => console.log('Ocurrió un error con el fetch', err) err => console.log('Ocurrió un error con el fetch', err)
); );
} }
}
} else {
setSubmitted(true);
}
}
const cambiarStatusUser = () => { const cambiarStatusUser = () => {
if (sysadmin.status == '1') { if (sysadmin.status == '1') {
@ -177,6 +264,31 @@ const AdministradoresSistema = () => {
setChangeStatusAdminSystemDialog(true); setChangeStatusAdminSystemDialog(true);
}; };
const hideAdminDialog = () => {
setSubmitted(false);
setAdminDialog(false);
setSysAdmin(emptySysAdmin);
};
const infoAdmin = (sysadmin) => {
setSysAdmin({ ...sysadmin });
setAdminDialog(true);
};
const cancelEdit = () => {
setSaveButtonTitle('Registrar');
setSubmitted(false);
setSysAdmin(emptySysAdmin);
}
const editAdmin = (sysadmin) => {
setSysAdmin({ ...sysadmin });
setSaveButtonTitle('Actualizar');
};
const deleteSysAdmin = () => { const deleteSysAdmin = () => {
fetch('http://localhost:4000/user/deleteAdminSystem/' + sysadmin._id, { fetch('http://localhost:4000/user/deleteAdminSystem/' + sysadmin._id, {
cache: 'no-cache', cache: 'no-cache',
@ -259,6 +371,21 @@ const AdministradoresSistema = () => {
return ( return (
<div className="actions"> <div className="actions">
<Button
icon="pi pi-exclamation-circle"
className="p-button-rounded p-button-info mt-2 mx-2"
onClick={() => infoAdmin(rowData)}
title="Ver información del Administrador"
/>
<Button
icon="pi pi-pencil"
className="p-button-rounded p-button-success mt-2 mx-2"
onClick={() => editAdmin(rowData)}
title="Editar Administrador"
/>
<Button <Button
icon={`${icono}`} icon={`${icono}`}
className="p-button-rounded p-button-warning mt-2 mx-2" className="p-button-rounded p-button-warning mt-2 mx-2"
@ -370,6 +497,36 @@ const AdministradoresSistema = () => {
</> </>
); );
const editAdminDialogFooter = (
<>
<Button
label="No"
icon="pi pi-times"
className="p-button-text"
onClick={hideChangeStatusAdminDialog}
/>
<Button
label="Yes"
icon="pi pi-check"
className="p-button-text"
onClick={editAdmin}
/>
</>
);
const adminDialogFooter = (
<>
<Button
label="Cerrar"
icon="pi pi-times"
className="p-button-text"
onClick={hideAdminDialog}
/>
</>
);
const headerName = ( const headerName = (
<> <>
<p> <p>
@ -440,6 +597,23 @@ const AdministradoresSistema = () => {
); );
}; };
const onInputChange = (e, name) => {
const val = (e.target && e.target.value) || '';
let _admin = { ...sysadmin };
_admin[`${name}`] = val;
setSysAdmin(_admin);
};
const onInputNumberChange = (e, name) => {
const val = e.value || 0;
let _admin = { ...sysadmin };
_admin[`${name}`] = val;
setSysAdmin(_admin);
};
return ( return (
<div className="grid"> <div className="grid">
<div className="col-12"> <div className="col-12">
@ -541,6 +715,84 @@ const AdministradoresSistema = () => {
body={actionsAdmin} body={actionsAdmin}
></Column> ></Column>
</DataTable> </DataTable>
<Dialog
visible={adminDialog}
style={{ width: '650px' }}
header="Información del Admin del Sistema"
modal
className="p-fluid"
footer={adminDialogFooter}
onHide={hideAdminDialog}
>
{sysadmin && (
<div className='container text-center'>
<div className='row my-4'>
<div className=" col-12 md:col-12">
<h3>Información Básica</h3>
</div>
<div className=" col-6 md:col-6">
<i className="pi pi-user icon-khaki"></i>
<p><strong>Nombre</strong></p>
<div className="p-0 col-12 md:col-12" style={{ margin: '0 auto' }}>
<div className="p-inputgroup align-items-center justify-content-evenly">
<p>{sysadmin.name}</p>
</div>
</div>
</div>
<div className=" col-6 md:col-6">
<i className="pi pi-user icon-khaki"></i>
<p><strong>Apellido(s)</strong></p>
<div className="p-0 col-12 md:col-12" style={{ margin: '0 auto' }}>
<div className="p-inputgroup align-items-center justify-content-evenly">
<p>{sysadmin.last_name}</p>
</div>
</div>
</div>
</div>
<div className='row my-5'>
<div className=" col-12 md:col-12">
<i className="pi pi-id-card icon-khaki"></i>
<p><strong>Identificación</strong></p>
<div className="p-0 col-12 md:col-12" style={{ margin: '0 auto' }}>
<div className="p-inputgroup align-items-center justify-content-evenly">
<p>{sysadmin.dni}</p>
</div>
</div>
</div>
</div>
<div className='row my-5'>
<div className=" col-12 md:col-12">
<h3>Contacto</h3>
</div>
<div className=" col-6 col-md-6 md:col-6">
<i className="pi pi-at icon-khaki"></i>
<p><strong>Correo electrónico</strong></p>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup align-items-center justify-content-evenly">
<p>{sysadmin.email}</p>
</div>
</div>
</div>
<div className=" col-6 md:col-6">
<i className="pi pi-phone icon-khaki"></i>
<p><strong>Teléfono</strong></p>
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup align-items-center justify-content-evenly">
<p>{sysadmin.phone}</p>
</div>
</div>
</div>
</div>
</div>
)}
</Dialog>
<Dialog <Dialog
visible={deleteAdminSystemDialog} visible={deleteAdminSystemDialog}
style={{ width: '450px' }} style={{ width: '450px' }}
@ -602,35 +854,146 @@ const AdministradoresSistema = () => {
)} )}
</div> </div>
</Dialog> </Dialog>
</div> </div>
</div> </div>
<div className="col-12"> <div className="col-12">
<div className="card"> <div className="card">
<h5>Registro de un administrador del sistema</h5> <h5>Mantenimiento Administrador del Sistema</h5>
<div className="p-fluid formgrid grid"> <div className="p-fluid formgrid grid">
<div className="field col-12 md:col-6"> <div className="field col-6 md:col-6">
<label htmlFor="nombre">Nombre</label> <label htmlFor="name">Nombre</label>
<InputText id="nombre" type="text" />
<div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-user"></i>
</span>
<InputText id="name" value={sysadmin.name}
onChange={(e) => onInputChange(e, 'name')}
required
autoFocus
className={classNames({
'p-invalid': submitted && sysadmin.name === '',
})}
/>
</div> </div>
<div className="field col-12 md:col-6"> {submitted && sysadmin.name === '' &&
<label htmlFor="apellidos">Apellido(s)</label> <small className="p-invalid">Nombre es requirido.</small>}
<InputText id="apellidos" type="text" />
</div> </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> <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>
<div className="field col-12 md:col-6">
<label htmlFor="identificacion">Identificación</label>
<InputText id="identificacion" type="text" />
</div> </div>
<div className="field col-12"> <div className="field col-12">
<label htmlFor="telefono">Teléfono</label> <label htmlFor="phone">Teléfono</label>
<InputText type="tel" id="telefono" pattern="[0-9]{8}" /> <div className="p-0 col-12 md:col-12">
<div className="p-inputgroup">
<span className="p-inputgroup-addon p-button p-icon-input-khaki">
<i className="pi pi-phone"></i>
</span>
<InputText type="tel" id="phone" pattern="[0-9]{8}"
value={sysadmin.phone}
onChange={(e) => onInputChange(e, 'phone')}
required
autoFocus
className={classNames({
'p-invalid': submitted && sysadmin.phone === '',
})}
/>
</div> </div>
<Button label="Registrar" onClick={registrarAdmin}></Button> {submitted && sysadmin.phone === '' && (
<small className="p-invalid">Teléfono es requerido.</small>
)}
</div> </div>
</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>
</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(() => { useEffect(() => {
tenantsList() tenantsList()
}, []) }, [])
@ -112,7 +122,7 @@ const Inquilinos = () => {
_tenant.password = _tenant.email; _tenant.password = _tenant.email;
console.log(`Registrando nuevo inquilino: ${_tenant}`) console.log(`Registrando nuevo inquilino: ${_tenant}`)
fetch(`http://localhost:4000/user/createUser`, { fetch(`http://localhost:4000/user/createTenant`, {
cache: 'no-cache', cache: 'no-cache',
method: 'POST', method: 'POST',
body: JSON.stringify(_tenant), body: JSON.stringify(_tenant),
@ -125,7 +135,12 @@ const Inquilinos = () => {
console.log(`Hubo un error en el servicio: ${response.status}`) console.log(`Hubo un error en el servicio: ${response.status}`)
else return response.json() 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) _tenants.push(_tenant)
toast.current.show({ toast.current.show({
severity: 'success', severity: 'success',
@ -133,6 +148,7 @@ const Inquilinos = () => {
detail: 'Inquilino creado', detail: 'Inquilino creado',
life: 3000, life: 3000,
}) })
setTenants(_tenants) setTenants(_tenants)
setTenant(emptyTenant) setTenant(emptyTenant)
setHouseNumber('') setHouseNumber('')
@ -168,6 +184,31 @@ const Inquilinos = () => {
} }
const deleteTenant = () => { 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) let _tenants = tenants.filter((val) => val._id !== tenant._id)
setTenants(_tenants) setTenants(_tenants)
setDeleteTenantDialog(false) setDeleteTenantDialog(false)
@ -178,9 +219,36 @@ const Inquilinos = () => {
life: 3000, 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 = () => { 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) setTenants(_tenants)
setDeleteTenantsDialog(false) setDeleteTenantsDialog(false)
setSelectedTenants(null) setSelectedTenants(null)
@ -858,7 +926,7 @@ const Inquilinos = () => {
/> />
{saveButtonTitle === 'Actualizar' && ( {saveButtonTitle === 'Actualizar' && (
<Button <Button
label="Cancel" label="Cancelar"
onClick={cancelEdit} onClick={cancelEdit}
className="p-button-danger" />)} className="p-button-danger" />)}
</div> </div>