import { DEFAULT_ALLOCATION_RULES, type AllocationRules, } from './allocationRules'; import { getAllocationRulesApi, setAllocationRulesApi } from './workflowApi'; const ALLOCATION_RULES_KEY = 'canteen.allocation.rules'; const ALLOCATION_RULES_MIGRATED_KEY = 'canteen.allocation.rules.migrated'; /** 从服务端加载分配规则;可选一次性迁移本机 localStorage */ export async function loadAllocationRules(): Promise { try { const { data } = await getAllocationRulesApi(); if (data) { try { const migrated = localStorage.getItem(ALLOCATION_RULES_MIGRATED_KEY); const raw = localStorage.getItem(ALLOCATION_RULES_KEY); if (!migrated && raw) { const local = { ...DEFAULT_ALLOCATION_RULES, ...JSON.parse(raw) } as AllocationRules; await setAllocationRulesApi(local); localStorage.removeItem(ALLOCATION_RULES_KEY); localStorage.setItem(ALLOCATION_RULES_MIGRATED_KEY, '1'); const refreshed = await getAllocationRulesApi(); return refreshed.data || local; } if (raw) localStorage.removeItem(ALLOCATION_RULES_KEY); } catch { /* 迁移失败不影响读服务端 */ } return { ...DEFAULT_ALLOCATION_RULES, ...data }; } } catch (err) { console.warn('加载服务端分摊规则失败,尝试本机缓存:', err); } try { const raw = localStorage.getItem(ALLOCATION_RULES_KEY); return raw ? { ...DEFAULT_ALLOCATION_RULES, ...JSON.parse(raw) } : DEFAULT_ALLOCATION_RULES; } catch (err) { console.warn('加载分摊规则配置失败,使用默认值:', err); return DEFAULT_ALLOCATION_RULES; } }