Files
SupplierSystem/miniprogram/components/picking-panel/index.js
T
雨天 efabb72e94
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(分拣): 保存不再覆盖已存的手选批次
- Web/小程序提交时优先沿用已持久化的 outbound_batches,避免再次保存
  被默认 FIFO 覆盖(Web「已完成单保存修改」会丢手选批次)
- 已出库(≥40)单展示落库计划,不再用剩余库存重算 FIFO
- 批次编辑器行按 batch_id 作 key
2026-10-11 13:52:17 +08:00

1152 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,
fetchPickingWeighDevices,
createPickingPrintJobs,
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') {
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,
printing: false,
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 === '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(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 || '',
}));
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),
},
});
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),
},
});
} catch (err) {
this.setData({
[`batchesMap.${item.id}`]: {
loading: false,
error: (err && err.message) || '批次加载失败',
batches: [],
plan: [],
},
});
}
})
);
},
/** 本行要提交的出库批次计划;无批次信息返回 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),
});
},
/** 给待提交明细注入「本次出库批次」 */
withPlans(items) {
return (items || []).map((item) => {
const plan = this.resolveItemPlan(item);
return plan ? { ...item, outbound_batches: plan } : 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 || '',
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) });
},
moveBatchRow(e) {
const index = Number(e.currentTarget.dataset.index);
const dir = Number(e.currentTarget.dataset.dir);
const editor = this.data.editor;
if (!editor) return;
const rows = (editor.rows || []).slice();
const target = index + dir;
if (target < 0 || target >= rows.length) return;
const tmp = rows[index];
rows[index] = rows[target];
rows[target] = tmp;
this.setData({ 'editor.rows': 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 || '',
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 info = this.data.batchesMap[editor.itemId] || { batches: [] };
this.setData({
[`batchesMap.${editor.itemId}`]: {
...info,
manual: true,
need: editor.need,
plan,
plan_text: formatBatchPlanText(plan, info.batches),
},
editor: null,
});
},
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;
},
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 });
await this.loadRows();
} catch (err) {
wx.showToast({ title: err.message || '分拣完成失败', icon: 'none' });
} finally {
this.setData({ saving: false });
}
},
async confirmAllPicks(e) {
if (this.data.saving || this.data.printing) 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();
for (const pickCode of codes) {
await this.finishPickingNow(pickCode);
}
for (const pickCode of codes) {
await this.printPickLabels({ pickCode, ignoreSaving: true });
}
} 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();
const items = this.data.itemsMap[pick] || [];
const task = (this.data.tasks || []).find((row) => row.pick_code === pick);
const summary = summarizeTask(items, task?.pick_status);
const printed = await this.printPickLabels({
pickCode: pick,
itemId: id,
ignoreSaving: true,
quietToast: true,
});
if (summary.canComplete) {
await this.finishPickingNow(pick);
if (printed === 'no_device') {
wx.showToast({ title: '请先在称上打开分拣工作台', icon: 'none' });
}
return;
}
if (printed === 'printed') {
wx.showToast({ title: '已确认并下发打印', icon: 'success' });
} else if (printed === 'no_device') {
wx.showToast({ title: '已确认,请先在称上打开分拣工作台', icon: 'none' });
} else if (printed !== 'cancelled' && printed !== 'busy') {
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);
},
pickPrintCodes() {
const pickCodes = (this.data.activePickCodes || []).filter(Boolean);
const fallback = this.data.activePickCode;
return pickCodes.length ? pickCodes : fallback ? [fallback] : [];
},
choosePrintDevice(devices) {
const list = (devices || []).slice(0, 6);
if (!list.length) return Promise.resolve({ empty: true });
if (list.length === 1) return Promise.resolve({ device: list[0] });
return new Promise((resolve) => {
wx.showActionSheet({
itemList: list.map((row) => String(row.display_name || row.device_id || '秤')),
success: (res) => resolve({ device: list[res.tapIndex] || null }),
fail: () => resolve({ cancelled: true }),
});
});
},
async printPickLabels(opts = {}) {
if (this.data.printing) return 'busy';
if (this.data.saving && !opts.ignoreSaving) return 'busy';
const pickCode = String(opts.pickCode || '').trim();
const itemId = String(opts.itemId || '').trim();
if (!pickCode) {
wx.showToast({ title: '请先选择拣货范围', icon: 'none' });
return 'need_pick';
}
if (opts.requireConfirmed) {
const row = (this.data.itemsMap[pickCode] || []).find((item) => String(item.id) === itemId);
if (row && isItemPending(row)) {
wx.showToast({ title: '请先确认分拣', icon: 'none' });
return 'need_confirm';
}
}
this.setData({ printing: true });
try {
const mineRes = await fetchPickingWeighDevices({ mine: true });
const mine = mineRes.data || [];
let deviceId = '';
if (mine.length === 1) {
deviceId = mine[0].device_id;
} else {
const poolRes =
mine.length > 1 ? { data: mine } : await fetchPickingWeighDevices({ online: true });
const chosen = await this.choosePrintDevice(poolRes.data || []);
if (chosen.empty) {
wx.showToast({ title: '请先在称上打开分拣工作台', icon: 'none' });
return 'no_device';
}
if (chosen.cancelled || !chosen.device) return 'cancelled';
deviceId = chosen.device.device_id;
}
const result = await createPickingPrintJobs({
pick_code: pickCode,
device_id: deviceId || undefined,
picking_item_id: itemId || undefined,
});
const created = (result.data && result.data.jobs && result.data.jobs.length) || 0;
const skipped = (result.data && result.data.skipped && result.data.skipped.length) || 0;
if (!opts.quietToast) {
const title = skipped > 0 ? `已下发 ${created} 张,跳过 ${skipped} 行` : `已下发 ${created} 张`;
wx.showToast({ title, icon: created ? 'success' : 'none' });
}
return created ? 'printed' : 'empty_jobs';
} catch (err) {
wx.showToast({ title: err.message || '下发打印失败', icon: 'none' });
return 'error';
} finally {
this.setData({ printing: false });
}
},
async printCurrentPick(e) {
const pick = String((e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.pick) || '').trim();
const id = String((e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.id) || '').trim();
return this.printPickLabels({
pickCode: pick,
itemId: id,
requireConfirmed: true,
});
},
/** 兼容旧按钮名 */
submitAudit(e) {
return this.submitComplete(e);
},
},
});