Files
SupplierSystem/server/src/services/uiPreferenceService.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

335 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<string, UiPreferenceMeta> = {
[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<string, unknown> {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
return raw as Record<string, unknown>;
}
/** 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<string, unknown> {
return { ...asObjectMap(existing), ...asObjectMap(incoming) };
}
async function readUserPreference(
userId: string,
branchCode: string,
prefKey: string
): Promise<unknown | undefined> {
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<unknown | undefined> {
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<void> {
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<void> {
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<void> {
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<EffectivePreferenceResult> {
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<EffectivePreferenceResult> {
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<typeof getEffectiveBranchCode>[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;