import { pool } from '../db'; import { getEffectiveBranchCode } from './tenantScope'; export type UiPreferenceWriteScope = 'branch_or_user' | 'user_only'; export type UiPreferenceMeta = { writeScope: UiPreferenceWriteScope; /** hardcoded default when neither user nor branch has a value */ defaultValue: unknown; /** system_configs.config_group when writing branch default */ configGroup?: string; description?: string; }; const AGGREGATE_KEY = 'purchase_list.aggregate_same_products'; const EXPORT_KEY = 'export.preferences'; const COLUMN_ORDER_PREFIX = 'table.column_order.'; const PREF_KEY_MAX_LEN = 200; const PREFERENCE_META: Record = { [AGGREGATE_KEY]: { writeScope: 'branch_or_user', defaultValue: { enabled: true }, configGroup: 'purchase', description: '自采列表合计相同商品:开=折叠合计,关=逐单', }, [EXPORT_KEY]: { writeScope: 'user_only', defaultValue: {}, }, }; function isMissingRelationError(error: unknown): boolean { const err = error as { code?: string; message?: string }; return ( err?.code === '42P01' || /relation .*user_preferences.* does not exist/i.test(String(err?.message || '')) ); } function resolveMeta(prefKey: string): UiPreferenceMeta | null { const key = String(prefKey || '').trim(); if (!key || key.length > PREF_KEY_MAX_LEN) return null; if (PREFERENCE_META[key]) return PREFERENCE_META[key]; if (key.startsWith(COLUMN_ORDER_PREFIX) && key.length > COLUMN_ORDER_PREFIX.length) { return { writeScope: 'user_only', defaultValue: null, }; } return null; } export function assertKnownPreferenceKey(prefKey: string): UiPreferenceMeta { const meta = resolveMeta(prefKey); if (!meta) { throw Object.assign(new Error(`不支持的偏好键: ${prefKey}`), { status: 400, code: 'invalid_pref_key' }); } return meta; } function isAdminRoles(roles: string[] | null | undefined): boolean { const list = roles || []; return list.includes('super_admin') || list.includes('admin'); } function asObjectMap(raw: unknown): Record { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}; return raw as Record; } /** Exported for unit tests */ export function normalizePreferenceValue(prefKey: string, raw: unknown): unknown { if (prefKey === AGGREGATE_KEY) { if (raw && typeof raw === 'object' && 'enabled' in (raw as object)) { return { enabled: (raw as { enabled?: unknown }).enabled !== false }; } if (raw === false || raw === 'false' || raw === 0 || raw === '0') return { enabled: false }; if (raw === true || raw === 'true' || raw === 1 || raw === '1') return { enabled: true }; return { enabled: true }; } if (prefKey === EXPORT_KEY) { return asObjectMap(raw); } if (prefKey.startsWith(COLUMN_ORDER_PREFIX)) { if (Array.isArray(raw)) return raw.filter((x) => typeof x === 'string'); if (raw && typeof raw === 'object' && Array.isArray((raw as { ids?: unknown }).ids)) { return (raw as { ids: unknown[] }).ids.filter((x) => typeof x === 'string'); } return null; } return raw ?? null; } /** Merge export maps so cross-device partial updates do not wipe other keys. */ export function mergeExportPreferenceMaps(existing: unknown, incoming: unknown): Record { return { ...asObjectMap(existing), ...asObjectMap(incoming) }; } async function readUserPreference( userId: string, branchCode: string, prefKey: string ): Promise { try { const result = await pool.query( `SELECT pref_value FROM user_preferences WHERE user_id = $1 AND branch_code = $2 AND pref_key = $3 LIMIT 1`, [userId, branchCode, prefKey] ); if (!result.rows[0]) return undefined; return result.rows[0].pref_value; } catch (error) { if (isMissingRelationError(error)) return undefined; throw error; } } async function readBranchPreference(branchCode: string, prefKey: string): Promise { const branchRow = await pool.query( `SELECT config_value FROM system_configs WHERE config_key = $1 AND branch_code = $2 LIMIT 1`, [prefKey, branchCode] ); if (branchRow.rows[0]?.config_value != null) return branchRow.rows[0].config_value; const globalRow = await pool.query( `SELECT config_value FROM system_configs WHERE config_key = $1 AND branch_code IS NULL LIMIT 1`, [prefKey] ); if (globalRow.rows[0]?.config_value != null) return globalRow.rows[0].config_value; return undefined; } async function writeUserPreference( userId: string, branchCode: string, prefKey: string, value: unknown ): Promise { try { await pool.query( `INSERT INTO user_preferences (user_id, branch_code, pref_key, pref_value, updated_at) VALUES ($1, $2, $3, $4::jsonb, NOW()) ON CONFLICT (user_id, branch_code, pref_key) DO UPDATE SET pref_value = EXCLUDED.pref_value, updated_at = NOW()`, [userId, branchCode, prefKey, JSON.stringify(value)] ); } catch (error) { if (isMissingRelationError(error)) { throw Object.assign(new Error('偏好表未就绪,请先执行数据库迁移(user_preferences)'), { status: 503, code: 'pref_table_missing', }); } throw error; } } /** Clear personal override so branch default becomes visible to this user. */ async function deleteUserPreference( userId: string, branchCode: string, prefKey: string ): Promise { try { await pool.query( `DELETE FROM user_preferences WHERE user_id = $1 AND branch_code = $2 AND pref_key = $3`, [userId, branchCode, prefKey] ); } catch (error) { if (isMissingRelationError(error)) return; throw error; } } async function writeBranchPreference( branchCode: string, prefKey: string, value: unknown, meta: UiPreferenceMeta ): Promise { const payload = JSON.stringify(value); const updated = await pool.query( `UPDATE system_configs SET config_value = $1::jsonb, updated_at = NOW() WHERE config_key = $2 AND branch_code = $3`, [payload, prefKey, branchCode] ); if (!updated.rowCount) { await pool.query( `INSERT INTO system_configs (config_key, config_value, config_group, description, branch_code) VALUES ($1, $2::jsonb, $3, $4, $5)`, [ prefKey, payload, meta.configGroup || 'ui', meta.description || prefKey, branchCode, ] ); } } export type EffectivePreferenceResult = { key: string; value: unknown; source: 'user' | 'branch' | 'default'; write_scope: UiPreferenceWriteScope; writes_branch: boolean; branch_code: string; }; export async function getEffectivePreference(input: { userId: string; branchCode: string | null | undefined; prefKey: string; roles?: string[] | null; }): Promise { const meta = assertKnownPreferenceKey(input.prefKey); const branchCode = String(input.branchCode || '').trim(); if (!branchCode) { throw Object.assign(new Error('缺少分公司编码'), { status: 400 }); } const userVal = await readUserPreference(input.userId, branchCode, input.prefKey); if (userVal !== undefined) { return { key: input.prefKey, value: normalizePreferenceValue(input.prefKey, userVal), source: 'user', write_scope: meta.writeScope, writes_branch: meta.writeScope === 'branch_or_user' && isAdminRoles(input.roles), branch_code: branchCode, }; } if (meta.writeScope === 'branch_or_user') { const branchVal = await readBranchPreference(branchCode, input.prefKey); if (branchVal !== undefined) { return { key: input.prefKey, value: normalizePreferenceValue(input.prefKey, branchVal), source: 'branch', write_scope: meta.writeScope, writes_branch: isAdminRoles(input.roles), branch_code: branchCode, }; } } return { key: input.prefKey, value: normalizePreferenceValue(input.prefKey, meta.defaultValue), source: 'default', write_scope: meta.writeScope, writes_branch: meta.writeScope === 'branch_or_user' && isAdminRoles(input.roles), branch_code: branchCode, }; } export async function setPreference(input: { userId: string; branchCode: string | null | undefined; prefKey: string; value: unknown; roles?: string[] | null; }): Promise { const meta = assertKnownPreferenceKey(input.prefKey); const branchCode = String(input.branchCode || '').trim(); if (!branchCode) { throw Object.assign(new Error('缺少分公司编码'), { status: 400 }); } let normalized = normalizePreferenceValue(input.prefKey, input.value); // export.preferences:与库中已有 map 合并,避免多端互相覆盖丢 key if (input.prefKey === EXPORT_KEY) { const existing = await readUserPreference(input.userId, branchCode, input.prefKey); normalized = mergeExportPreferenceMaps(existing, normalized); } const writeBranch = meta.writeScope === 'branch_or_user' && isAdminRoles(input.roles); if (writeBranch) { await writeBranchPreference(branchCode, input.prefKey, normalized, meta); // 管理员写的是分公司默认:清掉自己的个人覆盖,否则下次 GET 仍被个人偏好盖住 await deleteUserPreference(input.userId, branchCode, input.prefKey); return { key: input.prefKey, value: normalized, source: 'branch', write_scope: meta.writeScope, writes_branch: true, branch_code: branchCode, }; } await writeUserPreference(input.userId, branchCode, input.prefKey, normalized); return { key: input.prefKey, value: normalized, source: 'user', write_scope: meta.writeScope, writes_branch: false, branch_code: branchCode, }; } export function resolvePreferenceBranchCode( ctx: { branchCode?: string | null; isSuperAdmin?: boolean } | null, operatingBranch?: string | null ): string { const code = getEffectiveBranchCode(ctx as Parameters[0], operatingBranch) || String(ctx?.branchCode || '').trim() || String(operatingBranch || '').trim(); if (!code) { throw Object.assign(new Error('缺少分公司编码(超管请先选择经营分公司)'), { status: 400 }); } return code; } export const UI_PREF_KEYS = { AGGREGATE: AGGREGATE_KEY, EXPORT: EXPORT_KEY, columnOrder: (storageKey: string) => `${COLUMN_ORDER_PREFIX}${storageKey}`, } as const;