品名格:不再出现两行「品名」;新建行只在有输入时出现(新建「X」),输入新名后输入框显示该名字;点「新建「X」」弹窗建品并选中该行(Web Modal + 小程序底部表单,含品名/分类/规格/单位/生产地区)。 存放区域格:同口径去掉 allowEmpty/emptyLabel/alwaysShowCreate,空查询不再渲染「存放区域」选项行;仍支持输入新区域。 SearchableSelect.selected 的 fallback 条件加 !allowEmpty,使未传 allowEmpty 的字段空值也能显示 fallbackLabel;Bid/Purchase/分类/区域行为不变。
772 lines
28 KiB
JavaScript
772 lines
28 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 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)}`;
|
||
}
|
||
|
||
function applyMatchedFields(line, candidate, backfill) {
|
||
// 单位 / 规格 / 分类:**匹配到的商品优先**,AI 识别值只是没匹配时的备选
|
||
if (candidate) {
|
||
if (candidate.spec) line.spec = candidate.spec;
|
||
if (candidate.unit) line.unit = candidate.unit;
|
||
}
|
||
if (backfill && backfill.category_code) {
|
||
line.category_code = backfill.category_code;
|
||
line.category_name = 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 = backfill.last_storage_zone;
|
||
}
|
||
if (!line.shelf_life && backfill.last_shelf_life_days != null) {
|
||
line.shelf_life = `${backfill.last_shelf_life_days}天`;
|
||
}
|
||
if (!line.origin && backfill.origin) {
|
||
line.origin = 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: String((item && item.item_name) || ''),
|
||
spec: String((item && item.spec) || ''),
|
||
unit: String((item && item.unit) || ''),
|
||
origin: String((item && item.origin) || ''),
|
||
qty: item && item.qty != null ? String(item.qty) : '',
|
||
unit_cost: item && item.unit_cost != null ? String(item.unit_cost) : '',
|
||
sku_code: String(matched.sku_code || ''),
|
||
candidates,
|
||
// 分类:未命中商品时用 AI 从已有分类里选的(命中时由 applyMatchedFields 覆盖为商品档案值)
|
||
category_code: String((item && item.category_code) || ''),
|
||
category_name: String((item && item.category_name) || ''),
|
||
storage_zone: '',
|
||
production_date: String((item && item.production_date) || ''),
|
||
shelf_life: String((item && item.shelf_life) || ''),
|
||
};
|
||
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 (!target.unit && source.unit) target.unit = source.unit;
|
||
if (!target.unit_cost && source.unit_cost) target.unit_cost = source.unit_cost;
|
||
if (!target.production_date && source.production_date) target.production_date = source.production_date;
|
||
if (!target.shelf_life && source.shelf_life) target.shelf_life = source.shelf_life;
|
||
if (!target.storage_zone && source.storage_zone) target.storage_zone = source.storage_zone;
|
||
if (!target.origin && source.origin) target.origin = 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,
|
||
productionDateEnd: '',
|
||
categories: [],
|
||
categoryOptions: [],
|
||
zoneOptions: [],
|
||
sheetOpen: false,
|
||
sheetType: '',
|
||
sheetIndex: -1,
|
||
sheetQuery: '',
|
||
sheetList: [],
|
||
sheetCanCreate: false,
|
||
sheetCreateLabel: '',
|
||
/** 「商品选择」远程检索结果(带上次设置回填) */
|
||
productOptions: [],
|
||
/** 「新建商品」表单草稿(sheetType='newProduct' 时用) */
|
||
newProduct: null,
|
||
creatingProduct: false,
|
||
},
|
||
|
||
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);
|
||
this.openSheet('product', index);
|
||
this.searchProducts('');
|
||
},
|
||
|
||
openSheet(type, index) {
|
||
if (!Number.isInteger(index) || index < 0) return;
|
||
this.setData({
|
||
sheetOpen: true,
|
||
sheetType: type,
|
||
sheetIndex: index,
|
||
sheetQuery: '',
|
||
sheetList: this.sheetSource(type),
|
||
sheetCanCreate: false,
|
||
sheetCreateLabel: '',
|
||
});
|
||
},
|
||
|
||
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,
|
||
};
|
||
// 规格 / 单位:商品档案优先
|
||
if (opt.spec) patch[`lines[${index}].spec`] = opt.spec;
|
||
if (opt.unit) patch[`lines[${index}].unit`] = opt.unit;
|
||
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}天`;
|
||
}
|
||
if (!String(line.origin || '').trim() && bf.origin) {
|
||
patch[`lines[${index}].origin`] = bf.origin;
|
||
}
|
||
}
|
||
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`]: [],
|
||
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;
|
||
this.setData({ [`lines[${index}].${field}`]: e.detail.value });
|
||
},
|
||
|
||
onLineProd(e) {
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
this.setData({ [`lines[${index}].production_date`]: e.detail.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`] = candidate.sku_name;
|
||
// 单位 / 规格:**匹配到的商品优先**
|
||
if (candidate.spec) patch[`lines[${index}].spec`] = candidate.spec;
|
||
if (candidate.unit) patch[`lines[${index}].unit`] = candidate.unit;
|
||
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}天`;
|
||
}
|
||
// 生产地区:AI 优先,空才回填
|
||
if (!String(line.origin || '').trim() && bf.origin) {
|
||
patch[`lines[${index}].origin`] = bf.origin;
|
||
}
|
||
}
|
||
}
|
||
this.setData(patch);
|
||
},
|
||
|
||
onLineRemove(e) {
|
||
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({})]),
|
||
});
|
||
},
|
||
|
||
// ── 提交 ──────────────────────────────────────────────
|
||
async submitBatch() {
|
||
if (this.data.submitting) return;
|
||
const lines = this.data.lines;
|
||
if (!lines.length) {
|
||
wx.showToast({ title: '请先识别或手动添加商品', icon: 'none' });
|
||
return;
|
||
}
|
||
const rows = [];
|
||
for (const line of lines) {
|
||
const qty = Number(line.qty);
|
||
const label = line.item_name || '未命名行';
|
||
if (!(qty > 0)) {
|
||
wx.showToast({ title: `数量须大于 0:${label}`, icon: 'none' });
|
||
return;
|
||
}
|
||
if (!line.sku_code) {
|
||
if (!String(line.item_name || '').trim()) {
|
||
wx.showToast({ title: '有行缺少品名', icon: 'none' });
|
||
return;
|
||
}
|
||
if (!line.category_code) {
|
||
wx.showToast({ title: `请为「${label}」选择分类`, icon: 'none' });
|
||
return;
|
||
}
|
||
}
|
||
rows.push({
|
||
sku_code: line.sku_code || undefined,
|
||
new_product: line.sku_code
|
||
? undefined
|
||
: {
|
||
name: String(line.item_name || '').trim(),
|
||
category_code: line.category_code,
|
||
spec: String(line.spec || '').trim() || undefined,
|
||
unit: String(line.unit || '').trim() || undefined,
|
||
origin: String(line.origin || '').trim() || undefined,
|
||
},
|
||
qty,
|
||
unit_cost: line.unit_cost === '' || line.unit_cost == null ? null : Number(line.unit_cost),
|
||
production_date: line.production_date || undefined,
|
||
shelf_life: String(line.shelf_life || '').trim() || undefined,
|
||
storage_zone: String(line.storage_zone || '').trim() || undefined,
|
||
});
|
||
}
|
||
|
||
this.setData({ submitting: true });
|
||
try {
|
||
const res = await submitStockInboundBatch({ rows });
|
||
const data = res.data || res || {};
|
||
const okCount = Number(data.ok_count || 0);
|
||
const failed = Number(data.failed_count || 0);
|
||
if (!failed) {
|
||
wx.showToast({ title: `已入库 ${okCount} 行`, icon: 'none' });
|
||
this.setData({ lines: [], imageList: [] });
|
||
} else {
|
||
const results = Array.isArray(data.results) ? data.results : [];
|
||
const failedRows = results.filter((r) => r.mode === 'failed');
|
||
const firstErr = failedRows[0] && failedRows[0].error ? failedRows[0].error : '见错误行';
|
||
wx.showModal({
|
||
title: '部分未入库',
|
||
content: `成功 ${okCount} 行,失败 ${failed} 行。首个失败:${firstErr}`,
|
||
showCancel: false,
|
||
});
|
||
const failedNumbers = new Set(failedRows.map((r) => Number(r.rowNumber)));
|
||
const remain = this.data.lines.filter((_, i) => failedNumbers.has(i + 1));
|
||
this.setData({ lines: remain });
|
||
}
|
||
} catch (e) {
|
||
wx.showToast({ title: e.message || '批量入库失败', icon: 'none' });
|
||
} finally {
|
||
this.setData({ submitting: false });
|
||
}
|
||
},
|
||
},
|
||
});
|