Files
bodyshop-media-server/bills/billsListMedia.ts
2024-08-27 13:45:12 -07:00

95 lines
3.3 KiB
TypeScript

import { Request, Response } from "express";
import { fileTypeFromFile } from "file-type";
import { FileTypeResult } from "file-type/core";
import fs from "fs-extra";
import path from "path";
import GenerateUrl from "../util/MediaUrlGen.js";
import GenerateThumbnail from "../util/generateThumbnail.js";
import MediaFile from "../util/interfaces/MediaFile.js";
import ListableChecker from "../util/listableChecker.js";
import { PathToRoBillsFolder } from "../util/pathGenerators.js";
import { FolderPaths } from "../util/serverInit.js";
/** @description Bills will use the hierarchy of PDFs stored under the Job first, and then the Bills folder. */
export async function BillsListMedia(req: Request, res: Response) {
const jobid: string = (req.body.jobid || "").trim();
//const vendorid: string = (req.body.vendorid || "").trim();
const invoice_number: string = (req.body.invoice_number || "").trim();
let ret: MediaFile[];
//Ensure all directories exist.
await fs.ensureDir(PathToRoBillsFolder(jobid));
if (req.files) {
ret = await Promise.all(
(req.files as Express.Multer.File[]).map(async (file) => {
const relativeFilePath: string = path.join(PathToRoBillsFolder(jobid), file.filename);
const relativeThumbPath: string = await GenerateThumbnail(relativeFilePath);
const type: FileTypeResult | undefined = await fileTypeFromFile(relativeFilePath);
return {
type,
size: file.size,
src: GenerateUrl([
FolderPaths.StaticPath,
FolderPaths.JobsFolder,
jobid,
FolderPaths.BillsSubDir,
file.filename
]),
thumbnail: GenerateUrl([
FolderPaths.StaticPath,
FolderPaths.JobsFolder,
jobid,
FolderPaths.BillsSubDir,
relativeThumbPath
]),
thumbnailHeight: 250,
thumbnailWidth: 250,
filename: file.filename,
relativeFilePath
};
})
);
} else {
let filesList: fs.Dirent[] = (
await fs.readdir(PathToRoBillsFolder(jobid), {
withFileTypes: true
})
).filter(
(f) =>
f.isFile() &&
!/(^|\/)\.[^\/\.]/g.test(f.name) &&
(invoice_number !== "" ? f.name.toLowerCase().includes(invoice_number.toLowerCase()) : true) &&
ListableChecker(f)
);
ret = await Promise.all(
filesList.map(async (file) => {
const relativeFilePath: string = path.join(PathToRoBillsFolder(jobid), file.name);
const relativeThumbPath: string = await GenerateThumbnail(relativeFilePath);
const type: FileTypeResult | undefined = await fileTypeFromFile(relativeFilePath);
const fileSize = await fs.stat(relativeFilePath);
return {
type,
size: fileSize.size,
src: GenerateUrl([FolderPaths.StaticPath, FolderPaths.JobsFolder, jobid, FolderPaths.BillsSubDir, file.name]),
thumbnail: GenerateUrl([
FolderPaths.StaticPath,
FolderPaths.JobsFolder,
jobid,
FolderPaths.BillsSubDir,
relativeThumbPath
]),
thumbnailHeight: 250,
thumbnailWidth: 250,
filename: file.name,
relativeFilePath
};
})
);
}
res.json(ret);
}