来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
254 lines
8.2 KiB
TypeScript
254 lines
8.2 KiB
TypeScript
import { getRawPoolQuery, pool } from '../db';
|
|
import { getTenantDbStore } from './tenantDbContext';
|
|
import { listActiveTenantBranches, runInBranchSchema } from './tenantSchemaFallback';
|
|
import { pushNotificationCreated } from './notificationStreamService';
|
|
|
|
const rawQuery = getRawPoolQuery();
|
|
|
|
async function resolveProfileBranch(userId: string): Promise<string | null> {
|
|
const result = await rawQuery(`SELECT branch_code FROM public.profiles WHERE id = $1 LIMIT 1`, [userId]);
|
|
const code = String(result.rows[0]?.branch_code || '').trim();
|
|
return code || null;
|
|
}
|
|
|
|
/** 写/读通知落点:显式分公司 → ALS → 用户资料分公司 */
|
|
async function resolveNotificationBranch(input: {
|
|
userId?: string;
|
|
branchCode?: string | null;
|
|
}): Promise<string | null> {
|
|
const explicit = String(input.branchCode || '').trim();
|
|
if (explicit) return explicit;
|
|
const als = getTenantDbStore()?.branchCode;
|
|
if (als) return als;
|
|
if (input.userId) return resolveProfileBranch(input.userId);
|
|
return null;
|
|
}
|
|
|
|
async function withNotificationSchemas<T>(
|
|
branchCode: string | null,
|
|
fn: () => Promise<T>
|
|
): Promise<T[]> {
|
|
if (branchCode) {
|
|
return [await runInBranchSchema(branchCode, fn)];
|
|
}
|
|
const tenants = await listActiveTenantBranches();
|
|
const out: T[] = [];
|
|
for (const t of tenants) {
|
|
out.push(await runInBranchSchema(t.branch_code, fn));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** 24 小时内是否已有相同类型+标题+订单号的通知(防定时任务重复刷屏) */
|
|
export async function hasRecentNotification(input: {
|
|
notifyType: string;
|
|
title: string;
|
|
relatedOrderCode?: string | null;
|
|
withinHours?: number;
|
|
branchCode?: string | null;
|
|
}): Promise<boolean> {
|
|
const hours = input.withinHours ?? 24;
|
|
const branch = await resolveNotificationBranch({ branchCode: input.branchCode });
|
|
const results = await withNotificationSchemas(branch, async () => {
|
|
const result = await pool.query(
|
|
`SELECT 1 FROM notifications
|
|
WHERE notify_type = $1
|
|
AND title = $2
|
|
AND COALESCE(related_order_code, '') = COALESCE($3::text, '')
|
|
AND created_at >= NOW() - ($4::text || ' hours')::interval
|
|
LIMIT 1`,
|
|
[input.notifyType, input.title, input.relatedOrderCode || null, String(hours)]
|
|
);
|
|
return (result.rowCount ?? 0) > 0;
|
|
});
|
|
return results.some(Boolean);
|
|
}
|
|
|
|
export async function notifyUser(input: {
|
|
userId: string;
|
|
notifyType: string;
|
|
title: string;
|
|
content: string;
|
|
relatedOrderCode?: string | null;
|
|
branchCode?: string | null;
|
|
}) {
|
|
const branch = await resolveNotificationBranch({
|
|
userId: input.userId,
|
|
branchCode: input.branchCode,
|
|
});
|
|
|
|
const insertOnce = async () => {
|
|
const result = await pool.query(
|
|
`INSERT INTO notifications (user_id, notify_type, title, content, related_order_code)
|
|
VALUES ($1, $2, $3, $4, $5)
|
|
RETURNING *`,
|
|
[input.userId, input.notifyType, input.title, input.content, input.relatedOrderCode || null]
|
|
);
|
|
return result.rows[0] || null;
|
|
};
|
|
|
|
let row: Record<string, unknown> | null = null;
|
|
if (branch) {
|
|
row = await runInBranchSchema(branch, insertOnce);
|
|
} else {
|
|
// 平台账号:写入各 active tenant,推送取首条
|
|
const rows = await withNotificationSchemas(null, insertOnce);
|
|
row = rows.find(Boolean) || null;
|
|
}
|
|
|
|
if (row) {
|
|
await pushNotificationCreated(input.userId, row as any);
|
|
}
|
|
}
|
|
|
|
export async function notifyRoleUsers(input: {
|
|
roles: string[];
|
|
notifyType: string;
|
|
title: string;
|
|
content: string;
|
|
relatedOrderCode?: string | null;
|
|
branchCode?: string | null;
|
|
skipIfRecent?: boolean;
|
|
dedupWithinHours?: number;
|
|
}): Promise<boolean> {
|
|
if (input.skipIfRecent !== false) {
|
|
const exists = await hasRecentNotification({
|
|
notifyType: input.notifyType,
|
|
title: input.title,
|
|
relatedOrderCode: input.relatedOrderCode,
|
|
withinHours: input.dedupWithinHours ?? 24,
|
|
branchCode: input.branchCode,
|
|
});
|
|
if (exists) return false;
|
|
}
|
|
const params: unknown[] = [input.roles];
|
|
let branchSql = '';
|
|
if (input.branchCode) {
|
|
params.push(input.branchCode);
|
|
branchSql = `AND p.branch_code = $${params.length}`;
|
|
}
|
|
// profiles / user_roles 在 public
|
|
const users = await rawQuery(
|
|
`SELECT DISTINCT ur.user_id
|
|
FROM public.user_roles ur
|
|
JOIN public.profiles p ON p.id = ur.user_id
|
|
WHERE ur.role = ANY($1::text[]) ${branchSql}
|
|
LIMIT 100`,
|
|
params
|
|
);
|
|
if (!users.rows.length) return false;
|
|
for (const row of users.rows) {
|
|
await notifyUser({
|
|
userId: row.user_id,
|
|
notifyType: input.notifyType,
|
|
title: input.title,
|
|
content: input.content,
|
|
relatedOrderCode: input.relatedOrderCode,
|
|
branchCode: input.branchCode,
|
|
});
|
|
}
|
|
return true;
|
|
}
|
|
|
|
export async function listUserNotifications(userId: string, limit = 50, offset = 0) {
|
|
const branch = await resolveNotificationBranch({ userId });
|
|
if (branch) {
|
|
return runInBranchSchema(branch, async () => {
|
|
const result = await pool.query(
|
|
`SELECT * FROM notifications WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3`,
|
|
[userId, limit, offset]
|
|
);
|
|
return result.rows;
|
|
});
|
|
}
|
|
|
|
const batches = await withNotificationSchemas(null, async () => {
|
|
const result = await pool.query(
|
|
`SELECT * FROM notifications WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2`,
|
|
[userId, limit + offset]
|
|
);
|
|
return result.rows as Array<Record<string, unknown>>;
|
|
});
|
|
const merged = batches.flat();
|
|
const byId = new Map<string, Record<string, unknown>>();
|
|
for (const row of merged) {
|
|
const id = String(row.id || '');
|
|
if (!id || byId.has(id)) continue;
|
|
byId.set(id, row);
|
|
}
|
|
return [...byId.values()]
|
|
.sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || '')))
|
|
.slice(offset, offset + limit);
|
|
}
|
|
|
|
/** 当前用户未读全部标记为已读 */
|
|
export async function markAllNotificationsRead(userId: string): Promise<number> {
|
|
const branch = await resolveNotificationBranch({ userId });
|
|
const counts = await withNotificationSchemas(branch, async () => {
|
|
const result = await pool.query(
|
|
`UPDATE notifications
|
|
SET is_read = true
|
|
WHERE user_id = $1
|
|
AND is_read IS DISTINCT FROM true`,
|
|
[userId]
|
|
);
|
|
return result.rowCount || 0;
|
|
});
|
|
return counts.reduce((sum, n) => sum + n, 0);
|
|
}
|
|
|
|
/** 清空当前用户自己的通知 */
|
|
export async function clearAllNotifications(userId: string): Promise<number> {
|
|
const branch = await resolveNotificationBranch({ userId });
|
|
const counts = await withNotificationSchemas(branch, async () => {
|
|
const result = await pool.query(`DELETE FROM notifications WHERE user_id = $1`, [userId]);
|
|
return result.rowCount || 0;
|
|
});
|
|
return counts.reduce((sum, n) => sum + n, 0);
|
|
}
|
|
|
|
/** 订单删除时同步清理关联通知,返回受影响用户 ID */
|
|
export async function deleteNotificationsByRelatedOrderCode(
|
|
orderCode: string,
|
|
client: Pick<typeof pool, 'query'> = pool
|
|
): Promise<{ deleted: number; userIds: string[] }> {
|
|
const code = String(orderCode || '').trim();
|
|
if (!code) return { deleted: 0, userIds: [] };
|
|
|
|
// 已有 tenant client / ALS 时只清当前 schema;否则扫全部 tenant
|
|
if (client !== pool || getTenantDbStore()?.branchCode) {
|
|
const result = await client.query(
|
|
`DELETE FROM notifications
|
|
WHERE related_order_code = $1
|
|
RETURNING user_id`,
|
|
[code]
|
|
);
|
|
const userIds = [
|
|
...new Set(
|
|
(result.rows || [])
|
|
.map((row: { user_id?: string | null }) => row.user_id)
|
|
.filter((id: string | null | undefined): id is string => Boolean(id))
|
|
),
|
|
];
|
|
return { deleted: result.rowCount || 0, userIds };
|
|
}
|
|
|
|
const batches = await withNotificationSchemas(null, async () => {
|
|
const result = await pool.query(
|
|
`DELETE FROM notifications
|
|
WHERE related_order_code = $1
|
|
RETURNING user_id`,
|
|
[code]
|
|
);
|
|
return {
|
|
deleted: result.rowCount || 0,
|
|
userIds: (result.rows || [])
|
|
.map((row: { user_id?: string | null }) => row.user_id)
|
|
.filter((id: string | null | undefined): id is string => Boolean(id)),
|
|
};
|
|
});
|
|
const userIds = [...new Set(batches.flatMap((b) => b.userIds))];
|
|
const deleted = batches.reduce((sum, b) => sum + b.deleted, 0);
|
|
return { deleted, userIds };
|
|
}
|