const { fetchProcessingTasks, fetchStandaloneProcessingSkuOptions, createStandaloneProcessingTask, pickDemandSheetMaterial, startProcessingTask, completeProcessingWork, 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: { 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); 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', can_start_work: row.source_type === 'demand' ? Number(row.process_status) < 40 : 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; 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: [], 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; this.setData({ createForm: { ...this.data.createForm, selectedSku: selected, skuSearch: selected.sku_name }, createSkuOptions: [], }); }, async submitCreate() { const { createForm } = this.data; 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 }); } }, 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' }); } }, }, });