Upload Neu

This commit is contained in:
s4luorth
2026-05-04 09:40:27 +02:00
parent a9c86c6dad
commit 290969f848
6 changed files with 499 additions and 291 deletions

View File

@@ -49,8 +49,11 @@ function getProductDefinitions() {
products[key] = {
...baseConfig,
label: backendSettings.label || key,
description: backendSettings.description || 'Professionelle handgeschriebene Korrespondenz',
basePrice: parseFloat(backendSettings.base_price) || 2.50,
description:
backendSettings.description ||
"Professionelle handgeschriebene Korrespondenz",
basePrice: parseFloat(backendSettings.base_price) || 2.5,
imageUrl: backendSettings.image_url || "",
};
}
@@ -86,21 +89,22 @@ export function deriveContextFromUrl(search) {
}
// Quantity aus URL
const quantityParam = q.get('quantity');
const quantityParam = q.get("quantity");
const quantity = quantityParam ? parseInt(quantityParam, 10) : null;
// Format aus URL (a4, a6h = A6 Hochformat, a6q = A6 Querformat)
const formatParam = q.get('format')?.toLowerCase();
const formatParam = q.get("format")?.toLowerCase();
let format = null;
if (formatParam === 'a4') format = 'a4';
else if (formatParam === 'a6h') format = 'a6p'; // Hochformat
else if (formatParam === 'a6q') format = 'a6l'; // Querformat
if (formatParam === "a4") format = "a4";
else if (formatParam === "a6h")
format = "a6p"; // Hochformat
else if (formatParam === "a6q") format = "a6l"; // Querformat
// noPrice Parameter (Preise ausblenden)
const noPrice = q.has('noPrice') || q.has('noprice');
const noPrice = q.has("noPrice") || q.has("noprice");
// noLimits Parameter (keine Mindestmengen)
const noLimits = q.has('noLimits') || q.has('nolimits');
const noLimits = q.has("noLimits") || q.has("nolimits");
return {
urlParam: urlParam || null,
@@ -162,11 +166,14 @@ export function createInitialState(ctx) {
}
// Standardmenge auf beste Preismenge (normalQuantity) setzen, außer URL-Parameter
const dynamicPricing = window.SkriftConfigurator?.settings?.dynamic_pricing || {};
const dynamicPricing =
window.SkriftConfigurator?.settings?.dynamic_pricing || {};
const isB2B = initialCustomerType === "business";
const defaultQuantity = urlQuantity || (isB2B
? (dynamicPricing.business_normal_quantity || 200)
: (dynamicPricing.private_normal_quantity || 50));
const defaultQuantity =
urlQuantity ||
(isB2B
? dynamicPricing.business_normal_quantity || 200
: dynamicPricing.private_normal_quantity || 50);
// Format aus URL oder null
const initialFormat = urlFormat || null;
@@ -217,6 +224,8 @@ export function createInitialState(ctx) {
// Inhalt
contentCreateMode: null, // 'self' | 'textservice'
letterText: "",
font: "tilda",
envelopeFont: "tilda",
// Motiv
motifNeed: null,
@@ -232,7 +241,7 @@ export function createInitialState(ctx) {
recipientRows: [],
// Adressmodus: 'classic' (Name, Anschrift) oder 'free' (5 freie Zeilen)
addressMode: 'classic',
addressMode: "classic",
// Freie Adresszeilen (separat gespeichert, damit beim Wechsel nichts verloren geht)
freeAddressRows: [],
placeholders: {
@@ -314,9 +323,8 @@ export function calcEffectiveEnvelopeType(state) {
}
export function getAvailableProductsForCustomerType(customerType) {
return Object.values(PRODUCT_BY_PARAM).filter(
(p) => p.category === customerType
);
const fresh = getProductDefinitions();
return Object.values(fresh).filter((p) => p.category === customerType);
}
export function syncPlaceholders(state) {
@@ -406,109 +414,17 @@ export function validateStep(state) {
// Versandart muss gewählt sein
if (!state.answers.shippingMode) return false;
// Bei Versand durch Skrift ist Umschlag automatisch
if (state.answers.shippingMode === "direct") {
// Automatisch gesetzt, keine Validierung nötig für envelope
if (!state.answers.envelopeMode) return false;
// Bei Follow-ups: keine Empfängerdaten-Validierung (kommt aus CRM)
// Bei regulären Produkten: Empfängerdaten müssen vorhanden sein
if (!isFollowups(state)) {
// Empfängerdaten validieren für reguläre Produkte
if (state.answers.envelopeMode === "recipientData") {
const addressMode = state.addressMode || 'classic';
if (addressMode === 'free') {
// Freie Adresse: mindestens Zeile 1 muss ausgefüllt sein
const rows = state.freeAddressRows || [];
if (rows.length !== requiredRowCount(state)) return false;
for (const r of rows) {
if (!r) return false;
// Mindestens Zeile 1 muss ausgefüllt sein
if (!String(r.line1 || "").trim()) return false;
}
} else {
// Klassische Adresse
const rows = state.recipientRows || [];
if (rows.length !== requiredRowCount(state)) return false;
for (const r of rows) {
if (!r) return false;
const required = [
"firstName",
"lastName",
"street",
"houseNumber",
"zip",
"city",
"country",
];
for (const k of required) {
if (!String(r[k] || "").trim()) return false;
}
}
}
}
}
} else {
if (state.answers.shippingMode !== "direct") {
// Bulk versand
if (state.answers.envelope === null) return false;
if (state.answers.envelope === true) {
// Beschriftungsmodus muss gewählt sein
if (!state.answers.envelopeMode) return false;
// Empfängerdaten validieren für Bulk-Versand (nur wenn Umschlag gewählt)
if (state.answers.envelopeMode === "recipientData") {
const addressMode = state.addressMode || 'classic';
if (addressMode === 'free') {
// Freie Adresse: mindestens Zeile 1 muss ausgefüllt sein
const rows = state.freeAddressRows || [];
if (rows.length !== requiredRowCount(state)) return false;
for (const r of rows) {
if (!r) return false;
if (!String(r.line1 || "").trim()) return false;
}
} else {
// Klassische Adresse
const rows = state.recipientRows || [];
if (rows.length !== requiredRowCount(state)) return false;
for (const r of rows) {
if (!r) return false;
const required = [
"firstName",
"lastName",
"street",
"houseNumber",
"zip",
"city",
"country",
];
for (const k of required) {
if (!String(r[k] || "").trim()) return false;
}
}
}
}
// Custom Text validieren (nur wenn Umschlag gewählt)
if (state.answers.envelopeMode === "customText") {
if (!state.answers.envelopeCustomText?.trim()) return false;
if (state.placeholders.envelope.length > 0) {
for (const ph of state.placeholders.envelope) {
const arr = state.placeholderValues[ph] || [];
if (arr.length !== requiredRowCount(state)) return false;
if (arr.some((v) => !String(v || "").trim())) return false;
}
}
}
}
// Wenn envelope === false, keine weitere Validierung nötig
}
return true;
@@ -520,31 +436,6 @@ export function validateStep(state) {
// Wenn self, muss Text vorhanden sein
if (state.answers.contentCreateMode === "self") {
if (!state.answers.letterText?.trim()) return false;
// Platzhalter validieren
const usedLetter = extractPlaceholders(state.answers.letterText);
// Platzhalter validieren
// "vorname", "name", "ort" können immer aus recipientRows kommen (bei shippingMode=direct oder envelopeMode=recipientData)
const recipientPlaceholders = new Set(["vorname", "name", "ort"]);
const hasRecipientData = state.answers.shippingMode === "direct" || state.answers.envelopeMode === "recipientData";
// Platzhalter aus dem Umschlag
const envSet = new Set(state.placeholders.envelope || []);
// Platzhalter die validiert werden müssen (nicht aus Umschlag, nicht aus recipientRows)
const needed = usedLetter.filter((p) => {
if (envSet.has(p)) return false; // aus Umschlag
if (hasRecipientData && recipientPlaceholders.has(p)) return false; // aus recipientRows
return true;
});
// Nur die übrigen Platzhalter validieren
for (const ph of needed) {
const arr = state.placeholderValues[ph] || [];
if (arr.length !== requiredRowCount(state)) return false;
if (arr.some((v) => !String(v || "").trim())) return false;
}
}
// Motiv Validierung
@@ -594,7 +485,14 @@ export function validateStep(state) {
if (state.order.shippingDifferent) {
const sh = state.order.shipping;
// Shipping braucht kein E-Mail/Telefon - nur Adressfelder
const shippingReq = ["firstName", "lastName", "street", "zip", "city", "country"];
const shippingReq = [
"firstName",
"lastName",
"street",
"zip",
"city",
"country",
];
for (const k of shippingReq) {
if (!String(sh[k] || "").trim()) return false;
}
@@ -614,17 +512,17 @@ export function validateStep(state) {
// Preisrelevante Felder die eine Neuberechnung auslösen
const PRICE_RELEVANT_FIELDS = new Set([
'quantity',
'format',
'shippingMode',
'envelope',
'envelopeMode',
'motifSource',
'motifNeed',
'contentCreateMode',
'followupYearlyVolume',
'followupCreateMode',
'customerType',
"quantity",
"format",
"shippingMode",
"envelope",
"envelopeMode",
"motifSource",
"motifNeed",
"contentCreateMode",
"followupYearlyVolume",
"followupCreateMode",
"customerType",
]);
/**
@@ -632,7 +530,7 @@ const PRICE_RELEVANT_FIELDS = new Set([
*/
function hasPriceRelevantChanges(patch) {
if (!patch) return false;
return Object.keys(patch).some(key => PRICE_RELEVANT_FIELDS.has(key));
return Object.keys(patch).some((key) => PRICE_RELEVANT_FIELDS.has(key));
}
/**
@@ -647,19 +545,20 @@ function countCountryDistribution(rows, addressMode) {
for (const row of rows) {
if (!row) continue;
let country = '';
if (addressMode === 'free') {
country = row.line5 || '';
let country = "";
if (addressMode === "free") {
country = row.line5 || "";
} else {
country = row.country || '';
country = row.country || "";
}
const countryLower = country.toLowerCase().trim();
const isDomestic = !countryLower ||
countryLower === 'deutschland' ||
countryLower === 'germany' ||
countryLower === 'de' ||
countryLower === 'ger';
const isDomestic =
!countryLower ||
countryLower === "deutschland" ||
countryLower === "germany" ||
countryLower === "de" ||
countryLower === "ger";
if (isDomestic) {
domestic++;
@@ -710,6 +609,11 @@ export function reducer(state, action) {
if (p.urlFormat !== null) delete answerPatch.format;
next.answers = { ...next.answers, ...answerPatch };
// Auto-Logik: Bei Direktversand immer envelopeMode sicherstellen
if (next.answers.shippingMode === "direct" && !next.answers.envelopeMode) {
next.answers = { ...next.answers, envelope: true, envelopeMode: "recipientData" };
}
// Empfängerdaten
if (Array.isArray(p.recipientRows)) {
next.recipientRows = p.recipientRows;
@@ -737,7 +641,11 @@ export function reducer(state, action) {
}
// Step wiederherstellen (nur wenn nicht im PRODUCT Step)
if (typeof p.step === "number" && p.step >= 0 && p.currentStep !== STEPS.PRODUCT) {
if (
typeof p.step === "number" &&
p.step >= 0 &&
p.currentStep !== STEPS.PRODUCT
) {
next.step = p.step;
next.history = [];
for (let i = 0; i < p.step; i++) {
@@ -745,6 +653,12 @@ export function reducer(state, action) {
}
}
// Wenn nur ein Format verfügbar und keins gespeichert: automatisch setzen
const hydrateFormats = next.ctx?.product?.formats || [];
if (hydrateFormats.length === 1 && !next.answers.format) {
next.answers = { ...next.answers, format: hydrateFormats[0] };
}
// Quote einmal am Ende berechnen
next = recalculateQuote(next);
@@ -773,6 +687,11 @@ export function reducer(state, action) {
next.answers = { ...next.answers, format: null };
}
// Wenn nur ein Format verfügbar: automatisch setzen
const availFormats = action.product?.formats || [];
if (availFormats.length === 1 && !next.answers.format) {
next.answers = { ...next.answers, format: availFormats[0] };
}
// Follow-ups: Automatisch Direktversand setzen
if (action.product?.key === "follow-ups") {
next.answers = { ...next.answers, shippingMode: "direct" };
@@ -796,6 +715,11 @@ export function reducer(state, action) {
next.answers = { ...next.answers, format: null };
}
// Wenn nur ein Format verfügbar: automatisch setzen
const availFormats = action.product?.formats || [];
if (availFormats.length === 1 && !next.answers.format) {
next.answers = { ...next.answers, format: availFormats[0] };
}
// Follow-ups: Automatisch Direktversand setzen
if (action.product?.key === "follow-ups") {
next.answers = { ...next.answers, shippingMode: "direct" };
@@ -813,7 +737,7 @@ export function reducer(state, action) {
// WICHTIG: Preview Cache löschen wenn envelopeMode geändert wird
if (action.patch && "envelopeMode" in action.patch) {
console.log('[State] envelopeMode changed, clearing envelope previews');
console.log("[State] envelopeMode changed, clearing envelope previews");
if (window.envelopePreviewManager) {
window.envelopePreviewManager.currentBatchPreviews = [];
window.envelopePreviewManager.currentDocIndex = 0;
@@ -834,10 +758,13 @@ export function reducer(state, action) {
};
// Bei Einzelversand: Leere Länder-Felder auf "Deutschland" setzen (Default)
if (Array.isArray(next.recipientRows)) {
next.recipientRows = next.recipientRows.map(row => ({
next.recipientRows = next.recipientRows.map((row) => ({
...row,
// Nur setzen wenn Feld leer ist
country: row.country && row.country.trim() !== "" ? row.country : "Deutschland"
country:
row.country && row.country.trim() !== ""
? row.country
: "Deutschland",
}));
}
}
@@ -848,20 +775,21 @@ export function reducer(state, action) {
// Nur setzen wenn Menge noch nicht vom Benutzer geändert wurde
// (d.h. wenn sie noch dem alten Default entspricht oder nicht gesetzt ist)
const currentQty = next.answers.quantity;
const dynamicPricing = window.SkriftConfigurator?.settings?.dynamic_pricing || {};
const dynamicPricing =
window.SkriftConfigurator?.settings?.dynamic_pricing || {};
// Alte Default-Werte berechnen
const wasB2B = state.answers.customerType === "business";
const oldDefaultQty = wasB2B
? (dynamicPricing.business_normal_quantity || 200)
: (dynamicPricing.private_normal_quantity || 50);
? dynamicPricing.business_normal_quantity || 200
: dynamicPricing.private_normal_quantity || 50;
// Nur überschreiben wenn Menge noch dem alten Default entspricht oder nicht gesetzt ist
if (!currentQty || currentQty === oldDefaultQty || currentQty === 1) {
const isB2B = action.patch.customerType === "business";
const newDefaultQuantity = isB2B
? (dynamicPricing.business_normal_quantity || 200)
: (dynamicPricing.private_normal_quantity || 50);
? dynamicPricing.business_normal_quantity || 200
: dynamicPricing.private_normal_quantity || 50;
next.answers = { ...next.answers, quantity: newDefaultQuantity };
}
}
@@ -885,7 +813,11 @@ export function reducer(state, action) {
// Auto-Logik für motifNeed: Wenn kein Motiv gewählt, motifSource zurücksetzen
if (action.patch && "motifNeed" in action.patch) {
if (action.patch.motifNeed === false) {
next.answers = { ...next.answers, motifSource: null, serviceDesign: false };
next.answers = {
...next.answers,
motifSource: null,
serviceDesign: false,
};
}
}
@@ -893,7 +825,10 @@ export function reducer(state, action) {
if (action.patch && "format" in action.patch) {
if (action.patch.format === "a4") {
// Wenn upload oder design ausgewählt war, auf printed umstellen
if (next.answers.motifSource === "upload" || next.answers.motifSource === "design") {
if (
next.answers.motifSource === "upload" ||
next.answers.motifSource === "design"
) {
next.answers = { ...next.answers, motifSource: "printed" };
}
}
@@ -914,9 +849,18 @@ export function reducer(state, action) {
// Quote nur neu berechnen wenn sich Inland/Ausland-Verteilung geändert hat
let next = { ...state, recipientRows: action.rows };
if (state.answers?.shippingMode === "direct") {
const oldDist = countCountryDistribution(state.recipientRows, state.addressMode);
const newDist = countCountryDistribution(action.rows, state.addressMode);
if (oldDist.domestic !== newDist.domestic || oldDist.international !== newDist.international) {
const oldDist = countCountryDistribution(
state.recipientRows,
state.addressMode,
);
const newDist = countCountryDistribution(
action.rows,
state.addressMode,
);
if (
oldDist.domestic !== newDist.domestic ||
oldDist.international !== newDist.international
) {
next = recalculateQuote(next);
}
}
@@ -936,9 +880,12 @@ export function reducer(state, action) {
// Quote nur neu berechnen wenn sich Inland/Ausland-Verteilung geändert hat
let next = { ...state, freeAddressRows: action.rows };
if (state.answers?.shippingMode === "direct") {
const oldDist = countCountryDistribution(state.freeAddressRows, 'free');
const newDist = countCountryDistribution(action.rows, 'free');
if (oldDist.domestic !== newDist.domestic || oldDist.international !== newDist.international) {
const oldDist = countCountryDistribution(state.freeAddressRows, "free");
const newDist = countCountryDistribution(action.rows, "free");
if (
oldDist.domestic !== newDist.domestic ||
oldDist.international !== newDist.international
) {
next = recalculateQuote(next);
}
}
@@ -967,8 +914,35 @@ export function reducer(state, action) {
return { ...state, placeholderValues: action.values || {} };
}
case "SYNC_GLOBAL_STATE": {
// Synchronisiert alle direkt mutierten Daten (aus window.currentGlobalState)
// in einem einzigen Dispatch ohne mehrfaches Re-Render
const p = action.payload || {};
let next = { ...state };
if (Array.isArray(p.recipientRows)) {
next.recipientRows = p.recipientRows;
}
if (Array.isArray(p.freeAddressRows)) {
next.freeAddressRows = p.freeAddressRows;
}
if (p.placeholderValues && typeof p.placeholderValues === "object") {
next.placeholderValues = p.placeholderValues;
}
// Quote neu berechnen falls relevant
if (next.answers?.shippingMode === "direct") {
next = recalculateQuote(next);
}
return next;
}
case "SET_ORDER": {
const nextState = { ...state, order: { ...state.order, ...action.patch } };
const nextState = {
...state,
order: { ...state.order, ...action.patch },
};
// Quote neu berechnen wenn Gutschein geändert wurde
return recalculateQuote(nextState);
}
@@ -1000,7 +974,7 @@ export function reducer(state, action) {
const nextStep = Math.min(STEPS.REVIEW, state.step + 1);
// Nach oben scrollen
window.scrollTo({ top: 0, behavior: 'smooth' });
window.scrollTo({ top: 0, behavior: "smooth" });
return {
...state,
@@ -1015,7 +989,7 @@ export function reducer(state, action) {
const prev = hist[hist.length - 1];
// Nach oben scrollen
window.scrollTo({ top: 0, behavior: 'smooth' });
window.scrollTo({ top: 0, behavior: "smooth" });
return { ...state, step: prev, history: hist.slice(0, -1) };
}
@@ -1026,5 +1000,7 @@ export function reducer(state, action) {
}
export function listProducts() {
return Object.values(PRODUCT_BY_PARAM);
// Immer frisch laden damit Backend-Settings (inkl. imageUrl) verfügbar sind
const fresh = getProductDefinitions();
return Object.values(fresh);
}