Skip to content

Develop #2

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

Merged
merged 6 commits into from
May 8, 2024
Merged
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
2 changes: 0 additions & 2 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -3,8 +3,6 @@ name: Deploy Backend
on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
build:
16 changes: 16 additions & 0 deletions prisma/migrations/20240507205058_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- CreateTable
CREATE TABLE "shelter_supplies" (
"shelter_id" TEXT NOT NULL,
"supply_id" TEXT NOT NULL,
"priority" INTEGER NOT NULL,
"created_at" VARCHAR(32) NOT NULL,
"updated_at" VARCHAR(32),

CONSTRAINT "shelter_supplies_pkey" PRIMARY KEY ("shelter_id","supply_id")
);

-- AddForeignKey
ALTER TABLE "shelter_supplies" ADD CONSTRAINT "shelter_supplies_shelter_id_fkey" FOREIGN KEY ("shelter_id") REFERENCES "shelters"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "shelter_supplies" ADD CONSTRAINT "shelter_supplies_supply_id_fkey" FOREIGN KEY ("supply_id") REFERENCES "supplies"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
3 changes: 3 additions & 0 deletions prisma/migrations/20240507221950_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "shelters" ADD COLUMN "latitude" DOUBLE PRECISION,
ADD COLUMN "longitude" DOUBLE PRECISION;
11 changes: 11 additions & 0 deletions prisma/migrations/20240508022250_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
Warnings:

- You are about to drop the column `shelter_id` on the `supplies` table. All the data in the column will be lost.

*/
-- DropForeignKey
ALTER TABLE "supplies" DROP CONSTRAINT "supplies_shelter_id_fkey";

-- AlterTable
ALTER TABLE "supplies" DROP COLUMN "shelter_id";
11 changes: 11 additions & 0 deletions prisma/migrations/20240508041443_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
Warnings:

- You are about to drop the column `priority` on the `supplies` table. All the data in the column will be lost.

*/
-- AlterTable
ALTER TABLE "shelter_supplies" ALTER COLUMN "priority" SET DEFAULT 0;

-- AlterTable
ALTER TABLE "supplies" DROP COLUMN "priority";
8 changes: 8 additions & 0 deletions prisma/migrations/20240508050213_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:

- A unique constraint covering the columns `[name]` on the table `supplies` will be added. If there are existing duplicate values, this will fail.

*/
-- CreateIndex
CREATE UNIQUE INDEX "supplies_name_key" ON "supplies"("name");
2 changes: 2 additions & 0 deletions prisma/migrations/20240508150340_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- DropIndex
DROP INDEX "supplies_name_key";
24 changes: 19 additions & 5 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -54,17 +54,29 @@ model SupplyCategory {
@@map("category_supplies")
}

model ShelterSupply {
shelterId String @map("shelter_id")
supplyId String @map("supply_id")
priority Int @default(value: 0)
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)

shelter Shelter @relation(fields: [shelterId], references: [id])
supply Supply @relation(fields: [supplyId], references: [id])

@@id([shelterId, supplyId])
@@map("shelter_supplies")
}

model Supply {
id String @id @default(uuid())
shelterId String @map("shelter_id")
supplyCategoryId String @map("supply_category_id")
name String
priority Int @default(value: 0)
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)

supplyCategory SupplyCategory @relation(fields: [supplyCategoryId], references: [id])
shelter Shelter @relation(fields: [shelterId], references: [id])
supplyCategory SupplyCategory @relation(fields: [supplyCategoryId], references: [id])
shelterSupplies ShelterSupply[]

@@map("supplies")
}
@@ -79,11 +91,13 @@ model Shelter {
capacity Int?
contact String?
prioritySum Int @default(value: 0) @map("priority_sum")
latitude Float?
longitude Float?
createdAt String @map("created_at") @db.VarChar(32)
updatedAt String? @map("updated_at") @db.VarChar(32)

supplies Supply[]
shelterManagers ShelterManagers[]
shelterSupplies ShelterSupply[]

@@map("shelters")
}
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -10,6 +10,7 @@ import { UsersModule } from './users/users.module';
import { SessionsModule } from './sessions/sessions.module';
import { SupplyCategoriesModule } from './supply-categories/supply-categories.module';
import { ShelterManagersModule } from './shelter-managers/shelter-managers.module';
import { ShelterSupplyModule } from './shelter-supply/shelter-supply.module';

