Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d4a51cd4d | |||
|
|
3b21608ca4 | ||
|
|
d5a051befc | ||
|
|
17eebcfe6a | ||
|
|
9984b822aa | ||
|
|
29021281bb | ||
|
|
a882bf37f5 | ||
|
|
7930c177ee | ||
|
|
c73109b8ca | ||
|
|
2c2282e05a |
@@ -69,6 +69,9 @@ async function buildMergedPdf(subs) {
|
|||||||
async function ftpUpload(dateien) {
|
async function ftpUpload(dateien) {
|
||||||
const { host, port, user, password, secure, rejectUnauthorized } = config.ftp;
|
const { host, port, user, password, secure, rejectUnauthorized } = config.ftp;
|
||||||
if (!host || !user) throw new Error('FTP nicht konfiguriert (SKRIFT_FTP_HOST/USER fehlen).');
|
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);
|
const client = new ftp.Client(30000);
|
||||||
// client.ftp.verbose = true;
|
// client.ftp.verbose = true;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -5,33 +5,48 @@
|
|||||||
* Unterschriften-Service) zu EINER PDF zusammen, die am Bürodrucker in einem
|
* Unterschriften-Service) zu EINER PDF zusammen, die am Bürodrucker in einem
|
||||||
* Rutsch gedruckt werden kann. Reihenfolge = Auftragsnummer (aufsteigend), damit
|
* Rutsch gedruckt werden kann. Reihenfolge = Auftragsnummer (aufsteigend), damit
|
||||||
* sie zur Kuvert-Reihenfolge im Plotter passt.
|
* sie zur Kuvert-Reihenfolge im Plotter passt.
|
||||||
|
*
|
||||||
|
* Dazu passend: Excel-Export aller Adressen in EXAKT derselben Reihenfolge wie
|
||||||
|
* das Sammel-PDF (gleiche Auftragsabfrage, gleiche Datei-Reihenfolge).
|
||||||
*/
|
*/
|
||||||
const { PDFDocument } = require('pdf-lib');
|
const { PDFDocument } = require('pdf-lib');
|
||||||
|
const ExcelJS = require('exceljs');
|
||||||
const directus = require('../../services/directus-service');
|
const directus = require('../../services/directus-service');
|
||||||
|
|
||||||
|
/** Druckdateien eines Auftrags in Stapel-Reihenfolge (geteilt von PDF + Excel). */
|
||||||
|
function dateienVon(order) {
|
||||||
|
const sf = Array.isArray(order.source_files) ? order.source_files.filter(Boolean) : [];
|
||||||
|
if (sf.length) return sf;
|
||||||
|
return order.source_file ? [order.source_file] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ausgewählte Aufträge laden – sortiert nach Auftragsnummer (wie bisher). */
|
||||||
|
async function ladeAuftraege(req, res) {
|
||||||
|
const ids = Array.isArray(req.body?.orderIds) ? req.body.orderIds.filter((v) => v != null) : [];
|
||||||
|
if (!ids.length) {
|
||||||
|
res.status(400).json({ error: 'Invalid request', message: 'orderIds (array) is required.' });
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const orders = await directus.fetchOrdersMinimal(ids);
|
||||||
|
if (!orders || !orders.length) {
|
||||||
|
res.status(404).json({ error: 'Not found', message: 'Keine Aufträge gefunden.' });
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return orders;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* POST /api/charge/merge-pdf
|
* POST /api/charge/merge-pdf
|
||||||
* Body: { orderIds: (number|string)[] } → application/pdf (zusammengeführt)
|
* Body: { orderIds: (number|string)[] } → application/pdf (zusammengeführt)
|
||||||
*/
|
*/
|
||||||
async function mergePdf(req, res, next) {
|
async function mergePdf(req, res, next) {
|
||||||
try {
|
try {
|
||||||
const ids = Array.isArray(req.body?.orderIds) ? req.body.orderIds.filter((v) => v != null) : [];
|
const orders = await ladeAuftraege(req, res);
|
||||||
if (!ids.length) {
|
if (!orders) return undefined;
|
||||||
return res.status(400).json({ error: 'Invalid request', message: 'orderIds (array) is required.' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const orders = await directus.fetchOrdersMinimal(ids);
|
|
||||||
if (!orders || !orders.length) {
|
|
||||||
return res.status(404).json({ error: 'Not found', message: 'Keine Aufträge gefunden.' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Datei-IDs in Auftragsnummern-Reihenfolge (orders ist bereits sortiert).
|
// Datei-IDs in Auftragsnummern-Reihenfolge (orders ist bereits sortiert).
|
||||||
const fileIds = [];
|
const fileIds = [];
|
||||||
for (const o of orders) {
|
for (const o of orders) fileIds.push(...dateienVon(o));
|
||||||
const sf = Array.isArray(o.source_files) ? o.source_files.filter(Boolean) : [];
|
|
||||||
if (sf.length) fileIds.push(...sf);
|
|
||||||
else if (o.source_file) fileIds.push(o.source_file);
|
|
||||||
}
|
|
||||||
if (!fileIds.length) {
|
if (!fileIds.length) {
|
||||||
return res.status(400).json({ error: 'No files', message: 'Keine Druckdateien an den Aufträgen.' });
|
return res.status(400).json({ error: 'No files', message: 'Keine Druckdateien an den Aufträgen.' });
|
||||||
}
|
}
|
||||||
@@ -66,4 +81,103 @@ async function mergePdf(req, res, next) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { mergePdf };
|
const seitenText = (von, bis) => (bis < von ? '' : (von === bis ? String(von) : `${von}–${bis}`));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/charge/merge-xlsx
|
||||||
|
* Body: { orderIds: (number|string)[] } → .xlsx (Adressen in Sammel-PDF-Reihenfolge)
|
||||||
|
*
|
||||||
|
* Je Empfänger eine Zeile. Aufträge in derselben Reihenfolge wie merge-pdf,
|
||||||
|
* innerhalb des Auftrags nach Briefnummer. „PDF-Seiten" zeigt, wo die Zeile im
|
||||||
|
* Sammel-PDF liegt: je Brief, wenn der Auftrag genau eine PDF je Empfänger hat,
|
||||||
|
* sonst den Seitenbereich des ganzen Auftrags.
|
||||||
|
*/
|
||||||
|
async function mergeXlsx(req, res, next) {
|
||||||
|
try {
|
||||||
|
const orders = await ladeAuftraege(req, res);
|
||||||
|
if (!orders) return undefined;
|
||||||
|
|
||||||
|
const entries = await directus.fetchEntriesForOrders(orders.map((o) => o.id));
|
||||||
|
const proAuftrag = new Map();
|
||||||
|
for (const e of entries) {
|
||||||
|
const k = String(e.order);
|
||||||
|
if (!proAuftrag.has(k)) proAuftrag.set(k, []);
|
||||||
|
proAuftrag.get(k).push(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
const wb = new ExcelJS.Workbook();
|
||||||
|
const ws = wb.addWorksheet('Adressen');
|
||||||
|
ws.columns = [
|
||||||
|
{ header: 'Nr.', key: 'nr', width: 6 },
|
||||||
|
{ header: 'Auftragsnummer', key: 'auftrag', width: 16 },
|
||||||
|
{ header: 'Briefnummer', key: 'brief', width: 11 },
|
||||||
|
{ header: 'Anrede', key: 'salutation', width: 12 },
|
||||||
|
{ header: 'Vorname', key: 'first_name', width: 16 },
|
||||||
|
{ header: 'Nachname', key: 'last_name', width: 18 },
|
||||||
|
{ header: 'Straße', key: 'street', width: 22 },
|
||||||
|
{ header: 'Hausnr.', key: 'house_no', width: 8 },
|
||||||
|
{ header: 'PLZ', key: 'zip', width: 8 },
|
||||||
|
{ header: 'Ort', key: 'city', width: 16 },
|
||||||
|
{ header: 'Land', key: 'country', width: 12 },
|
||||||
|
{ header: 'Adresse (Freitext)', key: 'free_text', width: 36 },
|
||||||
|
{ header: 'PDF-Seiten', key: 'seiten', width: 11 },
|
||||||
|
{ header: 'Hinweis', key: 'hinweis', width: 34 },
|
||||||
|
];
|
||||||
|
ws.getRow(1).font = { bold: true };
|
||||||
|
ws.views = [{ state: 'frozen', ySplit: 1 }];
|
||||||
|
|
||||||
|
// Seitenzähler läuft über alle Dateien – identisch zum Zusammenfügen in merge-pdf
|
||||||
|
// (defekte/fehlende PDFs werden dort übersprungen und belegen keine Seiten).
|
||||||
|
let seite = 0;
|
||||||
|
let nr = 0;
|
||||||
|
for (const o of orders) {
|
||||||
|
const empf = proAuftrag.get(String(o.id)) || [];
|
||||||
|
const dateien = [];
|
||||||
|
for (const fid of dateienVon(o)) {
|
||||||
|
try {
|
||||||
|
const buf = await directus.fetchAssetBuffer(fid);
|
||||||
|
const src = await PDFDocument.load(buf, { ignoreEncryption: true });
|
||||||
|
const n = src.getPageCount();
|
||||||
|
dateien.push({ von: seite + 1, bis: seite + n, ok: true });
|
||||||
|
seite += n;
|
||||||
|
} catch (e) {
|
||||||
|
dateien.push({ ok: false });
|
||||||
|
console.warn(`[Charge] PDF ${fid} (Excel) übersprungen: ${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const okDateien = dateien.filter((d) => d.ok);
|
||||||
|
const auftragSeiten = okDateien.length ? seitenText(okDateien[0].von, okDateien[okDateien.length - 1].bis) : '';
|
||||||
|
const jeBrief = dateien.length > 0 && dateien.length === empf.length && okDateien.length === dateien.length;
|
||||||
|
|
||||||
|
let hinweis = '';
|
||||||
|
if (!dateien.length) hinweis = 'Keine Druckdatei – nicht im Sammel-PDF.';
|
||||||
|
else if (okDateien.length < dateien.length) hinweis = `${dateien.length - okDateien.length} PDF(s) defekt/fehlend – im Sammel-PDF übersprungen.`;
|
||||||
|
else if (!jeBrief) hinweis = 'Seitenbereich gilt für den ganzen Auftrag.';
|
||||||
|
|
||||||
|
const zeilen = empf.length ? empf : [{}]; // Auftrag ohne Empfänger trotzdem sichtbar
|
||||||
|
zeilen.forEach((e, i) => {
|
||||||
|
nr += 1;
|
||||||
|
ws.addRow({
|
||||||
|
nr,
|
||||||
|
auftrag: o.order_number || '',
|
||||||
|
brief: e.letter_number ?? '',
|
||||||
|
salutation: e.salutation || '', first_name: e.first_name || '', last_name: e.last_name || '',
|
||||||
|
street: e.street || '', house_no: e.house_no || '', zip: e.zip || '', city: e.city || '',
|
||||||
|
country: e.country || '', free_text: e.free_text || '',
|
||||||
|
seiten: jeBrief ? seitenText(dateien[i].von, dateien[i].bis) : auftragSeiten,
|
||||||
|
hinweis: empf.length ? hinweis : 'Keine Empfänger am Auftrag.',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
ws.getColumn('free_text').alignment = { wrapText: true, vertical: 'top' };
|
||||||
|
|
||||||
|
const buf = Buffer.from(await wb.xlsx.writeBuffer());
|
||||||
|
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||||
|
res.setHeader('Content-Disposition', 'attachment; filename="charge.xlsx"');
|
||||||
|
return res.status(200).send(buf);
|
||||||
|
} catch (err) {
|
||||||
|
return next(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { mergePdf, mergeXlsx };
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ const { replacePlaceholders } = require('../../services/placeholder-service');
|
|||||||
|
|
||||||
// Directus-Formatschlüssel → Backend-Formate
|
// Directus-Formatschlüssel → Backend-Formate
|
||||||
const LETTER_FORMAT = { a4: 'a4', a6_hoch: 'a6p', a6_quer: 'a6l' };
|
const LETTER_FORMAT = { a4: 'a4', a6_hoch: 'a6p', a6_quer: 'a6l' };
|
||||||
const ENVELOPE_FORMAT = { c6: 'c6', dinlang: 'din_lang' };
|
const ENVELOPE_FORMAT = { c6: 'c6', dinlang: 'din_lang', c4: 'c4' };
|
||||||
|
|
||||||
/** Baut den Adressblock für einen Umschlag aus einer Empfängerzeile. */
|
/** Baut den Adressblock für einen Umschlag aus einer Empfängerzeile. */
|
||||||
function addressText(entry) {
|
function addressText(entry) {
|
||||||
|
|||||||
@@ -598,6 +598,113 @@ async function registerOrder(req, res, next) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Empfänger-Datei einlesen (XLSX/CSV) nach Spaltennamen ────────────────────
|
||||||
|
// Spiegelt die Logik der Web-App (skrift-app/src/lib/excel.ts): feste Spalten,
|
||||||
|
// „Zeile N" → Freitext, unbekannte Spalten → Platzhalter.
|
||||||
|
const EMPF_SPALTEN = {
|
||||||
|
anrede: 'salutation', vorname: 'first_name', nachname: 'last_name', name: 'last_name',
|
||||||
|
strasse: 'street', 'straße': 'street', nr: 'house_no', hausnummer: 'house_no',
|
||||||
|
plz: 'zip', ort: 'city', stadt: 'city', land: 'country',
|
||||||
|
};
|
||||||
|
const normSpalte = (s) => String(s || '').trim().toLowerCase().replace(/\s+/g, '');
|
||||||
|
|
||||||
|
function zelleText(v) {
|
||||||
|
if (v === null || v === undefined) return '';
|
||||||
|
if (v instanceof Date) return v.toISOString().slice(0, 10);
|
||||||
|
if (typeof v === 'object') {
|
||||||
|
if (v.text !== undefined) return String(v.text);
|
||||||
|
if (v.result !== undefined) return String(v.result);
|
||||||
|
if (v.richText) return v.richText.map((t) => t.text).join('');
|
||||||
|
if (v.hyperlink !== undefined) return String(v.text || v.hyperlink);
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return String(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Robuster CSV/TSV-Parser (Trenner-Erkennung, Anführungszeichen, "" = ").
|
||||||
|
function parseCsvText(text) {
|
||||||
|
const erste = String(text).replace(/\r\n?/g, '\n').replace(/^/, '').split('\n')[0] || '';
|
||||||
|
const anz = (d) => erste.split(d).length - 1;
|
||||||
|
const delim = anz('\t') > 0 ? '\t' : ((anz(';') > 0 && anz(';') >= anz(',')) ? ';' : ',');
|
||||||
|
const s = String(text).replace(/\r\n?/g, '\n').replace(/^/, '');
|
||||||
|
const rows = []; let row = []; let cur = ''; let q = false;
|
||||||
|
for (let i = 0; i < s.length; i++) {
|
||||||
|
const c = s[i];
|
||||||
|
if (q) { if (c === '"') { if (s[i + 1] === '"') { cur += '"'; i++; } else { q = false; } } else { cur += c; } }
|
||||||
|
else if (c === '"') { q = true; }
|
||||||
|
else if (c === delim) { row.push(cur); cur = ''; }
|
||||||
|
else if (c === '\n') { row.push(cur); rows.push(row); row = []; cur = ''; }
|
||||||
|
else { cur += c; }
|
||||||
|
}
|
||||||
|
if (cur !== '' || row.length) { row.push(cur); rows.push(row); }
|
||||||
|
return rows.filter((r) => r.some((c) => String(c).trim() !== ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function tabelleAusDatei(buffer, filename) {
|
||||||
|
const ext = String(filename || '').toLowerCase();
|
||||||
|
const istCsv = ext.endsWith('.csv') || ext.endsWith('.tsv') || ext.endsWith('.txt');
|
||||||
|
if (!istCsv) {
|
||||||
|
try {
|
||||||
|
const ExcelJS = require('exceljs');
|
||||||
|
const wb = new ExcelJS.Workbook();
|
||||||
|
await wb.xlsx.load(buffer);
|
||||||
|
const ws = wb.worksheets[0];
|
||||||
|
if (ws) {
|
||||||
|
const breite = ws.actualColumnCount || ws.columnCount || 0;
|
||||||
|
const rows = [];
|
||||||
|
ws.eachRow({ includeEmpty: false }, (zeile) => {
|
||||||
|
const a = [];
|
||||||
|
for (let c = 1; c <= breite; c++) a.push(zelleText(zeile.getCell(c).value));
|
||||||
|
rows.push(a);
|
||||||
|
});
|
||||||
|
if (rows.length) return rows;
|
||||||
|
}
|
||||||
|
} catch (e) { /* keine gültige XLSX → als CSV versuchen */ }
|
||||||
|
}
|
||||||
|
return parseCsvText(buffer.toString('utf8'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/order/parse-recipients
|
||||||
|
* Body: { data_base64, filename }. Antwort: { entries, columns, count }.
|
||||||
|
*/
|
||||||
|
async function parseRecipients(req, res, next) {
|
||||||
|
try {
|
||||||
|
const b64 = String((req.body && req.body.data_base64) || '').replace(/^data:[^,]*,/, '');
|
||||||
|
const filename = (req.body && req.body.filename) || '';
|
||||||
|
if (!b64) return res.status(400).json({ error: 'Keine Datei übermittelt.' });
|
||||||
|
const buffer = Buffer.from(b64, 'base64');
|
||||||
|
if (!buffer.length) return res.status(400).json({ error: 'Leere Datei.' });
|
||||||
|
|
||||||
|
const tab = await tabelleAusDatei(buffer, filename);
|
||||||
|
if (tab.length < 2) return res.status(422).json({ error: 'Keine Datenzeilen – Datei braucht eine Kopfzeile mit Spaltennamen und mindestens einen Empfänger.' });
|
||||||
|
|
||||||
|
const kopf = tab[0].map((h) => String(h || '').trim());
|
||||||
|
const erkannt = new Set();
|
||||||
|
const entries = [];
|
||||||
|
for (let r = 1; r < tab.length; r++) {
|
||||||
|
const zellen = tab[r];
|
||||||
|
const e = { salutation: '', first_name: '', last_name: '', street: '', house_no: '', zip: '', city: '', country: '', free_text: '', placeholders: {} };
|
||||||
|
const freitextZeilen = [];
|
||||||
|
kopf.forEach((spalte, ci) => {
|
||||||
|
if (!spalte) return;
|
||||||
|
const wert = String(zellen[ci] ?? '').trim();
|
||||||
|
const zm = /^zeile\s*(\d+)$/i.exec(spalte);
|
||||||
|
const feld = EMPF_SPALTEN[normSpalte(spalte)];
|
||||||
|
if (zm) { freitextZeilen[Number(zm[1]) - 1] = wert; erkannt.add('Zeile ' + zm[1]); }
|
||||||
|
else if (feld) { e[feld] = wert; erkannt.add(spalte); }
|
||||||
|
else if (wert) { e.placeholders[spalte] = wert; erkannt.add(spalte); }
|
||||||
|
});
|
||||||
|
if (freitextZeilen.length) e.free_text = freitextZeilen.map((z) => z || '').join('\n').replace(/\n+$/, '');
|
||||||
|
entries.push(e);
|
||||||
|
}
|
||||||
|
return res.json({ entries, columns: [...erkannt], count: entries.length });
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[Order] parseRecipients:', err);
|
||||||
|
return res.status(500).json({ error: 'Datei konnte nicht gelesen werden.' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
finalizeOrder,
|
finalizeOrder,
|
||||||
generateOrder,
|
generateOrder,
|
||||||
@@ -605,4 +712,5 @@ module.exports = {
|
|||||||
uploadMotif,
|
uploadMotif,
|
||||||
uploadOrderFile,
|
uploadOrderFile,
|
||||||
registerOrder,
|
registerOrder,
|
||||||
|
parseRecipients,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,4 +10,11 @@ const { authenticateApiToken } = require('../middleware/auth');
|
|||||||
*/
|
*/
|
||||||
router.post('/merge-pdf', authenticateApiToken, chargeController.mergePdf);
|
router.post('/merge-pdf', authenticateApiToken, chargeController.mergePdf);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/charge/merge-xlsx
|
||||||
|
* Excel-Export aller Adressen in derselben Reihenfolge wie merge-pdf.
|
||||||
|
* Body: { orderIds: (number|string)[] }
|
||||||
|
*/
|
||||||
|
router.post('/merge-xlsx', authenticateApiToken, chargeController.mergeXlsx);
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
@@ -133,6 +133,13 @@ router.post('/files', authenticateApiToken, uploadOrderFile.single('file'), orde
|
|||||||
*/
|
*/
|
||||||
router.post('/register', authenticateApiToken, orderController.registerOrder);
|
router.post('/register', authenticateApiToken, orderController.registerOrder);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/order/parse-recipients
|
||||||
|
* Liest eine hochgeladene Empfängerdatei (XLSX/CSV als Base64) nach Spaltennamen ein.
|
||||||
|
* Body: { data_base64, filename }
|
||||||
|
*/
|
||||||
|
router.post('/parse-recipients', authenticateApiToken, orderController.parseRecipients);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* POST /api/order/from-directus
|
* POST /api/order/from-directus
|
||||||
* Generiert einen Auftrag, dessen Daten in Directus liegen.
|
* Generiert einen Auftrag, dessen Daten in Directus liegen.
|
||||||
|
|||||||
@@ -64,11 +64,16 @@ module.exports = {
|
|||||||
// Login incorrect" führen, obwohl die Daten korrekt sind.
|
// Login incorrect" führen, obwohl die Daten korrekt sind.
|
||||||
ftp: (() => {
|
ftp: (() => {
|
||||||
const envClean = (v) => String(v || '').replace(/[\r\n]+/g, '').replace(/^(['"])([\s\S]*)\1$/, '$2');
|
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 {
|
return {
|
||||||
host: envClean(process.env.SKRIFT_FTP_HOST),
|
host: envClean(process.env.SKRIFT_FTP_HOST),
|
||||||
port: parseInt(process.env.SKRIFT_FTP_PORT, 10) || 21,
|
port: parseInt(process.env.SKRIFT_FTP_PORT, 10) || 21,
|
||||||
user: envClean(process.env.SKRIFT_FTP_USER),
|
user: envClean(process.env.SKRIFT_FTP_USER),
|
||||||
password: envClean(process.env.SKRIFT_FTP_PASSWORD),
|
password,
|
||||||
// explizites FTP über TLS (wie im FTP-Client eingestellt). 'false' schaltet ab.
|
// explizites FTP über TLS (wie im FTP-Client eingestellt). 'false' schaltet ab.
|
||||||
secure: String(process.env.SKRIFT_FTP_SECURE || 'true').toLowerCase() !== 'false',
|
secure: String(process.env.SKRIFT_FTP_SECURE || 'true').toLowerCase() !== 'false',
|
||||||
// Selbstsigniertes Zertifikat zulassen (viele FTP-Server) – auf 'false' setzen für strikte Prüfung.
|
// Selbstsigniertes Zertifikat zulassen (viele FTP-Server) – auf 'false' setzen für strikte Prüfung.
|
||||||
|
|||||||
@@ -6,23 +6,37 @@ 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 },
|
// A5 greift an der KURZEN (148 mm) Seite: hoch → unten, quer → rechts.
|
||||||
a6l: { marginTopMm: 8, marginLeftMm: 8, marginRightMm: 14, lineHeightFactor: 1.2 },
|
a5p: { marginTopMm: 20, marginLeftMm: 15, marginBottomMm: 14, lineHeightFactor: 1.35 },
|
||||||
|
a5l: { marginTopMm: 20, marginLeftMm: 15, marginRightMm: 14, lineHeightFactor: 1.35 },
|
||||||
|
// DIN lang greift an der langen (210 mm) Seite → unten.
|
||||||
|
dinlang_karte: { marginTopMm: 8, marginLeftMm: 10, marginBottomMm: 14, 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 },
|
||||||
|
// C4 quer (Querformat-Beschriftung, maschinenseitig quer eingelegt).
|
||||||
|
c4: { marginTopMm: 70, marginLeftMm: 20, 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 },
|
||||||
|
c4: { widthMm: 324, heightMm: 229 },
|
||||||
};
|
};
|
||||||
// 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', c4: '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 +70,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 +126,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 +160,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 +182,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"
|
||||||
@@ -156,12 +156,13 @@ function generateLetterSVG(text, format, options = {}) {
|
|||||||
|
|
||||||
// ── Pfad mit Signaturen: Text in Segmente aufteilen ───────────────────────
|
// ── Pfad mit Signaturen: Text in Segmente aufteilen ───────────────────────
|
||||||
// Jede Signatur-Zeile ist 2 Zeilen hoch; bis zu 3 Signaturen nebeneinander.
|
// Jede Signatur-Zeile ist 2 Zeilen hoch; bis zu 3 Signaturen nebeneinander.
|
||||||
const sigHeightPx = 2 * lineHeightPx;
|
// Signatur-Größe: kompakte Zielhöhe (~1,2 Zeilen statt fix 2) ODER schmaler Slot –
|
||||||
|
// gleichmäßig skalieren. Über signatureOffsets[key].scale je Signatur anpassbar.
|
||||||
const sigSlotW = maxWidthPx / 3; // Breite pro Signatur-Slot
|
const sigSlotW = maxWidthPx / 3; // Breite pro Signatur-Slot
|
||||||
const sigScaleH = sigHeightPx / SIG_CANVAS_H;
|
const sigScale = Math.min((lineHeightPx * 1.2) / SIG_CANVAS_H, sigSlotW / SIG_CANVAS_W);
|
||||||
const sigScaleW = sigSlotW / SIG_CANVAS_W;
|
// Standard-Abstand ober-/unterhalb der Signatur = halber Zeilenabstand.
|
||||||
const sigScale = Math.min(sigScaleH, sigScaleW); // gleichmäßig skalieren
|
// Pro Signatur über signatureOffsets[key].spacing (mm) überschreibbar.
|
||||||
const sigPaddingPx = lineHeightPx * 0.3; // kleiner Abstand ober/unterhalb
|
const defaultSpacingPx = lineHeightPx * 0.5;
|
||||||
|
|
||||||
const rawText = String(text || '');
|
const rawText = String(text || '');
|
||||||
const segments = [];
|
const segments = [];
|
||||||
@@ -182,17 +183,19 @@ 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) {
|
||||||
const seg = segments[si];
|
const seg = segments[si];
|
||||||
|
|
||||||
if (seg.type === 'text') {
|
if (seg.type === 'text') {
|
||||||
|
// Leerzeilen direkt an der Signatur-Grenze entfernen – sonst „fressen" die
|
||||||
|
// \n\n um [[signatur1]] zusätzlichen Platz. Abstand regelt NUR das spacing.
|
||||||
const trimmed = seg.content.replace(/^\n+/, '').replace(/\n+$/, '');
|
const trimmed = seg.content.replace(/^\n+/, '').replace(/\n+$/, '');
|
||||||
if (!trimmed) { si++; continue; }
|
if (!trimmed) { si++; continue; }
|
||||||
const lines = wrapTextToLinesByWidth({
|
const lines = wrapTextToLinesByWidth({
|
||||||
text: seg.content,
|
text: trimmed,
|
||||||
maxWidthPx,
|
maxWidthPx,
|
||||||
fontFileName: fontConfig.file,
|
fontFileName: fontConfig.file,
|
||||||
fontSizePx,
|
fontSizePx,
|
||||||
@@ -217,13 +220,25 @@ function generateLetterSVG(text, format, options = {}) {
|
|||||||
totalLineCount += lines.length;
|
totalLineCount += lines.length;
|
||||||
si++;
|
si++;
|
||||||
} else {
|
} else {
|
||||||
// Aufeinanderfolgende Signaturen als Zeile nebeneinander rendern
|
// Aufeinanderfolgende Signaturen als Zeile nebeneinander rendern.
|
||||||
const sigRow = [];
|
const sigRow = [];
|
||||||
while (si < segments.length && segments[si].type === 'sig') {
|
while (si < segments.length && segments[si].type === 'sig') {
|
||||||
sigRow.push(segments[si]);
|
sigRow.push(segments[si]);
|
||||||
si++;
|
si++;
|
||||||
}
|
}
|
||||||
currentY += sigPaddingPx;
|
// Tatsächlich gerenderte Höhe der Zeile + individueller Abstand je Signatur
|
||||||
|
// (Default halber Zeilenabstand). So wird nur der real benötigte Platz
|
||||||
|
// reserviert statt fix 2 Zeilen – Signaturen „fressen" keinen Platz mehr.
|
||||||
|
let rowHeightPx = 0;
|
||||||
|
let spacingPx = defaultSpacingPx;
|
||||||
|
for (const sigSeg of sigRow) {
|
||||||
|
const off = signatureOffsets[sigSeg.key] || {};
|
||||||
|
const sc = Number(off.scale) > 0 ? Number(off.scale) : 1;
|
||||||
|
if (signatures[sigSeg.key]) rowHeightPx = Math.max(rowHeightPx, SIG_CANVAS_H * sigScale * sc);
|
||||||
|
if (off.spacing != null && off.spacing !== '') spacingPx = Math.max(0, mmToPx(Number(off.spacing)));
|
||||||
|
}
|
||||||
|
if (rowHeightPx <= 0) rowHeightPx = lineHeightPx; // keine SVG → eine Platzhalterzeile
|
||||||
|
currentY += spacingPx;
|
||||||
sigRow.forEach((sigSeg, slotIdx) => {
|
sigRow.forEach((sigSeg, slotIdx) => {
|
||||||
const svgString = signatures[sigSeg.key] || null;
|
const svgString = signatures[sigSeg.key] || null;
|
||||||
if (svgString) {
|
if (svgString) {
|
||||||
@@ -237,8 +252,8 @@ function generateLetterSVG(text, format, options = {}) {
|
|||||||
if (sigEl) allSvgElements.push(sigEl);
|
if (sigEl) allSvgElements.push(sigEl);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
currentY += sigHeightPx + sigPaddingPx;
|
currentY += rowHeightPx + spacingPx;
|
||||||
totalLineCount += 2; // ganze Zeile zählt als 2 Zeilen, unabhängig von Anzahl
|
totalLineCount += Math.max(1, Math.ceil((2 * spacingPx + rowHeightPx) / lineHeightPx));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -606,7 +621,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);
|
||||||
@@ -666,7 +681,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)) {
|
||||||
|
|||||||
@@ -88,6 +88,16 @@ async function fetchOrdersMinimal(ids) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Empfängerzeilen mehrerer Aufträge, je Auftrag nach Briefnummer sortiert
|
||||||
|
* (dieselbe Reihenfolge wie bei der Generierung in fetchOrder). */
|
||||||
|
async function fetchEntriesForOrders(ids) {
|
||||||
|
const idList = ids.map((v) => encodeURIComponent(v)).join(',');
|
||||||
|
return (await directusFetch(
|
||||||
|
`/items/order_entries?filter[order][_in]=${idList}&sort=letter_number&limit=-1` +
|
||||||
|
'&fields=order,letter_number,salutation,first_name,last_name,street,house_no,zip,city,country,free_text',
|
||||||
|
)) || [];
|
||||||
|
}
|
||||||
|
|
||||||
/** Lädt eine Directus-Datei (z. B. hochgeladenes Brief-PDF) als Buffer. */
|
/** Lädt eine Directus-Datei (z. B. hochgeladenes Brief-PDF) als Buffer. */
|
||||||
async function fetchAssetBuffer(fileId) {
|
async function fetchAssetBuffer(fileId) {
|
||||||
requireConfig();
|
requireConfig();
|
||||||
@@ -129,4 +139,4 @@ async function markBatchBundled(ids, bundleName) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { fetchOrder, updateOrder, addStatusHistory, fetchRenderFormats, fetchOrdersMinimal, fetchAssetBuffer, fetchBatchPending, markBatchBundled };
|
module.exports = { fetchOrder, updateOrder, addStatusHistory, fetchRenderFormats, fetchOrdersMinimal, fetchEntriesForOrders, fetchAssetBuffer, fetchBatchPending, markBatchBundled };
|
||||||
|
|||||||
Reference in New Issue
Block a user