Skip to content
Open
Show file tree
Hide file tree
Changes from 6 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,
"created_at" VARCHAR(32) NOT NULL,

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;
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
Warnings:

- You are about to drop the column `created_at` on the `supply_auto_remove_logs` table. All the data in the column will be lost.
- Added the required column `removed_at` to the `supply_auto_remove_logs` table without a default value. This is not possible if the table is not empty.

*/
-- AlterTable
ALTER TABLE "supply_auto_remove_logs" DROP COLUMN "created_at",
ADD COLUMN "removed_at" VARCHAR(32) NOT NULL;
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 String @map("removed_at") @db.VarChar(32)



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
98 changes: 98 additions & 0 deletions src/shelter-supply/shelter-supply-cleanup.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { ShelterSupply } from '@prisma/client';
import { differenceInHours, parseISO } 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 * *')
async handleCron() {
const shelterSupplies = await this.prismaService.shelterSupply.findMany({
include: {
supply: true,
shelter: true,
},
});

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

await this.removeShelterSupply(shelterSupply);
}
}

hasPassed48Hours(
createdAt: string | null,
updatedAt: string | null,
): boolean {
const targetDate = updatedAt
? parseISO(updatedAt)
: createdAt
? parseISO(createdAt)
: null;

if (!targetDate) {
return false;
}

const hoursDifference = differenceInHours(new Date(), targetDate);

return hoursDifference >= 48;
}

private async removeShelterSupply(shelterSupply: ShelterSupply) {
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}`,
);

if (!this.canRemoveShelterSupply(shelterSupply)) return;
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,
},
},
removedAt: new Date().toISOString(),
},
}),
]);
} catch (error) {
this.logger.error(
`Erro ao tentar remover o suprimento ${shelterSupply.supplyId} do abrigo ${shelterSupply.shelterId}`,
(error as Error).stack,
);
}
}

private canRemoveShelterSupply(shelterSupply: ShelterSupply): boolean {
const hasPassedTime = this.hasPassed48Hours(
shelterSupply.createdAt,
shelterSupply.updatedAt,
);

const isNotUrgent = shelterSupply.priority !== SupplyPriority.Urgent;

return isNotUrgent && hasPassedTime;
}
}
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 {}