inventory 无 spec 列 ⇒「上次入库的规格」唯一落点是商品档案,而批量入库对已匹配老商品从不回写,导致下次选同一商品带不出规格。 按方案 A 扩已批准的「档案回写」:只回写人工改过的字段(AI/预填值绝不覆盖),在入库同事务内写 product_catalog.spec。 - 服务端: StockImportRowInput/BatchInboundRowInput 增 archive,透传到 writeStockImportRow 调 applyArchiveWriteback - 前端: 行上脏标记(选商品/点候选/新建商品预填即清),只对已匹配且被改过的行发 archive;Web 与小程序两端一致 - 新增 buildBatchRowArchive + 单测/契约测试 + 设计文档
885 lines
33 KiB
JavaScript
885 lines
33 KiB
JavaScript
const {
|
||
fetchStockInboundCategories,
|
||
fetchStockInboundStorageZones,
|
||
fetchStockInboundSkuOptions,
|
||
createStockInboundCategory,
|
||
createStockInboundProduct,
|
||
recognizeStockInboundLines,
|
||
submitStockInboundBatch,
|
||
} = require('../../utils/request');
|
||
const { ensureMobileRole } = require('../../utils/roleGuard');
|
||
const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate');
|
||
const { prepareOrderImageBase64 } = require('../../utils/orderImage');
|
||
const {
|
||
SHELF_LIFE_UNITS,
|
||
applyShelfLifeToLine,
|
||
applyShelfLifeFromAi,
|
||
composeShelfLifeText,
|
||
shelfLifeTextFromLine,
|
||
shelfLifeUnitIndex,
|
||
} = require('../../utils/shelfLife');
|
||
const { buildArchivePayload } = require('../../utils/stockInboundArchive');
|
||
|
||
const WAREHOUSE_ROLES = ['warehouse', 'inspector'];
|
||
const MAX_IMAGES = 9;
|
||
|
||
function todayYmd() {
|
||
const d = new Date();
|
||
const pad = (n) => String(n).padStart(2, '0');
|
||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||
}
|
||
|
||
function lineKey() {
|
||
return `l_${Date.now()}_${Math.floor(Math.random() * 1e6)}`;
|
||
}
|
||
|
||
/** AI / 接口偶发返回字面量 "null"——展示与落表单一律当空(与采购日 displayText 同口径) */
|
||
function aiText(value) {
|
||
if (value === undefined || value === null) return '';
|
||
const text = String(value).trim();
|
||
if (!text || text.toLowerCase() === 'null') return '';
|
||
return text;
|
||
}
|
||
|
||
function applyMatchedFields(line, candidate, backfill) {
|
||
// 单位 / 规格 / 分类:**匹配到的商品优先**,AI 识别值只是没匹配时的备选
|
||
if (candidate) {
|
||
const spec = aiText(candidate.spec);
|
||
const unit = aiText(candidate.unit);
|
||
if (spec) line.spec = spec;
|
||
if (unit) line.unit = unit;
|
||
}
|
||
if (backfill && backfill.category_code) {
|
||
line.category_code = backfill.category_code;
|
||
line.category_name = aiText(backfill.category_name);
|
||
}
|
||
// 成本价 / 存放区域 / 保质期 / 生产地区:AI 优先,空才回填
|
||
if (backfill) {
|
||
if (!line.unit_cost && backfill.last_cost_price != null) {
|
||
line.unit_cost = String(backfill.last_cost_price);
|
||
}
|
||
if (!line.storage_zone && backfill.last_storage_zone) {
|
||
line.storage_zone = aiText(backfill.last_storage_zone);
|
||
}
|
||
if (!line.shelf_life && backfill.last_shelf_life_days != null) {
|
||
applyShelfLifeToLine(line, `${backfill.last_shelf_life_days}天`);
|
||
}
|
||
if (!line.origin && backfill.origin) {
|
||
line.origin = aiText(backfill.origin);
|
||
}
|
||
}
|
||
return line;
|
||
}
|
||
|
||
function lineFromRecognized(item) {
|
||
const matched = (item && item.matched) || {};
|
||
const candidates = Array.isArray(matched.candidates) ? matched.candidates : [];
|
||
const line = {
|
||
key: lineKey(),
|
||
item_name: aiText(item && item.item_name),
|
||
spec: aiText(item && item.spec),
|
||
unit: aiText(item && item.unit),
|
||
origin: aiText(item && item.origin),
|
||
qty: item && item.qty != null && String(item.qty).toLowerCase() !== 'null' ? String(item.qty) : '',
|
||
unit_cost:
|
||
item && item.unit_cost != null && String(item.unit_cost).toLowerCase() !== 'null'
|
||
? String(item.unit_cost)
|
||
: '',
|
||
sku_code: aiText(matched.sku_code),
|
||
candidates,
|
||
// 分类:未命中商品时用 AI 从已有分类里选的(命中时由 applyMatchedFields 覆盖为商品档案值)
|
||
category_code: aiText(item && item.category_code),
|
||
category_name: aiText(item && item.category_name),
|
||
storage_zone: '',
|
||
production_date: aiText(item && item.production_date),
|
||
// 人工编辑追踪(批量入库时只回写「操作员改过」的档案字段;见 docs/design/20261016-批量入库规格回写商品档案.md)
|
||
specEdited: false,
|
||
originEdited: false,
|
||
// 保质期:新提示词给「数值 + 单位(年/月/日)」;未识别单位则留空给人自选
|
||
shelf_life: '',
|
||
shelf_life_value: '',
|
||
shelf_life_unit: '',
|
||
shelf_life_unit_index: 0,
|
||
};
|
||
applyShelfLifeFromAi(line, item || {});
|
||
const candidate = line.sku_code
|
||
? candidates.find((c) => c.sku_code === line.sku_code) || null
|
||
: null;
|
||
const backfill = matched.backfill || (candidate && candidate.backfill) || null;
|
||
return applyMatchedFields(line, candidate, backfill);
|
||
}
|
||
|
||
function normProductName(value) {
|
||
return String(value || '').replace(/\s+/g, '').toLowerCase();
|
||
}
|
||
|
||
/**
|
||
* 判断两行是否指同一商品(多图拍到的同一实物):
|
||
* ① 命中同一 SKU;② 归一化品名完全相同;③ 一方品名包含另一方(如「矿泉水」⊂「农夫山泉矿泉水」)。
|
||
*/
|
||
function isSameProduct(a, b) {
|
||
if (a.sku_code && b.sku_code && a.sku_code === b.sku_code) return true;
|
||
const na = normProductName(a.item_name);
|
||
const nb = normProductName(b.item_name);
|
||
if (!na || !nb) return false;
|
||
if (na === nb) return true;
|
||
const shorter = na.length <= nb.length ? na : nb;
|
||
const longer = na.length <= nb.length ? nb : na;
|
||
return shorter.length >= 2 && longer.indexOf(shorter) >= 0;
|
||
}
|
||
|
||
/** 同一商品多图合并:数量取最大值(多张图是补全信息,不叠加),其余字段以第一个为准、空的才补 */
|
||
function mergeLine(target, source) {
|
||
const tq = String(target.qty ?? '') === '' ? null : Number(target.qty);
|
||
const sq = String(source.qty ?? '') === '' ? null : Number(source.qty);
|
||
if (tq != null && sq != null) target.qty = String(Math.max(tq, sq));
|
||
else if (tq == null && sq != null) target.qty = source.qty;
|
||
|
||
if (!aiText(target.spec) && aiText(source.spec)) target.spec = aiText(source.spec);
|
||
if (!aiText(target.unit) && aiText(source.unit)) target.unit = aiText(source.unit);
|
||
if (!target.unit_cost && source.unit_cost) target.unit_cost = source.unit_cost;
|
||
if (!aiText(target.production_date) && aiText(source.production_date)) {
|
||
target.production_date = aiText(source.production_date);
|
||
}
|
||
if (!aiText(target.shelf_life) && aiText(source.shelf_life)) {
|
||
applyShelfLifeToLine(target, aiText(source.shelf_life));
|
||
}
|
||
if (!aiText(target.storage_zone) && aiText(source.storage_zone)) {
|
||
target.storage_zone = aiText(source.storage_zone);
|
||
}
|
||
if (!aiText(target.origin) && aiText(source.origin)) target.origin = aiText(source.origin);
|
||
if (!target.category_code && source.category_code) {
|
||
target.category_code = source.category_code;
|
||
target.category_name = source.category_name;
|
||
}
|
||
if (!target.sku_code && source.sku_code) target.sku_code = source.sku_code;
|
||
if ((!target.candidates || !target.candidates.length) && source.candidates && source.candidates.length) {
|
||
target.candidates = source.candidates;
|
||
}
|
||
return target;
|
||
}
|
||
|
||
Component({
|
||
options: { addGlobalClass: true },
|
||
|
||
properties: {
|
||
embedded: { type: Boolean, value: false },
|
||
},
|
||
|
||
data: {
|
||
imageList: [],
|
||
recognizing: false,
|
||
lines: [],
|
||
submitting: false,
|
||
/** 正在入库的行下标;-1 表示无 */
|
||
submittingIndex: -1,
|
||
productionDateEnd: '',
|
||
categories: [],
|
||
categoryOptions: [],
|
||
zoneOptions: [],
|
||
sheetOpen: false,
|
||
sheetType: '',
|
||
sheetIndex: -1,
|
||
sheetQuery: '',
|
||
sheetList: [],
|
||
sheetCanCreate: false,
|
||
sheetCreateLabel: '',
|
||
/** 「商品选择」远程检索结果(带上次设置回填) */
|
||
productOptions: [],
|
||
/** 「新建商品」表单草稿(sheetType='newProduct' 时用) */
|
||
newProduct: null,
|
||
creatingProduct: false,
|
||
/** 保质期单位选择器:年 / 月 / 日(空选项留给「未识别 → 用户自选」) */
|
||
shelfLifeUnits: SHELF_LIFE_UNITS,
|
||
},
|
||
|
||
lifetimes: {
|
||
attached() {
|
||
this.onPanelShow();
|
||
},
|
||
},
|
||
|
||
pageLifetimes: {
|
||
show() {
|
||
this.onPanelShow();
|
||
},
|
||
},
|
||
|
||
methods: {
|
||
async onPanelShow() {
|
||
if (!beginPanelShow(this)) return;
|
||
try {
|
||
const ok = await ensureMobileRole(WAREHOUSE_ROLES);
|
||
if (!ok) return;
|
||
await this.loadCategories();
|
||
await this.loadZones();
|
||
this.setData({ productionDateEnd: todayYmd() });
|
||
} finally {
|
||
endPanelShow(this);
|
||
}
|
||
},
|
||
|
||
async loadCategories() {
|
||
try {
|
||
const res = await fetchStockInboundCategories();
|
||
const rows = res.data || res || [];
|
||
this.setData({ categories: Array.isArray(rows) ? rows : [] });
|
||
this.rebuildCategoryOptions();
|
||
} catch (e) {
|
||
wx.showToast({ title: e.message || '加载分类失败', icon: 'none' });
|
||
}
|
||
},
|
||
|
||
async loadZones() {
|
||
try {
|
||
const res = await fetchStockInboundStorageZones();
|
||
const rows = res.data || res || [];
|
||
this.setData({ zoneOptions: Array.isArray(rows) ? rows.map((z) => String(z)) : [] });
|
||
} catch (e) {
|
||
/* 存放区域列表加载失败不阻断 */
|
||
}
|
||
},
|
||
|
||
/** 分类下拉选项([{code,label}]) */
|
||
rebuildCategoryOptions() {
|
||
const options = (this.data.categories || []).map((row) => ({
|
||
code: String(row.category_code || ''),
|
||
label: String(row.category_name || row.label || row.category_code || ''),
|
||
}));
|
||
this.setData({ categoryOptions: options });
|
||
},
|
||
|
||
// ── 分类 / 存放区域 / 商品:输入下拉 + 可新建(弹层)────────
|
||
sheetSource(type) {
|
||
if (type === 'category') return this.data.categoryOptions || [];
|
||
if (type === 'product') return this.data.productOptions || [];
|
||
return (this.data.zoneOptions || []).map((z) => ({ code: z, label: z }));
|
||
},
|
||
|
||
openCategorySheet(e) {
|
||
this.openSheet('category', Number(e.currentTarget.dataset.index));
|
||
},
|
||
|
||
openZoneSheet(e) {
|
||
this.openSheet('zone', Number(e.currentTarget.dataset.index));
|
||
},
|
||
|
||
/** 「品名」格 = 商品选择器:打开弹层并远程搜商品档案(与 Web 口径一致) */
|
||
openProductSheet(e) {
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
const line = (this.data.lines || [])[index] || {};
|
||
// 带上 AI 识别 / 已填品名,便于直接搜库或一键新建
|
||
const seed = String(line.item_name || '').trim();
|
||
this.openSheet('product', index, seed);
|
||
this.searchProducts(seed);
|
||
},
|
||
|
||
openSheet(type, index, initialQuery) {
|
||
if (!Number.isInteger(index) || index < 0) return;
|
||
const q = String(initialQuery || '');
|
||
const source = this.sheetSource(type);
|
||
this.setData({
|
||
sheetOpen: true,
|
||
sheetType: type,
|
||
sheetIndex: index,
|
||
sheetQuery: q,
|
||
sheetList: source,
|
||
sheetCanCreate: false,
|
||
sheetCreateLabel: '',
|
||
});
|
||
if (q) this.refreshSheetLocal(q, source);
|
||
},
|
||
|
||
onSheetInput(e) {
|
||
this.refreshSheet(String(e.detail.value || ''));
|
||
},
|
||
|
||
refreshSheet(query) {
|
||
const type = this.data.sheetType;
|
||
this.refreshSheetLocal(query, this.sheetSource(type));
|
||
// 商品:本地过滤后仍走远程搜(商品库大,需服务端检索)
|
||
if (type === 'product') this.searchProducts(String(query || ''));
|
||
},
|
||
|
||
refreshSheetLocal(query, all) {
|
||
const type = this.data.sheetType;
|
||
const q = String(query || '');
|
||
const ql = q.trim().toLowerCase();
|
||
const list = ql
|
||
? (all || []).filter((o) => String(o.label || '').toLowerCase().indexOf(ql) >= 0)
|
||
: all || [];
|
||
const trimmed = q.trim();
|
||
const matched = (all || []).some((o) =>
|
||
type === 'product'
|
||
? String(o.sku_name || '').trim() === trimmed
|
||
: String(o.label || '').trim() === trimmed
|
||
);
|
||
const canCreate = Boolean(trimmed) && !matched;
|
||
const createLabel =
|
||
type === 'category'
|
||
? `+ 新建分类「${trimmed}」`
|
||
: type === 'product'
|
||
? `+ 使用「${trimmed}」作为新商品`
|
||
: `+ 使用区域「${trimmed}」`;
|
||
this.setData({
|
||
sheetQuery: q,
|
||
sheetList: list,
|
||
sheetCanCreate: canCreate,
|
||
sheetCreateLabel: canCreate ? createLabel : '',
|
||
});
|
||
},
|
||
|
||
/** 「品名」远程检索(防抖) */
|
||
searchProducts(query) {
|
||
if (this._skuTimer) clearTimeout(this._skuTimer);
|
||
const q = String(query || '');
|
||
this._skuTimer = setTimeout(async () => {
|
||
try {
|
||
const res = await fetchStockInboundSkuOptions({ search: q, limit: 20 });
|
||
const rows = (res && (res.data || res)) || [];
|
||
const options = (Array.isArray(rows) ? rows : []).map((o) => ({
|
||
code: String(o.sku_code || ''),
|
||
sku_name: String(o.sku_name || o.sku_code || ''),
|
||
label: o.spec ? `${o.sku_name} · ${o.spec}` : String(o.sku_name || o.sku_code || ''),
|
||
spec: o.spec || '',
|
||
unit: o.unit || '',
|
||
origin: o.origin || '',
|
||
category_code: o.category_code || '',
|
||
category_name: o.category_name || '',
|
||
backfill: o.backfill || null,
|
||
}));
|
||
this.setData({ productOptions: options });
|
||
if (this.data.sheetType === 'product') {
|
||
this.refreshSheetLocal(this.data.sheetQuery, options);
|
||
}
|
||
} catch (e) {
|
||
// 搜索失败静默:不阻断手输 / 新建
|
||
}
|
||
}, 300);
|
||
},
|
||
|
||
closeSheet() {
|
||
this.setData({ sheetOpen: false, sheetType: '', newProduct: null });
|
||
},
|
||
|
||
/** 阻止弹层内部的点击冒泡到遮罩 */
|
||
noop() {},
|
||
|
||
onSheetPick(e) {
|
||
const code = String(e.currentTarget.dataset.code || '');
|
||
const label = String(e.currentTarget.dataset.label || '');
|
||
if (this.data.sheetType === 'product') {
|
||
const opt = (this.data.productOptions || []).find((o) => o.code === code);
|
||
if (opt) {
|
||
this.applyProductPick(opt);
|
||
return;
|
||
}
|
||
}
|
||
this.applySheetValue(code, label);
|
||
},
|
||
|
||
/** 选中已有商品:回填 sku + 上次设置(生产日期 / 数量不动) */
|
||
applyProductPick(opt) {
|
||
const index = this.data.sheetIndex;
|
||
if (!Number.isInteger(index) || index < 0) {
|
||
this.setData({ sheetOpen: false });
|
||
return;
|
||
}
|
||
const line = (this.data.lines || [])[index] || {};
|
||
const bf = opt.backfill || null;
|
||
const patch = {
|
||
[`lines[${index}].sku_code`]: opt.code,
|
||
[`lines[${index}].item_name`]: opt.sku_name || opt.label,
|
||
[`lines[${index}].candidates`]: [],
|
||
sheetOpen: false,
|
||
};
|
||
// 规格 / 单位:商品档案优先(字面量 null 不当值)
|
||
const pickSpec = aiText(opt.spec);
|
||
const pickUnit = aiText(opt.unit);
|
||
if (pickSpec) {
|
||
patch[`lines[${index}].spec`] = pickSpec;
|
||
// 预填值出自商品档案,不算人工改过 ⇒ 清掉脏标记
|
||
patch[`lines[${index}].specEdited`] = false;
|
||
}
|
||
if (pickUnit) patch[`lines[${index}].unit`] = pickUnit;
|
||
if (bf) {
|
||
// 分类:商品档案 / 上次设置优先
|
||
if (bf.category_code) {
|
||
patch[`lines[${index}].category_code`] = bf.category_code;
|
||
patch[`lines[${index}].category_name`] = bf.category_name || '';
|
||
}
|
||
// 成本价 / 存放区域 / 保质期 / 生产地区:空才回填
|
||
if (!String(line.unit_cost ?? '').trim() && bf.last_cost_price != null) {
|
||
patch[`lines[${index}].unit_cost`] = String(bf.last_cost_price);
|
||
}
|
||
if (!String(line.storage_zone || '').trim() && bf.last_storage_zone) {
|
||
patch[`lines[${index}].storage_zone`] = bf.last_storage_zone;
|
||
}
|
||
if (!String(line.shelf_life || '').trim() && bf.last_shelf_life_days != null) {
|
||
patch[`lines[${index}].shelf_life`] = `${bf.last_shelf_life_days}天`;
|
||
patch[`lines[${index}].shelf_life_value`] = String(bf.last_shelf_life_days);
|
||
patch[`lines[${index}].shelf_life_unit`] = '日';
|
||
patch[`lines[${index}].shelf_life_unit_index`] = shelfLifeUnitIndex('日');
|
||
}
|
||
if (!String(line.origin || '').trim() && bf.origin) {
|
||
patch[`lines[${index}].origin`] = bf.origin;
|
||
// 预填值出自商品档案 ⇒ 清掉脏标记
|
||
patch[`lines[${index}].originEdited`] = false;
|
||
}
|
||
}
|
||
this.setData(patch);
|
||
},
|
||
|
||
async onSheetCreate() {
|
||
const q = String(this.data.sheetQuery || '').trim();
|
||
if (!q) return;
|
||
// 商品:输入新名 ⇒ 打开「新建商品」表单(B,2026-11-02)
|
||
if (this.data.sheetType === 'product') {
|
||
this.openNewProductForm(this.data.sheetIndex, q);
|
||
return;
|
||
}
|
||
// 存放区域是自由文本,直接采用输入值
|
||
if (this.data.sheetType === 'zone') {
|
||
this.applySheetValue(q, q);
|
||
return;
|
||
}
|
||
try {
|
||
wx.showLoading({ title: '新建分类中' });
|
||
const r = await createStockInboundCategory(q);
|
||
const row = r.data || r || {};
|
||
const code = String(row.category_code || '');
|
||
const label = String(row.category_name || row.label || q);
|
||
const list = this.data.categories.slice();
|
||
list.push({ category_code: code, category_name: label, label });
|
||
this.setData({ categories: list });
|
||
this.rebuildCategoryOptions();
|
||
if (code) this.applySheetValue(code, label);
|
||
wx.showToast({ title: '分类已新建', icon: 'none' });
|
||
} catch (e) {
|
||
wx.showToast({ title: e.message || '新建分类失败', icon: 'none' });
|
||
} finally {
|
||
wx.hideLoading();
|
||
}
|
||
},
|
||
|
||
applySheetValue(code, label) {
|
||
const index = this.data.sheetIndex;
|
||
if (!Number.isInteger(index) || index < 0) {
|
||
this.setData({ sheetOpen: false });
|
||
return;
|
||
}
|
||
if (this.data.sheetType === 'category') {
|
||
this.setData({
|
||
[`lines[${index}].category_code`]: code,
|
||
[`lines[${index}].category_name`]: label,
|
||
sheetOpen: false,
|
||
});
|
||
} else {
|
||
this.setData({
|
||
[`lines[${index}].storage_zone`]: label,
|
||
sheetOpen: false,
|
||
});
|
||
}
|
||
},
|
||
|
||
// ── 新建商品表单(B,2026-11-02)──────────────────────
|
||
openNewProductForm(index, name) {
|
||
if (!Number.isInteger(index) || index < 0) return;
|
||
const line = (this.data.lines || [])[index] || {};
|
||
const options = this.data.categoryOptions || [];
|
||
let categoryIndex = options.findIndex((o) => o.code === (line.category_code || ''));
|
||
if (categoryIndex < 0) categoryIndex = 0;
|
||
this.setData({
|
||
sheetType: 'newProduct',
|
||
sheetIndex: index,
|
||
newProduct: {
|
||
index,
|
||
name: String(name || line.item_name || '').trim(),
|
||
categoryIndex,
|
||
spec: String(line.spec || ''),
|
||
unit: String(line.unit || ''),
|
||
origin: String(line.origin || ''),
|
||
},
|
||
});
|
||
},
|
||
|
||
onNewProductField(e) {
|
||
const field = e.currentTarget.dataset.field;
|
||
if (!field) return;
|
||
this.setData({ [`newProduct.${field}`]: e.detail.value });
|
||
},
|
||
|
||
onNewProductCategory(e) {
|
||
this.setData({ 'newProduct.categoryIndex': Number(e.detail.value) || 0 });
|
||
},
|
||
|
||
async submitNewProduct() {
|
||
if (this.data.creatingProduct) return;
|
||
const np = this.data.newProduct;
|
||
if (!np) return;
|
||
const name = String(np.name || '').trim();
|
||
if (!name) {
|
||
wx.showToast({ title: '请填写商品名', icon: 'none' });
|
||
return;
|
||
}
|
||
const cats = this.data.categoryOptions || [];
|
||
const cat = cats[np.categoryIndex];
|
||
if (!cat || !cat.code) {
|
||
wx.showToast({ title: '请选择分类', icon: 'none' });
|
||
return;
|
||
}
|
||
this.setData({ creatingProduct: true });
|
||
try {
|
||
const res = await createStockInboundProduct({
|
||
name,
|
||
parent_code: cat.code,
|
||
spec: String(np.spec || '').trim() || undefined,
|
||
unit: String(np.unit || '').trim() || undefined,
|
||
origin: String(np.origin || '').trim() || undefined,
|
||
});
|
||
const d = (res && (res.data || res)) || {};
|
||
const code = String(d.skuCode || d.sku_code || '');
|
||
if (!code) {
|
||
wx.showToast({ title: '新建商品失败', icon: 'none' });
|
||
return;
|
||
}
|
||
const index = np.index;
|
||
this.setData({
|
||
[`lines[${index}].sku_code`]: code,
|
||
[`lines[${index}].item_name`]: String(d.name || name),
|
||
[`lines[${index}].spec`]: String(np.spec || '').trim(),
|
||
[`lines[${index}].unit`]: String(np.unit || '').trim(),
|
||
[`lines[${index}].origin`]: String(np.origin || '').trim(),
|
||
[`lines[${index}].category_code`]: cat.code,
|
||
[`lines[${index}].category_name`]: cat.label,
|
||
[`lines[${index}].candidates`]: [],
|
||
// 建档已写入档案(createCatalogSkuForInbound)⇒ 不当作人工改过的档案字段
|
||
[`lines[${index}].specEdited`]: false,
|
||
[`lines[${index}].originEdited`]: false,
|
||
sheetOpen: false,
|
||
sheetType: '',
|
||
newProduct: null,
|
||
});
|
||
wx.showToast({ title: '商品已新建', icon: 'none' });
|
||
} catch (e) {
|
||
wx.showToast({ title: (e && e.message) || '新建商品失败', icon: 'none' });
|
||
} finally {
|
||
this.setData({ creatingProduct: false });
|
||
}
|
||
},
|
||
|
||
// ── 图片 ──────────────────────────────────────────────
|
||
chooseImageFromCamera() {
|
||
// 连续拍照:拍一张后自动再开相机,直到用户取消或达到上限
|
||
if (this._capturing) return;
|
||
this._capturing = true;
|
||
this.captureLoop().then(
|
||
() => { this._capturing = false; },
|
||
() => { this._capturing = false; }
|
||
);
|
||
},
|
||
|
||
async captureLoop() {
|
||
while (this.data.imageList.length < MAX_IMAGES) {
|
||
const path = await new Promise((resolve) => {
|
||
wx.chooseImage({
|
||
count: 1,
|
||
sizeType: ['compressed'],
|
||
sourceType: ['camera'],
|
||
success: (res) => resolve((res.tempFilePaths || [])[0] || ''),
|
||
fail: () => resolve(''),
|
||
});
|
||
});
|
||
if (!path) break;
|
||
this.setData({
|
||
imageList: this.data.imageList.concat([{ key: `img_${Date.now()}_${Math.random()}`, path }]),
|
||
});
|
||
}
|
||
},
|
||
|
||
chooseImageFromAlbum() {
|
||
this.pickImages(['album']);
|
||
},
|
||
|
||
pickImages(sourceType) {
|
||
const remain = Math.max(1, MAX_IMAGES - this.data.imageList.length);
|
||
wx.chooseImage({
|
||
count: remain,
|
||
sizeType: ['compressed'],
|
||
sourceType,
|
||
success: (res) => {
|
||
const paths = res.tempFilePaths || [];
|
||
if (!paths.length) return;
|
||
const added = paths.map((path) => ({ key: `img_${Date.now()}_${Math.random()}`, path }));
|
||
this.setData({ imageList: this.data.imageList.concat(added) });
|
||
},
|
||
});
|
||
},
|
||
|
||
onImagePreview(e) {
|
||
const idx = Number(e.currentTarget.dataset.index);
|
||
const urls = this.data.imageList.map((it) => it.path);
|
||
if (!urls.length) return;
|
||
wx.previewImage({ current: urls[idx] || urls[0], urls });
|
||
},
|
||
|
||
onImageDelete(e) {
|
||
const idx = Number(e.currentTarget.dataset.index);
|
||
const list = this.data.imageList.slice();
|
||
list.splice(idx, 1);
|
||
this.setData({ imageList: list });
|
||
},
|
||
|
||
clearImages() {
|
||
this.setData({ imageList: [] });
|
||
},
|
||
|
||
// ── 识别 ──────────────────────────────────────────────
|
||
async recognizeAll() {
|
||
const images = this.data.imageList;
|
||
if (!images.length) {
|
||
wx.showToast({ title: '请先拍照或选择图片', icon: 'none' });
|
||
return;
|
||
}
|
||
this.setData({ recognizing: true });
|
||
let collected = [];
|
||
try {
|
||
// 先把所有图片转 base64,再一次提交(服务端一次多图调用,由 AI 合并同一商品)
|
||
const imagesBase64 = [];
|
||
for (const img of images) {
|
||
let base64 = '';
|
||
try {
|
||
base64 = await prepareOrderImageBase64(img.path);
|
||
} catch (e) {
|
||
continue;
|
||
}
|
||
if (base64) imagesBase64.push(base64);
|
||
}
|
||
if (!imagesBase64.length) {
|
||
this.setData({ recognizing: false });
|
||
wx.showToast({ title: '未识别到商品,请重拍或手动添加', icon: 'none' });
|
||
return;
|
||
}
|
||
const res = await recognizeStockInboundLines({ images_base64: imagesBase64 });
|
||
const data = res.data || res || {};
|
||
this.setData({ recognizing: false });
|
||
if (data.no_llm) {
|
||
wx.showToast({ title: '未配置多模态识别(LLM),请手动添加', icon: 'none' });
|
||
return;
|
||
}
|
||
collected = Array.isArray(data.items) ? data.items : [];
|
||
} catch (e) {
|
||
this.setData({ recognizing: false });
|
||
wx.showToast({ title: e.message || '识别失败', icon: 'none' });
|
||
return;
|
||
}
|
||
if (!collected.length) {
|
||
wx.showToast({ title: '未识别到商品,请重拍或手动添加', icon: 'none' });
|
||
return;
|
||
}
|
||
const lines = this.data.lines.map((l) => ({ ...l }));
|
||
for (const item of collected) {
|
||
const incoming = lineFromRecognized(item);
|
||
const idx = lines.findIndex((l) => isSameProduct(l, incoming));
|
||
if (idx >= 0) {
|
||
mergeLine(lines[idx], incoming);
|
||
} else {
|
||
lines.push(incoming);
|
||
}
|
||
}
|
||
this.setData({ lines });
|
||
wx.showToast({ title: `识别到 ${collected.length} 项`, icon: 'none' });
|
||
},
|
||
|
||
// ── 审核行 ────────────────────────────────────────────
|
||
onLineField(e) {
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
const field = e.currentTarget.dataset.field;
|
||
if (!Number.isInteger(index) || !field) return;
|
||
const patch = { [`lines[${index}].${field}`]: e.detail.value };
|
||
// 档案字段被人工改过 ⇒ 打脏标记(批量入库时随行回写商品档案)
|
||
if (field === 'spec') patch[`lines[${index}].specEdited`] = true;
|
||
if (field === 'origin') patch[`lines[${index}].originEdited`] = true;
|
||
this.setData(patch);
|
||
},
|
||
|
||
onLineProd(e) {
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
this.setData({ [`lines[${index}].production_date`]: e.detail.value || '' });
|
||
},
|
||
|
||
/** 保质期数字:同步拼原文(有单位才拼得全) */
|
||
onLineShelfValue(e) {
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
if (!Number.isInteger(index) || index < 0) return;
|
||
const value = String((e.detail && e.detail.value) || '').trim();
|
||
const line = (this.data.lines || [])[index] || {};
|
||
const unit = line.shelf_life_unit || '';
|
||
this.setData({
|
||
[`lines[${index}].shelf_life_value`]: value,
|
||
[`lines[${index}].shelf_life`]: composeShelfLifeText(value, unit) || value,
|
||
});
|
||
},
|
||
|
||
/** 保质期单位:年 / 月 / 日 */
|
||
onLineShelfUnit(e) {
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
if (!Number.isInteger(index) || index < 0) return;
|
||
const unitIndex = Number(e.detail && e.detail.value);
|
||
const unit = SHELF_LIFE_UNITS[unitIndex] || '';
|
||
const line = (this.data.lines || [])[index] || {};
|
||
const value = String(line.shelf_life_value || '').trim();
|
||
this.setData({
|
||
[`lines[${index}].shelf_life_unit`]: unit,
|
||
[`lines[${index}].shelf_life_unit_index`]: shelfLifeUnitIndex(unit),
|
||
[`lines[${index}].shelf_life`]: composeShelfLifeText(value, unit) || value,
|
||
});
|
||
},
|
||
|
||
onLinePickCandidate(e) {
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
const sku = String(e.currentTarget.dataset.sku || '');
|
||
const line = this.data.lines[index];
|
||
if (!line) return;
|
||
const candidate = (line.candidates || []).find((c) => c.sku_code === sku);
|
||
const patch = { [`lines[${index}].sku_code`]: sku };
|
||
if (candidate) {
|
||
if (candidate.sku_name) patch[`lines[${index}].item_name`] = aiText(candidate.sku_name);
|
||
// 单位 / 规格:**匹配到的商品优先**(字面量 null 不当值)
|
||
const candSpec = aiText(candidate.spec);
|
||
const candUnit = aiText(candidate.unit);
|
||
if (candSpec) {
|
||
patch[`lines[${index}].spec`] = candSpec;
|
||
// 候选商品档案值 ⇒ 不算人工改过
|
||
patch[`lines[${index}].specEdited`] = false;
|
||
}
|
||
if (candUnit) patch[`lines[${index}].unit`] = candUnit;
|
||
const bf = candidate.backfill || null;
|
||
if (bf) {
|
||
// 分类:匹配到的商品优先
|
||
if (bf.category_code) {
|
||
patch[`lines[${index}].category_code`] = bf.category_code;
|
||
patch[`lines[${index}].category_name`] = bf.category_name || '';
|
||
}
|
||
// 成本价 / 存放区域 / 保质期:AI 优先,空才回填
|
||
if (!String(line.unit_cost ?? '').trim() && bf.last_cost_price != null) {
|
||
patch[`lines[${index}].unit_cost`] = String(bf.last_cost_price);
|
||
}
|
||
if (!String(line.storage_zone || '').trim() && bf.last_storage_zone) {
|
||
patch[`lines[${index}].storage_zone`] = bf.last_storage_zone;
|
||
}
|
||
if (!String(line.shelf_life || '').trim() && bf.last_shelf_life_days != null) {
|
||
patch[`lines[${index}].shelf_life`] = `${bf.last_shelf_life_days}天`;
|
||
patch[`lines[${index}].shelf_life_value`] = String(bf.last_shelf_life_days);
|
||
patch[`lines[${index}].shelf_life_unit`] = '日';
|
||
patch[`lines[${index}].shelf_life_unit_index`] = shelfLifeUnitIndex('日');
|
||
}
|
||
// 生产地区:AI 优先,空才回填
|
||
if (!String(line.origin || '').trim() && bf.origin) {
|
||
patch[`lines[${index}].origin`] = bf.origin;
|
||
patch[`lines[${index}].originEdited`] = false;
|
||
}
|
||
}
|
||
}
|
||
this.setData(patch);
|
||
},
|
||
|
||
onLineRemove(e) {
|
||
if (this.data.submitting) return;
|
||
const idx = Number(e.currentTarget.dataset.index);
|
||
const lines = this.data.lines.slice();
|
||
lines.splice(idx, 1);
|
||
this.setData({ lines });
|
||
},
|
||
|
||
addEmptyLine() {
|
||
this.setData({
|
||
lines: this.data.lines.concat([lineFromRecognized({})]),
|
||
});
|
||
},
|
||
|
||
// ── 按行入库(复用 stock-in-batch,一次只传一行)────────
|
||
buildRowFromLine(line) {
|
||
const qty = Number(line.qty);
|
||
const label = aiText(line.item_name) || '未命名行';
|
||
if (!(qty > 0)) {
|
||
return { error: `数量须大于 0:${label}` };
|
||
}
|
||
if (!line.sku_code) {
|
||
if (!aiText(line.item_name)) {
|
||
return { error: '请先填写品名' };
|
||
}
|
||
if (!line.category_code) {
|
||
return { error: `请为「${label}」选择分类` };
|
||
}
|
||
}
|
||
return {
|
||
row: {
|
||
sku_code: line.sku_code || undefined,
|
||
new_product: line.sku_code
|
||
? undefined
|
||
: {
|
||
name: aiText(line.item_name),
|
||
category_code: line.category_code,
|
||
spec: aiText(line.spec) || undefined,
|
||
unit: aiText(line.unit) || undefined,
|
||
origin: aiText(line.origin) || undefined,
|
||
},
|
||
qty,
|
||
unit_cost:
|
||
line.unit_cost === '' || line.unit_cost == null || String(line.unit_cost).toLowerCase() === 'null'
|
||
? null
|
||
: Number(line.unit_cost),
|
||
production_date: aiText(line.production_date) || undefined,
|
||
shelf_life: shelfLifeTextFromLine(line) || undefined,
|
||
storage_zone: aiText(line.storage_zone) || undefined,
|
||
// 已匹配商品且操作员改过规格/生产地区 ⇒ 回写商品档案(只发人工改过的字段;
|
||
// 新建商品行走 new_product,不由这里回写)。见 docs/design/20261016-批量入库规格回写商品档案.md
|
||
archive: line.sku_code
|
||
? buildArchivePayload(
|
||
{ archiveSpec: line.spec, archiveOrigin: line.origin },
|
||
{ archiveSpec: line.specEdited, archiveOrigin: line.originEdited }
|
||
) || undefined
|
||
: undefined,
|
||
},
|
||
};
|
||
},
|
||
|
||
async submitLine(e) {
|
||
if (this.data.submitting) return;
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
if (!Number.isInteger(index) || index < 0) return;
|
||
const line = (this.data.lines || [])[index];
|
||
if (!line) return;
|
||
const built = this.buildRowFromLine(line);
|
||
if (built.error) {
|
||
wx.showToast({ title: built.error, icon: 'none' });
|
||
return;
|
||
}
|
||
|
||
this.setData({ submitting: true, submittingIndex: index });
|
||
try {
|
||
const res = await submitStockInboundBatch({ rows: [built.row] });
|
||
const data = res.data || res || {};
|
||
const failed = Number(data.failed_count || 0);
|
||
if (failed) {
|
||
const results = Array.isArray(data.results) ? data.results : [];
|
||
const firstErr =
|
||
(results.find((r) => r.mode === 'failed') || {}).error || '入库失败';
|
||
wx.showToast({ title: firstErr, icon: 'none' });
|
||
return;
|
||
}
|
||
const remain = this.data.lines.filter((_, i) => i !== index);
|
||
const patch = { lines: remain };
|
||
if (!remain.length) patch.imageList = [];
|
||
this.setData(patch);
|
||
wx.showToast({ title: '已入库', icon: 'none' });
|
||
} catch (err) {
|
||
wx.showToast({ title: err.message || '入库失败', icon: 'none' });
|
||
} finally {
|
||
this.setData({ submitting: false, submittingIndex: -1 });
|
||
}
|
||
},
|
||
},
|
||
});
|