diff --git a/App.jsx b/App.jsx index 062fd75..330d9e4 100644 --- a/App.jsx +++ b/App.jsx @@ -5,7 +5,7 @@ import { Building2, Globe, Phone, Save, RefreshCw, LayoutDashboard, Users, Package, Layers, Zap, Tag, Inbox, Paperclip, Menu, LogOut, GripVertical, BookOpen, FileText, FolderTree, Lock, Sparkles, Printer, Image as ImageIcon, - ShieldCheck, Settings2, Boxes, Download, Wifi, Radio, QrCode, Folder, FolderPlus, Factory, UploadCloud + ShieldCheck, Settings2, Boxes, Download, Wifi, Radio, QrCode, Folder, FolderPlus, Factory, UploadCloud, ClipboardList } from 'lucide-react'; import { MicUploadPage } from './mic-upload/MicUploadPage'; import { ImageToolPage } from './mic-upload/ImageToolPage'; @@ -254,7 +254,7 @@ const COUNTRIES = [ const COUNTRY_BY_NAME = Object.fromEntries(COUNTRIES.map(c => [c.name, c])); const SAVE_KEY_LABEL = { 'crm:customers': '客户', 'crm:products': '产品', 'crm:quotes': '报价单', 'crm:sellerProfiles': '卖方信息', 'crm:certifications': '授权', 'crm:productCategories': '产品分组', 'crm:packingLists': '箱单', 'crm:catalogDocs': '产品目录', 'crm:jmsLines': 'Just My Socks', 'crm:backPanelTemplates': '后板图模板', 'crm:suppliers': '供应商', 'crm:webDetailTemplates': '模板', 'crm:webAssets': '网站图片', 'crm:webNews': '近期动态', 'crm:webPackSpecs': 'Packing List' }; -const STORAGE_KEYS = { customers: 'crm:customers', products: 'crm:products', quotes: 'crm:quotes', sellerProfiles: 'crm:sellerProfiles', certifications: 'crm:certifications', productCategories: 'crm:productCategories', packingLists: 'crm:packingLists', catalogDocs: 'crm:catalogDocs', jmsLines: 'crm:jmsLines', backPanelTemplates: 'crm:backPanelTemplates', suppliers: 'crm:suppliers', webDetailTemplates: 'crm:webDetailTemplates', webAssets: 'crm:webAssets', webNews: 'crm:webNews', webPackSpecs: 'crm:webPackSpecs' }; +const STORAGE_KEYS = { customers: 'crm:customers', products: 'crm:products', quotes: 'crm:quotes', sellerProfiles: 'crm:sellerProfiles', certifications: 'crm:certifications', productCategories: 'crm:productCategories', packingLists: 'crm:packingLists', catalogDocs: 'crm:catalogDocs', jmsLines: 'crm:jmsLines', backPanelTemplates: 'crm:backPanelTemplates', suppliers: 'crm:suppliers', webDetailTemplates: 'crm:webDetailTemplates', webAssets: 'crm:webAssets', webNews: 'crm:webNews', webPackSpecs: 'crm:webPackSpecs', orders: 'crm:orders' }; const blankCustomer = () => ({ id: 'c_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7), @@ -1647,8 +1647,13 @@ async function loadAll() { const wps = await storageGet(STORAGE_KEYS.webPackSpecs); if (wps && wps.value) webPackSpecs = JSON.parse(wps.value) || []; } catch (e) { if (!e.notFound) failed.push(e.message); } + let orders = []; + try { + const od = await storageGet(STORAGE_KEYS.orders); + if (od && od.value) orders = JSON.parse(od.value) || []; + } catch (e) { if (!e.notFound) failed.push(e.message); } if (failed.length) { const err = new Error(failed[0]); err.loadFailed = true; throw err; } - return { customers, products, quotes, sellerProfiles, certifications, productCategories, packingLists, catalogDocs, jmsLines, backPanelTemplates, suppliers, webDetailTemplates, webAssets, webNews, webPackSpecs }; + return { orders, customers, products, quotes, sellerProfiles, certifications, productCategories, packingLists, catalogDocs, jmsLines, backPanelTemplates, suppliers, webDetailTemplates, webAssets, webNews, webPackSpecs }; } /* -------------------------------- styles -------------------------------- */ @@ -1852,6 +1857,137 @@ const Styles = () => ( } .crm-sidebar-sub { padding-left: 38px !important; font-size: 13px; } .crm-sidebar-item.active { color: var(--copper); background: var(--copper-soft); border-left-color: var(--copper); } + .ord-side-badge { margin-left: auto; min-width: 18px; height: 18px; padding: 0 5px; border-radius: 9px; background: var(--led-red); color: #fff; font-size: 10.5px; font-weight: 700; display: inline-flex; align-items: center; justify-content: center; } + + /* ---------- 订单管理 ---------- */ + .ord-layout { grid-template-columns: 340px 1fr; } + .ord-layout .input, .ord-layout .select, .ord-layout .textarea { box-sizing: border-box; max-width: 100%; } + @media (max-width: 1000px) { .ord-layout { grid-template-columns: minmax(0, 1fr); } } + .ord-layout > div { min-width: 0; } + .ord-tbl-wrap { overflow-x: auto; } + .ord-filters { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; } + .ord-filters button { border: 1px solid var(--line); background: var(--panel); border-radius: 16px; padding: 4px 10px; font-size: 12px; cursor: pointer; color: var(--ink-soft); display: inline-flex; gap: 5px; align-items: center; } + .ord-filters button.on { background: var(--ink); border-color: var(--ink); color: #fff; } + .ord-filters em { font-style: normal; font-size: 10.5px; opacity: .75; } + .ord-row { cursor: pointer; align-items: flex-start; } + .ord-mini { height: 4px; border-radius: 2px; background: var(--line); margin-top: 7px; overflow: hidden; } + .ord-mini i { display: block; height: 100%; background: var(--led-green); border-radius: 2px; } + .ord-status { font-size: 12px; font-weight: 700; padding: 5px 11px; border-radius: 14px; white-space: nowrap; background: var(--led-blue-bg); color: var(--blue); } + .ord-status.sm { font-size: 10.5px; padding: 2px 8px; } + .ord-status.early { background: var(--led-amber-bg); color: var(--led-amber); } + .ord-status.mid { background: var(--led-blue-bg); color: var(--blue); } + .ord-status.ok { background: var(--led-green-bg); color: var(--led-green); } + .ord-status.done { background: #E9ECEF; color: var(--ink-soft); } + .ord-pill { font-size: 10.5px; font-weight: 600; padding: 2px 8px; border-radius: 10px; background: var(--led-blue-bg); color: var(--blue); display: inline-flex; align-items: center; gap: 3px; white-space: nowrap; } + .ord-pill.ok { background: var(--led-green-bg); color: var(--led-green); } + .ord-pill.warn { background: var(--led-amber-bg); color: var(--led-amber); } + .ord-pill.bad { background: var(--led-red-bg); color: var(--led-red); } + .ord-detail { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; min-width: 0; } + .ord-detail > * { min-width: 0; } + .ord-no { min-width: 0; box-sizing: border-box; } + .ord-head { padding: 16px 18px; } + .ord-head-top { display: flex; align-items: flex-start; gap: 10px; flex-wrap: wrap; } + .ord-no { font-family: 'Space Grotesk', sans-serif; font-size: 20px; font-weight: 700; border: 0; border-bottom: 1px dashed transparent; width: 100%; padding: 2px 0; background: transparent; color: var(--ink); } + .ord-no:hover, .ord-no:focus { border-bottom-color: var(--line); outline: none; } + .ord-head-sub { display: flex; gap: 8px; align-items: center; font-size: 12.5px; color: var(--ink-soft); margin-top: 2px; } + .ord-date { border: 0; background: transparent; font: inherit; color: inherit; } + .ord-steps { display: grid; grid-template-columns: repeat(8, minmax(0, 1fr)); gap: 4px; margin: 14px 0; } + @media (max-width: 760px) { .ord-steps { grid-template-columns: repeat(4, minmax(0, 1fr)); } } + .ord-step { position: relative; display: grid; justify-items: center; gap: 4px; font-size: 11px; color: var(--ink-soft); text-align: center; } + .ord-step::before { content: ""; position: absolute; top: 11px; left: -50%; right: 50%; height: 2px; background: var(--line); z-index: 0; } + .ord-step:first-child::before { display: none; } + .ord-step.done::before, .ord-step.cur::before { background: var(--led-green); } + .ord-step i { position: relative; z-index: 1; width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-style: normal; font-weight: 700; font-size: 11px; background: #fff; border: 2px solid var(--line); color: var(--ink-soft); } + .ord-step.done i { background: var(--led-green); border-color: var(--led-green); color: #fff; } + .ord-step.cur i { border-color: var(--copper); color: var(--copper); box-shadow: 0 0 0 4px var(--copper-soft); } + .ord-step.cur span { color: var(--copper); font-weight: 700; } + .ord-link-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } + @media (max-width: 760px) { .ord-link-row { grid-template-columns: 1fr; } } + .ord-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; } + .ord-chip { max-width: 100%; flex-wrap: wrap; display: inline-flex; align-items: center; gap: 6px; padding: 4px 6px 4px 10px; border: 1px solid var(--line); border-radius: 16px; font-size: 12px; background: #FAFBFC; } + .ord-chip a { color: var(--blue); cursor: pointer; font-weight: 600; } + .ord-chip em { font-style: normal; color: var(--ink-soft); font-family: 'IBM Plex Mono', monospace; font-size: 11px; } + .ord-chip button, .ord-x { border: 0; background: transparent; color: var(--ink-soft); cursor: pointer; padding: 3px; border-radius: 50%; display: inline-flex; } + .ord-chip button:hover, .ord-x:hover { background: var(--led-red-bg); color: var(--led-red); } + .ord-money { display: grid; grid-template-columns: repeat(auto-fit, minmax(128px, 1fr)); gap: 8px; } + .ord-money > div { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; display: grid; gap: 2px; min-width: 0; } + .ord-money span { font-size: 11px; color: var(--ink-soft); font-weight: 600; } + .ord-money b { font-family: 'Space Grotesk', sans-serif; font-size: 16px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .ord-money b.ok { color: var(--led-green); } .ord-money b.warn { color: var(--led-amber); } .ord-money b.bad { color: var(--led-red); } + .ord-money small { font-size: 10.5px; color: var(--ink-soft); } + .ord-money .profit { background: #18233A; border-color: #18233A; color: #fff; } + .ord-money .profit span, .ord-money .profit small { color: rgba(255,255,255,.65); } + .ord-money .profit b.ok { color: #7EE2A8; } .ord-money .profit b.bad { color: #FF9C94; } + .ord-grid2 { display: grid; grid-template-columns: 1fr 1.3fr; gap: 14px; } + @media (max-width: 1100px) { .ord-grid2 { grid-template-columns: minmax(0, 1fr); } } + .ord-grid2 > * { min-width: 0; } + .ord-box { padding: 14px 16px; } + .ord-box-h { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; font-weight: 700; font-size: 13px; margin-bottom: 8px; } + .ord-alert { display: flex; gap: 8px; align-items: baseline; font-size: 12.5px; padding: 6px 0; border-bottom: 1px dashed var(--line); } + .ord-alert:last-child { border-bottom: 0; } + .ord-alert i { width: 7px; height: 7px; border-radius: 50%; flex: none; background: var(--blue); transform: translateY(-1px); } + .ord-alert.bad i { background: var(--led-red); } .ord-alert.warn i { background: var(--led-amber); } .ord-alert.ok i { background: var(--led-green); } + .ord-alert.bad { color: var(--led-red); font-weight: 600; } + .ord-rm-add { display: grid; grid-template-columns: 190px 1fr auto; gap: 6px; } + @media (max-width: 600px) { .ord-rm-add { grid-template-columns: minmax(0, 1fr); } } + .ord-quick { display: flex; flex-wrap: wrap; gap: 5px; margin: 8px 0; } + .ord-quick button { border: 1px dashed var(--line); background: transparent; border-radius: 12px; padding: 2px 9px; font-size: 11.5px; cursor: pointer; color: var(--ink-soft); } + .ord-quick button:hover { border-color: var(--copper); color: var(--copper); } + .ord-rm { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 12.5px; padding: 6px 8px; border-radius: 7px; margin-top: 4px; background: #FAFBFC; } + .ord-rm .crm-mono { font-size: 11.5px; color: var(--ink-soft); white-space: nowrap; } + .ord-rm .t { flex: 1; min-width: 0; } + .ord-rm.due { background: var(--led-red-bg); } + .ord-rm.done { opacity: .5; } .ord-rm.done .t { text-decoration: line-through; } + .ord-secs { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; } + .ord-secs > * { min-width: 0; } + .ord-fields { grid-template-columns: repeat(auto-fill, minmax(min(160px, 100%), 1fr)) !important; } + .ord-sec { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; } + .ord-sec-h { width: 100%; display: flex; align-items: center; gap: 8px; padding: 12px 16px; border: 0; background: transparent; cursor: pointer; font: inherit; color: var(--ink); text-align: left; } + .ord-sec-h b { font-size: 13.5px; } + .ord-sec-ico { width: 26px; height: 26px; border-radius: 7px; display: grid; place-items: center; background: var(--copper-soft); color: var(--copper); flex: none; } + .ord-sec-h .ord-pill { margin-left: auto; } + .ord-chev { margin-left: 8px; color: var(--ink-soft); transition: transform .15s; flex: none; } + .ord-sec-h .ord-pill + .ord-chev { margin-left: 8px; } + .ord-sec-h b + .ord-chev { margin-left: auto; } + .ord-sec.open .ord-chev { transform: rotate(90deg); } + .ord-sec-b { padding: 4px 16px 16px; border-top: 1px solid var(--line); padding-top: 14px; } + .ord-sub-h { font-size: 11.5px; font-weight: 700; color: var(--ink-soft); text-transform: uppercase; letter-spacing: .04em; margin-bottom: 8px; } + .ord-fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 10px; margin-bottom: 8px; } + .ord-f { display: grid; gap: 4px; min-width: 0; } + .ord-f > span { font-size: 11px; font-weight: 600; color: var(--ink-soft); } + .ord-f.wide { grid-column: 1 / -1; } + .ord-item, .ord-rowcard { position: relative; border: 1px solid var(--line); border-radius: 9px; padding: 12px; margin-bottom: 10px; background: #FCFDFE; } + .ord-item-h { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; } + .ord-item-h b { font-family: 'Space Grotesk', sans-serif; color: var(--copper); } + .ord-del { position: absolute; top: 8px; right: 8px; } + .ord-rowcard .ord-fields { padding-right: 24px; } + .ord-refund { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 12.5px; } + .ord-refund-l { font-size: 11px; font-weight: 700; color: var(--ink-soft); } + .ord-seg { display: inline-flex; border: 1px solid var(--line); border-radius: 8px; overflow: hidden; } + .ord-seg button { border: 0; background: #fff; padding: 6px 12px; font-size: 12px; cursor: pointer; color: var(--ink-soft); border-right: 1px solid var(--line); } + .ord-seg button:last-child { border-right: 0; } + .ord-seg button.on { background: var(--led-green); color: #fff; font-weight: 600; } + .ord-seg button.on.no { background: var(--ink-soft); } + .ord-inl { display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; } + .ord-inl .input { width: 80px; padding: 6px 8px; } + .ord-files { margin-top: 4px; } + .ord-drop { display: inline-flex; align-items: center; gap: 6px; border: 1px dashed var(--line); border-radius: 8px; padding: 7px 12px; font-size: 12px; color: var(--ink-soft); cursor: pointer; background: #fff; } + .ord-drop:hover, .ord-drop.on { border-color: var(--copper); color: var(--copper); background: var(--copper-soft); } + .ord-file-list { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; } + .ord-file { position: relative; display: flex; align-items: center; border: 1px solid var(--line); border-radius: 8px; background: #fff; max-width: 220px; } + .ord-file-main { display: flex; align-items: center; gap: 8px; border: 0; background: transparent; padding: 5px 8px 5px 5px; cursor: pointer; min-width: 0; font: inherit; font-size: 12px; color: var(--blue); } + .ord-file-main img { width: 34px; height: 34px; object-fit: cover; border-radius: 5px; flex: none; } + .ord-file-main svg { flex: none; color: var(--led-red); } + .ord-file-main span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .ord-tbl { width: 100%; border-collapse: collapse; font-size: 12.5px; } + .ord-tbl th { text-align: left; font-size: 11px; color: var(--ink-soft); font-weight: 600; padding: 6px 8px; border-bottom: 1px solid var(--line); } + .ord-tbl td { padding: 7px 8px; border-bottom: 1px solid var(--line); } + .ord-bar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; padding: 10px 14px; margin-bottom: 14px; border-radius: 10px; background: var(--led-red-bg); color: var(--led-red); border: 1px solid #F1C4BF; font-size: 13px; } + .ord-bar-list { display: flex; flex-wrap: wrap; gap: 6px 14px; color: var(--ink); } + .ord-bar-list span { display: inline-flex; align-items: center; gap: 4px; } + .ord-bar-list a { cursor: pointer; text-decoration: underline; text-underline-offset: 2px; } + .ord-bar-list button { border: 1px solid #E8B3AE; background: #fff; border-radius: 50%; width: 18px; height: 18px; display: inline-grid; place-items: center; cursor: pointer; color: var(--led-green); padding: 0; } + .ord-bar-list em { font-style: normal; color: var(--ink-soft); } .crm-sidebar-item:hover:not(.active) { background: #F4F6F8; } .crm-sidebar-footer { border-top: 1px solid var(--line); padding: 12px 16px; } .crm-sidebar-user { font-size: 12px; color: var(--ink-soft); margin-bottom: 8px; display: flex; align-items: center; gap: 6px; } @@ -2219,6 +2355,7 @@ const NAV_GROUPS = [ { label: '客户', items: [ { id: 'monitor', label: '客户档案', icon: LayoutDashboard }, { id: 'manage', label: '客户管理', icon: Users }, + { id: 'orders', label: '订单管理', icon: ClipboardList }, { id: 'jms', label: 'Just My Socks', icon: Wifi }, ] }, { label: '产品', items: [ @@ -2418,6 +2555,8 @@ function MainApp({ username, onLogout }) { const [sellerLogoUploading, setSellerLogoUploading] = useState(false); const [pdfExporting, setPdfExporting] = useState(false); const [packingLists, setPackingLists] = useState([]); + const [orders, setOrders] = useState([]); + const [selectedOrderId, setSelectedOrderId] = useState(null); const [packingSubView, setPackingSubView] = useState('list'); // 'list' | 'editor' const [packingDraft, setPackingDraft] = useState(null); const [packingPdfExporting, setPackingPdfExporting] = useState(false); @@ -2484,6 +2623,7 @@ function MainApp({ username, onLogout }) { setSellerProfiles(data.sellerProfiles); setCertifications(data.certifications); setPackingLists(data.packingLists); + setOrders(Array.isArray(data.orders) ? data.orders : []); setCatalogDocs((data.catalogDocs || []).filter(d => d.fileName)); setJmsLines(data.jmsLines || []); setBackPanelTemplates(data.backPanelTemplates || []); @@ -2510,6 +2650,11 @@ function MainApp({ username, onLogout }) { useEffect(() => { if (loaded) storageSet(STORAGE_KEYS.webPackSpecs, JSON.stringify(webPackSpecs)).catch(reportSaveError); }, [webPackSpecs, loaded]); useEffect(() => { if (loaded) storageSet(STORAGE_KEYS.webAssets, JSON.stringify(webAssets)).catch(reportSaveError); }, [webAssets, loaded]); useEffect(() => { if (loaded) storageSet(STORAGE_KEYS.webNews, JSON.stringify(webNews)).catch(reportSaveError); }, [webNews, loaded]); + useEffect(() => { if (loaded) storageSet(STORAGE_KEYS.orders, JSON.stringify(orders)).catch(reportSaveError); }, [orders, loaded]); + // 侧栏“订单管理”上的数字:到期未处理的订单提醒(每分钟刷新一次) + const [ordTick, setOrdTick] = useState(0); + useEffect(() => { const t = setInterval(() => setOrdTick(x => x + 1), 60000); return () => clearInterval(t); }, []); + const ordDue = useMemo(() => dueReminders(orders).length, [orders, ordTick]); function notify(msg) { setToast(msg); setTimeout(() => setToast(''), 2200); } @@ -3655,6 +3800,7 @@ function MainApp({ username, onLogout }) { onClick={() => { setView(item.id); setMobileMenuOpen(false); }} > {item.label} + {item.id === 'orders' && ordDue > 0 && {ordDue}} {kids.length > 0 && } {expanded && kids.map(k => { @@ -3693,6 +3839,16 @@ function MainApp({ username, onLogout }) {
+ { setView('orders'); setSelectedOrderId(id); }} + onDone={(oid2, rid) => setOrders(prev => prev.map(o => (o.id === oid2 ? { ...o, reminders: (o.reminders || []).map(r => (r.id === rid ? { ...r, done: true } : r)) } : o)))} /> + + {view === 'orders' && ( + { setView('quotes'); startEditQuote(q); }} + onOpenPacking={(pl) => { setView('packing'); startEditPackingList(pl); }} /> + )} {view === 'monitor' && ( <> @@ -4720,6 +4876,782 @@ function MainApp({ username, onLogout }) { /* ----------------------------- customer form / detail ----------------------------- */ +/* ------------------------------- 订单管理 ------------------------------- */ +// 真实订单:关联客户和 PI,记录售价、采购成本(合同 + 付款)、其他成本、客户付款与实际入账、 +// 产品 HS / 申报要素 / 供应商、货代与打包要求、退税、发货、报关单、箱单、箱唛、是否完结,以及提醒。 +// 文件(合同、付款凭证、报关单、箱唛等)上传到 uploads/<订单id>/,订单里只存文件名。 + +const ORDER_SHIP_MODES = [ + { id: 'sea', label: '海运' }, { id: 'air', label: '空运' }, { id: 'land', label: '陆运' }, { id: 'express', label: '快递' }, +]; +const ORDER_REFUND_STATUS = ['未申报', '已申报', '审核中', '已到账']; +const ORDER_COST_TYPES = ['物流运费', '木箱包装', '报关费', '拖车 / 内陆运输', '保险', '银行手续费', '其他']; +const ORDER_VAT = 0.13; // 采购价按含 13% 增值税计,退税额 = 含税采购额 ÷ 1.13 × 退税率 + +const oid = (p) => p + '_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6); +const num0 = (v) => { const n = parseFloat(String(v ?? '').replace(/,/g, '')); return Number.isFinite(n) ? n : 0; }; +const cny = (n) => '¥' + (Number.isFinite(n) ? n : 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); + +const blankOrderItem = () => ({ + id: oid('oi'), productId: '', name: '', qty: '', unitPrice: '', + hsCode: '', declareElements: '', supplierId: '', purchaseUnitCost: '', + refundable: '', refundRate: '', refundStatus: '未申报', refundReceived: '', +}); +const blankOrder = () => ({ + id: oid('ord'), number: '', date: todayStr(), customerId: '', quoteIds: [], currency: 'USD', fxRate: '', + salePriceOverride: '', items: [blankOrderItem()], + purchaseContracts: [], purchasePayments: [], otherCosts: [], customerPayments: [], + forwarder: { name: '', contact: '', phone: '', email: '', warehouse: '', packingReq: '', notes: '' }, + shipping: { shipped: false, mode: 'sea', etd: '', eta: '', blNo: '', vessel: '', containerNo: '', notes: '' }, + customsDecl: { number: '', date: '', files: [] }, + packingListIds: [], packingFiles: [], + shippingMark: { text: '', files: [] }, + closed: false, closedDate: '', notes: '', + reminders: [], + createdAt: todayStr(), +}); + +// 订单各项金额:售价按订单币种,成本按人民币 +function orderCalc(o) { + const items = o.items || []; + const itemsSale = items.reduce((s, it) => s + num0(it.qty) * num0(it.unitPrice), 0); + const sale = o.salePriceOverride !== '' && o.salePriceOverride != null ? num0(o.salePriceOverride) : itemsSale; + const paid = (o.customerPayments || []).reduce((s, p) => s + num0(p.amount), 0); + const receivedCny = (o.customerPayments || []).reduce((s, p) => s + num0(p.receivedCny), 0); + const purchaseItems = items.reduce((s, it) => s + num0(it.qty) * num0(it.purchaseUnitCost), 0); + const contractTotal = (o.purchaseContracts || []).reduce((s, c) => s + num0(c.amount), 0); + const purchase = contractTotal || purchaseItems; + const purchasePaid = (o.purchasePayments || []).reduce((s, p) => s + num0(p.amount), 0); + const other = (o.otherCosts || []).reduce((s, c) => s + num0(c.amount), 0); + const refundEst = items.reduce((s, it) => it.refundable === 'yes' ? s + num0(it.qty) * num0(it.purchaseUnitCost) / (1 + ORDER_VAT) * num0(it.refundRate) / 100 : s, 0); + const refundGot = items.reduce((s, it) => s + num0(it.refundReceived), 0); + const fx = o.currency === 'CNY' ? 1 : num0(o.fxRate); + const balance = Math.max(0, sale - paid); + // 预计利润:已入账 + 未收部分按汇率折算 + 退税(已到账优先,否则按预计) − 采购 − 其他成本 + const expectIncome = receivedCny + (fx ? balance * fx : 0); + const refund = refundGot || refundEst; + const profit = expectIncome + refund - purchase - other; + return { itemsSale, sale, paid, balance, receivedCny, purchase, purchaseItems, contractTotal, purchasePaid, purchaseUnpaid: Math.max(0, purchase - purchasePaid), other, refundEst, refundGot, refund, fx, profit, hasFx: !!fx }; +} + +// 订单进度:按填写的内容自动判断每一步是否完成 +function orderSteps(o) { + const c = orderCalc(o); + const items = (o.items || []).filter(it => it.name || it.productId); + const refundItems = items.filter(it => it.refundable === 'yes'); + const refundDone = items.length > 0 && items.every(it => it.refundable === 'no' || (it.refundable === 'yes' && it.refundStatus === '已到账')); + return [ + { id: 'sign', label: '签单', done: !!(o.customerId && (items.length || (o.quoteIds || []).length)) }, + { id: 'deposit', label: '收款', done: c.paid > 0 }, + { id: 'purchase', label: '采购', done: (o.purchaseContracts || []).length > 0 }, + { id: 'ship', label: '发货', done: !!(o.shipping && o.shipping.shipped) }, + { id: 'paid', label: '收齐货款', done: c.sale > 0 && c.paid >= c.sale * 0.995 }, + { id: 'customs', label: '报关单', done: !!(o.customsDecl && (o.customsDecl.number || (o.customsDecl.files || []).length)) }, + { id: 'refund', label: refundItems.length ? '退税' : '退税', done: refundDone }, + { id: 'close', label: '完结', done: !!o.closed }, + ]; +} +function orderStatus(o) { + if (o.closed) return { label: '已完结', tone: 'done' }; + const steps = orderSteps(o); + const next = steps.find(s => !s.done); + const doneN = steps.filter(s => s.done).length; + if (!next) return { label: '可以完结', tone: 'ok' }; + const map = { sign: '待签单', deposit: '待收款', purchase: '待采购', ship: '待发货', paid: '待收尾款', customs: '待报关单', refund: '退税中', close: '待完结' }; + return { label: map[next.id], tone: doneN >= 4 ? 'mid' : 'early' }; +} +// 自动提示:根据订单内容发现需要跟进的事 +function orderAlerts(o) { + if (o.closed) return []; + const c = orderCalc(o), out = []; + const shipped = !!(o.shipping && o.shipping.shipped); + const today = todayStr(); + if (shipped && c.balance > 0.5) out.push({ tone: 'bad', text: `已发货,客户还欠 ${formatMoney(c.balance, o.currency)}` }); + if (c.purchaseUnpaid > 0.5 && (o.purchaseContracts || []).length) out.push({ tone: 'warn', text: `供应商货款未付清:还差 ${cny(c.purchaseUnpaid)}` }); + if (shipped && !(o.customsDecl && (o.customsDecl.number || (o.customsDecl.files || []).length))) out.push({ tone: 'warn', text: '已发货,还没有上传报关单' }); + if (!shipped && o.shipping && o.shipping.etd && o.shipping.etd < today) out.push({ tone: 'warn', text: `预计 ${o.shipping.etd} 发货,已过期还没标记发货` }); + const pend = (o.items || []).filter(it => it.refundable === 'yes' && it.refundStatus !== '已到账'); + if (shipped && pend.length) out.push({ tone: 'info', text: `${pend.length} 项产品退税未到账` }); + if ((o.items || []).some(it => (it.name || it.productId) && !it.refundable)) out.push({ tone: 'info', text: '有产品还没填写能否退税' }); + if (shipped && !c.hasFx && c.balance > 0) out.push({ tone: 'info', text: '填写汇率后可以估算未收部分的人民币和利润' }); + if (orderSteps(o).every(s => s.id === 'close' || s.done)) out.push({ tone: 'ok', text: '所有环节都已完成,可以标记完结' }); + return out; +} +const reminderDue = (r, now = new Date()) => !r.done && r.at && new Date(r.at) <= now; +function dueReminders(orders, now = new Date()) { + const out = []; + for (const o of orders || []) for (const r of o.reminders || []) if (reminderDue(r, now)) out.push({ order: o, r }); + return out.sort((a, b) => a.r.at.localeCompare(b.r.at)); +} + +/* ---- 小部件 ---- */ +function OrderFiles({ orderId, files, onChange, label, notify }) { + const [busy, setBusy] = useState(false); + const [preview, setPreview] = useState(null); + const [drag, setDrag] = useState(false); + const list = files || []; + async function add(fs) { + if (!fs || !fs.length) return; + setBusy(true); + const added = []; + for (const f of fs) { + try { const r = await uploadFile(orderId, f); added.push({ fileName: r.fileName, originalName: r.originalName || f.name, date: todayStr() }); } + catch (e) { notify && notify(e.message || '上传失败'); } + } + setBusy(false); + if (added.length) onChange((prev) => [...added, ...prev]); + } + async function remove(fn) { + if (!window.confirm('删除这个文件?')) return; + try { await deleteFile(orderId, fn); } catch (e) {} + onChange((prev) => prev.filter(x => x.fileName !== fn)); + } + return ( +
+ + {list.length > 0 && ( +
+ {list.map(f => { + const url = `/uploads/${orderId}/${f.fileName}`; + const img = isPreviewableImage(f.originalName || f.fileName); + return ( +
+ + +
+ ); + })} +
+ )} + {preview && setPreview(null)} />} +
+ ); +} + +function OrdSection({ id, icon, title, badge, tone, children, open, onToggle }) { + return ( +
+ + {open &&
{children}
} +
+ ); +} + +function OrdField({ label, children, wide }) { + return ; +} + +/* ---- 订单详情 ---- */ +function OrderDetail({ order: o, update, onDelete, customers, quotes, products, suppliers, packingLists, orders, notify, onOpenQuote, onOpenPacking }) { + const [open, setOpen] = useState({ items: true, pay: true }); + const tog = (k) => setOpen(s => ({ ...s, [k]: !s[k] })); + // 所有修改都基于订单的最新状态(文件上传是异步的,不能用渲染时的旧数据去覆盖) + const set = (patch) => update(o.id, patch); + const setIn = (key, patch) => update(o.id, (cur) => ({ [key]: { ...(cur[key] || {}), ...patch } })); + const upd = (key, id, patch) => update(o.id, (cur) => ({ [key]: (cur[key] || []).map(x => (x.id === id ? { ...x, ...patch } : x)) })); + const del = (key, id) => { if (window.confirm('删除这一条?')) update(o.id, (cur) => ({ [key]: (cur[key] || []).filter(x => x.id !== id) })); }; + const add = (key, x) => update(o.id, (cur) => ({ [key]: [...(cur[key] || []), x] })); + // 文件列表的修改函数:fn(旧列表) → 新列表 + const filesOf = (key, id) => (fn) => update(o.id, (cur) => ({ [key]: (cur[key] || []).map(x => (x.id === id ? { ...x, files: fn(x.files || []) } : x)) })); + const filesIn = (key) => (fn) => update(o.id, (cur) => ({ [key]: { ...(cur[key] || {}), files: fn((cur[key] || {}).files || []) } })); + + const c = orderCalc(o); + const steps = orderSteps(o); + const st = orderStatus(o); + const alerts = orderAlerts(o); + const cust = customers.find(x => x.id === o.customerId); + const custQuotes = quotes.filter(q => q.type === 'invoice' || q.type === 'quote').filter(q => !o.customerId || !q.customerId || q.customerId === o.customerId); + const linkedQuotes = (o.quoteIds || []).map(id => quotes.find(q => q.id === id)).filter(Boolean); + const supName = (id) => (suppliers.find(s => s.id === id) || {}).name || ''; + const now = new Date(); + + function pickCustomer(id) { + const cu = customers.find(x => x.id === id); + const patch = { customerId: id }; + // 货代 / 箱唛默认带出客户档案里的信息(只在订单里还没填时) + if (cu) { + const fw = o.forwarder || {}; + if (!fw.contact && !fw.warehouse && (cu.freightContact || cu.warehouseAddress)) patch.forwarder = { ...fw, contact: fw.contact || cu.freightContact || '', warehouse: fw.warehouse || cu.warehouseAddress || '' }; + if (!(o.shippingMark && o.shippingMark.text) && cu.shippingMarkNote) patch.shippingMark = { ...(o.shippingMark || {}), text: cu.shippingMarkNote }; + } + set(patch); + } + function linkQuote(id) { + if (!id || (o.quoteIds || []).includes(id)) return; + const q = quotes.find(x => x.id === id); + const patch = { quoteIds: [...(o.quoteIds || []), id] }; + if (q) { + if (!o.number) patch.number = q.number || ''; + if (!o.customerId && q.customerId) patch.customerId = q.customerId; + patch.currency = q.currency || o.currency; + // 订单里还没有产品时,用 PI 的明细生成产品行 + const empty = !(o.items || []).some(it => it.name || it.productId); + if (empty && (q.lineItems || []).length) { + patch.items = q.lineItems.filter(li => li.description).map(li => { + const name = String(li.description).split('\n')[0].trim(); + const prod = products.find(p => (p.name || '').trim().toUpperCase() === name.toUpperCase()); + const it = { ...blankOrderItem(), name, qty: li.quantity || '', unitPrice: li.rate || '', productId: prod ? prod.id : '' }; + return fillFromHistory(it); + }); + } + } + set(patch); + } + // 同一个产品以前下过单:带出 HS 编码、申报要素、供应商、采购价、退税率 + function fillFromHistory(it) { + const key = it.productId || (it.name || '').trim().toUpperCase(); + if (!key) return it; + for (const x of [...orders].reverse()) { + if (x.id === o.id) continue; + const h = (x.items || []).find(y => (it.productId && y.productId === it.productId) || ((y.name || '').trim().toUpperCase() === (it.name || '').trim().toUpperCase() && y.name)); + if (h) return { ...it, hsCode: it.hsCode || h.hsCode || '', declareElements: it.declareElements || h.declareElements || '', supplierId: it.supplierId || h.supplierId || '', purchaseUnitCost: it.purchaseUnitCost || h.purchaseUnitCost || '', refundable: it.refundable || h.refundable || '', refundRate: it.refundRate || h.refundRate || '' }; + } + return it; + } + function pickProduct(itemId, val) { + const prod = products.find(p => p.id === val); + const it = (o.items || []).find(x => x.id === itemId) || {}; + let next = { ...it, productId: prod ? prod.id : '', name: prod ? prod.name : it.name }; + next = fillFromHistory(next); + upd('items', itemId, next); + } + function addReminder(at, text) { + if (!at || !text.trim()) return; + add('reminders', { id: oid('rm'), at, text: text.trim(), done: false, createdAt: todayStr() }); + } + const [rmAt, setRmAt] = useState(''); + const [rmText, setRmText] = useState(''); + const quick = (days, text) => { + const d = new Date(); d.setDate(d.getDate() + days); d.setHours(9, 0, 0, 0); + const pad = (n) => String(n).padStart(2, '0'); + setRmAt(`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T09:00`); + if (text) setRmText(text); + }; + const plOptions = packingLists.filter(pl => !(o.packingListIds || []).includes(pl.id)).filter(pl => !o.customerId || !pl.customerId || pl.customerId === o.customerId); + const linkedPLs = (o.packingListIds || []).map(id => packingLists.find(p => p.id === id)).filter(Boolean); + const plTot = linkedPLs.reduce((s, pl) => { const t = packingTotals(pl); return { cartons: s.cartons + t.cartons, gw: s.gw + t.grossWeight, cbm: s.cbm + t.volume }; }, { cartons: 0, gw: 0, cbm: 0 }); + const reminders = [...(o.reminders || [])].sort((a, b) => (a.done - b.done) || (a.at || '').localeCompare(b.at || '')); + const itemsReal = (o.items || []).filter(it => it.name || it.productId); + const refundPending = itemsReal.filter(it => it.refundable === 'yes' && it.refundStatus !== '已到账').length; + const sw = o.shipping || {}; + const fw = o.forwarder || {}; + + return ( +
+ {/* 头部:单号、客户、PI、状态 */} +
+
+
+ set({ number: e.target.value })} /> +
+ {cust ? cust.company || cust.contact : '未关联客户'} + · + set({ date: e.target.value })} /> +
+
+ {st.label} + +
+
+ {steps.map((s, i) => ( +
x.done) ? 'cur' : ''}`}> + {s.done ? : i + 1}{s.label} +
+ ))} +
+
+ + + + + + +
+ {linkedQuotes.length > 0 && ( +
+ {linkedQuotes.map(q => ( + + onOpenQuote(q)}>{q.type === 'invoice' ? 'PI' : 'Quote'} {q.number || '(无单号)'} + {formatMoney(quoteTotals(q).total, q.currency)} + + + ))} +
+ )} +
+ + {/* 金额总览 */} +
+
出售价格{formatMoney(c.sale, o.currency)}{o.salePriceOverride !== '' && o.salePriceOverride != null ? '手动填写的总价' : '按产品明细合计'}
+
客户已付 0.5 ? 'warn' : 'ok'}>{formatMoney(c.paid, o.currency)}{c.balance > 0.5 ? `未收 ${formatMoney(c.balance, o.currency)}` : '已收齐'}
+
实际入账{cny(c.receivedCny)}人民币到账合计
+
采购成本{cny(c.purchase)}{c.purchaseUnpaid > 0.5 ? `未付供应商 ${cny(c.purchaseUnpaid)}` : (c.purchase ? '已付清' : '—')}
+
其他成本{cny(c.other)}物流 / 包装等
+
退税{cny(c.refund)}{c.refundGot ? '已到账' : '预计'}
+
预计利润= 0 ? 'ok' : 'bad'}>{cny(c.profit)}{c.hasFx || c.balance <= 0.5 ? '入账 + 退税 − 成本' : '未收部分需填汇率才计入'}
+
+ + {/* 自动提示 + 提醒 */} +
+
+
需要跟进
+ {alerts.length === 0 ?
{o.closed ? '订单已完结' : '暂时没有需要跟进的事项'}
+ : alerts.map((a, i) =>
{a.text}
)} +
+
+
提醒到时间后在侧栏和页面顶部提示
+
+ setRmAt(e.target.value)} /> + setRmText(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') { addReminder(rmAt, rmText); setRmText(''); } }} /> + +
+
+ + + + + + +
+ {reminders.length === 0 ?
还没有提醒
: reminders.map(r => { + const due = reminderDue(r, now); + return ( +
+ upd('reminders', r.id, { done: e.target.checked })} /> + {(r.at || '').replace('T', ' ')} + {r.text} + {due && 到期} + +
+ ); + })} +
+
+ +
+ {/* 6. 产品 */} + } title="产品(HS 编码 / 申报要素 / 供应商 / 退税)" badge={itemsReal.length ? `${itemsReal.length} 项` : ''} open={open.items} onToggle={() => tog('items')}> + {products.map(p => + {(o.items || []).map((it, i) => ( +
+
#{i + 1} + + +
+
+ upd('items', it.id, { name: e.target.value })} onBlur={() => { const f = fillFromHistory(it); if (f !== it) upd('items', it.id, f); }} /> + upd('items', it.id, { qty: e.target.value })} /> + upd('items', it.id, { unitPrice: e.target.value })} /> + upd('items', it.id, { hsCode: e.target.value })} /> + + + + upd('items', it.id, { purchaseUnitCost: e.target.value })} /> +