template preparation

This commit is contained in:
Julian Krauser 2024-12-23 14:00:50 +01:00
parent 5f18e614be
commit 6cb8ca0a12
16 changed files with 414 additions and 21 deletions

View file

@ -0,0 +1,6 @@
export interface UpdateTemplateUsageCommand {
scope: string;
headerId: number | null;
bodyId: number | null;
footerId: number | null;
}

View file

@ -0,0 +1,28 @@
import { dataSource } from "../data-source";
import { templateUsage } from "../entity/templateUsage";
import InternalException from "../exceptions/internalException";
import { UpdateTemplateUsageCommand } from "./templateUsageCommand";
export default abstract class TemplateUsageCommandHandler {
/**
* @description update templateUsage
* @param UpdateTemplateUsageCommand
* @returns {Promise<void>}
*/
static async update(updateTemplateUsage: UpdateTemplateUsageCommand): Promise<void> {
return await dataSource
.createQueryBuilder()
.update(templateUsage)
.set({
headerId: updateTemplateUsage.headerId,
bodyId: updateTemplateUsage.bodyId,
footerId: updateTemplateUsage.footerId,
})
.where("scope = :scope", { scope: updateTemplateUsage.scope })
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException("Failed updating templateUsage", err);
});
}
}

View file

@ -237,7 +237,7 @@ export async function createProtocolPrintoutById(req: Request, res: Response): P
)}`; )}`;
await PdfExport.renderFile({ await PdfExport.renderFile({
template: "protocol.template.html", template: "protocol",
title, title,
filename, filename,
data: { data: {

View file

@ -0,0 +1,64 @@
import { Request, Response } from "express";
import TemplateUsageService from "../../service/templateUsageService";
import TemplateUsageFactory from "../../factory/admin/templateUsage";
import { UpdateTemplateUsageCommand } from "../../command/templateUsageCommand";
import TemplateUsageCommandHandler from "../../command/templateUsageCommandHandler";
import PermissionHelper from "../../helpers/permissionHelper";
import ForbiddenRequestException from "../../exceptions/forbiddenRequestException";
import { PermissionModule } from "../../type/permissionTypes";
/**
* @description get all templateUsages
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function getAllTemplateUsages(req: Request, res: Response): Promise<any> {
let templateUsages = await TemplateUsageService.getAll();
if (!req.isOwner) {
templateUsages = templateUsages.filter((tu) => {
return (
PermissionHelper.can(req.permissions, "update", "settings", tu.scope) ||
PermissionHelper.can(req.permissions, "update", "club", tu.scope)
);
});
}
res.json(TemplateUsageFactory.mapToBase(templateUsages));
}
/**
* @description update templateUsage
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function updateTemplateUsage(req: Request, res: Response): Promise<any> {
const scope = req.params.scope;
let allowedSettings = PermissionHelper.can(
req.permissions,
"update",
"settings",
req.params.scope as PermissionModule
);
let allowedClub = PermissionHelper.can(req.permissions, "update", "club", req.params.scope as PermissionModule);
if (!(req.isOwner || allowedSettings || allowedClub)) {
throw new ForbiddenRequestException(`missing permission for editing scope ${req.params.scope}`);
}
const headerId = req.body.headerId ?? null;
const bodyId = req.body.bodyId ?? null;
const footerId = req.body.footerId ?? null;
let updateTemplateUsage: UpdateTemplateUsageCommand = {
scope: scope,
headerId: headerId,
bodyId: bodyId,
footerId: footerId,
};
await TemplateUsageCommandHandler.update(updateTemplateUsage);
res.sendStatus(204);
}

View file

@ -53,6 +53,8 @@ import { membershipView } from "./views/membershipsView";
import { MemberDataViews1734520998539 } from "./migrations/1734520998539-memberDataViews"; import { MemberDataViews1734520998539 } from "./migrations/1734520998539-memberDataViews";
import { template } from "./entity/template"; import { template } from "./entity/template";
import { Template1734854680201 } from "./migrations/1734854680201-template"; import { Template1734854680201 } from "./migrations/1734854680201-template";
import { templateUsage } from "./entity/templateUsage";
import { TemplateUsage1734949173739 } from "./migrations/1734949173739-templateUsage";
const dataSource = new DataSource({ const dataSource = new DataSource({
type: DB_TYPE as any, type: DB_TYPE as any,
@ -93,6 +95,7 @@ const dataSource = new DataSource({
calendarType, calendarType,
query, query,
template, template,
templateUsage,
memberView, memberView,
memberExecutivePositionsView, memberExecutivePositionsView,
memberQualificationsView, memberQualificationsView,
@ -116,6 +119,7 @@ const dataSource = new DataSource({
QueryStore1734187754677, QueryStore1734187754677,
MemberDataViews1734520998539, MemberDataViews1734520998539,
Template1734854680201, Template1734854680201,
TemplateUsage1734949173739,
], ],
migrationsRun: true, migrationsRun: true,
migrationsTransactionMode: "each", migrationsTransactionMode: "each",

View file

@ -40,7 +40,7 @@ export class member {
birthdate: Date; birthdate: Date;
@OneToMany(() => communication, (communications) => communications.member) @OneToMany(() => communication, (communications) => communications.member)
communications: communication; communications: communication[];
@OneToOne(() => communication, { @OneToOne(() => communication, {
nullable: true, nullable: true,

View file

@ -0,0 +1,39 @@
import { Column, Entity, ManyToOne, PrimaryColumn } from "typeorm";
import { template } from "./template";
import { PermissionModule } from "../type/permissionTypes";
@Entity()
export class templateUsage {
@PrimaryColumn({ type: "varchar", length: 255 })
scope: PermissionModule;
@Column({ type: "number", nullable: true })
headerId: number | null;
@Column({ type: "number", nullable: true })
bodyId: number | null;
@Column({ type: "number", nullable: true })
footerId: number | null;
@ManyToOne(() => template, {
nullable: true,
onDelete: "RESTRICT",
onUpdate: "RESTRICT",
})
header: template | null;
@ManyToOne(() => template, {
nullable: true,
onDelete: "RESTRICT",
onUpdate: "RESTRICT",
})
body: template | null;
@ManyToOne(() => template, {
nullable: true,
onDelete: "RESTRICT",
onUpdate: "RESTRICT",
})
footer: template | null;
}

View file

@ -0,0 +1,27 @@
import { templateUsage } from "../../entity/templateUsage";
import { TemplateUsageViewModel } from "../../viewmodel/admin/templateUsage.models";
export default abstract class TemplateUsageFactory {
/**
* @description map record to templateUsage
* @param {templateUsage} record
* @returns {TemplateUsageViewModel}
*/
public static mapToSingle(record: templateUsage): TemplateUsageViewModel {
return {
scope: record.scope,
header: record.header ? { id: record.header.id, template: record.header.template } : null,
body: record.body ? { id: record.body.id, template: record.body.template } : null,
footer: record.footer ? { id: record.footer.id, template: record.footer.template } : null,
};
}
/**
* @description map records to templateUsage
* @param {Array<templateUsage>} records
* @returns {Array<TemplateUsageViewModel>}
*/
public static mapToBase(records: Array<templateUsage>): Array<TemplateUsageViewModel> {
return records.map((r) => this.mapToSingle(r));
}
}

View file

@ -1,36 +1,34 @@
import { readFileSync } from "fs";
import Handlebars from "handlebars";
import puppeteer from "puppeteer"; import puppeteer from "puppeteer";
import { TemplateHelper } from "./templateHelper";
import { PermissionModule } from "../type/permissionTypes";
export abstract class PdfExport { export abstract class PdfExport {
static getTemplate(template: string) {
return readFileSync(process.cwd() + "/src/templates/" + template, "utf8");
}
static async renderFile({ static async renderFile({
template, template,
title = "pdf-export Mitgliederverwaltung", title = "pdf-export Mitgliederverwaltung",
filename, filename,
data, data,
}: { }: {
template: string; template: PermissionModule;
title: string; title: string;
filename: string; filename: string;
data: any; data: any;
}) { }) {
const templateHtml = this.getTemplate(template); const { header, footer, body } = await TemplateHelper.renderFileForModule({
const templateCompiled = Handlebars.compile(templateHtml); module: template,
const html = templateCompiled(data); bodyData: data,
title: title,
});
const browser = await puppeteer.launch({ const browser = await puppeteer.launch({
headless: true, headless: true,
args: ["--no-sandbox", "--disable-gpu", "--disable-setuid-sandbox"], args: ["--no-sandbox", "--disable-gpu", "--disable-setuid-sandbox"],
}); });
const page = await browser.newPage(); const page = await browser.newPage();
await page.setContent(html, { waitUntil: "domcontentloaded" }); await page.setContent(body, { waitUntil: "domcontentloaded" });
await page.pdf({ await page.pdf({
path: process.cwd() + `/export/${filename}.pdf`, // Name der PDF-Datei path: process.cwd() + `/export/${filename}.pdf`,
format: "A4", format: "A4",
printBackground: false, printBackground: false,
margin: { margin: {
@ -40,12 +38,8 @@ export abstract class PdfExport {
right: "10mm", right: "10mm",
}, },
displayHeaderFooter: true, displayHeaderFooter: true,
headerTemplate: `<h1 style="font-size:10px; text-align:center; width:100%;">${title}</h1>`, headerTemplate: header,
footerTemplate: ` footerTemplate: footer,
<div style="font-size:10px; text-align:center; width:100%; color:#888;">
Seite <span class="pageNumber"></span> von <span class="totalPages"></span>
</div>
`,
}); });
await browser.close(); await browser.close();

View file

@ -0,0 +1,76 @@
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,
};
}
}

View file

@ -0,0 +1,75 @@
import { MigrationInterface, QueryRunner, Table, TableForeignKey } from "typeorm";
import { DB_TYPE } from "../env.defaults";
import { templateUsage } from "../entity/templateUsage";
export class TemplateUsage1734949173739 implements MigrationInterface {
name = "TemplateUsage1734949173739";
public async up(queryRunner: QueryRunner): Promise<void> {
const variableType_int = DB_TYPE == "mysql" ? "int" : "integer";
await queryRunner.createTable(
new Table({
name: "template_usage",
columns: [
{ name: "scope", type: "varchar", length: "255", isPrimary: true },
{ name: "headerId", type: variableType_int, isNullable: true },
{ name: "bodyId", type: variableType_int, isNullable: true },
{ name: "footerId", type: variableType_int, isNullable: true },
],
}),
true
);
await queryRunner.manager
.createQueryBuilder()
.insert()
.into(templateUsage)
.values({ scope: "protocol" })
.orIgnore()
.execute();
await queryRunner.createForeignKey(
"template_usage",
new TableForeignKey({
columnNames: ["headerId"],
referencedColumnNames: ["id"],
referencedTableName: "template",
onDelete: "RESTRICT",
onUpdate: "RESTRICT",
})
);
await queryRunner.createForeignKey(
"template_usage",
new TableForeignKey({
columnNames: ["bodyId"],
referencedColumnNames: ["id"],
referencedTableName: "template",
onDelete: "RESTRICT",
onUpdate: "RESTRICT",
})
);
await queryRunner.createForeignKey(
"template_usage",
new TableForeignKey({
columnNames: ["footerId"],
referencedColumnNames: ["id"],
referencedTableName: "template",
onDelete: "RESTRICT",
onUpdate: "RESTRICT",
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
const template_usage = await queryRunner.getTable("template_usage");
let foreignKey = template_usage.foreignKeys.find((fk) => fk.columnNames.indexOf("headerId") !== -1);
await queryRunner.dropForeignKey("template_usage", foreignKey);
foreignKey = template_usage.foreignKeys.find((fk) => fk.columnNames.indexOf("bodyId") !== -1);
await queryRunner.dropForeignKey("template_usage", foreignKey);
foreignKey = template_usage.foreignKeys.find((fk) => fk.columnNames.indexOf("footerId") !== -1);
await queryRunner.dropForeignKey("template_usage", foreignKey);
await queryRunner.dropTable("template_usage");
}
}

View file

@ -9,6 +9,7 @@ import qualification from "./qualification";
import calendarType from "./calendarType"; import calendarType from "./calendarType";
import queryStore from "./queryStore"; import queryStore from "./queryStore";
import template from "./template"; import template from "./template";
import templateUsage from "./templateUsage";
import member from "./member"; import member from "./member";
import protocol from "./protocol"; import protocol from "./protocol";
@ -41,6 +42,7 @@ router.use("/qualification", PermissionHelper.passCheckMiddleware("read", "setti
router.use("/calendartype", PermissionHelper.passCheckMiddleware("read", "settings", "calendar_type"), calendarType); router.use("/calendartype", PermissionHelper.passCheckMiddleware("read", "settings", "calendar_type"), calendarType);
router.use("/querystore", PermissionHelper.passCheckMiddleware("read", "settings", "query_store"), queryStore); router.use("/querystore", PermissionHelper.passCheckMiddleware("read", "settings", "query_store"), queryStore);
router.use("/template", PermissionHelper.passCheckMiddleware("read", "settings", "template"), template); router.use("/template", PermissionHelper.passCheckMiddleware("read", "settings", "template"), template);
router.use("/templateusage", PermissionHelper.passCheckMiddleware("read", "settings", "template_usage"), templateUsage);
router.use("/member", PermissionHelper.passCheckMiddleware("read", "club", "member"), member); router.use("/member", PermissionHelper.passCheckMiddleware("read", "club", "member"), member);
router.use("/protocol", PermissionHelper.passCheckMiddleware("read", "club", "protocol"), protocol); router.use("/protocol", PermissionHelper.passCheckMiddleware("read", "club", "protocol"), protocol);

View file

@ -0,0 +1,21 @@
import express, { Request, Response } from "express";
import PermissionHelper from "../../helpers/permissionHelper";
import { getAllTemplateUsages, updateTemplateUsage } from "../../controller/admin/templateUsageController";
import { PermissionModule } from "../../type/permissionTypes";
import ForbiddenRequestException from "../../exceptions/forbiddenRequestException";
var router = express.Router({ mergeParams: true });
router.get("/", async (req: Request, res: Response) => {
await getAllTemplateUsages(req, res);
});
router.patch(
"/:scope",
PermissionHelper.passCheckMiddleware("update", "settings", "template_usage"),
async (req: Request, res: Response) => {
await updateTemplateUsage(req, res);
}
);
export default router;

View file

@ -0,0 +1,46 @@
import { dataSource } from "../data-source";
import { templateUsage } from "../entity/templateUsage";
import InternalException from "../exceptions/internalException";
export default abstract class TemplateUsageService {
/**
* @description get all templateUsages
* @returns {Promise<Array<templateUsage>>}
*/
static async getAll(): Promise<Array<templateUsage>> {
return await dataSource
.getRepository(templateUsage)
.createQueryBuilder("templateUsage")
.leftJoinAndSelect("templateUsage.header", "headerTemplate")
.leftJoinAndSelect("templateUsage.body", "bodyTemplate")
.leftJoinAndSelect("templateUsage.footer", "footerTemplate")
.getMany()
.then((res) => {
return res;
})
.catch((err) => {
throw new InternalException("templates not found", err);
});
}
/**
* @description get template by scope
* @returns {Promise<templateUsage>}
*/
static async getByScope(scope: string): Promise<templateUsage | null> {
return await dataSource
.getRepository(templateUsage)
.createQueryBuilder("templateUsage")
.leftJoinAndSelect("templateUsage.header", "headerTemplate")
.leftJoinAndSelect("templateUsage.body", "bodyTemplate")
.leftJoinAndSelect("templateUsage.footer", "footerTemplate")
.where("templateUsage.scope = :scope", { scope: scope })
.getOneOrFail()
.then((res) => {
return res;
})
.catch((err): null => {
return null;
});
}
}

View file

@ -15,7 +15,8 @@ export type PermissionModule =
| "role" | "role"
| "query" | "query"
| "query_store" | "query_store"
| "template"; | "template"
| "template_usage";
export type PermissionType = "read" | "create" | "update" | "delete"; export type PermissionType = "read" | "create" | "update" | "delete";
@ -55,6 +56,7 @@ export const permissionModules: Array<PermissionModule> = [
"query", "query",
"query_store", "query_store",
"template", "template",
"template_usage",
]; ];
export const permissionTypes: Array<PermissionType> = ["read", "create", "update", "delete"]; export const permissionTypes: Array<PermissionType> = ["read", "create", "update", "delete"];
export const sectionsAndModules: SectionsAndModulesObject = { export const sectionsAndModules: SectionsAndModulesObject = {
@ -68,6 +70,7 @@ export const sectionsAndModules: SectionsAndModulesObject = {
"calendar_type", "calendar_type",
"query_store", "query_store",
"template", "template",
"template_usage",
], ],
user: ["user", "role"], user: ["user", "role"],
}; };

View file

@ -0,0 +1,8 @@
import { PermissionModule } from "../../type/permissionTypes";
export interface TemplateUsageViewModel {
scope: PermissionModule;
header: { id: number; template: string } | null;
body: { id: number; template: string } | null;
footer: { id: number; template: string } | null;
}