Files
SupplierSystem/miniprogram/components/stock-inbound-panel/index.js
T
雨天 8213c17166
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
feat(小程序入库): 待审核行支持一键入库
逐行本地校验后一次提交全部行;409 规格冲突确认后带 confirm_spec_conflict
重提(移动端路由本次补上该参数转发与 spec_conflicts 透传)。

失败行按 rowNumber 留在列表、成功行移除;报告随行绑定,绑定失败只提示
去 Web 补挂。逐行与一键共用 _submitInFlight 在途锁,防双击重复入库。
2026-10-21 19:15:00 +08:00

1216 lines
46 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const {
fetchStockInboundCategories,
fetchStockInboundStorageZones,
fetchStockInboundSkuOptions,
createStockInboundCategory,
createStockInboundProduct,
recognizeStockInboundLines,
submitStockInboundBatch,
parseStockInboundBatchReport,
uploadQualityReportStorageFile,
} = 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;
/** 批次报告类型(与后端 `BATCH_REPORT_TYPES` / Web 端文案一致) */
const REPORT_TYPES = [
{ value: 'batch', label: '批次报告' },
{ value: 'pesticide', label: '农残报告' },
{ value: 'quarantine', label: '检疫证明' },
{ value: 'annual', label: '年度检测' },
];
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,
/** 批次报告:上传 → 解析 → 挂到待入库行(2026-10-21;只存存储对象路径,不落表) */
reportOpen: false,
reportBusy: false,
reportTypes: REPORT_TYPES,
reportTypeIndex: 0,
reportNo: '',
/** 解析结果:file_path / product_names / produced_at / testing_org */
reportParsed: null,
/** 解析结果的可读文本(WXML 不支持 join) */
reportNameText: '',
/** 可勾选的行:[{ key, name, spec, picked }] */
reportOptions: [],
},
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({})]),
});
},
// ── 批次报告:上传→解析→挂到行(2026-10-21)──────────────
/** 把当前行做成勾选项(报告可挂多行;picked 用行 key 标记,不用下标) */
buildReportOptions(pickedKeys) {
const picked = Array.isArray(pickedKeys) ? pickedKeys : [];
return (this.data.lines || []).map((line) => ({
key: String(line.key || ''),
name: aiText(line.item_name) || '未命名行',
spec: aiText(line.spec),
picked: picked.indexOf(String(line.key || '')) >= 0,
}));
},
openReportSheet() {
if (this.data.reportBusy || this.data.submitting) return;
if (!(this.data.lines || []).length) {
wx.showToast({ title: '请先识别或手动添加商品', icon: 'none' });
return;
}
this.setData({
reportOpen: true,
reportTypeIndex: 0,
reportNo: '',
reportParsed: null,
reportNameText: '',
reportOptions: this.buildReportOptions([]),
});
},
closeReportSheet() {
if (this.data.reportBusy) return;
this.setData({ reportOpen: false, reportParsed: null, reportNameText: '', reportOptions: [] });
},
onReportTypeChange(e) {
this.setData({ reportTypeIndex: Number(e.detail && e.detail.value) || 0 });
},
onReportNoInput(e) {
this.setData({ reportNo: String((e.detail && e.detail.value) || '') });
},
pickReportSource() {
if (this.data.reportBusy) return;
wx.showActionSheet({
itemList: ['拍照', '相册', '聊天文件(PDF)'],
success: (res) => {
if (res.tapIndex === 0) this.pickReportImages(['camera']);
else if (res.tapIndex === 1) this.pickReportImages(['album']);
else if (res.tapIndex === 2) this.pickReportFiles();
},
fail: () => undefined,
});
},
pickReportImages(sourceType) {
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: sourceType || ['camera', 'album'],
success: (res) => {
const file = ((res && res.tempFiles) || []).find((f) => f && f.tempFilePath);
if (file) this.uploadAndParseReport({ path: file.tempFilePath, name: 'report.jpg' });
},
fail: () => undefined,
});
},
pickReportFiles() {
if (typeof wx.chooseMessageFile !== 'function') {
wx.showToast({ title: '当前微信版本不支持选文件', icon: 'none' });
return;
}
wx.chooseMessageFile({
count: 1,
type: 'file',
extension: ['pdf', 'jpg', 'jpeg', 'png', 'webp'],
success: (res) => {
const file = ((res && res.tempFiles) || []).find((f) => f && f.path);
if (file) this.uploadAndParseReport({ path: file.path, name: file.name || 'report.pdf' });
},
fail: () => undefined,
});
},
/** 上传到 `quality-reports` 桶 → 只解析(不落库)→ 默认勾选唯一命中的行 */
async uploadAndParseReport(file) {
if (this.data.reportBusy) return;
this.setData({ reportBusy: true });
wx.showLoading({ title: '解析批次报告中…', mask: true });
try {
const path = await uploadQualityReportStorageFile(file.path, file.name);
const lines = (this.data.lines || []).map((line) => ({ name: aiText(line.item_name) }));
const res = await parseStockInboundBatchReport({ file: path, lines });
const data = (res && res.data) || res || {};
const names = Array.isArray(data.product_names) ? data.product_names.map((n) => String(n)) : [];
const suggestions = Array.isArray(data.suggestions) ? data.suggestions : [];
const pickedKeys = [];
suggestions.forEach((s) => {
if (!s || s.status !== 'unique' || !Array.isArray(s.line_indexes)) return;
s.line_indexes.forEach((i) => {
const line = (this.data.lines || [])[Number(i)];
if (line && line.key && pickedKeys.indexOf(String(line.key)) < 0) {
pickedKeys.push(String(line.key));
}
});
});
this.setData({
reportParsed: {
file_path: String(data.file_path || path),
product_names: names,
produced_at: data.produced_at || null,
testing_org: data.testing_org || null,
},
reportNameText: names.length ? names.join('、') : '未识别到品名',
reportOptions: this.buildReportOptions(pickedKeys),
});
} catch (err) {
wx.showToast({ title: (err && err.message) || '报告解析失败', icon: 'none' });
} finally {
wx.hideLoading();
this.setData({ reportBusy: false });
}
},
toggleReportLine(e) {
const key = String((e.currentTarget.dataset && e.currentTarget.dataset.key) || '');
if (!key) return;
const options = (this.data.reportOptions || []).map((opt) =>
opt.key === key ? { ...opt, picked: !opt.picked } : opt
);
this.setData({ reportOptions: options });
},
/** 确定:把报告挂到勾选的行上(只改 lines[i].reports,不重建 lines) */
applyReportToLines() {
const parsed = this.data.reportParsed;
if (!parsed || !parsed.file_path) {
wx.showToast({ title: '请先上传报告', icon: 'none' });
return;
}
const picked = (this.data.reportOptions || []).filter((o) => o.picked).map((o) => o.key);
if (!picked.length) {
wx.showToast({ title: '请选择这份报告属于哪些商品', icon: 'none' });
return;
}
const type = REPORT_TYPES[this.data.reportTypeIndex] || REPORT_TYPES[0];
const attachment = {
id: `r_${Date.now()}_${Math.floor(Math.random() * 1e6)}`,
file_path: parsed.file_path,
report_type: type.value,
type_label: type.label,
report_no: String(this.data.reportNo || '').trim(),
product_names: parsed.product_names || [],
produced_at: parsed.produced_at || null,
testing_org: parsed.testing_org || null,
};
const patch = {};
(this.data.lines || []).forEach((line, index) => {
if (picked.indexOf(String(line.key || '')) < 0) return;
const current = Array.isArray(line.reports) ? line.reports : [];
// 同一份文件 + 同一类型不重复挂
if (
current.some(
(r) => r.file_path === attachment.file_path && r.report_type === attachment.report_type
)
) {
return;
}
patch[`lines[${index}].reports`] = current.concat([attachment]);
});
if (Object.keys(patch).length) this.setData(patch);
this.setData({ reportOpen: false, reportParsed: null, reportNameText: '', reportOptions: [] });
wx.showToast({ title: '已挂到所选商品', icon: 'none' });
},
onReportChipRemove(e) {
const index = Number(e.currentTarget.dataset.index);
const reportId = String((e.currentTarget.dataset && e.currentTarget.dataset.reportId) || '');
const line = (this.data.lines || [])[index];
if (!line || !reportId) return;
const next = (Array.isArray(line.reports) ? line.reports : []).filter(
(r) => String(r.id) !== reportId
);
this.setData({ [`lines[${index}].reports`]: next });
},
// ── 按行入库(复用 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,
// 上传时挂到本行的批次报告:随入库一起提交(入库成功后才落库并绑定)
reports: (Array.isArray(line.reports) ? line.reports : []).map((r) => ({
file_path: r.file_path,
report_type: r.report_type,
report_no: r.report_no || null,
product_names: r.product_names || [],
produced_at: r.produced_at || null,
testing_org: r.testing_org || null,
})),
},
};
},
async submitLine(e) {
if (this.data.submitting || this._submitInFlight) 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._submitInFlight = true;
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);
// 报告绑定结果:入库已经成功,报告失败只提示去 Web 补挂(开发者口径 2026-10-21)
const bindings = Array.isArray(data.report_bindings) ? data.report_bindings : [];
const reportFailures = bindings.reduce(
(sum, b) => sum + (b && Array.isArray(b.failed) ? b.failed.length : 0),
0
);
if (reportFailures > 0) {
wx.showModal({
title: '已入库,报告未挂上',
content: `有 ${reportFailures} 份报告未绑定成功,可到 Web「库存管理」该批次下补挂。`,
showCancel: false,
});
} else {
wx.showToast({ title: '已入库', icon: 'none' });
}
} catch (err) {
wx.showToast({ title: err.message || '入库失败', icon: 'none' });
} finally {
this._submitInFlight = false;
this.setData({ submitting: false, submittingIndex: -1 });
}
},
/**
* 一键入库(2026-10-21 开发者需求):把全部待审核行一次性提交。
*
* 口径与 Web 批量入库一致:
* - 先逐行本地校验,任何一行不合格就整体不提交(提示第几行、什么问题);
* - 规格与商品档案不一致(409 `spec_conflict`)⇒ 确认后带 `confirm_spec_conflict` 重提;
* - **失败行留在列表**(按 rowNumber),成功行移除;
* - 行携带的报告随入库绑定,绑定失败只提示去 Web 补挂(不影响入库)。
*/
async submitAllLines() {
if (this.data.submitting || this._submitInFlight) return;
const lines = this.data.lines || [];
if (!lines.length) return;
const rows = [];
for (let i = 0; i < lines.length; i += 1) {
const built = this.buildRowFromLine(lines[i]);
if (built.error) {
wx.showModal({
title: '无法一键入库',
content: `第 ${i + 1} 行:${built.error}`,
showCancel: false,
});
return;
}
rows.push(built.row);
}
this._submitInFlight = true;
this.setData({ submitting: true, submittingIndex: -1 });
try {
let data = {};
try {
const res = await submitStockInboundBatch({ rows });
data = (res && res.data) || res || {};
} catch (conflictError) {
const code = conflictError && conflictError.body && conflictError.body.error;
const message = String((conflictError && conflictError.message) || '');
if (code !== 'spec_conflict' && !(/规格/.test(message) && /不一致/.test(message))) {
throw conflictError;
}
const proceed = await new Promise((resolve) => {
wx.showModal({
title: '规格与商品档案不一致',
content: message,
confirmText: '仍然入库',
cancelText: '取消',
success: (r) => resolve(Boolean(r.confirm)),
fail: () => resolve(false),
});
});
if (!proceed) return;
const retry = await submitStockInboundBatch({ rows, confirm_spec_conflict: true });
data = (retry && retry.data) || retry || {};
}
const failedRows = (Array.isArray(data.results) ? data.results : []).filter(
(r) => r && r.mode === 'failed'
);
const failedCount = Number(data.failed_count || failedRows.length || 0);
const okCount = Number(data.ok_count || rows.length - failedCount || 0);
const reportFailures = (Array.isArray(data.report_bindings) ? data.report_bindings : []).reduce(
(sum, binding) =>
sum + (binding && Array.isArray(binding.failed) ? binding.failed.length : 0),
0
);
// 失败行按 rowNumber 留在列表,成功行移除(与 Web 同口径)
const failedNumbers = new Set(failedRows.map((r) => Number(r.rowNumber)));
const remain = (this.data.lines || []).filter((_, i) => failedNumbers.has(i + 1));
const patch = { lines: remain };
if (!remain.length) patch.imageList = [];
this.setData(patch);
if (failedCount) {
const first = (failedRows[0] && failedRows[0].error) || '';
wx.showModal({
title: '部分入库失败',
content: `成功 ${okCount} 行,失败 ${failedCount} 行${first ? `:${first}` : ''}`,
showCancel: false,
});
} else if (reportFailures > 0) {
wx.showModal({
title: '已入库,报告未挂上',
content: `有 ${reportFailures} 份报告未绑定成功,可到 Web「库存管理」该批次下补挂。`,
showCancel: false,
});
} else {
wx.showToast({ title: `已入库 ${okCount} 行`, icon: 'none' });
}
} catch (err) {
wx.showToast({ title: (err && err.message) || '批量入库失败', icon: 'none' });
} finally {
this._submitInFlight = false;
this.setData({ submitting: false, submittingIndex: -1 });
}
},
},
});