Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add dashboard endpoints #131

Merged
merged 19 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -26,6 +27,7 @@ import { SuppliesHistoryModule } from './supplies-history/supplies-history.modul
ShelterManagersModule,
ShelterSupplyModule,
PartnersModule,
DashboardModule,
SupportersModule,
SuppliesHistoryModule,
],
Expand Down
20 changes: 20 additions & 0 deletions src/modules/dashboard/dashboard.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -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>(DashboardController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
22 changes: 22 additions & 0 deletions src/modules/dashboard/dashboard.controller.ts
Original file line number Diff line number Diff line change
@@ -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) {
rodrigooler marked this conversation as resolved.
Show resolved Hide resolved
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);
}
}
}
11 changes: 11 additions & 0 deletions src/modules/dashboard/dashboard.module.ts
Original file line number Diff line number Diff line change
@@ -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 {}
18 changes: 18 additions & 0 deletions src/modules/dashboard/dashboard.service.spec.ts
Original file line number Diff line number Diff line change
@@ -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>(DashboardService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
140 changes: 140 additions & 0 deletions src/modules/dashboard/dashboard.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
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 { parseTagResponse, ShelterSearch } from 'src/shelter/ShelterSearch';
import { DefaultArgs } from '@prisma/client/runtime/library';
import { Prisma } from '@prisma/client';
import { SupplyPriority } from 'src/supply/types';

@Injectable()
export class DashboardService {
constructor(private readonly prismaService: PrismaService) {}

async index(query: any) {
rodrigooler marked this conversation as resolved.
Show resolved Hide resolved
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 count = await this.prismaService.shelter.count({ where });

const take = perPage;
const skip = perPage * (page - 1);

const whereData: Prisma.ShelterFindManyArgs<DefaultArgs> = {
take,
skip,
orderBy: { [orderBy]: order },
where,
};

//Shelters
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
}
}
}
}
}
});

// Mapeia as categorias e conta as prioridades para cada abrigo
const result = categoriesWithPriorities.map(category => {
const priorityCounts = {
priority100: 0,
priority10: 0,
priority1: 0
};

// Cria um conjunto para evitar a contagem duplicada de abrigos
const countedShelters = new Set();

// Para cada abrigo associado à categoria
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;
}
// Adiciona o abrigo ao conjunto para evitar a contagem duplicada
rodrigooler marked this conversation as resolved.
Show resolved Hide resolved
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);


return {
allShelters: allShelters.length,
categoriesWithPriorities: result,
allPeopleSheltered: allPeopleSheltered,
};
}
}
1 change: 1 addition & 0 deletions src/modules/dashboard/entities/dashboard.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class Dashboard {}
rodrigooler marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 2 additions & 0 deletions src/partners/partners.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down