import { econtCalculate } from './econt'; import { getDb } from './db'; export function getShippingConfig() { const db = getDb(); const rows = db.query("SELECT key, value FROM content WHERE key LIKE 'shipping_%' OR key = 'free_shipping_threshold'").all() as { key: string; value: string }[]; const cfg: Record = {}; for (const r of rows) cfg[r.key] = r.value; return { ratePerKg: parseInt(cfg.shipping_rate_per_kg || '500') || 500, // cents per kg freeThreshold: parseInt(cfg.free_shipping_threshold || '5000') || 5000, // cents }; } // Fixed courier rates (in euro cents) for orders up to 1 kg. Anything over // 1 kg falls back to the Econt API or the per-kg rate. const FIXED_ADDRESS_RATE = 522; // €5.22 - delivery to personal address const FIXED_OFFICE_RATE = 395; // €3.95 - delivery to office / APS locker const FIXED_RATE_MAX_KG = 1; // shippingCostCents returns shipping cost in stotinki (euro cents). // If econt is configured, calls the Econt API. Otherwise uses // the configurable per-kg rate with free-shipping threshold. export async function shippingCostCents( totalKg: number, subtotalCents: number, city?: string, courier?: string, codAmount?: number, officeDelivery?: boolean, ): Promise { try { const { freeThreshold } = getShippingConfig(); if (freeThreshold > 0 && subtotalCents >= freeThreshold) return 0; // fixed rate for packages up to 1 kg (not prorated) if (totalKg <= FIXED_RATE_MAX_KG) { return officeDelivery ? FIXED_OFFICE_RATE : FIXED_ADDRESS_RATE; } // try econt if configured const econtCfg = getEcontConfigured(); if (econtCfg && courier === 'econt' && city) { const result = await econtCalculate(city, totalKg, codAmount || 0, officeDelivery || false); if (!result.error) { return Math.round(result.totalPrice * 100); } } // fallback: per-kg rate const { ratePerKg } = getShippingConfig(); return Math.round(ratePerKg * totalKg); } catch { const { ratePerKg, freeThreshold } = getShippingConfig(); if (freeThreshold > 0 && subtotalCents >= freeThreshold) return 0; return Math.round(ratePerKg * totalKg); } } function getEcontConfigured(): boolean { try { const db = getDb(); const row = db.query("SELECT value FROM content WHERE key = 'econt_username'").get() as { value: string } | null; const pw = db.query("SELECT value FROM content WHERE key = 'econt_password'").get() as { value: string } | null; return !!(row?.value && pw?.value); } catch { return false; } } // sync version for stripe payment intent creation export function shippingCostCentsSync(totalKg: number, subtotalCents: number, officeDelivery = false): number { const { ratePerKg, freeThreshold } = getShippingConfig(); if (freeThreshold > 0 && subtotalCents >= freeThreshold) return 0; if (totalKg <= FIXED_RATE_MAX_KG) { return officeDelivery ? FIXED_OFFICE_RATE : FIXED_ADDRESS_RATE; } return Math.round(ratePerKg * totalKg); }