1540 lines
54 KiB
JavaScript
1540 lines
54 KiB
JavaScript
const {
|
||
fetchProcessingTasks,
|
||
fetchStandaloneProcessingSkuOptions,
|
||
createStandaloneProcessingTask,
|
||
pickDemandSheetMaterial,
|
||
fetchDemandProcessingBom,
|
||
previewDemandFinishedOutput,
|
||
startProcessingTask,
|
||
completeProcessingWork,
|
||
completeStandaloneProcessingTask,
|
||
listStandaloneLines,
|
||
fetchStockInboundSkuOptions,
|
||
fetchStockInboundCategories,
|
||
createStockInboundCategory,
|
||
createStockInboundProduct,
|
||
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'];
|
||
|
||
/**
|
||
* 成品候选:只留展示需要的字段。
|
||
* 服务端 `listInboundSkuOptions` 每行还带 `backfill` 等大对象,整块 setData 会拖慢输入框(真机上表现为卡顿/丢字)。
|
||
*/
|
||
function toOutputSkuOption(row) {
|
||
const code = String((row && row.sku_code) || '').trim();
|
||
if (!code) return null;
|
||
return {
|
||
sku_code: code,
|
||
sku_name: String((row && row.sku_name) || code),
|
||
spec: row && row.spec ? String(row.spec) : '',
|
||
unit: row && row.unit ? String(row.unit) : '',
|
||
};
|
||
}
|
||
|
||
function matchesOutputSku(option, keyword) {
|
||
const kw = String(keyword || '').toLowerCase();
|
||
if (!kw) return true;
|
||
return (
|
||
String((option && option.sku_name) || '').toLowerCase().includes(kw) ||
|
||
String((option && option.sku_code) || '').toLowerCase().includes(kw)
|
||
);
|
||
}
|
||
|
||
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: [],
|
||
/** 成品:搜不到时的新建商品表单(复用库存入库同一个建品接口) */
|
||
showOutputProductModal: false,
|
||
outputProductForm: { name: '', categoryIndex: -1, spec: '', unit: '', origin: '' },
|
||
outputCategoryOptions: [],
|
||
/** 分类:就地新建(不弹滚轮选择器) */
|
||
outputCategoryCreating: false,
|
||
outputCategoryName: '',
|
||
creatingOutputCategory: false,
|
||
creatingOutputProduct: false,
|
||
/**
|
||
* ⚠️ 2026-10-23 复查结论:搜索框必须**受控**(wxml 绑定 `value="{{outputSkuSearch}}"`)。
|
||
* 之前为绕开 `undefined` 改成"非受控 + epoch 重建输入框",真机上表现为**输入什么都被清空**,
|
||
* 根因是重建/未绑定导致框架不回写输入值。现在 data 声明了 `outputSkuSearch`,
|
||
* 处理器用 `String((e && e.detail && e.detail.value) || '')` 兜底 ⇒ 不会再把 undefined 写进输入框。
|
||
*/
|
||
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: '',
|
||
pickHasBom: false,
|
||
pickBomMaterial: null,
|
||
pickBomLossRate: 0,
|
||
pickBomPickedMaterialQty: 0,
|
||
pickOutputQty: '',
|
||
pickOutputPreviewRows: [],
|
||
pickOutputPreviewLoading: false,
|
||
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() {
|
||
// 防呆:搜索关键字必须是字符串(历史上出现过数据层 undefined 被当成关键字搜出去)
|
||
if (typeof this.data.outputSkuSearch !== 'string') {
|
||
this.setData({ outputSkuSearch: '' });
|
||
}
|
||
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: '',
|
||
pickHasBom: false,
|
||
pickBomMaterial: null,
|
||
pickBomLossRate: 0,
|
||
pickBomPickedMaterialQty: 0,
|
||
pickOutputQty: '',
|
||
pickOutputPreviewRows: [],
|
||
pickOutputPreviewLoading: false,
|
||
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)}`,
|
||
pickHasBom: false,
|
||
pickBomMaterial: null,
|
||
pickBomLossRate: 0,
|
||
pickBomPickedMaterialQty: 0,
|
||
pickOutputQty: '',
|
||
pickOutputPreviewRows: [],
|
||
pickOutputPreviewLoading: false,
|
||
createSkuOptions: [],
|
||
createForm: {
|
||
skuSearch: '',
|
||
selectedSku: null,
|
||
qty: '',
|
||
processingMethod: '仓内加工',
|
||
processUnitPrice: '',
|
||
remark: '',
|
||
},
|
||
});
|
||
this.loadDemandBom(id, row);
|
||
},
|
||
|
||
/** 需求单领料:按 BOM 自动带出原材料,并预填剩余领料量/加工产出 */
|
||
async loadDemandBom(taskId, taskRow) {
|
||
try {
|
||
const res = await fetchDemandProcessingBom(taskId);
|
||
const bom = (res && res.data) || {};
|
||
if (!bom.has_bom) {
|
||
// 静默回退会让「接口没能带出 BOM」看起来像「界面没写」,留一行可排查日志
|
||
console.warn('[processing] 需求单无 BOM,回退手选原料', taskId, bom);
|
||
this.loadCreateSkuOptions();
|
||
return;
|
||
}
|
||
const materialSku = String(bom.materialSku || bom.material_sku || '').trim();
|
||
if (!materialSku) {
|
||
this.loadCreateSkuOptions();
|
||
return;
|
||
}
|
||
let selected = null;
|
||
try {
|
||
const optionsRes = await fetchStandaloneProcessingSkuOptions(materialSku, 20);
|
||
const options = (optionsRes && optionsRes.data) || [];
|
||
selected = options.find((opt) => opt.sku_code === materialSku) || null;
|
||
} catch (err) {
|
||
selected = null;
|
||
}
|
||
const materialName = String(
|
||
bom.materialName || bom.material_name || (selected && selected.sku_name) || materialSku
|
||
).trim();
|
||
const materialUnit = String(
|
||
bom.materialUnit || bom.material_unit || (selected && selected.unit) || ''
|
||
).trim();
|
||
const availableQty = Number(
|
||
selected && selected.available_qty != null ? selected.available_qty : bom.availableQty
|
||
) || 0;
|
||
if (!selected) {
|
||
selected = {
|
||
sku_code: materialSku,
|
||
sku_name: materialName,
|
||
unit: materialUnit,
|
||
available_qty: availableQty,
|
||
};
|
||
}
|
||
const demandQty = Number(bom.demand_qty);
|
||
const outputQty = Number.isFinite(demandQty) && demandQty > 0 ? demandQty : Number(taskRow?.source_qty) || 0;
|
||
const pickedMaterialQty = Number(bom.picked_material_qty) || 0;
|
||
const loss = Math.min(Math.max(Number(bom.lossRate ?? bom.loss_rate) || 0, 0), 0.95);
|
||
const expectedTotal = outputQty > 0 ? Math.max(1, Math.ceil(outputQty * (1 + loss) - 1e-9)) : 0;
|
||
const expectedPick = Math.max(0, expectedTotal - pickedMaterialQty);
|
||
this.setData({
|
||
pickHasBom: true,
|
||
pickBomMaterial: {
|
||
...selected,
|
||
display_unit: displayUnit(materialUnit),
|
||
sku_name: materialName,
|
||
},
|
||
pickBomLossRate: loss,
|
||
pickBomPickedMaterialQty: pickedMaterialQty,
|
||
pickOutputQty: outputQty > 0 ? String(outputQty) : '',
|
||
createSkuOptions: [],
|
||
createForm: {
|
||
...this.data.createForm,
|
||
selectedSku: {
|
||
...selected,
|
||
sku_name: materialName,
|
||
available_qty: availableQty,
|
||
},
|
||
skuSearch: materialName,
|
||
qty: expectedPick > 0 ? String(expectedPick) : '',
|
||
},
|
||
});
|
||
if (outputQty > 0) this.loadDemandOutputPreview(taskId, outputQty);
|
||
} catch (err) {
|
||
// BOM 读取失败时退回旧的手动选原料流程,不阻断领料
|
||
console.warn('[processing] 需求单 BOM 读取失败,回退手选原料', taskId, err);
|
||
this.loadCreateSkuOptions();
|
||
}
|
||
},
|
||
|
||
/** 加工产出变化后预演各客户分到的数量 */
|
||
async loadDemandOutputPreview(taskId, outputQty) {
|
||
const qty = Number(outputQty);
|
||
if (!Number.isFinite(qty) || qty <= 0) {
|
||
this.setData({ pickOutputPreviewRows: [], pickOutputPreviewLoading: false });
|
||
return;
|
||
}
|
||
const seq = (this._demandPreviewSeq || 0) + 1;
|
||
this._demandPreviewSeq = seq;
|
||
this.setData({ pickOutputPreviewLoading: true });
|
||
try {
|
||
const res = await previewDemandFinishedOutput(taskId, qty);
|
||
if (seq !== this._demandPreviewSeq) return;
|
||
const allocations = ((res && res.data && res.data.plan && res.data.plan.allocations) || []).map((row) => ({
|
||
orderItemId: String(row.orderItemId || ''),
|
||
orderCode: String(row.orderCode || ''),
|
||
customerName: String(row.customerName || ''),
|
||
demandQty: Number(row.demandQty) || 0,
|
||
qty: String(Number(row.allocatedQty) || 0),
|
||
}));
|
||
this.setData({ pickOutputPreviewRows: allocations, pickOutputPreviewLoading: false });
|
||
} catch (err) {
|
||
if (seq !== this._demandPreviewSeq) return;
|
||
this.setData({ pickOutputPreviewRows: [], pickOutputPreviewLoading: false });
|
||
wx.showToast({ title: err.message || '加载客户分配失败', icon: 'none' });
|
||
}
|
||
},
|
||
|
||
onDemandOutputInput(e) {
|
||
const value = String((e && e.detail && e.detail.value) || '');
|
||
// 产出一变,旧的客户分配立即作废,等新预览回来再显示
|
||
this.setData({ pickOutputQty: value, pickOutputPreviewRows: [] });
|
||
if (this._demandPreviewTimer) clearTimeout(this._demandPreviewTimer);
|
||
this._demandPreviewTimer = setTimeout(() => {
|
||
this.loadDemandOutputPreview(this.data.pickTaskId, value);
|
||
}, 250);
|
||
},
|
||
|
||
onDemandAllocationInput(e) {
|
||
const orderItemId = String(e.currentTarget.dataset.item || '');
|
||
const value = String((e && e.detail && e.detail.value) || '');
|
||
this.setData({
|
||
pickOutputPreviewRows: (this.data.pickOutputPreviewRows || []).map((row) =>
|
||
row.orderItemId === orderItemId ? { ...row, qty: value } : row
|
||
),
|
||
});
|
||
},
|
||
|
||
closeCreateForm() {
|
||
if (this._demandPreviewTimer) {
|
||
clearTimeout(this._demandPreviewTimer);
|
||
this._demandPreviewTimer = null;
|
||
}
|
||
this.setData({
|
||
showCreateModal: false,
|
||
pickTaskId: '',
|
||
pickDemandName: '',
|
||
pickDemandQtyText: '',
|
||
pickDemandInboundText: '',
|
||
pickDemandUnit: '',
|
||
pickHasBom: false,
|
||
pickBomMaterial: null,
|
||
pickBomLossRate: 0,
|
||
pickBomPickedMaterialQty: 0,
|
||
pickOutputQty: '',
|
||
pickOutputPreviewRows: [],
|
||
pickOutputPreviewLoading: false,
|
||
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;
|
||
}
|
||
// BOM 领料:同时填写产出并直接完工,按客户分配数量回写订单
|
||
let manualOutputAllocations = null;
|
||
let outputQty = 0;
|
||
if (this.data.pickTaskId && this.data.pickHasBom) {
|
||
outputQty = Number(this.data.pickOutputQty);
|
||
if (!Number.isFinite(outputQty) || outputQty <= 0) {
|
||
wx.showToast({ title: '请填写加工产出数量', icon: 'none' });
|
||
return;
|
||
}
|
||
const rows = this.data.pickOutputPreviewRows || [];
|
||
if (!rows.length) {
|
||
wx.showToast({ title: '客户分配还未加载完成', icon: 'none' });
|
||
return;
|
||
}
|
||
manualOutputAllocations = rows.map((row) => ({
|
||
order_item_id: row.orderItemId,
|
||
qty: Number(row.qty) || 0,
|
||
}));
|
||
const allocationSum = manualOutputAllocations.reduce((sum, row) => sum + row.qty, 0);
|
||
if (Math.abs(allocationSum - outputQty) > 0.0011) {
|
||
wx.showToast({ title: '客户分配合计必须等于加工产出', icon: 'none' });
|
||
return;
|
||
}
|
||
const gross = Number(this.data.pickBomPickedMaterialQty || 0) + qty;
|
||
if (outputQty > gross + 1e-9) {
|
||
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,
|
||
});
|
||
if (this.data.pickHasBom) {
|
||
const gross = Number(this.data.pickBomPickedMaterialQty || 0) + qty;
|
||
await completeProcessingWork({
|
||
task_id: this.data.pickTaskId,
|
||
gross_weight: gross,
|
||
net_weight: outputQty,
|
||
process_unit_price: processUnitPrice || 0,
|
||
process_fee: Math.round((processUnitPrice || 0) * outputQty * 100) / 100,
|
||
remark: String(createForm.remark || '').trim() || undefined,
|
||
manual_output_allocations: manualOutputAllocations,
|
||
});
|
||
wx.showToast({ title: '加工完成', icon: 'success' });
|
||
this.closeCreateForm();
|
||
this.applyTab('done');
|
||
return;
|
||
}
|
||
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: [],
|
||
});
|
||
this.recalcOutput();
|
||
// 与 Web 一致:打开弹窗就给出候选,不必先打字
|
||
this.loadOutputSkuOptions();
|
||
},
|
||
|
||
|
||
/** 一次性载入在售商品(本地过滤用;limit 走接口上限) */
|
||
async loadOutputSkuOptions() {
|
||
try {
|
||
const res = await fetchStockInboundSkuOptions({ limit: 50 });
|
||
const rows = res && Array.isArray(res.data) ? res.data : [];
|
||
const all = rows.map(toOutputSkuOption).filter(Boolean);
|
||
this.setData({ allOutputSkus: all, outputSkuOptions: all });
|
||
} 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()
|
||
);
|
||
},
|
||
|
||
/**
|
||
* 成品搜索输入(2026-10-23 重构)。
|
||
* 这里**只做一件事**:把用户敲的字原样写回输入框,然后刷新候选。
|
||
* ⚠️ 绝不能在这里(或任何搜索回调里)把「搜索结果」写回输入框——
|
||
* 历史 bug:搜不到时把空结果/异常值回填,导致输入内容被清空、框里出现字面量 `undefined`,
|
||
* 还被当成关键字又搜一次(Network 里可见 `search=undefined`)。
|
||
*/
|
||
onOutputSkuInput(e) {
|
||
const raw = e && e.detail ? e.detail.value : '';
|
||
const keyword = typeof raw === 'string' ? raw : '';
|
||
this.setData({ outputSkuSearch: keyword });
|
||
this.refreshOutputSkuOptions(keyword);
|
||
},
|
||
|
||
/** 候选:本地过滤优先(输入即时),本地没命中才回服务端搜全量(丢过期响应) */
|
||
refreshOutputSkuOptions(keyword) {
|
||
const text = typeof keyword === 'string' ? keyword : '';
|
||
const kw = text.trim().toLowerCase();
|
||
const all = this.data.allOutputSkus || [];
|
||
if (!kw) {
|
||
this.setData({ outputSkuOptions: all });
|
||
return;
|
||
}
|
||
const local = all.filter((o) => matchesOutputSku(o, kw));
|
||
if (local.length) {
|
||
this.setData({ outputSkuOptions: local });
|
||
return;
|
||
}
|
||
const seq = (this._outputSkuSeq || 0) + 1;
|
||
this._outputSkuSeq = seq;
|
||
fetchStockInboundSkuOptions({ search: text.trim(), limit: 20 })
|
||
.then((res) => {
|
||
if (seq !== this._outputSkuSeq) return;
|
||
const rows = res && Array.isArray(res.data) ? res.data : [];
|
||
this.setData({ outputSkuOptions: rows.map(toOutputSkuOption).filter(Boolean) });
|
||
})
|
||
.catch(() => {
|
||
if (seq !== this._outputSkuSeq) 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;
|
||
this.appendOutputRow(opt);
|
||
// 选中后清空关键字、恢复全量候选(与 Web 一致)
|
||
this.setData({ outputSkuSearch: '', outputSkuOptions: this.data.allOutputSkus || [] });
|
||
},
|
||
|
||
/** 加一行成品(两个报告继承默认勾选;同 SKU 不重复加) */
|
||
appendOutputRow(opt) {
|
||
const code = String((opt && opt.sku_code) || '');
|
||
if (!code) return;
|
||
if ((this.data.outputRows || []).some((r) => r.sku_code === code)) return;
|
||
this.setData(
|
||
{
|
||
outputRows: [
|
||
...this.data.outputRows,
|
||
{
|
||
sku_code: code,
|
||
sku_name: String((opt && opt.sku_name) || code),
|
||
qty: '',
|
||
unit_cost: '',
|
||
unit_cost_manual: false,
|
||
inherit_batch_report: true,
|
||
inherit_inspection_report: true,
|
||
},
|
||
],
|
||
},
|
||
() => this.recalcOutput()
|
||
);
|
||
},
|
||
|
||
/** 搜不到 → 用当前搜索词新建商品(与 Web「搜不到就用该名称新建」同口径) */
|
||
async openOutputProductForm() {
|
||
const name = String(this.data.outputSkuSearch || '').trim();
|
||
this.setData({
|
||
showOutputProductModal: true,
|
||
outputProductForm: { name, categoryIndex: -1, spec: '', unit: '', origin: '' },
|
||
outputCategoryCreating: false,
|
||
outputCategoryName: '',
|
||
});
|
||
if (!(this.data.outputCategoryOptions || []).length) await this.loadOutputCategoryOptions();
|
||
},
|
||
|
||
async loadOutputCategoryOptions() {
|
||
try {
|
||
const res = await fetchStockInboundCategories();
|
||
const rows = (res && (res.data || res)) || [];
|
||
const options = (Array.isArray(rows) ? rows : [])
|
||
.map((row) => ({
|
||
code: String((row && row.category_code) || ''),
|
||
label: String((row && (row.category_name || row.label)) || (row && row.category_code) || ''),
|
||
}))
|
||
.filter((o) => o.code);
|
||
this.setData({ outputCategoryOptions: options });
|
||
} catch (err) {
|
||
this.setData({ outputCategoryOptions: [] });
|
||
}
|
||
},
|
||
|
||
onOutputProductField(e) {
|
||
const field = e.currentTarget.dataset.field;
|
||
if (!field) return;
|
||
this.setData({ [`outputProductForm.${field}`]: e.detail.value });
|
||
},
|
||
|
||
/** 分类:点标签选(内联,不弹滚轮选择器) */
|
||
pickOutputCategory(e) {
|
||
const index = Number(e.currentTarget.dataset.index);
|
||
if (!Number.isInteger(index) || index < 0) return;
|
||
this.setData({ 'outputProductForm.categoryIndex': index });
|
||
},
|
||
|
||
toggleOutputCategoryCreate() {
|
||
this.setData({
|
||
outputCategoryCreating: !this.data.outputCategoryCreating,
|
||
outputCategoryName: '',
|
||
});
|
||
},
|
||
|
||
cancelOutputCategoryCreate() {
|
||
if (this.data.creatingOutputCategory) return;
|
||
this.setData({ outputCategoryCreating: false, outputCategoryName: '' });
|
||
},
|
||
|
||
onOutputCategoryNameInput(e) {
|
||
const raw = e && e.detail ? e.detail.value : '';
|
||
this.setData({ outputCategoryName: typeof raw === 'string' ? raw : '' });
|
||
},
|
||
|
||
/** 新建分类(与库存入库同一个接口):建完直接选中,不关表单 */
|
||
async submitOutputCategory() {
|
||
if (this.data.creatingOutputCategory) return;
|
||
const name = String(this.data.outputCategoryName || '').trim();
|
||
if (!name) {
|
||
wx.showToast({ title: '请填写分类名', icon: 'none' });
|
||
return;
|
||
}
|
||
this.setData({ creatingOutputCategory: true });
|
||
try {
|
||
const res = await createStockInboundCategory(name);
|
||
const row = (res && (res.data || res)) || {};
|
||
const code = String(row.category_code || '');
|
||
const label = String(row.category_name || row.label || name);
|
||
if (!code) {
|
||
wx.showToast({ title: '新建分类失败', icon: 'none' });
|
||
return;
|
||
}
|
||
const options = (this.data.outputCategoryOptions || []).slice();
|
||
const existed = options.findIndex((o) => o.code === code);
|
||
if (existed >= 0) options[existed] = { code, label };
|
||
else options.push({ code, label });
|
||
const index = options.findIndex((o) => o.code === code);
|
||
this.setData({
|
||
outputCategoryOptions: options,
|
||
'outputProductForm.categoryIndex': index,
|
||
outputCategoryCreating: false,
|
||
outputCategoryName: '',
|
||
});
|
||
} catch (err) {
|
||
wx.showToast({ title: err.message || '新建分类失败', icon: 'none' });
|
||
} finally {
|
||
this.setData({ creatingOutputCategory: false });
|
||
}
|
||
},
|
||
|
||
closeOutputProductForm() {
|
||
if (this.data.creatingOutputProduct || this.data.creatingOutputCategory) return;
|
||
this.setData({
|
||
showOutputProductModal: false,
|
||
outputCategoryCreating: false,
|
||
outputCategoryName: '',
|
||
});
|
||
},
|
||
|
||
async submitOutputProduct() {
|
||
if (this.data.creatingOutputProduct) return;
|
||
const form = this.data.outputProductForm || {};
|
||
const name = String(form.name || '').trim();
|
||
if (!name) {
|
||
wx.showToast({ title: '请填写商品名', icon: 'none' });
|
||
return;
|
||
}
|
||
// 分类必填:没选(-1)就拦下来,不默认取第一个
|
||
const catIndex = Number(form.categoryIndex);
|
||
const cat =
|
||
Number.isInteger(catIndex) && catIndex >= 0
|
||
? (this.data.outputCategoryOptions || [])[catIndex]
|
||
: null;
|
||
if (!cat || !cat.code) {
|
||
wx.showToast({ title: '请选择分类', icon: 'none' });
|
||
return;
|
||
}
|
||
this.setData({ creatingOutputProduct: true });
|
||
try {
|
||
const res = await createStockInboundProduct({
|
||
name,
|
||
parent_code: cat.code,
|
||
spec: String(form.spec || '').trim() || undefined,
|
||
unit: String(form.unit || '').trim() || undefined,
|
||
origin: String(form.origin || '').trim() || undefined,
|
||
});
|
||
const data = (res && (res.data || res)) || {};
|
||
const code = String(data.skuCode || data.sku_code || '');
|
||
if (!code) {
|
||
wx.showToast({ title: '新建商品失败', icon: 'none' });
|
||
return;
|
||
}
|
||
this.setData({ showOutputProductModal: false, outputSkuSearch: '' });
|
||
this.appendOutputRow({
|
||
sku_code: code,
|
||
sku_name: String(data.name || data.sku_name || name),
|
||
unit: String(form.unit || ''),
|
||
});
|
||
this.loadOutputSkuOptions();
|
||
wx.showToast({ title: '商品已创建并加入', icon: 'success' });
|
||
} catch (err) {
|
||
wx.showToast({ title: err.message || '新建商品失败', icon: 'none' });
|
||
} finally {
|
||
this.setData({ creatingOutputProduct: false });
|
||
}
|
||
},
|
||
|
||
closeOutputForm() {
|
||
this.setData({
|
||
showOutputModal: false,
|
||
showOutputProductModal: false,
|
||
outputTaskId: '',
|
||
outputTaskCode: '',
|
||
outputRows: [],
|
||
outputLoss: '',
|
||
outputLossManual: false,
|
||
outputSkuSearch: '',
|
||
outputSkuOptions: [],
|
||
allOutputSkus: [],
|
||
});
|
||
},
|
||
|
||
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_manual ? Number(r.unit_cost) : null,
|
||
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' });
|
||
}
|
||
},
|
||
},
|
||
});
|