Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b21608ca4 | ||
|
|
d5a051befc | ||
|
|
17eebcfe6a | ||
|
|
9984b822aa | ||
|
|
29021281bb | ||
|
|
a882bf37f5 |
@@ -17,7 +17,7 @@ const { replacePlaceholders } = require('../../services/placeholder-service');
|
||||
|
||||
// Directus-Formatschlüssel → Backend-Formate
|
||||
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. */
|
||||
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 = {
|
||||
finalizeOrder,
|
||||
generateOrder,
|
||||
@@ -605,4 +712,5 @@ module.exports = {
|
||||
uploadMotif,
|
||||
uploadOrderFile,
|
||||
registerOrder,
|
||||
parseRecipients,
|
||||
};
|
||||
|
||||
@@ -133,6 +133,13 @@ router.post('/files', authenticateApiToken, uploadOrderFile.single('file'), orde
|
||||
*/
|
||||
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
|
||||
* Generiert einen Auftrag, dessen Daten in Directus liegen.
|
||||
|
||||
@@ -9,9 +9,11 @@ const FONT_SIZE_PX = 26;
|
||||
const DEFAULT_LINE_LIMITS = { a4: 27, a5p: 19, a5l: 13, a6p: 14, a6l: 11, dinlang_karte: 11 };
|
||||
const DEFAULT_FORMAT_LAYOUTS = {
|
||||
a4: { marginTopMm: 25, marginLeftMm: 20, lineHeightFactor: 1.35 },
|
||||
a5p: { marginTopMm: 20, marginLeftMm: 15, lineHeightFactor: 1.35 },
|
||||
a5l: { marginTopMm: 20, marginLeftMm: 15, lineHeightFactor: 1.35 },
|
||||
dinlang_karte: { marginTopMm: 8, marginLeftMm: 10, lineHeightFactor: 1.2 },
|
||||
// A5 greift an der KURZEN (148 mm) Seite: hoch → unten, quer → rechts.
|
||||
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)
|
||||
@@ -19,6 +21,8 @@ const DEFAULT_FORMAT_LAYOUTS = {
|
||||
a6l: { marginTopMm: 8, marginLeftMm: 8, marginBottomMm: 14, lineHeightFactor: 1.2 },
|
||||
din_lang: { marginTopMm: 50, 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 = {
|
||||
a4: { widthMm: 210, heightMm: 297 },
|
||||
@@ -29,9 +33,10 @@ const DEFAULT_PAGE_FORMATS = {
|
||||
a6l: { widthMm: 148, heightMm: 105 },
|
||||
din_lang: { widthMm: 220, heightMm: 110 },
|
||||
c6: { widthMm: 162, heightMm: 114 },
|
||||
c4: { widthMm: 324, heightMm: 229 },
|
||||
};
|
||||
// Art des Formats (brief/umschlag/postkarte) – steuert, WAS generiert wird.
|
||||
const DEFAULT_KINDS = { a4: 'brief', a5p: 'brief', a5l: 'brief', a6p: 'brief', a6l: 'brief', dinlang_karte: '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.
|
||||
let LINE_LIMITS = { ...DEFAULT_LINE_LIMITS };
|
||||
|
||||
@@ -156,12 +156,13 @@ function generateLetterSVG(text, format, options = {}) {
|
||||
|
||||
// ── Pfad mit Signaturen: Text in Segmente aufteilen ───────────────────────
|
||||
// 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 sigScaleH = sigHeightPx / SIG_CANVAS_H;
|
||||
const sigScaleW = sigSlotW / SIG_CANVAS_W;
|
||||
const sigScale = Math.min(sigScaleH, sigScaleW); // gleichmäßig skalieren
|
||||
const sigPaddingPx = lineHeightPx * 0.3; // kleiner Abstand ober/unterhalb
|
||||
const sigScale = Math.min((lineHeightPx * 1.2) / SIG_CANVAS_H, sigSlotW / SIG_CANVAS_W);
|
||||
// Standard-Abstand ober-/unterhalb der Signatur = halber Zeilenabstand.
|
||||
// Pro Signatur über signatureOffsets[key].spacing (mm) überschreibbar.
|
||||
const defaultSpacingPx = lineHeightPx * 0.5;
|
||||
|
||||
const rawText = String(text || '');
|
||||
const segments = [];
|
||||
@@ -189,10 +190,12 @@ function generateLetterSVG(text, format, options = {}) {
|
||||
const seg = segments[si];
|
||||
|
||||
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+$/, '');
|
||||
if (!trimmed) { si++; continue; }
|
||||
const lines = wrapTextToLinesByWidth({
|
||||
text: seg.content,
|
||||
text: trimmed,
|
||||
maxWidthPx,
|
||||
fontFileName: fontConfig.file,
|
||||
fontSizePx,
|
||||
@@ -217,13 +220,25 @@ function generateLetterSVG(text, format, options = {}) {
|
||||
totalLineCount += lines.length;
|
||||
si++;
|
||||
} else {
|
||||
// Aufeinanderfolgende Signaturen als Zeile nebeneinander rendern
|
||||
// Aufeinanderfolgende Signaturen als Zeile nebeneinander rendern.
|
||||
const sigRow = [];
|
||||
while (si < segments.length && segments[si].type === 'sig') {
|
||||
sigRow.push(segments[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) => {
|
||||
const svgString = signatures[sigSeg.key] || null;
|
||||
if (svgString) {
|
||||
@@ -237,8 +252,8 @@ function generateLetterSVG(text, format, options = {}) {
|
||||
if (sigEl) allSvgElements.push(sigEl);
|
||||
}
|
||||
});
|
||||
currentY += sigHeightPx + sigPaddingPx;
|
||||
totalLineCount += 2; // ganze Zeile zählt als 2 Zeilen, unabhängig von Anzahl
|
||||
currentY += rowHeightPx + spacingPx;
|
||||
totalLineCount += Math.max(1, Math.ceil((2 * spacingPx + rowHeightPx) / lineHeightPx));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user