const FALLBACK_UNIT_OPTIONS = [ '斤', '市斤', '公斤', '千克', '两', '克', '个', '件', '箱', '包', '只', '袋', '筐', '瓶', '盒', ]; let cachedLabels = null; let cacheAt = 0; const CACHE_TTL_MS = 5 * 60 * 1000; /** 与后端 unitConversion 重量单位对齐(小程序离线判断) */ const WEIGHT_UNIT_KEYS = new Set([ '斤', '市斤', 'jin', '公斤', '千克', 'kg', '克', 'g', '两', ]); function normalizeUnitLabel(value) { return String(value || '').trim(); } /** 是否为重量单位:应拣「斤」等只录一个实拣,避免数量/重量双框 */ function isWeightUnit(unit) { const raw = normalizeUnitLabel(unit); const key = raw.toLowerCase(); if (!key) return false; if (WEIGHT_UNIT_KEYS.has(raw) || WEIGHT_UNIT_KEYS.has(key)) return true; return /斤|公斤|千克|两|^kg$|^g$|克/.test(key); } function labelsFromRows(rows) { const labels = []; const seen = new Set(); for (const row of rows || []) { const label = normalizeUnitLabel(row.unit_name || row.unit_code); if (!label || seen.has(label)) continue; seen.add(label); labels.push(label); } return labels; } function getCachedUnitLabels() { if (cachedLabels && cachedLabels.length && Date.now() - cacheAt < CACHE_TTL_MS) { return cachedLabels; } return null; } function setCachedUnitLabels(labels) { if (!labels || !labels.length) return FALLBACK_UNIT_OPTIONS; cachedLabels = labels; cacheAt = Date.now(); return cachedLabels; } function getUnitDictionaryLabels() { return getCachedUnitLabels() || FALLBACK_UNIT_OPTIONS; } /** * @param {string} currentUnit * @param {string[]} [dictionary] */ function buildUnitPicker(currentUnit, dictionary) { const base = Array.isArray(dictionary) && dictionary.length ? dictionary : getUnitDictionaryLabels(); const unit = normalizeUnitLabel(currentUnit) || '个'; const unitOptions = base.includes(unit) ? base.slice() : [unit, ...base]; return { unit, unitOptions, unitIndex: Math.max(0, unitOptions.indexOf(unit)), }; } /** * @param {() => Promise<{ data?: Array<{ unit_code?: string; unit_name?: string }> }>} fetchFn */ async function ensureUnitDictionary(fetchFn) { const hit = getCachedUnitLabels(); if (hit) return hit; if (typeof fetchFn !== 'function') return getUnitDictionaryLabels(); try { const res = await fetchFn(); const labels = labelsFromRows(res?.data || res || []); if (labels.length) return setCachedUnitLabels(labels); } catch (error) { console.warn('load unit dictionary failed', error); } return getUnitDictionaryLabels(); } function clearUnitDictionaryCache() { cachedLabels = null; cacheAt = 0; } module.exports = { FALLBACK_UNIT_OPTIONS, getUnitDictionaryLabels, buildUnitPicker, ensureUnitDictionary, setCachedUnitLabels, clearUnitDictionaryCache, isWeightUnit, };