lecoffre-back/src/app/api/customer/FilesController.ts
2023-09-14 10:20:12 +02:00

278 lines
8.4 KiB
TypeScript

import { Response, Request } from "express";
import { Controller, Delete, Get, Post, Put } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import { Service } from "typedi";
import FilesService from "@Services/common/FilesService/FilesService";
import { Files, Prisma } from "@prisma/client";
import { File } from "le-coffre-resources/dist/Customer";
import { Document } from "le-coffre-resources/dist/Customer";
import { validateOrReject } from "class-validator";
import DocumentsService from "@Services/customer/DocumentsService/DocumentsService";
import authHandler from "@App/middlewares/AuthHandler";
import fileHandler from "@App/middlewares/CustomerHandler/FileHandler";
import DocumentTypesService from "@Services/super-admin/DocumentTypesService/DocumentTypesService";
import { DocumentType } from "le-coffre-resources/dist/SuperAdmin";
import ObjectHydrate from "@Common/helpers/ObjectHydrate";
import NotificationBuilder from "@Common/notifications/NotificationBuilder";
@Controller()
@Service()
export default class FilesController extends ApiController {
constructor(private filesService: FilesService, private documentService: DocumentsService, private documentTypesService : DocumentTypesService, private notificationBuilder : NotificationBuilder) {
super();
}
/**
* @description Get all Files
* @returns File[] list of Files
*/
@Get("/api/v1/customer/files", [authHandler])
protected async get(req: Request, response: Response) {
try {
//get query
let query: Prisma.FilesFindManyArgs = {};
if (req.query["q"]) {
query = JSON.parse(req.query["q"] as string);
}
const customerId: string = req.body.user.customerId;
const customerWhereInput: Prisma.FilesWhereInput = { document: { depositor: { uid: customerId } } };
query.where = customerWhereInput;
//call service to get prisma entity
const fileEntities = await this.filesService.get(query);
//Hydrate ressource with prisma entity
const files = File.hydrateArray<File>(fileEntities, { strategy: "excludeAll" });
//success
this.httpSuccess(response, files);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Get a specific File by uid
*/
@Get("/api/v1/customer/files/download/:uid", [authHandler, fileHandler])
protected async download(req: Request, response: Response) {
const uid = req.params["uid"];
if (!uid) {
this.httpBadRequest(response, "uid not found");
return;
}
try {
const fileInfo = await this.filesService.download(uid);
if (!fileInfo) {
this.httpNotFoundRequest(response, "file not found");
return;
}
response.setHeader("Content-Type", fileInfo.file.mimetype);
response.setHeader("Content-Disposition", `inline; filename=${encodeURIComponent(fileInfo.file.file_name)}`);
this.httpSuccess(response, fileInfo.buffer);
} catch (error) {
this.httpInternalError(response, error);
return;
}
}
/**
* @description Create a new File
* @returns File created
*/
@Post("/api/v1/customer/files", [authHandler, fileHandler])
protected async post(req: Request, response: Response) {
try {
//get file
if (!req.file) throw new Error("No file provided");
//init File resource with request body values
const fileEntity = File.hydrate<File>(JSON.parse(req.body["q"]));
//validate File
// await validateOrReject(fileEntity, { groups: ["createFile"] });
//call service to get prisma entity
const fileEntityCreated = await this.filesService.create(fileEntity, req.file);
const document = await this.documentService.getByUid(fileEntity.document!.uid!);
const documentToUpdate = Document.hydrate<Document>(document!);
documentToUpdate!.document_status = "DEPOSITED";
const documentUpdated = await this.documentService.update(document!.uid!, documentToUpdate);
await this.notificationBuilder.sendDocumentDepositedNotification(documentUpdated!);
//Hydrate ressource with prisma entity
const fileEntityHydrated = File.hydrate<File>(fileEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpCreated(response, fileEntityHydrated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Update a specific file
*/
@Put("/api/v1/customer/files/:uid", [authHandler, fileHandler])
protected async update(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
throw new Error("No uid provided");
}
const fileFound = await this.filesService.getByUid(uid);
if (!fileFound) {
this.httpNotFoundRequest(response, "file not found");
return;
}
//init File resource with request body values
const fileEntity = File.hydrate<File>(req.body);
//call service to get prisma entity
const fileEntityUpdated: Files = await this.filesService.update(uid, fileEntity);
//Hydrate ressource with prisma entity
const file = File.hydrate<File>(fileEntityUpdated, { strategy: "excludeAll" });
//success
this.httpSuccess(response, file);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
/**
* @description Delete a specific File
*/
@Delete("/api/v1/customer/files/:uid", [authHandler, fileHandler])
protected async delete(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
this.httpBadRequest(response, "No uid provided");
return;
}
const fileFound = await this.filesService.getByUid(uid);
if (!fileFound) {
this.httpNotFoundRequest(response, "file not found");
return;
}
//call service to get prisma entity
const fileEntity = await this.filesService.deleteKeyAndArchive(uid);
if (!fileEntity) {
this.httpNotFoundRequest(response, "file not found");
return;
}
//Hydrate ressource with prisma entity
const file = File.hydrate<File>(fileEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, file);
} catch (error) {
this.httpInternalError(response, error);
return;
}
}
/**
* @description Get a specific File by uid
*/
@Get("/api/v1/customer/files/:uid", [authHandler, fileHandler])
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
this.httpBadRequest(response, "No uid provided");
return;
}
//get query
let query;
if (req.query["q"]) {
query = JSON.parse(req.query["q"] as string);
}
const fileEntity = await this.filesService.getByUid(uid, query);
if (!fileEntity) {
this.httpNotFoundRequest(response, "file not found");
return;
}
//Hydrate ressource with prisma entity
const file = File.hydrate<File>(fileEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, file);
} catch (error) {
this.httpInternalError(response, error);
return;
}
}
/**
* @description Create a new File
* @returns File created
*/
@Post("/api/v1/customer/addPersonalFile", [authHandler, fileHandler])
protected async addPersonalFile(req: Request, response: Response) {
try {
//get file
if (!req.file) throw new Error("No file provided");
//init File resource with request body values
const fileEntity = File.hydrate<File>(JSON.parse(req.body["q"]));
const documentTypeEntities = await this.documentTypesService.get({ where: { name: "Other"} });
const documentTypeEntity = documentTypeEntities[0];
const documentType = ObjectHydrate.hydrate<DocumentType>(new DocumentType(), documentTypeEntity!, { strategy: "excludeAll" });
const documentEntity = Document.hydrate<Document>({document_type: documentType});
await validateOrReject(documentEntity, { groups: ["createDocument"], forbidUnknownValues: false });
const documentEntityCreated = await this.documentService.create(documentEntity);
const document = Document.hydrate<Document>(documentEntityCreated, {
strategy: "excludeAll",
});
fileEntity.document = document;
const fileEntityCreated = await this.filesService.create(fileEntity, req.file);
const documentToUpdate = Document.hydrate<Document>(document!);
documentToUpdate!.document_status = "DEPOSITED";
await this.documentService.update(document!.uid!, documentToUpdate);
//Hydrate ressource with prisma entity
const fileEntityHydrated = File.hydrate<File>(fileEntityCreated, {
strategy: "excludeAll",
});
//success
this.httpCreated(response, fileEntityHydrated);
} catch (error) {
this.httpBadRequest(response, error);
return;
}
}
}