-
Notifications
You must be signed in to change notification settings - Fork 294
feat: adicionar serviço agendado para remover itens(supplies) abaixo de urgente e registrar logs #157
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
Open
luizpbello
wants to merge
10
commits into
SOS-RS:develop
Choose a base branch
from
luizpbello:develop
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: adicionar serviço agendado para remover itens(supplies) abaixo de urgente e registrar logs #157
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
a4196e4
feat: adicionar serviço agendado para remover itens(supplies) abaixo …
luizpbello 7a877f3
fix: remove modulo schedule genérico e move o service para shelter-su…
luizpbello da6583e
fix: remove pasta de modulo genérico desnecessária
luizpbello d485a9d
refact: Adicionado cron job para remoção automática de suprimentos de…
luizpbello 22af9ea
fix: crrogie parametros passados para as funções, renomeia funções pa…
luizpbello 9c0cc2b
refact: ajuste parametro das funções e move lógica de canRemove para …
luizpbello 6027b3e
refact: ajusta findMany do shelterSupply aplicando condições diretame…
luizpbello 8a4983b
chore: adiciona await no findMany
luizpbello 7ff9df0
refact: ajustado coluna remove_at no model de supplyAutoRemoveLogs
luizpbello 44e00f6
refact: remove criação do removed_at
luizpbello File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
15 changes: 15 additions & 0 deletions
15
prisma/migrations/20240521123041_create_supply_remove_log/migration.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 * *') | ||
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, | ||
); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.