import { supabase } from '../supabase/client'; import { isPlatformMenuScope, menuScopeToDbBranchCode } from './menuLayoutBranch'; import { createDefaultPrintTemplates, mergePrintTemplates, type PrintTemplatesStore, } from './printTemplates'; const CONFIG_KEY = 'print_templates'; export interface PrintTemplateRecord { id: string | null; store: PrintTemplatesStore; fromDirectRecord: boolean; } async function fetchPrintTemplateRecord(branchCode: string | null) { let query = supabase .from('system_configs') .select('id, config_value') .eq('config_key', CONFIG_KEY); if (branchCode === null) { query = query.is('branch_code', null); } else { query = query.eq('branch_code', branchCode); } return query.maybeSingle(); } export async function loadPrintTemplatesForScope(scope: string): Promise { const branchCode = menuScopeToDbBranchCode(scope); if (isPlatformMenuScope(scope)) { const { data, error } = await fetchPrintTemplateRecord(null); if (error) throw error; return { id: data?.id ?? null, store: mergePrintTemplates(data?.config_value), fromDirectRecord: Boolean(data?.config_value), }; } const { data, error } = await fetchPrintTemplateRecord(branchCode); if (error) throw error; if (data?.config_value) { return { id: data.id ?? null, store: mergePrintTemplates(data.config_value), fromDirectRecord: true, }; } const { data: platformData, error: platformError } = await fetchPrintTemplateRecord(null); if (platformError) throw platformError; return { id: null, store: mergePrintTemplates(platformData?.config_value), fromDirectRecord: false, }; } export async function savePrintTemplatesForScope( scope: string, store: PrintTemplatesStore, existingId: string | null ): Promise { const branchCode = menuScopeToDbBranchCode(scope); const payload = { config_key: CONFIG_KEY, config_value: store as unknown as Record, config_group: 'print', description: '打印模板配置', branch_code: branchCode, }; if (existingId) { const { error } = await supabase.from('system_configs').update(payload).eq('id', existingId); if (error) throw error; return existingId; } const { data, error } = await supabase.from('system_configs').insert(payload).select('id').single(); if (error) throw error; return data.id as string; } export function createDefaultPrintTemplateRecord(): PrintTemplateRecord { return { id: null, store: createDefaultPrintTemplates(), fromDirectRecord: false, }; } let cachedStore: PrintTemplatesStore | null = null; let cacheScope: string | null = null; export async function loadPrintTemplatesCached(scope: string): Promise { if (cachedStore && cacheScope === scope) return cachedStore; const record = await loadPrintTemplatesForScope(scope); cachedStore = record.store; cacheScope = scope; return record.store; } export function invalidatePrintTemplateCache() { cachedStore = null; cacheScope = null; }