const requestApi = require('../../utils/request'); const { fetchPickingTasks, fetchPickingOutboundBatches, request, } = requestApi; function savePickingProgress(payload) { if (typeof requestApi.savePickingProgress === 'function') { return requestApi.savePickingProgress(payload); } return request('/mobile/picking/progress', { method: 'POST', data: payload }); } function confirmPickingComplete(payload) { if (typeof requestApi.confirmPickingComplete === 'function') { return requestApi.confirmPickingComplete(payload); } return request('/mobile/picking/complete', { method: 'POST', data: payload }); } const { ensureMobileRole } = require('../../utils/roleGuard'); const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate'); const { isItemPending, visibleItemsForStatus, normalizePickingItem, summarizeTask, buildProgressRows, resolvePickMeasures, resolveItemNeed, allocateBatchesFifo, formatBatchPlanText, formatBatchQty, isScaleWeightMandatory, } = require('../../utils/pickingAssembly'); const { buildUnitPicker, ensureUnitDictionary, getUnitDictionaryLabels, isWeightUnit } = require('../../utils/units'); const { formatMpOrderCode, formatMpOrderCodeList } = require('../../utils/orderCodeDisplay'); const { fmtLocalDate } = require('../../utils/purchaseToday'); const { printPickingLabel } = require('../../utils/pickingLabelPrint'); const { prepareOrderImageBase64 } = require('../../utils/orderImage'); const DATE_FIELD_OPTIONS = [ { label: '下单日', value: 'created_at' }, { label: '配送日', value: 'delivery_date' }, ]; function countPending(items) { return (items || []).filter((item) => isItemPending(item)).length; } /** 归一化已持久化的批次计划;空返回 null */ function normalizeSavedPlan(raw) { if (!Array.isArray(raw)) return null; const out = raw .map((p) => ({ batch_no: String((p && p.batch_no) || ''), qty: Number(p && p.qty) || 0, })) .filter((p) => p.batch_no && p.qty > 0); return out.length ? out : null; } /** AI 生产日期 → 批次:**唯一命中**(可用量 > 0)才返回该批次,多命中/无命中都返回 null(不猜,交拣货员手动选) */ function matchBatchByProductionDate(batches, date) { const target = String(date || '').trim(); if (!target) return null; const hits = (batches || []).filter( (b) => String((b && b.production_date) || '').trim() === target && (Number(b && b.available_qty) || 0) > 0 ); return hits.length === 1 ? hits[0] : null; } /** 出库计划打底:命中批次先取(不超需拣量),余量按先进先出补;未命中则整行先进先出 */ function buildBatchBasePlan(batches, need, matched) { const needQty = Math.max(0, Number(need) || 0); if (!matched) return allocateBatchesFifo(batches, needQty).plan; const take = Math.min(Number(matched.available_qty) || 0, needQty); const plan = take > 0 ? [{ batch_no: String(matched.batch_no), qty: Math.round(take * 1000) / 1000 }] : []; const remaining = Math.round((needQty - take) * 1000) / 1000; if (remaining > 0) { const rest = (batches || []).filter((b) => String(b.batch_no) !== String(matched.batch_no)); plan.push(...allocateBatchesFifo(rest, remaining).plan); } return plan; } function taskScopeType(task) { return String((task && task.scope_type) || 'order').trim() || 'order'; } function taskGroupKey(task) { const type = taskScopeType(task); if (type === 'category' || type === 'sku' || type === 'zone') { return `${type}:${String(task.scope_key || task.scope_label || '').trim() || 'NA'}`; } return `order:${String(task.order_code || task.pick_code || '').trim()}`; } function taskPickerLabel(task) { const type = taskScopeType(task); if (type === 'category') return String(task.scope_label || task.scope_key || '未分类').trim(); if (type === 'sku') return String(task.scope_label || task.scope_key || '商品').trim(); // 区域模式(2026-11-05 新增):选择器/分组标签必须显示**区域名**,否则落到下面的兜底 → 全部显示订单号 if (type === 'zone') return String(task.scope_label || task.scope_key || '未设区域').trim(); return String(task.order_code_short || task.order_code || '订单').trim(); } function buildScopeGroups(tasks) { const map = new Map(); (tasks || []).forEach((task) => { const key = taskGroupKey(task); if (!map.has(key)) { map.set(key, { key, scopeType: taskScopeType(task), label: taskPickerLabel(task), pickCodes: [], tasks: [], }); } const group = map.get(key); group.tasks.push(task); group.pickCodes.push(task.pick_code); }); const labelCount = {}; map.forEach((group) => { labelCount[group.label] = (labelCount[group.label] || 0) + 1; }); map.forEach((group) => { if ((labelCount[group.label] || 0) > 1) { const extra = group.tasks .map((row) => row.order_code_short || row.order_code) .filter(Boolean)[0]; if (extra) group.label = `${group.label} · ${extra}`; } }); return Array.from(map.values()); } function flattenGroupItems(group, itemsMap, scaleRequired) { const rows = []; if (!group) return rows; (group.tasks || []).forEach((task) => { const status = Number(task.pick_status) || 0; ((itemsMap && itemsMap[task.pick_code]) || []).forEach((item) => { const normalized = normalizePickingItem(item, status, { scaleRequired }); const orderCode = String(task.order_code_short || task.order_code || '').trim(); const product = String(normalized.display_name || '').trim(); rows.push({ ...normalized, pick_code: task.pick_code, order_code_short: orderCode, delivery_date: item.delivery_date || task.delivery_date, line_pick_status: status, display_name: product || normalized.display_name, line_name: [product, orderCode].filter(Boolean).join(' · ') || '—', rowKey: `${task.pick_code}:${normalized.id}`, }); }); }); return rows; } function groupMinStatus(group) { const statuses = (group && group.tasks ? group.tasks : []).map((row) => Number(row.pick_status) || 0); if (!statuses.length) return 0; return Math.min.apply(null, statuses); } function groupStillOpen(group, itemsMap, scaleRequired) { if (!group) return false; if (groupMinStatus(group) >= 30) return false; return flattenGroupItems(group, itemsMap, scaleRequired).length > 0; } /** * 按商品区域插入分组表头。 * 无任何区域时不分组(直接平铺);有区域时按区域归组,未设区域的归入「未设区域」。 */ function withZoneHeaders(rows) { const list = rows || []; const hasZone = list.some((row) => String(row.storage_zone || '').trim()); if (!hasZone) return list; const out = []; const seen = Object.create(null); list.forEach((row) => { const zone = String(row.storage_zone || '').trim() || '未设区域'; if (!seen[zone]) { seen[zone] = true; out.push({ _zone: true, zone_label: zone, rowKey: `zone:${zone}` }); } out.push(row); }); return out; } const PICKING_ROLES = ['picker', 'warehouse', 'delivery']; Component({ options: { addGlobalClass: true }, properties: { embedded: { type: Boolean, value: false }, hideProgress: { type: Boolean, value: false }, }, data: { tasks: [], itemsMap: {}, batchesMap: {}, editor: null, activePickCode: '', activeTask: null, activeItems: [], activePendingItems: [], taskSummary: null, pendingCount: 0, pickingBarcodeEnabled: false, pickingScaleRequired: false, workMode: 'manual', loading: false, saving: false, printing: false, /** 出库拍照(可选,商品级):按拣货明细 id 存「已上传到 delivery-photos 桶的对象路径 + 本地临时图预览」 */ rowPhotos: {}, photoUploadingId: '', error: '', scanTip: '', workflowTip: '', showWorkTitle: false, showCompanyMeta: false, showOrderCodesMeta: false, scopeGroups: [], scopePickerLabels: [], scopePickerIndex: 0, activeGroupKey: '', activePickCodes: [], scopeMenuOpen: false, skuCatalogMode: false, skuSections: [], dayGroups: [], hasOpenPicks: false, dateField: 'created_at', dateFieldLabel: '下单日', dateFieldIndex: 0, dateFieldOptions: DATE_FIELD_OPTIONS, dateFrom: '', dateTo: '', todayValue: fmtLocalDate(), }, lifetimes: { attached() { this.onPanelShow(); }, }, pageLifetimes: { show() { this.onPanelShow(); }, }, methods: { emitProgress(patch = {}) { if (!this.properties.hideProgress) return; const summary = this.data.taskSummary || {}; this.triggerEvent('progresschange', { taskCount: patch.taskCount != null ? patch.taskCount : (this.data.tasks || []).length, pickedCount: patch.pickedCount != null ? patch.pickedCount : Number(summary.pickedCount) || 0, pendingCount: patch.pendingCount != null ? patch.pendingCount : this.data.pendingCount, }); }, async onPanelShow() { if (!beginPanelShow(this)) return; try { const ok = await ensureMobileRole(PICKING_ROLES, { prefer: 'picker', message: '请切换到分拣员、仓管员或配送员工作台,且账号需开通分拣出库权限', }); if (!ok) return; await ensureUnitDictionary(() => requestApi.fetchUnits()); await this.loadRows(); } finally { endPanelShow(this); } }, async loadRows() { this.setData({ loading: true, error: '', workflowTip: '仅显示 Web 分配给您的拣货单' }); try { const params = {}; if (this.data.dateFrom) params.date_from = this.data.dateFrom; if (this.data.dateTo) params.date_to = this.data.dateTo; if ((this.data.dateFrom || this.data.dateTo) && this.data.dateField) { params.date_field = this.data.dateField; } const result = await fetchPickingTasks(params); const scaleRequired = result.picking_scale_required === true; const statusByPick = Object.fromEntries((result.data || []).map((task) => [task.pick_code, task.pick_status])); const map = {}; (result.items || []).forEach((item) => { if (!map[item.pick_code]) map[item.pick_code] = []; map[item.pick_code].push( normalizePickingItem(item, statusByPick[item.pick_code], { scaleRequired }) ); }); const tasks = (result.data || []) .filter((task) => Number(task.pick_status) < 40) .map((task) => { const scopeType = task.scope_type || 'order'; const orderCodeShort = formatMpOrderCode(task.order_code); let tabTitle = orderCodeShort || '分拣任务'; if (scopeType === 'category') { tabTitle = `${orderCodeShort || ''}·${task.scope_label || task.scope_key || '分类'}`.replace(/^·/, ''); } else if (scopeType === 'sku') { tabTitle = `${orderCodeShort || ''}·${task.scope_label || task.scope_key || '商品'}`.replace(/^·/, ''); } else if (scopeType === 'zone') { tabTitle = `${orderCodeShort || ''}·${task.scope_label || task.scope_key || '区域'}`.replace(/^·/, ''); } else if (scopeType === 'customer') { tabTitle = task.scope_label || task.company_name || '客户合单'; } else { tabTitle = orderCodeShort || '分拣任务'; } return { ...task, order_code_short: orderCodeShort, order_codes_short: formatMpOrderCodeList(task.order_codes), tab_title: tabTitle, status_label: summarizeTask(map[task.pick_code] || [], task.pick_status).statusLabel, group_key: '', }; }); tasks.forEach((task) => { task.group_key = taskGroupKey(task); }); const scopeGroups = buildScopeGroups(tasks).filter((group) => groupStillOpen(group, map, scaleRequired) ); const scopePickerLabels = scopeGroups.map((group) => group.label); let activeGroupKey = this.data.activeGroupKey; if (activeGroupKey && !scopeGroups.some((group) => group.key === activeGroupKey)) { activeGroupKey = ''; } if (!activeGroupKey && this.data.activePickCode) { const prev = tasks.find((row) => row.pick_code === this.data.activePickCode); if (prev) activeGroupKey = prev.group_key; } if (!activeGroupKey && scopeGroups.length) { activeGroupKey = scopeGroups[0].key; } this.setData({ tasks, itemsMap: map, pickingBarcodeEnabled: false, pickingScaleRequired: scaleRequired, workMode: 'manual', scopeGroups, scopePickerLabels, scopeMenuOpen: false, skuCatalogMode: false, }); this.selectGroupByKey(activeGroupKey); this.emitProgress({ taskCount: tasks.length }); // 列表有 LIMIT 50,红点数量让首页回源 /mobile/badges 的 COUNT,避免封顶 this.triggerEvent('badgechange'); } catch (err) { this.setData({ error: err.message || '加载失败', tasks: [], itemsMap: {}, activePickCode: '', activeTask: null, activeItems: [], activePendingItems: [], taskSummary: null, pendingCount: 0, pickingScaleRequired: false, showWorkTitle: false, showCompanyMeta: false, showOrderCodesMeta: false, scopeGroups: [], scopePickerLabels: [], scopePickerIndex: 0, activeGroupKey: '', activePickCodes: [], scopeMenuOpen: false, skuCatalogMode: false, skuSections: [], dayGroups: [], hasOpenPicks: false, }); this.emitProgress({ taskCount: 0, pickedCount: 0, pendingCount: 0 }); } finally { this.setData({ loading: false }); } }, selectTask(e) { const pick = e.currentTarget.dataset.pick; const task = (this.data.tasks || []).find((row) => row.pick_code === pick); if (task) this.selectGroupByKey(taskGroupKey(task)); }, onDateFieldPick(e) { const idx = Number(e.detail.value) || 0; const opt = DATE_FIELD_OPTIONS[idx] || DATE_FIELD_OPTIONS[0]; if (opt.value === this.data.dateField) return; this.setData( { dateField: opt.value, dateFieldIndex: idx, dateFieldLabel: opt.label, }, () => { if (this.data.dateFrom || this.data.dateTo) this.loadRows(); } ); }, onCustomFromChange(e) { const next = String(e.detail.value || '').trim().slice(0, 10); if (!/^\d{4}-\d{2}-\d{2}$/.test(next)) return; let to = this.data.dateTo || ''; if (to && next > to) to = next; this.setData({ dateFrom: next, dateTo: to }, () => this.loadRows()); }, onCustomToChange(e) { const next = String(e.detail.value || '').trim().slice(0, 10); if (!/^\d{4}-\d{2}-\d{2}$/.test(next)) return; let from = this.data.dateFrom || ''; if (from && next < from) from = next; this.setData({ dateFrom: from, dateTo: next }, () => this.loadRows()); }, toggleScopeMenu() { if (!(this.data.scopeGroups || []).length) return; this.setData({ scopeMenuOpen: !this.data.scopeMenuOpen }); }, onScopeOptionTap(e) { const key = e.currentTarget.dataset.key; this.setData({ scopeMenuOpen: false }); if (key) this.selectGroupByKey(key); }, switchWorkMode(e) { const mode = e.currentTarget.dataset.mode; if (!mode || mode === this.data.workMode) return; if (mode === 'scan' && !this.data.pickingBarcodeEnabled) { wx.showToast({ title: '未开通扫码权限,请用手动确认', icon: 'none' }); return; } this.setData({ workMode: mode, scanTip: '' }); if (this.data.activePickCode) { this.selectTaskByCode(this.data.activePickCode); } }, selectTaskByCode(pickCode) { const task = (this.data.tasks || []).find((row) => row.pick_code === pickCode); if (task) { this.selectGroupByKey(taskGroupKey(task)); return; } this.selectGroupByKey(this.data.activeGroupKey); }, applySkuCatalogView() { this.selectGroupByKey(this.data.activeGroupKey); }, selectGroupByKey(groupKey) { if (!groupKey) { this.setData({ activePickCode: '', activePickCodes: [], activeGroupKey: '', scopePickerIndex: 0, scopeMenuOpen: false, skuCatalogMode: false, skuSections: [], dayGroups: [], hasOpenPicks: false, activeTask: null, activeItems: [], activePendingItems: [], taskSummary: null, pendingCount: 0, workflowTip: '', showWorkTitle: false, showCompanyMeta: false, showOrderCodesMeta: false, }); this.emitProgress({ taskCount: (this.data.tasks || []).length, pickedCount: 0, pendingCount: 0, }); return; } const groups = this.data.scopeGroups || []; const groupIndex = groups.findIndex((row) => row.key === groupKey); const group = groupIndex >= 0 ? groups[groupIndex] : null; if (!group) { this.selectGroupByKey(''); return; } const scaleRequired = this.data.pickingScaleRequired === true; const items = flattenGroupItems(group, this.data.itemsMap, scaleRequired); const status = groupMinStatus(group); const task = group.tasks.find((row) => Number(row.pick_status) < 30) || group.tasks[0] || null; const taskSummary = summarizeTask(items, status); const pendingCount = countPending(items); const hasOpenPicks = status < 30; const pendingItems = visibleItemsForStatus(items, status); this.setData( { activePickCode: task ? task.pick_code : '', activePickCodes: group.pickCodes, activeGroupKey: group.key, scopePickerIndex: groupIndex, scopeMenuOpen: false, skuCatalogMode: false, skuSections: [], dayGroups: [], hasOpenPicks, activeTask: task ? { ...task, pick_status: status } : { pick_status: status }, activeItems: items, activePendingItems: withZoneHeaders(this.applyItemZones(pendingItems)), taskSummary, pendingCount, scanTip: '', workflowTip: '', showWorkTitle: false, showCompanyMeta: false, showOrderCodesMeta: false, }, () => { this.loadBatchInfo(pendingItems); } ); this.emitProgress({ taskCount: (this.data.tasks || []).length, pickedCount: Number(taskSummary && taskSummary.pickedCount) || 0, pendingCount, }); }, /** 按商品 id 在已加载明细中查找(itemsMap 是最新数据源) */ findItemById(id) { if (!id) return null; const map = this.data.itemsMap || {}; for (const key of Object.keys(map)) { const found = (map[key] || []).find((item) => item.id === id); if (found) return found; } return (this.data.activeItems || []).find((item) => item.id === id) || null; }, /** 拉取每行候选批次并默认按先进先出预分配(只读,不扣库) */ async loadBatchInfo(items) { const targets = (items || []).filter( (item) => item && item.id && String(item.sku_code || '').trim() && resolveItemNeed(item) > 0 && !this.data.batchesMap[item.id] ); if (!targets.length) return; targets.forEach((item) => { this.setData({ [`batchesMap.${item.id}`]: { loading: true, error: '', batches: [], plan: [] }, }); }); await Promise.all( targets.map(async (item) => { try { const payload = await fetchPickingOutboundBatches(item.id); const data = payload && payload.data ? payload.data : payload || {}; const batches = (data.batches || []).map((b) => ({ batch_id: b.batch_id, batch_no: String(b.batch_no), available_qty: Number(b.available_qty) || 0, storage_zone: b.storage_zone || '', inbound_date: b.inbound_date || '', production_date: b.production_date || '', expiry_date: b.expiry_date || '', })); const need = resolveItemNeed(item); const serverPlan = normalizeSavedPlan(item.outbound_batches) || []; if (serverPlan.length) { this.setData({ [`batchesMap.${item.id}`]: { loading: false, error: '', batches, claimable: Number(data.claimable) || 0, total_available: Number(data.total_available) || 0, other_reserved: Number(data.other_reserved) || 0, need, plan: serverPlan, manual: true, shortfall: allocateBatchesFifo(batches, need).shortfall, plan_text: formatBatchPlanText(serverPlan, batches, item.unit), }, }); return; } const { plan, shortfall } = allocateBatchesFifo(batches, need); this.setData({ [`batchesMap.${item.id}`]: { loading: false, error: '', batches, claimable: Number(data.claimable) || 0, total_available: Number(data.total_available) || 0, other_reserved: Number(data.other_reserved) || 0, need, plan, manual: false, shortfall, plan_text: formatBatchPlanText(plan, batches, item.unit), }, }); } catch (err) { this.setData({ [`batchesMap.${item.id}`]: { loading: false, error: (err && err.message) || '批次加载失败', batches: [], plan: [], }, }); } }) ); // 区域来源(开发者 2026-10-12 选 A):批次加载完后,把「商品所在区」补到行上并刷新区域分组 this.setData({ activePendingItems: withZoneHeaders(this.applyItemZones(items)) }); }, /** 区域来源(开发者 2026-10-12 选 A/②):商品所在区 = **FIFO 计划里**要取的批次所在的区(跨区用「 / 」并列); * 没进计划的批次不显示 —— 若 B 区先入库且够量,就只显示 B 区;不够才会再带上 A 区。 */ applyItemZones(items) { const list = items || []; const map = this.data.batchesMap || {}; return list.map((item) => { const info = item && item.id ? map[item.id] : null; if (!info || !Array.isArray(info.batches) || !info.batches.length) return item; const plan = Array.isArray(info.plan) && info.plan.length ? info.plan : allocateBatchesFifo(info.batches, info.need || 0).plan; if (!plan || !plan.length) return item; const byNo = new Map(); info.batches.forEach((b) => byNo.set(String(b.batch_no), b)); const zones = []; plan.forEach((p) => { const z = String((byNo.get(String(p.batch_no)) || {}).storage_zone || '').trim(); if (z && zones.indexOf(z) === -1) zones.push(z); }); if (!zones.length) return item; return { ...item, storage_zone: zones.join(' / ') }; }); }, /** 本行要提交的出库批次计划;无批次信息返回 null(= 服务端按 FIFO) */ resolveItemPlan(item) { if (!item || !item.id) return null; const info = this.data.batchesMap[item.id]; if (info && Array.isArray(info.batches) && info.batches.length) { if (info.manual && Array.isArray(info.plan) && info.plan.length) return info.plan; const need = resolveItemNeed(item); if (need > 0) { const plan = allocateBatchesFifo(info.batches, need).plan; if (plan.length) return plan; } } // 批次拿不到(已完成单不再拉取 / 无库存)时回退已保存选择,避免被默认 FIFO 覆盖 return normalizeSavedPlan(item.outbound_batches); }, /** 勾选/改量后,未手改过的行按新数量重算 FIFO 预分配 */ refreshItemBatchPlan(id) { const info = this.data.batchesMap[id]; if (!info || info.manual || !Array.isArray(info.batches) || !info.batches.length) return; const item = this.findItemById(id); if (!item) return; const need = resolveItemNeed(item); const { plan, shortfall } = allocateBatchesFifo(info.batches, need); this.setData({ [`batchesMap.${id}.need`]: need, [`batchesMap.${id}.plan`]: plan, [`batchesMap.${id}.shortfall`]: shortfall, [`batchesMap.${id}.plan_text`]: formatBatchPlanText(plan, info.batches, item.unit), }); }, /** 给待提交明细注入「本次出库批次」与「出库留证照片(商品级)」 */ withPlans(items) { return (items || []).map((item) => { const plan = this.resolveItemPlan(item); const photos = (this.data.rowPhotos && this.data.rowPhotos[item.id]) || []; const patch = {}; if (plan) patch.outbound_batches = plan; if (photos.length) patch.outbound_photos = photos.map((p) => p.path); return Object.keys(patch).length ? { ...item, ...patch } : item; }); }, sumEditorQty(rows) { const total = (rows || []).reduce((sum, row) => sum + (Number(row.qty) || 0), 0); return Math.round(total * 1000) / 1000; }, openBatchEditor(e) { const id = e.currentTarget.dataset.id; const item = this.findItemById(id); const info = this.data.batchesMap[id]; if (!item || !info || !Array.isArray(info.batches) || !info.batches.length) { wx.showToast({ title: '暂无可扣批次', icon: 'none' }); return; } const need = resolveItemNeed(item); const basePlan = info.manual && Array.isArray(info.plan) ? info.plan : allocateBatchesFifo(info.batches, need).plan; const editor = this.buildEditorState(id, basePlan); if (editor) this.setData({ editor }); }, /** 由一个「打底计划」构造批次弹窗状态(openBatchEditor 与拍照 AI 匹配共用,避免两处漂)。 * extra.aiBatchNo:命中的批次号 ⇒ 该行高亮(“展示 AI 匹配到的那条”),其余行照常列出可选。 */ buildEditorState(itemId, basePlan, extra) { const item = this.findItemById(itemId); const info = this.data.batchesMap[itemId]; if (!item || !info || !Array.isArray(info.batches) || !info.batches.length) return null; const need = resolveItemNeed(item); const qtyByNo = new Map((basePlan || []).map((p) => [String(p.batch_no), Number(p.qty) || 0])); const aiBatchNo = String((extra && extra.aiBatchNo) || ''); const rows = info.batches.map((b) => ({ batch_id: String(b.batch_id || b.batch_no), batch_no: String(b.batch_no), storage_zone: b.storage_zone || '', inbound_date: b.inbound_date || '', expiry_date: b.expiry_date || '', available_qty: Number(b.available_qty) || 0, qty: formatBatchQty(qtyByNo.get(String(b.batch_no)) || 0), ai: Boolean(aiBatchNo) && String(b.batch_no) === aiBatchNo, })); return { itemId, name: item.display_name || item.item_name || '商品', unit: item.unit || '', need, claimable: Number(info.claimable) || 0, rows, total: this.sumEditorQty(rows), shortfall: Number(info.shortfall) || 0, }; }, closeBatchEditor() { if (this.data.editor) this.setData({ editor: null }); }, noop() {}, onBatchQtyInput(e) { const index = Number(e.currentTarget.dataset.index); const editor = this.data.editor; if (!editor) return; const rows = (editor.rows || []).map((row, i) => i === index ? { ...row, qty: e.detail.value } : row ); this.setData({ 'editor.rows': rows, 'editor.total': this.sumEditorQty(rows) }); }, resetBatchEditorFifo() { const editor = this.data.editor; if (!editor) return; const info = this.data.batchesMap[editor.itemId]; if (!info || !Array.isArray(info.batches)) return; const item = this.findItemById(editor.itemId); const need = item ? resolveItemNeed(item) : editor.need; const { plan } = allocateBatchesFifo(info.batches, need); const qtyByNo = new Map(plan.map((p) => [String(p.batch_no), Number(p.qty) || 0])); const rows = info.batches.map((b) => ({ batch_id: String(b.batch_id || b.batch_no), batch_no: String(b.batch_no), storage_zone: b.storage_zone || '', inbound_date: b.inbound_date || '', expiry_date: b.expiry_date || '', available_qty: Number(b.available_qty) || 0, qty: formatBatchQty(qtyByNo.get(String(b.batch_no)) || 0), ai: false, })); this.setData({ 'editor.rows': rows, 'editor.need': need, 'editor.total': this.sumEditorQty(rows), }); }, applyBatchEditor() { const editor = this.data.editor; if (!editor) return; const plan = (editor.rows || []) .map((row) => ({ batch_no: String(row.batch_no), qty: Math.round((Number(row.qty) || 0) * 1000) / 1000, })) .filter((row) => row.qty > 0); const total = Math.round(plan.reduce((sum, row) => sum + row.qty, 0) * 1000) / 1000; // 超量只提醒、不拦截:整件/不可拆分货物可能必须多取,计划合计允许超过实拣量 if (total - (Number(editor.need) || 0) > 1e-6) { wx.showToast({ title: '出库合计已超过需拣量', icon: 'none' }); } const info = this.data.batchesMap[editor.itemId] || { batches: [] }; this.setData({ [`batchesMap.${editor.itemId}`]: { ...info, manual: true, need: total > 0 ? total : editor.need, plan, plan_text: formatBatchPlanText(plan, info.batches, editor.unit), }, editor: null, }); // 方案 1(2026-10-12):批次合计 = 本次实际取出的量 ⇒ 回写「实拣量」,让扣库/批次报告与手选一致 this.syncItemMeasureFromPlan(editor.itemId, total); }, /** 把「调整批次」的合计回写为该行实拣量(重量单位写重量、计件写数量) */ syncItemMeasureFromPlan(itemId, total) { const value = Number(total) || 0; if (!(value > 0)) return; const item = this.findItemById(itemId); if (!item) return; const pick = item.pick_code || this.data.activePickCode; if (!pick) return; this.patchItemInput(pick, itemId, item.pick_by_weight ? 'input_weight' : 'input_qty', value); }, refreshActiveTaskView(pickCode, items) { const patch = { [`itemsMap.${pickCode}`]: items, }; this.setData(patch); if ((this.data.activePickCodes || []).includes(pickCode) || pickCode === this.data.activePickCode) { this.selectGroupByKey(this.data.activeGroupKey); } }, /** 只改输入字段,避免整表 setData 导致 input 失焦、界面点不动 */ patchItemInput(pick, id, field, value) { const items = (this.data.itemsMap[pick] || []).map((item) => item.id === id ? { ...item, [field]: value } : item ); const patch = { [`itemsMap.${pick}`]: items, }; if ((pick === this.data.activePickCode || (this.data.activePickCodes || []).includes(pick))) { const pendingIdx = (this.data.activePendingItems || []).findIndex((item) => item.id === id); if (pendingIdx >= 0) { patch[`activePendingItems[${pendingIdx}].${field}`] = value; } const activeIdx = (this.data.activeItems || []).findIndex((item) => item.id === id); if (activeIdx >= 0) { patch[`activeItems[${activeIdx}].${field}`] = value; } } this.setData(patch); this.refreshItemBatchPlan(id); }, onFieldInput(e) { const { pick, id, field } = e.currentTarget.dataset; const key = field === 'input_weight' ? 'input_weight' : 'input_qty'; this.patchItemInput(pick, id, key, e.detail.value); }, onUnitChange(e) { const { pick, id } = e.currentTarget.dataset; const index = Number(e.detail.value) || 0; const items = (this.data.itemsMap[pick] || []).map((item) => { if (item.id !== id) return item; const options = item.unitOptions || getUnitDictionaryLabels(); const unit = options[index] || options[0] || '个'; const byWeight = isWeightUnit(unit); const currentMeasure = byWeight ? Number(item.input_weight ?? item.input_qty ?? 0) : Number(item.input_qty ?? item.input_weight ?? 0); const measure = Number.isFinite(currentMeasure) ? currentMeasure : Number(item.required_qty) || 0; const picker = buildUnitPicker(unit, options); const keepWeight = byWeight || item.scale_required ? byWeight ? measure : Number(item.input_weight) || 0 : 0; return normalizePickingItem( { ...item, unit: picker.unit, unitOptions: picker.unitOptions, unitIndex: picker.unitIndex, pick_by_weight: byWeight, input_qty: byWeight ? 0 : measure, input_weight: keepWeight, }, this.data.activeTask?.pick_status, { scaleRequired: this.data.pickingScaleRequired === true } ); }); this.refreshActiveTaskView(pick, items); this.refreshItemBatchPlan(id); }, onQtyInput(e) { const { pick, id } = e.currentTarget.dataset; this.patchItemInput(pick, id, 'input_qty', e.detail.value); }, onWeightInput(e) { const { pick, id } = e.currentTarget.dataset; this.patchItemInput(pick, id, 'input_weight', e.detail.value); }, onScanPick() { const pickCode = this.data.activePickCode; if (!pickCode) { wx.showToast({ title: '请先选择拣货单', icon: 'none' }); return; } wx.navigateTo({ url: `/pages/picking-scan/picking-scan?pick_code=${encodeURIComponent(pickCode)}`, }); }, pickBleDevice() { const sheet = this.selectComponent('#blePicker'); if (!sheet || typeof sheet.pick !== 'function') { return Promise.resolve(null); } return sheet.pick(); }, /** 打印当前商品行的一张分拣标签(BLE 热敏直连;不走旧 print_jobs / 称重终端链路) */ async printCurrentPick(e) { if (this.data.printing) return; const id = e.currentTarget.dataset.id; const item = this.findItemById(id); if (!item) { wx.showToast({ title: '未找到该商品行', icon: 'none' }); return; } this.setData({ printing: true }); try { await printPickingLabel(this, this.data.activeTask || {}, item, () => this.pickBleDevice()); wx.showToast({ title: '已发送到打印机', icon: 'success' }); } catch (err) { wx.hideLoading(); if (err && err.message !== '已取消') { wx.showToast({ title: err.message || '打印失败', icon: 'none' }); } } finally { this.setData({ printing: false }); } }, buildConfirmRows(list) { const rows = []; for (const target of list) { const targetMeasures = resolvePickMeasures(target); const targetSettlement = Number(targetMeasures.picked_weight) > 0 ? Number(targetMeasures.picked_weight) : Number(targetMeasures.picked_qty) || 0; if (!(targetSettlement > 0)) { wx.showToast({ title: `${target.display_name || '商品'}实拣须大于 0`, icon: 'none' }); return null; } if (isScaleWeightMandatory(target, this.data.pickingScaleRequired)) { wx.showToast({ title: `${target.display_name || '商品'}请录入重量`, icon: 'none' }); return null; } rows.push({ id: target.id, required_qty: target.required_qty, picked_qty: targetMeasures.picked_qty, picked_weight: targetMeasures.picked_weight, unit: target.unit || null, diff_reason: target.diff_reason_input || target.diff_reason || '', outbound_batches: Array.isArray(target.outbound_batches) ? target.outbound_batches : undefined, }); } return rows; }, /** 出库拍照(可选,商品级):选/拍后立即上传得到对象路径;不拍也能完成分拣。 * 2026-10-15:上传成功后,用**第 1 张**照片读包装生产日期(AI-30),按它匹配出库批次并打开同一个 * 「调整批次」弹窗(命中唯一批次则预选该批次并高亮,否则维持先进先出由拣货员手动选)。识别失败不阻断。 */ pickItemPhotos(e) { const itemId = (e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.id) || ''; if (!itemId) return; wx.chooseMedia({ count: 9, mediaType: ['image'], sourceType: ['camera', 'album'], success: (res) => { const files = (res.tempFiles || []).filter((f) => f && f.tempFilePath); if (!files.length) return; this.setData({ photoUploadingId: itemId }); Promise.all( files.map((f) => requestApi .uploadPickingOutboundPhoto(f.tempFilePath) .then((path) => ({ path, tempFilePath: f.tempFilePath })) .catch((err) => { wx.showToast({ title: (err && err.message) || '照片上传失败', icon: 'none' }); return null; }) ) ).then((rows) => { const uploaded = rows.filter(Boolean); const existing = (this.data.rowPhotos && this.data.rowPhotos[itemId]) || []; this.setData({ photoUploadingId: '', [`rowPhotos.${itemId}`]: [...existing, ...uploaded], }); // 目前只读第 1 张(多张需逐个识别,暂不做) return this.applyBatchAiFromPhoto(itemId, files[0].tempFilePath); }).catch(() => { // AI 匹配属加法能力:任何意外都不得影响出库照上传与分拣 this.setData({ photoUploadingId: '' }); }); }, }); }, /** 拍到的照片 → AI 读生产日期 → 匹配批次 → 打开批次弹窗;识别失败/未配多模态时弹窗照常打开(按先进先出) */ async applyBatchAiFromPhoto(itemId, filePath) { let date = ''; try { const base64 = await prepareOrderImageBase64(filePath); const ext = String((filePath || '').split('.').pop() || 'jpg') .toLowerCase() .replace(/[^a-z0-9]/g, '') || 'jpg'; const payload = await requestApi.recognizePickingProductionDate({ image_base64: base64, ext }); const data = (payload && payload.data) || {}; date = String(data.production_date || '').trim(); } catch (err) { date = ''; } const info = this.data.batchesMap[itemId]; if (!info || !Array.isArray(info.batches) || !info.batches.length) return; const item = this.findItemById(itemId); if (!item) return; const matched = matchBatchByProductionDate(info.batches, date); const basePlan = buildBatchBasePlan(info.batches, resolveItemNeed(item), matched); const editor = this.buildEditorState(itemId, basePlan, { aiBatchNo: matched ? matched.batch_no : '', }); if (editor) this.setData({ editor }); }, /** 点缩略图预览出库照大图(本地临时图,会话内有效;删除按钮 catchtap 已阻止冒泡) */ previewItemPhoto(e) { const dataset = (e.currentTarget && e.currentTarget.dataset) || {}; const itemId = dataset.id || ''; const index = Number(dataset.index) || 0; if (!itemId) return; const photos = (this.data.rowPhotos && this.data.rowPhotos[itemId]) || []; const urls = photos.map((p) => p && p.tempFilePath).filter(Boolean); if (!urls.length) return; wx.previewImage({ current: urls[index] || urls[0], urls }); }, removeItemPhoto(e) { const dataset = (e.currentTarget && e.currentTarget.dataset) || {}; const itemId = dataset.id || ''; const index = Number(dataset.index); if (!itemId) return; const existing = (this.data.rowPhotos && this.data.rowPhotos[itemId]) || []; this.setData({ [`rowPhotos.${itemId}`]: existing.filter((_, i) => i !== index) }); }, async finishPickingNow(pickCode) { const items = this.data.itemsMap[pickCode] || this.data.activeItems || []; const task = (this.data.tasks || []).find((row) => row.pick_code === pickCode) || this.data.activeTask; const summary = summarizeTask(items, task?.pick_status); if (Number(task?.pick_status) >= 30) { wx.showToast({ title: '分拣已完成', icon: 'success' }); return; } if (!summary.canComplete) { wx.showToast({ title: '请先确认全部分拣明细', icon: 'none', }); return; } if (this.data.pickingScaleRequired) { const missingWeight = items.filter((item) => isScaleWeightMandatory(item, true)); if (missingWeight.length) { wx.showToast({ title: `还有 ${missingWeight.length} 项未录入重量`, icon: 'none' }); return; } } this.setData({ saving: true }); try { await confirmPickingComplete({ pick_code: pickCode, items: buildProgressRows(this.withPlans(items), pickCode), }); wx.showToast({ title: '分拣完成,订单进入待配送', icon: 'success', duration: 2500 }); this.setData({ rowPhotos: {} }); await this.loadRows(); } catch (err) { wx.showToast({ title: err.message || '分拣完成失败', icon: 'none' }); } finally { this.setData({ saving: false }); } }, async confirmAllPicks(e) { if (this.data.saving) return; const pickCodes = (this.data.activePickCodes || []).filter(Boolean); const fallback = (e && e.currentTarget && e.currentTarget.dataset.pick) || this.data.activePickCode; const codes = pickCodes.length ? pickCodes : (fallback ? [fallback] : []); if (!codes.length) { wx.showToast({ title: '请先选择拣货范围', icon: 'none' }); return; } this.setData({ saving: true }); try { for (const pickCode of codes) { const items = this.data.itemsMap[pickCode] || []; const toSave = items.filter( (item) => item.can_pick || (Number(item.review_status) || 0) < 20 ); if (toSave.length) { const rows = this.buildConfirmRows(this.withPlans(toSave)); if (!rows) { this.setData({ saving: false }); return; } await savePickingProgress({ pick_code: pickCode, items: rows }); } } await this.loadRows(); // 一键确认**只批量确认**,不自动完成;完成由底部「分拣完成」按钮触发(2026-10-13)。 wx.showToast({ title: '分拣已确认', icon: 'success' }); } catch (err) { wx.showToast({ title: err.message || '一键确认失败', icon: 'none' }); } finally { this.setData({ saving: false }); } }, async confirmItemPick(e) { const { pick, id } = e.currentTarget.dataset; const items = this.data.itemsMap[pick] || []; const target = items.find((item) => item.id === id); if (!target) return; const targetMeasures = resolvePickMeasures(target); const targetSettlement = Number(targetMeasures.picked_weight) > 0 ? Number(targetMeasures.picked_weight) : Number(targetMeasures.picked_qty) || 0; if (!(targetSettlement > 0)) { wx.showToast({ title: '实拣须大于 0,不能按 0 确认', icon: 'none' }); return; } if (isScaleWeightMandatory(target, this.data.pickingScaleRequired)) { wx.showToast({ title: '已开启称重,请录入重量', icon: 'none' }); return; } const rows = [ { id: target.id, required_qty: target.required_qty, picked_qty: targetMeasures.picked_qty, picked_weight: targetMeasures.picked_weight, unit: target.unit || null, diff_reason: target.diff_reason_input || target.diff_reason || '', outbound_batches: this.resolveItemPlan(target) || undefined, }, ]; this.setData({ saving: true }); try { await savePickingProgress({ pick_code: pick, items: rows }); await this.loadRows(); // 逐项确认**只存进度**;整单完成改由底部「分拣完成」按钮触发(2026-10-13,与 Web 对齐)。 // 原因:原先最后一项确认完就自动置 30,会立刻收起行级「拍照」入口,来不及补拍出库照。 // (小程序不做打印:开发者 2026-10-12) wx.showToast({ title: '分拣已确认', icon: 'success' }); } catch (err) { wx.showToast({ title: err.message || '确认分拣失败', icon: 'none' }); } finally { this.setData({ saving: false }); } }, async submitComplete(e) { const pickCode = e.currentTarget.dataset.pick || this.data.activePickCode; await this.finishPickingNow(pickCode); }, /** 兼容旧按钮名 */ submitAudit(e) { return this.submitComplete(e); }, }, });