① 规格从商品名列(被单位/数量/单价挤到极窄、规格与商品名都折行)移到卡片行下方独占一行; ② 单价输入预填去 0:0 视为未定价 ⇒ 留空(点击即可直接填,无需先删 0),>0 才预填;pickCostPriceHint 的「0 合法」语义不变。 均只改自采列表卡片,新增两条契约测试。
791 lines
28 KiB
JavaScript
791 lines
28 KiB
JavaScript
const {
|
||
buildCategoryPickerOptions,
|
||
enrichItemCategoryFields,
|
||
applyManualCategory,
|
||
applyCategoryInput,
|
||
findCategoryOptionByName,
|
||
filterCategoryOptions,
|
||
categoryDisplayText,
|
||
categoryHasValue,
|
||
getCategoryDisplay,
|
||
} = require('./orderCategory');
|
||
const { buildUnitPicker, getUnitDictionaryLabels } = require('./units');
|
||
const { formatChinaDate, calendarDayYmd, chinaTodayYmd, shiftChinaYmd } = require('./chinaDate');
|
||
|
||
const WEEKDAY = ['日', '一', '二', '三', '四', '五', '六'];
|
||
const AGGREGATE_PREF_KEY = 'purchase_list.aggregate_same_products';
|
||
const PERIOD_OPTIONS = [
|
||
{ key: 'today', label: '今日' },
|
||
{ key: '7d', label: '近七天' },
|
||
{ key: '30d', label: '近30天' },
|
||
];
|
||
|
||
const DATE_FIELD_OPTIONS = [
|
||
{ key: 'delivery_date', label: '配送日' },
|
||
{ key: 'created_at', label: '下单日' },
|
||
];
|
||
|
||
const DATE_FIELD_LABELS = DATE_FIELD_OPTIONS.map((item) => item.label);
|
||
|
||
function pad2(n) {
|
||
return String(n).padStart(2, '0');
|
||
}
|
||
|
||
function fmtLocalDate(date = new Date()) {
|
||
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
|
||
}
|
||
|
||
function shiftLocalDate(days) {
|
||
const date = new Date();
|
||
date.setDate(date.getDate() + days);
|
||
return fmtLocalDate(date);
|
||
}
|
||
|
||
function resolvePeriodRange(preset) {
|
||
const today = fmtLocalDate();
|
||
switch (preset) {
|
||
case 'today':
|
||
return { from: today, to: today };
|
||
case '7d':
|
||
return { from: shiftLocalDate(-6), to: today };
|
||
case '30d':
|
||
return { from: shiftLocalDate(-29), to: today };
|
||
default:
|
||
return { from: shiftLocalDate(-6), to: today };
|
||
}
|
||
}
|
||
|
||
function formatDayLabel(dayKey) {
|
||
if (!dayKey) return '未知日期';
|
||
const today = chinaTodayYmd();
|
||
const yesterday = shiftChinaYmd(today, -1);
|
||
if (dayKey === today) return '今天';
|
||
if (dayKey === yesterday) return '昨天';
|
||
const parts = dayKey.split('-');
|
||
if (parts.length !== 3) return dayKey;
|
||
const date = new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
|
||
const weekday = WEEKDAY[date.getDay()] || '';
|
||
return `${Number(parts[1])}月${Number(parts[2])}日 周${weekday}`;
|
||
}
|
||
|
||
function formatPeriodLabel(from, to) {
|
||
if (!from || !to) return '';
|
||
if (from === to) return formatDayLabel(from);
|
||
return `${from} 至 ${to}`;
|
||
}
|
||
|
||
function summarizePurchaseGroups(categoryGroups, rows, queryDate) {
|
||
let pending = 0;
|
||
let total = 0;
|
||
let amount = 0;
|
||
const list = Array.isArray(rows) && rows.length
|
||
? rows
|
||
: (categoryGroups || []).flatMap((g) =>
|
||
(g.productGroups || []).flatMap((p) => p.items || [])
|
||
);
|
||
for (const row of list) {
|
||
total += 1;
|
||
if (canCompletePurchase(row)) pending += 1;
|
||
const qty = Number(row.actual_qty_input != null ? row.actual_qty_input : row.actual_qty || row.purchase_qty);
|
||
const price = Number(row.actual_price_input != null ? row.actual_price_input : row.actual_price || row.purchase_price);
|
||
if (Number.isFinite(qty) && qty > 0 && Number.isFinite(price) && price > 0) {
|
||
amount += qty * price;
|
||
}
|
||
}
|
||
const dateKey = /^\d{4}-\d{2}-\d{2}$/.test(String(queryDate || ''))
|
||
? String(queryDate)
|
||
: '';
|
||
return {
|
||
heroDate: dateKey ? formatDayLabel(dateKey) : '全部',
|
||
completedCount: Math.max(0, total - pending),
|
||
totalCount: total,
|
||
pendingCount: pending,
|
||
todayTotalText: amount.toFixed(2),
|
||
};
|
||
}
|
||
|
||
function decorateHistoryRow(row) {
|
||
const qty = Number(row.actual_qty);
|
||
const qtyNum = Number.isFinite(qty) && qty > 0 ? qty : Number(row.purchase_qty);
|
||
// 0 是合法成本价:只有「未填」才回退下单价(与 Web 采购管理同口径)。
|
||
// 金额仍与 Web 一致:total_amount > 0 优先,否则 数量 × 单价(0 成本行得 0 而不是「—」)。
|
||
const priceNum = pickStoredPrice(row.actual_price, row.purchase_price);
|
||
const dbTotal = Number(row.total_amount);
|
||
const computed = Number.isFinite(qtyNum) && qtyNum > 0 && priceNum !== null && priceNum >= 0
|
||
? qtyNum * priceNum
|
||
: null;
|
||
const total = Number.isFinite(dbTotal) && dbTotal > 0 ? dbTotal : computed;
|
||
return {
|
||
...row,
|
||
display_qty: Number.isFinite(qtyNum) ? qtyNum : row.purchase_qty || 0,
|
||
display_price: Number.isFinite(priceNum) ? priceNum : 0,
|
||
total_price: total,
|
||
total_price_text: total != null ? total.toFixed(2) : '—',
|
||
spi_pending: isSelfPurchaseInbound(row) && Number(row.purchase_status) === 10,
|
||
};
|
||
}
|
||
|
||
function groupByDay(rows) {
|
||
const map = new Map();
|
||
for (const row of rows) {
|
||
const dayKey = row.history_day || 'unknown';
|
||
if (!map.has(dayKey)) {
|
||
map.set(dayKey, { dayKey, dayLabel: formatDayLabel(dayKey), items: [], totalAmount: 0 });
|
||
}
|
||
const group = map.get(dayKey);
|
||
group.items.push(row);
|
||
if (typeof row.total_price === 'number' && Number.isFinite(row.total_price)) {
|
||
group.totalAmount += row.total_price;
|
||
}
|
||
}
|
||
return Array.from(map.values())
|
||
.map((group) => ({
|
||
...group,
|
||
totalAmountText: group.totalAmount > 0 ? group.totalAmount.toFixed(2) : '',
|
||
}))
|
||
.sort((a, b) => b.dayKey.localeCompare(a.dayKey));
|
||
}
|
||
|
||
function flattenHistoryExportRows(dayGroups) {
|
||
const rows = [];
|
||
for (const group of dayGroups || []) {
|
||
for (const item of group.items || []) {
|
||
const qty = Number(item.display_qty);
|
||
const price = Number(item.display_price);
|
||
let amount = '';
|
||
if (typeof item.total_price === 'number' && Number.isFinite(item.total_price)) {
|
||
amount = Math.round(item.total_price * 100) / 100;
|
||
} else if (Number.isFinite(qty) && Number.isFinite(price) && qty > 0 && price > 0) {
|
||
amount = Math.round(qty * price * 100) / 100;
|
||
}
|
||
rows.push([
|
||
group.dayKey || '',
|
||
item.item_name || '未知商品',
|
||
Number.isFinite(qty) ? qty : 0,
|
||
item.unit || '个',
|
||
Number.isFinite(price) ? price : 0,
|
||
amount,
|
||
]);
|
||
}
|
||
}
|
||
return rows;
|
||
}
|
||
|
||
function applyDayCollapseState(groups, expandedDayKeys) {
|
||
const activeKeys = new Set(groups.map((g) => g.dayKey));
|
||
for (const key of [...expandedDayKeys]) {
|
||
if (!activeKeys.has(key)) expandedDayKeys.delete(key);
|
||
}
|
||
const hasUserExpanded = expandedDayKeys.size > 0;
|
||
return groups.map((group, idx) => {
|
||
if (!hasUserExpanded && idx === 0) {
|
||
expandedDayKeys.add(group.dayKey);
|
||
return { ...group, collapsed: false };
|
||
}
|
||
return { ...group, collapsed: !expandedDayKeys.has(group.dayKey) };
|
||
});
|
||
}
|
||
|
||
function formatLocalDate(date = new Date()) {
|
||
return formatChinaDate(date);
|
||
}
|
||
|
||
function toInputString(value, fallback) {
|
||
if (value !== undefined && value !== null && value !== '') {
|
||
return String(value);
|
||
}
|
||
if (fallback !== undefined && fallback !== null && fallback !== '') {
|
||
return String(fallback);
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/** 「未填」= null / undefined / 空串;**0 是填了的合法数值**。 */
|
||
function isFilledPrice(value) {
|
||
return value !== undefined && value !== null && String(value).trim() !== '';
|
||
}
|
||
|
||
/** 取第一个「填了」的数值(0 也算填了,不会被跳过);全未填返回 null。 */
|
||
function pickStoredPrice(...values) {
|
||
for (const value of values) {
|
||
if (!isFilledPrice(value)) continue;
|
||
const num = Number(value);
|
||
if (Number.isFinite(num)) return num;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** 实采默认价:当前实采/采购价 → 上次成交建议价
|
||
* ⚠️ 0 是合法实采价(「允许成本价为 0」):只有「未填」才回退。
|
||
* 若把 0 当缺失,成本价改成 0 之后列表预填又会显示回下单价/建议价。
|
||
*/
|
||
function pickCostPriceHint(row) {
|
||
const filled = pickStoredPrice(row?.actual_price, row?.purchase_price);
|
||
if (filled !== null) return filled;
|
||
const suggested = Number(row?.suggested_price);
|
||
if (Number.isFinite(suggested) && suggested > 0) return suggested;
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 单价输入**预填**:0 视为「尚未定价」⇒ **留空**(点击即可直接输入,免得先删一个 0);
|
||
* 只有 > 0 的真实价才预填。⚠️ 只影响「预填」,不改 `pickCostPriceHint` 的「0 合法」语义
|
||
* (取值/回退仍按 0 处理,提交空串也仍是 0)。
|
||
*/
|
||
function prefillPriceInput(hint) {
|
||
const n = Number(hint);
|
||
return Number.isFinite(n) && n > 0 ? String(hint) : '';
|
||
}
|
||
|
||
function resolveActualQty(row) {
|
||
const raw = row?.actual_qty_input;
|
||
if (raw !== undefined && raw !== null && String(raw).trim() !== '') {
|
||
return Number(raw);
|
||
}
|
||
return Number(row?.actual_qty ?? row?.purchase_qty);
|
||
}
|
||
|
||
function resolveActualPrice(row) {
|
||
const raw = row?.actual_price_input;
|
||
if (raw !== undefined && raw !== null && String(raw).trim() !== '') {
|
||
return Number(raw);
|
||
}
|
||
const hint = pickCostPriceHint(row);
|
||
return hint === '' ? Number(row?.actual_price ?? row?.purchase_price) : hint;
|
||
}
|
||
|
||
function displayText(value, fallback = '') {
|
||
if (value === undefined || value === null) return fallback;
|
||
const text = String(value).trim();
|
||
if (!text || text.toLowerCase() === 'null') return fallback;
|
||
return text;
|
||
}
|
||
|
||
function resolveCategoryDisplayName(categoryCode, categoryName) {
|
||
const code = displayText(categoryCode, '');
|
||
const name = displayText(categoryName, '');
|
||
if (!name || (code && name.toUpperCase() === code.toUpperCase())) {
|
||
return '未分类';
|
||
}
|
||
return name;
|
||
}
|
||
|
||
function extractNameFromRemark(remark) {
|
||
if (!remark) return '';
|
||
const stripped = String(remark).replace(/^\[[^\]]+\]\s*/, '').trim();
|
||
const patterns = [
|
||
/未匹配商品(?:流转)?:\s*(.+)$/,
|
||
/无绑定供应商:\s*(.+)$/,
|
||
];
|
||
for (const pattern of patterns) {
|
||
const match = stripped.match(pattern);
|
||
if (match?.[1]?.trim()) return match[1].trim();
|
||
}
|
||
return '';
|
||
}
|
||
|
||
const SYSTEM_PURCHASE_REMARK_SEGMENT =
|
||
/^(?:\[[^\]]+\]\s*)?(?:(?:一级分类|二级分类|分类)「[^」]*」无绑定供应商[,,]\s*流转至自有采购员|未匹配商品「[^」]*」[,,]\s*流转至自有采购员自采|未匹配商品:\s*.+|无商品分类,按规则流转至自有采购员|订单保存:(?:分类无供应商|无分类商品)|强制覆盖:订单明细必须进自采或备货,禁止遗漏|可修改时限内新增商品自动分配:未匹配供应商,转自采|手动分配:未指定供应商,转自采|分配兜底:未匹配供应商,转自采|采购员加单:自采|改派供应商,取消原无货流转自采|分配重新匹配供应商,取消原无货流转自采|改回自采,恢复待采|入库后转挂自采(已完成)|入库后转挂履约方|仓内加工成品:系统自动完成自采并生成待验|仓内加工:改采原料独立入库,成品自采跳过|取消仓内加工,恢复待采|库存抵扣\s+[0-9.eE+-]+\s*[,,]?\s*本单采购\s+[0-9.eE+-]+)$/;
|
||
|
||
function purchaseRemarkDisplay(remark) {
|
||
return String(remark || '')
|
||
.replace(/\s*\|\s*/g, ' ')
|
||
.replace(/规格:\s*[^|]*/g, '')
|
||
.replace(/^\[[^\]]+\]\s*/, '')
|
||
.split(/[;;]/)
|
||
.map((part) => String(part || '').trim())
|
||
.filter((part) => part && !SYSTEM_PURCHASE_REMARK_SEGMENT.test(part))
|
||
.join(';')
|
||
.trim();
|
||
}
|
||
|
||
function collectProductRemarkText(items) {
|
||
const seen = [];
|
||
for (const row of items || []) {
|
||
const text = purchaseRemarkDisplay(row && row.order_item_remark);
|
||
if (text && seen.indexOf(text) < 0) seen.push(text);
|
||
}
|
||
return seen.join(';');
|
||
}
|
||
|
||
function enrichPurchaseRowCategory(row, categoryOptions) {
|
||
const enriched = enrichItemCategoryFields(row, categoryOptions);
|
||
return {
|
||
...enriched,
|
||
category_display: categoryDisplayText(enriched),
|
||
category_has_value: categoryHasValue(enriched),
|
||
};
|
||
}
|
||
|
||
function isSelfPurchaseInbound(row) {
|
||
return (
|
||
String(row?.source_type || '') === 'self_purchase_inbound' ||
|
||
String(row?.purchase_code || '').indexOf('SPI-') === 0
|
||
);
|
||
}
|
||
|
||
function canAssignSupplier(row) {
|
||
if (isSelfPurchaseInbound(row) || isWarehouseDemandPurchase(row)) return false;
|
||
const status = Number(row?.purchase_status);
|
||
return status === 10 || status === 32;
|
||
}
|
||
|
||
function isWarehouseDemandPurchase(row) {
|
||
return row?.warehouse_demand === true || row?.warehouse_demand === 't';
|
||
}
|
||
|
||
function canCompletePurchase(row) {
|
||
if (isSelfPurchaseInbound(row) || isWarehouseDemandPurchase(row)) return false;
|
||
const status = Number(row?.purchase_status);
|
||
return status === 10 || status === 32;
|
||
}
|
||
|
||
function canSkipWarehouseDemand(_row) {
|
||
return false;
|
||
}
|
||
|
||
function splitActualQtyByPlan(planQtys, totalActual) {
|
||
const n = planQtys.length;
|
||
if (n === 0) return [];
|
||
const actual = Number(totalActual);
|
||
if (!Number.isFinite(actual) || actual < 0) return planQtys.map(() => 0);
|
||
const plans = planQtys.map((q) => {
|
||
const num = Number(q);
|
||
return Number.isFinite(num) && num > 0 ? num : 0;
|
||
});
|
||
const planSum = plans.reduce((s, q) => s + q, 0);
|
||
if (planSum <= 1e-12) {
|
||
const even = Math.round((actual / n) * 1000) / 1000;
|
||
const out = Array.from({ length: n }, () => even);
|
||
const drift = Math.round((actual - out.reduce((s, q) => s + q, 0)) * 1000) / 1000;
|
||
out[n - 1] = Math.round((out[n - 1] + drift) * 1000) / 1000;
|
||
return out;
|
||
}
|
||
const out = [];
|
||
let allocated = 0;
|
||
for (let i = 0; i < n; i += 1) {
|
||
if (i === n - 1) {
|
||
out.push(Math.round((actual - allocated) * 1000) / 1000);
|
||
} else {
|
||
const share = Math.round((actual * (plans[i] / planSum)) * 1000) / 1000;
|
||
out.push(share);
|
||
allocated += share;
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function isSkuDirectDelivery(row) {
|
||
return row && (row.direct_delivery === true || row.direct_delivery === 't' || row.direct_delivery === 1);
|
||
}
|
||
|
||
function needsDirectDeliveryPhoto(row) {
|
||
return isSkuDirectDelivery(row) && row.requires_photo_inspection !== false;
|
||
}
|
||
|
||
function directDeliveryPhotoCount(row) {
|
||
if (Array.isArray(row?.direct_delivery_photo_urls)) return row.direct_delivery_photo_urls.length;
|
||
if (Array.isArray(row?.direct_delivery_photos)) return row.direct_delivery_photos.length;
|
||
const n = Number(row?.direct_delivery_photo_count);
|
||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||
}
|
||
|
||
function productGroupKey(row) {
|
||
const day = purchaseDeliveryDay(row);
|
||
const sku = displayText(row.sku_code, '');
|
||
const name = displayText(row.item_name, '未知商品');
|
||
const unit = displayText(row.unit, '个');
|
||
return `${day}||${sku || name}||${unit}`;
|
||
}
|
||
|
||
/** 待采分组日:订单配送日(中国日历);无订单回退采购建单日 */
|
||
function purchaseDeliveryDay(row) {
|
||
const delivery = calendarDayYmd(row?.delivery_date);
|
||
if (delivery) return delivery;
|
||
const created = formatChinaDate(row?.created_at);
|
||
return created || 'unknown';
|
||
}
|
||
|
||
function buildProductGroups(rows) {
|
||
const map = new Map();
|
||
for (const row of rows) {
|
||
const key = productGroupKey(row);
|
||
if (!map.has(key)) {
|
||
map.set(key, {
|
||
productKey: key,
|
||
productName: displayText(row.item_name, '未知商品'),
|
||
unit: displayText(row.unit, '个'),
|
||
unitIndex: row.unitIndex || 0,
|
||
unitOptions: row.unitOptions || getUnitDictionaryLabels(),
|
||
items: [],
|
||
planQtyTotal: 0,
|
||
pendingCount: 0,
|
||
needs_product_setup: false,
|
||
collapsedChildren: false,
|
||
});
|
||
}
|
||
const group = map.get(key);
|
||
group.items.push(row);
|
||
group.planQtyTotal += Number(row.purchase_qty) || 0;
|
||
if (canCompletePurchase(row)) group.pendingCount += 1;
|
||
if (row.needs_product_setup) group.needs_product_setup = true;
|
||
}
|
||
return Array.from(map.values())
|
||
.map((group) => {
|
||
const first = group.items[0];
|
||
const planText = Number.isInteger(group.planQtyTotal)
|
||
? String(group.planQtyTotal)
|
||
: group.planQtyTotal.toFixed(2).replace(/\.?0+$/, '');
|
||
const skipAll = false;
|
||
const recordAll = group.items.length > 0 && group.items.every((row) => isWarehouseDemandPurchase(row));
|
||
return {
|
||
...group,
|
||
warehouseDemandAll: skipAll,
|
||
warehouseDemandRecord: recordAll,
|
||
planQtyText: planText,
|
||
actual_qty_input: toInputString(null, group.planQtyTotal),
|
||
actual_price_input: prefillPriceInput(pickCostPriceHint(first)),
|
||
unit: displayText(first?.unit, group.unit),
|
||
unitIndex: first?.unitIndex || 0,
|
||
unitOptions: first?.unitOptions || group.unitOptions,
|
||
items: [...group.items].sort((a, b) =>
|
||
displayText(a.purchase_code, '').localeCompare(displayText(b.purchase_code, ''), 'zh-CN')
|
||
),
|
||
direct_delivery: group.items.some(isSkuDirectDelivery),
|
||
photoRequired: group.items.some(needsDirectDeliveryPhoto),
|
||
photoCount: Math.max(0, ...group.items.map(directDeliveryPhotoCount)),
|
||
photoUrls: (group.items.find((row) => (row.direct_delivery_photo_urls || []).length) || {})
|
||
.direct_delivery_photo_urls || [],
|
||
remarkText: collectProductRemarkText(group.items),
|
||
};
|
||
})
|
||
.sort((a, b) => a.productName.localeCompare(b.productName, 'zh-CN'));
|
||
}
|
||
|
||
function decoratePurchaseRow(row, categoryOptions) {
|
||
const categoryCode = displayText(row.category_code, '');
|
||
const resolvedName =
|
||
displayText(row.item_name, '') ||
|
||
extractNameFromRemark(row.remark) ||
|
||
displayText(row.sku_code, '');
|
||
const needsProductSetup = Boolean(row.needs_product_setup);
|
||
const supplyUnit = displayText(row.unit, '个');
|
||
const { unit, unitOptions, unitIndex } = buildUnitPicker(supplyUnit, getUnitDictionaryLabels());
|
||
return enrichPurchaseRowCategory({
|
||
...row,
|
||
item_name: resolvedName || '未知商品',
|
||
item_name_input: resolvedName || '',
|
||
category_code: categoryCode,
|
||
category_name: resolveCategoryDisplayName(categoryCode, row.category_name),
|
||
unit,
|
||
unitIndex,
|
||
unitOptions,
|
||
needs_product_setup: needsProductSetup,
|
||
can_assign_supplier: canAssignSupplier(row),
|
||
can_skip_warehouse: canSkipWarehouseDemand(row),
|
||
order_supplier_name: displayText(row.order_supplier_name, ''),
|
||
actual_qty_input: toInputString(row.actual_qty, row.purchase_qty),
|
||
actual_price_input: prefillPriceInput(pickCostPriceHint(row)),
|
||
direct_delivery: isSkuDirectDelivery(row),
|
||
photoRequired: needsDirectDeliveryPhoto(row),
|
||
photoCount: directDeliveryPhotoCount(row),
|
||
direct_delivery_photo_urls: Array.isArray(row.direct_delivery_photo_urls)
|
||
? row.direct_delivery_photo_urls
|
||
: [],
|
||
}, categoryOptions);
|
||
}
|
||
|
||
function buildCategoryProductGroups(items, aggregateSameProducts = true) {
|
||
if (aggregateSameProducts !== false) return buildProductGroups(items);
|
||
// 逐单:productKey 必须唯一,否则同品多单 wx:key / findProductGroup 互相覆盖
|
||
return items
|
||
.map((item) => {
|
||
const group = buildProductGroups([item])[0];
|
||
if (!group) return null;
|
||
const code = displayText(item.purchase_code, '');
|
||
return {
|
||
...group,
|
||
productKey: `flat||${code || productGroupKey(item)}`,
|
||
collapsedChildren: false,
|
||
};
|
||
})
|
||
.filter(Boolean);
|
||
}
|
||
|
||
function leafCategoryNameHint(raw) {
|
||
const name = displayText(raw, '');
|
||
if (!name) return '';
|
||
if (name.includes(' / ')) {
|
||
const parts = name.split(' / ').map((p) => p.trim()).filter(Boolean);
|
||
return parts[parts.length - 1] || name;
|
||
}
|
||
if (name.includes('/')) {
|
||
const parts = name.split('/').map((p) => p.trim()).filter(Boolean);
|
||
return parts[parts.length - 1] || name;
|
||
}
|
||
return name;
|
||
}
|
||
|
||
/** 分类树排序用:按名称匹配,优先二级分类(勿与 orderCategory.findCategoryOptionByName 重名) */
|
||
function findCategoryOptionForTreeSort(categoryOptions, categoryName) {
|
||
const raw = displayText(categoryName, '');
|
||
if (!raw || raw === '未分类' || raw === '-') return null;
|
||
const opts = Array.isArray(categoryOptions) ? categoryOptions : [];
|
||
const candidates = [raw, leafCategoryNameHint(raw)].filter(
|
||
(name, index, arr) => name && arr.indexOf(name) === index
|
||
);
|
||
for (const name of candidates) {
|
||
const matches = opts.filter((o) => displayText(o.category_name, '') === name);
|
||
if (matches.length === 0) continue;
|
||
const l2 = matches.find((o) => displayText(o.parent_code, '') || Number(o.level) === 2);
|
||
return l2 || matches[0];
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function categoryTreeSortMeta(categoryCode, categoryOptions, categoryName) {
|
||
const UNCAT = 999999;
|
||
const code = displayText(categoryCode, '');
|
||
const opts = Array.isArray(categoryOptions) ? categoryOptions : [];
|
||
const byCode = new Map(opts.map((o) => [displayText(o.category_code, ''), o]));
|
||
let row = (code && byCode.get(code)) || null;
|
||
if (!row && code) {
|
||
row = opts.find((o) => displayText(o.category_code, '') === code) || null;
|
||
}
|
||
// 有编码时禁止用可能错误的快照名去匹配其它分类(避免「蔬菜」编码被名称「菌菇」拐走)
|
||
if (!row && !code) {
|
||
row = findCategoryOptionForTreeSort(opts, categoryName);
|
||
}
|
||
if (!row) {
|
||
const fallback = code
|
||
? displayText(categoryName, '') && displayText(categoryName, '') !== code
|
||
? displayText(categoryName, '')
|
||
: code
|
||
: displayText(categoryName, '') || code;
|
||
if (!fallback) {
|
||
return { l1Sort: UNCAT, l1Name: '未分类', l2Sort: UNCAT, l2Name: '', label: '未分类' };
|
||
}
|
||
const leaf = leafCategoryNameHint(fallback) || fallback;
|
||
return {
|
||
l1Sort: leaf === '未分类' ? UNCAT : 500000,
|
||
l1Name: leaf,
|
||
l2Sort: 0,
|
||
l2Name: '',
|
||
label: fallback,
|
||
categoryCode: code || undefined,
|
||
};
|
||
}
|
||
let l1 = row;
|
||
const parentCode = displayText(row.parent_code, '');
|
||
if (parentCode && byCode.has(parentCode)) {
|
||
l1 = byCode.get(parentCode);
|
||
} else if (Number(row.level) === 2 && parentCode) {
|
||
l1 = byCode.get(parentCode) || row;
|
||
}
|
||
const isL2 = Boolean(parentCode) || Number(row.level) === 2;
|
||
return {
|
||
l1Sort: Number(l1.sort_order) || 0,
|
||
l1Name: displayText(l1.category_name || l1.label, '未分类'),
|
||
l2Sort: isL2 ? Number(row.sort_order) || 0 : 0,
|
||
l2Name: isL2 ? displayText(row.category_name, '') : '',
|
||
label: displayText(row.label || row.category_name, '未分类'),
|
||
categoryCode: displayText(row.category_code, code),
|
||
};
|
||
}
|
||
|
||
function compareCategoryGroupsByTree(a, b, categoryOptions) {
|
||
const ma = categoryTreeSortMeta(a.categoryCode, categoryOptions, a.categoryName);
|
||
const mb = categoryTreeSortMeta(b.categoryCode, categoryOptions, b.categoryName);
|
||
if (ma.l1Sort !== mb.l1Sort) return ma.l1Sort - mb.l1Sort;
|
||
const byL1 = ma.l1Name.localeCompare(mb.l1Name, 'zh-CN');
|
||
if (byL1 !== 0) return byL1;
|
||
if (ma.l2Sort !== mb.l2Sort) return ma.l2Sort - mb.l2Sort;
|
||
const byL2 = ma.l2Name.localeCompare(mb.l2Name, 'zh-CN');
|
||
if (byL2 !== 0) return byL2;
|
||
return String(a.categoryName || '').localeCompare(String(b.categoryName || ''), 'zh-CN');
|
||
}
|
||
|
||
function groupByCategory(rows, aggregateSameProducts = true, categoryOptions = []) {
|
||
const byDay = new Map();
|
||
for (const row of rows || []) {
|
||
const dayKey = purchaseDeliveryDay(row);
|
||
if (!byDay.has(dayKey)) byDay.set(dayKey, []);
|
||
byDay.get(dayKey).push(row);
|
||
}
|
||
const dayKeys = [...byDay.keys()].sort((a, b) => String(a).localeCompare(String(b)));
|
||
const result = [];
|
||
for (const dayKey of dayKeys) {
|
||
const dayRows = byDay.get(dayKey) || [];
|
||
const map = new Map();
|
||
for (const row of dayRows) {
|
||
const meta = categoryTreeSortMeta(row.category_code, categoryOptions, row.category_name);
|
||
const categoryCode = meta.categoryCode || row.category_code || '';
|
||
const categoryKey = categoryCode || meta.label || '__uncategorized__';
|
||
const categoryName =
|
||
meta.label && meta.label !== '未分类'
|
||
? meta.label
|
||
: resolveCategoryDisplayName(categoryCode, row.category_name);
|
||
if (!map.has(categoryKey)) {
|
||
map.set(categoryKey, {
|
||
categoryKey,
|
||
categoryCode,
|
||
categoryName,
|
||
pendingCount: 0,
|
||
items: [],
|
||
});
|
||
}
|
||
const group = map.get(categoryKey);
|
||
group.items.push(row);
|
||
if (canCompletePurchase(row)) {
|
||
group.pendingCount += 1;
|
||
}
|
||
}
|
||
const cats = Array.from(map.values())
|
||
.map((group) => {
|
||
const productGroups = buildCategoryProductGroups(group.items, aggregateSameProducts);
|
||
return {
|
||
...group,
|
||
categoryName: displayText(group.categoryName, '未分类'),
|
||
productGroups,
|
||
productCount: productGroups.length,
|
||
items: group.items,
|
||
};
|
||
})
|
||
.sort((a, b) => compareCategoryGroupsByTree(a, b, categoryOptions));
|
||
cats.forEach((group, index) => {
|
||
result.push({
|
||
...group,
|
||
categoryKey: `${dayKey}||${group.categoryKey}`,
|
||
dayKey,
|
||
dayLabel: formatDayLabel(dayKey),
|
||
showDayHeader: index === 0,
|
||
isEarliestDay: dayKey === dayKeys[0],
|
||
});
|
||
});
|
||
}
|
||
return result;
|
||
}
|
||
|
||
function applyCategoryCollapseState(groups, expandedCategoryKeys) {
|
||
const activeKeys = new Set(groups.map((g) => g.categoryKey));
|
||
for (const key of expandedCategoryKeys) {
|
||
if (!activeKeys.has(key)) expandedCategoryKeys.delete(key);
|
||
}
|
||
return groups.map((group) => {
|
||
if (group.pendingCount === 0) {
|
||
expandedCategoryKeys.delete(group.categoryKey);
|
||
return { ...group, collapsed: true };
|
||
}
|
||
return {
|
||
...group,
|
||
collapsed: !expandedCategoryKeys.has(group.categoryKey),
|
||
};
|
||
});
|
||
}
|
||
|
||
function mergeCategoryGroupInputs(prevGroups, nextGroups) {
|
||
if (!prevGroups?.length) return nextGroups;
|
||
const prevProductByKey = new Map();
|
||
const prevRowByCode = new Map();
|
||
for (const group of prevGroups) {
|
||
for (const pg of group.productGroups || []) {
|
||
prevProductByKey.set(pg.productKey, pg);
|
||
for (const row of pg.items || []) {
|
||
if (row.purchase_code) prevRowByCode.set(row.purchase_code, row);
|
||
}
|
||
}
|
||
for (const row of group.items || []) {
|
||
if (row.purchase_code) prevRowByCode.set(row.purchase_code, row);
|
||
}
|
||
}
|
||
return nextGroups.map((group) => ({
|
||
...group,
|
||
items: (group.items || []).map((row) => {
|
||
const prev = prevRowByCode.get(row.purchase_code);
|
||
if (!prev) return row;
|
||
return {
|
||
...row,
|
||
actual_qty_input: prev.actual_qty_input,
|
||
actual_price_input: prev.actual_price_input,
|
||
unit: prev.unit,
|
||
unitIndex: prev.unitIndex,
|
||
item_name_input: prev.item_name_input,
|
||
};
|
||
}),
|
||
productGroups: (group.productGroups || []).map((pg) => {
|
||
const prev = prevProductByKey.get(pg.productKey);
|
||
if (!prev) return pg;
|
||
return {
|
||
...pg,
|
||
actual_qty_input: prev.actual_qty_input,
|
||
actual_price_input: prev.actual_price_input,
|
||
unit: prev.unit,
|
||
unitIndex: prev.unitIndex,
|
||
unitOptions: prev.unitOptions,
|
||
collapsedChildren: prev.collapsedChildren,
|
||
items: (pg.items || []).map((row) => {
|
||
const prevRow = prevRowByCode.get(row.purchase_code);
|
||
if (!prevRow) return row;
|
||
return {
|
||
...row,
|
||
actual_qty_input: prevRow.actual_qty_input,
|
||
actual_price_input: prevRow.actual_price_input,
|
||
unit: prevRow.unit,
|
||
unitIndex: prevRow.unitIndex,
|
||
item_name_input: prevRow.item_name_input,
|
||
};
|
||
}),
|
||
};
|
||
}),
|
||
}));
|
||
}
|
||
|
||
|
||
module.exports = {
|
||
WEEKDAY,
|
||
AGGREGATE_PREF_KEY,
|
||
PERIOD_OPTIONS,
|
||
DATE_FIELD_OPTIONS,
|
||
DATE_FIELD_LABELS,
|
||
pad2,
|
||
fmtLocalDate,
|
||
shiftLocalDate,
|
||
resolvePeriodRange,
|
||
formatDayLabel,
|
||
formatPeriodLabel,
|
||
summarizePurchaseGroups,
|
||
decorateHistoryRow,
|
||
groupByDay,
|
||
flattenHistoryExportRows,
|
||
applyDayCollapseState,
|
||
formatChinaDate,
|
||
formatLocalDate,
|
||
toInputString,
|
||
pickCostPriceHint,
|
||
resolveActualQty,
|
||
resolveActualPrice,
|
||
displayText,
|
||
resolveCategoryDisplayName,
|
||
extractNameFromRemark,
|
||
enrichPurchaseRowCategory,
|
||
canAssignSupplier,
|
||
canCompletePurchase,
|
||
canSkipWarehouseDemand,
|
||
isSkuDirectDelivery,
|
||
needsDirectDeliveryPhoto,
|
||
directDeliveryPhotoCount,
|
||
splitActualQtyByPlan,
|
||
productGroupKey,
|
||
purchaseDeliveryDay,
|
||
buildProductGroups,
|
||
decoratePurchaseRow,
|
||
buildCategoryProductGroups,
|
||
leafCategoryNameHint,
|
||
findCategoryOptionForTreeSort,
|
||
categoryTreeSortMeta,
|
||
compareCategoryGroupsByTree,
|
||
groupByCategory,
|
||
applyCategoryCollapseState,
|
||
mergeCategoryGroupInputs
|
||
};
|