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

Endpoint para cruzar excedente e doações necessárias entre abrigos #74

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
26 changes: 26 additions & 0 deletions src/supply/supply.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import {
Body,
Controller,
DefaultValuePipe,
Get,
HttpException,
Logger,
Param,
ParseIntPipe,
Post,
Put,
Query,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';

Expand Down Expand Up @@ -52,4 +55,27 @@ export class SupplyController {
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
}
}

@Get('surplus-demand-matches')
async surplus_demand_matches(
@Query('supplyId') supplyId: string,
@Query('shelterIdSurplus') shelterIdSurplus: string,
@Query('shelterIdNeeded') shelterIdNeeded: string,
@Query('perPage', new DefaultValuePipe(20), ParseIntPipe) perPage: number,
@Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
) {
try {
const data = await this.supplyServices.surplus_demand_matches({
supplyId,
shelterIdSurplus,
shelterIdNeeded,
perPage,
page
});
return new ServerResponse(200, 'Successfully got matches between surplus and demand', data);
} catch (err: any) {
this.logger.error(`Failed to get matches: ${err}`);
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
}
}
}
70 changes: 69 additions & 1 deletion src/supply/supply.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import z from 'zod';
import { Injectable } from '@nestjs/common';

import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { CreateSupplySchema, UpdateSupplySchema } from './types';
import { CreateSupplySchema, SurplusDemandMatch, UpdateSupplySchema } from './types';

@Injectable()
export class SupplyService {
Expand Down Expand Up @@ -53,4 +54,71 @@ export class SupplyService {

return data;
}

async surplus_demand_matches(body: z.infer<typeof SurplusDemandMatch>) {
const payload = SurplusDemandMatch.parse(body);
const skip = payload.perPage * (payload.page - 1);

let where: Prisma.Sql[] = [];

if (payload.supplyId) {
if (where.length == 0) {
where.push(Prisma.sql`WHERE spl.supply_id = ${payload.supplyId}`);
} else {
where.push(Prisma.sql`spl.supply_id = ${payload.supplyId}`);
}
}
if (payload.shelterIdSurplus) {
if (where.length == 0) {
where.push(Prisma.sql`WHERE spl.shelter_id = ${payload.shelterIdSurplus}`);
} else {
where.push(Prisma.sql`spl.shelter_id = ${payload.shelterIdSurplus}`);
}
}
if (payload.shelterIdNeeded) {
if (where.length == 0) {
where.push(Prisma.sql`WHERE sd.shelter_id = ${payload.shelterIdNeeded}`);
} else {
where.push(Prisma.sql`sd.shelter_id = ${payload.shelterIdNeeded}`);
}
}

const query = Prisma.sql`
WITH supply_surplus AS (
SELECT
ss.supply_id,
sp.name AS supply_name,
s.id AS shelter_id,
s.name AS shelter_name
FROM shelter_supplies ss
INNER JOIN shelters s ON s.id = ss.shelter_id
INNER JOIN supplies sp ON sp.id = ss.supply_id
WHERE ss.priority IN (1) -- 1 is 'Remaining'
), supply_demand AS (
SELECT
ss.supply_id,
sp.name AS supply_name,
s.id AS shelter_id,
s.name AS shelter_name
FROM shelter_supplies ss
INNER JOIN shelters s ON s.id = ss.shelter_id
INNER JOIN supplies sp ON sp.id = ss.supply_id
WHERE ss.priority IN (10, 100) -- 10 & 100 are 'Needing' & 'Urgent'
)
SELECT
spl.supply_id,
spl.supply_name,
spl.shelter_id AS shelter_from_id,
spl.shelter_name AS shelter_from_name,
sd.shelter_id AS shelter_to_id,
sd.shelter_name AS shelter_to_name
FROM supply_surplus spl
INNER JOIN supply_demand sd ON sd.supply_id = spl.supply_id
${where.length > 0 ? Prisma.join(where, ' AND ') : Prisma.empty}
ORDER BY spl.supply_name DESC, shelter_from_name DESC, shelter_to_name DESC
LIMIT ${payload.perPage} OFFSET ${skip}
`;

return await this.prismaService.$queryRaw(query);
}
}
19 changes: 18 additions & 1 deletion src/supply/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,21 @@ const UpdateSupplySchema = SupplySchema.pick({
supplyCategoryId: true,
}).partial();

export { SupplySchema, CreateSupplySchema, UpdateSupplySchema, SupplyPriority };
const SurplusDemandMatch = z.object({
supplyId: z.string().nullable().optional(),
shelterIdSurplus: z.string().nullable().optional(),
shelterIdNeeded: z.string().nullable().optional(),
page: z.preprocess((v) => +((v ?? '1') as string), z.number().min(1)),
perPage: z.preprocess(
(v) => +((v ?? '10') as string),
z.number().min(1).max(100),
),
});

export {
SupplySchema,
CreateSupplySchema,
UpdateSupplySchema,
SurplusDemandMatch,
SupplyPriority
};