const { fetchSupplierPreparations, updateSupplierPreparationStatus, amendSupplierPreparationPrice, uploadSupplierQualityReport, uploadQualityReportStorageFile, confirmSupplierQualityReportHits, discardSupplierQualityReport, fetchMobileRoles, fetchUnits, } = require('../../utils/request'); const { compressOrderImage } = require('../../utils/orderImage'); const config = require('../../config'); const { getSession, setSession } = require('../../utils/auth'); const { ensureMobileRole } = require('../../utils/roleGuard'); const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate'); const { buildFeaturePatchFromPayload } = require('../../utils/roleFeatures'); const { buildUnitPicker, ensureUnitDictionary, getUnitDictionaryLabels } = require('../../utils/units'); const { submitCompleteWithOverQtyConfirm, } = require('../../utils/prepSupplyOverQty'); const { buildSimpleXlsxBytes } = require('../../utils/simpleXlsx'); const { printHistory } = require('../../utils/printHistory'); const STATUS_TEXT = { 10: '待供货', 20: '供货中', 30: '已完成', 40: '缺货', }; const WEEKDAY = ['日', '一', '二', '三', '四', '五', '六']; const PERIOD_OPTIONS = [ { key: 'today', label: '今天' }, { key: 'week', label: '本周' }, { key: 'month', label: '本月' }, { key: 'custom', label: '选择起止日期' }, ]; 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 getWeekStartDate() { const date = new Date(); const weekday = date.getDay(); const diff = weekday === 0 ? 6 : weekday - 1; date.setDate(date.getDate() - diff); return formatLocalDate(date); } function getMonthStartDate() { const date = new Date(); return formatLocalDate(new Date(date.getFullYear(), date.getMonth(), 1)); } function resolvePeriodRange(preset) { const today = formatLocalDate(); switch (preset) { case 'today': return { from: today, to: today }; case 'week': return { from: getWeekStartDate(), to: today }; case 'month': return { from: getMonthStartDate(), to: today }; default: return { from: today, to: today }; } } function formatDayLabel(dayKey) { if (!dayKey) return '未知日期'; const today = formatLocalDate(); const yesterdayDate = new Date(); yesterdayDate.setDate(yesterdayDate.getDate() - 1); const yesterday = formatLocalDate(yesterdayDate); if (dayKey === today) return '今天'; if (dayKey === yesterday) return '昨天'; const parts = dayKey.split('-'); if (parts.length !== 3) return dayKey; const date = new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2])); const weekday = WEEKDAY[date.getDay()] || ''; return `${Number(parts[1])}月${Number(parts[2])}日 周${weekday}`; } function formatPeriodLabel(from, to) { if (!from || !to) return ''; if (from === to) return formatDayLabel(from); return `${from} 至 ${to}`; } function collectAiProductNames(data) { const out = []; const push = (v) => { if (Array.isArray(v)) { v.forEach(push); return; } const s = String(v || '').trim(); if (s) out.push(s); }; if (!data) return out; push(data.product_name); const raw = data.ai_raw; if (raw && typeof raw === 'object') { push(raw.product_name); push(raw.product_names); } return [...new Set(out)]; } function formatQualityReportResultContent(data) { const d = data || {}; const lines = []; if (d.validity_label) lines.push(d.validity_label); if (d.tested_at) lines.push(d.tested_at); if (d.valid_from || d.valid_to) { lines.push([d.valid_from, d.valid_to].filter(Boolean).join(' ~ ')); } const hitNames = (Array.isArray(d.proposed_hits) ? d.proposed_hits : []) .map((h) => (h && (h.product_name || h.sku_code)) || '') .map((s) => String(s).trim()) .filter(Boolean); const names = hitNames.length ? hitNames : collectAiProductNames(d); if (names.length) lines.push(names.join('、')); return lines.join('\n') || (d.validity_label || ''); } function buildReportSheetHits(candidates, proposed) { const checked = new Set((proposed || []).map((h) => String(h && h.id))); return (candidates || []).map((h) => ({ id: String(h.id), name: String((h && (h.product_name || h.sku_code)) || '').trim(), checked: checked.has(String(h.id)), })); } function formatReportSheetMeta(data) { const d = data || {}; const parts = []; if (d.validity_label) parts.push(d.validity_label); if (d.tested_at) parts.push(d.tested_at); if (d.valid_from || d.valid_to) { parts.push([d.valid_from, d.valid_to].filter(Boolean).join(' ~ ')); } return parts.join(' '); } function absolutizeMediaUrl(url) { const raw = String(url || '').trim(); if (!raw) return ''; if (/^https?:\/\//i.test(raw)) return raw; const apiBase = String(config.apiBase || '').replace(/\/+$/, ''); const origin = apiBase.replace(/\/api$/i, ''); if (raw.startsWith('/')) return `${origin}${raw}`; return `${apiBase}/${raw.replace(/^\/+/, '')}`; } function isPdfUrl(url) { return /\.pdf($|\?)/i.test(String(url || '')); } function mapReportFiles(urls) { return (Array.isArray(urls) ? urls : []) .map((u) => absolutizeMediaUrl(u)) .filter(Boolean) .map((url) => ({ url, isPdf: isPdfUrl(url) })); } function flattenArchiveExportRows(dayGroups) { const rows = []; for (const group of dayGroups || []) { for (const item of group.items || []) { const qty = Number(item.prepare_qty); const price = Number(item.purchase_price); let amount = ''; if (typeof item.total_price === 'number' && Number.isFinite(item.total_price)) { amount = Math.round(item.total_price * 100) / 100; } else if (Number.isFinite(qty) && Number.isFinite(price) && qty > 0 && price > 0) { amount = Math.round(qty * price * 100) / 100; } rows.push([ group.dayKey || '', item.item_name || item.display_name || '商品', Number.isFinite(qty) ? qty : 0, item.unit || '', Number.isFinite(price) ? price : 0, amount, ]); } } return rows; } function toInputString(value, fallback) { if (value !== undefined && value !== null && value !== '') { return String(value); } if (fallback !== undefined && fallback !== null && fallback !== '') { return String(fallback); } return ''; } function displayPrice(row) { const saved = Number(row?.purchase_price); if (Number.isFinite(saved) && saved > 0) return saved; return Number(row?.suggested_price ?? 0); } function resolvePrepareQty(row) { const raw = row?.prepare_qty_input; if (raw !== undefined && raw !== null && String(raw).trim() !== '') { return Number(raw); } return Number(row?.prepare_qty); } function resolvePurchasePrice(row) { const raw = row?.purchase_price_input; if (raw !== undefined && raw !== null && String(raw).trim() !== '') { return Number(raw); } const saved = Number(row?.purchase_price); if (Number.isFinite(saved) && saved > 0) return saved; return Number(row?.suggested_price ?? 0); } function formatPriceHint(price, unit) { const n = Number(price); if (!Number.isFinite(n) || n <= 0) return ''; const text = Number.isInteger(n) ? String(n) : n.toFixed(1).replace(/\.0$/, ''); return `¥${text}/${unit || '个'}`; } function formatMoney(amount) { if (!Number.isFinite(amount) || amount <= 0) return '0.00'; return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } function rowLineAmount(row) { const qty = resolvePrepareQty(row); const price = resolvePurchasePrice(row); if (!Number.isFinite(qty) || qty <= 0 || !Number.isFinite(price) || price <= 0) return 0; return qty * price; } function decoratePrepRow(row, allowZeroCost = false) { const priceHint = displayPrice(row); const baseStatus = STATUS_TEXT[row.prepare_status] || '未知'; const statusText = row.return_code ? `验收退回·${baseStatus}` : baseStatus; const supplyUnit = String(row.unit || row.order_unit || '个').trim() || '个'; const { unit, unitOptions, unitIndex } = buildUnitPicker(supplyUnit, getUnitDictionaryLabels()); const orderQty = row.order_qty != null && row.order_qty !== '' ? row.order_qty : row.prepare_qty; const orderUnit = String(row.order_unit || supplyUnit).trim() || supplyUnit; const prepQtyNum = Number(row.prepare_qty); const priceNum = Number(row.purchase_price); const hasTotal = Number.isFinite(prepQtyNum) && prepQtyNum > 0 && Number.isFinite(priceNum) && (allowZeroCost ? priceNum >= 0 : priceNum > 0); return { ...row, statusText, order_qty: orderQty, order_unit: orderUnit, unit, unitIndex, unitOptions, priceHintText: formatPriceHint(priceHint, unit), total_price: hasTotal ? prepQtyNum * priceNum : null, total_price_text: hasTotal ? (prepQtyNum * priceNum).toFixed(2) : '—', prepare_qty_input: toInputString(row.prepare_qty, row.prepare_qty), purchase_price_input: toInputString( allowZeroCost && Number(row.purchase_price) === 0 ? 0 : Number(row.purchase_price) > 0 ? row.purchase_price : '', priceHint ), amendStatus: row.amend_request ? Number(row.amend_request.status) : 0, amendStatusLabel: row.amend_request ? row.amend_request.status_label || '' : '', amendPending: row.amend_request && Number(row.amend_request.status) === 10, amendRejected: row.amend_request && Number(row.amend_request.status) === 30, amendRemark: row.amend_request ? row.amend_request.review_remark || '' : '', orderItemRemark: String(row.order_item_remark || '').trim(), requires_quality_report: Boolean(row.requires_quality_report), report_covered: Boolean(row.report_covered), quality_report_type: row.quality_report_type || '', quality_report_file_urls: row.quality_report && Array.isArray(row.quality_report.file_urls) ? row.quality_report.file_urls.map(absolutizeMediaUrl).filter(Boolean) : [], quality_report_expired: Boolean( row.quality_report && row.quality_report.validity_status === 'expired' ), quality_report_result: row.quality_report ? { report_label: row.quality_report.report_label || '', validity_status: row.quality_report.validity_status || '', validity_label: row.quality_report.validity_label || '', tested_at: row.quality_report.tested_at || '', valid_from: row.quality_report.valid_from || '', valid_to: row.quality_report.valid_to || '', product_name: row.quality_report.product_name || '', } : null, }; } /** 刷新列表前收集未完成行的本地草稿,避免点「完成」后其它行已填价被冲掉 */ function collectRowDrafts(dayGroups) { const drafts = new Map(); for (const group of dayGroups || []) { for (const row of group.items || []) { if (!row || !row.id) continue; drafts.set(String(row.id), { prepare_qty_input: row.prepare_qty_input, purchase_price_input: row.purchase_price_input, unit: row.unit, unitIndex: row.unitIndex, }); } } return drafts; } function applyRowDrafts(rows, drafts, { onlyPending = true } = {}) { if (!drafts || drafts.size === 0) return rows; return (rows || []).map((row) => { if (onlyPending && Number(row.prepare_status) >= 30) return row; const draft = drafts.get(String(row.id)); if (!draft) return row; const next = { ...row }; if (draft.prepare_qty_input !== undefined && draft.prepare_qty_input !== null) { next.prepare_qty_input = draft.prepare_qty_input; } if (draft.purchase_price_input !== undefined && draft.purchase_price_input !== null) { next.purchase_price_input = draft.purchase_price_input; } if (draft.unit) { const options = next.unitOptions || getUnitDictionaryLabels(); const idx = options.indexOf(draft.unit); next.unit = draft.unit; next.unitIndex = idx >= 0 ? idx : Number(draft.unitIndex) || 0; next.priceHintText = formatPriceHint(displayPrice(next), next.unit); } return next; }); } function buildHeroParts(dayGroups) { const today = formatLocalDate(); const todayGroup = (dayGroups || []).find((g) => g.dayKey === today); const focus = todayGroup || (dayGroups && dayGroups[0]); if (!focus || !focus.dayKey) { const d = new Date(); return { heroLabel: '今日供货', heroDate: `${d.getMonth() + 1}月${d.getDate()}日 · 周${WEEKDAY[d.getDay()]}`, }; } const parts = String(focus.dayKey).split('-'); if (parts.length === 3) { const date = new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2])); return { heroLabel: focus.dayKey === today ? '今日供货' : '供货', heroDate: `${Number(parts[1])}月${Number(parts[2])}日 · 周${WEEKDAY[date.getDay()] || ''}`, }; } return { heroLabel: '今日供货', heroDate: focus.dayLabel || '' }; } function computeActiveSummary(dayGroups) { let totalCount = 0; let completedCount = 0; let pendingCount = 0; let todayTotal = 0; for (const group of dayGroups || []) { for (const row of group.items || []) { totalCount += 1; const status = Number(row.prepare_status); if (status >= 30) { completedCount += 1; } else { pendingCount += 1; } todayTotal += rowLineAmount(row); } } return { ...buildHeroParts(dayGroups), totalCount, completedCount, pendingCount, todayTotalText: formatMoney(todayTotal), }; } function groupByDay(rows, dayField = 'task_day') { const map = new Map(); for (const row of rows) { const dayKey = row[dayField] || row.task_day || row.archive_day || 'unknown'; if (!map.has(dayKey)) { map.set(dayKey, { dayKey, dayLabel: formatDayLabel(dayKey), pendingCount: 0, items: [], totalAmount: 0, }); } const group = map.get(dayKey); group.items.push(row); if (Number(row.prepare_status) < 30) { group.pendingCount += 1; } if (typeof row.total_price === 'number' && Number.isFinite(row.total_price)) { group.totalAmount += row.total_price; } } return Array.from(map.values()) .map((group) => ({ ...group, totalAmountText: group.totalAmount > 0 ? group.totalAmount.toFixed(2) : '', })) .sort((a, b) => b.dayKey.localeCompare(a.dayKey)); } function applyDayCollapseState(groups, expandedDayKeys, { expandAllPending = false } = {}) { const activeKeys = new Set(groups.map((g) => g.dayKey)); for (const key of [...expandedDayKeys]) { if (!activeKeys.has(key)) expandedDayKeys.delete(key); } const hasUserExpanded = expandedDayKeys.size > 0; for (const group of groups) { if (expandAllPending && !hasUserExpanded) { expandedDayKeys.add(group.dayKey); continue; } if (group.pendingCount > 0 && !hasUserExpanded) { expandedDayKeys.add(group.dayKey); } } return groups.map((group) => { if (group.pendingCount === 0 && !expandAllPending) { return { ...group, collapsed: true }; } return { ...group, collapsed: !expandedDayKeys.has(group.dayKey) }; }); } Component({ options: { addGlobalClass: true }, properties: { embedded: { type: Boolean, value: false }, hideProgress: { type: Boolean, value: false }, initialTab: { type: String, value: 'active' }, }, data: { tab: 'active', dayGroups: [], archiveFrom: '', archiveTo: '', archivePeriod: 'today', archivePeriodLabel: '', periodOptions: PERIOD_OPTIONS, archiveSummary: '', exporting: false, printing: false, priceAmendDeliveryDate: '', priceAmendWindowHours: 0, priceAmendEnabled: false, confirmRequired: true, /** 「允许成本价为 0」开关(分公司级,默认关闭):由列表接口回传 */ allowZeroCost: false, loading: false, error: '', submitting: false, heroLabel: '今日供货', heroDate: '', totalCount: 0, completedCount: 0, pendingCount: 0, todayTotalText: '0.00', reportSheetVisible: false, reportSheetTitle: '', reportSheetMeta: '', reportSheetExpired: false, reportSheetHits: [], reportSheetFiles: [], reportSheetReportId: '', reportSheetPrepId: '', reportSheetReportType: '', reportSheetMode: 'confirm', reportSheetBusy: false, }, lifetimes: { attached() { this.expandedDayKeys = new Set(); this.archivedExpandedDayKeys = new Set(); this.priceAmendExpandedDayKeys = new Set(); this.applyInitialTab(this.properties.initialTab); this.onPanelShow(); }, }, observers: { initialTab(tab) { if (!tab) return; if (tab === this.data.tab) return; this.applyInitialTab(tab); this.onPanelShow(); }, }, pageLifetimes: { show() { this.onPanelShow(); }, }, methods: { applyInitialTab(tab) { const next = tab === 'archived' || tab === 'price_amend' ? tab : 'active'; if (next === 'archived' && (!this.data.archiveFrom || !this.data.archiveTo)) { this.initArchivePeriod('today'); } this.data.tab = next; this.setData({ tab: next }); }, 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, }); }, emitBadgeChange(count, badgeKey) { const key = String(badgeKey || '').trim() || 'preparationTaskCount'; const value = Number(count); if (Number.isFinite(value)) { this.triggerEvent('badgechange', { count: value, badgeKey: key }); return; } this.triggerEvent('badgechange', { badgeKey: key }); }, async onPanelShow() { if (!beginPanelShow(this)) return; try { const ok = await ensureMobileRole('supplier'); if (!ok) return; await Promise.all([ ensureUnitDictionary(fetchUnits), this.refreshPriceAmendFlag(), ]); if (this.data.tab === 'archived' && (!this.data.archiveFrom || !this.data.archiveTo)) { this.initArchivePeriod('today'); } await this.loadCurrentTab(); } finally { endPanelShow(this); } }, async refreshPriceAmendFlag() { const session = getSession() || {}; let enabled = false; try { const rolesResult = await fetchMobileRoles(); const patch = buildFeaturePatchFromPayload('supplier', rolesResult); enabled = patch.supplierPriceAmendEnabled === true; const features = { ...(rolesResult.supplier_features || session.supplier_features || {}), price_amend_enabled: enabled, }; setSession({ ...getSession(), supplier_features: features, }); } catch { // 拉角色失败时不沿用旧 true,避免关开关后仍显示入口 enabled = false; } this.setData({ priceAmendEnabled: enabled }); if (!enabled && this.data.tab === 'price_amend') { this.setData({ tab: 'active', dayGroups: [], priceAmendDeliveryDate: '' }); } return enabled; }, initArchivePeriod(preset) { const range = resolvePeriodRange(preset); this.setData({ archivePeriod: preset, archiveFrom: range.from, archiveTo: range.to, archivePeriodLabel: formatPeriodLabel(range.from, range.to), }); }, async loadCurrentTab() { if (this.data.tab === 'archived') { await this.loadArchivedRows(); return; } if (this.data.tab === 'price_amend') { await this.loadPriceAmendRows(); return; } await this.loadActiveRows(); }, switchTab(e) { const tab = e.currentTarget.dataset.tab; if (tab === this.data.tab) return; if (tab === 'price_amend' && !this.data.priceAmendEnabled) { wx.showToast({ title: '未开放追加改价', icon: 'none' }); return; } if (tab === 'archived' && (!this.data.archiveFrom || !this.data.archiveTo)) { this.initArchivePeriod('today'); } this.setData({ tab, error: '', dayGroups: [] }); this.loadCurrentTab(); }, async loadActiveRows() { if (!this.expandedDayKeys) this.expandedDayKeys = new Set(); this.setData({ loading: true, error: '', archiveSummary: '', priceAmendDeliveryDate: '' }); try { const session = getSession(); if (session?.role_type && session.role_type !== 'supplier') { this.setData({ error: '当前不是供应商工作台,请在工作台切换到「供应商」后再查看', dayGroups: [], }); return; } const drafts = collectRowDrafts(this.data.dayGroups); const result = await fetchSupplierPreparations({ view: 'active' }); const allowZeroCost = result.allow_zero_cost === true; const rows = applyRowDrafts( (result.data || []).map((row) => decoratePrepRow(row, allowZeroCost)), drafts, { onlyPending: true } ); const dayGroups = applyDayCollapseState(groupByDay(rows, 'task_day'), this.expandedDayKeys); this.setData({ dayGroups, confirmRequired: result.confirm_required !== false, allowZeroCost, ...computeActiveSummary(dayGroups), }, () => { this.emitProgress(); this.emitBadgeChange(this.data.pendingCount, 'preparationTaskCount'); }); } catch (err) { const message = err.statusCode === 403 ? '无权访问供货任务,请在工作台切换到「供应商」角色' : err.message || '加载失败'; this.setData({ error: message, dayGroups: [], ...computeActiveSummary([]) }, () => this.emitProgress()); } finally { this.setData({ loading: false }); } }, async loadPriceAmendRows() { if (!this.data.priceAmendEnabled) { this.emitBadgeChange(0, 'prepPriceAmendCount'); this.setData({ tab: 'active', dayGroups: [], priceAmendDeliveryDate: '', error: '', loading: false, }); await this.loadActiveRows(); return; } this.setData({ loading: true, error: '', archiveSummary: '' }); try { const drafts = collectRowDrafts(this.data.dayGroups); const result = await fetchSupplierPreparations({ view: 'price_amend' }); // 改价页行多为已完成单,仍需保留其它行本地未提交草稿 const rows = applyRowDrafts((result.data || []).map(decoratePrepRow), drafts, { onlyPending: false }); const dayGroups = applyDayCollapseState( groupByDay(rows, 'task_day'), this.priceAmendExpandedDayKeys || (this.priceAmendExpandedDayKeys = new Set()), { expandAllPending: true } ); this.setData({ dayGroups, priceAmendDeliveryDate: result.delivery_date || '', priceAmendWindowHours: Number(result.price_amend_window_hours) || 0, }); this.emitBadgeChange(rows.length, 'prepPriceAmendCount'); } catch (err) { if (err.statusCode === 403) { setSession({ ...getSession(), supplier_features: { ...(getSession()?.supplier_features || {}), price_amend_enabled: false, }, }); this.emitBadgeChange(0, 'prepPriceAmendCount'); this.setData({ priceAmendEnabled: false, tab: 'active', dayGroups: [], priceAmendDeliveryDate: '', error: '', }); await this.loadActiveRows(); return; } this.setData({ error: err.message || '加载失败', dayGroups: [], priceAmendDeliveryDate: '', }); } finally { this.setData({ loading: false }); } }, async loadArchivedRows() { const { archiveFrom, archiveTo } = this.data; if (!archiveFrom || !archiveTo) { this.setData({ dayGroups: [], error: '', loading: false, archiveSummary: '' }); return; } if (archiveFrom > archiveTo) { this.setData({ error: '开始日期不能晚于结束日期', dayGroups: [], archiveSummary: '' }); return; } this.setData({ loading: true, error: '', archivePeriodLabel: formatPeriodLabel(archiveFrom, archiveTo), priceAmendDeliveryDate: '', }); try { const result = await fetchSupplierPreparations({ view: 'archived', date_from: archiveFrom, date_to: archiveTo, }); const rows = (result.data || []).map(decoratePrepRow); const dayGroups = applyDayCollapseState( groupByDay(rows, 'archive_day'), this.archivedExpandedDayKeys || (this.archivedExpandedDayKeys = new Set()), { expandAllPending: true } ); const archiveSummary = rows.length ? `共 ${rows.length} 项 · ${dayGroups.length} 天` : ''; this.setData({ dayGroups, archiveSummary }); } catch (err) { this.setData({ error: err.message || '加载失败', dayGroups: [], archiveSummary: '' }); } finally { this.setData({ loading: false }); } }, pickArchivePeriod(e) { const preset = e.currentTarget.dataset.period; if (!preset || preset === this.data.archivePeriod) return; if (preset !== 'custom') { this.initArchivePeriod(preset); this.archivedExpandedDayKeys.clear(); this.loadArchivedRows(); return; } this.setData({ archivePeriod: 'custom' }); }, onArchiveFromChange(e) { const archiveFrom = e.detail.value; this.setData({ archiveFrom, archivePeriod: 'custom', archivePeriodLabel: formatPeriodLabel(archiveFrom, this.data.archiveTo), }); this.archivedExpandedDayKeys.clear(); this.loadArchivedRows(); }, onArchiveToChange(e) { const archiveTo = e.detail.value; this.setData({ archiveTo, archivePeriod: 'custom', archivePeriodLabel: formatPeriodLabel(this.data.archiveFrom, archiveTo), }); this.archivedExpandedDayKeys.clear(); this.loadArchivedRows(); }, async printArchiveList() { if (this.data.printing || this.data.exporting) return; const rows = flattenArchiveExportRows(this.data.dayGroups); if (!rows.length) { wx.showToast({ title: '该周期暂无历史订单记录', icon: 'none' }); return; } this.setData({ printing: true }); try { await printHistory( this, { rows, title: '安惟衡 · 历史订单', subtitle: `周期 ${this.data.archivePeriodLabel || ''}`, emptyText: '该周期暂无历史订单记录', fileName: 'prep-archive.pdf', }, () => this.pickBleDevice() ); } catch (err) { wx.hideLoading(); if (err && err.message !== '已取消') { wx.showToast({ title: err.message || '打印失败', icon: 'none' }); } } finally { this.setData({ printing: false }); } }, pickBleDevice() { const sheet = this.selectComponent('#blePicker'); if (!sheet || typeof sheet.pick !== 'function') { return Promise.resolve(null); } return sheet.pick(); }, async exportArchiveExcel() { if (this.data.exporting) return; const rows = flattenArchiveExportRows(this.data.dayGroups); if (!rows.length) { wx.showToast({ title: '该周期暂无历史订单记录', icon: 'none' }); return; } this.setData({ exporting: true }); wx.showLoading({ title: '正在导出', mask: true }); try { const bytes = buildSimpleXlsxBytes( '历史订单', ['供货日期', '商品名', '数量', '单位', '单价', '合计'], rows ); const filePath = `${wx.env.USER_DATA_PATH}/prep-archive.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({ exporting: false }); } }, toggleDayGroup(e) { const dayKey = e.currentTarget.dataset.day; const tab = this.data.tab; const expandedKeys = tab === 'archived' ? this.archivedExpandedDayKeys : tab === 'price_amend' ? this.priceAmendExpandedDayKeys : this.expandedDayKeys; const group = this.data.dayGroups.find((item) => item.dayKey === dayKey); if (!group) return; if (tab === 'active' && group.pendingCount === 0) return; if (expandedKeys.has(dayKey)) { expandedKeys.delete(dayKey); } else { expandedKeys.add(dayKey); } this.setData({ dayGroups: this.data.dayGroups.map((item) => item.dayKey === dayKey ? { ...item, collapsed: !item.collapsed } : item ), }); }, onFieldInput(e) { const { id, field } = e.currentTarget.dataset; const value = e.detail.value; const dayGroups = this.data.dayGroups; let gi = -1; let ri = -1; for (let g = 0; g < dayGroups.length; g += 1) { const idx = (dayGroups[g].items || []).findIndex((row) => row.id === id); if (idx >= 0) { gi = g; ri = idx; break; } } if (gi < 0 || ri < 0) return; const nextGroups = dayGroups.map((group, gIdx) => { if (gIdx !== gi) return group; return { ...group, items: group.items.map((row, rIdx) => (rIdx === ri ? { ...row, [field]: value } : row)), }; }); const patch = { [`dayGroups[${gi}].items[${ri}].${field}`]: value, }; if (this.data.tab === 'active') { Object.assign(patch, computeActiveSummary(nextGroups)); } // 同步内存结构,供完成提交/草稿合并读取(避免仅 path setData 后 this.data 滞后) this.data.dayGroups = nextGroups; this.setData(patch, () => { if (this.data.tab === 'active') this.emitProgress(); }); }, onUnitChange(e) { const { id } = e.currentTarget.dataset; const index = Number(e.detail.value) || 0; const dayGroups = this.data.dayGroups.map((group) => ({ ...group, items: group.items.map((row) => { if (row.id !== id) return row; const options = row.unitOptions || getUnitDictionaryLabels(); const unit = options[index] || options[0] || '个'; return { ...row, unit, unitIndex: index, priceHintText: formatPriceHint(displayPrice(row), unit), }; }), })); this.data.dayGroups = dayGroups; const patch = { dayGroups }; if (this.data.tab === 'active') Object.assign(patch, computeActiveSummary(dayGroups)); this.setData(patch, () => { if (this.data.tab === 'active') this.emitProgress(); }); }, findRowById(id) { for (const group of this.data.dayGroups) { const row = group.items.find((item) => item.id === id); if (row) return row; } return null; }, onReportTap(e) { if (this.data.submitting || this.data.reportSheetVisible) return; const id = e.currentTarget.dataset.id; if (!id) return; const row = this.findRowById(id); if (!row || !row.requires_quality_report) return; const reportType = row.quality_report_type || ''; if (row.report_covered) { const qr = row.quality_report_result || row.quality_report || {}; this.setData({ reportSheetVisible: true, reportSheetMode: 'view', reportSheetTitle: qr.report_label || '检验报告', reportSheetMeta: formatReportSheetMeta(qr), reportSheetExpired: qr.validity_status === 'expired', reportSheetHits: [], reportSheetFiles: mapReportFiles(row.quality_report_file_urls || []), reportSheetReportId: '', reportSheetPrepId: id, reportSheetReportType: reportType, reportSheetBusy: false, }); return; } this.pickAndUploadReport(id, reportType); }, pickAndUploadReport(id, reportType) { if (this.data.submitting) return; wx.showActionSheet({ itemList: ['图片', 'PDF'], success: (res) => { if (res.tapIndex === 1) { this.choosePdfThenUpload(id, reportType); return; } this.chooseImagesThenUpload(id, reportType); }, }); }, chooseImagesThenUpload(id, reportType) { wx.chooseMedia({ count: 3, mediaType: ['image'], sourceType: ['album', 'camera'], success: (res) => { const files = res.tempFiles || []; if (!files.length) return; this.uploadReportPayloads( id, reportType, files.map((file) => compressOrderImage(file.tempFilePath).then((path) => uploadQualityReportStorageFile(path, 'quality-report.jpg') ) ) ); }, }); }, choosePdfThenUpload(id, reportType) { wx.chooseMessageFile({ count: 3, type: 'file', extension: ['pdf'], success: (res) => { const files = (res.tempFiles || []).filter((file) => /\.pdf$/i.test(String((file && (file.name || file.path)) || '')) ); if (!files.length) { wx.showToast({ title: '请选择 PDF', icon: 'none' }); return; } this.uploadReportPayloads( id, reportType, files.map((file) => uploadQualityReportStorageFile(file.path, file.name || 'quality-report.pdf') ) ); }, }); }, uploadReportPayloads(id, reportType, payloadPromises) { if (this.data.submitting) return; this.setData({ submitting: true }); wx.showLoading({ title: '上传中', mask: true }); Promise.all(payloadPromises) .then((payloads) => uploadSupplierQualityReport({ preparation_id: id, files: payloads, report_type: reportType, defer_coverage: true, }) ) .then((result) => { const data = (result && result.data) || {}; const candidates = data.candidate_hits || data.proposed_hits || []; this.setData({ submitting: false, reportSheetVisible: true, reportSheetMode: 'confirm', reportSheetTitle: data.report_label || '检验报告', reportSheetMeta: formatReportSheetMeta(data), reportSheetExpired: data.validity_status === 'expired', reportSheetHits: buildReportSheetHits(candidates, data.proposed_hits || []), reportSheetFiles: mapReportFiles(data.file_urls || []), reportSheetReportId: data.id || '', reportSheetPrepId: id, reportSheetReportType: reportType || '', reportSheetBusy: false, }); }) .catch((err) => { wx.showToast({ title: (err && err.message) || '上传失败', icon: 'none' }); this.setData({ submitting: false }); }) .finally(() => wx.hideLoading()); }, preventSheetClose() {}, onReportFileTap(e) { const index = Number(e.currentTarget.dataset.index); const files = this.data.reportSheetFiles || []; const current = files[index]; if (!current || !current.url) return; if (current.isPdf) { wx.downloadFile({ url: current.url, success: (res) => { if (res.statusCode !== 200 || !res.tempFilePath) { wx.showToast({ title: '打开失败', icon: 'none' }); return; } wx.openDocument({ filePath: res.tempFilePath, fileType: 'pdf', showMenu: true, fail: () => wx.showToast({ title: '打开失败', icon: 'none' }), }); }, fail: () => wx.showToast({ title: '打开失败', icon: 'none' }), }); return; } const urls = files.filter((f) => f && !f.isPdf && f.url).map((f) => f.url); if (!urls.length) return; wx.previewImage({ urls, current: current.url }); }, onReportHitTap(e) { if (this.data.reportSheetBusy) return; const id = String(e.currentTarget.dataset.id || ''); if (!id) return; const hits = (this.data.reportSheetHits || []).map((h) => h.id === id ? { ...h, checked: !h.checked } : h ); this.setData({ reportSheetHits: hits }); }, onReportSheetCancel() { if (this.data.reportSheetBusy) return; const reportId = this.data.reportSheetReportId; const isView = this.data.reportSheetMode === 'view'; this.setData({ reportSheetBusy: true }); const done = () => this.setData({ reportSheetVisible: false, reportSheetHits: [], reportSheetFiles: [], reportSheetReportId: '', reportSheetPrepId: '', reportSheetReportType: '', reportSheetMode: 'confirm', reportSheetBusy: false, submitting: false, }); if (isView || !reportId) { done(); return; } discardSupplierQualityReport(reportId) .catch(() => null) .then(() => done()); }, onReportSheetConfirm() { if (this.data.reportSheetBusy) return; if (this.data.reportSheetMode === 'view') { const id = this.data.reportSheetPrepId; const reportType = this.data.reportSheetReportType || ''; this.setData( { reportSheetVisible: false, reportSheetHits: [], reportSheetFiles: [], reportSheetReportId: '', reportSheetBusy: false, submitting: false, }, () => { if (id) this.pickAndUploadReport(id, reportType); } ); return; } const reportId = this.data.reportSheetReportId; const prepIds = (this.data.reportSheetHits || []) .filter((h) => h.checked) .map((h) => h.id); if (!prepIds.length) { wx.showToast({ title: '请选择商品', icon: 'none' }); return; } if (!reportId) return; this.setData({ reportSheetBusy: true }); confirmSupplierQualityReportHits(reportId, prepIds) .then(() => { this.setData({ reportSheetVisible: false, reportSheetHits: [], reportSheetFiles: [], reportSheetReportId: '', reportSheetPrepId: '', reportSheetReportType: '', reportSheetMode: 'confirm', reportSheetBusy: false, submitting: false, }); return this.loadActiveRows(); }) .catch((err) => { wx.showToast({ title: (err && err.message) || '确认失败', icon: 'none' }); this.setData({ reportSheetBusy: false }); }); }, async completePreparation(e) { if (this.data.submitting || this.data.reportSheetVisible) return; const { id } = e.currentTarget.dataset; const row = this.findRowById(id); if (!row) return; const prepareQty = resolvePrepareQty(row); const purchasePrice = resolvePurchasePrice(row); const unit = String(row.unit || '').trim() || '个'; if (!Number.isFinite(prepareQty) || prepareQty <= 0) { wx.showToast({ title: '请填写有效数量', icon: 'none' }); return; } if ( !Number.isFinite(purchasePrice) || (this.data.allowZeroCost ? purchasePrice < 0 : purchasePrice <= 0) ) { wx.showToast({ title: '单价必须大于 0', icon: 'none' }); return; } const confirmed = await new Promise((resolve) => { wx.showModal({ title: '确认完成备货', content: `确认提交「${row.item_name || row.sku_code || '商品'}」数量 ${prepareQty}${unit}?`, success: (res) => resolve(Boolean(res.confirm)), fail: () => resolve(false), }); }); if (!confirmed) return; this.setData({ submitting: true }); wx.showLoading({ title: '提交中', mask: true }); try { const result = await submitCompleteWithOverQtyConfirm((confirmOverQty) => updateSupplierPreparationStatus({ id, status: 30, prepare_qty: prepareQty, purchase_price: purchasePrice, unit, ...(confirmOverQty ? { confirm_over_qty: true } : {}), }) ); if (result && result.needs_customer_price) { wx.showToast({ title: '已按实重回写,请采购补客户单价', icon: 'none', duration: 3000, }); } else { wx.showToast({ title: '已完成', icon: 'success' }); } await this.loadActiveRows(); this.emitBadgeChange(); } catch (err) { wx.showToast({ title: err.message || '更新失败', icon: 'none' }); } finally { wx.hideLoading(); this.setData({ submitting: false }); } }, async saveAmendPrice(e) { if (this.data.submitting) return; const { id } = e.currentTarget.dataset; const row = this.findRowById(id); if (!row) return; const prepareQty = resolvePrepareQty(row); const purchasePrice = resolvePurchasePrice(row); const unit = String(row.unit || '').trim() || '个'; if (!Number.isFinite(prepareQty) || prepareQty <= 0) { wx.showToast({ title: '请填写有效数量', icon: 'none' }); return; } if ( !Number.isFinite(purchasePrice) || (this.data.allowZeroCost ? purchasePrice < 0 : purchasePrice <= 0) ) { wx.showToast({ title: '单价必须大于 0', icon: 'none' }); return; } this.setData({ submitting: true }); try { const result = await amendSupplierPreparationPrice({ id, prepare_qty: prepareQty, purchase_price: purchasePrice, unit, }); const msg = (result && result.data && result.data.message) || (result && result.data && result.data.overwritten ? '已更新申请,待管理员确认' : '已提交,待管理员确认'); wx.showToast({ title: msg, icon: 'none', duration: 2500 }); this.loadPriceAmendRows(); } catch (err) { if (err.statusCode === 403) { this.setData({ priceAmendEnabled: false, tab: 'active' }); wx.showToast({ title: '功能已关闭', icon: 'none' }); this.emitBadgeChange(0, 'prepPriceAmendCount'); await this.loadActiveRows(); return; } wx.showToast({ title: err.message || '提交失败', icon: 'none' }); } finally { this.setData({ submitting: false }); } }, async markStockout(e) { if (this.data.submitting || this.data.reportSheetVisible) return; const { id } = e.currentTarget.dataset; const confirmed = await new Promise((resolve) => { wx.showModal({ title: '标记缺货', content: '确认标记缺货并流转自采?', success: (res) => resolve(Boolean(res.confirm)), fail: () => resolve(false), }); }); if (!confirmed) return; this.setData({ submitting: true }); try { await updateSupplierPreparationStatus({ id, status: 40, stockout_reason: 'no_stock' }); wx.showToast({ title: '已标记缺货并流转自采', icon: 'success' }); await this.loadActiveRows(); this.emitBadgeChange(); } catch (err) { wx.showToast({ title: err.message || '更新失败', icon: 'none' }); } finally { this.setData({ submitting: false }); } }, collectPendingActiveRows() { const rows = []; for (const group of this.data.dayGroups) { for (const row of group.items || []) { if (Number(row.prepare_status) < 30) rows.push(row); } } return rows; }, async submitTodaySupply() { if (this.data.submitting || this.data.reportSheetVisible || !this.data.confirmRequired) return; const pending = this.collectPendingActiveRows(); if (pending.length === 0) { wx.showToast({ title: '没有待提交项', icon: 'none' }); return; } const invalid = []; const ready = []; for (const row of pending) { const prepareQty = resolvePrepareQty(row); const purchasePrice = resolvePurchasePrice(row); const unit = String(row.unit || '').trim() || '个'; if ( !Number.isFinite(prepareQty) || prepareQty <= 0 || !Number.isFinite(purchasePrice) || (this.data.allowZeroCost ? purchasePrice < 0 : purchasePrice <= 0) ) { invalid.push(row.item_name || row.display_name || '商品'); continue; } ready.push({ row, prepareQty, purchasePrice, unit }); } if (ready.length === 0) { wx.showToast({ title: '请先填写有效数量与单价', icon: 'none' }); return; } const confirmed = await new Promise((resolve) => { const extra = invalid.length > 0 ? `\n另有 ${invalid.length} 项量价不完整将跳过` : ''; wx.showModal({ title: '提交今日供货', content: `确认提交 ${ready.length} 项供货?${extra}`, success: (res) => resolve(Boolean(res.confirm)), fail: () => resolve(false), }); }); if (!confirmed) return; this.setData({ submitting: true }); wx.showLoading({ title: '提交中', mask: true }); let ok = 0; let failMsg = ''; try { for (const item of ready) { try { await submitCompleteWithOverQtyConfirm((confirmOverQty) => updateSupplierPreparationStatus({ id: item.row.id, status: 30, prepare_qty: item.prepareQty, purchase_price: item.purchasePrice, unit: item.unit, ...(confirmOverQty ? { confirm_over_qty: true } : {}), }) ); ok += 1; } catch (err) { failMsg = err.message || '提交失败'; break; } } if (ok > 0 && !failMsg) { wx.showToast({ title: `已提交 ${ok} 项`, icon: 'success' }); } else if (ok > 0 && failMsg) { wx.showToast({ title: `已提交 ${ok} 项,其余失败:${failMsg}`, icon: 'none', duration: 3000 }); } else { wx.showToast({ title: failMsg || '提交失败', icon: 'none' }); } await this.loadActiveRows(); this.emitBadgeChange(); } finally { wx.hideLoading(); this.setData({ submitting: false }); } }, }, });