/* ========================================================================= * demo-session.js — DEMO-ONLY * Симулация на сървърна сесия за статичното демо (фаза 1). * Във фаза 2 (Spring MVC + Thymeleaf) ЦЕЛИЯТ този файл се заменя от * server session + model attributes (по правилата на salex: количката * живее в сесията на сървъра, цените идват от backend). * ========================================================================= */ (function () { 'use strict'; /* --- Демо данни (от референтния макет; фаза 2: идват от backend) ------ */ var DEMO = { company: { name: 'Агро Прим ЕООД', eik: '111583456', mol: 'Иван Петров', paymentTerms: 'отложено, по договорени падежи' }, addresses: [ { id: 'addr-1', label: 'гр. Монтана, ул. „Индустриална" 14', isDefault: true }, { id: 'addr-2', label: 'гр. Враца, бул. „Втори юни" 68', isDefault: false } ], paymentDueDates: ['20.07.2026', '20.08.2026', '20.09.2026'], orders: [ { number: 'ACM-2026-0031', date: '14.05.2026', total: 4218, status: 'Изпълнена', warehouseName: 'Монтана' }, { number: 'ACM-2026-0038', date: '26.06.2026', total: 11640, status: 'В изпълнение', warehouseName: 'Стара Загора' }, { number: 'ACM-2026-0042', date: '08.07.2026', total: 2890.5, status: 'Приета', warehouseName: 'Монтана' } ], nextOrderNumber: 'ACM-2026-0043', creditLimits: { warning: 15000, blocked: 25000 }, vat: 0.2, warehouses: [ { key: 'montana', name: 'Монтана', abbr: 'МО' }, { key: 'staraZagora', name: 'Стара Загора', abbr: 'СЗ' }, { key: 'ruse', name: 'Русе', abbr: 'РУ' }, { key: 'sofia', name: 'София', abbr: 'СФ' } ], stockStatus: { green: { label: 'Наличен', dot: 'bg-st-green' }, orange: { label: 'Ниски запаси', dot: 'bg-st-orange' }, red: { label: 'Няма наличност', dot: 'bg-st-red' }, grey: { label: 'Очаквана доставка', dot: 'bg-st-grey' } }, deliveryMethods: [ { method: 'pickup', label: 'Вземане от склад', note: 'безплатно', cost: 0 }, { method: 'company', label: 'Фирмен транспорт', note: '100,00 € (безплатен за поръчки над 3 000,00 €)', cost: 100, freeThreshold: 3000 }, { method: 'courier', label: 'Куриер', note: 'по тарифа на куриера', cost: null } ], brandColors: { 'Bayer': '#0E7C86', 'Syngenta': '#3A9E4B', 'Corteva': '#1F6FB2', 'BASF': '#C4442E', 'Summit Agro': '#0E9488', 'ADAMA': '#E0791B', 'Intermag': '#2563A8', 'Brandt': '#4B7A2A', 'Nufarm': '#C2410C', 'Limagrain': '#7A8B1F', 'Kelp Products': '#0F766E' }, categories: ['Растителна защита', 'Семена', 'Торове', 'Други'], cultures: ['Пшеница', 'Царевица', 'Слънчоглед', 'Рапица', 'Ечемик', 'Лозя', 'Зеленчуци', 'Люцерна'], packagingBuckets: ['до 1 л', '1–5 л', '5–20 л', '20+ л', 'кг', 'брой'] }; /* --- Валута (bg-BG, като в оригинала) ---------------------------------- */ var nf = new Intl.NumberFormat('bg-BG', { minimumFractionDigits: 2, maximumFractionDigits: 2, useGrouping: 'always' }); function fmtPrice(v) { return nf.format(v) + ' €'; } /* --- Количка (localStorage; фаза 2: server session) -------------------- */ var CART_KEY = 'acm-cart'; function readCart() { try { var raw = window.localStorage.getItem(CART_KEY); if (!raw) return []; var arr = JSON.parse(raw); if (!Array.isArray(arr)) return []; return arr.filter(function (i) { return i && typeof i.productId === 'string' && typeof i.qty === 'number' && findProduct(i.productId); }).map(function (i) { return { productId: i.productId, qty: Math.max(1, Math.floor(i.qty)) }; }); } catch (e) { return []; } } function writeCart(items) { try { window.localStorage.setItem(CART_KEY, JSON.stringify(items)); } catch (e) {} document.dispatchEvent(new CustomEvent('acm:cart-changed')); } function findProduct(id) { var list = window.ACM_PRODUCTS || []; for (var i = 0; i < list.length; i++) if (list[i].id === id) return list[i]; return null; } var Cart = { items: readCart, add: function (id, qty) { if (!findProduct(id)) return; qty = Math.max(1, Math.floor(qty || 1)); var items = readCart(); var ex = items.find(function (i) { return i.productId === id; }); if (ex) ex.qty += qty; else items.push({ productId: id, qty: qty }); writeCart(items); }, setQty: function (id, qty) { qty = Math.max(1, Math.floor(qty || 1)); var items = readCart().map(function (i) { return i.productId === id ? { productId: id, qty: qty } : i; }); writeCart(items); }, remove: function (id) { writeCart(readCart().filter(function (i) { return i.productId !== id; })); }, clear: function () { writeCart([]); }, restore: function (items) { writeCart(items); }, totalUnits: function () { return readCart().reduce(function (s, i) { return s + i.qty; }, 0); }, subtotal: function () { return readCart().reduce(function (s, i) { var p = findProduct(i.productId); return p ? s + p.price.perBox * i.qty : s; }, 0); } }; /* --- Доставка / кредит (както в оригиналния макет) --------------------- */ function deliveryCost(method, subtotal) { var m = DEMO.deliveryMethods.find(function (d) { return d.method === method; }); if (!m || m.cost === null) return 0; if (m.freeThreshold && subtotal >= m.freeThreshold) return 0; return m.cost; } function creditState(subtotal) { if (subtotal > DEMO.creditLimits.blocked) return 'blocked'; if (subtotal > DEMO.creditLimits.warning) return 'warning'; return 'info'; } /* --- Публичен API ------------------------------------------------------- */ window.ACM = window.ACM || {}; window.ACM.demo = DEMO; window.ACM.cart = Cart; window.ACM.fmtPrice = fmtPrice; window.ACM.findProduct = findProduct; window.ACM.deliveryCost = deliveryCost; window.ACM.creditState = creditState; })();