Files
SupplierSystem/miniprogram/components/picking-panel/index.js
T
Ubuntu deb3e72750
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
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

853 lines
28 KiB
JavaScript

const requestApi = require('../../utils/request');
const {
fetchPickingTasks,
fetchPickingWeighDevices,
createPickingPrintJobs,
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,
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;
}
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;
}
const PICKING_ROLES = ['picker', 'warehouse', 'delivery'];
Component({
options: { addGlobalClass: true },
properties: {
embedded: { type: Boolean, value: false },
hideProgress: { type: Boolean, value: false },
},
data: {
tasks: [],
itemsMap: {},
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;
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: visibleItemsForStatus(items, status),
taskSummary,
pendingCount,
scanTip: '',
workflowTip: '',
showWorkTitle: false,
showCompanyMeta: false,
showOrderCodesMeta: false,
});
this.emitProgress({
taskCount: (this.data.tasks || []).length,
pickedCount: Number(taskSummary && taskSummary.pickedCount) || 0,
pendingCount,
});
},
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);
},
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);
},
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 || '',
});
}
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(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(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 || '',
},
];
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);
},
},
});