@Module({
imports: [
@@ -20,6 +21,7 @@ import { ShelterManagersModule } from './shelter-managers/shelter-managers.modul
SupplyModule,
SupplyCategoriesModule,
ShelterManagersModule,
ShelterSupplyModule,
],
controllers: [],
providers: [
18 changes: 18 additions & 0 deletions src/shelter-supply/shelter-supply.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ShelterSupplyController } from './shelter-supply.controller';

describe('ShelterSupplyController', () => {
let controller: ShelterSupplyController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ShelterSupplyController],
}).compile();

controller = module.get<ShelterSupplyController>(ShelterSupplyController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
70 changes: 70 additions & 0 deletions src/shelter-supply/shelter-supply.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import {
Body,
Controller,
Get,
HttpException,
Logger,
Param,
Post,
Put,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';

import { ShelterSupplyService } from './shelter-supply.service';
import { ServerResponse } from '../utils';

@ApiTags('Suprimento de abrigos')
@Controller('shelter/supplies')
export class ShelterSupplyController {
private logger = new Logger(ShelterSupplyController.name);

constructor(private readonly shelterSupplyService: ShelterSupplyService) {}

@Get(':shelterId')
async index(@Param('shelterId') shelterId: string) {
try {
const data = await this.shelterSupplyService.index(shelterId);
return new ServerResponse(200, 'Successfully get shelter supplies', data);
} catch (err: any) {
this.logger.error(`Failed to get shelter supplies: ${err}`);
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
}
}

@Post('')
async store(@Body() body) {
try {
const data = await this.shelterSupplyService.store(body);
return new ServerResponse(
200,
'Successfully created shelter supply',
data,
);
} catch (err: any) {
this.logger.error(`Failed to create shelter supply: ${err}`);
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
}
}

@Put(':shelterId/:supplyId')
async update(
@Body() body,
@Param('shelterId') shelterId: string,
@Param('supplyId') supplyId: string,
) {
try {
const data = await this.shelterSupplyService.update({
where: { shelterId, supplyId },
data: body,
});
return new ServerResponse(
200,
'Successfully updated shelter supply',
data,
);
} catch (err: any) {
this.logger.error(`Failed to update shelter supply: ${err}`);
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
}
}
}
12 changes: 12 additions & 0 deletions src/shelter-supply/shelter-supply.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';

import { ShelterSupplyService } from './shelter-supply.service';
import { ShelterSupplyController } from './shelter-supply.controller';
import { PrismaModule } from '../prisma/prisma.module';

@Module({
imports: [PrismaModule],
providers: [ShelterSupplyService],
controllers: [ShelterSupplyController],
})
export class ShelterSupplyModule {}
18 changes: 18 additions & 0 deletions src/shelter-supply/shelter-supply.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ShelterSupplyService } from './shelter-supply.service';

describe('ShelterSupplyService', () => {
let service: ShelterSupplyService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ShelterSupplyService],
}).compile();

service = module.get<ShelterSupplyService>(ShelterSupplyService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
101 changes: 101 additions & 0 deletions src/shelter-supply/shelter-supply.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { z } from 'zod';
import { Injectable } from '@nestjs/common';

import { PrismaService } from '../prisma/prisma.service';
import { CreateShelterSupplySchema, UpdateShelterSupplySchema } from './types';

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

private async handleUpdateShelterSum(
shelterId: string,
oldPriority: number,
newPriority: number,
) {
await this.prismaService.shelter.update({
where: {
id: shelterId,
},
data: {
prioritySum: {
increment: newPriority - oldPriority,
},
updatedAt: new Date().toISOString(),
},
});
}

async store(body: z.infer<typeof CreateShelterSupplySchema>) {
const { shelterId, priority, supplyId } =
CreateShelterSupplySchema.parse(body);
await this.handleUpdateShelterSum(shelterId, 0, priority);
await this.prismaService.shelterSupply.create({
data: {
shelterId,
priority,
supplyId,
createdAt: new Date().toISOString(),
},
});
}

async update(body: z.infer<typeof UpdateShelterSupplySchema>) {
const { data, where } = UpdateShelterSupplySchema.parse(body);
const { priority } = data;
if (priority !== null && priority !== undefined) {
const shelterSupply = await this.prismaService.shelterSupply.findFirst({
where: {
shelterId: where.shelterId,
supplyId: where.supplyId,
},
select: {
priority: true,
},
});
if (shelterSupply)
await this.handleUpdateShelterSum(
where.shelterId,
shelterSupply.priority,
priority,
);
}

await this.prismaService.shelterSupply.update({
where: {
shelterId_supplyId: where,
},
data: {
...data,
createdAt: new Date().toISOString(),
},
});
}

async index(shelterId: string) {
return await this.prismaService.shelterSupply.findMany({
where: {
shelterId,
},
select: {
priority: true,
supply: {
select: {
id: true,
name: true,
supplyCategory: {
select: {
id: true,
name: true,
},
},
updatedAt: true,
createdAt: true,
},
},
createdAt: true,
updatedAt: true,
},
});
}
}
Loading