Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7930c177ee | ||
|
|
c73109b8ca | ||
|
|
2c2282e05a | ||
|
|
3bef26b332 | ||
|
|
94751c12ff | ||
|
|
a6eb41f996 | ||
|
|
a39ae8cffd | ||
|
|
c7fb778a8d | ||
|
|
ee8e60bb0d | ||
|
|
812f4784fd |
@@ -16,8 +16,10 @@
|
|||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"basic-ftp": "^5.0.5",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^16.4.5",
|
"dotenv": "^16.4.5",
|
||||||
|
"exceljs": "^4.4.0",
|
||||||
"express": "^4.19.0",
|
"express": "^4.19.0",
|
||||||
"multer": "^2.0.2",
|
"multer": "^2.0.2",
|
||||||
"pdf-lib": "^1.17.1",
|
"pdf-lib": "^1.17.1",
|
||||||
|
|||||||
148
src/api/controllers/batch-controller.js
Normal file
148
src/api/controllers/batch-controller.js
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
/**
|
||||||
|
* Batch-Bündelung (alternativer Übermittlungsweg)
|
||||||
|
* ---------------------------------------------------------------------------
|
||||||
|
* Fasst offene batch_submissions JE ZUGANG (api_client) zusammen:
|
||||||
|
* • xlsx im festen Schema (Firma, Vorname, Nachname, Zeile1-3, PLZ, Stadt, Land)
|
||||||
|
* • Sammel-Druck-PDF: alle mitgelieferten Druck-PDFs 1:1 aneinandergehängt
|
||||||
|
* und lädt beide per FTP(S) in die Wurzel des Ziel-Servers. Danach werden die
|
||||||
|
* Datensätze als „bundled" markiert. Text-only-Datensätze (ohne PDF) bleiben
|
||||||
|
* offen (für die manuelle Schreibvorlage/Plotter) und wandern NICHT ins Bündel.
|
||||||
|
*
|
||||||
|
* Ausgelöst durch: Cron (03:00 Folgetag; Sa+So gemeinsam) und den Directus-Knopf
|
||||||
|
* (POST /api/batch/build mit client_id = sofortige Bündelung des aktuellen Stands).
|
||||||
|
*/
|
||||||
|
const { Readable } = require('stream');
|
||||||
|
const { PDFDocument } = require('pdf-lib');
|
||||||
|
const ExcelJS = require('exceljs');
|
||||||
|
const ftp = require('basic-ftp');
|
||||||
|
const config = require('../../config');
|
||||||
|
const { fetchBatchPending, markBatchBundled, fetchAssetBuffer } = require('../../services/directus-service');
|
||||||
|
|
||||||
|
const XLSX_HEADER = ['Firma', 'Vorname', 'Nachname', 'Zeile1', 'Zeile2', 'Zeile3', 'PLZ', 'Stadt', 'Land'];
|
||||||
|
|
||||||
|
/** Datum/Uhrzeit in Europe/Berlin (für Cron-Fenster + Dateinamen, TZ-unabhängig). */
|
||||||
|
function berlinParts(d = new Date()) {
|
||||||
|
const fmt = new Intl.DateTimeFormat('en-CA', {
|
||||||
|
timeZone: 'Europe/Berlin', year: 'numeric', month: '2-digit', day: '2-digit',
|
||||||
|
hour: '2-digit', minute: '2-digit', weekday: 'short', hour12: false,
|
||||||
|
});
|
||||||
|
const p = Object.fromEntries(fmt.formatToParts(d).map((x) => [x.type, x.value]));
|
||||||
|
return { date: `${p.year}-${p.month}-${p.day}`, hour: parseInt(p.hour, 10), minute: parseInt(p.minute, 10), weekday: p.weekday };
|
||||||
|
}
|
||||||
|
/** Kalendertag (Berlin) minus N Tage → YYYY-MM-DD. Mittag-UTC vermeidet DST-Sprünge. */
|
||||||
|
function datumMinus(dateStr, tage) {
|
||||||
|
const [y, m, d] = String(dateStr).split('-').map(Number);
|
||||||
|
return new Date(Date.UTC(y, m - 1, d - tage, 12, 0, 0)).toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildXlsx(subs) {
|
||||||
|
const wb = new ExcelJS.Workbook();
|
||||||
|
const ws = wb.addWorksheet('Empfaenger');
|
||||||
|
ws.addRow(XLSX_HEADER);
|
||||||
|
ws.getRow(1).font = { bold: true };
|
||||||
|
for (const s of subs) {
|
||||||
|
ws.addRow([s.firma || '', s.vorname || '', s.nachname || '', s.zeile1 || '', s.zeile2 || '',
|
||||||
|
s.zeile3 || '', s.plz || '', s.stadt || '', s.land || '']);
|
||||||
|
}
|
||||||
|
ws.columns.forEach((c) => { c.width = 18; });
|
||||||
|
return wb.xlsx.writeBuffer().then((ab) => Buffer.from(ab));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildMergedPdf(subs) {
|
||||||
|
const merged = await PDFDocument.create();
|
||||||
|
let seiten = 0;
|
||||||
|
for (const s of subs) {
|
||||||
|
if (!s.pdf_file) continue;
|
||||||
|
try {
|
||||||
|
const buf = await fetchAssetBuffer(s.pdf_file);
|
||||||
|
const src = await PDFDocument.load(buf, { ignoreEncryption: true });
|
||||||
|
const pages = await merged.copyPages(src, src.getPageIndices());
|
||||||
|
pages.forEach((p) => merged.addPage(p));
|
||||||
|
seiten += pages.length;
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[batch] PDF ${s.pdf_file} (Datensatz ${s.id}) übersprungen: ${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { bytes: Buffer.from(await merged.save()), seiten };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ftpUpload(dateien) {
|
||||||
|
const { host, port, user, password, secure, rejectUnauthorized } = config.ftp;
|
||||||
|
if (!host || !user) throw new Error('FTP nicht konfiguriert (SKRIFT_FTP_HOST/USER fehlen).');
|
||||||
|
// Diagnose ohne Passwort-Leak: bei „530 Login incorrect" trotz korrekter Daten
|
||||||
|
// ist meist die Passwort-Laenge im .env falsch (Quotes/CRLF/Leerzeichen).
|
||||||
|
console.log(`[batch] FTP-Login: host=${host}:${port} user="${user}" pw_len=${(password || '').length} secure=${secure}`);
|
||||||
|
const client = new ftp.Client(30000);
|
||||||
|
// client.ftp.verbose = true;
|
||||||
|
try {
|
||||||
|
await client.access({ host, port, user, password, secure, secureOptions: { rejectUnauthorized } });
|
||||||
|
for (const f of dateien) await client.uploadFrom(Readable.from(f.buffer), f.name);
|
||||||
|
} finally {
|
||||||
|
client.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bündelt EINEN Zugang: xlsx + Sammel-PDF bauen, hochladen, Datensätze markieren. */
|
||||||
|
async function buendleZugang(clientId, subs, label, zeitSuffix) {
|
||||||
|
const withPdf = subs.filter((s) => s.pdf_file);
|
||||||
|
if (!withPdf.length) return { client_id: clientId, count: 0, skipped: 'keine Druck-PDFs' };
|
||||||
|
const basis = `${clientId}_${label}${zeitSuffix ? `_${zeitSuffix}` : ''}`;
|
||||||
|
const xlsx = await buildXlsx(withPdf);
|
||||||
|
const { bytes: pdf, seiten } = await buildMergedPdf(withPdf);
|
||||||
|
await ftpUpload([
|
||||||
|
{ name: `${basis}.xlsx`, buffer: xlsx },
|
||||||
|
{ name: `${basis}.pdf`, buffer: pdf },
|
||||||
|
]);
|
||||||
|
await markBatchBundled(withPdf.map((s) => s.id), basis);
|
||||||
|
console.log(`[batch] Zugang ${clientId}: ${withPdf.length} Datensätze / ${seiten} PDF-Seiten → ${basis}.{xlsx,pdf} hochgeladen.`);
|
||||||
|
return { client_id: clientId, count: withPdf.length, pages: seiten, file: basis };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bündelt alle offenen Datensätze (optional nur ein Zugang), gruppiert je Zugang. */
|
||||||
|
async function buendleAlle({ clientId = null, ids = null, label, zeitSuffix = '' }) {
|
||||||
|
const alle = await fetchBatchPending(clientId, ids);
|
||||||
|
const proZugang = new Map();
|
||||||
|
for (const s of alle) {
|
||||||
|
const k = String(s.api_client);
|
||||||
|
if (!proZugang.has(k)) proZugang.set(k, []);
|
||||||
|
proZugang.get(k).push(s);
|
||||||
|
}
|
||||||
|
const ergebnis = [];
|
||||||
|
for (const [k, subs] of proZugang) {
|
||||||
|
try { ergebnis.push(await buendleZugang(k, subs, label, zeitSuffix)); }
|
||||||
|
catch (e) { console.error(`[batch] Zugang ${k} fehlgeschlagen: ${e.message}`); ergebnis.push({ client_id: k, error: e.message }); }
|
||||||
|
}
|
||||||
|
return ergebnis;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** HTTP: POST /api/batch/build { client_id?, label?, time_suffix? }
|
||||||
|
* Ohne client_id → alle Zugänge (wie der Cron). label default = heute (Berlin). */
|
||||||
|
async function buildBundles(req, res) {
|
||||||
|
try {
|
||||||
|
const clientId = (req.body && req.body.client_id != null && String(req.body.client_id).trim()) ? String(req.body.client_id).trim() : null;
|
||||||
|
const ids = (req.body && Array.isArray(req.body.ids) && req.body.ids.length) ? req.body.ids : null;
|
||||||
|
const label = (req.body && req.body.label) ? String(req.body.label) : berlinParts().date;
|
||||||
|
// Manuelle Bündelung mit Uhrzeit-Suffix, damit sie den Cron-Tageslauf (nur Datum) nicht überschreibt.
|
||||||
|
const zeitSuffix = (req.body && req.body.time_suffix !== undefined)
|
||||||
|
? String(req.body.time_suffix)
|
||||||
|
: `${String(berlinParts().hour).padStart(2, '0')}${String(berlinParts().minute).padStart(2, '0')}`;
|
||||||
|
const ergebnis = await buendleAlle({ clientId, ids, label, zeitSuffix });
|
||||||
|
return res.json({ ok: true, bundles: ergebnis });
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[batch] build fehlgeschlagen:', err);
|
||||||
|
return res.status(500).json({ error: 'Batch-Bündelung fehlgeschlagen', message: err.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cron-Lauf: alle Zugänge, Label = Vortag (Berlin). Sa+So gemeinsam am Montag,
|
||||||
|
* Sonntag 03:00 wird übersprungen (Samstag wartet auf den Montagslauf). */
|
||||||
|
async function runScheduledBatch() {
|
||||||
|
const { date, weekday } = berlinParts();
|
||||||
|
if (weekday === 'Sun') { console.log('[batch-cron] Sonntag – Samstag wird am Montag mit Sonntag gebündelt, kein Lauf.'); return; }
|
||||||
|
const label = datumMinus(date, 1); // Vortag (bei Montag = Sonntag; deckt Sa+So ab)
|
||||||
|
console.log(`[batch-cron] Start Tageslauf, Label ${label} (${weekday}).`);
|
||||||
|
const ergebnis = await buendleAlle({ label, zeitSuffix: '' });
|
||||||
|
console.log(`[batch-cron] fertig: ${ergebnis.length} Zugang/Zugänge verarbeitet.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { buildBundles, runScheduledBatch, berlinParts };
|
||||||
@@ -90,7 +90,8 @@ function buildDocuments(order, entries) {
|
|||||||
const briefText = (entry.text && String(entry.text).trim()) ? entry.text : (order.text_template || '');
|
const briefText = (entry.text && String(entry.text).trim()) ? entry.text : (order.text_template || '');
|
||||||
|
|
||||||
// Postkarte: EIN Dokument mit Text + Absender + Empfänger (über Marker getrennt).
|
// Postkarte: EIN Dokument mit Text + Absender + Empfänger (über Marker getrennt).
|
||||||
if (istPostkarte) {
|
// Ohne Brieftext KEINE Karte erzeugen – dann wird (falls gewünscht) nur das Kuvert erzeugt.
|
||||||
|
if (istPostkarte && String(briefText).trim()) {
|
||||||
const recip = addressText(entry);
|
const recip = addressText(entry);
|
||||||
const sender = order.envelope_sender ? String(order.envelope_sender).trim() : '';
|
const sender = order.envelope_sender ? String(order.envelope_sender).trim() : '';
|
||||||
let combined = String(briefText || '');
|
let combined = String(briefText || '');
|
||||||
@@ -98,7 +99,7 @@ function buildDocuments(order, entries) {
|
|||||||
if (recip) combined += `[[pk_adr]]${recip}`;
|
if (recip) combined += `[[pk_adr]]${recip}`;
|
||||||
documents.push({
|
documents.push({
|
||||||
index: nr, type: 'postcard', text: combined, format: letterFormat, font,
|
index: nr, type: 'postcard', text: combined, format: letterFormat, font,
|
||||||
placeholders, fontScale: fontScaleLetter, realisticHandwriting: realistisch,
|
placeholders, fontScale: fontScaleLetter, fontScaleEnv, realisticHandwriting: realistisch,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -336,7 +336,7 @@ async function runGeneration({ orderNumber, letters, metadata }) {
|
|||||||
} else if (isPostcard) {
|
} else if (isPostcard) {
|
||||||
svgResult = generatePostcardSVG(
|
svgResult = generatePostcardSVG(
|
||||||
scriptalizedText, letter.format,
|
scriptalizedText, letter.format,
|
||||||
{ font: letter.font, realisticHandwriting: letter.realisticHandwriting ?? false, fontScale: letter.fontScale, senderScale: metadata.envelopeSenderScale || 1 }
|
{ font: letter.font, realisticHandwriting: letter.realisticHandwriting ?? false, fontScale: letter.fontScale, senderScale: metadata.envelopeSenderScale || 1, recipientScale: letter.fontScaleEnv || 1 }
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
svgResult = generateLetterSVG(
|
svgResult = generateLetterSVG(
|
||||||
|
|||||||
@@ -181,7 +181,7 @@ async function generateBatch(req, res, next) {
|
|||||||
} else if (letter.type === "postcard") {
|
} else if (letter.type === "postcard") {
|
||||||
const svgResult = generatePostcardSVG(scriptalizedText, letter.format, {
|
const svgResult = generatePostcardSVG(scriptalizedText, letter.format, {
|
||||||
font: letter.font, realisticHandwriting: letter.realisticHandwriting ?? false,
|
font: letter.font, realisticHandwriting: letter.realisticHandwriting ?? false,
|
||||||
fontScale: letter.fontScale, senderScale: letter.senderScale || 1,
|
fontScale: letter.fontScale, senderScale: letter.senderScale || 1, recipientScale: letter.recipientScale || 1,
|
||||||
});
|
});
|
||||||
if (svgResult.overflow) hasOverflow = true;
|
if (svgResult.overflow) hasOverflow = true;
|
||||||
const filename = `letter_${pad}.svg`;
|
const filename = `letter_${pad}.svg`;
|
||||||
|
|||||||
14
src/api/routes/batch-routes.js
Normal file
14
src/api/routes/batch-routes.js
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const router = express.Router();
|
||||||
|
const { authenticateApiToken } = require('../middleware/auth');
|
||||||
|
const batchController = require('../controllers/batch-controller');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/batch/build
|
||||||
|
* Bündelt offene batch_submissions (xlsx + Sammel-Druck-PDF) und lädt sie per FTP
|
||||||
|
* hoch. Body: { client_id?, label?, time_suffix? }. Ohne client_id → alle Zugänge.
|
||||||
|
* Wird vom Directus-Knopf (ein Zugang, sofort) und intern vom Cron genutzt.
|
||||||
|
*/
|
||||||
|
router.post('/build', authenticateApiToken, batchController.buildBundles);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -55,5 +55,29 @@ module.exports = {
|
|||||||
clientSecret: process.env.PAYPAL_CLIENT_SECRET || '',
|
clientSecret: process.env.PAYPAL_CLIENT_SECRET || '',
|
||||||
// 'sandbox' oder 'live'
|
// 'sandbox' oder 'live'
|
||||||
environment: process.env.PAYPAL_ENVIRONMENT || 'sandbox'
|
environment: process.env.PAYPAL_ENVIRONMENT || 'sandbox'
|
||||||
}
|
},
|
||||||
|
|
||||||
|
// Alternativer Übermittlungsweg (batch_submissions): Ziel-FTP für die täglichen
|
||||||
|
// Bündel (xlsx + Sammel-Druck-PDF). Passwort NUR über ENV.
|
||||||
|
// envClean entfernt versehentliche umschließende Anführungszeichen und CR/LF
|
||||||
|
// (häufige .env-Fallen unter Windows/docker env_file), die sonst zu „530
|
||||||
|
// Login incorrect" führen, obwohl die Daten korrekt sind.
|
||||||
|
ftp: (() => {
|
||||||
|
const envClean = (v) => String(v || '').replace(/[\r\n]+/g, '').replace(/^(['"])([\s\S]*)\1$/, '$2');
|
||||||
|
// Passwoerter mit Sonderzeichen ($ # @ …) werden in .env-Dateien oft
|
||||||
|
// verstuemmelt ($ = Variable, # = Kommentar). Deshalb bevorzugt base64:
|
||||||
|
// SKRIFT_FTP_PASSWORD_B64 wird dekodiert und ist damit env-sicher.
|
||||||
|
const pwB64 = envClean(process.env.SKRIFT_FTP_PASSWORD_B64);
|
||||||
|
const password = pwB64 ? Buffer.from(pwB64, 'base64').toString('utf8') : envClean(process.env.SKRIFT_FTP_PASSWORD);
|
||||||
|
return {
|
||||||
|
host: envClean(process.env.SKRIFT_FTP_HOST),
|
||||||
|
port: parseInt(process.env.SKRIFT_FTP_PORT, 10) || 21,
|
||||||
|
user: envClean(process.env.SKRIFT_FTP_USER),
|
||||||
|
password,
|
||||||
|
// explizites FTP über TLS (wie im FTP-Client eingestellt). 'false' schaltet ab.
|
||||||
|
secure: String(process.env.SKRIFT_FTP_SECURE || 'true').toLowerCase() !== 'false',
|
||||||
|
// Selbstsigniertes Zertifikat zulassen (viele FTP-Server) – auf 'false' setzen für strikte Prüfung.
|
||||||
|
rejectUnauthorized: String(process.env.SKRIFT_FTP_REJECT_UNAUTHORIZED || 'false').toLowerCase() === 'true',
|
||||||
|
};
|
||||||
|
})(),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,23 +6,32 @@ const FONT_SIZE_PX = 26;
|
|||||||
// im Speicher gehalten (stündlich / manuell aufgefrischt via applyRenderFormats).
|
// im Speicher gehalten (stündlich / manuell aufgefrischt via applyRenderFormats).
|
||||||
// Ist Directus nicht erreichbar oder ein Format nicht hinterlegt, greifen die
|
// Ist Directus nicht erreichbar oder ein Format nicht hinterlegt, greifen die
|
||||||
// eingebauten Defaults – die Generierung läuft also immer.
|
// eingebauten Defaults – die Generierung läuft also immer.
|
||||||
const DEFAULT_LINE_LIMITS = { a4: 27, a6p: 14, a6l: 11 };
|
const DEFAULT_LINE_LIMITS = { a4: 27, a5p: 19, a5l: 13, a6p: 14, a6l: 11, dinlang_karte: 11 };
|
||||||
const DEFAULT_FORMAT_LAYOUTS = {
|
const DEFAULT_FORMAT_LAYOUTS = {
|
||||||
a4: { marginTopMm: 25, marginLeftMm: 20, lineHeightFactor: 1.35 },
|
a4: { marginTopMm: 25, marginLeftMm: 20, lineHeightFactor: 1.35 },
|
||||||
a6p: { marginTopMm: 8, marginLeftMm: 8, lineHeightFactor: 1.3 },
|
a5p: { marginTopMm: 20, marginLeftMm: 15, lineHeightFactor: 1.35 },
|
||||||
a6l: { marginTopMm: 8, marginLeftMm: 8, marginRightMm: 14, lineHeightFactor: 1.2 },
|
a5l: { marginTopMm: 20, marginLeftMm: 15, lineHeightFactor: 1.35 },
|
||||||
|
dinlang_karte: { marginTopMm: 8, marginLeftMm: 10, lineHeightFactor: 1.2 },
|
||||||
|
// A6-Greifrand IMMER an der langen (148 mm) Seite:
|
||||||
|
// • a6p (hoch, 105×148): lange Seite = rechts → marginRightMm (Breite)
|
||||||
|
// • a6l (quer, 148×105): lange Seite = unten → marginBottomMm (Zeilen)
|
||||||
|
a6p: { marginTopMm: 8, marginLeftMm: 8, marginRightMm: 14, lineHeightFactor: 1.3 },
|
||||||
|
a6l: { marginTopMm: 8, marginLeftMm: 8, marginBottomMm: 14, lineHeightFactor: 1.2 },
|
||||||
din_lang: { marginTopMm: 50, marginLeftMm: 10, lineHeightFactor: 1.2 },
|
din_lang: { marginTopMm: 50, marginLeftMm: 10, lineHeightFactor: 1.2 },
|
||||||
c6: { marginTopMm: 60, marginLeftMm: 10, lineHeightFactor: 1.2 },
|
c6: { marginTopMm: 60, marginLeftMm: 10, lineHeightFactor: 1.2 },
|
||||||
};
|
};
|
||||||
const DEFAULT_PAGE_FORMATS = {
|
const DEFAULT_PAGE_FORMATS = {
|
||||||
a4: { widthMm: 210, heightMm: 297 },
|
a4: { widthMm: 210, heightMm: 297 },
|
||||||
|
a5p: { widthMm: 148, heightMm: 210 },
|
||||||
|
a5l: { widthMm: 210, heightMm: 148 },
|
||||||
|
dinlang_karte: { widthMm: 210, heightMm: 105 },
|
||||||
a6p: { widthMm: 105, heightMm: 148 },
|
a6p: { widthMm: 105, heightMm: 148 },
|
||||||
a6l: { widthMm: 148, heightMm: 105 },
|
a6l: { widthMm: 148, heightMm: 105 },
|
||||||
din_lang: { widthMm: 220, heightMm: 110 },
|
din_lang: { widthMm: 220, heightMm: 110 },
|
||||||
c6: { widthMm: 162, heightMm: 114 },
|
c6: { widthMm: 162, heightMm: 114 },
|
||||||
};
|
};
|
||||||
// Art des Formats (brief/umschlag/postkarte) – steuert, WAS generiert wird.
|
// Art des Formats (brief/umschlag/postkarte) – steuert, WAS generiert wird.
|
||||||
const DEFAULT_KINDS = { a4: 'brief', a6p: 'brief', a6l: 'brief', din_lang: 'umschlag', c6: 'umschlag' };
|
const DEFAULT_KINDS = { a4: 'brief', a5p: 'brief', a5l: 'brief', a6p: 'brief', a6l: 'brief', dinlang_karte: 'brief', din_lang: 'umschlag', c6: 'umschlag' };
|
||||||
|
|
||||||
// Live-Cache (wird von applyRenderFormats ersetzt). Start = Defaults.
|
// Live-Cache (wird von applyRenderFormats ersetzt). Start = Defaults.
|
||||||
let LINE_LIMITS = { ...DEFAULT_LINE_LIMITS };
|
let LINE_LIMITS = { ...DEFAULT_LINE_LIMITS };
|
||||||
@@ -56,6 +65,8 @@ function applyRenderFormats(rows) {
|
|||||||
};
|
};
|
||||||
const mr = r.margin_right_mm ?? alt.marginRightMm;
|
const mr = r.margin_right_mm ?? alt.marginRightMm;
|
||||||
if (mr != null && mr !== '') layout.marginRightMm = Number(mr);
|
if (mr != null && mr !== '') layout.marginRightMm = Number(mr);
|
||||||
|
const mb = r.margin_bottom_mm ?? alt.marginBottomMm;
|
||||||
|
if (mb != null && mb !== '') layout.marginBottomMm = Number(mb);
|
||||||
fl[k] = layout;
|
fl[k] = layout;
|
||||||
if (r.line_limit != null && r.line_limit !== '') ll[k] = Number(r.line_limit);
|
if (r.line_limit != null && r.line_limit !== '') ll[k] = Number(r.line_limit);
|
||||||
}
|
}
|
||||||
@@ -110,6 +121,7 @@ function getLayoutForFormat(format) {
|
|||||||
marginTopPx: mmToPx(layoutConfig.marginTopMm),
|
marginTopPx: mmToPx(layoutConfig.marginTopMm),
|
||||||
marginLeftPx: mmToPx(layoutConfig.marginLeftMm),
|
marginLeftPx: mmToPx(layoutConfig.marginLeftMm),
|
||||||
marginRightPx: layoutConfig.marginRightMm ? mmToPx(layoutConfig.marginRightMm) : null,
|
marginRightPx: layoutConfig.marginRightMm ? mmToPx(layoutConfig.marginRightMm) : null,
|
||||||
|
marginBottomPx: layoutConfig.marginBottomMm ? mmToPx(layoutConfig.marginBottomMm) : 0,
|
||||||
lineHeightPx: FONT_SIZE_PX * layoutConfig.lineHeightFactor,
|
lineHeightPx: FONT_SIZE_PX * layoutConfig.lineHeightFactor,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -143,6 +155,21 @@ function getLineLimit(format) {
|
|||||||
return LINE_LIMITS[normalizedFormat] || LINE_LIMITS.a4;
|
return LINE_LIMITS[normalizedFormat] || LINE_LIMITS.a4;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Effektives Zeilenlimit: das kleinere aus (a) konfiguriertem line_limit,
|
||||||
|
// gegenläufig zur Schriftgröße skaliert, und (b) geometrischer Kapazität, die
|
||||||
|
// einen unteren Greifrand (marginBottomMm) frei hält. Dadurch reserviert A6 quer
|
||||||
|
// (marginBottomMm=14) unten Freiraum für den rollengeführten Plotter, ohne dass
|
||||||
|
// die anderen Formate (ohne Bottom-Rand) berührt werden.
|
||||||
|
function getEffectiveLineLimit(format, fontScale = 1) {
|
||||||
|
const fs = Math.max(0.8, Math.min(1.5, Number(fontScale) || 1));
|
||||||
|
const konfiguriert = Math.max(1, Math.round(getLineLimit(format) / fs));
|
||||||
|
const { heightPx } = getPageDimensions(format);
|
||||||
|
const { marginTopPx, marginBottomPx, lineHeightPx } = getLayoutForFormat(format);
|
||||||
|
const nutzbarPx = heightPx - marginTopPx - (marginBottomPx || 0);
|
||||||
|
const geo = Math.max(1, Math.floor(nutzbarPx / (lineHeightPx * fs)));
|
||||||
|
return Math.min(konfiguriert, geo);
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
PX_PER_MM,
|
PX_PER_MM,
|
||||||
FONT_SIZE_PX,
|
FONT_SIZE_PX,
|
||||||
@@ -150,6 +177,7 @@ module.exports = {
|
|||||||
getLayoutForFormat,
|
getLayoutForFormat,
|
||||||
getPageDimensions,
|
getPageDimensions,
|
||||||
getLineLimit,
|
getLineLimit,
|
||||||
|
getEffectiveLineLimit,
|
||||||
getFormatKind,
|
getFormatKind,
|
||||||
escapeXml,
|
escapeXml,
|
||||||
applyRenderFormats,
|
applyRenderFormats,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ const {
|
|||||||
FONT_SIZE_PX,
|
FONT_SIZE_PX,
|
||||||
getLayoutForFormat,
|
getLayoutForFormat,
|
||||||
getPageDimensions,
|
getPageDimensions,
|
||||||
getLineLimit,
|
getEffectiveLineLimit,
|
||||||
escapeXml,
|
escapeXml,
|
||||||
mmToPx
|
mmToPx
|
||||||
} = require('./page-layout');
|
} = require('./page-layout');
|
||||||
@@ -140,7 +140,7 @@ function generateLetterSVG(text, format, options = {}) {
|
|||||||
.join('\n ');
|
.join('\n ');
|
||||||
|
|
||||||
// Größere Schrift → weniger Zeilen passen aufs Blatt (Limit gegenläufig skalieren).
|
// Größere Schrift → weniger Zeilen passen aufs Blatt (Limit gegenläufig skalieren).
|
||||||
const lineLimit = Math.max(1, Math.round(getLineLimit(format) / fontScale));
|
const lineLimit = getEffectiveLineLimit(format, fontScale);
|
||||||
return {
|
return {
|
||||||
svg: `<svg xmlns="http://www.w3.org/2000/svg"
|
svg: `<svg xmlns="http://www.w3.org/2000/svg"
|
||||||
width="${widthMm}mm" height="${heightMm}mm"
|
width="${widthMm}mm" height="${heightMm}mm"
|
||||||
@@ -182,7 +182,7 @@ function generateLetterSVG(text, format, options = {}) {
|
|||||||
const allSvgElements = [];
|
const allSvgElements = [];
|
||||||
let currentY = marginTopPx + fontSizePx;
|
let currentY = marginTopPx + fontSizePx;
|
||||||
let totalLineCount = 0;
|
let totalLineCount = 0;
|
||||||
const lineLimit = Math.max(1, Math.round(getLineLimit(format) / fontScale));
|
const lineLimit = getEffectiveLineLimit(format, fontScale);
|
||||||
|
|
||||||
let si = 0;
|
let si = 0;
|
||||||
while (si < segments.length) {
|
while (si < segments.length) {
|
||||||
@@ -502,8 +502,25 @@ function generatePostcardSVG(text, format, options = {}) {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Text links (L-förmig). Nur DER Text kann „zu lang" sein (Nutzer kürzt ihn).
|
// Absender oben links – ZUERST, damit der Text knapp darunter beginnen kann.
|
||||||
const baseline0 = mmToPx(14) + fontSizePx;
|
// Größe folgt der „Absender-Größe" aus dem manuellen Druck (options.senderScale).
|
||||||
|
let senderBottomPx = mmToPx(2);
|
||||||
|
if (sender) {
|
||||||
|
const senderScale = Math.max(0.5, Math.min(1.8, Number(options.senderScale) || 1));
|
||||||
|
const senderSize = FONT_SIZE_PX * 0.55 * senderScale;
|
||||||
|
const senderLH = (baseLineHeightPx / FONT_SIZE_PX) * senderSize;
|
||||||
|
const senderLines = wrapTextToLinesByWidth({ text: sender, maxWidthPx: mmToPx(textUpperRightMm - textLeftMm), fontFileName: fontFile, fontSizePx: senderSize }).slice(0, 2);
|
||||||
|
const senderStartY = mmToPx(2) + senderSize;
|
||||||
|
paths.push(...layoutTextToPaths({
|
||||||
|
lines: senderLines, fontFileName: fontFile, fontSizePx: senderSize,
|
||||||
|
startX: mmToPx(textLeftMm), startY: senderStartY, lineHeightPx: senderLH, realisticHandwriting: realistic,
|
||||||
|
}));
|
||||||
|
senderBottomPx = senderStartY + Math.max(0, senderLines.length - 1) * senderLH + senderSize * 0.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text links (L-förmig). Beginn nur ETWAS unter dem Absender (≈2 mm); ohne
|
||||||
|
// Absender wie im Maßblatt bei y≈14 mm. Nur DER Text kann „zu lang" sein.
|
||||||
|
const baseline0 = (sender ? senderBottomPx + mmToPx(2) : mmToPx(14)) + fontSizePx;
|
||||||
bodyLineLimit = Math.max(1, Math.floor((mmToPx(maxYmm) - baseline0) / lineHeightPx) + 1);
|
bodyLineLimit = Math.max(1, Math.floor((mmToPx(maxYmm) - baseline0) / lineHeightPx) + 1);
|
||||||
if (body) {
|
if (body) {
|
||||||
const bodyLines = flowVariabel(body, fontSizePx, baseline0, lineHeightPx);
|
const bodyLines = flowVariabel(body, fontSizePx, baseline0, lineHeightPx);
|
||||||
@@ -515,30 +532,22 @@ function generatePostcardSVG(text, format, options = {}) {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Absender oben links (2 Zeilen), klein genug für die 10-mm-Zone.
|
// Empfänger im sicheren Adressfeld (rechts unten). Größe folgt der „Schriftgröße
|
||||||
if (sender) {
|
// Kuvert" (options.recipientScale). Passt der Block nicht in die 46-mm-Zone, wird
|
||||||
const senderSize = FONT_SIZE_PX * 0.55 * Math.max(0.7, Math.min(1.2, Number(options.senderScale) || 1));
|
// er automatisch verkleinert – so bleibt die Codierzone IMMER frei.
|
||||||
const senderLH = (baseLineHeightPx / FONT_SIZE_PX) * senderSize;
|
|
||||||
const senderLines = wrapTextToLinesByWidth({ text: sender, maxWidthPx: mmToPx(textUpperRightMm - textLeftMm), fontFileName: fontFile, fontSizePx: senderSize }).slice(0, 2);
|
|
||||||
paths.push(...layoutTextToPaths({
|
|
||||||
lines: senderLines, fontFileName: fontFile, fontSizePx: senderSize,
|
|
||||||
startX: mmToPx(textLeftMm), startY: mmToPx(2) + senderSize, lineHeightPx: senderLH, realisticHandwriting: realistic,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Empfänger im sicheren Adressfeld (rechts unten). Passt der Block nicht in die
|
|
||||||
// 46 mm hohe Zone, wird die Schrift automatisch verkleinert – so bleibt die
|
|
||||||
// Codierzone (unten) IMMER frei und es gibt keinen „Adresse zu lang"-Fehler.
|
|
||||||
if (recipient) {
|
if (recipient) {
|
||||||
const feldOben = mmToPx(addrTopMm);
|
const feldOben = mmToPx(addrTopMm);
|
||||||
const feldUnten = mmToPx(maxYmm);
|
const feldUnten = mmToPx(maxYmm);
|
||||||
const feldBreite = mmToPx(addrRightMm - addrLeftMm);
|
const feldBreite = mmToPx(addrRightMm - addrLeftMm);
|
||||||
let recSize = fontSizePx;
|
const recScale = Math.max(0.6, Math.min(1.6, Number(options.recipientScale) || 1));
|
||||||
let recLH = lineHeightPx;
|
const recBaseSize = FONT_SIZE_PX * recScale;
|
||||||
|
const recBaseLH = baseLineHeightPx * recScale;
|
||||||
|
let recSize = recBaseSize;
|
||||||
|
let recLH = recBaseLH;
|
||||||
let recLines = [];
|
let recLines = [];
|
||||||
for (const scale of [1, 0.9, 0.8, 0.72, 0.65, 0.6]) {
|
for (const scale of [1, 0.9, 0.8, 0.72, 0.65, 0.6]) {
|
||||||
recSize = fontSizePx * scale;
|
recSize = recBaseSize * scale;
|
||||||
recLH = lineHeightPx * scale;
|
recLH = recBaseLH * scale;
|
||||||
recLines = wrapTextToLinesByWidth({ text: recipient, maxWidthPx: feldBreite, fontFileName: fontFile, fontSizePx: recSize });
|
recLines = wrapTextToLinesByWidth({ text: recipient, maxWidthPx: feldBreite, fontFileName: fontFile, fontSizePx: recSize });
|
||||||
const blockUnten = feldOben + recSize + Math.max(0, recLines.length - 1) * recLH + recSize * 0.3;
|
const blockUnten = feldOben + recSize + Math.max(0, recLines.length - 1) * recLH + recSize * 0.3;
|
||||||
if (blockUnten <= feldUnten) break;
|
if (blockUnten <= feldUnten) break;
|
||||||
@@ -561,8 +570,9 @@ function generatePostcardSVG(text, format, options = {}) {
|
|||||||
/>`)
|
/>`)
|
||||||
.join('\n ');
|
.join('\n ');
|
||||||
|
|
||||||
// Trennstrich (solide Linie, 1,2 mm breit) zwischen Text und Adressfeld.
|
// Trennstrich: einfache Kugelschreiber-Linie (Single-Stroke, keine Füllung) –
|
||||||
const trennstrich = `<path d="M ${mmToPx(trennXmm).toFixed(1)} ${mmToPx(addrTopMm).toFixed(1)} L ${mmToPx(trennXmm).toFixed(1)} ${mmToPx(maxYmm).toFixed(1)}" stroke="#000000" stroke-width="${mmToPx(1.2).toFixed(1)}" stroke-linecap="butt" fill="none"/>`;
|
// gleiche Strichstärke wie die Handschrift, damit die Ballpoint-Optik greift.
|
||||||
|
const trennstrich = `<path d="M ${mmToPx(trennXmm).toFixed(1)} ${mmToPx(addrTopMm).toFixed(1)} L ${mmToPx(trennXmm).toFixed(1)} ${mmToPx(maxYmm).toFixed(1)}" stroke="#000000" stroke-width="0.6" fill="none" stroke-linecap="round" vector-effect="non-scaling-stroke"/>`;
|
||||||
|
|
||||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg"
|
const svg = `<svg xmlns="http://www.w3.org/2000/svg"
|
||||||
width="${W}mm"
|
width="${W}mm"
|
||||||
@@ -596,7 +606,7 @@ function generateLetterPages(text, format, options = {}) {
|
|||||||
const fontScale = Math.max(0.8, Math.min(1.5, Number(options.fontScale) || 1));
|
const fontScale = Math.max(0.8, Math.min(1.5, Number(options.fontScale) || 1));
|
||||||
const fontSizePx = FONT_SIZE_PX * fontScale;
|
const fontSizePx = FONT_SIZE_PX * fontScale;
|
||||||
const lineHeightPx = baseLineHeightPx * fontScale;
|
const lineHeightPx = baseLineHeightPx * fontScale;
|
||||||
const linesPerPage = Math.max(1, Math.round(getLineLimit(format) / fontScale));
|
const linesPerPage = getEffectiveLineLimit(format, fontScale);
|
||||||
|
|
||||||
// Erzwungene Seitenumbrüche zuerst; danach jeden Block nach Zeilen auto-fließen.
|
// Erzwungene Seitenumbrüche zuerst; danach jeden Block nach Zeilen auto-fließen.
|
||||||
const bloecke = String(text || '').split(/\[\[seitenumbruch\]\]/gi);
|
const bloecke = String(text || '').split(/\[\[seitenumbruch\]\]/gi);
|
||||||
@@ -656,7 +666,7 @@ function countLetterPages(text, format, options = {}) {
|
|||||||
const maxWidthPx = widthPx - marginLeftPx - (marginRightPx ?? marginLeftPx);
|
const maxWidthPx = widthPx - marginLeftPx - (marginRightPx ?? marginLeftPx);
|
||||||
const fontScale = Math.max(0.8, Math.min(1.5, Number(options.fontScale) || 1));
|
const fontScale = Math.max(0.8, Math.min(1.5, Number(options.fontScale) || 1));
|
||||||
const fontSizePx = FONT_SIZE_PX * fontScale;
|
const fontSizePx = FONT_SIZE_PX * fontScale;
|
||||||
const linesPerPage = Math.max(1, Math.round(getLineLimit(format) / fontScale));
|
const linesPerPage = getEffectiveLineLimit(format, fontScale);
|
||||||
|
|
||||||
const seitenZeilen = [];
|
const seitenZeilen = [];
|
||||||
for (const block of String(text || '').split(/\[\[seitenumbruch\]\]/gi)) {
|
for (const block of String(text || '').split(/\[\[seitenumbruch\]\]/gi)) {
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ const config = require('./config');
|
|||||||
const previewRoutes = require('./api/routes/preview-routes');
|
const previewRoutes = require('./api/routes/preview-routes');
|
||||||
const orderRoutes = require('./api/routes/order-routes');
|
const orderRoutes = require('./api/routes/order-routes');
|
||||||
const chargeRoutes = require('./api/routes/charge-routes');
|
const chargeRoutes = require('./api/routes/charge-routes');
|
||||||
|
const batchRoutes = require('./api/routes/batch-routes');
|
||||||
const healthRoutes = require('./api/routes/health-routes');
|
const healthRoutes = require('./api/routes/health-routes');
|
||||||
|
const { runScheduledBatch, berlinParts } = require('./api/controllers/batch-controller');
|
||||||
|
|
||||||
const errorHandler = require('./api/middleware/error-handler');
|
const errorHandler = require('./api/middleware/error-handler');
|
||||||
const requestLogger = require('./api/middleware/request-logger');
|
const requestLogger = require('./api/middleware/request-logger');
|
||||||
@@ -49,6 +51,7 @@ app.use('/health', healthRoutes);
|
|||||||
app.use('/api/preview', previewRoutes);
|
app.use('/api/preview', previewRoutes);
|
||||||
app.use('/api/order', orderRoutes);
|
app.use('/api/order', orderRoutes);
|
||||||
app.use('/api/charge', chargeRoutes);
|
app.use('/api/charge', chargeRoutes);
|
||||||
|
app.use('/api/batch', batchRoutes);
|
||||||
|
|
||||||
// Format-Cache manuell auffrischen (Token-geschützt) – für „sofort übernehmen".
|
// Format-Cache manuell auffrischen (Token-geschützt) – für „sofort übernehmen".
|
||||||
app.post('/api/formats/refresh', async (req, res) => {
|
app.post('/api/formats/refresh', async (req, res) => {
|
||||||
@@ -80,6 +83,22 @@ app.listen(config.port, () => {
|
|||||||
// Formate initial laden und stündlich auffrischen (zentral aus Directus).
|
// Formate initial laden und stündlich auffrischen (zentral aus Directus).
|
||||||
refreshRenderFormats();
|
refreshRenderFormats();
|
||||||
setInterval(refreshRenderFormats, 60 * 60 * 1000);
|
setInterval(refreshRenderFormats, 60 * 60 * 1000);
|
||||||
|
|
||||||
|
// Batch-FTP-Bündelung nur, wenn ausdrücklich aktiviert (Standardweg ist die
|
||||||
|
// Übernahme in die Produktion, nicht FTP). SKRIFT_BATCH_FTP_CRON=true schaltet
|
||||||
|
// den täglichen 03:00-Lauf (Europe/Berlin) wieder ein; Sa+So am Montag.
|
||||||
|
if (String(process.env.SKRIFT_BATCH_FTP_CRON || '').toLowerCase() === 'true') {
|
||||||
|
let letzterBatchTag = null;
|
||||||
|
setInterval(() => {
|
||||||
|
try {
|
||||||
|
const { date, hour } = berlinParts();
|
||||||
|
if (hour !== 3 || letzterBatchTag === date) return;
|
||||||
|
letzterBatchTag = date;
|
||||||
|
runScheduledBatch().catch((e) => console.error('[batch-cron] Fehler:', e.message));
|
||||||
|
} catch (e) { console.error('[batch-cron] Tick-Fehler:', e.message); }
|
||||||
|
}, 60 * 1000);
|
||||||
|
console.log('Batch-FTP-Cron: aktiv (03:00 Europe/Berlin)');
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Graceful shutdown
|
// Graceful shutdown
|
||||||
|
|||||||
@@ -110,4 +110,23 @@ async function fetchRenderFormats() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { fetchOrder, updateOrder, addStatusHistory, fetchRenderFormats, fetchOrdersMinimal, fetchAssetBuffer };
|
/** Offene (pending) Batch-Übermittlungen MIT Druck-PDF, optional je Zugang.
|
||||||
|
* Text-only-Datensätze (ohne PDF) werden bewusst NICHT gebündelt. */
|
||||||
|
async function fetchBatchPending(clientId, ids) {
|
||||||
|
let filter = 'filter[status][_eq]=pending&filter[pdf_file][_nnull]=true';
|
||||||
|
if (clientId != null) filter += `&filter[api_client][_eq]=${encodeURIComponent(clientId)}`;
|
||||||
|
if (Array.isArray(ids) && ids.length) filter += `&filter[id][_in]=${ids.map(encodeURIComponent).join(',')}`;
|
||||||
|
const fields = 'id,api_client,firma,vorname,nachname,zeile1,zeile2,zeile3,plz,stadt,land,pdf_file';
|
||||||
|
return (await directusFetch(`/items/batch_submissions?${filter}&sort=date_created&limit=-1&fields=${fields}`)) || [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Markiert Datensätze als gebündelt (nach erfolgreichem FTP-Upload). */
|
||||||
|
async function markBatchBundled(ids, bundleName) {
|
||||||
|
if (!ids || !ids.length) return;
|
||||||
|
return directusFetch('/items/batch_submissions', {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify({ keys: ids, data: { status: 'bundled', bundle_name: bundleName, bundled_at: new Date().toISOString() } }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { fetchOrder, updateOrder, addStatusHistory, fetchRenderFormats, fetchOrdersMinimal, fetchAssetBuffer, fetchBatchPending, markBatchBundled };
|
||||||
|
|||||||
Reference in New Issue
Block a user