Merge pull request 'Card generation feature/14-card_generation' (#24) from feature/14-card_generation into dev
Some checks failed
continuous-integration/drone/push Build is failing

Reviewed-on: #24
This commit is contained in:
Nicolai Ort 2021-02-12 16:59:53 +00:00
commit 703eaa0e9d
7 changed files with 564 additions and 357 deletions

View File

@ -34,6 +34,7 @@ The basic generation mechanism makes the templates and routes interchangeable (i
| EVENT_NAME | String | "Please set the event name" | The event's name - used to generate pdf text.
| CURRENCY_SYMBOL | String | "€" | The your currency's symbol - used to generate pdf text.
| SPONSORING_RECEIPT_MINIMUM_AMOUNT | String | "10" | The mimimum total donation amount a sponsor has to donate to be able to receive a donation receipt - used to generate pdf text.
| SPONOR_LOGOS | Array<String> | Empty png | The sponsor images you want to loop through. You can provide them via http url, local file or base64-encoded image.
## Templates
> The document server uses html templates to generate various pdf documents.

View File

@ -11,6 +11,7 @@ import puppeteer from "puppeteer";
import { awaitAsyncHandlebarHelpers, helpers } from './asyncHelpers';
import { config } from './config';
import { Runner } from './models/Runner';
import { RunnerCard } from './models/RunnerCard';
import { RunnerGroup } from './models/RunnerGroup';
/**
@ -86,6 +87,15 @@ export class PdfCreator {
return i18next.t(str, PdfCreator.interpolations).toString();
}
);
await Handlebars.registerHelper('--sponsor',
function (str) {
const index = (parseInt(str) % config.sponor_logos.length);
if (isNaN(index)) {
return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=="
}
return config.sponor_logos[index];
}
);
this.browser = await puppeteer.launch({ headless: true, args: minimal_args });
}
@ -117,6 +127,33 @@ export class PdfCreator {
return pdf
}
/**
* Generate runner card pdfs.
* @param cards The runner cars you want to generate the cards for.
* @param locale The locale used for the cards (default:en)
*/
public async generateRunnerCards(cards: RunnerCard[], locale: string = "en", codeformat: string = config.codeformat): Promise<Buffer> {
if (cards.length > 10) {
let pdf_promises = new Array<Promise<Buffer>>();
let i, j;
for (i = 0, j = cards.length; i < j; i += 10) {
let chunk = cards.slice(i, i + 10);
pdf_promises.push(this.generateRunnerCards(chunk, locale));
}
const pdfs = await Promise.all(pdf_promises);
return await this.mergePdfs(pdfs);
}
const cards_swapped = this.swapArrayPairs(cards);
await i18next.changeLanguage(locale);
const template_source = fs.readFileSync(`${this.templateDir}/runner_card.html`, 'utf8');
const template = Handlebars.compile(template_source);
let result = template({ cards, cards_swapped, eventname: "LfK! 2069", codeformat: "qrcode" })
result = await awaitAsyncHandlebarHelpers(result);
fs.writeFileSync("lelelelele.tmp", result);
const pdf = await this.renderPdf(result, { format: "A4", landscape: false });
return pdf
}
/**
* Converts all images in html to base64.
* Works with image files in the template directory or images from urls.
@ -203,4 +240,26 @@ export class PdfCreator {
runner.group = group;
return runner;
}
/**
* Swaps pairs (0/1, 2/3, ...) of elements in an array recursively.
* If the last element has no partner it inserts an empty element at the end and swaps the two
* This is needed to generate pdfs with front- and backside that get printet on one paper.
* @param array The array which's pairs shall get switched.
* @returns Array with swapped pairs,
*/
private swapArrayPairs(array): Array<any> {
if (array.length == 1) {
return [null, array[0]];
}
if (array.length == 0) {
return null;
}
const rest = this.swapArrayPairs(array.slice(2))
if (!rest) {
return [array[1], array[0]]
}
return [array[1], array[0]].concat(rest);
}
}

View File

@ -3,6 +3,7 @@ import bwipjs from "bwip-js";
export const asyncHelpers = new AsyncHelpers();
async function generateBarcode(str, options, emtpy, cb) {
if (str == null) { cb(null, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=="); return; }
let res = await generateBase64Barcode(options.toString(), str.toString());
cb(null, res);
}
@ -18,7 +19,7 @@ export async function generateBase64Barcode(type: string, content: string): Prom
height: 10,
width: 10,
includetext: true,
textxalign: 'center',
textxalign: 'center'
}
if (type != "qrcode") {
delete options.width;

View File

@ -8,7 +8,8 @@ export const config = {
eventname: process.env.EVENT_NAME || "Please set the event name",
currency_symbol: process.env.CURRENCY_SYMBOL || "€",
sponsoring_receipt_minimum_amount: process.env.SPONSORING_RECEIPT_MINIMUM_AMOUNT || "10",
codeformat: process.env.CODEFORMAT || "qrcode"
codeformat: process.env.CODEFORMAT || "qrcode",
sponor_logos: getSponsorLogos()
}
let errors = 0
if (typeof config.internal_port !== "number") {
@ -17,4 +18,13 @@ if (typeof config.internal_port !== "number") {
if (typeof config.development !== "boolean") {
errors++
}
function getSponsorLogos(): string[] {
try {
const logos = JSON.parse(process.env.SPONOR_LOGOS);
if (!Array.isArray(logos)) { throw new Error("Not an array.") }
return logos;
} catch (error) {
return ["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=="];
}
}
export let e = errors

View File

@ -1,6 +1,7 @@
import { Body, JsonController, Post, QueryParam, Res } from 'routing-controllers';
import { OpenAPI } from 'routing-controllers-openapi';
import { Runner } from '../models/Runner';
import { RunnerCard } from '../models/RunnerCard';
import { PdfCreator } from '../PdfCreator';
/**
@ -27,4 +28,19 @@ export class PdfController {
res.setHeader('content-type', 'application/pdf');
return contracts;
}
@Post('/cards')
@OpenAPI({ description: "Generate runner card pdfs from runner card objects.<br>You can choose your prefered locale by passing the 'locale' query-param." })
async generateCards(@Body({ validate: true, options: { limit: "500mb" } }) cards: RunnerCard | RunnerCard[], @Res() res: any, @QueryParam("locale") locale: string) {
if (!this.initialized) {
await this.pdf.init();
this.initialized = true;
}
if (!Array.isArray(cards)) {
cards = [cards];
}
const contracts = await this.pdf.generateRunnerCards(cards, locale);
res.setHeader('content-type', 'application/pdf');
return contracts;
}
}

View File

@ -0,0 +1,71 @@
<html>
<head>
<meta charset="utf8">
<title>Sponsoring contract</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
<style>
.sheet {
margin: 0;
overflow: hidden;
position: relative;
box-sizing: border-box;
page-break-after: always;
padding: 1.2cm 2cm 1.2cm 2cm
}
body.A4 .sheet {
width: 210mm;
height: 296mm
}
.runnercard {
border: 1px solid;
height: 5.5cm;
overflow: hidden;
}
</style>
</head>
<body class="A4 landscape">
<div class="sheet">
<div class="columns is-multiline">
{{#each cards}}
<div class="column is-half runnercard">
<p class="title is-5" style="text-align: center; padding-bottom: 0; margin-top: -0.75rem;">{{../eventname}}</p>
<p style="text-align: center; margin-top: -1.5rem; font-size: small;">lauf-fuer-kaya.de - am 01.01.2021</p>
<p style="font-size: small;">Mit unterstützung von:</p>
<div class="columns" style="height: 6rem; overflow: hidden;">
<div class="column is-two-thirds">
<!--SPONSOR LOGO HERE-->
<img style="vertical-align: revert; margin-top: auto; object-fit: cover; max-height: 2cm;"
src="{{--sponsor this.id}}" />
</div>
<div class="column is-one-third">
<!--BARCODE HERE-->
<img style="vertical-align: revert; margin-top: auto; object-fit: cover; max-height: 2cm;"
src="{{--bc this.id ../codeformat}}" />
</div>
</div>
<p>{{this.runner.lastname}}, {{this.runner.firstname}} {{this.runner.middlename}}</p>
<p>{{this.runner.group.name}}</p>
</div>
{{/each}}
</div>
</div>
<div class="sheet">
<div class="columns is-multiline">
{{#each cards_swapped}}
<div class="column is-half runnercard" style="justify-content: center; align-items: center; text-align: center;">
<!--SPONSOR LOGO FIRST-->
<div style="height: 2cm; padding: 0 0 2.25cm 0">
<img style="object-fit: cover; max-height: 2cm;" src="{{--sponsor this.id}}" />
</div>
<img style="object-fit: cover; max-height: 2.5cm; position: relative;" src="{{--bc this.id ../codeformat}}" />
</div>
{{/each}}
</div>
</div>
</body>
</html>

View File

@ -1,6 +1,7 @@
import axios from "axios"
import faker from "faker"
import { Runner } from '../models/Runner'
import { RunnerCard } from '../models/RunnerCard'
import { RunnerGroup } from '../models/RunnerGroup'
const baseurl = "http://localhost:4010"
@ -33,11 +34,45 @@ function generateRunners(amount: number): Runner[] {
return runners;
}
function generateCards(amount: number): RunnerCard[] {
let cards: RunnerCard[] = new Array<RunnerCard>();
let card = new RunnerCard();
for (let runner of generateRunners(amount)) {
card.id = runner.id;
card.code = idToEan13(card.id);
card.runner = runner;
cards.push(card);
}
return cards;
}
function idToEan13(id): string {
const multiply = [1, 3];
id = id.toString();
if (id.length > 12) {
throw new Error("id too long");
}
while (id.length < 12) { id = '0' + id; }
let total = 0;
id.split('').forEach((letter, index) => {
total += parseInt(letter, 10) * multiply[index % 2];
});
const checkSum = (Math.ceil(total / 10) * 10) - total;
return id + checkSum.toString();
}
async function postContracts(runners: Runner[]): Promise<Measurement> {
const res = await axios.post(`${baseurl}/contracts`, runners);
return new Measurement("contract", runners.length, parseInt(res.headers['request-duration']))
}
async function postCards(cards: RunnerCard[]): Promise<Measurement> {
const res = await axios.post(`${baseurl}/cards`, cards);
return new Measurement("card", cards.length, parseInt(res.headers['request-duration']))
}
async function testContracts(sizes): Promise<Measurement[]> {
let measurements = new Array<Measurement>();
console.log("#### Testing contracts ####");
@ -50,14 +85,28 @@ async function testContracts(sizes): Promise<Measurement[]> {
return measurements;
}
async function testCards(sizes): Promise<Measurement[]> {
let measurements = new Array<Measurement>();
console.log("#### Testing Cards ####");
for (let size of sizes) {
const m = await postCards(generateCards(size));
console.log(m.toString());
measurements.push(m);
}
return measurements;
}
async function main() {
const sizes = [0, 1, 10, 50, 100, 200, 500, 1000]
console.log("########### Speedtest ###########");
console.log(`Document server version (according to the api): ${(await axios.get("http://localhost:4010/version")).data.version}`);
console.log("####### Running tests #######");
const contractResults = await testContracts(sizes);
const cardResults = await testCards(sizes);
console.log("####### Results #######");
console.table(contractResults);
console.table(cardResults);
}
main();