Merge branch 'dev' of github.com:DeimosPr4/katoikia-app into 61-us-34-lista-de-invitados-de-inquilinos

This commit is contained in:
Eduardo Quiros 2022-08-24 21:16:11 -06:00
commit fb02a51689
No known key found for this signature in database
GPG Key ID: B77F36C3F12720B4
44 changed files with 1133 additions and 16342 deletions

View File

@ -233,6 +233,36 @@ export class AppController {
return this.appService.deleteTenant(id, community_id, number_house);
}
@Put('user/resetUserPassword/:id')
resetUserPassword(@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('password') password: string,
@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.updateUser(
id,
dni,
name,
last_name,
email,
phone,
password,
user_type,
status,
date_entry,
community_id,
number_house,
);
}
@Post('user/changeStatus')
changeStatusUser(
@Body('id') pId: string,
@ -343,6 +373,11 @@ export class AppController {
) {
return this.appService.saveTenant(community_id, number_house, tenant_id);
}
@Delete('community/deleteCommunity/:id')
deleteCommunity(@Param('id') paramCommunityId: string) {
return this.appService.deleteCommunity(paramCommunityId);
}
// #==== API Common Areas
@Post('commonArea/createCommonArea')
createCommonArea(
@ -476,6 +511,8 @@ export class AppController {
@Body('date_entry') date_entry: Date,
@Body('user_id') user_id: string,
@Body('common_area_id') common_area_id: string,
@Body('common_area_name') common_area_name: string,
@Body('communty_id') communty_id: string,
) {
return this.appService.createReservation(
start_time,
@ -484,6 +521,8 @@ export class AppController {
date_entry,
user_id,
common_area_id,
common_area_name,
communty_id,
);
}
@ -497,6 +536,12 @@ export class AppController {
return this.appService.findReservation(paramReservation);
}
@Get('reservation/findReservations/:id')
findReservations(@Param('id') community_id: string) {
return this.appService.findReservations(community_id);
}
// #==== API Post
@Post('post/createPost')

View File

@ -225,6 +225,22 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
resetUserPassword(id: string, dni: string, name: string, last_name: string, email: string, phone: number
, user_type: string, status: string, date_entry: Date, community_id: string) {
const pattern = { cmd: 'resetUserPassword' };
const payload = {
id: id, 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
};
return this.clientUserApp
.send<string>(pattern, payload)
.pipe(
map((message: string) => ({ message })),
);
}
allUsersAdminSistema() {
const pattern = { cmd: 'findAdminSistema' };
const payload = {};
@ -309,12 +325,12 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
updateAdminSystem(_id: string, dni: string, name: string,
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,
_id: _id, dni: dni, name: name, last_name: last_name,
email: email, phone: phone
};
return this.clientUserApp
@ -429,6 +445,15 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
deleteCommunity(id: string) {
const pattern = { cmd: 'removeCommunity' };
const payload = { _id: id };
return this.clientCommunityApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
// ====================== COMMON AREAS ===============================
//POST parameter from API
createCommonArea(
@ -589,11 +614,13 @@ export class AppService {
//POST parameter from API
createReservation(start_time: string, finish_time: string, status: string,
date_entry: Date, user_id: string, common_area_id: string) {
date_entry: Date, user_id: string, common_area_id: string,
common_area_name: string, communty_id: string) {
const pattern = { cmd: 'createReservation' };
const payload = {
start_time: start_time, finish_time: finish_time, status: status,
date_entry: date_entry, user_id: user_id, common_area_id: common_area_id
date_entry: date_entry, user_id: user_id, common_area_id: common_area_id,
common_area_name: common_area_name, communty_id: communty_id
};
return this.clientReservationApp
.send<string>(pattern, payload)
@ -617,6 +644,14 @@ export class AppService {
.pipe(map((message: string) => ({ message })));
}
findReservations(community_id: string) {
const pattern = { cmd: 'findReservationsByCommunity' };
const payload = { community_id: community_id };
return this.clientReservationApp
.send<string>(pattern, payload)
.pipe(map((message: string) => ({ message })));
}
// ====================== POSTS ===============================
//POST parameter from API

View File

@ -1,25 +0,0 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir : __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

35
service-a/.gitignore vendored
View File

@ -1,35 +0,0 @@
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

View File

@ -1,4 +0,0 @@
{
"singleQuote": true,
"trailingComma": "all"
}

View File

@ -1,73 +0,0 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).

View File

@ -1,5 +0,0 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}

15687
service-a/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,77 +0,0 @@
{
"name": "service-a",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^8.0.0",
"@nestjs/core": "^8.0.0",
"@nestjs/mapped-types": "*",
"@nestjs/microservices": "^8.4.7",
"@nestjs/mongoose": "^9.1.1",
"@nestjs/platform-express": "^8.0.0",
"@nestjs/swagger": "^5.2.1",
"mongoose": "^6.4.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"swagger-ui-express": "^4.4.0"
},
"devDependencies": {
"@nestjs/cli": "^8.0.0",
"@nestjs/schematics": "^8.0.0",
"@nestjs/testing": "^8.0.0",
"@types/express": "^4.17.13",
"@types/jest": "27.5.0",
"@types/node": "^16.0.0",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "28.0.3",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "28.0.1",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.0.0",
"typescript": "^4.3.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@ -1,22 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@ -1,12 +0,0 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

View File

@ -1,17 +0,0 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
import { BooksModule } from './books/books.module';
@Module({
imports: [
MongooseModule.forRoot(
`mongodb+srv://proyecto_4:proyecto_4@proyecto4.yv4fb.mongodb.net/servicio_books?retryWrites=true&w=majority`,
),
BooksModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

View File

@ -1,8 +0,0 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -1,20 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { BooksController } from './books.controller';
import { BooksService } from './books.service';
describe('BooksController', () => {
let controller: BooksController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [BooksController],
providers: [BooksService],
}).compile();
controller = module.get<BooksController>(BooksController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -1,47 +0,0 @@
import { Req } from '@nestjs/common';
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Request } from 'express';
import { BooksService } from './books.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { BookDocument } from './schemas/book.schema';
@Controller('books')
@ApiTags('book')
export class BooksController {
constructor(private readonly booksService: BooksService) {}
@Post()
create(@Body() book: BookDocument) {
return this.booksService.create(book);
}
@Get()
findAll(@Req() request: Request) {
return this.booksService.findAll(request);
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.booksService.findOne(id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() book: BookDocument) {
return this.booksService.update(id, book);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.booksService.remove(id);
}
}

View File

@ -1,14 +0,0 @@
import { Module } from '@nestjs/common';
import { BooksService } from './books.service';
import { BooksController } from './books.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { Book, BookSchema } from './schemas/book.schema';
@Module({
imports: [
MongooseModule.forFeature([{ name: Book.name, schema: BookSchema }]),
],
controllers: [BooksController],
providers: [BooksService],
})
export class BooksModule {}

View File

@ -1,18 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { BooksService } from './books.service';
describe('BooksService', () => {
let service: BooksService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [BooksService],
}).compile();
service = module.get<BooksService>(BooksService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -1,39 +0,0 @@
import { Injectable } from '@nestjs/common';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Book, BookDocument } from './schemas/book.schema';
import { Model } from 'mongoose';
import { Request } from 'express';
@Injectable()
export class BooksService {
constructor(
@InjectModel(Book.name) private readonly bookModel: Model<BookDocument>,
) {}
async create(book: BookDocument): Promise<Book> {
return this.bookModel.create(book);
}
async findAll(request: Request): Promise<Book[]> {
return this.bookModel
.find(request.query)
.setOptions({ sanitizeFilter: true })
.exec();
}
async findOne(id: string): Promise<Book> {
return this.bookModel.findOne({ _id: id }).exec();
}
async update(id: string, book: BookDocument) {
return this.bookModel.findOneAndUpdate({ _id: id }, book, {
new: true,
});
}
async remove(id: string) {
return this.bookModel.findByIdAndRemove({ _id: id }).exec();
}
}

View File

@ -1,31 +0,0 @@
import { ApiProperty } from '@nestjs/swagger';
export class CreateBookDto {
@ApiProperty({
example: 'Nest.js: A Progressive Node.js Framework (English Edition)',
})
readonly title: string;
@ApiProperty({ example: 'Web Development' })
readonly genre: string;
@ApiProperty({
example:
'JavaScript frameworks go in and out of style very quickly as web technologies change and grow. Nest.js is a good starting point for many developers that are looking to use a modern web framework because it uses a language that is very similar to that of the most used language on the web to this day, JavaScript...',
})
readonly description: string;
@ApiProperty({ example: 'Jay Bell' })
readonly author: string;
@ApiProperty({ example: 350 })
readonly pages: number;
@ApiProperty({
example: 'https://m.media-amazon.com/images/I/41fveBeDWmL._SY346_.jpg',
})
readonly image_url: string;
@ApiProperty({ example: ['NestJS', 'REST API'] })
readonly keywords: string[];
}

View File

@ -1,4 +0,0 @@
import { PartialType } from '@nestjs/swagger';
import { CreateBookDto } from './create-book.dto';
export class UpdateBookDto extends PartialType(CreateBookDto) {}

View File

@ -1,27 +0,0 @@
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type BookDocument = Book & Document;
@Schema()
export class Book {
@Prop()
genre: string;
@Prop()
description: string;
@Prop()
author: string;
@Prop()
pages: number;
@Prop()
image_url: string;
@Prop([String])
keywords: string[];
}
export const BookSchema = SchemaFactory.createForClass(Book);

View File

@ -1,21 +0,0 @@
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Configurar títulos de documentación
const options = new DocumentBuilder()
.setTitle('MongoDB Book REST API')
.setDescription('API REST para libros con MongoDB')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, options);
// La ruta en que se sirve la documentación
SwaggerModule.setup('docs', app, document);
await app.listen(3000);
}
bootstrap();

View File

@ -1,24 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

View File

@ -1,9 +0,0 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

View File

@ -1,4 +0,0 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

View File

@ -1,21 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}

View File

@ -5,7 +5,7 @@ import { CommonAreasService } from './common_areas.service';
@Controller()
export class CommonAreasController {
constructor(private readonly commonAreasService: CommonAreasService) {}
constructor(private readonly commonAreasService: CommonAreasService) { }
@MessagePattern({ cmd: 'createCommonArea' })
create(@Payload() commonArea: CommonAreaDocument) {
@ -40,11 +40,17 @@ export class CommonAreasController {
return this.commonAreasService.findByCommunity(_community_id);
}
//cambiar de estado
@MessagePattern({ cmd: 'changeStatus' })
changeStatus(@Payload() body: string) {
let pid = body['id'];
let pstatus = body['status'];
return this.commonAreasService.changeStatus(pid,pstatus);
}
//cambiar de estado
@MessagePattern({ cmd: 'changeStatus' })
changeStatus(@Payload() body: string) {
let pid = body['id'];
let pstatus = body['status'];
return this.commonAreasService.changeStatus(pid, pstatus);
}
@MessagePattern({ cmd: 'removeIdCommunity' })
removeIdCommunity(@Payload() area: any) {
let community_id = area['community_id'];
return this.commonAreasService.removeIdCommunity(community_id);
}
}

View File

@ -47,4 +47,8 @@ export class CommonAreasService {
});
}
async removeIdCommunity(community_id: string){
await this.commonAreaModel.updateMany({community_id: community_id}, {"$set":{"status": '-1'}});
}
}

View File

@ -5,7 +5,7 @@ import { Community, CommunityDocument } from 'src/schemas/community.schema';
@Controller()
export class CommunitiesController {
constructor(private readonly communitiesService: CommunitiesService) {}
constructor(private readonly communitiesService: CommunitiesService) { }
@MessagePattern({ cmd: 'createCommunity' })
create(@Payload() community: CommunityDocument) {
@ -46,17 +46,17 @@ export class CommunitiesController {
return this.communitiesService.remove(_id);
}
//cambiar de estado
@MessagePattern({ cmd: 'changeStatus' })
changeStatus(@Payload() body: string) {
let pid = body['id'];
let pstatus = body['status'];
return this.communitiesService.changeStatus(pid,pstatus);
}
//cambiar de estado
@MessagePattern({ cmd: 'changeStatus' })
changeStatus(@Payload() body: string) {
let pid = body['id'];
let pstatus = body['status'];
return this.communitiesService.changeStatus(pid, pstatus);
}
@MessagePattern({ cmd: 'saveTenant' })
saveTenant(@Payload() body: string) {
@MessagePattern({ cmd: 'saveTenant' })
saveTenant(@Payload() body: string) {
let id = body['_id'];
let tenant_id = body['tenant_id'];
@ -66,9 +66,9 @@ export class CommunitiesController {
@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);
}
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

@ -18,6 +18,26 @@ import { Community, CommunitySchema } from '../schemas/community.schema';
},
},
]),
ClientsModule.register([
{
name: 'SERVICIO_AREAS_COMUNES',
transport: Transport.TCP,
options: {
host: '127.0.0.1',
port: 3003,
},
},
]),
ClientsModule.register([
{
name: 'SERVICIO_RESERVACIONES',
transport: Transport.TCP,
options: {
host: '127.0.0.1',
port: 3006,
},
},
]),
MongooseModule.forFeature([
{ name: Community.name, schema: CommunitySchema },
]),

View File

@ -14,6 +14,8 @@ export class CommunitiesService {
@InjectModel(Community.name)
private readonly communityModel: Model<CommunityDocument>,
@Inject('SERVICIO_USUARIOS') private readonly clientUserApp: ClientProxy,
@Inject('SERVICIO_AREAS_COMUNES') private readonly clientAreaApp: ClientProxy,
@Inject('SERVICIO_RESERVACIONES') private readonly clientReservationApp: ClientProxy,
) { }
async create(community: CommunityDocument): Promise<Community> {
@ -57,6 +59,7 @@ export class CommunitiesService {
}
async remove(id: string) {
await this.removeIdCommunity(id);
return this.communityModel.findOneAndUpdate({ _id: id }, { status: '-1' }, {
new: true,
});
@ -80,7 +83,6 @@ export class CommunitiesService {
return finalValue['response'];
}
async saveTenant(id: string, number_house: string, ptenant_id: string) {
let community = await this.findOne(id);
await community.houses.map(house => {
@ -97,13 +99,11 @@ export class CommunitiesService {
}
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);
@ -114,9 +114,31 @@ export class CommunitiesService {
}
return house;
})
return await this.communityModel.findOneAndUpdate({ _id: id }, community, {
new: true,
});
}
async removeIdCommunity(community: string) {
const pattern = { cmd: 'removeIdCommunity' };
const payload = { community_id: community };
await this.clientUserApp
.send<string>(pattern, payload)
.pipe(map((response: string) => ({ response })));
const pattern2 = { cmd: 'removeIdCommunity' };
const payload2 = { community_id: community };
await this.clientAreaApp
.send<string>(pattern2, payload2)
.pipe(map((response: string) => ({ response })));
const pattern3 = { cmd: 'removeIdCommunity' };
const payload3 = { community_id: community };
await this.clientReservationApp
.send<string>(pattern3, payload3)
.pipe(map((response: string) => ({ response })));
}
}

View File

@ -6,18 +6,18 @@ import { User } from './user/user.entity';
@Controller()
export class EmailController {
constructor(private mailService: MailerService) {}
constructor(private mailService: MailerService) { }
@MessagePattern({ cmd: 'sendMail' })
sendMail(@Payload() toEmail: string) {
var response = this.mailService.sendMail({
to: toEmail['email'],
from: 'katoikiap4@gmail.com',
subject: 'Plain Text Email ✔',
text: 'Welcome NestJS Email Sending Tutorial',
});
return response;
}
@MessagePattern({ cmd: 'sendMail' })
sendMail(@Payload() toEmail: string) {
var response = this.mailService.sendMail({
to: toEmail['email'],
from: 'katoikiap4@gmail.com',
subject: 'Plain Text Email ✔',
text: 'Welcome NestJS Email Sending Tutorial',
});
return response;
}
@MessagePattern({ cmd: 'html' })
async postHTMLEmail(@Payload() user: any) {
@ -112,4 +112,37 @@ export class EmailController {
});
return response;
}
@MessagePattern({ cmd: 'emailResetUserPassword' })
async emailResetUserPassword(@Payload() user: any) {
const url = "http://localhost:3000/";
const image = "images/email.png";
const logo = "images/Logo Katoikia.png";
let response = await this.mailService.sendMail({
to: user["email"],
from: "katoikiap4@gmail.com",
subject: 'Restablecer contraseña',
template: 'emailResetUserPassword',
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'
},
{
filename: 'Logo_Katoikia.png',
path: __dirname + '/mails/images/Logo_Katoikia.png',
cid: 'logoKatoikia'
}],
});
return response;
}
}

View File

@ -0,0 +1,451 @@
<!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 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

@ -28,6 +28,12 @@ export class ReservationsController {
return this.reservationsService.findOne(_id);
}
@MessagePattern({ cmd: 'findReservationsByCommunity' })
findReservationsByCommunity(@Payload() body: string) {
let community_id = body['community_id'];
return this.reservationsService.findReservationsByCommunity(community_id);
}
@MessagePattern({ cmd: 'updateReservation' })
update(@Payload() reservation: ReservationDocument) {
return this.reservationsService.update(reservation.id, reservation);
@ -38,4 +44,10 @@ export class ReservationsController {
let _id = id['id'];
return this.reservationsService.remove(_id);
}
@MessagePattern({ cmd: 'removeIdCommunity' })
removeIdCommunity(@Payload() reservation: any) {
let community_id = reservation['community_id'];
return this.reservationsService.removeIdCommunity(community_id);
}
}

View File

@ -45,4 +45,13 @@ export class ReservationsService {
new: true,
});
}
async removeIdCommunity(community_id: string){
await this.reservationModel.updateMany({community_id: community_id}, {"$set":{"status": '-1'}});
}
async findReservationsByCommunity(community_id: string){
return this.reservationModel.find({ community_id: community_id }).exec();
}
}

