const { fetchPurchaseOrders, fetchPurchaseCategories, createPurchaseCategory, fetchPurchaseAssignSuppliers, assignPurchaseToSupplier, updatePurchaseOrderStatus, uploadPurchaseDirectDeliveryPhoto, fetchUnits, fetchUiPreference, setUiPreference, searchPurchaseSkus, createSelfPurchaseStockInbound, skipWarehouseDemandPurchase, } = require('../../utils/request'); const { ensureMobileRole } = require('../../utils/roleGuard'); const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate'); const { buildCategoryPickerOptions, applyManualCategory, applyCategoryInput, findCategoryOptionByName, filterCategoryOptions, getCategoryDisplay, } = require('../../utils/orderCategory'); const { ensureUnitDictionary, getUnitDictionaryLabels } = require('../../utils/units'); const { AGGREGATE_PREF_KEY, PERIOD_OPTIONS, DATE_FIELD_OPTIONS, DATE_FIELD_LABELS, fmtLocalDate, formatDayLabel, summarizePurchaseGroups, displayText, resolveCategoryDisplayName, leafCategoryNameHint, canAssignSupplier, canCompletePurchase, canSkipWarehouseDemand, needsDirectDeliveryPhoto, directDeliveryPhotoCount, splitActualQtyByPlan, decoratePurchaseRow, buildCategoryProductGroups, groupByCategory, applyCategoryCollapseState, mergeCategoryGroupInputs, enrichPurchaseRowCategory, resolveActualQty, resolveActualPrice, resolvePeriodRange, formatPeriodLabel, decorateHistoryRow, groupByDay, flattenHistoryExportRows, applyDayCollapseState, pickCostPriceHint, } = require('../../utils/purchaseToday'); const { buildSimpleXlsxBytes } = require('../../utils/simpleXlsx'); const { printHistory } = require('../../utils/printHistory'); const { getSession } = require('../../utils/auth'); const { prepareOrderImageBase64 } = require('../../utils/orderImage'); const SPI_CATEGORY_TARGET = '__spi__'; function emptySpiForm() { return { sku_code: '', sku_name: '', category_code: '', category_label: '', unit: '斤', qty: '', unit_cost: '', remark: '', }; } function filterUnitOptions(query, labels) { const q = String(query || '').trim().toLowerCase(); const list = Array.isArray(labels) ? labels : []; if (!q) return list.slice(); return list.filter((item) => String(item || '').toLowerCase().includes(q)); } function resolveCanOrderItems(session, extra) { if (extra?.listScope === 'all') return true; const superAdmin = extra?.isSuperAdmin === true || session?.is_super_admin === true || session?.isSuperAdmin === true; if (superAdmin) return true; const fromExtra = Array.isArray(extra?.permissions) ? extra.permissions : []; const fromSession = Array.isArray(session?.permissions) ? session.permissions : []; return ( fromExtra.includes('mp_purchaser_order_items') || fromSession.includes('mp_purchaser_order_items') ); } function formatRefPrice(product) { const first = (product && product.items && product.items[0]) || {}; const price = pickCostPriceHint(first); const num = Number(price); if (!Number.isFinite(num) || num <= 0) return ''; const unit = displayText(product.unit || first.unit, '个'); return `¥${num}/${unit}`; } function decorateProductGroupDisplay(pg, categoryName) { const label = leafCategoryNameHint(categoryName) || displayText(categoryName, '未分类'); // 规格:只认订单行录单规格(与订单详情同口径);组内去重,空则整行不显示 const specText = [ ...new Set( (pg.items || []).map((item) => String(item.order_spec || '').trim()).filter(Boolean) ), ].join('、'); return { ...pg, categoryLabel: label || '未分类', specText, refPriceText: formatRefPrice(pg), canAssignAny: (pg.items || []).some((item) => item.can_assign_supplier), assignPurchaseCode: ((pg.items || []).find((item) => item.can_assign_supplier) || {}).purchase_code || '', direct_delivery: Boolean(pg.direct_delivery), photoRequired: Boolean(pg.photoRequired), photoCount: Number(pg.photoCount) || 0, photoUrls: pg.photoUrls || [], }; } Component({ options: { addGlobalClass: true, }, properties: { embedded: { type: Boolean, value: false, }, initialTab: { type: String, value: 'today', }, hideProgress: { type: Boolean, value: false, }, permissions: { type: Array, value: [], }, isSuperAdmin: { type: Boolean, value: false, }, listScope: { type: String, value: '', }, }, observers: { 'permissions, isSuperAdmin, listScope': function () { this.syncOrderItemsPermission(); }, }, lifetimes: { attached() { this.expandedCategoryKeys = new Set(); this.historyExpandedDayKeys = new Set(); this.refreshTimer = null; this._categoryExpandInited = false; const tab = this.properties.initialTab === 'history' ? 'history' : 'today'; if (tab !== this.data.tab) { this.setData({ tab }); } // 首页内嵌时 pageLifetimes.show 偶发不触发,attached 也拉一次 this.onPanelShow(); }, detached() { this.stopAutoRefresh(); }, }, pageLifetimes: { show() { this.onPanelShow(); }, hide() { this.stopAutoRefresh(); }, }, data: { /** 「允许成本价为 0」开关(分公司级,默认关闭):由采购单列表接口回传 */ allowZeroCost: false, tab: 'today', categoryGroups: [], categoryOptions: [], catalogCategoryOptions: [], selectedCategory: '', aggregateSameProducts: true, aggregateWritesBranch: false, aggregateSaving: false, loading: false, error: '', activeCategoryPurchaseCode: '', categoryDropdownQuery: '', categoryDropdownOptions: [], categoryDropdownCurrentCode: '', categorySearchFocus: false, showQuickCategoryModal: false, quickCategoryTargetCode: '', quickCategoryName: '', creatingCategory: false, batchSubmitting: false, assignSubmittingCode: '', heroDate: '', completedCount: 0, totalCount: 0, pendingCount: 0, todayTotalText: '0.00', historyDayGroups: [], historyFrom: '', historyTo: '', historyPeriod: '7d', historyPeriodLabel: '', historySummary: '', historyLoading: false, historyError: '', historyDateField: 'delivery_date', historyDateFieldIndex: 0, historyDateFieldLabel: '配送日', historyDateFieldLabels: DATE_FIELD_LABELS, historyExporting: false, historyPrinting: false, periodOptions: PERIOD_OPTIONS, canOrderItems: false, todayDateField: 'delivery_date', todayDateFieldIndex: DATE_FIELD_OPTIONS.findIndex((row) => row.key === 'delivery_date'), todayDateFieldLabel: '配送日', todayDateFieldLabels: DATE_FIELD_LABELS, todayQueryDate: '', todayDateChipLabel: '全部', todayQueryIsToday: false, showSpiModal: false, spiMode: 'select', spiForm: emptySpiForm(), spiSkuQuery: '', spiSkuSuggestions: [], spiSkuSearching: false, spiSkuListOpen: false, spiSubmitting: false, spiCategoryTarget: SPI_CATEGORY_TARGET, spiUnitDropdownOpen: false, spiUnitQuery: '', spiUnitOptions: [], spiUnitCanUseQuery: false, spiUnitSearchFocus: false, }, methods: { syncOrderItemsPermission() { const next = resolveCanOrderItems(getSession() || {}, { permissions: this.properties.permissions, isSuperAdmin: this.properties.isSuperAdmin, listScope: this.properties.listScope, }); if (next !== this.data.canOrderItems) { this.setData({ canOrderItems: next }); } }, async onPanelShow() { if (!beginPanelShow(this)) return; try { const listAll = String(this.properties.listScope || '') === 'all'; const ok = await ensureMobileRole(listAll ? ['admin', 'operator'] : 'purchaser'); if (!ok) return; this.syncOrderItemsPermission(); const today = fmtLocalDate(); const queryDate = /^\d{4}-\d{2}-\d{2}$/.test(String(this.data.todayQueryDate || '')) ? this.data.todayQueryDate : ''; this.setData({ todayQueryDate: queryDate, todayDateChipLabel: queryDate ? formatDayLabel(queryDate) : '全部', todayQueryIsToday: Boolean(queryDate) && queryDate === today, }); if (!this.data.historyFrom || !this.data.historyTo) { this.initHistoryPeriod('7d'); } await Promise.all([ ensureUnitDictionary(fetchUnits), this.loadCatalogCategories(), this.loadAggregatePreference(), ]); if (this.data.tab === 'history') { this.stopAutoRefresh(); await this.loadHistoryRows(); } else { await this.loadRows(); this.startAutoRefresh(); } } finally { endPanelShow(this); } }, openOrderItemsDialog(e) { const mode = String(e.currentTarget.dataset.mode || '').trim(); const dialog = this.selectComponent('#purchaserOrderDialog'); if (dialog && dialog.open) dialog.open(mode); }, openSpiModal() { this.closeCategoryDropdown(); this.closeSpiUnitDropdown(); this.setData({ showSpiModal: true, spiMode: 'select', spiForm: emptySpiForm(), // 幂等键:本次表单会话内重试/双击复用同一键,服务端去重 spiRequestId: `spi-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`, spiSkuQuery: '', spiSkuSuggestions: [], spiSkuSearching: false, spiSkuListOpen: false, spiSubmitting: false, }); }, closeSpiModal() { this.closeCategoryDropdown(); this.closeSpiUnitDropdown(); this.setData({ showSpiModal: false, spiSkuListOpen: false }); }, stopSpiTap() {}, setSpiMode(e) { const mode = String(e.currentTarget.dataset.mode || 'select'); this.closeCategoryDropdown(); this.closeSpiUnitDropdown(); this.setData({ spiMode: mode === 'create' ? 'create' : 'select', spiSkuListOpen: false, 'spiForm.sku_code': '', }); }, onSpiFormInput(e) { const field = String(e.currentTarget.dataset.field || ''); if (!field) return; this.setData({ [`spiForm.${field}`]: e.detail.value }); }, closeSpiUnitDropdown() { this.setData({ spiUnitDropdownOpen: false, spiUnitQuery: '', spiUnitOptions: [], spiUnitCanUseQuery: false, spiUnitSearchFocus: false, }); }, toggleSpiUnitDropdown() { if (this.data.spiUnitDropdownOpen) { this.closeSpiUnitDropdown(); return; } this.closeCategoryDropdown(); const labels = getUnitDictionaryLabels(); this.setData({ spiUnitDropdownOpen: true, spiUnitQuery: '', spiUnitOptions: filterUnitOptions('', labels), spiUnitCanUseQuery: false, spiUnitSearchFocus: false, }, () => { setTimeout(() => { if (this.data.spiUnitDropdownOpen) { this.setData({ spiUnitSearchFocus: true }); } }, 80); }); }, onSpiUnitSearchFocus() { if (this.data.spiUnitSearchFocus) { this.setData({ spiUnitSearchFocus: false }); } }, onSpiUnitDropdownSearch(e) { const value = e.detail.value; const labels = getUnitDictionaryLabels(); const trimmed = String(value || '').trim(); const options = filterUnitOptions(value, labels); const exact = labels.some((item) => String(item) === trimmed); this.setData({ spiUnitQuery: value, spiUnitOptions: options, spiUnitCanUseQuery: Boolean(trimmed) && !exact, }); }, pickSpiUnit(e) { const unit = String(e.currentTarget.dataset.unit || '').trim(); if (!unit) { this.closeSpiUnitDropdown(); return; } this.setData({ 'spiForm.unit': unit }); this.closeSpiUnitDropdown(); }, useSpiUnitQuery() { const unit = String(this.data.spiUnitQuery || '').trim(); if (!unit) return; this.setData({ 'spiForm.unit': unit }); this.closeSpiUnitDropdown(); }, onSpiSkuFocus() { const q = String(this.data.spiSkuQuery || '').trim(); if (!q) return; this.setData({ spiSkuListOpen: true }); this.searchSpiSkus(this.data.spiSkuQuery); }, onSpiSkuInput(e) { const value = String(e.detail.value || ''); const hasQuery = Boolean(value.trim()); this.setData({ spiSkuQuery: value, spiSkuListOpen: hasQuery, 'spiForm.sku_code': '', 'spiForm.sku_name': value, }); clearTimeout(this._spiSkuTimer); this._spiSkuTimer = setTimeout(() => this.searchSpiSkus(value), 250); }, async searchSpiSkus(query) { const q = String(query || '').trim(); const seq = (this._spiSkuSeq || 0) + 1; this._spiSkuSeq = seq; if (!q) { this.setData({ spiSkuSuggestions: [], spiSkuSearching: false }); return; } this.setData({ spiSkuSearching: true }); try { const result = await searchPurchaseSkus(q); if (seq !== this._spiSkuSeq) return; this.setData({ spiSkuSuggestions: result.data || [], spiSkuSearching: false, }); } catch (_err) { if (seq !== this._spiSkuSeq) return; this.setData({ spiSkuSuggestions: [], spiSkuSearching: false }); } }, pickSpiSku(e) { const index = Number(e.currentTarget.dataset.index); const row = (this.data.spiSkuSuggestions || [])[index]; if (!row) return; this.setData({ spiSkuQuery: row.sku_name || row.sku_code, spiSkuListOpen: false, spiSkuSuggestions: [], spiForm: { ...this.data.spiForm, sku_code: String(row.sku_code || ''), sku_name: String(row.sku_name || row.sku_code || ''), unit: String(row.unit || ''), category_code: String(row.category_code || ''), }, }); }, async submitSpiInbound() { if (this.data.spiSubmitting) return; const form = this.data.spiForm || emptySpiForm(); const qty = Number(form.qty); const unitCost = Number(form.unit_cost); if (this.data.spiMode === 'select' && !String(form.sku_code || '').trim()) { wx.showToast({ title: '请选择商品', icon: 'none' }); return; } if (this.data.spiMode === 'create' && !String(form.sku_name || '').trim()) { wx.showToast({ title: '请输入商品名称', icon: 'none' }); return; } if (this.data.spiMode === 'create' && !String(form.category_code || '').trim()) { wx.showToast({ title: '请选择商品分类', icon: 'none' }); return; } if (!Number.isFinite(qty) || qty <= 0) { wx.showToast({ title: '入库数量须大于 0', icon: 'none' }); return; } // 「允许成本价为 0」开关:开启后 0 合法(未填空串按 0),负数/非法输入仍拦。 // 服务端 selfPurchaseStockInboundService 已按开关放行 0,这里不跟着放行就只剩前端拦路。 if (!Number.isFinite(unitCost) || (this.data.allowZeroCost ? unitCost < 0 : unitCost <= 0)) { wx.showToast({ title: '成本价须大于 0', icon: 'none' }); return; } this.setData({ spiSubmitting: true }); try { const payload = this.data.spiMode === 'select' ? { sku_code: form.sku_code, qty, unit_cost: unitCost, remark: form.remark, request_id: this.data.spiRequestId, } : { sku_name: form.sku_name, category_code: form.category_code, unit: String(form.unit || '').trim() || '斤', qty, unit_cost: unitCost, remark: form.remark, request_id: this.data.spiRequestId, }; await createSelfPurchaseStockInbound(payload); this.setData({ showSpiModal: false, spiSubmitting: false, tab: 'history', }); this.stopAutoRefresh(); wx.showToast({ title: '已提交,待验收入库', icon: 'none' }); await this.loadHistoryRows(); } catch (err) { this.setData({ spiSubmitting: false }); wx.showToast({ title: err.message || '入库失败', icon: 'none' }); } }, onOrderItemsSaved() { if (this.data.tab === 'history') { this.loadHistoryRows(); } else { this.loadRows(); } }, switchTab(e) { const tab = e.currentTarget.dataset.tab; if (!tab || tab === this.data.tab) return; this.setData({ tab }); if (tab === 'history') { this.stopAutoRefresh(); this.loadHistoryRows(); } else { this.loadRows(); this.startAutoRefresh(); } }, emitProgress(patch = {}) { if (!this.properties.hideProgress) return; this.triggerEvent('progresschange', { heroDate: patch.heroDate != null ? patch.heroDate : this.data.heroDate, completedCount: patch.completedCount != null ? patch.completedCount : this.data.completedCount, totalCount: patch.totalCount != null ? patch.totalCount : this.data.totalCount, }); }, emitBadge(count) { const badgeKey = String(this.properties.listScope || '') === 'all' ? 'adminPurchasePendingBadgeCount' : 'purchasePendingBadgeCount'; const value = Number(count); if (Number.isFinite(value)) { this.triggerEvent('badgechange', { count: value, badgeKey, }); return; } this.triggerEvent('badgechange', { badgeKey }); }, onTodayDateFieldChange(e) { const idx = Number(e.detail.value); const option = DATE_FIELD_OPTIONS[idx] || DATE_FIELD_OPTIONS.find((row) => row.key === 'delivery_date'); if (!option || option.key === this.data.todayDateField) return; this.setData({ todayDateField: option.key, todayDateFieldIndex: Number.isFinite(idx) ? idx : 0, todayDateFieldLabel: option.label, }, () => this.loadRows()); }, onTodayQueryAll() { if (!this.data.todayQueryDate) return; this.expandedCategoryKeys.clear(); this._categoryExpandInited = false; this.setData( { todayQueryDate: '', todayDateChipLabel: '全部', todayQueryIsToday: false, }, () => this.loadRows() ); }, onTodayQueryDateChange(e) { const next = String(e.detail.value || '').trim(); if (!/^\d{4}-\d{2}-\d{2}$/.test(next) || next === this.data.todayQueryDate) return; this.expandedCategoryKeys.clear(); this._categoryExpandInited = false; this.setData( { todayQueryDate: next, todayDateChipLabel: formatDayLabel(next), todayQueryIsToday: next === fmtLocalDate(), }, () => this.loadRows() ); }, onRefresh() { if (this.data.tab === 'history') this.loadHistoryRows(); else this.loadRows(); }, initHistoryPeriod(preset) { const range = resolvePeriodRange(preset); this.setData({ historyPeriod: preset, historyFrom: range.from, historyTo: range.to, historyPeriodLabel: formatPeriodLabel(range.from, range.to), }); }, onHistoryPeriodTap(e) { const preset = e.currentTarget.dataset.period; if (!preset) return; if (preset === this.data.historyPeriod) return; this.historyExpandedDayKeys.clear(); this.initHistoryPeriod(preset); this.loadHistoryRows(); }, onHistoryFromChange(e) { const from = e.detail.value; this.setData({ historyFrom: from, historyPeriod: 'custom', historyPeriodLabel: formatPeriodLabel(from, this.data.historyTo), }); this.historyExpandedDayKeys.clear(); this.loadHistoryRows(); }, onHistoryToChange(e) { const to = e.detail.value; this.setData({ historyTo: to, historyPeriod: 'custom', historyPeriodLabel: formatPeriodLabel(this.data.historyFrom, to), }); this.historyExpandedDayKeys.clear(); this.loadHistoryRows(); }, onHistoryDateFieldChange(e) { const idx = Number(e.detail.value); const option = DATE_FIELD_OPTIONS[idx] || DATE_FIELD_OPTIONS[0]; if (option.key === this.data.historyDateField) return; this.setData({ historyDateField: option.key, historyDateFieldIndex: Number.isFinite(idx) ? idx : 0, historyDateFieldLabel: option.label, }); this.historyExpandedDayKeys.clear(); this.loadHistoryRows(); }, async printHistoryList() { if (this.data.historyPrinting || this.data.historyExporting) return; const rows = flattenHistoryExportRows(this.data.historyDayGroups); if (!rows.length) { wx.showToast({ title: '该周期暂无历史采购记录', icon: 'none' }); return; } this.setData({ historyPrinting: true }); try { await printHistory( this, { rows, title: '鲜配达 · 历史采购', subtitle: `周期 ${this.data.historyPeriodLabel || ''} · ${this.data.historyDateFieldLabel || ''}`.trim(), emptyText: '该周期暂无历史采购记录', fileName: 'purchase-history.pdf', }, () => this.pickBleDevice() ); } catch (err) { wx.hideLoading(); if (err && err.message !== '已取消') { wx.showToast({ title: err.message || '打印失败', icon: 'none' }); } } finally { this.setData({ historyPrinting: false }); } }, pickBleDevice() { const sheet = this.selectComponent('#blePicker'); if (!sheet || typeof sheet.pick !== 'function') { return Promise.resolve(null); } return sheet.pick(); }, async exportHistoryExcel() { if (this.data.historyExporting) return; const rows = flattenHistoryExportRows(this.data.historyDayGroups); if (!rows.length) { wx.showToast({ title: '该周期暂无历史采购记录', icon: 'none' }); return; } this.setData({ historyExporting: true }); wx.showLoading({ title: '正在导出', mask: true }); try { const bytes = buildSimpleXlsxBytes( '历史采购', ['日期', '商品名', '数量', '单位', '单价', '合计'], rows ); const filePath = `${wx.env.USER_DATA_PATH}/purchase-history.xlsx`; await new Promise((resolve, reject) => { wx.getFileSystemManager().writeFile({ filePath, data: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), success: resolve, fail: (err) => reject(new Error(err.errMsg || '保存表格失败')), }); }); wx.hideLoading(); await new Promise((resolve, reject) => { wx.openDocument({ filePath, fileType: 'xlsx', showMenu: true, success: resolve, fail: (err) => reject(new Error(err.errMsg || '打开表格失败')), }); }); } catch (err) { wx.hideLoading(); wx.showToast({ title: err.message || '导出失败', icon: 'none' }); } finally { this.setData({ historyExporting: false }); } }, toggleHistoryDayGroup(e) { const dayKey = e.currentTarget.dataset.day; if (!dayKey) return; const set = this.historyExpandedDayKeys; if (set.has(dayKey)) set.delete(dayKey); else set.add(dayKey); const historyDayGroups = this.data.historyDayGroups.map((g) => g.dayKey === dayKey ? { ...g, collapsed: !g.collapsed } : g ); this.setData({ historyDayGroups }); }, async loadHistoryRows() { const { historyFrom, historyTo } = this.data; if (!historyFrom || !historyTo) return; if (historyFrom > historyTo) { this.setData({ historyError: '开始日期不能晚于结束日期', historyDayGroups: [], historySummary: '', }); return; } this.setData({ historyLoading: true, historyError: '' }); try { const result = await fetchPurchaseOrders({ view: 'history', date_from: historyFrom, date_to: historyTo, date_field: this.data.historyDateField || 'delivery_date', ...(String(this.properties.listScope || '') === 'all' ? { scope: 'all' } : {}), }); this.setData({ allowZeroCost: result && result.allow_zero_cost === true }); const rows = (result.data || []).map(decorateHistoryRow); const historyDayGroups = applyDayCollapseState(groupByDay(rows), this.historyExpandedDayKeys); const totalCount = rows.length; const totalAmount = rows.reduce( (sum, r) => sum + (Number.isFinite(r.total_price) ? r.total_price : 0), 0 ); this.setData({ historyDayGroups, historyLoading: false, historySummary: totalCount ? `共 ${totalCount} 项 · 合计 ¥${totalAmount.toFixed(2)}` : '', }); } catch (err) { this.setData({ historyLoading: false, historyError: err.message || '加载失败', historyDayGroups: [], historySummary: '', }); } }, async loadAggregatePreference() { try { const result = await fetchUiPreference(AGGREGATE_PREF_KEY); const data = result.data || {}; const enabled = data.value && typeof data.value === 'object' ? data.value.enabled !== false : data.value !== false; this.setData({ aggregateSameProducts: enabled !== false, aggregateWritesBranch: data.writes_branch === true, }); } catch (_err) { /* keep default */ } }, async onToggleAggregate(e) { const checked = !!(e.detail && e.detail.value); if (this.data.aggregateSaving) return; const prev = this.data.aggregateSameProducts; this.setData({ aggregateSameProducts: checked, aggregateSaving: true }); try { const result = await setUiPreference(AGGREGATE_PREF_KEY, { enabled: checked }); const data = result.data || {}; this.setData({ aggregateWritesBranch: data.writes_branch === true, }); this.loadRows({ silent: true }); } catch (err) { this.setData({ aggregateSameProducts: prev }); wx.showToast({ title: err.message || '保存失败', icon: 'none' }); } finally { this.setData({ aggregateSaving: false }); } }, async loadCatalogCategories() { try { const result = await fetchPurchaseCategories(); const catalogCategoryOptions = buildCategoryPickerOptions(result.data || []); this.setData({ catalogCategoryOptions }); } catch (_err) { this.setData({ catalogCategoryOptions: buildCategoryPickerOptions([]) }); } }, startAutoRefresh() { this.stopAutoRefresh(); if (this.data.tab !== 'today') return; this.refreshTimer = setInterval(() => { if (this.data.batchSubmitting || this.data.tab !== 'today') return; this.loadRows({ silent: true }); }, 15000); }, stopAutoRefresh() { if (this.refreshTimer) { clearInterval(this.refreshTimer); this.refreshTimer = null; } }, async loadRows(options = {}) { const silent = Boolean(options.silent); if (!silent) { this.setData({ loading: true, error: '' }); } try { const queryDate = /^\d{4}-\d{2}-\d{2}$/.test(String(this.data.todayQueryDate || '')) ? this.data.todayQueryDate : ''; const params = { category_code: this.data.selectedCategory || undefined, date_field: this.data.todayDateField || 'delivery_date', ...(queryDate ? { delivery_date: queryDate } : { all_pending: 1 }), ...(String(this.properties.listScope || '') === 'all' ? { scope: 'all' } : {}), }; const result = await fetchPurchaseOrders(params); this.setData({ allowZeroCost: result && result.allow_zero_cost === true }); const categoryOptions = this.data.catalogCategoryOptions || buildCategoryPickerOptions([]); const rows = (result.data || []).map((row) => decoratePurchaseRow(row, categoryOptions)); const grouped = mergeCategoryGroupInputs( this.data.categoryGroups, groupByCategory(rows, this.data.aggregateSameProducts !== false, categoryOptions) ); if (!this._categoryExpandInited) { for (const group of grouped) { if (group.pendingCount > 0) this.expandedCategoryKeys.add(group.categoryKey); } this._categoryExpandInited = true; } const categoryGroups = applyCategoryCollapseState(grouped, this.expandedCategoryKeys).map( (group) => ({ ...group, productGroups: (group.productGroups || []).map((pg) => decorateProductGroupDisplay(pg, group.categoryName) ), }) ); const summary = summarizePurchaseGroups(categoryGroups, rows, queryDate); this.setData({ categoryGroups, categoryOptions: (result.categories || []).map((item) => { const code = displayText(item.category_code, ''); const fromCatalog = getCategoryDisplay(categoryOptions, code); const chipName = fromCatalog && fromCatalog !== '未分类' ? leafCategoryNameHint(fromCatalog) || fromCatalog : resolveCategoryDisplayName(code, item.category_name); return { category_code: code, category_name: chipName, count: item.count, }; }), ...summary, }); this.emitProgress({ heroDate: summary.heroDate, completedCount: summary.completedCount, totalCount: summary.totalCount, }); this.emitBadge(result.pending_count); } catch (err) { if (!silent) { this.setData({ error: err.message || '加载失败', categoryGroups: [], categoryOptions: [] }); } this.emitProgress({ completedCount: 0, totalCount: 0, }); } finally { if (!silent) { this.setData({ loading: false }); } } }, onCategoryFilter(e) { const code = e.currentTarget.dataset.code || ''; if (code === this.data.selectedCategory) return; this.expandedCategoryKeys.clear(); this._categoryExpandInited = false; this.setData({ selectedCategory: code }, () => this.loadRows()); }, toggleCategory(e) { const categoryKey = e.currentTarget.dataset.category; const group = this.data.categoryGroups.find((item) => item.categoryKey === categoryKey); if (!group || group.pendingCount === 0) return; if (this.expandedCategoryKeys.has(categoryKey)) { this.expandedCategoryKeys.delete(categoryKey); } else { this.expandedCategoryKeys.add(categoryKey); } this.setData({ categoryGroups: applyCategoryCollapseState(this.data.categoryGroups, this.expandedCategoryKeys), }); }, findRow(purchaseCode) { for (const group of this.data.categoryGroups) { for (const product of group.productGroups || []) { const row = product.items.find((item) => item.purchase_code === purchaseCode); if (row) return row; } const row = (group.items || []).find((item) => item.purchase_code === purchaseCode); if (row) return row; } return null; }, findProductGroup(productKey) { for (const group of this.data.categoryGroups) { const product = (group.productGroups || []).find((p) => p.productKey === productKey); if (product) return product; } return null; }, updateGroupsRow(purchaseCode, patch) { const categoryOptions = this.data.catalogCategoryOptions || buildCategoryPickerOptions([]); this.setData({ categoryGroups: this.data.categoryGroups.map((group) => { const items = (group.items || []).map((row) => { if (row.purchase_code !== purchaseCode) return row; return enrichPurchaseRowCategory({ ...row, ...patch }, categoryOptions); }); return { ...group, items, productGroups: buildCategoryProductGroups( items, this.data.aggregateSameProducts !== false ).map((pg) => { const prev = (group.productGroups || []).find((p) => p.productKey === pg.productKey); const next = decorateProductGroupDisplay(pg, group.categoryName); if (!prev) return next; return { ...next, actual_qty_input: prev.actual_qty_input, actual_price_input: prev.actual_price_input, unit: prev.unit, unitIndex: prev.unitIndex, unitOptions: prev.unitOptions, collapsedChildren: prev.collapsedChildren, }; }), }; }), }); }, updateProductGroup(productKey, patch) { this.setData({ categoryGroups: this.data.categoryGroups.map((group) => ({ ...group, productGroups: (group.productGroups || []).map((pg) => pg.productKey === productKey ? { ...pg, ...patch } : pg ), })), }); }, toggleProductChildren(e) { const productKey = e.currentTarget.dataset.productKey; const product = this.findProductGroup(productKey); if (!product) return; this.updateProductGroup(productKey, { collapsedChildren: !product.collapsedChildren }); }, onProductActualInput(e) { const { productKey, field } = e.currentTarget.dataset; this.updateProductGroup(productKey, { [field]: e.detail.value }); }, onProductUnitChange(e) { const productKey = e.currentTarget.dataset.productKey; const product = this.findProductGroup(productKey); if (!product) return; const index = Number(e.detail.value) || 0; const options = product.unitOptions || getUnitDictionaryLabels(); const unit = options[index] || product.unit || '个'; this.updateProductGroup(productKey, { unit, unitIndex: index }); }, resolvePurchaseCategory(row) { const categoryOptions = this.data.catalogCategoryOptions || buildCategoryPickerOptions([]); let resolved = applyCategoryInput(row, row.category_label || row.category_name, categoryOptions); if (!resolved.category_code) { const name = String(resolved.category_name || resolved.category_label || '').trim(); const matched = name ? findCategoryOptionByName(name, categoryOptions) : null; if (matched?.category_code) { resolved = applyManualCategory(resolved, matched); } } return resolved; }, closeCategoryDropdown() { this.setData({ activeCategoryPurchaseCode: '', categoryDropdownQuery: '', categoryDropdownOptions: [], categoryDropdownCurrentCode: '', categorySearchFocus: false, }); }, toggleCategoryDropdown(e) { const purchaseCode = e.currentTarget.dataset.code; if (this.data.activeCategoryPurchaseCode === purchaseCode) { this.closeCategoryDropdown(); return; } const isSpi = purchaseCode === SPI_CATEGORY_TARGET; if (isSpi) this.closeSpiUnitDropdown(); const row = isSpi ? this.data.spiForm : (this.findRow(purchaseCode) || {}); this.setData({ activeCategoryPurchaseCode: purchaseCode, categoryDropdownQuery: '', categoryDropdownOptions: filterCategoryOptions('', this.data.catalogCategoryOptions, 999), categoryDropdownCurrentCode: row.category_code || '', categorySearchFocus: false, }, () => { setTimeout(() => { if (this.data.activeCategoryPurchaseCode === purchaseCode) { this.setData({ categorySearchFocus: true }); } }, 80); }); }, onCategorySearchFocus() { if (this.data.categorySearchFocus) { this.setData({ categorySearchFocus: false }); } }, onCategoryDropdownSearch(e) { const value = e.detail.value; if (value === this.data.categoryDropdownQuery) return; this.setData({ categoryDropdownQuery: value, categoryDropdownOptions: filterCategoryOptions(value, this.data.catalogCategoryOptions, 999), }); }, pickCategoryFromDropdown(e) { const sidx = Number(e.currentTarget.dataset.sidx); const option = this.data.categoryDropdownOptions[sidx]; const purchaseCode = this.data.activeCategoryPurchaseCode; if (!option || !purchaseCode) { this.closeCategoryDropdown(); return; } if (purchaseCode === SPI_CATEGORY_TARGET) { this.setData({ 'spiForm.category_code': option.category_code, 'spiForm.category_label': option.label || option.category_name, }); this.closeCategoryDropdown(); return; } const row = this.findRow(purchaseCode); if (!row) { this.closeCategoryDropdown(); return; } const next = applyManualCategory(row, option); this.updateGroupsRow(purchaseCode, next); this.closeCategoryDropdown(); }, openQuickCategoryFromDropdown() { const purchaseCode = this.data.activeCategoryPurchaseCode; const presetName = String(this.data.categoryDropdownQuery || '').trim(); this.closeCategoryDropdown(); this.setData({ showQuickCategoryModal: true, quickCategoryTargetCode: purchaseCode, quickCategoryName: presetName, }); }, openQuickCategory(e) { const purchaseCode = e.currentTarget.dataset.code; this.closeCategoryDropdown(); this.setData({ showQuickCategoryModal: true, quickCategoryTargetCode: purchaseCode, quickCategoryName: '', }); }, closeQuickCategoryModal() { if (this.data.creatingCategory) return; this.setData({ showQuickCategoryModal: false, quickCategoryTargetCode: '', quickCategoryName: '', }); }, onQuickCategoryNameInput(e) { this.setData({ quickCategoryName: e.detail.value }); }, async submitQuickCategory() { const name = String(this.data.quickCategoryName || '').trim(); if (!name) { wx.showToast({ title: '请输入分类名称', icon: 'none' }); return; } this.setData({ creatingCategory: true }); try { const result = await createPurchaseCategory(name); const created = result.data || {}; const catalogCategoryOptions = buildCategoryPickerOptions([ ...(this.data.catalogCategoryOptions || []).filter((item) => item.category_code), created, ]); const purchaseCode = this.data.quickCategoryTargetCode; if (purchaseCode === SPI_CATEGORY_TARGET) { const applied = applyManualCategory({}, created); this.setData({ catalogCategoryOptions, showQuickCategoryModal: false, quickCategoryTargetCode: '', quickCategoryName: '', 'spiForm.category_code': applied.category_code, 'spiForm.category_label': applied.category_label, }); } else { if (purchaseCode) { const row = this.findRow(purchaseCode); if (row) { this.updateGroupsRow(purchaseCode, applyManualCategory(row, created)); } } this.setData({ catalogCategoryOptions, showQuickCategoryModal: false, quickCategoryTargetCode: '', quickCategoryName: '', }); } wx.showToast({ title: '分类已创建', icon: 'success' }); } catch (err) { wx.showToast({ title: err.message || '创建失败', icon: 'none' }); } finally { this.setData({ creatingCategory: false }); } }, async skipProductGroup(e) { if (this.data.batchSubmitting) return; const productKey = e.currentTarget.dataset.productKey; const product = this.findProductGroup(productKey); if (!product) return; const pending = (product.items || []).filter(canSkipWarehouseDemand); if (!pending.length) { wx.showToast({ title: '没有可跳过单据', icon: 'none' }); return; } const confirmed = await new Promise((resolve) => { wx.showModal({ title: '跳过成品自采', content: `「${displayText(product.productName, '商品')}」共 ${pending.length} 单将跳过,请用新增自采入库原料。`, success: (res) => resolve(Boolean(res.confirm)), fail: () => resolve(false), }); }); if (!confirmed) return; const listAll = String(this.properties.listScope || '') === 'all'; this.setData({ batchSubmitting: true }); wx.showLoading({ title: '提交中', mask: true }); let ok = 0; let lastError = ''; try { for (const row of pending) { try { await skipWarehouseDemandPurchase(row.purchase_code, listAll); ok += 1; } catch (err) { lastError = err.message || '失败'; } } } finally { wx.hideLoading(); this.setData({ batchSubmitting: false }); } wx.showToast({ title: ok === pending.length ? `已跳过 ${ok} 单` : `跳过 ${ok}/${pending.length}${lastError ? ':' + lastError : ''}`, icon: ok === pending.length ? 'success' : 'none', }); this.loadRows(); }, async skipWarehouseDemand(e) { const code = e.currentTarget.dataset.code; const listAll = String(this.properties.listScope || '') === 'all'; try { await skipWarehouseDemandPurchase(code, listAll); wx.showToast({ title: '已跳过', icon: 'success' }); this.loadRows(); } catch (err) { wx.showToast({ title: err.message || '跳过失败', icon: 'none' }); } }, chooseDirectPhoto(e) { const productKey = e.currentTarget.dataset.productKey; const product = this.findProductGroup(productKey); if (!product) return; const pending = (product.items || []).filter(canCompletePurchase); const codes = pending.map((row) => row.purchase_code).filter(Boolean); if (!codes.length) { wx.showToast({ title: '没有待完成单据', icon: 'none' }); return; } this.uploadDirectDeliveryPhotos(codes); }, chooseDirectPhotoRow(e) { const code = e.currentTarget.dataset.code; if (!code) return; this.uploadDirectDeliveryPhotos([code]); }, uploadDirectDeliveryPhotos(codes) { wx.chooseImage({ count: 3, sizeType: ['compressed'], sourceType: ['camera', 'album'], success: async (res) => { const paths = res.tempFilePaths || []; if (!paths.length) return; wx.showLoading({ title: '上传中…', mask: true }); try { for (const filePath of paths) { const content = await prepareOrderImageBase64(filePath); const ext = (filePath.split('.').pop() || 'jpg').toLowerCase(); await uploadPurchaseDirectDeliveryPhoto({ purchase_code: codes[0], extra_purchase_codes: codes.slice(1), content, ext, }); } wx.showToast({ title: '已拍照', icon: 'success' }); this.loadRows(); } catch (err) { wx.showToast({ title: err.message || '上传失败', icon: 'none' }); } finally { wx.hideLoading(); } }, fail: () => { wx.showToast({ title: '未选择照片', icon: 'none' }); }, }); }, async completeProductGroup(e) { if (this.data.batchSubmitting) return; const productKey = e.currentTarget.dataset.productKey; const product = this.findProductGroup(productKey); if (!product) return; if (product.needs_product_setup) { wx.showToast({ title: '未匹配商品请展开后逐单建档完成', icon: 'none' }); return; } const pending = (product.items || []).filter(canCompletePurchase); if (!pending.length) { wx.showToast({ title: '没有待完成单据', icon: 'none' }); return; } if (product.photoRequired && !(Number(product.photoCount) > 0)) { wx.showToast({ title: '该分类需要拍照,请先在完成旁拍照', icon: 'none' }); return; } const actualQty = Number(product.actual_qty_input); const actualPrice = Number(product.actual_price_input); if (!Number.isFinite(actualQty) || actualQty <= 0) { wx.showToast({ title: '请填写实采数量', icon: 'none' }); return; } if ( !Number.isFinite(actualPrice) || (this.data.allowZeroCost ? actualPrice < 0 : actualPrice <= 0) ) { wx.showToast({ title: '实采单价必须大于 0', icon: 'none' }); return; } const confirmed = await new Promise((resolve) => { wx.showModal({ title: '完成该商品', content: `将按合计实采完成「${displayText(product.productName, '商品')}」共 ${pending.length} 单,是否继续?`, success: (res) => resolve(Boolean(res.confirm)), fail: () => resolve(false), }); }); if (!confirmed) return; const splits = splitActualQtyByPlan( pending.map((row) => Number(row.purchase_qty) || 0), actualQty ); this.setData({ batchSubmitting: true }); this.stopAutoRefresh(); wx.showLoading({ title: '提交中', mask: true }); let ok = 0; let lastError = ''; try { for (let i = 0; i < pending.length; i += 1) { const row = pending[i]; try { await updatePurchaseOrderStatus({ purchase_code: row.purchase_code, status: 20, actual_qty: splits[i], actual_price: actualPrice, unit: displayText(product.unit, row.unit || '个'), }); ok += 1; } catch (err) { lastError = err.message || '失败'; } } } finally { wx.hideLoading(); this.setData({ batchSubmitting: false }); this.startAutoRefresh(); } if (ok === pending.length) { wx.showToast({ title: `已完成 ${ok} 单`, icon: 'success' }); } else { wx.showToast({ title: `完成 ${ok}/${pending.length}${lastError ? ':' + lastError : ''}`, icon: 'none', duration: 3000, }); } this.loadRows(); }, async completeAllPending() { if (this.data.batchSubmitting) return; const products = []; for (const group of this.data.categoryGroups) { for (const product of group.productGroups || []) { if ((product.pendingCount || 0) > 0 && !product.needs_product_setup) { products.push(product); } } } if (!products.length) { wx.showToast({ title: '暂无待完成商品', icon: 'none' }); return; } const confirmed = await new Promise((resolve) => { wx.showModal({ title: '一键全部完成', content: `将按各商品合计实采完成 ${products.length} 类商品,是否继续?`, success: (res) => resolve(Boolean(res.confirm)), fail: () => resolve(false), }); }); if (!confirmed) return; this.setData({ batchSubmitting: true }); this.stopAutoRefresh(); wx.showLoading({ title: '批量完成中', mask: true }); let okGroups = 0; let skippedGroups = 0; let failedGroups = 0; try { for (const product of products) { const skipRows = (product.items || []).filter(canSkipWarehouseDemand); if (skipRows.length && product.warehouseDemandAll) { const listAll = String(this.properties.listScope || '') === 'all'; let groupOk = true; for (const row of skipRows) { try { await skipWarehouseDemandPurchase(row.purchase_code, listAll); } catch (_err) { groupOk = false; } } if (groupOk) okGroups += 1; else failedGroups += 1; continue; } const pending = (product.items || []).filter(canCompletePurchase); if (!pending.length) { skippedGroups += 1; continue; } if (product.photoRequired && !(Number(product.photoCount) > 0)) { skippedGroups += 1; continue; } const actualQty = Number(product.actual_qty_input); const actualPrice = Number(product.actual_price_input); // 与单行路径(updateStatus)同口径:开关开启时 0 合法、负数才拦。 // 否则「允许成本价为 0」时这些组会被**静默跳过**,只报"跳过 N(缺数量/单价)"。 if ( !Number.isFinite(actualQty) || actualQty <= 0 || !Number.isFinite(actualPrice) || (this.data.allowZeroCost ? actualPrice < 0 : actualPrice <= 0) ) { skippedGroups += 1; continue; } const splits = splitActualQtyByPlan( pending.map((row) => Number(row.purchase_qty) || 0), actualQty ); let groupOk = true; for (let i = 0; i < pending.length; i += 1) { try { await updatePurchaseOrderStatus({ purchase_code: pending[i].purchase_code, status: 20, actual_qty: splits[i], actual_price: actualPrice, unit: displayText(product.unit, pending[i].unit || '个'), }); } catch (_err) { groupOk = false; } } if (groupOk) okGroups += 1; else failedGroups += 1; } } finally { wx.hideLoading(); this.setData({ batchSubmitting: false }); this.startAutoRefresh(); } const parts = [`成功 ${okGroups}`]; if (skippedGroups) parts.push(`跳过 ${skippedGroups}(缺数量/单价)`); if (failedGroups) parts.push(`失败 ${failedGroups}`); wx.showToast({ title: `${parts.join(',')} / 共 ${products.length} 类`, icon: 'none', duration: 3500, }); this.loadRows(); }, async updateStatus(e) { if (this.data.batchSubmitting) return; const { code, status } = e.currentTarget.dataset; const row = this.findRow(code); const actualQty = resolveActualQty(row); const actualPrice = resolveActualPrice(row); if (Number(status) === 20) { if (!actualQty || actualQty <= 0) { wx.showToast({ title: '请填写实采数量', icon: 'none' }); return; } if ( !Number.isFinite(actualPrice) || (this.data.allowZeroCost ? actualPrice < 0 : actualPrice <= 0) ) { wx.showToast({ title: '实采单价必须大于 0', icon: 'none' }); return; } if (needsDirectDeliveryPhoto(row) && directDeliveryPhotoCount(row) <= 0) { wx.showToast({ title: '该分类需要拍照,请先点拍照', icon: 'none' }); return; } if (row?.needs_product_setup) { const itemName = displayText(row.item_name_input, '').trim(); const resolvedCategory = this.resolvePurchaseCategory(row); if (!itemName) { wx.showToast({ title: '请填写商品名称', icon: 'none' }); return; } if (!resolvedCategory.category_code) { wx.showToast({ title: '请选择或新建商品分类', icon: 'none' }); return; } } } this.setData({ batchSubmitting: true }); try { const payload = { purchase_code: code, status: Number(status), actual_qty: actualQty, actual_price: actualPrice, unit: displayText(row?.unit, '个'), }; if (row?.needs_product_setup) { const resolvedCategory = this.resolvePurchaseCategory(row); payload.item_name = displayText(row.item_name_input, '').trim(); payload.category_code = displayText(resolvedCategory.category_code, '').trim(); payload.category_name = displayText(resolvedCategory.category_name || resolvedCategory.category_label, '').trim(); } const result = await updatePurchaseOrderStatus(payload); const createdNote = result?.sku_created ? ',已新建商品' : ''; if (result && result.needs_customer_price) { wx.showToast({ title: '已按实采回写,请补客户单价' + createdNote, icon: 'none', duration: 3000, }); } else { wx.showToast({ title: (Number(status) === 20 && Number(row?.purchase_status) === 32 ? '已重新提交采购,待仓管验收' : row?.direct_delivery ? '采购完成,商品直送不进仓' : '采购完成,待仓管验收') + createdNote, icon: 'success', }); } this.loadRows(); } catch (err) { wx.showToast({ title: err.message || '更新失败', icon: 'none' }); } finally { this.setData({ batchSubmitting: false }); } }, onUnitChange(e) { const { code } = e.currentTarget.dataset; const index = Number(e.detail.value) || 0; const row = this.findRow(code); if (!row) return; const options = row.unitOptions || getUnitDictionaryLabels(); const unit = options[index] || row.unit || '个'; this.updateGroupsRow(code, { unit, unitIndex: index }); }, onActualInput(e) { const { code, field } = e.currentTarget.dataset; const value = e.detail.value; this.updateGroupsRow(code, { [field]: value }); }, onItemNameInput(e) { const { code } = e.currentTarget.dataset; const value = e.detail.value; this.updateGroupsRow(code, { item_name_input: value, item_name: value }); }, async assignToSupplier(e) { const { code } = e.currentTarget.dataset; if (this.data.assignSubmittingCode) return; const row = this.findRow(code); if (!row || !canAssignSupplier(row)) return; try { this.setData({ assignSubmittingCode: code }); const result = await fetchPurchaseAssignSuppliers(code); const suppliers = result.suppliers || []; if (!suppliers.length) { wx.showToast({ title: '暂无可分配供应商,请继续自采', icon: 'none' }); return; } const pickAndAssign = async (supplierCode) => { await assignPurchaseToSupplier({ purchase_code: code, supplier_code: supplierCode, }); wx.showToast({ title: '已转供应商备货', icon: 'success' }); this.loadRows(); }; if (suppliers.length === 1) { const only = suppliers[0]; const confirmed = await new Promise((resolve) => { wx.showModal({ title: '转供应商', content: `确定转给「${only.supplier_name}」备货吗?`, success: (res) => resolve(Boolean(res.confirm)), }); }); if (!confirmed) return; await pickAndAssign(only.supplier_code); return; } wx.showActionSheet({ itemList: suppliers.map((item) => item.is_order_supplier ? `${item.supplier_name}(订单供应商)` : item.supplier_name ), success: async (res) => { const selected = suppliers[res.tapIndex]; if (!selected) return; await pickAndAssign(selected.supplier_code); }, }); } catch (err) { wx.showToast({ title: err.message || '转供应商失败', icon: 'none' }); } finally { this.setData({ assignSubmittingCode: '' }); } } }, });