# CRM VNO mock - Components & conventions

Thuật ngữ viết tắt: nguồn duy nhất là `assets/glossary.js`; bảng đọc được ở [Bảng thuật ngữ](../01-actors-and-workflow.md#bảng-thuật-ngữ).

Đọc kèm `assets/screens/sales.js` (reference). Không dùng ES module, không fetch file local. Mọi thứ nằm trên `window.VNO`.

## Cấu trúc
`index.html` nạp theo thứ tự: `i18n.js` → `i18n/*.js` (từ điển) → `data.js` → `customer-view.js` (`VNO.cv`) → `app.js` → `screens/<role>.js` (cổng khách gồm `screens/customer-orders.js` + `screens/customer-requests.js`, cùng `registerScreens('customer', …)`). Mỗi file screens là một IIFE, kết thúc bằng `VNO.registerScreens(role, {...})`. Phase 2 chỉ ghi đè file screens của vai trò mình, không sửa `app.js`, `styles.css`, `data.js` (cần thêm dữ liệu/CSS thì báo lại).

## registerScreens contract
```js
VNO.registerScreens('engineer', {
  'tech-review': {
    title: 'Technical Review',
    render(container, ctx) { container.append(/* DOM nodes */); }   // hoặc return một Node
  }
});
```
- Screen id lấy từ `VNO.NAV[role]` (đã định nghĩa đủ 9 role). Id chưa đăng ký tự hiện placeholder "Đang xây dựng".
- `ctx`: `{ role, user, data (=VNO.data), ui (=VNO.ui), param, screen, navigate(screen, param?), refresh() }`.
- `ctx.param` = đoạn thứ 3 của hash (`#/sales/quotations/q1` → `q1`). Dùng để mở drawer/editor. Nếu mở drawer từ param, xóa param bằng `history.replaceState(null,'','#/role/screen')` để `refresh()` không mở lại.
- Mỗi lần điều hướng container được làm rỗng và overlay (drawer/modal) tự đóng. Lỗi trong render được bắt và hiển thị banner.
- Dữ liệu mock là mutable trong bộ nhớ (reload là reset). Khi sửa, gọi lại hàm vẽ cục bộ (xem `drawBoard` trong sales.js) thay vì `refresh()` nếu muốn giữ trạng thái UI.

## VNO.ui (viết tắt `ui`)
| Helper | Chữ ký | Ghi chú |
|---|---|---|
| `h(tag, attrs, ...children)` | trả Element | attrs: `class`, `html` (raw), `style` (object, hỗ trợ `--var`), `onclick`…, `value`; children: Node/string/array (string là text, an toàn XSS) |
| `icon(name, size)` / `iconHtml` | SVG | tên trong `ui.ICONS` (dashboard, kanban, file, users, alert, bell, upload, download, sparkles, clock, truck, package, dollar, shield, clipboard, factory, calendar, trend, ruler, repeat, camera, gantt, table, ship, plane, …) |
| `statusBadge(kind, state)` | badge | kind: inquiry, po, qc, payment, quotation, approval, car, complaint, cipl, rfq, gantt. `statusLabel(kind,state)` lấy nhãn. Thêm state mới: sửa `ui.STATUS` |
| `badge(text, tone)` | badge | tone: neutral, primary, info, success, warning, danger, purple |
| `kpiCard({label,value,sub,delta,tone,icon,size:'sm',onClick})` | card | tone chọn màu icon |
| `card({title,actions,body,flush,class})` | section | `flush` bỏ padding (dùng với table) |
| `pageHeader({title,subtitle,actions,crumbs})` | header | |
| `button(label,{kind,size,icon,onClick,disabled})` | button | kind: primary, ghost, danger, success |
| `table({columns,rows,onRowClick,dense,sortKey,sortDir,rowClass,empty})` | wrapper | column: `{key,label,render(row),sort(row),align:'num'\|'c',sortable:false,width}`; sort click-header client-side |
| `kanban({columns,items,columnOf,renderCard,onCardClick,onMove,emptyText,key,sortBy,onAdd,canAdd})` | board | columns `{id,title,color}`; có `onMove` thì kéo thả được; vẽ lại khi dữ liệu đổi 
| `klabel(text,key)` / `kbadge(icon,text,tone,title)` | span | phần tử thẻ kanban: nhãn màu (key chuỗi → màu cố định theo hash, số 1-8 → chọn màu) và badge icon + chữ dưới tiêu đề (tone: success, warning, danger) |
| `drawer({title,subtitle,body,footer,width,onClose})` / `modal(...)` | `{el,body,footer,setBody,setFooter,close}` | footer là mảng nút; Esc/bấm nền đóng |
| `toast(msg, tone)` | | tone: success, error, warning |
| `tabs({tabs:[{id,label,count,content:()=>Node}],active,onChange})` | element | content render lazy; `count` có thể là hàm, gọi `el.refreshCounts()` sau khi dữ liệu đổi |
| `timeline([{text,who,date,tone,icon}])` | ul | tone: primary, purple (AI [Artificial Intelligence]), success, warning, danger |
| `fileChip({name,kb,type})` | chip | tự nhận PDF/XLS/IMG theo đuôi |
| `emptyState({icon,title,text,action})` | | |
| `aiDraftBanner(text?)` | banner | luôn đặt phía trên nội dung do AI tạo |
| `banner(tone, ...content)` | | tone: info, warn, danger, success |
| `progressBar(pct, tone)` | | tone: '', success, warning, danger |
| `field({label,name,type,value,options,required,hint,placeholder,rows,readonly,full,onInput})` | `.field` (+ `.input`) | type: text, number, date, select, textarea; `options` là `[{value,label}]`; `el.input` là control |
| `formValues(root)` / `validate(root)` | | `validate` gắn `.invalid` cho field `required` rỗng |
| `dropzone({label,hint,accept,multiple,onFiles})` | element | `el.files`, `el.addFiles([...])` |
| `dropdown(triggerBtn, build(close), align?)` | wrapper | popover đóng khi bấm ngoài |
| `seg(options, value, onChange)` / `kv([[k,v]])` / `paper(...children)` | | `paper` = khung PDF preview chung (chỉ dùng cho tài liệu chưa có mẫu, vd PO khách đọc bằng AI); chứng từ VNO dùng `VNO.docs` bên dưới |
| `avatar(name,size,color)` / `logo(size)` | | |
| `fmt` | | `usd(n)`, `vnd(n)`, `num(n,dec)`, `pct(n)`, `date(iso)` → dd/mm/yyyy, `daysFromToday(iso)`, `relDays(iso)`, `size(kb)` |

## VNO.docs (xem `docs.js`): trang chứng từ giống hệt file mẫu của VNO
Mỗi hàm trả về một trang (`div.paper.pdoc`, kích thước tính bằng pt, đo từ file mẫu trong `CRM VNO/`); `viewer(pages, {title})` bọc các trang trong khung xem PDF (vừa khung, `−` / `+`, mở cỡ lớn); `show(host, pages, opts)` dùng cho bản xem trước cập nhật trực tiếp (giữ mức zoom).

| Hàm | File mẫu |
|---|---|
| `quotation(d)` | `2. …/QT VNO 26243-169A - Frame FMD 100.pdf` (Letter) |
| `purchaseOrder(d)` | `3. …/PO- VNO26085  to 3TB -  32520-200 Valve.pdf` (A4) |
| `cipl(d)` → `[CI, PL]` | `5. …/Pacific CIPL-PO#29857-…-Final.pdf` (A4); dòng `data-k="packing" / "payment"`, ô `data-k="pkgs-total"` cho test |
| `rfq(d)` | `1. …/[VNO] RFQ VNO Template (1).xlsx` (A4, in 77 %) |
| `car(d)` | `7. …/CAR report-Hydrocyclone 4inch-20241007.xlsx` (A4 ngang, song ngữ) |
| `invoice(d)` / `letter(d)` | chưa có mẫu: theo kiểu trang CI/PL / trang báo giá |

Chữ ký tay và con dấu thật **không** đưa vào mock (link Vercel công khai): trang đã duyệt hiện ô "Signature & company stamp" đúng vị trí, trang chưa duyệt có watermark DRAFT. Trang song ngữ theo mẫu (RFQ, CAR) mang `data-doc-lang="bilingual"`.

## VNO.data (xem `data.js`)
`TODAY` ('2026-11-28'), `VND_RATE`, `roles`, `users`, `customers`, `suppliers`, `products`, `inquiries`, `quotations`, `salesOrders`, `supplierPOs`, `ganttStages`, `gantt`, `fairLots`, `qcSchedule`, `shipments`, `invoices`, `cars`, `complaints`, `notifications`, `approvals`; helper `customer(id)`, `supplier(id)`, `user(id)`, `paymentState(invoice)` → payment state, `quotationTotal(q)`, `quotationCost(q)`. Ngày là chuỗi ISO. Dùng `D.TODAY` thay cho `new Date()` để demo luôn nhất quán.

Nghiệp vụ dùng chung nằm trong `data.js` (một nguồn duy nhất cho mọi role): `enqueueApproval(kind, refId, fields)` / `withdrawApprovals` (hàng chờ GĐ [Giám đốc], mỗi mục mang id bản ghi, `APPROVAL_REF`), `queueQuotation`, `createRework` / `reworkSetState` / `applyReinspectPass` / `approveLotExport` (lô FAIR [First Article Inspection Report] ↔ rework ↔ shipment), `confirmPO` (+ `makeGantt`), `scheduleInspection(po)` (PO [Purchase Order] → TBI [To Be Inspected]), `markShipped(shipment, dates)` (shipment + PO Shipped, bước 5.5), `soStage(so)` (giai đoạn SO [Sales Order] suy ra từ PO), `soPayment(so)` (AR [Accounts Receivable] đã thu của SO), `createCarFromComplaint` / `setCarState`, `poStage(po)`, `isIssued(invoice)`, `soConfirmed(so)`; `notifications` là getter tính từ dữ liệu hiện tại.

## Quy ước
- Ngôn ngữ UI song ngữ EN / VI, mặc định EN (xem mục i18n bên dưới); bản VI giữ thuật ngữ EN (RFQ [Request for Quotation], PO, FAIR, CI/PL [Commercial Invoice / Packing List], CAR [Corrective Action Report], Gantt…).
- Class tiện ích: `.row .col .grid .g2 .g3 .g4 .g-main .g-split .muted .small .xs .mono .num .strong .mt`. Không inline màu hex; dùng token `var(--…)`.
- Chỉ dùng `h()` hoặc `textContent`; không nối chuỗi người dùng vào `innerHTML`.
- Mỗi file screens tối đa ~600 dòng; tách helper dùng chung vào `app.js` (báo lại người sở hữu) thay vì copy.
- Trạng thái màu dùng `statusBadge`, không tự tô.
- Hành động giả lập (gửi, duyệt, tải PDF) phải có `ui.toast` phản hồi.
- QC (Quality Control) (tablet): ô bấm tối thiểu 48px, tránh hover-only; layout `data-layout=tablet` đã tăng cỡ chữ.
- Kiểm thử: `node --check <file>` + headless Chrome `…/index.html#/<role>/<screen>`; `?theme=dark`, `?role=<role>` hỗ trợ sẵn.

## Vòng 7: API dùng chung mới (data.js / app.js)
Màn hình **gọi** các hàm này, không tự tính lại. Tất cả nằm trong `VNO.data` (`D`) trừ khi ghi khác.

### Shell & responsive (app.js / styles.css)
- Chuông: mục thông báo có `go: [role, screen, param?]` thì bấm mở bản ghi (`note(sev, text, time, go)`).
- Role switcher ẩn ở portal nhà máy, chỉ hiện với `?demo=1`. QC (tablet) và portal ≤600px dùng **bottom nav** (`NAV[...].short` là nhãn ngắn).
- Bảng: `ui.table` gắn `data-label` cho mọi ô; ≤640px bảng ≤7 cột không có input tự thành **thẻ** (`ui.table({cards:false})` / class `no-cards` để giữ bảng cuộn; `cards:true` / class `cards` để ép thẻ cả bảng rộng, dùng cho form bóc tách). Bảng dựng tay trong màn hình tự được gắn nhãn (MutationObserver); gọi `ui.labelTables(root)` nếu cần ngay.
- `ui.statusBadge` đổi nhãn theo layout (`STATUS_LOCAL`: QC, portal). Kind mới: `arrival`, `shipType`, `tranche`, `quoteState`.
- Điện thoại ≤480px: nút / input / tab ≥44px; `.kv` xếp dọc; drawer + modal toàn màn hình.

### Shipment đa dòng
`shipLines(s)` → `[{soId, poId, itemNo, qty, kind: regular|replacement|sample|foc}]` · `shipPOIds / shipSOIds / shipCustomerIds / shipSupplierIds(s)` · `shipmentsOfPO(poId)` / `shipmentsOfSO(soId)` · `poShipProgress(po)` / `soShipProgress(so)` → `{lines:[{ordered, shipped, planned, remaining}], shipped, ordered, partial, pct}` · `createShipment(spec)` → `{ok, shipment}` | `{ok:false, errors[]}` (kiểm EXW [Ex Works] ≤ ETD [Estimated Time of Departure] ≤ ETA [Estimated Time of Arrival], SL [số lượng] còn lại, bù hàng / mẫu không cần SL còn lại) · `validateShipmentDates(d, 'plan'|'confirm')` · `markShipped(s, {actExw, actShip, ...})` (mọi PO trên shipment) · `updateEta(s, eta, {by, reason})` (sau Shipped vẫn được, ghi `etaLog`) · `confirmArrival(s, ata, by)` · `arrivalState(s)` · `ciPlRowsFromShipment(s)` / `ciPlWarnings(s, rows)` / `hsCodeOf(itemNo)`. Trường vận chuyển: `forwarder, booking, vessel, bl, container, seal, pol, pod, dest, freightPayer, ata, etaLog`. Trường cũ `poId / po / qty` còn dùng được (mirror): `syncShipmentMirror(s)`.

### Công nợ
`paymentPlan('AR'|'AP')` → mọi tranche `{docId, kind: DP|Balance, amount, due, basis:{text}, inv, state, invoiceable, partial}` (không ẩn khoản cũ) · `apThisWeek(days=7)` → `{total, items[], breakdown:{approved, pending, unvouchered}}` (định nghĩa duy nhất của "AP tuần này") · `arOverdue()` · `deliveredNotInvoiced()` · `invoiceGuard(doc, kind, amount)` → `{ok, errors, warnings, total, invoiced}` (`doc = paymentDocOf(type, id)`) · `recordPayment(inv, {amount, date, bankRef, method, bankCharge, borneBy})` · `invOwed(inv)` · `inv.payments[]` · `closeTranche(type, docId, kind, reason, by)` · `revenueOfPO(po)` · `masterFileFields(po)` → `{dcNo (= số CI/PL), revenueDate (cuối tháng), poIssuedBy (pháp nhân khách), vnoPo, customerPo}`.

### Theo dõi đơn & bàn giao Sales → Mua hàng
`soTrack(so)` → `{stage, promised, forecast, slackDays, late, delayDays, lines, lots[{poId, progress, forecast, delayDays, qc, steps[], shipments[]}], shipments, payments{paid,total,invoices,next}, sentence}` · `soSentence(track)` · `ordersAwaitingPO()` · `defaultSupplierForSO(so)` · `defaultPoDelivery(so)` → `{date, customerDate, buffer, leadTime}`.

### Báo giá
`quotationLocked(q)` / `quotationPerms(q, role)` → `{editPrice, editCost, canSend, canRevise, reason}` · `reviseQuotation(old, lines, by, {reason})` (Sales không đổi được cost) · `quotationDiff(q)` · `quotationCostSource(q)` · `lastSoldPrice(customerId, itemNo)`.

### RFQ nhiều nhà máy
`rfq.moqs=[{id, qtys[]}]`, `rfq.quotes[supplierId]={leadtime, terms, validity, quotedAt, tiers:[{moq, qtys, lines}]}`, `rfq.selected={supplierId, tier}` · `rfqQuote(r, sid)` · `quoteTierCalc(quote, tier)` · `rfqCompare(r, tier)` · `rfqProgress(r)` · `submitQuote(r, sid, {leadtime, terms, validity, tiers|lines})` · `selectSupplier(inqId, sid, tier)` · `selectedSupplierOf(inqId)` · `rfqUnitUsd(r, sid?, tier?)` · `drawingFilesOf(rfqOrPo)` (an toàn cho nhà máy) / `logDrawingDownload`.

### FAIR
Feature: `{kind: dim|dia|depth|angle|thread|limit|surface|pos|visual, unit, nominal, tol | tolPlus + tolMinus | lower + upper, actual[]}` (ren / visual: `actual = 'go'|'nogo'`). `judge(f, v)` · `featureSpec(f, lot)` (primary + alt in/mm) · `fmtMeasure(f, v, lot)` · `parseMeasure(raw)` (chặt) · `measureWarning(f, v, lot)` · `lot.sample={mode:'sample'|'all', size, of}` · `lot.serials[]` + `serialLabel(lot, i)` · `lotSubmitBlockers(lot)` (chưa đo, thiếu NC [Non-Conformance] note, NG [No Good] thiếu ảnh `lot.photos[{no, sample}]`) · `fairTemplates` / `publishFairTemplate(tpl, poId)` / `createFairLot(qs)` · tái kiểm: `recordReworkReinspection(rw, [{no, sample, value}], {by, photos})`; `reworkSetState(rw, 'pass')` trả `false` khi lô còn ô NG chưa đo lại.

## i18n: `VNO.i18n` (`assets/i18n.js`, nạp đầu tiên)
Song ngữ EN / VI, mặc định EN. Thứ tự chọn: `?lang=` > `localStorage['vno.lang']` > `en`. Đổi ngôn ngữ không reload: `setLang` lưu lại, đặt `<html lang>`, phát `window` event `vno:lang`; app.js chụp trạng thái trang (tab / segment đang chọn, giá trị input / select / textarea), đóng overlay không chạy `onClose` (hash của drawer giữ nguyên), xóa toast, đặt `state.shellRole = null`, `renderRoute()` với `ctx.resume = true`, rồi khôi phục tab + giá trị. Màn hình có trạng thái ngoài DOM (wizard Sales Order) giữ bản nháp ở module và dựng lại khi `ctx.resume`. `ui.t` / `ui.lang` là bí danh.

| API | Việc |
|---|---|
| `lang()` / `setLang(l)` / `LANGS` | ngôn ngữ hiện tại (`'en'`/`'vi'`), đổi + lưu, danh sách |
| `t(key, params)` | dịch; `{x}` nội suy; giá trị param có thể là **hàm** (gọi lúc đọc, dùng cho ngày / nhãn lưu trong log); số nhiều: chuỗi EN `'one|many'` + `params.n` (EN n===1 → vế 1, ngược lại vế 2; VI dùng vế 1). Thiếu key → trả về chính key và ghi vào `missing` (không `console.error`) |
| `add({ key: [en, vi] })` | đăng ký từ điển (mỗi entry một cặp `[en, vi]`) |
| `has(key)` / `pick([en, vi])` | key có tồn tại / chọn vế theo ngôn ngữ |
| `fmtDate(iso)` | vi `DD/MM/YYYY`, en `DD Mon YYYY` (`ui.fmt.date` dùng hàm này; `cv.fmtDate` của portal luôn `DD Mon YYYY`) |
| `statusTable(ns, {state: tone})` | bảng nhãn trạng thái cục bộ; nhãn lấy từ key `<ns>.<state>` |
| `missing` (Set) / `dupes` (mảng) | key được gọi mà thiếu / key đăng ký trùng; test kỳ vọng cả hai rỗng |

**Từ điển**: mỗi file một vùng trong `assets/i18n/` (`common.js`, `data.js`, `customer-view.js`, `glossary.js` + một file mỗi screen: `sales.js`, `customer-orders.js`, `customer-requests.js`, `director.js`, `engineer.js`, `purchasing.js`, `logistics.js`, `accounting.js`, `qc.js`, `supplier.js`). Key `<ns>.<area>.<id>` chữ thường, namespace theo file: `common`/`shell`/`st`/`nav` (common.js), `role`/`data` (data.js), `cv`, `gl`, `sales`, `co`, `cr`, `dir`, `eng`, `pur`, `log`, `acc`, `qc`, `sup`. Chỉ thêm key vào file của mình, đọc `common.*` của file khác; không trùng key giữa các file; mỗi file < 800 dòng. Giá trị VI giữ nguyên đúng chữ cũ (suite cũ assert ở `?lang=vi`); giá trị EN không có dấu tiếng Việt; hai vế cùng tập `{placeholder}`.

**Quy tắc**
- Không gọi `t()` ở top-level IIFE (lúc load): sẽ đóng băng ngôn ngữ boot. Nhãn tĩnh dùng getter (`get label() { return t('x.y.z'); }`) hoặc hàm; bảng / mảng cột dựng trong `render()`. Màn hình đặt `title` là hàm (`title: () => t('sales.title')`) để tab title đổi theo ngôn ngữ.
- Biến cục bộ tên `t` che `t()`: nhập dưới bí danh (`const tt = VNO.i18n.t`, `const { t: tx } = VNO.i18n`).
- Text do hệ thống sinh dùng khóa, không chuỗi: `D.evk(date, who, key, params, tone)` → `{date, who, tone, text(getter)}` cho activity / log; `D.pushNote(role, sev, key, params, go)` cho chuông (dạng cũ `pushNote(role, sev, 'text', go)` vẫn chạy nhưng không dịch); `D.enqueueApproval(kind, refId, { titleKey, titleParams, by, amount })`; `D.reworkSetState(rw, state, who, text, tone)` nhận `text` là chuỗi hoặc `{ k, p }`. Chữ do người gõ giữ `{ text }` thuần, không dịch.
- Nhãn trạng thái qua `ui.statusBadge(kind, state)` / `ui.statusLabel` (theo ngôn ngữ), không tự giữ bảng nhãn.
- Không dịch: `ui.paper(...)` (chứng từ gửi khách), `soSentence`, `D.enDate`, CAR `*En`, dữ liệu seed người gõ, tên thương hiệu (`CRM VNO`, `VNO Customer Portal`, `VNO Supplier Portal`). Literal tiếng Việt cố ý ngoài `data.js` / `glossary.js` bọc trong `/* i18n-exempt-start: <lý do> */ … /* i18n-exempt-end */`.
- Glossary: entry `viOnly: true` chỉ bọc / liệt kê khi VI; cache tra cứu khóa theo role + ngôn ngữ.

**Component `.langsw`** (app.js, CSS trong `styles.css`): `div.langsw[role=group][aria-label]` chứa các `button.langsw-b[data-lang][aria-pressed]` (`.on` = đang chọn), có ở topbar mọi vai trò và trang login.

**Thêm chuỗi mới**: (1) thêm `'<ns>.<area>.<id>': ['English', 'Tiếng Việt']` vào `assets/i18n/<file>.js`; (2) gọi `t('<key>', params)` lúc render; (3) chạy `node tests/test-i18n-keys.mjs` (toàn bộ) hoặc `--scope screens/<file>.js` (chỉ file của mình). Test kiểm: key trùng, hình dạng cặp, placeholder, dấu tiếng Việt trong EN, key được gọi có tồn tại, literal tiếng Việt ngoài vùng miễn trừ, helper cũ `T(vi, en)`, `lang === 'en' ?` viết tay. Suite cũ chạy ở `?lang=vi`; `tests/test-i18n.mjs` quét 2 ngôn ngữ.

## Customer Portal API (`VNO.cv`, `assets/customer-view.js`)
Role `customer` (R9, layout `portal`, user `u-cus` Michael Slunder / Pacific Press, UI mặc định tiếng Anh, có VI cho chrome; tài liệu / `sentence` / CAR luôn EN). **Màn hình khách chỉ đọc `VNO.cv`, không đụng `VNO.data`.** Mọi projection là object mới dựng từ allowlist (không spread bản ghi gốc), lọc theo `cid()`; id của khách khác / không tồn tại → `null`. Ngày giữ ISO; chuỗi tiếng Anh; văn bản tự do qua `scrub()` (`cv._noScrub = true` tắt scrub để test chứng minh projection tự sạch). Hợp đồng đầy đủ nằm ở đầu file `customer-view.js`.

| Nhóm | API |
|---|---|
| Định danh | `me()`, `cid()`, `customer()` → `{id,name,short,contact}`, `today` |
| Nhãn | `STATUS[kind][key] = [label, tone]` (kind: inquiry, quotation, order, po, payment, complaint, car, qc, arrival, cpo), `lbl(kind,key)`; `STATUS_LOCAL.customer = cv.STATUS` (app.js chọn theo `dataset.role` trước layout) |
| RFQ | `inquiries()` / `inquiry(id)` → `{id, rfq, start, due, status, statusLabel, source:'sales'\|'portal', note, items[], drawings[], quotationIds[]}` |
| Báo giá | `quotations()` / `quotation(id)` → `{id, number, inquiryId, validUntil, expired, status, canDecide, canAccept, canUploadPO, lines[], total, payment, leadTime, incoterm, decision, revisionNote, orderId, poUpload}` (chỉ báo giá có `sentAt`; mọi trường đọc từ bản chụp `q.sent` lúc gửi; `statusKey` thêm `declined` / `updating`; `canUploadPO` = `sent` còn hạn hoặc `won`, chưa có SO / PO đang xử lý) |
| Đơn | `orders()` / `order(id)` → `{id, customerPo, promised, forecast, late, delayDays, progress, stage, sentence (== D.soSentence(D.soTrack(so))), lines[], lots[{n, label, qty, progress, forecast, qc, steps[{key,label,date,state:'done'\|'now'\|'todo'}], shipments[]}], shipments[], payments{total,paid,next}, invoices[]}`; `shipment(id)` |
| Tài liệu | `documents()` / `document(id)` → `{id, kind:'fair'\|'mtc'\|'cipl', kindLabel, name (sinh lại), date, orderId, lot, serial (đã `maskSerial`), kb}`; chỉ FAIR lô `packSent`, MTC (Material Test Certificate) đã accepted, CI/PL `released` của khách |
| AR | `invoices()` / `invoice(id)` (chỉ `isIssued`), `invoiceTotals()` → `{invoiced, paid, outstanding, overdue}`, `scheduled()` (tranche chưa lập phiếu: `to_invoice` / `scheduled`) |
| Khiếu nại | `complaints()` / `complaint(id)` → `{…, customerText, status, published:{rootCause, actions, date}\|null}`; `shippedForClaim()` → shipment đã giao + dòng của khách |
| PO upload | `poUploads()` → `{id, quotationId, poNo, poDate, requestedDate, file, note, state: received\|converted\|rejected, orderId, rejectReason}` (`received` đã có SO của báo giá thì hiện `converted`) |
| Ghi | `submitInquiry({rfq,due,note,items[],drawings[]})`, `decideQuotation(quotationId, 'accept'\|'reject'\|'revise', note)`, `uploadPO({quotationId,poNo,poDate,requestedDate,file,note})` → `{ok, upload}`, `submitComplaint({shipment,customerPo,itemNo,qty,text,serial,claimNo,remedy})`; ép `customerId = cid()`, `source:'portal'`, bắn `window` event `vno:data`, trả `{ok, error?}` |
| Bảo vệ / định dạng | `scrub(text)` (chỉ chữ VNO viết; tên nhà máy, mã có chữ số, PO nhà máy), `maskSerial(serial)` (serial FAIR do Sales nhập; serial khách gõ giữ nguyên), `fmtDate(iso)` → `DD Mon YYYY` |

**Mutator dùng chung đã nâng lên `data.js` (Sales và portal cùng gọi, không nhân đôi):** `createInquiry(spec)`, `createComplaint(spec)` (tự mở CAR), `loseQuotation(q, reason, by)`, `customerDecideQuotation(q, decision, note, by)` (accept → `won` + `customerDecision`; reject → `loseQuotation` với lý do của khách; revise → `revise` + `customerRequest`; mỗi nhánh gọi `pushNote('sales', …)`), `receiveCustomerPO(spec)` → mục `customerPoInbox`, `convertCustomerPO(cpoId, soId)`, `publishCar(car, {rootCause, actions})` → `car.published = {rootCause, actions, date}` (cả hai là chữ EN; thiếu một ô → `null`, không công bố, không rơi về `analysisVn` / `actions`) · `markQuotationSent(q)` (status `sent` + `sentAt` + bản chụp `sent`; `sentSnapshot(q)`) · `convertCustomerPOsOfQuotation(quotationId, soId)`. `reviseQuotation` không chép `customerDecision`, `customerRequest`, `sentAt`, `sent`, `supersededBy`, `lostReason` sang revision. CAR có thêm `actionsEn` (Engineer nhập, Sales sửa khi gửi).

**Trường dữ liệu thêm (chỉ thêm, bản ghi cũ không đổi):** `inquiry.source`, `quotation.customerRequest / customerDecision`, `car.published`, `complaint.customerText`; bộ sưu tập `D.customerPoInbox[] = {id:'CPO-26-nnn', customerId, quotationId, poNo, poDate, requestedDate, file, note, date, state:'received'\|'converted'\|'rejected', soId, rejectReason}`; `D.roles.<role>.brand`; `D.defineNotes('customer', …)` (chuông của khách chỉ tính từ bản ghi của khách).

**Nhãn trạng thái theo vai trò:** `STATUS_LOCAL` khóa theo `dataset.role` trước, `dataset.layout` sau (khách dùng `cv.STATUS`, nhà máy dùng bảng portal tiếng Việt). Role switcher ẩn với `PORTALS = ['supplier','customer']` trừ `?demo=1`; phiên khách bị khóa ở `#/customer/*`.
