- 搜索框改为非受控(不再绑定 value),框架无从把异常值写回 - 打开、选中、关闭三处改变 outputSearchEpochList 重建输入框以清空 - 契约测试钉住:把 value 绑定加回去立即变红
1137 lines
38 KiB
JavaScript
1137 lines
38 KiB
JavaScript
const {
|
|
fetchProcessingTasks,
|
|
fetchStandaloneProcessingSkuOptions,
|
|
createStandaloneProcessingTask,
|
|
pickDemandSheetMaterial,
|
|
startProcessingTask,
|
|
completeProcessingWork,
|
|
completeStandaloneProcessingTask,
|
|
listStandaloneLines,
|
|
fetchStockInboundSkuOptions,
|
|
uploadProcessingInspectPhoto,
|
|
submitProcessingInspection,
|
|
} = require('../../utils/request');
|
|
const { ensureMobileRole } = require('../../utils/roleGuard');
|
|
const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate');
|
|
const { prepareOrderImageBase64 } = require('../../utils/orderImage');
|
|
|
|
const WAREHOUSE_ROLES = ['warehouse', 'inspector'];
|
|
|
|
function formatLocalDate(date = new Date()) {
|
|
const y = date.getFullYear();
|
|
const m = String(date.getMonth() + 1).padStart(2, '0');
|
|
const d = String(date.getDate()).padStart(2, '0');
|
|
return `${y}-${m}-${d}`;
|
|
}
|
|
|
|
function shiftLocalDate(days) {
|
|
const date = new Date();
|
|
date.setDate(date.getDate() + days);
|
|
return formatLocalDate(date);
|
|
}
|
|
|
|
function formatDeliveryDate(value) {
|
|
if (!value) return '';
|
|
const text = String(value);
|
|
return text.length >= 10 ? text.slice(0, 10) : text;
|
|
}
|
|
|
|
const RESULT_OPTIONS = ['合格', '不合格'];
|
|
const RESULT_PASS = '合格';
|
|
const RESULT_FAIL = '不合格';
|
|
|
|
function formatResultLabel(rating) {
|
|
const raw = String(rating || '').trim();
|
|
if (!raw) return RESULT_PASS;
|
|
if (raw === '不合格' || raw.toUpperCase() === 'D') return '不合格';
|
|
if (['A', 'B', 'C'].includes(raw.toUpperCase())) return '合格';
|
|
return raw;
|
|
}
|
|
|
|
const STATUS_TEXT = {
|
|
10: '待加工',
|
|
20: '加工中',
|
|
30: '待加工验收',
|
|
40: '已完成',
|
|
50: '不合格',
|
|
};
|
|
|
|
function displayUnitPrice(row) {
|
|
const saved = Number(row?.process_unit_price);
|
|
if (Number.isFinite(saved) && saved > 0) return saved;
|
|
const fee = Number(row?.process_fee);
|
|
const net = Number(row?.net_weight);
|
|
if (Number.isFinite(fee) && fee > 0 && Number.isFinite(net) && net > 0) {
|
|
return Math.round((fee / net) * 100) / 100;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
function formatMoney(value) {
|
|
const num = Number(value);
|
|
if (!Number.isFinite(num)) return '0.00';
|
|
return num.toFixed(2);
|
|
}
|
|
|
|
function formatQty(value) {
|
|
const num = Number(value);
|
|
if (!Number.isFinite(num)) return '0';
|
|
const rounded = Math.round(num * 100) / 100;
|
|
return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(2);
|
|
}
|
|
|
|
/** 展示计量单位:纯「斤/个」照常;「4.80元/斤」只留斤;「12头」这类规格不展示 */
|
|
function displayUnit(unit) {
|
|
const raw = String(unit || '').trim();
|
|
if (!raw) return '';
|
|
if (!/\d|\//.test(raw) && !raw.includes('元')) return raw;
|
|
if (/[\/元]/.test(raw)) {
|
|
const last = raw.split('/').pop() || '';
|
|
const cleaned = last.replace(/^[\d.]+/, '').replace(/^元/, '').trim();
|
|
if (!cleaned || /\d/.test(cleaned)) return '';
|
|
return cleaned;
|
|
}
|
|
return '';
|
|
}
|
|
|
|
function formatLossQty(gross, net) {
|
|
const g = Number(gross);
|
|
const n = Number(net);
|
|
if (!Number.isFinite(g) && !Number.isFinite(n)) return '';
|
|
return formatQty(Math.max(0, (Number.isFinite(g) ? g : 0) - (Number.isFinite(n) ? n : 0)));
|
|
}
|
|
|
|
function rowLossText(row) {
|
|
const g = Number(row?.gross_weight);
|
|
const n = Number(row?.net_weight);
|
|
if (Number.isFinite(g) && Number.isFinite(n)) return formatLossQty(g, n);
|
|
const stored = Number(row?.loss_qty);
|
|
if (Number.isFinite(stored) && stored > 0) return formatQty(stored);
|
|
return '';
|
|
}
|
|
|
|
function mapQtyByUnit(rows) {
|
|
return (rows || [])
|
|
.map((row) => {
|
|
const unit = String(row.unit || '个').trim() || '个';
|
|
const total = Number(row.total) || 0;
|
|
return {
|
|
unit,
|
|
total,
|
|
text: `${formatQty(total)} ${unit}`,
|
|
};
|
|
})
|
|
.filter((row) => row.total > 0);
|
|
}
|
|
|
|
function isSameLocalDay(value) {
|
|
if (!value) return false;
|
|
const date = value instanceof Date ? value : new Date(value);
|
|
if (Number.isNaN(date.getTime())) return false;
|
|
return formatLocalDate(date) === formatLocalDate();
|
|
}
|
|
|
|
function aggregateQtyByUnitFromRows(rows, tab) {
|
|
const map = new Map();
|
|
for (const row of rows || []) {
|
|
const qty = Number(row.net_weight) || Number(row.source_qty) || 0;
|
|
if (qty <= 0) continue;
|
|
|
|
const status = Number(row.process_status) || 0;
|
|
let include = false;
|
|
if (row.completed_at) {
|
|
include = isSameLocalDay(row.completed_at);
|
|
} else if (tab === 'inspect' && status === 30) {
|
|
include = true;
|
|
} else if (tab === 'done' && status >= 40) {
|
|
include = isSameLocalDay(row.processing_inspection_time || row.updated_at);
|
|
}
|
|
|
|
if (!include) continue;
|
|
|
|
const unit = String(row.unit || '个').trim() || '个';
|
|
map.set(unit, (map.get(unit) || 0) + qty);
|
|
}
|
|
return mapQtyByUnit(Array.from(map, ([unit, total]) => ({ unit, total })));
|
|
}
|
|
|
|
function resolveDefaultGrossWeight(row) {
|
|
const saved = Number(row?.gross_weight);
|
|
if (Number.isFinite(saved) && saved > 0) return formatQty(saved);
|
|
const last = Number(row?.last_gross_weight);
|
|
if (Number.isFinite(last) && last > 0) return formatQty(last);
|
|
const sourceQty = Number(row?.source_qty);
|
|
if (Number.isFinite(sourceQty) && sourceQty > 0) return formatQty(sourceQty);
|
|
return '';
|
|
}
|
|
|
|
function resolveDefaultNetWeight(row) {
|
|
const saved = Number(row?.net_weight);
|
|
if (Number.isFinite(saved) && saved > 0) return formatQty(saved);
|
|
const last = Number(row?.last_net_weight);
|
|
if (Number.isFinite(last) && last > 0) return formatQty(last);
|
|
return '';
|
|
}
|
|
|
|
function resolveTodayProcessItemCount(result, rows, tab) {
|
|
const fromApi = Number(result.today_process_item_count);
|
|
if (result.today_process_item_count != null && Number.isFinite(fromApi) && fromApi >= 0) {
|
|
return fromApi;
|
|
}
|
|
const byUnit = result.today_process_qty_by_unit;
|
|
if (!Array.isArray(byUnit) || byUnit.length === 0) {
|
|
const legacyTotal = Number(result.today_process_qty_total ?? result.today_process_total);
|
|
if (Number.isFinite(legacyTotal) && legacyTotal >= 0) return legacyTotal;
|
|
}
|
|
return aggregateQtyByUnitFromRows(rows, tab).length;
|
|
}
|
|
|
|
Component({
|
|
options: { addGlobalClass: true },
|
|
|
|
properties: {
|
|
embedded: { type: Boolean, value: false },
|
|
homeTabFilter: { type: String, value: 'work' },
|
|
},
|
|
|
|
data: {
|
|
/** 独立加工:多行原料(与录单/Web 同口径) */
|
|
createMaterials: [],
|
|
/** 独立加工:成品申报(多行成品 + 损耗 + 报告继承) */
|
|
showOutputModal: false,
|
|
outputTaskId: '',
|
|
outputTaskCode: '',
|
|
outputUnit: '',
|
|
outputMaterialQty: 0,
|
|
outputMaterialCost: 0,
|
|
outputRows: [],
|
|
outputLoss: '',
|
|
outputLossManual: false,
|
|
outputAutoLoss: 0,
|
|
outputAutoUnitCost: 0,
|
|
/** 成品搜索:必须在 data 里声明,否则 setData 写不进数据层,
|
|
* 输入框会把 undefined 渲染成字面量并把每次输入刷回 undefined(表现为打字没反应) */
|
|
outputSkuSearch: '',
|
|
outputSkuOptions: [],
|
|
/** 打开弹窗时一次性载入的在售商品(与 Web 同交互:输入本地即时过滤) */
|
|
allOutputSkus: [],
|
|
/**
|
|
* 搜索框的重建计数:输入框**不绑定 value**(否则数据层一旦出现异常值,框架会把它写回输入框,
|
|
* 又被 bindinput 当成关键字提交——实测出现过 `search=undefined` 的请求)。
|
|
* 需要清空时改变这个数组元素,让输入框重新创建。
|
|
*/
|
|
outputSearchEpochList: [0],
|
|
activeTab: 'work',
|
|
viewMode: 'today',
|
|
dateField: 'created_at',
|
|
deliveryDate: '',
|
|
rangeFrom: '',
|
|
rangeTo: '',
|
|
rangeLabel: '',
|
|
periodSummary: '',
|
|
statsPeriodLabel: '今日',
|
|
rows: [],
|
|
loading: false,
|
|
saving: false,
|
|
error: '',
|
|
todayProcessFeeTotal: 0,
|
|
todayProcessFeeText: '0.00',
|
|
todayProcessItemCount: 0,
|
|
photoInspectionEnabled: false,
|
|
grades: RESULT_OPTIONS,
|
|
showWorkModal: false,
|
|
showCreateModal: false,
|
|
pickTaskId: '',
|
|
pickDemandName: '',
|
|
pickDemandQtyText: '',
|
|
pickDemandInboundText: '',
|
|
pickDemandUnit: '',
|
|
pickRequestId: '',
|
|
createSkuOptions: [],
|
|
createForm: {
|
|
skuSearch: '',
|
|
selectedSku: null,
|
|
qty: '',
|
|
processingMethod: '',
|
|
processUnitPrice: '',
|
|
remark: '',
|
|
},
|
|
workTaskId: '',
|
|
workTaskStatus: 10,
|
|
workUnit: '',
|
|
workForm: {
|
|
grossWeight: '',
|
|
netWeight: '',
|
|
processUnitPrice: '',
|
|
remark: '',
|
|
},
|
|
workLossText: '0',
|
|
},
|
|
|
|
observers: {
|
|
homeTabFilter(next) {
|
|
if (!this.properties.embedded) return;
|
|
const tab = this.normalizeHomeTab(next);
|
|
if (tab === this.data.activeTab) return;
|
|
this.setData({ activeTab: tab }, () => {
|
|
if (this._panelReady) this.loadRows();
|
|
});
|
|
},
|
|
},
|
|
|
|
lifetimes: {
|
|
attached() {
|
|
this.onPanelShow();
|
|
},
|
|
},
|
|
|
|
pageLifetimes: {
|
|
show() {
|
|
this.onPanelShow();
|
|
},
|
|
},
|
|
|
|
methods: {
|
|
normalizeHomeTab(raw) {
|
|
const tab = String(raw || 'work');
|
|
if (tab === 'inspect' || tab === 'done' || tab === 'work') return tab;
|
|
return 'work';
|
|
},
|
|
|
|
applyTab(tab) {
|
|
this.setData({ activeTab: tab }, () => this.loadRows());
|
|
if (this.properties.embedded) {
|
|
this.triggerEvent('tabchange', { tab });
|
|
}
|
|
},
|
|
|
|
async onPanelShow() {
|
|
if (!beginPanelShow(this)) return;
|
|
try {
|
|
const ok = await ensureMobileRole(WAREHOUSE_ROLES);
|
|
if (!ok) return;
|
|
if (this.properties.embedded) {
|
|
const tab = this.normalizeHomeTab(this.properties.homeTabFilter);
|
|
if (tab !== this.data.activeTab) {
|
|
this.setData({ activeTab: tab });
|
|
}
|
|
}
|
|
if (!this.data.deliveryDate) {
|
|
this.setData({ deliveryDate: formatLocalDate() });
|
|
}
|
|
this.updatePeriodSummary();
|
|
await this.loadRows();
|
|
this._panelReady = true;
|
|
} finally {
|
|
endPanelShow(this);
|
|
}
|
|
},
|
|
|
|
dateFieldLabel() {
|
|
return this.data.dateField === 'created_at' ? '下单日' : '配送日';
|
|
},
|
|
|
|
initWeekRange() {
|
|
const rangeFrom = shiftLocalDate(-6);
|
|
const rangeTo = formatLocalDate();
|
|
this.setData({
|
|
rangeFrom,
|
|
rangeTo,
|
|
rangeLabel: `${rangeFrom} 至 ${rangeTo}`,
|
|
});
|
|
},
|
|
|
|
buildRequestParams() {
|
|
const { activeTab, viewMode, deliveryDate, rangeFrom, rangeTo, dateField } = this.data;
|
|
const params = { tab: activeTab, date_field: dateField || 'created_at' };
|
|
if (viewMode === 'today') {
|
|
params.delivery_date = formatLocalDate();
|
|
return params;
|
|
}
|
|
if (viewMode === 'date') {
|
|
params.delivery_date = deliveryDate || formatLocalDate();
|
|
return params;
|
|
}
|
|
params.date_from = rangeFrom || shiftLocalDate(-6);
|
|
params.date_to = rangeTo || formatLocalDate();
|
|
return params;
|
|
},
|
|
|
|
updatePeriodSummary() {
|
|
const { viewMode, deliveryDate, rangeLabel } = this.data;
|
|
const axis = this.dateFieldLabel();
|
|
if (viewMode === 'today') {
|
|
const today = formatLocalDate();
|
|
this.setData({
|
|
periodSummary: `${axis} ${today}`,
|
|
statsPeriodLabel: '今日',
|
|
});
|
|
return;
|
|
}
|
|
if (viewMode === 'date') {
|
|
const day = deliveryDate || formatLocalDate();
|
|
this.setData({
|
|
periodSummary: `${axis} ${day}`,
|
|
statsPeriodLabel: day,
|
|
});
|
|
return;
|
|
}
|
|
this.setData({
|
|
periodSummary: rangeLabel ? `${axis} ${rangeLabel}` : '',
|
|
statsPeriodLabel: '近七天',
|
|
});
|
|
},
|
|
|
|
setDateField(e) {
|
|
const field = e.currentTarget.dataset.field;
|
|
if (!field || field === this.data.dateField) return;
|
|
this.setData({ dateField: field }, () => {
|
|
this.updatePeriodSummary();
|
|
this.loadRows();
|
|
});
|
|
},
|
|
|
|
showWeekRange() {
|
|
const rangeFrom = shiftLocalDate(-6);
|
|
const rangeTo = formatLocalDate();
|
|
this.setData(
|
|
{
|
|
viewMode: 'week',
|
|
rangeFrom,
|
|
rangeTo,
|
|
rangeLabel: `${rangeFrom} 至 ${rangeTo}`,
|
|
},
|
|
() => {
|
|
this.updatePeriodSummary();
|
|
this.loadRows();
|
|
}
|
|
);
|
|
},
|
|
|
|
showToday() {
|
|
this.setData({ viewMode: 'today' }, () => {
|
|
this.updatePeriodSummary();
|
|
this.loadRows();
|
|
});
|
|
},
|
|
|
|
onDeliveryDateChange(e) {
|
|
this.setData({ viewMode: 'date', deliveryDate: e.detail.value }, () => {
|
|
this.updatePeriodSummary();
|
|
this.loadRows();
|
|
});
|
|
},
|
|
|
|
switchTab(e) {
|
|
const tab = e.currentTarget.dataset.tab;
|
|
this.setData({ activeTab: tab }, () => this.loadRows());
|
|
},
|
|
|
|
async loadRows() {
|
|
this.setData({ loading: true, error: '' });
|
|
try {
|
|
const result = await fetchProcessingTasks(this.buildRequestParams());
|
|
const rows = (result.data || []).map((row) => {
|
|
const unitPrice = displayUnitPrice(row);
|
|
const isStandalone = row.source_type === 'standalone';
|
|
return {
|
|
...row,
|
|
statusText: STATUS_TEXT[row.process_status] || '未知',
|
|
delivery_date_text: formatDeliveryDate(row.delivery_date),
|
|
inspection_completed: row.inspection_completed === true,
|
|
is_demand: row.source_type === 'demand',
|
|
is_standalone: isStandalone,
|
|
// 独立加工没有验收行(inspection_id 为 NULL,后端 start 允许直接开工),
|
|
// 不能再用 inspection_completed 拦「开始加工」——Web 端一直是这样判的。
|
|
can_start_work:
|
|
row.source_type === 'demand'
|
|
? Number(row.process_status) < 40
|
|
: (isStandalone || row.inspection_completed === true) &&
|
|
Number(row.process_status) <= 20,
|
|
input_grade: row.input_grade || RESULT_PASS,
|
|
result_label: formatResultLabel(row.quality_rating),
|
|
inspection_photo_count: Number(row.inspection_photo_count || 0),
|
|
photoRequired: row.requires_photo_inspection !== false,
|
|
display_unit_price: unitPrice > 0 ? unitPrice : null,
|
|
process_unit_price_input: unitPrice > 0 ? String(unitPrice) : '',
|
|
loss_qty_text: rowLossText(row),
|
|
display_unit: displayUnit(row.unit),
|
|
source_qty_text: formatQty(row.source_qty),
|
|
net_weight_text: formatQty(row.net_weight || 0),
|
|
};
|
|
});
|
|
const todayProcessItemCount = resolveTodayProcessItemCount(result, rows, this.data.activeTab);
|
|
this.setData({
|
|
rows,
|
|
todayProcessFeeTotal: Number(result.today_process_fee_total) || 0,
|
|
todayProcessFeeText: formatMoney(result.today_process_fee_total),
|
|
todayProcessItemCount,
|
|
photoInspectionEnabled: true,
|
|
statsPeriodLabel: this.data.statsPeriodLabel || '今日',
|
|
});
|
|
const badgeCount = Number(result.today_pending_count);
|
|
if (Number.isFinite(badgeCount)) {
|
|
this.triggerEvent('badgechange', { count: badgeCount });
|
|
} else {
|
|
this.triggerEvent('badgechange');
|
|
}
|
|
} catch (err) {
|
|
this.setData({
|
|
error: err.message || '加载失败',
|
|
rows: [],
|
|
todayProcessFeeTotal: 0,
|
|
todayProcessFeeText: '0.00',
|
|
todayProcessItemCount: 0,
|
|
});
|
|
} finally {
|
|
this.setData({ loading: false });
|
|
}
|
|
},
|
|
|
|
openWorkForm(e) {
|
|
const { id } = e.currentTarget.dataset;
|
|
const row = this.data.rows.find((item) => item.id === id);
|
|
if (!row) return;
|
|
/** 独立加工 ≠ 订单/需求单加工:独立加工完工是**申报成品**,其它仍是毛重/净重(保持原样) */
|
|
if (String(row.source_type || '') === 'standalone') {
|
|
this.openOutputForm(row);
|
|
return;
|
|
}
|
|
|
|
const unitPrice = displayUnitPrice(row);
|
|
const workForm = {
|
|
grossWeight: resolveDefaultGrossWeight(row),
|
|
netWeight: resolveDefaultNetWeight(row),
|
|
processUnitPrice: unitPrice > 0 ? String(unitPrice) : '',
|
|
remark: row.remark || '',
|
|
};
|
|
this.setData({
|
|
showWorkModal: true,
|
|
workTaskId: id,
|
|
workTaskStatus: Number(row.process_status) || 10,
|
|
workUnit: row.unit || '个',
|
|
workForm,
|
|
workLossText: formatLossQty(workForm.grossWeight, workForm.netWeight),
|
|
});
|
|
},
|
|
|
|
closeWorkForm() {
|
|
this.setData({ showWorkModal: false, workTaskId: '', workTaskStatus: 10, workUnit: '' });
|
|
},
|
|
|
|
openCreateForm() {
|
|
this.setData({
|
|
showCreateModal: true,
|
|
pickTaskId: '',
|
|
pickDemandName: '',
|
|
pickDemandQtyText: '',
|
|
pickDemandInboundText: '',
|
|
pickDemandUnit: '',
|
|
createSkuOptions: [],
|
|
createMaterials: [],
|
|
createForm: {
|
|
skuSearch: '',
|
|
selectedSku: null,
|
|
qty: '',
|
|
processingMethod: '',
|
|
processUnitPrice: '',
|
|
remark: '',
|
|
},
|
|
});
|
|
this.loadCreateSkuOptions();
|
|
},
|
|
|
|
openDemandPick(e) {
|
|
const id = e.currentTarget.dataset.id;
|
|
const row = this.data.rows.find((item) => item.id === id);
|
|
const unit = displayUnit(row?.unit);
|
|
const demandQty = formatQty(row?.source_qty);
|
|
const inboundQty = formatQty(row?.net_weight || 0);
|
|
this.setData({
|
|
showCreateModal: true,
|
|
pickTaskId: id,
|
|
pickDemandName: String(row?.item_name || row?.sku_name || row?.sku_code || '成品').trim(),
|
|
pickDemandQtyText: demandQty,
|
|
pickDemandInboundText: inboundQty,
|
|
pickDemandUnit: unit,
|
|
// 幂等键:本次领料会话内重试/双击复用同一键,服务端去重
|
|
pickRequestId: `pick-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,
|
|
createSkuOptions: [],
|
|
createForm: {
|
|
skuSearch: '',
|
|
selectedSku: null,
|
|
qty: '',
|
|
processingMethod: '仓内加工',
|
|
processUnitPrice: '',
|
|
remark: '',
|
|
},
|
|
});
|
|
this.loadCreateSkuOptions();
|
|
},
|
|
|
|
closeCreateForm() {
|
|
this.setData({
|
|
showCreateModal: false,
|
|
pickTaskId: '',
|
|
pickDemandName: '',
|
|
pickDemandQtyText: '',
|
|
pickDemandInboundText: '',
|
|
pickDemandUnit: '',
|
|
createSkuOptions: [],
|
|
});
|
|
},
|
|
|
|
stopCreateTap() {},
|
|
|
|
async loadCreateSkuOptions(search = '') {
|
|
try {
|
|
const res = await fetchStandaloneProcessingSkuOptions(search, 20);
|
|
this.setData({
|
|
createSkuOptions: (res.data || []).map((item) => ({
|
|
...item,
|
|
display_unit: displayUnit(item.unit),
|
|
})),
|
|
});
|
|
} catch (err) {
|
|
wx.showToast({ title: err.message || '加载可选商品失败', icon: 'none' });
|
|
}
|
|
},
|
|
|
|
onCreateInput(e) {
|
|
const field = e.currentTarget.dataset.field;
|
|
const value = e.detail.value || '';
|
|
this.setData({ createForm: { ...this.data.createForm, [field]: value } });
|
|
if (field === 'skuSearch' && value.trim()) {
|
|
this.loadCreateSkuOptions(value.trim());
|
|
}
|
|
},
|
|
|
|
selectCreateSku(e) {
|
|
const skuCode = e.currentTarget.dataset.sku;
|
|
const selected = this.data.createSkuOptions.find((opt) => opt.sku_code === skuCode);
|
|
if (!selected) return;
|
|
/** 独立加工:点一次就**加一行原料**(多行);需求单领料:仍按单选(保持原流程) */
|
|
if (!this.data.pickTaskId) {
|
|
const exists = this.data.createMaterials.some((row) => row.sku_code === selected.sku_code);
|
|
this.setData({
|
|
createSkuOptions: [],
|
|
createForm: { ...this.data.createForm, skuSearch: '' },
|
|
createMaterials: exists
|
|
? this.data.createMaterials
|
|
: [
|
|
...this.data.createMaterials,
|
|
{
|
|
sku_code: selected.sku_code,
|
|
sku_name: selected.sku_name,
|
|
unit: selected.unit || '',
|
|
display_unit: displayUnit(selected.unit),
|
|
available_qty: Number(selected.available_qty) || 0,
|
|
qty: '',
|
|
},
|
|
],
|
|
});
|
|
return;
|
|
}
|
|
this.setData({
|
|
createForm: { ...this.data.createForm, selectedSku: selected, skuSearch: selected.sku_name },
|
|
createSkuOptions: [],
|
|
});
|
|
},
|
|
|
|
/** 多行原料:改数量 / 删除 */
|
|
onCreateMaterialQty(e) {
|
|
const skuCode = e.currentTarget.dataset.sku;
|
|
const value = e.detail.value || '';
|
|
this.setData({
|
|
createMaterials: this.data.createMaterials.map((row) =>
|
|
row.sku_code === skuCode ? { ...row, qty: value } : row
|
|
),
|
|
});
|
|
},
|
|
|
|
removeCreateMaterial(e) {
|
|
const skuCode = e.currentTarget.dataset.sku;
|
|
this.setData({
|
|
createMaterials: this.data.createMaterials.filter((row) => row.sku_code !== skuCode),
|
|
});
|
|
},
|
|
|
|
async submitCreate() {
|
|
const { createForm } = this.data;
|
|
/** 独立加工:多行原料校验(需求单领料仍走下面的单选校验,一行不改) */
|
|
if (!this.data.pickTaskId) {
|
|
const rows = this.data.createMaterials || [];
|
|
if (!rows.length) {
|
|
wx.showToast({ title: '请选择原料商品', icon: 'none' });
|
|
return;
|
|
}
|
|
for (let i = 0; i < rows.length; i += 1) {
|
|
const qty = Number(rows[i].qty);
|
|
if (!Number.isFinite(qty) || qty <= 0) {
|
|
wx.showToast({ title: `第 ${i + 1} 行数量须大于 0`, icon: 'none' });
|
|
return;
|
|
}
|
|
if (qty > rows[i].available_qty + 1e-9) {
|
|
wx.showToast({ title: `第 ${i + 1} 行库存不足:可用 ${rows[i].available_qty}`, icon: 'none' });
|
|
return;
|
|
}
|
|
}
|
|
const method = String(createForm.processingMethod || '').trim();
|
|
if (!method) {
|
|
wx.showToast({ title: '请填写加工方式', icon: 'none' });
|
|
return;
|
|
}
|
|
const price = createForm.processUnitPrice === '' ? null : Number(createForm.processUnitPrice);
|
|
if (price != null && (!Number.isFinite(price) || price < 0)) {
|
|
wx.showToast({ title: '加工单价不能为负数', icon: 'none' });
|
|
return;
|
|
}
|
|
this.setData({ saving: true });
|
|
try {
|
|
await createStandaloneProcessingTask({
|
|
materials: rows.map((row) => ({ sku_code: row.sku_code, qty: Number(row.qty) })),
|
|
processing_method: method,
|
|
process_unit_price: price,
|
|
remark: String(createForm.remark || '').trim() || undefined,
|
|
client_request_no: `spg-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,
|
|
});
|
|
wx.showToast({ title: '创建成功', icon: 'success' });
|
|
this.closeCreateForm();
|
|
this.applyTab('work');
|
|
} catch (err) {
|
|
wx.showToast({ title: err.message || '创建失败', icon: 'none' });
|
|
} finally {
|
|
this.setData({ saving: false });
|
|
}
|
|
return;
|
|
}
|
|
if (!createForm.selectedSku) {
|
|
wx.showToast({ title: '请选择商品', icon: 'none' });
|
|
return;
|
|
}
|
|
const qty = Number(createForm.qty);
|
|
if (!Number.isFinite(qty) || qty <= 0) {
|
|
wx.showToast({ title: '请填写领料数量', icon: 'none' });
|
|
return;
|
|
}
|
|
const processingMethod = String(createForm.processingMethod || '').trim();
|
|
if (!this.data.pickTaskId && !processingMethod) {
|
|
wx.showToast({ title: '请填写加工方式', icon: 'none' });
|
|
return;
|
|
}
|
|
if (qty > createForm.selectedSku.available_qty + 1e-9) {
|
|
wx.showToast({ title: `库存不足:可用 ${createForm.selectedSku.available_qty}`, icon: 'none' });
|
|
return;
|
|
}
|
|
const processUnitPrice = createForm.processUnitPrice === '' ? null : Number(createForm.processUnitPrice);
|
|
if (processUnitPrice != null && (!Number.isFinite(processUnitPrice) || processUnitPrice < 0)) {
|
|
wx.showToast({ title: '加工单价不能为负数', icon: 'none' });
|
|
return;
|
|
}
|
|
this.setData({ saving: true });
|
|
try {
|
|
if (this.data.pickTaskId) {
|
|
await pickDemandSheetMaterial(this.data.pickTaskId, {
|
|
sku_code: createForm.selectedSku.sku_code,
|
|
qty,
|
|
process_unit_price: processUnitPrice,
|
|
remark: String(createForm.remark || '').trim() || undefined,
|
|
request_id: this.data.pickRequestId,
|
|
});
|
|
wx.showToast({ title: '领料成功', icon: 'success' });
|
|
} else {
|
|
await createStandaloneProcessingTask({
|
|
sku_code: createForm.selectedSku.sku_code,
|
|
qty,
|
|
processing_method: processingMethod,
|
|
process_unit_price: processUnitPrice,
|
|
remark: String(createForm.remark || '').trim() || undefined,
|
|
});
|
|
wx.showToast({ title: '创建成功', icon: 'success' });
|
|
}
|
|
this.closeCreateForm();
|
|
this.applyTab('work');
|
|
} catch (err) {
|
|
wx.showToast({ title: err.message || '创建失败', icon: 'none' });
|
|
} finally {
|
|
this.setData({ saving: false });
|
|
}
|
|
},
|
|
|
|
/** 独立加工完工:申报成品(多行)——默认带出原料行,操作员填产出数量 */
|
|
async openOutputForm(row) {
|
|
const unit = displayUnit(row.unit);
|
|
let materialQty = Number(row.source_qty) || 0;
|
|
let materialCost = Number(row.material_cost) || 0;
|
|
let outputs = [];
|
|
try {
|
|
const res = await listStandaloneLines(row.id);
|
|
const materials = (res && res.data && res.data.materials) || [];
|
|
if (materials.length) {
|
|
materialQty = materials.reduce((sum, m) => sum + (Number(m.qty) || 0), 0);
|
|
materialCost = materials.reduce((sum, m) => sum + (Number(m.material_cost) || 0), 0);
|
|
outputs = materials.map((m) => ({
|
|
sku_code: m.sku_code,
|
|
sku_name: m.sku_name || m.sku_code,
|
|
qty: '',
|
|
unit_cost: '',
|
|
unit_cost_manual: false,
|
|
// 默认继承原料的报告(开发者 2026-10-23:这两个开关默认勾选)
|
|
inherit_batch_report: true,
|
|
inherit_inspection_report: true,
|
|
}));
|
|
}
|
|
} catch (err) {
|
|
// 读不到行时退回单据头
|
|
}
|
|
if (!outputs.length) {
|
|
outputs = [
|
|
{
|
|
sku_code: row.sku_code,
|
|
sku_name: row.item_name || row.sku_name || row.sku_code,
|
|
qty: '',
|
|
unit_cost: '',
|
|
unit_cost_manual: false,
|
|
inherit_batch_report: true,
|
|
inherit_inspection_report: true,
|
|
},
|
|
];
|
|
}
|
|
this.setData({
|
|
showOutputModal: true,
|
|
outputTaskId: row.id,
|
|
outputTaskCode: String(row.task_code || ''),
|
|
outputUnit: unit,
|
|
outputMaterialQty: materialQty,
|
|
outputMaterialCost: materialCost,
|
|
outputRows: outputs,
|
|
outputLoss: '',
|
|
outputLossManual: false,
|
|
outputSkuSearch: '',
|
|
outputSkuOptions: [],
|
|
allOutputSkus: [],
|
|
outputSearchEpochList: this.nextOutputSearchEpochList(),
|
|
});
|
|
this.recalcOutput();
|
|
// 与 Web 一致:打开弹窗就给出候选,不必先打字
|
|
this.loadOutputSkuOptions();
|
|
},
|
|
|
|
/** 输入框重建计数(清空输入框用;见 data.outputSearchEpochList 注释) */
|
|
nextOutputSearchEpochList() {
|
|
const cur = this.data.outputSearchEpochList;
|
|
const epoch = Array.isArray(cur) && cur.length ? Number(cur[0]) || 0 : 0;
|
|
return [epoch + 1];
|
|
},
|
|
|
|
/** 一次性载入在售商品(本地过滤用;limit 走接口上限) */
|
|
async loadOutputSkuOptions() {
|
|
try {
|
|
const res = await fetchStockInboundSkuOptions({ limit: 50 });
|
|
const rows = res && Array.isArray(res.data) ? res.data : [];
|
|
this.setData({ allOutputSkus: rows, outputSkuOptions: rows });
|
|
} catch (err) {
|
|
this.setData({ allOutputSkus: [], outputSkuOptions: [] });
|
|
}
|
|
},
|
|
|
|
recalcOutput() {
|
|
const rows = this.data.outputRows || [];
|
|
const totalQty = rows.reduce((sum, r) => sum + (Number(r.qty) || 0), 0);
|
|
const autoLoss = Math.max(0, Math.round((this.data.outputMaterialQty - totalQty) * 1000) / 1000);
|
|
const autoUnit =
|
|
totalQty > 0 && this.data.outputMaterialCost > 0
|
|
? Math.round((this.data.outputMaterialCost / totalQty) * 10000) / 10000
|
|
: 0;
|
|
const nextRows = rows.map((r) => {
|
|
if (r.unit_cost_manual || !(Number(r.qty) > 0) || autoUnit <= 0) return r;
|
|
return { ...r, unit_cost: autoUnit.toFixed(2) };
|
|
});
|
|
this.setData({
|
|
outputRows: nextRows,
|
|
outputAutoLoss: autoLoss,
|
|
outputAutoUnitCost: autoUnit,
|
|
outputLoss: this.data.outputLossManual ? this.data.outputLoss : String(autoLoss),
|
|
});
|
|
},
|
|
|
|
onOutputQtyInput(e) {
|
|
const skuCode = e.currentTarget.dataset.sku;
|
|
const value = e.detail.value || '';
|
|
this.setData(
|
|
{ outputRows: this.data.outputRows.map((r) => (r.sku_code === skuCode ? { ...r, qty: value } : r)) },
|
|
() => this.recalcOutput()
|
|
);
|
|
},
|
|
|
|
onOutputCostInput(e) {
|
|
const skuCode = e.currentTarget.dataset.sku;
|
|
const value = e.detail.value || '';
|
|
this.setData({
|
|
outputRows: this.data.outputRows.map((r) =>
|
|
r.sku_code === skuCode ? { ...r, unit_cost: value, unit_cost_manual: true } : r
|
|
),
|
|
});
|
|
},
|
|
|
|
onOutputLossInput(e) {
|
|
this.setData({ outputLossManual: true, outputLoss: e.detail.value || '' });
|
|
},
|
|
|
|
resetOutputLossAuto() {
|
|
this.setData({ outputLossManual: false }, () => this.recalcOutput());
|
|
},
|
|
|
|
toggleOutputInherit(e) {
|
|
const skuCode = e.currentTarget.dataset.sku;
|
|
const field = e.currentTarget.dataset.field;
|
|
this.setData({
|
|
outputRows: this.data.outputRows.map((r) =>
|
|
r.sku_code === skuCode ? { ...r, [field]: !r[field] } : r
|
|
),
|
|
});
|
|
},
|
|
|
|
removeOutputRow(e) {
|
|
const skuCode = e.currentTarget.dataset.sku;
|
|
this.setData({ outputRows: this.data.outputRows.filter((r) => r.sku_code !== skuCode) }, () =>
|
|
this.recalcOutput()
|
|
);
|
|
},
|
|
|
|
async searchOutputSkus(e) {
|
|
const search = String((e && e.detail && e.detail.value) || '');
|
|
const keyword = search.trim().toLowerCase();
|
|
this.setData({ outputSkuSearch: search });
|
|
const all = this.data.allOutputSkus || [];
|
|
if (!keyword) {
|
|
this.setData({ outputSkuOptions: all });
|
|
return;
|
|
}
|
|
// 与 Web 同交互:先在已载入的商品里本地过滤(输入即时响应,不等网络)
|
|
const local = all.filter(
|
|
(o) =>
|
|
String(o.sku_name || '').toLowerCase().includes(keyword) ||
|
|
String(o.sku_code || '').toLowerCase().includes(keyword)
|
|
);
|
|
if (local.length) {
|
|
this.setData({ outputSkuOptions: local });
|
|
return;
|
|
}
|
|
// 已载入的那批里没有 ⇒ 回服务端搜全量(防商品多时漏掉)
|
|
const seq = (this._outputSkuSearchSeq || 0) + 1;
|
|
this._outputSkuSearchSeq = seq;
|
|
try {
|
|
const res = await fetchStockInboundSkuOptions({ search: search.trim(), limit: 50 });
|
|
if (seq !== this._outputSkuSearchSeq) return;
|
|
this.setData({ outputSkuOptions: res && Array.isArray(res.data) ? res.data : [] });
|
|
} catch (err) {
|
|
if (seq !== this._outputSkuSearchSeq) return;
|
|
this.setData({ outputSkuOptions: [] });
|
|
}
|
|
},
|
|
|
|
addOutputSku(e) {
|
|
const skuCode = e.currentTarget.dataset.sku;
|
|
const opt = (this.data.outputSkuOptions || []).find((o) => o.sku_code === skuCode);
|
|
if (!opt) return;
|
|
if (this.data.outputRows.some((r) => r.sku_code === skuCode)) {
|
|
this.setData({ outputSkuOptions: this.data.allOutputSkus || [], outputSkuSearch: '' });
|
|
return;
|
|
}
|
|
this.setData(
|
|
{
|
|
outputSkuOptions: this.data.allOutputSkus || [],
|
|
outputSkuSearch: '',
|
|
outputSearchEpochList: this.nextOutputSearchEpochList(),
|
|
outputRows: [
|
|
...this.data.outputRows,
|
|
{
|
|
sku_code: opt.sku_code,
|
|
sku_name: opt.sku_name,
|
|
qty: '',
|
|
unit_cost: '',
|
|
unit_cost_manual: false,
|
|
inherit_batch_report: true,
|
|
inherit_inspection_report: true,
|
|
},
|
|
],
|
|
},
|
|
() => this.recalcOutput()
|
|
);
|
|
},
|
|
|
|
closeOutputForm() {
|
|
this.setData({
|
|
showOutputModal: false,
|
|
outputTaskId: '',
|
|
outputTaskCode: '',
|
|
outputRows: [],
|
|
outputLoss: '',
|
|
outputLossManual: false,
|
|
outputSkuSearch: '',
|
|
outputSkuOptions: [],
|
|
allOutputSkus: [],
|
|
outputSearchEpochList: this.nextOutputSearchEpochList(),
|
|
});
|
|
},
|
|
|
|
async submitOutput() {
|
|
const { outputTaskId, outputRows, outputMaterialQty } = this.data;
|
|
if (!outputTaskId) return;
|
|
const rows = (outputRows || []).filter((r) => Number(r.qty) > 0);
|
|
if (!rows.length) {
|
|
wx.showToast({ title: '请至少填写一行成品数量', icon: 'none' });
|
|
return;
|
|
}
|
|
const totalOut = rows.reduce((sum, r) => sum + (Number(r.qty) || 0), 0);
|
|
if (totalOut > outputMaterialQty + 1e-6) {
|
|
wx.showToast({ title: `产出合计 ${totalOut} 不能大于原料投入 ${outputMaterialQty}`, icon: 'none' });
|
|
return;
|
|
}
|
|
this.setData({ saving: true });
|
|
try {
|
|
await completeStandaloneProcessingTask(outputTaskId, {
|
|
outputs: rows.map((r) => ({
|
|
sku_code: r.sku_code,
|
|
qty: Number(r.qty),
|
|
unit_cost: r.unit_cost === '' ? null : Number(r.unit_cost),
|
|
inherit_batch_report: r.inherit_batch_report === true,
|
|
inherit_inspection_report: r.inherit_inspection_report === true,
|
|
})),
|
|
loss_qty: this.data.outputLoss === '' ? null : Number(this.data.outputLoss),
|
|
});
|
|
wx.showToast({ title: '成品已入库', icon: 'success' });
|
|
this.closeOutputForm();
|
|
this.applyTab('inspect');
|
|
this.fetchData && this.fetchData();
|
|
} catch (err) {
|
|
wx.showToast({ title: err.message || '提交失败', icon: 'none' });
|
|
} finally {
|
|
this.setData({ saving: false });
|
|
}
|
|
},
|
|
|
|
onWorkInput(e) {
|
|
const field = e.currentTarget.dataset.field;
|
|
const nextForm = { ...this.data.workForm, [field]: e.detail.value };
|
|
this.setData({
|
|
workForm: nextForm,
|
|
workLossText: formatLossQty(nextForm.grossWeight, nextForm.netWeight),
|
|
});
|
|
},
|
|
|
|
async submitWork() {
|
|
const { workTaskId, workTaskStatus, workForm, workUnit } = this.data;
|
|
if (!workTaskId) return;
|
|
|
|
const grossWeight = Number(workForm.grossWeight);
|
|
const netWeight = Number(workForm.netWeight);
|
|
const processUnitPrice = Number(workForm.processUnitPrice);
|
|
|
|
if (!Number.isFinite(grossWeight) || grossWeight <= 0) {
|
|
wx.showToast({ title: '请填写毛重', icon: 'none' });
|
|
return;
|
|
}
|
|
if (!Number.isFinite(netWeight) || netWeight <= 0) {
|
|
wx.showToast({ title: '请填写净重', icon: 'none' });
|
|
return;
|
|
}
|
|
if (netWeight > grossWeight) {
|
|
wx.showToast({ title: '净重不能大于毛重', icon: 'none' });
|
|
return;
|
|
}
|
|
if (!Number.isFinite(processUnitPrice) || processUnitPrice < 0) {
|
|
wx.showToast({ title: '请填写加工单价', icon: 'none' });
|
|
return;
|
|
}
|
|
|
|
this.setData({ saving: true });
|
|
try {
|
|
if (workTaskStatus === 10) {
|
|
await startProcessingTask(workTaskId);
|
|
}
|
|
await completeProcessingWork({
|
|
task_id: workTaskId,
|
|
gross_weight: grossWeight,
|
|
net_weight: netWeight,
|
|
process_unit_price: processUnitPrice,
|
|
process_fee: Math.round(processUnitPrice * netWeight * 100) / 100,
|
|
remark: workForm.remark,
|
|
});
|
|
wx.showToast({ title: '加工完成', icon: 'success' });
|
|
this.closeWorkForm();
|
|
this.applyTab('inspect');
|
|
} catch (err) {
|
|
wx.showToast({ title: err.message || '提交失败', icon: 'none' });
|
|
} finally {
|
|
this.setData({ saving: false });
|
|
}
|
|
},
|
|
|
|
onGradeChange(e) {
|
|
const id = e.currentTarget.dataset.id;
|
|
const grade = this.data.grades[Number(e.detail.value)] || RESULT_PASS;
|
|
this.setData({
|
|
rows: this.data.rows.map((row) => (row.id === id ? { ...row, input_grade: grade } : row)),
|
|
});
|
|
},
|
|
|
|
choosePhoto(e) {
|
|
const id = e.currentTarget.dataset.id;
|
|
wx.chooseImage({
|
|
count: 3,
|
|
sizeType: ['original'],
|
|
sourceType: ['camera', 'album'],
|
|
success: async (res) => {
|
|
try {
|
|
for (const filePath of res.tempFilePaths || []) {
|
|
await this.uploadPhoto(id, filePath);
|
|
}
|
|
wx.showToast({ title: '照片已上传', icon: 'success' });
|
|
this.loadRows();
|
|
} catch (err) {
|
|
wx.showToast({ title: err.message || '上传失败', icon: 'none' });
|
|
}
|
|
},
|
|
});
|
|
},
|
|
|
|
async uploadPhoto(taskId, filePath) {
|
|
const content = await prepareOrderImageBase64(filePath);
|
|
await uploadProcessingInspectPhoto({ task_id: taskId, content, ext: 'jpg' });
|
|
},
|
|
|
|
async submitInspection(e) {
|
|
await this.completeProcessingInspect(e.currentTarget.dataset.id, false);
|
|
},
|
|
|
|
async rejectInspection(e) {
|
|
await this.completeProcessingInspect(e.currentTarget.dataset.id, true);
|
|
},
|
|
|
|
async completeProcessingInspect(id, rejectFulfillment) {
|
|
const row = this.data.rows.find((item) => item.id === id);
|
|
if (!row) return;
|
|
if (!rejectFulfillment && row.photoRequired && Number(row.inspection_photo_count || 0) <= 0) {
|
|
wx.showToast({ title: '请先拍照上传', icon: 'none' });
|
|
return;
|
|
}
|
|
try {
|
|
const result = await submitProcessingInspection({
|
|
task_id: id,
|
|
quality_rating: rejectFulfillment ? RESULT_FAIL : row.input_grade || RESULT_PASS,
|
|
reject_fulfillment: rejectFulfillment || undefined,
|
|
});
|
|
wx.showToast({
|
|
title: result.isRejected ? '已退回' : '加工验收完成',
|
|
icon: 'success',
|
|
});
|
|
this.applyTab('done');
|
|
} catch (err) {
|
|
wx.showToast({ title: err.message || '提交失败', icon: 'none' });
|
|
}
|
|
},
|
|
},
|
|
});
|