From 38da3061d21e03336d4025ee779f22f73c8a9dcc Mon Sep 17 00:00:00 2001 From: Leonardo Santos Date: Tue, 28 May 2024 11:18:38 -0300 Subject: [PATCH] feat: add dashboard endpoints (#131) Co-authored-by: M4rcxs Co-authored-by: Marcos Silva <94569840+M4rcxs@users.noreply.github.com> --- package-lock.json | 35 ++++ package.json | 1 + prisma/dev_dump.sql | 2 +- src/app.module.ts | 2 + .../dashboard/dashboard.controller.spec.ts | 20 +++ src/modules/dashboard/dashboard.controller.ts | 22 +++ src/modules/dashboard/dashboard.module.ts | 11 ++ .../dashboard/dashboard.service.spec.ts | 18 ++ src/modules/dashboard/dashboard.service.ts | 160 ++++++++++++++++++ src/partners/partners.controller.ts | 2 + 10 files changed, 272 insertions(+), 1 deletion(-) create mode 100644 src/modules/dashboard/dashboard.controller.spec.ts create mode 100644 src/modules/dashboard/dashboard.controller.ts create mode 100644 src/modules/dashboard/dashboard.module.ts create mode 100644 src/modules/dashboard/dashboard.service.spec.ts create mode 100644 src/modules/dashboard/dashboard.service.ts diff --git a/package-lock.json b/package-lock.json index afb97b4b..65c13732 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,6 +15,7 @@ "@nestjs/jwt": "^10.2.0", "@nestjs/passport": "^10.0.3", "@nestjs/platform-fastify": "^10.3.8", + "@nestjs/schedule": "^4.0.2", "@nestjs/swagger": "^7.3.1", "@prisma/client": "^5.13.0", "bcrypt": "^5.1.1", @@ -2571,6 +2572,11 @@ "@types/node": "*" } }, + "node_modules/@types/luxon": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.4.2.tgz", + "integrity": "sha512-TifLZlFudklWlMBfhubvgqTXRzLDI5pCbGa4P8a3wPyUQSW+1xQ5eDsreP9DWHX3tjq1ke96uYG/nwundroWcA==" + }, "node_modules/@types/methods": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", @@ -4140,6 +4146,15 @@ "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", "dev": true }, + "node_modules/cron": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/cron/-/cron-3.1.7.tgz", + "integrity": "sha512-tlBg7ARsAMQLzgwqVxy8AZl/qlTc5nibqYwtNGoCrd+cV+ugI+tvZC1oT/8dFH8W455YrywGykx/KMmAqOr7Jw==", + "dependencies": { + "@types/luxon": "~3.4.0", + "luxon": "~3.4.0" + } + }, "node_modules/cross-spawn": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", @@ -7078,6 +7093,14 @@ "yallist": "^3.0.2" } }, + "node_modules/luxon": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.4.4.tgz", + "integrity": "sha512-zobTr7akeGHnv7eBOXcRgMeCP6+uyYsczwmeRCauvpvaAltgNyTbLH/+VaEAPUeWBT+1GuNmz4wC/6jtQzbbVA==", + "engines": { + "node": ">=12" + } + }, "node_modules/magic-string": { "version": "0.30.5", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.5.tgz", @@ -9764,6 +9787,18 @@ "node": ">= 0.4.0" } }, + "node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/v8-compile-cache-lib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", diff --git a/package.json b/package.json index b56b950f..a7caf97b 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "@nestjs/jwt": "^10.2.0", "@nestjs/passport": "^10.0.3", "@nestjs/platform-fastify": "^10.3.8", + "@nestjs/schedule": "^4.0.2", "@nestjs/swagger": "^7.3.1", "@prisma/client": "^5.13.0", "bcrypt": "^5.1.1", diff --git a/prisma/dev_dump.sql b/prisma/dev_dump.sql index 359fb6ef..211625a8 100644 --- a/prisma/dev_dump.sql +++ b/prisma/dev_dump.sql @@ -97,7 +97,7 @@ INSERT INTO public.users VALUES ('e0306bc0-8c29-429a-bbd2-384f48d4f993', 'Dinho' INSERT INTO public.users VALUES ('e82f476a-1574-4dd2-a4c4-1c1f0117db12', 'Rhuam', '51992047974', '$2b$10$V4hFTbT7MrskROc4TI2lNe6gAd0g7U1niziAPycFueLhPJRFIfoGm', '51992047974', '2024-05-05T22:06:11.390Z', '2024-05-16T18:52:36.650Z', 'Admin', 'Estevam'); --- +--- -- Data for Name: shelters; Type: TABLE DATA; Schema: public; Owner: doadmin -- diff --git a/src/app.module.ts b/src/app.module.ts index 942260de..3f814215 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -12,6 +12,7 @@ import { SupplyCategoriesModule } from './supply-categories/supply-categories.mo import { ShelterManagersModule } from './shelter-managers/shelter-managers.module'; import { ShelterSupplyModule } from './shelter-supply/shelter-supply.module'; import { PartnersModule } from './partners/partners.module'; +import { DashboardModule } from './modules/dashboard/dashboard.module'; import { SupportersModule } from './supporters/supporters.module'; import { SuppliesHistoryModule } from './supplies-history/supplies-history.module'; @@ -26,6 +27,7 @@ import { SuppliesHistoryModule } from './supplies-history/supplies-history.modul ShelterManagersModule, ShelterSupplyModule, PartnersModule, + DashboardModule, SupportersModule, SuppliesHistoryModule, ], diff --git a/src/modules/dashboard/dashboard.controller.spec.ts b/src/modules/dashboard/dashboard.controller.spec.ts new file mode 100644 index 00000000..9ae8da71 --- /dev/null +++ b/src/modules/dashboard/dashboard.controller.spec.ts @@ -0,0 +1,20 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { DashboardController } from './dashboard.controller'; +import { DashboardService } from './dashboard.service'; + +describe('DashboardController', () => { + let controller: DashboardController; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + controllers: [DashboardController], + providers: [DashboardService], + }).compile(); + + controller = module.get(DashboardController); + }); + + it('should be defined', () => { + expect(controller).toBeDefined(); + }); +}); diff --git a/src/modules/dashboard/dashboard.controller.ts b/src/modules/dashboard/dashboard.controller.ts new file mode 100644 index 00000000..db2c43a7 --- /dev/null +++ b/src/modules/dashboard/dashboard.controller.ts @@ -0,0 +1,22 @@ +import { Controller, Get, HttpException, Logger, Query } from '@nestjs/common'; +import { DashboardService } from './dashboard.service'; +import { ServerResponse } from '@/utils/utils'; +import { ApiTags } from '@nestjs/swagger'; + +@ApiTags('Dashboard') +@Controller('dashboard') +export class DashboardController { + private logger = new Logger(); + constructor(private readonly dashboardService: DashboardService) {} + + @Get('') + async index(@Query() query) { + try { + const data = await this.dashboardService.index(query); + return new ServerResponse(200, 'Successfully get dashboard', data); + } catch (err: any) { + this.logger.error(`Failed to get shelters: ${err}`); + throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400); + } + } +} diff --git a/src/modules/dashboard/dashboard.module.ts b/src/modules/dashboard/dashboard.module.ts new file mode 100644 index 00000000..9a988b87 --- /dev/null +++ b/src/modules/dashboard/dashboard.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { DashboardService } from './dashboard.service'; +import { DashboardController } from './dashboard.controller'; +import { PrismaModule } from 'src/prisma/prisma.module'; + +@Module({ + imports: [PrismaModule], + controllers: [DashboardController], + providers: [DashboardService], +}) +export class DashboardModule {} diff --git a/src/modules/dashboard/dashboard.service.spec.ts b/src/modules/dashboard/dashboard.service.spec.ts new file mode 100644 index 00000000..dc3993ae --- /dev/null +++ b/src/modules/dashboard/dashboard.service.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { DashboardService } from './dashboard.service'; + +describe('DashboardService', () => { + let service: DashboardService; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [DashboardService], + }).compile(); + + service = module.get(DashboardService); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); +}); diff --git a/src/modules/dashboard/dashboard.service.ts b/src/modules/dashboard/dashboard.service.ts new file mode 100644 index 00000000..22952e26 --- /dev/null +++ b/src/modules/dashboard/dashboard.service.ts @@ -0,0 +1,160 @@ +import * as qs from 'qs'; +import { Injectable } from '@nestjs/common'; +import { PrismaService } from 'src/prisma/prisma.service'; +import { ShelterSearchPropsSchema } from 'src/shelter/types/search.types'; +import { SearchSchema } from 'src/types'; +import { ShelterSearch } from 'src/shelter/ShelterSearch'; +import { DefaultArgs } from '@prisma/client/runtime/library'; +import { Prisma } from '@prisma/client'; + +@Injectable() +export class DashboardService { + constructor(private readonly prismaService: PrismaService) {} + + async index(query: any) { + const { + order, + orderBy, + page, + perPage, + search: searchQuery, + } = SearchSchema.parse(query); + const queryData = ShelterSearchPropsSchema.parse(qs.parse(searchQuery)); + const { getQuery } = new ShelterSearch(this.prismaService, queryData); + const where = await getQuery(); + + const take = perPage; + const skip = perPage * (page - 1); + + const whereData: Prisma.ShelterFindManyArgs = { + take, + skip, + orderBy: { [orderBy]: order }, + where, + }; + + const allShelters = await this.prismaService.shelter.findMany({ + ...whereData, + select: { + id: true, + name: true, + shelteredPeople: true, + actived: true, + capacity: true, + shelterSupplies: { + select: { + priority: true, + supply: { + select: { + supplyCategory: { + select: { + name: true, + }, + }, + }, + }, + }, + }, + }, + }); + + const categoriesWithPriorities = await this.prismaService.supplyCategory.findMany({ + select: { + id: true, + name: true, + supplies: { + select: { + shelterSupplies: { + select: { + priority: true, + shelterId: true + } + } + } + } + } + }); + + const result = categoriesWithPriorities.map(category => { + const priorityCounts = { + priority100: 0, + priority10: 0, + priority1: 0, + }; + + const countedShelters = new Set(); + + category.supplies.forEach(supply => { + supply.shelterSupplies.forEach(shelterSupply => { + if (!countedShelters.has(shelterSupply.shelterId)) { + switch (shelterSupply.priority) { + case 100: + priorityCounts.priority100++; + break; + case 10: + priorityCounts.priority10++; + break; + case 1: + priorityCounts.priority1++; + break; + default: + break; + } + countedShelters.add(shelterSupply.shelterId); + } + }); + }); + + return { + categoryId: category.id, + categoryName: category.name, + ...priorityCounts, + }; + }); + + const allPeopleSheltered = allShelters.reduce((accumulator, current) => { + if ( + current.actived && + current.capacity !== null && + current.capacity > 0 + ) { + return accumulator + (current.shelteredPeople ?? 0); + } else { + return accumulator; + } + }, 0); + + const numSheltersAvailable = allShelters.filter(shelter => { + if (shelter.actived && shelter.capacity !== null && shelter.capacity > 0) { + return (shelter.shelteredPeople ?? 0) < shelter.capacity; + } + return false; + }).length; + + const numSheltersFull = allShelters.reduce((count, shelter) => { + if (shelter.actived && shelter.capacity !== null && shelter.capacity > 0) { + if ((shelter.shelteredPeople ?? 0) >= shelter.capacity) { + return count + 1; + } + } + return count; + }, 0); + + const shelterWithoutInformation = allShelters.reduce((count, shelter) => { + if (shelter.shelteredPeople === null || shelter.shelteredPeople === undefined) { + return count + 1; + } + return count; + }, 0); + + + return { + allShelters: allShelters.length, + allPeopleSheltered: allPeopleSheltered, + shelterAvaliable: numSheltersAvailable, + shelterFull: numSheltersFull, + shelterWithoutInformation: shelterWithoutInformation, + categoriesWithPriorities: result, + }; + } +} diff --git a/src/partners/partners.controller.ts b/src/partners/partners.controller.ts index 9b33a6fa..2e1c3f4b 100644 --- a/src/partners/partners.controller.ts +++ b/src/partners/partners.controller.ts @@ -9,8 +9,10 @@ import { } from '@nestjs/common'; import { PartnersService } from './partners.service'; import { ServerResponse } from '../utils'; +import { ApiTags } from '@nestjs/swagger'; import { AdminGuard } from '@/guards/admin.guard'; +@ApiTags('Parceiros') @Controller('partners') export class PartnersController { private logger = new Logger(PartnersController.name);