const { fetchAdminPurchaseOrders, completeAdminPurchase, fetchAdminPurchaseAssignSuppliers, assignAdminPurchaseToSupplier, amendAdminPurchaseActual, updateAdminPurchaseSalePrice, fetchAdminPurchasePurchasers, patchAdminPurchasePurchaser, assignAdminPurchasePurchasers, } = require('../../utils/request'); const { ensureMobileRole } = require('../../utils/roleGuard'); const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate'); const { chinaTodayYmd, shiftChinaYmd } = require('../../utils/chinaDate'); const STATUS_TEXT = { 10: '待采购', 20: '待仓验', 32: '质检退回', 30: '已完成', 40: '已取消', }; const SOURCE_OPTIONS = [ { value: '', label: '全部来源' }, { value: 'stockout_transfer', label: '备货无货流转' }, { value: 'supply_stockout', label: '供货无货流转' }, { value: 'unmatched_transfer', label: '未匹配商品流转' }, { value: 'category_reassign', label: '分类调整流转' }, { value: 'order_no_supplier', label: '无供应商' }, { value: 'order_no_sku', label: '未匹配SKU' }, { value: 'order_no_category', label: '无分类' }, { value: 'direct', label: '直接采购' }, ]; const SOURCE_LABEL = SOURCE_OPTIONS.reduce((acc, item) => { acc[item.value] = item.label; return acc; }, {}); /** 「未填」= null / undefined / 空串;**0 是填了的合法数值**。 */ function isFilledPrice(value) { return value !== undefined && value !== null && String(value).trim() !== ''; } /** 取第一个「填了」的数值(0 也算填了,不会被跳过);全未填返回 null。 * ⚠️ 0 是合法成本价(「允许成本价为 0」):只有「未填」才回退下单价/建议价。 * 若写成 `actual_price || purchase_price`,把成本价改成 0 之后列表与预填 * 会显示回下单价或建议成本价(实测 BR004 该行会显示 6.00)。 */ function pickStoredPrice(...values) { for (const value of values) { if (!isFilledPrice(value)) continue; const num = Number(value); if (Number.isFinite(num)) return num; } return null; } function money(value) { const num = Number(value); if (!Number.isFinite(num) || num === 0) return '0.00'; return num.toFixed(2); } function qtyText(value) { const num = Number(value); if (!Number.isFinite(num)) return '0'; return Number.isInteger(num) ? String(num) : String(Math.round(num * 1000) / 1000); } function decorateRow(row) { const status = Number(row.purchase_status) || 0; const qty = Number(row.actual_qty || row.purchase_qty) || 0; const price = pickStoredPrice(row.actual_price, row.purchase_price) ?? 0; const amount = Number(row.total_amount) > 0 ? Number(row.total_amount) : qty * price; return { ...row, item_name: String(row.item_name || row.sku_name || '商品'), status, statusText: STATUS_TEXT[status] || String(status), sourceText: SOURCE_LABEL[String(row.source_type || '')] || String(row.source_type || '—'), purchaserText: String(row.purchaser_name || row.purchaser_code || '未分配'), qtyText: qtyText(row.purchase_qty), actualQtyText: qtyText(row.actual_qty || row.purchase_qty), unitText: String(row.unit || '个'), salePriceText: money(row.sale_price), costPriceText: money(pickStoredPrice(row.actual_price, row.purchase_price) ?? 0), amountText: money(amount), specText: String(row.product_spec || row.specification || '').trim() || '—', remarkText: String(row.order_item_remark || '').trim() || '—', canComplete: status === 10 || status === 32, canAssign: status === 10 || status === 32, canAssignPurchaser: status < 30 || status === 32, canAmend: status === 20 || status === 30, canEditSale: Boolean(row.order_item_id), actual_qty_input: qtyText(row.actual_qty || row.purchase_qty), actual_price_input: money( pickStoredPrice(row.actual_price, row.purchase_price, row.suggested_cost_price) ?? 0 ), sale_price_input: money(row.sale_price), }; } Component({ options: { addGlobalClass: true }, properties: { embedded: { type: Boolean, value: false }, homeStatusGroup: { type: String, value: '' }, }, data: { dateField: 'created_at', dateFieldLabel: '下单日', datePreset: 'today', dateFrom: '', dateTo: '', statusGroup: 'pending', searchQuery: '', sourceType: '', sourceIndex: 0, sourceLabels: SOURCE_OPTIONS.map((item) => item.label), categoryFilter: '', categories: [], rows: [], loading: false, error: '', stats: null, submitting: false, // 「允许成本价为 0」开关(分公司级,默认关闭),由列表接口下发;失败保持 false(保守拦截) allowZeroCost: false, purchaserOptions: [], purchaserLabels: [], }, observers: { homeStatusGroup(next) { if (!this.properties.embedded) return; const value = String(next || 'pending') === 'completed' ? 'completed' : 'pending'; if (value === this.data.statusGroup) return; this.setData({ statusGroup: value }, () => { if (this._panelReady) this.loadRows(); }); }, }, lifetimes: { attached() { const today = chinaTodayYmd(); this.setData({ dateFrom: today, dateTo: today }); this.onPanelShow(); }, }, pageLifetimes: { show() { this.onPanelShow(); }, }, methods: { async onPanelShow() { if (!beginPanelShow(this)) return; try { const ok = await ensureMobileRole(['admin', 'operator']); if (!ok) return; if (this.properties.embedded) { const fromHome = String(this.properties.homeStatusGroup || 'pending'); const statusGroup = fromHome === 'completed' ? 'completed' : 'pending'; if (statusGroup !== this.data.statusGroup) { this.setData({ statusGroup }); } } await this.loadPurchasers(); await this.loadRows(); this._panelReady = true; } finally { endPanelShow(this); } }, async loadPurchasers() { try { const result = await fetchAdminPurchasePurchasers(); const list = Array.isArray(result.data) ? result.data : []; const purchaserOptions = list .map((item) => ({ purchaser_code: String(item.purchaser_code || ''), purchaser_name: String(item.purchaser_name || item.purchaser_code || '采购员'), })) .filter((item) => item.purchaser_code); this.setData({ purchaserOptions, purchaserLabels: purchaserOptions.map((item) => item.purchaser_name), }); } catch (err) { this.setData({ purchaserOptions: [], purchaserLabels: [], }); } }, decorateRows(rawRows) { const options = this.data.purchaserOptions || []; return (rawRows || []).map((row) => { const next = decorateRow(row); const code = String(next.purchaser_code || ''); let purchaserIndex = options.findIndex((item) => item.purchaser_code === code); if (purchaserIndex < 0) purchaserIndex = 0; return { ...next, purchaserIndex }; }); }, pendingAssignCodes() { return (this.data.rows || []) .filter((row) => row.canAssignPurchaser) .map((row) => row.purchase_code) .filter(Boolean); }, async applyPurchaser(purchaseCode, purchaserCode) { if (!purchaseCode || !purchaserCode) { throw new Error('请选择采购员'); } await patchAdminPurchasePurchaser(purchaseCode, purchaserCode); }, async onPurchaserPick(e) { const code = e.currentTarget.dataset.code; const idx = Number(e.detail.value); const opt = (this.data.purchaserOptions || [])[idx]; const row = (this.data.rows || []).find((item) => item.purchase_code === code); if (!opt || !opt.purchaser_code) { wx.showToast({ title: '请选择采购员', icon: 'none' }); return; } if (!row || String(row.purchaser_code || '') === String(opt.purchaser_code || '')) return; this.setData({ submitting: true }); try { await this.applyPurchaser(code, opt.purchaser_code); wx.showToast({ title: opt.purchaser_name || '已分配', icon: 'success' }); await this.loadRows(); } catch (err) { wx.showToast({ title: err.message || '分配失败', icon: 'none' }); } finally { this.setData({ submitting: false }); } }, async onBatchPurchaser(e) { const codes = this.pendingAssignCodes(); if (!codes.length) { wx.showToast({ title: '当前没有可分配的待采单', icon: 'none' }); return; } const idx = Number(e.detail.value); const opt = (this.data.purchaserOptions || [])[idx]; if (!opt || !opt.purchaser_code) { wx.showToast({ title: '请选择采购员', icon: 'none' }); return; } const confirmed = await new Promise((resolve) => { wx.showModal({ title: '批量分配采购员', content: `将当前 ${codes.length} 条未完成单改为「${opt.purchaser_name}」?`, success: (res) => resolve(Boolean(res.confirm)), }); }); if (!confirmed) return; this.setData({ submitting: true }); try { await assignAdminPurchasePurchasers({ mode: 'to_purchaser', purchase_codes: codes, purchaser_code: opt.purchaser_code, }); wx.showToast({ title: '已批量分配', icon: 'success' }); await this.loadRows(); } catch (err) { wx.showToast({ title: err.message || '批量分配失败', icon: 'none' }); } finally { this.setData({ submitting: false }); } }, setDateField(e) { const field = e.currentTarget.dataset.field; if (!field || field === this.data.dateField) return; this.setData({ dateField: field, dateFieldLabel: field === 'created_at' ? '下单日' : '配送日', }); this.loadRows(); }, setDatePreset(e) { const preset = e.currentTarget.dataset.preset; const today = chinaTodayYmd(); let dateFrom = today; let dateTo = today; if (preset === 'week') dateFrom = shiftChinaYmd(today, -6); if (preset === 'custom') { this.setData({ datePreset: 'custom' }); return; } this.setData({ datePreset: preset, dateFrom, dateTo }); this.loadRows(); }, onCustomFromChange(e) { this.setData({ dateFrom: e.detail.value, datePreset: 'custom' }); this.loadRows(); }, onCustomToChange(e) { this.setData({ dateTo: e.detail.value, datePreset: 'custom' }); this.loadRows(); }, setStatusGroup(e) { const statusGroup = e.currentTarget.dataset.group === 'completed' ? 'completed' : 'pending'; if (statusGroup === this.data.statusGroup) return; this.setData({ statusGroup }); this.loadRows(); }, onSearchInput(e) { this.setData({ searchQuery: e.detail.value }); }, onSearchConfirm() { this.loadRows(); }, onSourceChange(e) { const idx = Number(e.detail.value) || 0; const opt = SOURCE_OPTIONS[idx] || SOURCE_OPTIONS[0]; this.setData({ sourceIndex: idx, sourceType: opt.value }); this.loadRows(); }, onCategoryTap(e) { const name = String(e.currentTarget.dataset.name || ''); this.setData({ categoryFilter: this.data.categoryFilter === name ? '' : name }); this.loadRows(); }, onDraftInput(e) { const code = e.currentTarget.dataset.code; const field = e.currentTarget.dataset.field; const value = e.detail.value; const rows = (this.data.rows || []).map((row) => row.purchase_code === code ? { ...row, [field]: value } : row ); this.setData({ rows }); }, async loadRows() { this.setData({ loading: true, error: '' }); try { const result = await fetchAdminPurchaseOrders({ status_group: this.data.statusGroup, date_field: this.data.dateField, date_from: this.data.dateFrom, date_to: this.data.dateTo, search: this.data.searchQuery || undefined, source_type: this.data.sourceType || undefined, category: this.data.categoryFilter || undefined, }); const rows = this.decorateRows(result.data || []); this.setData({ rows, allowZeroCost: result && result.allow_zero_cost === true, categories: result.categories || [], stats: result.stats || null, loading: false, }); const stats = result.stats || {}; this.triggerEvent('progresschange', { pendingCount: Number(stats.pending) || 0, completedCount: Number(stats.completed) || 0, }); } catch (err) { this.setData({ loading: false, error: err.message || '加载失败', rows: [], }); } }, async saveRow(e) { const code = e.currentTarget.dataset.code; const row = (this.data.rows || []).find((item) => item.purchase_code === code); if (!row || this.data.submitting) return; this.setData({ submitting: true }); try { if (row.canAmend) { const qty = Number(row.actual_qty_input); const price = Number(row.actual_price_input); // 「允许成本价为 0」开关开启后 0 合法(负数/NaN 仍拦);服务端 purchaseAmendService 同口径 if (!(qty > 0) || (this.data.allowZeroCost ? !(price >= 0) : !(price > 0))) { wx.showToast({ title: '实收和成本须大于 0', icon: 'none' }); return; } await amendAdminPurchaseActual(code, { actual_qty: qty, actual_price: price, unit: row.unit, }); } if (row.canEditSale) { const sale = Number(row.sale_price_input); if (!Number.isFinite(sale) || sale < 0) { wx.showToast({ title: '销售价须不小于 0', icon: 'none' }); return; } await updateAdminPurchaseSalePrice(code, sale); } wx.showToast({ title: '已保存', icon: 'success' }); await this.loadRows(); } catch (err) { wx.showToast({ title: err.message || '保存失败', icon: 'none' }); } finally { this.setData({ submitting: false }); } }, async completeRow(e) { const code = e.currentTarget.dataset.code; const row = (this.data.rows || []).find((item) => item.purchase_code === code); if (!row || this.data.submitting) return; this.setData({ submitting: true }); try { await completeAdminPurchase({ purchase_code: code, actual_qty: Number(row.actual_qty_input), actual_price: Number(row.actual_price_input), unit: row.unit, }); wx.showToast({ title: '已完成', icon: 'success' }); await this.loadRows(); } catch (err) { wx.showToast({ title: err.message || '完成失败', icon: 'none' }); } finally { this.setData({ submitting: false }); } }, async assignRow(e) { const code = e.currentTarget.dataset.code; if (!code || this.data.submitting) return; this.setData({ submitting: true }); try { const result = await fetchAdminPurchaseAssignSuppliers(code); const list = result.suppliers || []; const options = Array.isArray(list) ? list : []; const names = options.map((item) => item.company_name || item.supplier_name || item.supplier_code); if (!names.length) { wx.showToast({ title: '暂无可转供应商', icon: 'none' }); return; } const pick = await new Promise((resolve) => { wx.showActionSheet({ itemList: names.slice(0, 6), success: (res) => resolve(res.tapIndex), fail: () => resolve(-1), }); }); if (pick < 0) return; const supplier = options[pick]; await assignAdminPurchaseToSupplier({ purchase_code: code, supplier_code: supplier.supplier_code, }); wx.showToast({ title: '已转供应商', icon: 'success' }); await this.loadRows(); } catch (err) { wx.showToast({ title: err.message || '转供应商失败', icon: 'none' }); } finally { this.setData({ submitting: false }); } }, }, });