ff-admin-server/src/helpers/templateHelper.ts

74 lines
2.4 KiB
TypeScript

import TemplateService from "../service/templateService";
import { PermissionModule } from "../type/permissionTypes";
import TemplateUsageService from "../service/templateUsageService";
import Handlebars from "handlebars";
import { FileSystemHelper } from "./fileSystemHelper";
export abstract class TemplateHelper {
static getTemplateFromFile(template: string) {
return FileSystemHelper.readTemplateFile(`/src/templates/${template}.template.html`);
}
static async getTemplateFromStore(templateId: number): Promise<string> {
return (await TemplateService.getById(templateId)).html;
}
static applyDataToTemplate(template: string, data: any): string {
const normalizedTemplate = this.normalizeTemplate(template);
const templateCompiled = Handlebars.compile(normalizedTemplate);
return templateCompiled(data);
}
static normalizeTemplate(template: string): string {
template = template.replace(/<listend>.*?<\/listend>/g, "{{/each}}");
template = template.replace(/<liststart\b[^>]*>(WDH Start: )?/g, "{{#each ");
template = template.replace(/<\/liststart>/g, "}}");
return template;
}
static async renderFileForModule({
module,
title = "pdf-export Mitgliederverwaltung",
headerData = {},
bodyData = {},
footerData = {},
}: {
module: PermissionModule;
title?: string;
headerData?: any;
bodyData?: any;
footerData?: any;
}): Promise<{ header: string; body: string; footer: string; margins?: { top: string; bottom: string } }> {
const moduleTemplates = await TemplateUsageService.getByScope(module);
let header = `<h1 style="font-size:10px; text-align:center; width:100%;">${title}</h1>`;
let footer = "";
let body = "";
if (moduleTemplates.headerId) {
header = await this.getTemplateFromStore(moduleTemplates.headerId);
header = this.applyDataToTemplate(header, { title, ...headerData });
}
if (moduleTemplates.footerId) {
footer = await this.getTemplateFromStore(moduleTemplates.footerId);
} else {
footer = this.getTemplateFromFile(module + ".footer");
}
footer = this.applyDataToTemplate(footer, footerData);
if (moduleTemplates.bodyId) {
body = await this.getTemplateFromStore(moduleTemplates.bodyId);
} else {
body = this.getTemplateFromFile(module + ".body");
}
body = this.applyDataToTemplate(body, bodyData);
return {
header,
footer,
body,
};
}
}