feat: edm integrated document template
This commit is contained in:
parent
542c260aba
commit
56318f581c
3 changed files with 244 additions and 1 deletions
|
|
@ -9,6 +9,9 @@ import HttpError from "../interfaces/http-error";
|
||||||
import HttpStatus from "../interfaces/http-status";
|
import HttpStatus from "../interfaces/http-status";
|
||||||
import { getFileBuffer, listFile } from "../utils/minio";
|
import { getFileBuffer, listFile } from "../utils/minio";
|
||||||
import { dateFormat } from "../utils/datetime";
|
import { dateFormat } from "../utils/datetime";
|
||||||
|
import { downloadFile as edmDownloadFile, list as edmList } from "../services/edm/edm-api";
|
||||||
|
|
||||||
|
const DOCUMENT_PATH = process.env.DOCUMENT_TEMPLATE_LOCATION?.split("/").filter(Boolean) || [];
|
||||||
|
|
||||||
const quotationData = (id: string) =>
|
const quotationData = (id: string) =>
|
||||||
prisma.quotation.findFirst({
|
prisma.quotation.findFirst({
|
||||||
|
|
@ -66,6 +69,13 @@ const quotationData = (id: string) =>
|
||||||
export class DocTemplateController extends Controller {
|
export class DocTemplateController extends Controller {
|
||||||
@Get()
|
@Get()
|
||||||
async getTemplate() {
|
async getTemplate() {
|
||||||
|
if (
|
||||||
|
process.env.DOCUMENT_TEMPLATE_PROVIDER &&
|
||||||
|
process.env.DOCUMENT_TEMPLATE_PROVIDER === "edm-api"
|
||||||
|
) {
|
||||||
|
const ret = await edmList("file", DOCUMENT_PATH);
|
||||||
|
if (ret) return ret.map((v) => v.fileName);
|
||||||
|
}
|
||||||
return await listFile(`doc-template/`);
|
return await listFile(`doc-template/`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -122,7 +132,29 @@ export class DocTemplateController extends Controller {
|
||||||
if (!data) throw notFoundError("Data");
|
if (!data) throw notFoundError("Data");
|
||||||
if (dataOnly) return record;
|
if (dataOnly) return record;
|
||||||
|
|
||||||
const template = await getFileBuffer(`doc-template/${documentTemplate}`);
|
let template: Buffer<ArrayBufferLike> | null = null;
|
||||||
|
|
||||||
|
switch (process.env.DOCUMENT_TEMPLATE_PROVIDER) {
|
||||||
|
case "edm-api":
|
||||||
|
await edmDownloadFile(DOCUMENT_PATH, documentTemplate).then(async (payload) => {
|
||||||
|
if (!payload) return;
|
||||||
|
const res = await fetch(payload.downloadUrl);
|
||||||
|
if (!res.ok) return;
|
||||||
|
template = Buffer.from(await res.arrayBuffer());
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "local":
|
||||||
|
default:
|
||||||
|
template = await getFileBuffer(`${DOCUMENT_PATH.join("/")}/${documentTemplate}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!template) {
|
||||||
|
throw new HttpError(
|
||||||
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
"Failed to get template file",
|
||||||
|
"templateGetFailed",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (!data) Readable.from(template);
|
if (!data) Readable.from(template);
|
||||||
|
|
||||||
|
|
|
||||||
39
src/interfaces/edm.ts
Normal file
39
src/interfaces/edm.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
export interface StorageFolder {
|
||||||
|
/**
|
||||||
|
* @prop Full path to this folder. It is used as key as there are no files or directories at the same location.
|
||||||
|
*/
|
||||||
|
pathname: string;
|
||||||
|
/**
|
||||||
|
* @prop Directory / Folder name.
|
||||||
|
*/
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
createdAt: string | Date;
|
||||||
|
createdBy: string | Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StorageFile {
|
||||||
|
/**
|
||||||
|
* @prop Full path to this folder. It is used as key as there are no files or directories at the same location.
|
||||||
|
*/
|
||||||
|
pathname: string;
|
||||||
|
|
||||||
|
fileName: string;
|
||||||
|
fileSize: number;
|
||||||
|
fileType: string;
|
||||||
|
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
author: string;
|
||||||
|
category: string[];
|
||||||
|
keyword: string[];
|
||||||
|
metadata: Record<string, unknown>;
|
||||||
|
|
||||||
|
path: string;
|
||||||
|
upload: boolean;
|
||||||
|
|
||||||
|
updatedAt: string | Date;
|
||||||
|
updatedBy: string;
|
||||||
|
createdAt: string | Date;
|
||||||
|
createdBy: string;
|
||||||
|
}
|
||||||
172
src/services/edm/edm-api.ts
Normal file
172
src/services/edm/edm-api.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
import { DecodedJwt, createDecoder } from "fast-jwt";
|
||||||
|
import HttpError from "../../interfaces/http-error";
|
||||||
|
import HttpStatus from "../../interfaces/http-status";
|
||||||
|
import { StorageFile, StorageFolder } from "../../interfaces/edm";
|
||||||
|
|
||||||
|
const jwtDecode = createDecoder({ complete: true });
|
||||||
|
|
||||||
|
export type FileProps = Partial<
|
||||||
|
Pick<StorageFile, "title" | "description" | "author" | "keyword" | "category">
|
||||||
|
> & {
|
||||||
|
metadata?: { [key: string]: unknown };
|
||||||
|
};
|
||||||
|
|
||||||
|
const STORAGE_KEYCLOAK = process.env.EDM_KEYCLOAK!;
|
||||||
|
const STORAGE_KEYCLOAK_CLIENT = process.env.EDM_KEYCLOAK_CLIENT!;
|
||||||
|
const STORAGE_REALM = process.env.EDM_REALM!;
|
||||||
|
const STORAGE_URL = process.env.EDM_URL!;
|
||||||
|
const STORAGE_USER = process.env.EDM_ADMIN_USER!;
|
||||||
|
const STORAGE_PASSWORD = process.env.EDM_ADMIN_PASSWORD!;
|
||||||
|
|
||||||
|
let token: string | null = null;
|
||||||
|
let decoded: DecodedJwt | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if token is expired or will expire in 30 seconds
|
||||||
|
* @returns true if expire or can't get exp, false otherwise
|
||||||
|
*/
|
||||||
|
export function expireCheck(token: string, beforeExpire: number = 30) {
|
||||||
|
decoded = jwtDecode(token);
|
||||||
|
|
||||||
|
if (decoded && decoded.payload.exp) {
|
||||||
|
return Date.now() / 1000 >= decoded.payload.exp - beforeExpire;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get token from id service if needed
|
||||||
|
*/
|
||||||
|
export async function getToken() {
|
||||||
|
if (!token || expireCheck(token)) {
|
||||||
|
const body = new URLSearchParams();
|
||||||
|
|
||||||
|
body.append("scope", "openid");
|
||||||
|
body.append("grant_type", "password");
|
||||||
|
body.append("client_id", STORAGE_KEYCLOAK_CLIENT || "edm");
|
||||||
|
body.append("username", STORAGE_USER);
|
||||||
|
body.append("password", STORAGE_PASSWORD);
|
||||||
|
|
||||||
|
const res = await fetch(
|
||||||
|
`${STORAGE_KEYCLOAK}/realms/${STORAGE_REALM}/protocol/openid-connect/token`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
body: body,
|
||||||
|
},
|
||||||
|
).catch((e) => console.error(e));
|
||||||
|
|
||||||
|
if (!res) return;
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (data && data.access_token) {
|
||||||
|
token = data.access_token;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param path - Path that new folder will live
|
||||||
|
* @param name - Name of the folder to create
|
||||||
|
* @param recursive - Will create parent automatically
|
||||||
|
*/
|
||||||
|
export async function createFolder(path: string[], name: string, recursive: boolean = false) {
|
||||||
|
if (recursive && path.length > 0) {
|
||||||
|
await createFolder(path.slice(0, -1), path[path.length - 1], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`${STORAGE_URL}/storage/folder`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${await getToken()}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ path, name }),
|
||||||
|
}).catch((e) => console.error(e));
|
||||||
|
|
||||||
|
if (!res || !res.ok) {
|
||||||
|
return Boolean(console.error(res ? await res.json() : res));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param path - Path that new file will live
|
||||||
|
* @param file - Name of the file to create
|
||||||
|
*/
|
||||||
|
export async function createFile(path: string[], file: string, props?: FileProps) {
|
||||||
|
const res = await fetch(`${STORAGE_URL}/storage/file`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${await getToken()}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
...props,
|
||||||
|
path,
|
||||||
|
file,
|
||||||
|
hidden: path.some((v) => v.startsWith(".")),
|
||||||
|
}),
|
||||||
|
}).catch((e) => console.error(e));
|
||||||
|
|
||||||
|
if (!res || !res.ok) {
|
||||||
|
return Boolean(console.error(res ? await res.json() : res));
|
||||||
|
}
|
||||||
|
return (await res.json()) as StorageFile & { uploadUrl: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function list(
|
||||||
|
operation: "file" | "folder",
|
||||||
|
path: string[],
|
||||||
|
): Promise<false | (StorageFile & { uploadUrl: string })[]> {
|
||||||
|
const res = await fetch(`${STORAGE_URL}/storage/list`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${await getToken()}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ operation, path, hidden: true }),
|
||||||
|
}).catch((e) => console.error(e));
|
||||||
|
|
||||||
|
console.log(`${STORAGE_URL}/storage/list`);
|
||||||
|
|
||||||
|
if (!res || !res.ok) {
|
||||||
|
if (res && res.status === HttpStatus.NOT_FOUND) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return Boolean(console.error(res ? await res.json() : res)) as false;
|
||||||
|
}
|
||||||
|
return await res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listFolder(path: string[]) {
|
||||||
|
return (await list("folder", path)) as StorageFolder[] | boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listFile(path: string[]) {
|
||||||
|
return (await list("file", path)) as StorageFile[] | boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function downloadFile(
|
||||||
|
path: string[],
|
||||||
|
file: string,
|
||||||
|
): Promise<false | (StorageFile & { downloadUrl: string })> {
|
||||||
|
const res = await fetch(`${STORAGE_URL}/storage/file/download`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${await getToken()}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ path, file }),
|
||||||
|
}).catch((e) => console.error(e));
|
||||||
|
|
||||||
|
if (!res || !res.ok) {
|
||||||
|
if (res && res.status === HttpStatus.NOT_FOUND) {
|
||||||
|
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบไฟล์ในระบบ");
|
||||||
|
}
|
||||||
|
console.error(res ? await res.json() : res);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return await res.json();
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue