From 63a268c0f6cca222c5f05475611fa626dd03e2d5 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Wed, 4 Nov 2026 13:03:56 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=8A=A0=E5=B7=A5):=20=E5=B0=8F=E7=A8=8B?= =?UTF-8?q?=E5=BA=8F=20BOM/=E5=88=86=E9=85=8D=E5=AF=B9=E9=BD=90=E4=B8=8E?= =?UTF-8?q?=E4=BA=BA=E5=B7=A5=E8=BF=BD=E4=BB=B7=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 小程序领料 BOM/成品预览;移动端加工完成支持人工分配;订单完结后人工发起主系统 price-qty 申请。 --- .../components/processing-panel/index.js | 206 +++++++++++++++++- .../components/processing-panel/index.wxml | 42 +++- miniprogram/utils/request.js | 14 ++ .../src/routes/mobile/mobilePurchaseRoutes.ts | 63 ++++++ .../orderManagement/OrderManagementPage.tsx | 94 ++++++++ 5 files changed, 407 insertions(+), 12 deletions(-) diff --git a/miniprogram/components/processing-panel/index.js b/miniprogram/components/processing-panel/index.js index 6fd97fc..35ceb94 100644 --- a/miniprogram/components/processing-panel/index.js +++ b/miniprogram/components/processing-panel/index.js @@ -3,6 +3,8 @@ const { fetchStandaloneProcessingSkuOptions, createStandaloneProcessingTask, pickDemandSheetMaterial, + fetchDemandProcessingBom, + previewDemandFinishedOutput, startProcessingTask, completeProcessingWork, completeStandaloneProcessingTask, @@ -283,6 +285,13 @@ Component({ pickDemandInboundText: '', pickDemandUnit: '', pickRequestId: '', + pickHasBom: false, + pickBomMaterial: null, + pickBomLossRate: 0, + pickBomPickedMaterialQty: 0, + pickOutputQty: '', + pickOutputPreviewRows: [], + pickOutputPreviewLoading: false, createSkuOptions: [], createForm: { skuSearch: '', @@ -567,6 +576,13 @@ Component({ pickDemandQtyText: '', pickDemandInboundText: '', pickDemandUnit: '', + pickHasBom: false, + pickBomMaterial: null, + pickBomLossRate: 0, + pickBomPickedMaterialQty: 0, + pickOutputQty: '', + pickOutputPreviewRows: [], + pickOutputPreviewLoading: false, createSkuOptions: [], createMaterials: [], createForm: { @@ -596,6 +612,13 @@ Component({ 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: '', @@ -606,10 +629,139 @@ Component({ remark: '', }, }); - this.loadCreateSkuOptions(); + 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: '', @@ -617,6 +769,13 @@ Component({ pickDemandQtyText: '', pickDemandInboundText: '', pickDemandUnit: '', + pickHasBom: false, + pickBomMaterial: null, + pickBomLossRate: 0, + pickBomPickedMaterialQty: 0, + pickOutputQty: '', + pickOutputPreviewRows: [], + pickOutputPreviewLoading: false, createSkuOptions: [], }); }, @@ -768,6 +927,35 @@ Component({ 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) { @@ -778,6 +966,22 @@ Component({ 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({ diff --git a/miniprogram/components/processing-panel/index.wxml b/miniprogram/components/processing-panel/index.wxml index 7a44aa0..66814b8 100644 --- a/miniprogram/components/processing-panel/index.wxml +++ b/miniprogram/components/processing-panel/index.wxml @@ -134,7 +134,7 @@ {{pickTaskId ? '需求单领料' : '创建独立加工'}} - {{pickTaskId ? '选择库存原料并填写数量,可多次领料' : '选库存商品填数量,确认后扣库存并记原料成本'}} + {{pickTaskId ? (pickHasBom ? '按 BOM 带出原材料,填写产出后确认领料并完工' : '选择库存原料并填写数量,可多次领料') : '选库存商品填数量,确认后扣库存并记原料成本'}} 成品 {{pickDemandName}} 需加工 {{pickDemandQtyText}}{{pickDemandUnit}} @@ -144,17 +144,22 @@ × - - 商品 - + + 原材料:{{pickBomMaterial.sku_name}}(可用 {{pickBomMaterial.available_qty}}{{pickBomMaterial.display_unit || pickDemandUnit}}) - - - {{item.sku_name}} - {{item.sku_code}} · 可用 {{item.available_qty}}{{item.display_unit}} + + + 商品 + - - 已选 {{createForm.selectedSku.sku_name}} + + + {{item.sku_name}} + {{item.sku_code}} · 可用 {{item.available_qty}}{{item.display_unit}} + + + 已选 {{createForm.selectedSku.sku_name}} + 原料明细(可多行) @@ -183,10 +188,25 @@ + + 加工产出数量(成品净重) + + + 正在计算客户分配… + + 客户分配(合计需等于加工产出) + + + {{item.customerName || item.orderCode}} + {{item.orderCode}} · 需求 {{item.demandQty}} + + + + - + diff --git a/miniprogram/utils/request.js b/miniprogram/utils/request.js index 0fd7ce4..2a2bc5c 100644 --- a/miniprogram/utils/request.js +++ b/miniprogram/utils/request.js @@ -1447,6 +1447,18 @@ function fetchCustomerTraceOrder(orderCode) { return request(`/mobile/customer-trace/orders/${encodeURIComponent(orderCode || '')}`); } +/** 需求单领料:BOM 明细(原材料、可用库存、损耗率) */ +function fetchDemandProcessingBom(taskId) { + return request(`/mobile/processing/demand/${encodeURIComponent(taskId || '')}/bom`); +} + +/** 需求单完工:按实际产出预览客户分配 */ +function previewDemandFinishedOutput(taskId, actualQty) { + return request( + `/mobile/processing/demand/${encodeURIComponent(taskId || '')}/finished-output-preview?actual_qty=${encodeURIComponent(actualQty)}` + ); +} + module.exports = { request, fetchCustomerTraceOrders, @@ -1585,6 +1597,8 @@ module.exports = { completeStandaloneProcessingTask, listStandaloneLines, pickDemandSheetMaterial, + fetchDemandProcessingBom, + previewDemandFinishedOutput, skipWarehouseDemandPurchase, startProcessingTask, completeProcessingWork, diff --git a/server/src/routes/mobile/mobilePurchaseRoutes.ts b/server/src/routes/mobile/mobilePurchaseRoutes.ts index e242291..9a7dc2b 100644 --- a/server/src/routes/mobile/mobilePurchaseRoutes.ts +++ b/server/src/routes/mobile/mobilePurchaseRoutes.ts @@ -23,7 +23,9 @@ import { listStandaloneProcessingSkuOptions, listDemandSheetOwnOrderCodes, pickDemandSheetMaterial, + previewFinishedOutputAllocation, } from '../../services/processingOps'; +import { getProcessingBomMaterialDetails } from '../../services/processingRawMaterialService'; import { healOpenWarehouseDemandPurchases, healWarehousePurchaseZeroCosts, @@ -1034,6 +1036,61 @@ router.post('/processing/start', authMiddleware, async (req: AuthRequest, res: R } }); +router.get('/processing/demand/:taskId/bom', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + requireMobileRoles(req, ['warehouse', 'inspector']); + const ctx = await loadTenantContext(req.userId); + if (!ctx?.branchCode) { + return res.status(403).json({ error: 'invalid_branch', error_description: '未绑定分公司' }); + } + const taskResult = await pool.query( + `SELECT id, sku_code, processing_method, source_qty, material_qty, source_type, branch_code + FROM processing_tasks WHERE id = $1::uuid LIMIT 1`, + [String(req.params.taskId || '')] + ); + const task = taskResult.rows[0]; + if (!task) return res.status(404).json({ error: 'not_found', error_description: '加工任务不存在' }); + const detail = await getProcessingBomMaterialDetails({ + branchCode: String(task.branch_code || ctx.branchCode || ''), + outputSku: String(task.sku_code || ''), + processingMethod: String(task.processing_method || ''), + }); + return res.json({ + data: { + task_id: task.id, + has_bom: Boolean(detail), + output_sku: task.sku_code, + processing_method: task.processing_method, + demand_qty: Number(task.source_qty) || 0, + picked_material_qty: Number(task.material_qty) || 0, + unit: '', + ...(detail || {}), + }, + }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '加载加工原材料失败', + }); + } +}); + +router.get('/processing/demand/:taskId/finished-output-preview', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + requireMobileRoles(req, ['warehouse', 'inspector']); + const data = await previewFinishedOutputAllocation({ + taskId: String(req.params.taskId || ''), + actualQty: req.query.actual_qty != null ? Number(req.query.actual_qty) : undefined, + }); + return res.json({ data }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '加载成品分配失败', + }); + } +}); + router.post('/processing/complete', authMiddleware, async (req: AuthRequest, res: Response) => { try { requireMobileRoles(req, ['warehouse', 'inspector']); @@ -1050,6 +1107,12 @@ router.post('/processing/complete', authMiddleware, async (req: AuthRequest, res : Number(req.body.process_unit_price), remark: req.body?.remark ? String(req.body.remark) : undefined, operatorId: req.userId, + manualOutputAllocations: Array.isArray(req.body?.manual_output_allocations) + ? req.body.manual_output_allocations.map((row: any) => ({ + orderItemId: String(row?.order_item_id || ''), + qty: Number(row?.qty), + })) + : undefined, }); return res.json({ success: true }); } catch (error: any) { diff --git a/src/pages/orders/orderManagement/OrderManagementPage.tsx b/src/pages/orders/orderManagement/OrderManagementPage.tsx index c732735..015e53a 100644 --- a/src/pages/orders/orderManagement/OrderManagementPage.tsx +++ b/src/pages/orders/orderManagement/OrderManagementPage.tsx @@ -119,6 +119,7 @@ import { historicalFinalizeOrderApi, applyInventoryOffsetApi, cancelOrderItemStockCoverApi, + submitOrderItemPriceQtyRequestApi, } from '../../../utils/workflowApi'; import { useCategoryRows } from '../../../hooks/useCategoryRows'; import { useRowClickOrDoubleClick } from '../../../hooks/useRowClickOrDoubleClick'; @@ -437,6 +438,11 @@ export const OrderManagement: React.FC = () => { const [receivedQtyBaseline, setReceivedQtyBaseline] = useState>(new Map()); const [bomSetupOpen, setBomSetupOpen] = useState(false); const [bomSetupTargets, setBomSetupTargets] = useState([]); + + const [priceRequestOpen, setPriceRequestOpen] = useState(false); + const [priceRequestSaving, setPriceRequestSaving] = useState(false); + const [priceRequestItemId, setPriceRequestItemId] = useState(''); + const [priceRequestForm, setPriceRequestForm] = useState({ price: '', qty: '', unit: '', reason: '' }); const [activeQuoteSheetCode, setActiveQuoteSheetCode] = useState(null); const [quoteCostBySku, setQuoteCostBySku] = useState>(new Map()); const [supplierCategories, setSupplierCategories] = useState([]); @@ -4648,6 +4654,28 @@ export const OrderManagement: React.FC = () => { ) : null} + {Number(selectedOrder.order_status) >= 90 ? ( +
+ +
+ ) : null} + {planChanges.length > 0 ? (
@@ -5184,6 +5212,72 @@ export const OrderManagement: React.FC = () => { )} + {priceRequestOpen && selectedOrder ? ( + !priceRequestSaving && setPriceRequestOpen(false)}> +
+

主系统追加修改申请

+
+ +
+ + + +
+