77 lines
2.4 KiB
TypeScript
77 lines
2.4 KiB
TypeScript
|
import { readFileSync } from "fs";
|
||
|
import TemplateService from "../service/templateService";
|
||
|
import { PermissionModule } from "../type/permissionTypes";
|
||
|
import TemplateUsageService from "../service/templateUsageService";
|
||
|
import Handlebars from "handlebars";
|
||
|
|
||
|
export abstract class TemplateHelper {
|
||
|
static getTemplateFromFile(template: string) {
|
||
|
return readFileSync(`${process.cwd()}/src/templates/${template}.template.html`, "utf8");
|
||
|
}
|
||
|
|
||
|
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 }> {
|
||
|
const moduleTemplates = await TemplateUsageService.getByScope(module);
|
||
|
|
||
|
let header = `<h1 style="font-size:10px; text-align:center; width:100%;">${title}</h1>`;
|
||
|
let footer = `
|
||
|
<div style="font-size:10px; text-align:center; width:100%; color:#888;">
|
||
|
Seite <span class="pageNumber"></span> von <span class="totalPages"></span>
|
||
|
</div>
|
||
|
`;
|
||
|
let body = "";
|
||
|
|
||
|
if (moduleTemplates.headerId) {
|
||
|
header = await this.getTemplateFromStore(moduleTemplates.headerId);
|
||
|
header = this.applyDataToTemplate(header, headerData);
|
||
|
}
|
||
|
|
||
|
if (moduleTemplates.footerId) {
|
||
|
footer = await this.getTemplateFromStore(moduleTemplates.footerId);
|
||
|
footer = this.applyDataToTemplate(footer, footerData);
|
||
|
}
|
||
|
|
||
|
if (moduleTemplates.bodyId) {
|
||
|
body = await this.getTemplateFromStore(moduleTemplates.bodyId);
|
||
|
} else {
|
||
|
body = this.getTemplateFromFile(module);
|
||
|
}
|
||
|
body = this.applyDataToTemplate(body, bodyData);
|
||
|
|
||
|
return {
|
||
|
header,
|
||
|
footer,
|
||
|
body,
|
||
|
};
|
||
|
}
|
||
|
}
|