targo-backend/src/time-and-attendance/modules/expenses/services/expenses-archival.service.ts

62 lines
2.2 KiB
TypeScript

import { Injectable } from "@nestjs/common";
import { ExpensesArchive } from "@prisma/client";
import { PrismaService } from "src/prisma/prisma.service";
@Injectable()
export class ExpensesArchivalService {
constructor(private readonly prisma: PrismaService){}
async archiveOld(): Promise<void> {
//fetches archived timesheet's Ids
const archived_timesheets = await this.prisma.timesheetsArchive.findMany({
select: { timesheet_id: true },
});
const timesheet_ids = archived_timesheets.map(sheet => sheet.timesheet_id);
if(timesheet_ids.length === 0) {
return;
}
// copy/delete transaction
await this.prisma.$transaction(async transaction => {
//fetches expenses to move to archive
const expenses_to_archive = await transaction.expenses.findMany({
where: { timesheet_id: { in: timesheet_ids } },
});
if(expenses_to_archive.length === 0) {
return;
}
//copies sent to archive table
await transaction.expensesArchive.createMany({
data: expenses_to_archive.map(exp => ({
expense_id: exp.id,
timesheet_id: exp.timesheet_id,
bank_code_id: exp.bank_code_id,
date: exp.date,
amount: exp.amount,
attachment: exp.attachment,
comment: exp.comment,
is_approved: exp.is_approved,
supervisor_comment: exp.supervisor_comment,
})),
});
//delete from expenses table
await transaction.expenses.deleteMany({
where: { id: { in: expenses_to_archive.map(exp => exp.id) } },
})
})
}
//fetches all archived timesheets
async findAllArchived(): Promise<ExpensesArchive[]> {
return this.prisma.expensesArchive.findMany();
}
//fetches an archived timesheet
async findOneArchived(id: number): Promise<ExpensesArchive> {
return this.prisma.expensesArchive.findUniqueOrThrow({ where: { id } });
}
}