const { fetchOrderEntryCustomers, submitOrderEntryOrderWithConfirm, submitRetailOrderEntry, parseCustomerOrder, fetchOrderCategories, fetchCustomerMappingSkus, createOrderCategory, fetchCustomerOrderPrefill, fetchCustomerOrderBudget, fetchOrderEntryQuotePrices, searchOrderEntrySkus, upsertOrderEntryQuoteCosts, } = require('../../utils/request'); const { getSession } = require('../../utils/auth'); const { ensureMobileRole } = require('../../utils/roleGuard'); const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate'); const { PROCESSING_METHOD_OPTIONS } = require('../../utils/constants'); const { needsProcessingOwnerChoice, defaultProcessingOwnerForMethod, PROCESSING_OWNER_WAREHOUSE, PROCESSING_OWNER_SUPPLIER, } = require('../../utils/processingOwner'); const { buildCategoryPickerOptions, buildCategoryPickerLabels, enrichItemsCategoryFields, applyManualCategory, resolveItemsForSubmit, filterCategoryOptions, categoryInputValue, categoryDisplayText, categoryHasValue, mapParsedItem, stripAutoCategoriesUnlessManual, validateItemsCategories, emptyCategoryFields, mappingStatusText, } = require('../../utils/orderCategory'); const { prepareOrderImageBase64 } = require('../../utils/orderImage'); const MP3_RECORD_OPTIONS = { format: 'mp3', sampleRate: 16000, numberOfChannels: 1, duration: 60000, }; const ENTRY_MODES = [ { key: 'image', label: '拍照识别' }, { key: 'voice', label: '语音录入' }, { key: 'text', label: '文字录入' }, ]; const SHOW_COST_STORAGE_KEY = 'order_entry.show_cost_price'; /** 散客哨兵客户(与 Web / 后端 `RETAIL_CUSTOMER_CODE` 一致) */ const RETAIL_CUSTOMER_CODE = '__RETAIL__'; function isRetailCustomer(customer) { return String((customer && customer.customer_code) || '').trim() === RETAIL_CUSTOMER_CODE; } function readShowCostPrice() { try { const value = wx.getStorageSync(SHOW_COST_STORAGE_KEY); if (value === '' || value === undefined || value === null) return true; return value === '1' || value === true || value === 1; } catch { return true; } } function formatDateString(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 todayDateString() { return formatDateString(new Date()); } function tomorrowDateString() { const date = new Date(); date.setDate(date.getDate() + 1); return formatDateString(date); } function displayCustomerDeliveryDeadline(raw) { const trimmed = String(raw || '').trim(); if (!trimmed) return ''; const m = trimmed.match(/^(\d{1,2})[::](\d{2})(?::\d{2})?$/); if (!m) return trimmed; const hour = Number(m[1]); const minute = Number(m[2]); if (!Number.isInteger(hour) || !Number.isInteger(minute)) return trimmed; if (hour < 0 || hour > 23 || minute < 0 || minute > 59) return trimmed; return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`; } function currentCycleCode() { const now = new Date(); return `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}`; } function normalizeItem(item) { const qty = Number(item.quantity) || 0; const price = Number(item.price) || 0; const costPrice = Math.max(0, Number(item.cost_price) || 0); const amount = Math.round((Number(item.amount) || qty * price) * 100) / 100; const processingMethod = String(item.processing_method || '').trim() || '原材料'; const processingOwner = needsProcessingOwnerChoice(processingMethod) ? defaultProcessingOwnerForMethod(processingMethod, item.processing_owner) : null; const entryName = String(item.item_name || '').trim(); const catalogName = String(item.catalog_sku_name || item.sku_name || '').trim(); const skuCode = String(item.sku_code || '').trim(); const nameMismatch = Boolean(entryName && catalogName && skuCode && entryName !== catalogName); return { ...item, _uid: item._uid || `item-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, catalog_sku_name: catalogName, name_mismatch: nameMismatch, processing_method: processingMethod, processing_owner: processingOwner, show_processing_owner: Boolean(processingOwner), show_process_unit_price: processingOwner === PROCESSING_OWNER_WAREHOUSE, process_unit_price: Math.max(0, Number(item.process_unit_price) || 0), cost_price: costPrice, amount, amountText: amount.toFixed(2), mapping_status: mappingStatusText(item), category_input: categoryInputValue(item), category_display: categoryDisplayText(item), category_has_value: categoryHasValue(item), }; } /** 用生效报价单成本补齐明细(仅当当前成本为空/0) */ function applyQuoteCostsToItems(items, quotePriceMap) { const map = quotePriceMap || {}; return (items || []).map((item) => { const code = String(item.sku_code || '').trim(); let costPrice = Number(item.cost_price) || 0; if (!(costPrice > 0) && code && map[code]) { costPrice = Number(map[code].cost_price) || 0; } return normalizeItem({ ...item, cost_price: costPrice }); }); } function normalizeItems(items) { return items.map(normalizeItem); } function emptyItem() { return normalizeItem({ item_name: '', quantity: 1, unit: '斤', price: 0, cost_price: 0, sku_code: '', create_product: false, processing_method: '原材料', processing_owner: null, process_unit_price: 0, remark: '', ...emptyCategoryFields(), }); } function estimateAmount(items) { return items.reduce((sum, item) => { const qty = Number(item.quantity) || 0; const price = Number(item.price) || 0; return sum + Math.round((Number(item.amount) || price * qty) * 100) / 100; }, 0); } Component({ options: { addGlobalClass: true }, properties: { embedded: { type: Boolean, value: false }, }, lifetimes: { attached() { this._recorder = null; this._budgetTimer = null; this._scrollTimers = []; this._windowHeight = 600; this._focusedItemIndex = -1; this._typingItemIndex = -1; this._typingTimer = null; this._remarkFocus = false; this._pendingKeyboardHeight = 0; this._keyboardDebounceTimer = null; this._onRecorderStop = null; this._onRecorderError = null; this._tearingDown = false; this.setupHardware(); this.onPanelShow(); }, detached() { this.teardownHardware(); }, }, pageLifetimes: { show() { this.onPanelShow(); }, }, data: { customers: [], customerIndex: -1, /** 选中「散客录单」⇒ 走零售口径(只扣库存、无分拣/配送),与 Web 对齐 */ retailMode: false, entryMode: 'image', entryModes: ENTRY_MODES, items: [emptyItem()], remark: '', inputText: '', imagePreview: '', branchText: '', loading: false, submitting: false, parsing: false, recording: false, error: '', orderTotal: '0.00', processingMethods: PROCESSING_METHOD_OPTIONS, smartClassifyEnabled: true, showCostPrice: readShowCostPrice(), quotePriceMap: {}, quoteSheetCode: '', deliveryDate: tomorrowDateString(), deliveryDateStart: todayDateString(), customerDeliveryDeadline: '', deliveryAddress: '', categoryOptions: [{ category_code: '', category_name: '未分类', label: '未分类' }], categoryPickerLabels: ['未分类'], customerSkus: [], showMappingLibrary: false, unmatchedItems: [], budget: null, budgetMessage: '', budgetLevel: 'ok', budgetBlocked: false, showQuickCategoryModal: false, quickCategoryTargetIndex: -1, quickCategoryName: '', creatingCategory: false, prefilling: false, activeCategoryIndex: -1, categoryDropdownQuery: '', categoryDropdownOptions: [], categoryDropdownCurrentCode: '', categorySearchFocus: false, activeSkuIndex: -1, skuSuggestions: [], skuQuery: '', skuSearching: false, skuCanCreate: false, scrollViewHeight: 600, windowHeight: 600, panelHeight: 600, wrapStyle: '', scrollSpacerHeight: 80, keyboardHeight: 0, scrollTop: 0, }, methods: { setupHardware() { this._tearingDown = false; this.unbindRecorder(); const rec = wx.getRecorderManager(); this._onRecorderStop = (res) => this.onRecordStop(res); this._onRecorderError = () => { if (this._tearingDown) return; this.setData({ recording: false }); wx.showToast({ title: '录音失败', icon: 'none' }); }; rec.onStop(this._onRecorderStop); rec.onError(this._onRecorderError); this._recorder = rec; this.applyPanelHeight(); this._onKeyboardHeight = (res) => { this._pendingKeyboardHeight = res.height || 0; if (this._keyboardDebounceTimer) clearTimeout(this._keyboardDebounceTimer); const delay = (this._typingItemIndex >= 0 || this._remarkFocus) ? 800 : 80; this._keyboardDebounceTimer = setTimeout(() => { this.applyKeyboardLayout(this._pendingKeyboardHeight); }, delay); }; wx.onKeyboardHeightChange(this._onKeyboardHeight); }, unbindRecorder() { const rec = this._recorder; if (rec && this._onRecorderStop && typeof rec.offStop === 'function') { rec.offStop(this._onRecorderStop); } if (rec && this._onRecorderError && typeof rec.offError === 'function') { rec.offError(this._onRecorderError); } this._onRecorderStop = null; this._onRecorderError = null; }, resetDraftForm() { this.setData({ customerIndex: -1, retailMode: false, items: [emptyItem()], remark: '', inputText: '', imagePreview: '', unmatchedItems: [], orderTotal: '0.00', quotePriceMap: {}, quoteSheetCode: '', customerSkus: [], showMappingLibrary: false, budget: null, budgetMessage: '', budgetLevel: 'ok', budgetBlocked: false, parseSessionId: '', parseError: '', error: '', recording: false, parsing: false, submitting: false, prefilling: false, activeCategoryIndex: -1, categoryDropdownQuery: '', categoryDropdownOptions: [], categoryDropdownCurrentCode: '', categorySearchFocus: false, activeSkuIndex: -1, skuSuggestions: [], skuQuery: '', skuSearching: false, skuCanCreate: false, showQuickCategoryModal: false, quickCategoryTargetIndex: -1, quickCategoryName: '', deliveryDate: tomorrowDateString(), deliveryDateStart: todayDateString(), customerDeliveryDeadline: '', deliveryAddress: '', }); }, applyPanelHeight() { const windowInfo = wx.getWindowInfo ? wx.getWindowInfo() : {}; const rawWindow = Number(windowInfo.windowHeight) || 667; const keyboardOpen = this.data.keyboardHeight > 0; this._windowHeight = rawWindow; if (this.properties.embedded) { this.setData({ windowHeight: rawWindow, panelHeight: 0, wrapStyle: '', scrollViewHeight: 0, scrollSpacerHeight: keyboardOpen ? this.data.keyboardHeight + 100 : 16, }); return; } this.setData({ windowHeight: rawWindow, panelHeight: rawWindow, wrapStyle: `height: ${rawWindow}px;`, scrollViewHeight: rawWindow, scrollSpacerHeight: keyboardOpen ? this.data.keyboardHeight + 100 : 80, }); }, applyKeyboardLayout(keyboardHeight) { const idleSpacer = this.properties.embedded ? 16 : 80; const scrollSpacerHeight = keyboardHeight > 0 ? keyboardHeight + 100 : idleSpacer; if ( this.data.keyboardHeight === keyboardHeight && this.data.scrollSpacerHeight === scrollSpacerHeight ) { return; } this.setData({ keyboardHeight, scrollSpacerHeight, }, () => { if (this._typingItemIndex >= 0 || this._remarkFocus) return; const index = this._focusedItemIndex >= 0 ? this._focusedItemIndex : this.data.activeCategoryIndex; if (index >= 0 && keyboardHeight > 0) { this.scheduleScrollIntoView(index); } }); }, teardownHardware() { this._tearingDown = true; if (this.data.recording && this._recorder) { try { this._recorder.stop(); } catch (_) { /* ignore */ } } this.unbindRecorder(); if (this._onKeyboardHeight) { wx.offKeyboardHeightChange(this._onKeyboardHeight); this._onKeyboardHeight = null; } if (this._keyboardDebounceTimer) clearTimeout(this._keyboardDebounceTimer); this._keyboardDebounceTimer = null; if (this._budgetTimer) clearTimeout(this._budgetTimer); this._budgetTimer = null; if (this._typingTimer) clearTimeout(this._typingTimer); this._typingTimer = null; this.clearScrollTimers(); }, clearScrollTimers() { (this._scrollTimers || []).forEach((timer) => clearTimeout(timer)); this._scrollTimers = []; }, scheduleScrollIntoView(index) { if (this.properties.embedded) return; if (index === undefined || index === null || index < 0) return; if (this._typingItemIndex === index) return; this.clearScrollTimers(); [60, 220, 420].forEach((delay) => { const timer = setTimeout(() => { if (this._typingItemIndex === index) return; const focused = this._focusedItemIndex; const categoryOpen = this.data.activeCategoryIndex; if (focused !== index && categoryOpen !== index && !this._remarkFocus) return; this.scrollItemIntoView(index); }, delay); this._scrollTimers.push(timer); }); }, scrollItemIntoView(index) { if (this.properties.embedded) return; if (index === undefined || index === null || index < 0) return; if (this._typingItemIndex >= 0) return; const keyboardHeight = this.data.keyboardHeight || 0; const viewportHeight = Math.max(240, this._windowHeight - keyboardHeight); wx.nextTick(() => { const query = wx.createSelectorQuery().in(this); query.select('.page-scroll').scrollOffset(); query.select(`#item-card-${index}`).boundingClientRect(); query.select('.page-scroll').boundingClientRect(); query.exec((res) => { const scrollInfo = res[0]; const itemRect = res[1]; const scrollRect = res[2]; if (!scrollInfo || !itemRect || !scrollRect) return; const topGap = 12; const bottomGap = 20; const visibleTop = Math.max(scrollRect.top, 0); const visibleBottom = visibleTop + viewportHeight - bottomGap; let target = scrollInfo.scrollTop; if (itemRect.bottom > visibleBottom) { target = scrollInfo.scrollTop + (itemRect.bottom - visibleBottom); } else if (itemRect.top < visibleTop + topGap) { target = Math.max(0, scrollInfo.scrollTop + (itemRect.top - visibleTop - topGap)); } else { return; } target = Math.round(Math.max(0, target)); if (this.data.scrollTop === target) return; this.setData({ scrollTop: target }); }); }); }, scrollFieldIntoView(selector) { if (this.properties.embedded) return; if (this._typingItemIndex >= 0) return; const keyboardHeight = this.data.keyboardHeight || 0; const viewportHeight = Math.max(240, this._windowHeight - keyboardHeight); wx.nextTick(() => { const query = wx.createSelectorQuery().in(this); query.select('.page-scroll').scrollOffset(); query.select(selector).boundingClientRect(); query.select('.page-scroll').boundingClientRect(); query.exec((res) => { const scrollInfo = res[0]; const fieldRect = res[1]; const scrollRect = res[2]; if (!scrollInfo || !fieldRect || !scrollRect) return; const bottomGap = 20; const visibleTop = Math.max(scrollRect.top, 0); const visibleBottom = visibleTop + viewportHeight - bottomGap; if (fieldRect.bottom <= visibleBottom && fieldRect.top >= visibleTop) return; let target = scrollInfo.scrollTop; if (fieldRect.bottom > visibleBottom) { target = scrollInfo.scrollTop + (fieldRect.bottom - visibleBottom); } else if (fieldRect.top < visibleTop) { target = Math.max(0, scrollInfo.scrollTop + (fieldRect.top - visibleTop - 12)); } target = Math.round(Math.max(0, target)); if (this.data.scrollTop === target) return; this.setData({ scrollTop: target }); }); }); }, markItemTyping(index) { this._typingItemIndex = index; if (this._typingTimer) clearTimeout(this._typingTimer); this._typingTimer = setTimeout(() => { if (this._typingItemIndex === index) { this._typingItemIndex = -1; this.applyKeyboardLayout(this._pendingKeyboardHeight); } }, 500); this.clearScrollTimers(); }, onItemFieldFocus(e) { const index = Number(e.currentTarget.dataset.index); this._focusedItemIndex = index; this._remarkFocus = false; this.scheduleScrollIntoView(index); }, onItemFieldBlur(e) { const index = Number(e.currentTarget.dataset.index); const field = e.currentTarget.dataset.field; if (this._focusedItemIndex === index) { this._focusedItemIndex = -1; } const item = this.data.items[index]; if (!item) return; if (field === 'item_name' || field === 'unit') { const normalized = normalizeItem(item); this.data.items[index] = normalized; this.setData({ [`items[${index}]`]: normalized }); } this._typingItemIndex = -1; this.applyKeyboardLayout(this._pendingKeyboardHeight); }, onRemarkFocus(e) { this._remarkFocus = true; this._focusedItemIndex = -1; const selector = (e.currentTarget.dataset || {}).scrollTarget || '.order-remark-input'; [60, 220, 420].forEach((delay) => { setTimeout(() => { if (!this._remarkFocus) return; this.scrollFieldIntoView(selector); }, delay); }); }, onNumericFocus(e) { const index = Number(e.currentTarget.dataset.index); const field = e.currentTarget.dataset.field; this._focusedItemIndex = index; this._remarkFocus = false; this.scheduleScrollIntoView(index); const raw = (this.data.items[index] || {})[field]; if (raw === '' || raw === null || raw === undefined) return; if (Number(raw) === 0) { this.setData({ [`items[${index}].${field}`]: '' }); } }, onNumericBlur(e) { const index = Number(e.currentTarget.dataset.index); const field = e.currentTarget.dataset.field; if (this._focusedItemIndex === index) { this._focusedItemIndex = -1; } const items = normalizeItems(this.data.items.map((item, idx) => { if (idx !== index) return item; const raw = item[field]; if (raw === '' || raw === null || raw === undefined) { const defaultVal = field === 'quantity' ? 1 : 0; return { ...item, [field]: defaultVal }; } return item; })); // 同步写回,避免 setData 异步导致成本价写库读到旧值 this.data.items = items; this.setData({ items }); this.updateOrderTotal(items); this.scheduleBudgetCheck(); if (field === 'cost_price') { this.commitCostPrice(index, items[index]); } }, async onPanelShow() { if (!beginPanelShow(this)) return; try { const ok = await ensureMobileRole('order_entry'); if (!ok) return; const profile = getSession()?.profile || {}; this.setData({ branchText: profile.branch_name || (profile.branch_code ? '已绑定分公司' : ''), deliveryDateStart: todayDateString(), deliveryDate: this.data.deliveryDate || tomorrowDateString(), }); this.loadCustomers(); this.loadCategories(); } finally { endPanelShow(this); } }, getSelectedCustomer() { const index = this.data.customerIndex; if (index < 0) return null; return this.data.customers[index] || null; }, requireCustomer() { const customer = this.getSelectedCustomer(); if (!customer) { wx.showToast({ title: '请先选择客户', icon: 'none' }); return null; } return customer; }, updateOrderTotal(items) { this.setData({ orderTotal: estimateAmount(items).toFixed(2) }); }, scheduleBudgetCheck() { if (this._budgetTimer) clearTimeout(this._budgetTimer); this._budgetTimer = setTimeout(() => this.refreshBudget(), 400); }, async refreshBudget() { const customer = this.getSelectedCustomer(); // 散客无预算/账期口径:与 Web 一致,不做预算校验(否则空预算会把散客录单拦住) if (!customer || isRetailCustomer(customer)) { this.setData({ budget: null, budgetMessage: '', budgetLevel: 'ok', budgetBlocked: false }); return; } const orderAmount = estimateAmount(this.data.items); try { const budget = await fetchCustomerOrderBudget(customer.customer_code, orderAmount); if (budget.disabled) { this.setData({ budget: null, budgetMessage: '', budgetLevel: 'ok', budgetBlocked: false }); return; } this.setData({ budget, budgetMessage: budget.message || '', budgetLevel: budget.level || 'ok', budgetBlocked: budget.level === 'block' || budget.allowed === false, }); } catch (err) { this.setData({ budgetMessage: err.message || '预算校验失败,请稍后重试', budgetLevel: 'error', budgetBlocked: true, }); } }, async loadCategories() { try { const result = await fetchOrderCategories(); const categoryOptions = buildCategoryPickerOptions(result.data || []); this.setData({ categoryOptions, categoryPickerLabels: buildCategoryPickerLabels(categoryOptions), items: normalizeItems(enrichItemsCategoryFields(this.data.items, categoryOptions)), }); } catch (err) { console.warn('loadCategories failed', err); } }, async loadCustomerSkus(customerCode) { if (!customerCode) { this.setData({ customerSkus: [] }); return; } try { const result = await fetchCustomerMappingSkus(customerCode); this.setData({ customerSkus: result.data || [] }); } catch (err) { this.setData({ customerSkus: [] }); } }, async loadQuotePrices(customerCode) { if (!customerCode) { this.setData({ quotePriceMap: {}, quoteSheetCode: '' }); return; } try { const result = await fetchOrderEntryQuotePrices(customerCode); const map = {}; (result.data || []).forEach((row) => { const code = String(row.sku_code || '').trim(); if (!code) return; map[code] = { cost_price: Math.max(0, Number(row.cost_price) || 0), sale_price: Math.max(0, Number(row.sale_price) || 0), unit: row.unit || '斤', sku_name: row.sku_name || '', }; }); const items = applyQuoteCostsToItems(this.data.items, map); this.setData({ quotePriceMap: map, quoteSheetCode: result.quote_sheet_code || '', items, }); this.updateOrderTotal(items); } catch (err) { this.setData({ quotePriceMap: {}, quoteSheetCode: '' }); console.warn('loadQuotePrices failed', err); } }, async loadCustomers() { this.setData({ loading: true, error: '' }); try { const result = await fetchOrderEntryCustomers(); this.setData({ customers: result.data || [] }); } catch (err) { this.setData({ error: err.message || '加载客户失败' }); } finally { this.setData({ loading: false }); } }, onCustomerChange(e) { const customerIndex = Number(e.detail.value); const customer = this.data.customers[customerIndex]; this.setData({ customerIndex, retailMode: isRetailCustomer(customer), items: [emptyItem()], unmatchedItems: [], orderTotal: '0.00', quotePriceMap: {}, quoteSheetCode: '', deliveryAddress: String(customer?.address || '').trim(), customerDeliveryDeadline: displayCustomerDeliveryDeadline(customer?.delivery_time), activeSkuIndex: -1, skuSuggestions: [], skuCanCreate: false, }); if (customer?.customer_code) { this.loadCustomerSkus(customer.customer_code); this.loadQuotePrices(customer.customer_code); this.scheduleBudgetCheck(); } else { this.setData({ customerSkus: [], showMappingLibrary: false }); } }, toggleMappingLibrary() { this.setData({ showMappingLibrary: !this.data.showMappingLibrary }); }, onSmartClassifyChange(e) { const enabled = Boolean(e.detail.value); const items = normalizeItems( enabled ? this.data.items : this.data.items.map((item) => stripAutoCategoriesUnlessManual(item, this.data.categoryOptions)) ); this.setData({ smartClassifyEnabled: enabled, items }); }, onShowCostPriceChange(e) { const enabled = Boolean(e.detail.value); try { wx.setStorageSync(SHOW_COST_STORAGE_KEY, enabled ? '1' : '0'); } catch { // ignore } this.setData({ showCostPrice: enabled }); }, async commitCostPrice(index, itemOverride) { const customer = this.getSelectedCustomer(); const item = itemOverride || this.data.items[index]; if (!customer || !item) return; const skuCode = String(item.sku_code || '').trim(); const costPrice = Math.max(0, Number(item.cost_price) || 0); if (!(costPrice > 0)) return; if (!skuCode) { wx.showToast({ title: '请先匹配商品后再改成本价', icon: 'none' }); return; } if (!this.data.quoteSheetCode) { wx.showToast({ title: '无生效报价单,成本价不会落库', icon: 'none' }); return; } try { await upsertOrderEntryQuoteCosts({ customer_code: customer.customer_code, items: [{ sku_code: skuCode, cost_price: costPrice, sale_price: Number(item.price) || 0, sku_name: item.item_name || '', unit: item.unit || '斤', }], }); const quotePriceMap = { ...this.data.quotePriceMap, [skuCode]: { ...(this.data.quotePriceMap[skuCode] || {}), cost_price: costPrice, sale_price: Number(item.price) || Number(this.data.quotePriceMap[skuCode]?.sale_price) || 0, unit: item.unit || '斤', sku_name: item.item_name || '', }, }; this.setData({ quotePriceMap }); } catch (err) { wx.showToast({ title: err.message || '成本价保存失败', icon: 'none' }); } }, switchEntryMode(e) { const entryMode = e.currentTarget.dataset.mode; if (!entryMode || entryMode === this.data.entryMode) return; this.setData({ entryMode, parseError: '' }); }, onInputTextChange(e) { this.data.inputText = e.detail.value; }, onTextInputBlur() { this._remarkFocus = false; if (this.data.inputText !== undefined) { this.setData({ inputText: this.data.inputText }); } this.applyKeyboardLayout(this._pendingKeyboardHeight); }, onParseTextTap() { const customer = this.requireCustomer(); if (!customer) return; const text = String(this.data.inputText || '').trim(); if (!text) { wx.showToast({ title: '请输入订单内容', icon: 'none' }); return; } this.parseOrderInput({ text, customer_code: customer.customer_code }); }, onRecordTap() { const customer = this.requireCustomer(); if (!customer) return; if (this.data.recording) { this._recorder.stop(); this.setData({ recording: false }); return; } wx.authorize({ scope: 'scope.record', success: () => { this.setData({ recording: true }); this._recorder.start(MP3_RECORD_OPTIONS); wx.showToast({ title: '录音中,再次点击结束', icon: 'none' }); }, fail: () => wx.showToast({ title: '请授权麦克风', icon: 'none' }), }); }, onRecordStop(res) { if (this._tearingDown) return; this.setData({ recording: false }); const customer = this.getSelectedCustomer(); if (!customer || !res.tempFilePath) return; const fs = wx.getFileSystemManager(); fs.readFile({ filePath: res.tempFilePath, encoding: 'base64', success: (fileRes) => { if (this._tearingDown) return; this.parseOrderInput({ audio_base64: fileRes.data, audio_format: 'mp3', customer_code: customer.customer_code, }); }, fail: () => wx.showToast({ title: '读取录音失败', icon: 'none' }), }); }, chooseImageFromCamera() { this.pickImage(['camera']); }, chooseImageFromAlbum() { this.pickImage(['album']); }, pickImage(sourceType) { const customer = this.requireCustomer(); if (!customer) return; wx.chooseImage({ count: 1, sizeType: ['compressed'], sourceType, success: (res) => { const filePath = (res.tempFilePaths || [])[0]; if (!filePath) return; this.setData({ imagePreview: filePath, parsing: true }); prepareOrderImageBase64(filePath) .then((base64) => { this.parseOrderInput({ image_base64: base64, customer_code: customer.customer_code, }); }) .catch(() => { this.setData({ parsing: false }); wx.showToast({ title: '读取图片失败', icon: 'none' }); }); }, }); }, clearImagePreview() { this.setData({ imagePreview: '' }); }, async parseOrderInput(payload) { this.setData({ parsing: true }); try { const result = await parseCustomerOrder({ ...payload, smart_classify_enabled: this.data.smartClassifyEnabled, }); const parsed = result.data || {}; const items = applyQuoteCostsToItems( normalizeItems((parsed.items || []).map((row) => mapParsedItem( row, this.data.smartClassifyEnabled, this.data.categoryOptions ))), this.data.quotePriceMap ); if (!items.length) { wx.showToast({ title: parsed.message || '未识别到商品', icon: 'none' }); return; } if (parsed.text) { this.setData({ inputText: parsed.text }); } this.setData({ items, unmatchedItems: parsed.unmatched || [], parseSessionId: parsed.parse_session_id || '', }); this.updateOrderTotal(items); this.scheduleBudgetCheck(); const stats = parsed.extracted_stats; const extra = stats && stats.mergedItemCount > Math.max(...(stats.requestItemCounts || [0]), 0) ? '(已合并多次识别)' : ''; wx.showToast({ title: `识别 ${items.length} 项${extra}`, icon: 'success', duration: 2500 }); } catch (err) { wx.showToast({ title: err.message || '解析失败', icon: 'none' }); } finally { this.setData({ parsing: false }); } }, async handlePrefill() { const customer = this.requireCustomer(); if (!customer || this.data.prefilling) return; this.setData({ prefilling: true }); wx.showLoading({ title: '加载中…', mask: true }); try { const result = await fetchCustomerOrderPrefill(customer.customer_code); const rows = result.data || []; if (!rows.length) { wx.showToast({ title: '近30天无复购记录', icon: 'none' }); return; } const items = applyQuoteCostsToItems( normalizeItems(enrichItemsCategoryFields(rows.map((row) => ({ item_name: row.sku_name || row.item_name || '', sku_code: row.sku_code || '', quantity: Math.round(Number(row.avg_qty || row.quantity || 1) * 100) / 100 || 1, unit: row.unit || '斤', price: Number(row.price) || 0, cost_price: 0, processing_method: row.processing_method || '原材料', category_code: row.category_code || '', category_name: row.category_name || '', category_manually_set: false, library_category_code: row.category_code || '', in_customer_library: true, match_layer: 0, })), this.data.categoryOptions)), this.data.quotePriceMap ); this.closeCategoryDropdown(); this.setData({ items, unmatchedItems: [] }); this.updateOrderTotal(items); this.scheduleBudgetCheck(); wx.showToast({ title: `已载入 ${items.length} 项`, icon: 'success' }); } catch (err) { wx.showToast({ title: err.message || '预填失败', icon: 'none' }); } finally { wx.hideLoading(); this.setData({ prefilling: false }); } }, addMappingSku(e) { const sku = e.currentTarget.dataset.sku; if (!sku) return; const item = applyQuoteCostsToItems([normalizeItem(enrichItemsCategoryFields({ item_name: sku.customer_sku_name || '商品', sku_code: sku.sku_code, quantity: 1, unit: sku.customer_unit || '斤', price: Number(sku.price_preference) || 0, cost_price: 0, processing_method: sku.processing_method || '原材料', category_code: sku.category_code || '', category_name: '', category_manually_set: false, library_category_code: sku.category_code || '', in_customer_library: true, match_layer: 0, }, this.data.categoryOptions))], this.data.quotePriceMap)[0]; const items = normalizeItems([...this.data.items.filter((row) => row.item_name), item]); this.setData({ items: items.length ? items : [item] }); this.updateOrderTotal(items); this.scheduleBudgetCheck(); }, clearAllItems() { this.closeCategoryDropdown(); this.closeSkuDropdown(); this.setData({ items: [emptyItem()], unmatchedItems: [], orderTotal: '0.00', inputText: '', imagePreview: '', remark: '', }); this.scheduleBudgetCheck(); }, openQuickCategory(e) { const index = Number(e.currentTarget.dataset.index); this.closeCategoryDropdown(); this.setData({ showQuickCategoryModal: true, quickCategoryTargetIndex: index, quickCategoryName: '', }); }, closeQuickCategoryModal() { if (this.data.creatingCategory) return; this.setData({ showQuickCategoryModal: false, quickCategoryTargetIndex: -1, 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 createOrderCategory(name); const created = result.data || {}; const categoryOptions = buildCategoryPickerOptions([ ...(this.data.categoryOptions || []).filter((item) => item.category_code), created, ]); const targetIndex = this.data.quickCategoryTargetIndex; let items = this.data.items; if (targetIndex >= 0) { items = normalizeItems(items.map((item, idx) => ( idx === targetIndex ? applyManualCategory(item, created) : item ))); } this.setData({ categoryOptions, categoryPickerLabels: buildCategoryPickerLabels(categoryOptions), items, showQuickCategoryModal: false, quickCategoryTargetIndex: -1, quickCategoryName: '', }); this.updateOrderTotal(items); wx.showToast({ title: '分类已创建', icon: 'success' }); } catch (err) { wx.showToast({ title: err.message || '创建失败', icon: 'none' }); } finally { this.setData({ creatingCategory: false }); } }, updateItem(e) { const index = Number(e.currentTarget.dataset.index); const field = e.currentTarget.dataset.field; const value = e.detail.value; const current = this.data.items[index]; if (!current) return; current[field] = value; if (field === 'item_name') { this.closeCategoryDropdown(); current.sku_code = ''; current.create_product = false; current.in_customer_library = false; current.match_layer = null; const normalized = normalizeItem(current); this.data.items[index] = normalized; this.setData({ [`items[${index}].item_name`]: value, [`items[${index}].sku_code`]: '', [`items[${index}].create_product`]: false, [`items[${index}].mapping_status`]: normalized.mapping_status, activeSkuIndex: index, skuQuery: value, }); this.markItemTyping(index); if (this._skuSearchTimer) clearTimeout(this._skuSearchTimer); this._skuSearchTimer = setTimeout(() => this.searchSkusForItem(index, value), 250); return; } if (field === 'unit') { this.markItemTyping(index); return; } this.markItemTyping(index); const next = { ...current, [field]: value }; if (field === 'quantity' || field === 'price') { const qty = Number(field === 'quantity' ? value : next.quantity) || 0; const price = Number(field === 'price' ? value : next.price) || 0; next.amount = Math.round(qty * price * 100) / 100; } const amountText = (Math.round((Number(next.amount) || 0) * 100) / 100).toFixed(2); this.data.items[index] = next; const patch = { [`items[${index}].${field}`]: value, [`items[${index}].amount`]: next.amount, [`items[${index}].amountText`]: amountText, orderTotal: estimateAmount(this.data.items).toFixed(2), }; this.setData(patch); this.scheduleBudgetCheck(); }, onSkuNameFocus(e) { const index = Number(e.currentTarget.dataset.index); const item = this.data.items[index]; if (!item) return; this.closeCategoryDropdown(); this.setData({ activeSkuIndex: index, skuQuery: item.item_name || '', }); const customer = this.getSelectedCustomer(); if (!customer?.customer_code) { wx.showToast({ title: '请先选择客户', icon: 'none' }); return; } this.searchSkusForItem(index, item.item_name || ''); }, onSkuNameBlur() { setTimeout(() => { if (this.data.activeSkuIndex < 0) return; // 延迟关闭,给 catchtap 选中留时间 this.closeSkuDropdown(); }, 220); }, closeSkuDropdown() { this.setData({ activeSkuIndex: -1, skuSuggestions: [], skuCanCreate: false, skuSearching: false, skuQuery: '', }); }, async searchSkusForItem(index, query) { const customer = this.getSelectedCustomer(); if (!customer?.customer_code) return; const q = String(query || '').trim(); const searchSeq = (this._skuSearchSeq || 0) + 1; this._skuSearchSeq = searchSeq; this.setData({ skuSearching: true, skuQuery: q, activeSkuIndex: index }); try { const result = await searchOrderEntrySkus({ customer_code: customer.customer_code, q, }); if (searchSeq !== this._skuSearchSeq || this.data.activeSkuIndex !== index) return; const rows = result.data || []; const normalized = q.toLowerCase(); const exact = rows.some( (row) => String(row.sku_name || '').trim().toLowerCase() === normalized ); this.setData({ skuSuggestions: rows, skuCanCreate: Boolean(q) && !exact, }); } catch (err) { if (searchSeq !== this._skuSearchSeq) return; this.setData({ skuSuggestions: [], skuCanCreate: Boolean(q), }); wx.showToast({ title: err.message || '搜索商品失败', icon: 'none' }); } finally { if (searchSeq === this._skuSearchSeq) this.setData({ skuSearching: false }); } }, pickSkuSuggestion(e) { const index = Number(e.currentTarget.dataset.index); const sidx = Number(e.currentTarget.dataset.sidx); const row = this.data.skuSuggestions[sidx]; const current = this.data.items[index]; if (!row || !current) return; const enriched = enrichItemsCategoryFields( [ { ...current, sku_code: String(row.sku_code || ''), item_name: String(current.item_name || row.sku_name || row.sku_code || '').trim(), catalog_sku_name: String(row.sku_name || row.sku_code || ''), unit: String(row.unit || current.unit || '斤'), price: Number(row.sale_price) > 0 ? Number(row.sale_price) : Number(current.price) || 0, cost_price: Number(row.cost_price) > 0 ? Number(row.cost_price) : Number(current.cost_price) || 0, category_code: row.category_code || current.category_code || '', category_name: row.category_name || current.category_name || '', category_manually_set: Boolean(row.category_code), library_category_code: row.category_code || '', create_product: false, in_customer_library: false, match_layer: row.from_quote ? 0 : 3, }, ], this.data.categoryOptions ); const item = applyQuoteCostsToItems(enriched, this.data.quotePriceMap)[0]; const items = this.data.items.slice(); items[index] = item; this.setData({ items }); this.closeSkuDropdown(); this.updateOrderTotal(items); this.scheduleBudgetCheck(); }, chooseCreateSku(e) { const index = Number(e.currentTarget.dataset.index); const name = String(this.data.skuQuery || this.data.items[index]?.item_name || '').trim(); if (!name) return; const current = this.data.items[index]; if (!current) return; const item = normalizeItem({ ...current, item_name: name, sku_code: '', create_product: true, in_customer_library: false, match_layer: null, }); const items = this.data.items.slice(); items[index] = item; this.setData({ items }); this.closeSkuDropdown(); wx.showToast({ title: '请选择分类,提交时新建商品', icon: 'none' }); }, onProcessingMethodPick(e) { const index = Number(e.currentTarget.dataset.index); const method = this.data.processingMethods[Number(e.detail.value)] || '原材料'; const items = normalizeItems(this.data.items.map((item, idx) => { if (idx !== index) return item; const processing_owner = needsProcessingOwnerChoice(method) ? defaultProcessingOwnerForMethod(method, item.processing_owner) : null; return { ...item, processing_method: method, processing_owner, process_unit_price: processing_owner === PROCESSING_OWNER_WAREHOUSE ? Number(item.process_unit_price) || 0 : 0, }; })); this.setData({ items }); }, onProcessingOwnerTap(e) { const index = Number(e.currentTarget.dataset.index); const owner = String(e.currentTarget.dataset.owner || '') === PROCESSING_OWNER_WAREHOUSE ? PROCESSING_OWNER_WAREHOUSE : PROCESSING_OWNER_SUPPLIER; const items = normalizeItems(this.data.items.map((item, idx) => { if (idx !== index) return item; return { ...item, processing_owner: owner, process_unit_price: owner === PROCESSING_OWNER_WAREHOUSE ? Number(item.process_unit_price) || 0 : 0, }; })); this.setData({ items }); }, toggleCategoryDropdown(e) { const index = Number(e.currentTarget.dataset.index); this.closeSkuDropdown(); if (this.data.activeCategoryIndex === index) { this.closeCategoryDropdown(); return; } const item = this.data.items[index] || {}; this.setData({ activeCategoryIndex: index, categoryDropdownQuery: '', categoryDropdownOptions: filterCategoryOptions('', this.data.categoryOptions, 999), categoryDropdownCurrentCode: item.category_code || '', categorySearchFocus: false, }, () => { setTimeout(() => { if (this.data.activeCategoryIndex === index) { this.setData({ categorySearchFocus: true }); } }, 80); }); this.scheduleScrollIntoView(index); }, onCategorySearchFocus() { if (this.data.categorySearchFocus) { this.setData({ categorySearchFocus: false }); } const index = this.data.activeCategoryIndex; if (index >= 0) { this._focusedItemIndex = index; this.scheduleScrollIntoView(index); } }, closeCategoryDropdown() { this.setData({ activeCategoryIndex: -1, categoryDropdownQuery: '', categoryDropdownOptions: [], categoryDropdownCurrentCode: '', categorySearchFocus: false, }); }, onCategoryDropdownSearch(e) { const value = e.detail.value; if (value === this.data.categoryDropdownQuery) return; this.setData({ categoryDropdownQuery: value, categoryDropdownOptions: filterCategoryOptions(value, this.data.categoryOptions, 999), }); }, pickCategoryFromDropdown(e) { const sidx = Number(e.currentTarget.dataset.sidx); const option = this.data.categoryDropdownOptions[sidx]; const index = this.data.activeCategoryIndex; if (!option || index < 0) { this.closeCategoryDropdown(); return; } const items = normalizeItems(this.data.items.map((item, idx) => ( idx === index ? applyManualCategory(item, option) : item ))); this.setData({ items }); this.closeCategoryDropdown(); this.scheduleBudgetCheck(); }, openQuickCategoryFromDropdown() { const index = this.data.activeCategoryIndex; const presetName = String(this.data.categoryDropdownQuery || '').trim(); this.closeCategoryDropdown(); this.setData({ showQuickCategoryModal: true, quickCategoryTargetIndex: index, quickCategoryName: presetName, }); }, addItem() { this.closeCategoryDropdown(); this.closeSkuDropdown(); const items = normalizeItems([...this.data.items, emptyItem()]); this.setData({ items }); this.updateOrderTotal(items); this.scheduleBudgetCheck(); }, removeItem(e) { const index = Number(e.currentTarget.dataset.index); this.closeSkuDropdown(); this.closeCategoryDropdown(); const items = this.data.items.filter((_, idx) => idx !== index); const next = normalizeItems(items.length ? items : [emptyItem()]); this.setData({ items: next }); this.updateOrderTotal(next); this.scheduleBudgetCheck(); }, onRemarkInput(e) { this.data.remark = e.detail.value; }, onRemarkBlur() { this._remarkFocus = false; if (this.data.remark !== undefined) { this.setData({ remark: this.data.remark }); } this.applyKeyboardLayout(this._pendingKeyboardHeight); }, onDeliveryDateChange(e) { this.setData({ deliveryDate: e.detail.value }); }, onDeliveryAddressInput(e) { this.setData({ deliveryAddress: e.detail.value || '' }); }, async submitOrder() { if (this._submitInFlight) return; this._submitInFlight = true; try { const customer = this.getSelectedCustomer(); const rawItems = resolveItemsForSubmit( this.data.items.filter((item) => String(item.item_name || '').trim()), this.data.categoryOptions, this.data.smartClassifyEnabled ); const categoryError = validateItemsCategories(rawItems); const retail = isRetailCustomer(customer); if (!customer) { wx.showToast({ title: '请选择客户', icon: 'none' }); return; } // 散客不送货(与 Web 一致):不要求配送日期 if (!retail) { if (!this.data.deliveryDate) { wx.showToast({ title: '请选择配送日期', icon: 'none' }); return; } if (this.data.deliveryDate < todayDateString()) { wx.showToast({ title: '配送日期不能早于今天', icon: 'none' }); return; } } if (!rawItems.length) { wx.showToast({ title: '请填写或识别商品', icon: 'none' }); return; } if (!retail && categoryError) { wx.showToast({ title: categoryError, icon: 'none' }); return; } if (!retail && this.data.budgetBlocked) { wx.showModal({ title: this.data.budgetLevel === 'error' ? '预算校验失败' : '预算不足', content: this.data.budgetMessage || '当前订单将超出预算上限,无法提交', showCancel: false, }); return; } // 零价是否拦截由后端分公司配置决定,前端不再硬拦,避免与 Web 不一致 /** * 散客录单:与 Web 对齐,改走零售接口(建单即全额库存抵扣,不分配、无备货/分拣/配送)。 * 散客单**只支持已建档商品**(后端同口径),所以先把未选商品的行拦下来说清楚。 */ if (retail) { const missingRows = []; rawItems.forEach((item, index) => { if (!String(item.sku_code || '').trim()) missingRows.push(index + 1); }); if (missingRows.length) { wx.showModal({ title: '无法创建订单', content: `散客单只支持已建档商品:第 ${missingRows.join('、')} 行还没选商品`, showCancel: false, }); return; } this.setData({ submitting: true }); const retailResult = await submitRetailOrderEntry({ items: rawItems.map((item) => ({ sku_code: item.sku_code, quantity: item.quantity, price: item.price, unit: item.unit, item_name: item.item_name, })), remark: this.data.remark, parse_session_id: this.data.parseSessionId || undefined, }); const retailData = (retailResult && retailResult.data) || retailResult || {}; const orderCode = String(retailData.order_code || ''); wx.showModal({ title: '散客单已创建', content: `${orderCode ? `单号 ${orderCode}\n` : ''}到「订单管理」点「确认扣除并完结」`, showCancel: false, }); this.resetDraftForm(); return; } this.setData({ submitting: true }); const result = await submitOrderEntryOrderWithConfirm({ customer_code: customer.customer_code, items: rawItems, remark: this.data.remark, delivery_date: this.data.deliveryDate, delivery_time_slot: null, delivery_address: String(this.data.deliveryAddress || '').trim() || undefined, cycle_code: currentCycleCode(), bid_code: `BID${Date.now()}`, smart_classify_enabled: this.data.smartClassifyEnabled, parse_session_id: this.data.parseSessionId || undefined, }); const created = Number(result.new_products_created || 0); if (created > 0) { wx.showToast({ title: `已新建 ${created} 个基础商品`, icon: 'none' }); } const detailUrl = `/pages/order-detail/order-detail?orderCode=${encodeURIComponent(result.order_code)}`; if (this.properties.embedded) { this.resetDraftForm(); wx.navigateTo({ url: detailUrl }); } else { wx.redirectTo({ url: detailUrl }); } } catch (err) { if (!err?.cancelled) { const code = err?.body?.error; const content = err.message || '提交失败'; if ( code === 'zero_price_blocked' || code === 'budget_blocked' || code === 'order_allocation_incomplete' || code === 'needs_confirm_new_products' || content.length > 18 ) { wx.showModal({ title: '无法创建订单', content, showCancel: false, }); } else { wx.showToast({ title: content, icon: 'none' }); } } } finally { this._submitInFlight = false; this.setData({ submitting: false }); } }, }, });