Files
SupplierSystem/miniprogram/components/picking-panel/index.js
T
雨天 ab51e11596 feat(分拣): 小程序整单完成改由底部按钮触发
逐项确认与一键确认只存进度,不再自动置 30;整单完成由底部「分拣完成」按钮触发,与 Web 对齐。原先最后一项确认即完成会立刻收起行级拍照入口,来不及补拍出库照。
2026-10-13 10:09:18 +08:00

1130 lines
39 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 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,
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 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;
}
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();
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;
}
/** 未完成拣货单始终展示其仓内行(含已确认);完成(≥30)后才只留待补录 */
function visibleItemsForStatus(items, pickStatus) {
const status = Number(pickStatus) || 0;
const list = items || [];
if (status >= 40) return list;
if (status >= 30) {
const needs = list.filter((item) => isItemPending(item) || Number(item.settlement_qty || 0) <= 0);
return needs.length ? needs : list;
}
return list;
}
/**
* 按商品区域插入分组表头。
* 无任何区域时不分组(直接平铺);有区域时按区域归组,未设区域的归入「未设区域」。
*/
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,
/** 出库拍照(可选,商品级):按拣货明细 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 qtyByNo = new Map((basePlan || []).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),
}));
this.setData({
editor: {
itemId: id,
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),
}));
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)}`,
});
},
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;
},
/** 出库拍照(可选,商品级):选/拍后立即上传得到对象路径;不拍也能完成分拣 */
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],
});
});
},
});
},
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);
},
},
});