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: adicionar serviço agendado para remover itens(supplies) abaixo de urgente e registrar logs #157

Open
wants to merge 10 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
48 changes: 48 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 @@ -31,6 +31,7 @@
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.0.0",
"@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
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
-- CreateTable
CREATE TABLE "supply_auto_remove_logs" (
"id" TEXT NOT NULL,
"supply_id" TEXT NOT NULL,
"shelter_id" TEXT NOT NULL,
"removed_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "supply_auto_remove_logs_pkey" PRIMARY KEY ("id")
);

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

-- AddForeignKey
ALTER TABLE "supply_auto_remove_logs" ADD CONSTRAINT "supply_auto_remove_logs_supply_id_fkey" FOREIGN KEY ("supply_id") REFERENCES "supplies"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
17 changes: 17 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ model Supply {

supplyCategory SupplyCategory @relation(fields: [supplyCategoryId], references: [id])
shelterSupplies ShelterSupply[]
supplyAutoRemoveLogs SupplyAutoRemoveLog[]

@@map("supplies")
}
Expand Down Expand Up @@ -114,6 +115,7 @@ model Shelter {

shelterManagers ShelterManagers[]
shelterSupplies ShelterSupply[]
supplyAutoRemoveLogs SupplyAutoRemoveLog[]

@@map("shelters")
}
Expand Down Expand Up @@ -151,3 +153,18 @@ model Supporters {

@@map("supporters")
}


model SupplyAutoRemoveLog {
id String @id @default(uuid())
supplyId String @map("supply_id")
shelterId String @map("shelter_id")
removedAt DateTime @default(value: now()) @map("removed_at") @db.Timestamp(6)



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

@@map("supply_auto_remove_logs")
}
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { ShelterManagersModule } from './shelter-managers/shelter-managers.modul
import { ShelterSupplyModule } from './shelter-supply/shelter-supply.module';
import { PartnersModule } from './partners/partners.module';
import { SupportersModule } from './supporters/supporters.module';
import { ScheduleModule } from '@nestjs/schedule';

@Module({
imports: [
Expand All @@ -26,6 +27,7 @@ import { SupportersModule } from './supporters/supporters.module';
ShelterSupplyModule,
PartnersModule,
SupportersModule,
ScheduleModule.forRoot(),
],
controllers: [],
providers: [
Expand Down
88 changes: 88 additions & 0 deletions src/shelter-supply/shelter-supply-cleanup.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { ShelterSupply } from '@prisma/client';
import { subDays } from 'date-fns';
import { PrismaService } from 'src/prisma/prisma.service';
import { SupplyPriority } from 'src/supply/types';

@Injectable()
export class ShelterSupplyCleanupService {
private logger = new Logger('ShelterSupplyCleanupService');
constructor(private readonly prismaService: PrismaService) {}

@Cron('0 0 */2 * *')
luizpbello marked this conversation as resolved.
Show resolved Hide resolved
async handleCron() {
const shelterSuppliesToDelete = await this.getShelterSuppliesToDelete();

for (const shelterSupply of shelterSuppliesToDelete) {
this.logger.log(
`Verificando necessidade de exclusão de itens no abrigo ${shelterSupply.shelterId}`,
);

await this.removeShelterSupply(shelterSupply);
}
}

private async getShelterSuppliesToDelete(): Promise<ShelterSupply[]> {
const thresholdDate = subDays(new Date(), 2).toISOString();

return await this.prismaService.shelterSupply.findMany({
where: {
OR: [
{
createdAt: {
lte: thresholdDate,
},
updatedAt: null,
},
{
updatedAt: {
lte: thresholdDate,
},
},
],
priority: {
not: SupplyPriority.Urgent,
},
},
});
}

private async removeShelterSupply(
shelterSupply: ShelterSupply,
): Promise<void> {
this.logger.log(
`Suprimento ${shelterSupply.supplyId} já está há 48 horas com baixa movimentação e não é urgente. Removendo relação com o abrigo ${shelterSupply.shelterId}`,
);

try {
await this.prismaService.$transaction([
this.prismaService.shelterSupply.deleteMany({
where: {
supplyId: shelterSupply.supplyId,
shelterId: shelterSupply.shelterId,
},
}),
this.prismaService.supplyAutoRemoveLog.create({
data: {
supply: {
connect: {
id: shelterSupply.supplyId,
},
},
shelter: {
connect: {
id: shelterSupply.shelterId,
},
},
},
}),
]);
} catch (error) {
this.logger.error(
`Erro ao tentar remover o suprimento ${shelterSupply.supplyId} do abrigo ${shelterSupply.shelterId}`,
(error as Error).stack,
);
}
}
}
3 changes: 2 additions & 1 deletion src/shelter-supply/shelter-supply.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { Module } from '@nestjs/common';
import { ShelterSupplyService } from './shelter-supply.service';
import { ShelterSupplyController } from './shelter-supply.controller';
import { PrismaModule } from '../prisma/prisma.module';
import { ShelterSupplyCleanupService } from './shelter-supply-cleanup.service';

@Module({
imports: [PrismaModule],
providers: [ShelterSupplyService],
providers: [ShelterSupplyService, ShelterSupplyCleanupService],
controllers: [ShelterSupplyController],
})
export class ShelterSupplyModule {}