View File

@ -20,8 +20,15 @@ export class Reservation {
@Prop()
common_area_id: string;
@Prop()
common_area_name: string;
@Prop()
user_id: string;
@Prop()
community_id: string;
}
export const ReservationSchema = SchemaFactory.createForClass(Reservation);

View File

@ -147,6 +147,13 @@ export class UsersController {
user['number_house']);
}
@MessagePattern({ cmd: 'removeIdCommunity' })
removeIdCommunity(@Payload() user: any) {
let community_id = user['community_id'];
return this.userService.removeIdCommunity(community_id);
}
@MessagePattern({ cmd: 'changeStatus' })
changeStatus(@Payload() body: string) {
let pid = body['id'];

View File

@ -72,11 +72,30 @@ export class UsersService {
);
}
async resetUserPassword(user: UserDocument) {
const password = user.password;
const passwordEncriptada = Md5.init(password);
user.password = passwordEncriptada;
this.userModel.findOneAndUpdate({ _id: user._id }, { password: passwordEncriptada }, {
new: true,
});
const pattern = { cmd: 'emailResetUserPassword' };
const payload = {
email: user['email'], password: user['password'],
date_entry: user['date_entry'], community_name: user['community_id']
};
return this.clientNotificationtApp
.send<string>(pattern, payload)
.pipe(
map((message: string) => ({ message }))
);
}
async findCommunity(community_id: string) {
const pattern = { cmd: 'findOneCommunity' }
const payload = { _id: community_id }
let callback = await this.clientCommunityApp
let callback = this.clientCommunityApp
.send<string>(pattern, payload)
.pipe(
map((response: string) => ({ response }))
@ -106,8 +125,8 @@ 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']
}, {
dni: user['dni'], email: user['email'], phone: user['phone']
}, {
new: true,
});
}
@ -204,7 +223,7 @@ export class UsersService {
}
async deleteAdminSystem(id: string) {
return this.userModel.findOneAndUpdate({ _id: id }, { status: '-1'}, {
return this.userModel.findOneAndUpdate({ _id: id }, { status: '-1' }, {
new: true,
});
}
@ -217,13 +236,13 @@ export class UsersService {
async deleteTenant(tenant_id: string, community_id: string, number_house: string) {
try{
await this.userModel.findOneAndUpdate({ _id: tenant_id }, { status: '-1', number_house:''}, {
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){
} catch (error) {
console.log(error)
return error;
}
@ -295,5 +314,11 @@ export class UsersService {
map((response: string) => ({ response }))
)
}
async removeIdCommunity(community_id: string){
await this.userModel.updateMany({community_id: community_id, user_type:'2' }, {"$set":{"community_id": ''}});
await this.userModel.updateMany({community_id: community_id, user_type:'3' }, {"$set":{"community_id": '', "status": '-1'} });
return this.userModel.updateMany({ community_id: community_id, user_type: '4' }, { "$set": { "community_id": '', "status": '-1' } });
}
}

View File

@ -7163,4 +7163,8 @@
display: flex;
flex-direction: column;
align-items: center;
}
.layout-config-button{
display: none!important;
}

View File

@ -57,6 +57,7 @@ import AreasComunes from './components/AreasComunes';
import { useCookies } from "react-cookie";
import LogInUser from './components/LogInUser';
import Page404 from './components/Page404'
import Reservaciones from './components/Reservaciones';
const App = () => {
@ -202,10 +203,9 @@ const App = () => {
icon: PrimeIcons.BUILDING,
to: '/areasComunes',
},
{ label: 'Comunicados', icon: PrimeIcons.COMMENTS, to: '/registroComunicado' },
{ label: 'Invitados', icon: PrimeIcons.USERS, to: '/invitadosComunidad' },
{ label: 'Reservaciones', icon: PrimeIcons.CALENDAR, to: '/reservaciones'},
]
},
]
@ -469,6 +469,7 @@ const App = () => {
<Route path="/guardasSeguridad" component={GuardasSeguridad} />
<Route path="/inquilinos" component={Inquilinos} />
<Route path="/areasComunes" component={AreasComunes} />
<Route path="/reservaciones" component={Reservaciones} />
<Route path="/registroComunicado" component={RegistroComunicado} />
<Route path="/invitadosComunidad" component={InvitadosComunidad} />
</>

View File

@ -67,13 +67,18 @@ const AdministradoresComunidad = () => {
item.status_text = 'Eliminado';
}
//item.full_name returns the repositorie name
return fetch(`http://localhost:4000/community/findCommunityName/${item.community_id}`, { method: 'GET' })
.then((response2) => response2.json())
.then(data => data.message)
.then(data => {
item.community_name = data['name']
return item
})
if (item.community_id || item.community_id != '') {
return fetch(`http://localhost:4000/community/findCommunityName/${item.community_id}`, { method: 'GET' })
.then((response2) => response2.json())
.then(data => data.message)
.then(data => {
item.community_name = data['name']
return item
})
} else {
item.community_name = "Sin Comunidad Asignada";
return item;
}
}));
})
.then(data => {
@ -87,9 +92,6 @@ const AdministradoresComunidad = () => {
}
async function getCommunites() {
let response = await fetch('http://localhost:4000/community/allCommunities', { method: 'GET' })
.then((response) => response.json())

View File

@ -107,6 +107,7 @@ const AdministradoresSistema = () => {
} else {
if (_admin._id) {
fetch('http://localhost:4000/user/updateAdminSystem/', {
cache: 'no-cache',
method: 'POST',

View File

@ -315,10 +315,8 @@ const Communities = () => {
setDeleteCommunitiesDialog(true);
};
const infoCommunity = async (community) => {
await tenantsList(community._id);
setCommunity({ ...community });
setCommunityDialog(true);
};
@ -383,40 +381,38 @@ const Communities = () => {
);
}
const deleteCommunity = () => {
/* fetch('http://localhost:4000/community/deleteCommunity/' + community._id, {
cache: 'no-cache',
method: 'DELETE',
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 _community = communities.filter(val => val._id !== community._id);
setCommunities(_community);
setDeleteCommunityDialog(false);
setCommunity(emptyCommunity);
toast.current.show({ severity: 'success', summary: 'Exito', detail: 'Comunidad de Viviendas Eliminada', life: 3000 });
}
)
.catch(
err => {
console.log('Ocurrió un error con el fetch', err)
toast.current.show({ severity: 'danger', summary: 'Error', detail: 'Comunidad de Viviendas no se pudo eliminar', life: 3000 });
}
);
*/
fetch('http://localhost:4000/community/deleteCommunity/' + community._id, {
cache: 'no-cache',
method: 'DELETE',
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 _community = communitiesList.filter(val => val._id !== community._id);
setCommunitiesList(_community);
setDeleteCommunityDialog(false);
setCommunity(emptyCommunity);
toast.current.show({ severity: 'success', summary: 'Exito', detail: 'Comunidad de Viviendas Eliminada', life: 3000 });
}
)
.catch(
err => {
console.log('Ocurrió un error con el fetch', err)
toast.current.show({ severity: 'danger', summary: 'Error', detail: 'Comunidad de Viviendas no se pudo eliminar', life: 3000 });
}
);
let _communities = communitiesList.filter((val) => val._id !== community._id);
_communities = _communities.filter(
(val) => val.status != -1,

View File

@ -0,0 +1,355 @@
import React, { useEffect, useState, useRef } from 'react';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Dropdown } from 'primereact/dropdown';
import { Toast } from 'primereact/toast';
import classNames from 'classnames';
import { Dialog } from 'primereact/dialog';
import { Toolbar } from 'primereact/toolbar';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHome, faUserAlt } from '@fortawesome/free-solid-svg-icons';
import { faCircleQuestion } from '@fortawesome/free-solid-svg-icons';
import { faClockFour } from '@fortawesome/free-solid-svg-icons';
import { useCookies } from 'react-cookie';
const Reservations = () => {
let emptyReservation = {
_id: null,
start_time: '',
finish_time: '',
user_id: '',
user_name: '',
common_area_id: '',
common_area_name: '',
community_id: '',
status: '1',
status_text: '',
date_entry: new Date(),
};
const [reservations, setReservations] = useState([]);
const [reservation, setReservation] = useState(emptyReservation);
const [submitted, setSubmitted] = useState(false);
const [selectedReservations, setSelectedReservations] = useState(null);
const [globalFilter, setGlobalFilter] = useState(null);
const [deleteReservationDialog, setDeleteReservationDialog] = useState(false);
const [deleteReservationsDialog, setDeleteReservationsDialog] = useState(false);
const toast = useRef(null);
const dt = useRef(null);
const [cookies, setCookies] = useCookies()
const [areas, setAreas] = useState([]);
const [tenants, setTenants] = useState([]);
async function tenantsList(id) {
await fetch(`http://localhost:4000/user/findTenants/${id}`,
{ method: 'GET' })
.then((response) => response.json())
.then(data => data.message)
.then(data => {
data = data.filter(
(val) => val.status != -1,
)
data = data.map(item => {
item.password = '';
return item;
})
setTenants(data)
});
}
async function areasList(id) {
await fetch(`http://localhost:4000/commonArea/findByCommunity/${id}`,
{ method: 'GET' })
.then((response) => response.json())
.then(data => data.message)
.then(data => {
data = data.filter(
(val) => val.status != -1,
)
setAreas(data)
});
}
async function reservationList(id) {
await fetch(`http://localhost:4000/reservation/findReservations/${id}`,
{ method: 'GET' })
.then((response) => response.json())
.then(data => data.message)
.then(data => {
data = data.filter(
(val) => val.status != -1,
)
data.map((item) => {
if (item.status == '1') {
item.status_text = 'Activo';
} else if (item.status == '0') {
item.status_text = 'Inactivo';
}
})
setReservations(data)
});
}
useEffect(() => {
tenantsList(cookies.community_id);
}, [])
useEffect(() => {
areasList(cookies.community_id);
}, [])
reservations.map((item) => {
let tenant = tenants.find(item2 => item2._id == item.user_id);
if(tenant){
item.user_name = tenant.name + ' ' + tenant.last_name;
}
});
useEffect(() => {
reservationList(cookies.community_id);
}, [])
const actionsReservation = (rowData) => {
return (
<div className="actions">
<Button
icon="pi pi-trash"
className="p-button-rounded p-button-danger mt-2 mx-2"
onClick={() => confirmDeleteReservation(rowData)}
title="Eliminar Reserva"
/>
</div>
);
};
const confirmDeleteReservation = (reservation) => {
setReservation(reservation);
setDeleteReservationDialog(true);
};
const confirmDeleteSelected = () => {
setDeleteReservationsDialog(true);
};
const leftToolbarTemplate = () => {
return (
<React.Fragment>
<div className="my-2">
<Button
label="Eliminar"
icon="pi pi-trash"
className="p-button-danger"
onClick={confirmDeleteSelected}
disabled={!selectedReservations || !selectedReservations.length}
/>
</div>
</React.Fragment>
);
};
const rightToolbarTemplate = () => {
return (
<React.Fragment>
<Button
label="Exportar"
icon="pi pi-upload"
className="p-button-help"
/>
</React.Fragment>
);
};
const header = (
<div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
<h5 className="m-0">
Reservaciones <i className="fal fa-user"></i>
</h5>
<span className="block mt-2 md:mt-0 p-input-icon-left">
<i className="pi pi-search" />
<InputText
type="search"
onInput={(e) => setGlobalFilter(e.target.value)}
placeholder="Buscar..."
/>
</span>
</div>
);
const headerStartTime = (
<>
<p>
{' '}
<FontAwesomeIcon icon={faClockFour} style={{ color: '#C08135' }} />
Hora de Apertura
</p>
</>
);
const headerEndTime = (
<>
<p>
{' '}
<FontAwesomeIcon icon={faClockFour} style={{ color: '#D7A86E' }} />{' '}
Hora de Cierre
</p>
</>
);
const headerUser = (
<>
<p>
{' '}
<FontAwesomeIcon icon={faUserAlt} style={{ color: '#C08135' }} />{' '}
Inquilino
</p>
</>
);
const headerArea = (
<>
<p>
{' '}
<FontAwesomeIcon icon={faHome} style={{ color: '#D7A86E' }} />{' '}
Área Reservada
</p>
</>
);
const headerStatus = (
<>
<p> {' '}
<FontAwesomeIcon icon={faCircleQuestion} style={{ color: "#C08135" }} />{' '}
Estado
</p>
</>
)
const statusBodyTemplate = (rowData) => {
return (
<>
<span
className={`status status-${rowData.status}`}
>
{rowData.status_text}
</span>
</>
);
};
return (
<div className="grid">
<div className="col-12">
<Toast ref={toast} />
<div className="card">
<Toolbar
className="mb-4"
left={leftToolbarTemplate}
right={rightToolbarTemplate}
></Toolbar>
<DataTable
ref={dt}
value={reservations}
dataKey="_id"
paginator
rows={5}
selection={selectedReservations}
onSelectionChange={(e) => setSelectedReservations(e.value)}
scrollable
scrollHeight="400px"
scrollDirection="both"
header={header}
rowsPerPageOptions={[5, 10, 25]}
className="datatable-responsive mt-3"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Mostrando {first} a {last} de {totalRecords} reservaciones de la comunidad"
globalFilter={globalFilter}
emptyMessage="No hay reservas registradas."
>
<Column
selectionMode="multiple"
headerStyle={{ width: '3rem' }}
></Column>
<Column
field="start_time"
sortable
header={headerStartTime}
style={{
flexGrow: 1,
flexBasis: '160px',
minWidth: '160px',
wordBreak: 'break-word',
}}
></Column>
<Column
field="finish_time"
sortable
header={headerEndTime}
style={{
flexGrow: 1,
flexBasis: '160px',
minWidth: '160px',
wordBreak: 'break-word',
}}
alignFrozen="left"
></Column>
<Column
field="user_name"
header={headerUser}
style={{
flexGrow: 1,
flexBasis: '160px',
minWidth: '160px',
wordBreak: 'break-word',
}}
></Column>
<Column
field="common_area_name"
header={headerArea}
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: '80px', minWidth: '80px' }}
body={actionsReservation}
></Column>
</DataTable>
</div>
</div>
</div>
);
}
export default React.memo(Reservations);