import Database from "@Common/databases/database"; import BaseRepository from "@Repositories/BaseRepository"; import { Service } from "typedi"; import { Documents, EDocumentStatus, Prisma } from "@prisma/client"; import { Document } from "le-coffre-resources/dist/SuperAdmin"; @Service() export default class DocumentsRepository extends BaseRepository { constructor(private database: Database) { super(); } protected get model() { return this.database.getClient().documents; } protected get instanceDb() { return this.database.getClient(); } /** * @description : Find many documents */ public async findMany(query: any): Promise { query.take = Math.min(query.take || this.defaultFetchRows, this.maxFetchRows); return this.model.findMany(query); } /** * @description : Create a document */ public async create(document: Document): Promise { const documentCreated = await this.model.create({ data: { folder: { connect: { uid: document.folder!.uid, }, }, depositor: { connect: { uid: document.depositor!.uid, }, }, document_type: { connect: { uid: document.document_type!.uid, }, }, }, }); await this.instanceDb.documentHistory.create({ data: { document: { connect: { uid: documentCreated.uid, }, }, }, }); return documentCreated; } /** * @description : Create many documents linked to an office folder */ public async createMany(documents: Document[]): Promise { return this.model.createMany({ data: documents.map((document) => ({ folder_uid: document.folder!.uid!, depositor_uid: document.depositor!.uid!, document_type_uid: document.document_type!.uid!, })), skipDuplicates: true, }); } /** * @description : Update data of a document */ public async update(uid: string, document: Document, refusedReason?: string): Promise { return this.model.update({ where: { uid: uid, }, data: { document_status: EDocumentStatus[document.document_status as keyof typeof EDocumentStatus], document_history: { create: { document_status: EDocumentStatus[document.document_status as keyof typeof EDocumentStatus], refused_reason: refusedReason, }, } }, }); } /** * @description : Delete a document */ public async delete(uid: string): Promise { return this.model.delete({ where: { uid: uid, }, }); } /** * @description : Find unique document */ public async findOneByUid(uid: string, query?: any): Promise { const findOneArgs: Prisma.DocumentsFindUniqueArgs = { where: { uid: uid, }, }; if (query) { findOneArgs.include = query; } const documentEntity = await this.model.findUnique(findOneArgs); if (!documentEntity) { throw new Error("Document not found"); } return documentEntity; } }