278 lines
8.8 KiB
TypeScript
278 lines
8.8 KiB
TypeScript
import type { Prisma } from '@prisma/client'
|
||
import { getDingTalkSendRolloutStatus } from './dingtalkClient'
|
||
|
||
type TransactionClient = Prisma.TransactionClient
|
||
|
||
export type StationNotificationRecipient = {
|
||
id: number
|
||
}
|
||
|
||
export type NotificationRecipient = StationNotificationRecipient & {
|
||
person: { source_userid: string }
|
||
}
|
||
|
||
const isEligibleRecipient = (recipient: {
|
||
id: number
|
||
person: { source_userid: string | null } | null
|
||
}): recipient is NotificationRecipient => Boolean(recipient.person?.source_userid?.trim())
|
||
|
||
const recipientSelect = {
|
||
id: true,
|
||
person: { select: { source_userid: true } }
|
||
} as const
|
||
|
||
export type DingTalkRecipientRollout = {
|
||
enabled: boolean
|
||
fullRollout: boolean
|
||
testUserIds: string[]
|
||
}
|
||
|
||
export const getCurrentDingTalkRecipientRollout = (): DingTalkRecipientRollout => {
|
||
const rollout = getDingTalkSendRolloutStatus()
|
||
return {
|
||
// rollout 表示业务是否要求发送;配置完整性由 Worker/客户端单独处理。
|
||
// 这样全量模式临时缺配置时仍会留下可审计的投递任务,而不是静默丢消息。
|
||
enabled: rollout.enabled,
|
||
fullRollout: rollout.fullRollout,
|
||
testUserIds: rollout.testUserIds
|
||
}
|
||
}
|
||
|
||
const dingTalkPersonWhere = (rollout: DingTalkRecipientRollout) => ({
|
||
status: 'active',
|
||
source_userid: rollout.fullRollout
|
||
? { not: null }
|
||
: { in: rollout.testUserIds }
|
||
})
|
||
|
||
export const findActiveStationUsersByRoles = async (
|
||
client: TransactionClient,
|
||
roles: string[]
|
||
): Promise<StationNotificationRecipient[]> => client.user.findMany({
|
||
where: {
|
||
status: 'active',
|
||
role: { in: roles }
|
||
},
|
||
select: { id: true }
|
||
})
|
||
|
||
export const findActiveStationUsersByIds = async (
|
||
client: TransactionClient,
|
||
userIds: number[]
|
||
): Promise<StationNotificationRecipient[]> => {
|
||
if (userIds.length === 0) return []
|
||
return client.user.findMany({
|
||
where: { id: { in: userIds }, status: 'active' },
|
||
select: { id: true }
|
||
})
|
||
}
|
||
|
||
export const findActiveDingTalkUsersByRoles = async (
|
||
client: TransactionClient,
|
||
roles: string[],
|
||
rollout: DingTalkRecipientRollout = getCurrentDingTalkRecipientRollout()
|
||
): Promise<NotificationRecipient[]> => {
|
||
if (!rollout.enabled) return []
|
||
const users = await client.user.findMany({
|
||
where: {
|
||
status: 'active',
|
||
role: { in: roles },
|
||
person: {
|
||
is: dingTalkPersonWhere(rollout)
|
||
}
|
||
},
|
||
select: recipientSelect
|
||
})
|
||
return users.filter(isEligibleRecipient)
|
||
}
|
||
|
||
export const findActiveDingTalkUsersByIds = async (
|
||
client: TransactionClient,
|
||
userIds: number[],
|
||
rollout: DingTalkRecipientRollout = getCurrentDingTalkRecipientRollout()
|
||
): Promise<NotificationRecipient[]> => {
|
||
if (userIds.length === 0 || !rollout.enabled) return []
|
||
const users = await client.user.findMany({
|
||
where: {
|
||
id: { in: userIds },
|
||
status: 'active',
|
||
person: {
|
||
is: dingTalkPersonWhere(rollout)
|
||
}
|
||
},
|
||
select: recipientSelect
|
||
})
|
||
return users.filter(isEligibleRecipient)
|
||
}
|
||
|
||
export const mergeRecipients = <T extends StationNotificationRecipient>(...groups: T[][]) => {
|
||
const recipients = new Map<number, T>()
|
||
groups.flat().forEach((recipient) => recipients.set(recipient.id, recipient))
|
||
return [...recipients.values()]
|
||
}
|
||
|
||
export const compactNotificationText = (
|
||
value: unknown,
|
||
fallback = '未填写',
|
||
maxLength = 500
|
||
) => {
|
||
const text = String(value ?? '').replace(/\s+/g, ' ').trim()
|
||
const resolved = text || fallback
|
||
return resolved.length <= maxLength
|
||
? resolved
|
||
: `${resolved.slice(0, Math.max(1, maxLength - 1))}…`
|
||
}
|
||
|
||
export const escapeNotificationMarkdownInline = (
|
||
value: unknown,
|
||
fallback = '未填写',
|
||
maxLength = 500
|
||
) => compactNotificationText(value, fallback, maxLength)
|
||
.replace(/([\\`*_{}\[\]()#+\-.!|<>])/g, '\\$1')
|
||
|
||
export const formatBeijingDateTime = (value: Date) => {
|
||
const parts = new Intl.DateTimeFormat('zh-CN', {
|
||
timeZone: 'Asia/Shanghai',
|
||
year: 'numeric',
|
||
month: 'numeric',
|
||
day: 'numeric',
|
||
hour: '2-digit',
|
||
minute: '2-digit',
|
||
hourCycle: 'h23'
|
||
}).formatToParts(value)
|
||
const part = (type: Intl.DateTimeFormatPartTypes) =>
|
||
parts.find((item) => item.type === type)?.value || ''
|
||
return `${part('year')}年${part('month')}月${part('day')}日 ${part('hour')}:${part('minute')}`
|
||
}
|
||
|
||
export const createBusinessNotification = async (
|
||
client: TransactionClient,
|
||
input: {
|
||
eventType: string
|
||
businessType: string
|
||
businessId: number
|
||
title: string
|
||
content: string
|
||
level?: string
|
||
actionUrl: string
|
||
relatedSyncJobId?: number | null
|
||
metadata?: Record<string, unknown>
|
||
stationRecipients: StationNotificationRecipient[]
|
||
dingTalkRecipients: NotificationRecipient[]
|
||
dingTalk: {
|
||
title: string
|
||
content: string
|
||
additionalContents?: string[]
|
||
actionTitle: string
|
||
messageVersion?: string
|
||
}
|
||
rollout?: DingTalkRecipientRollout
|
||
}
|
||
) => {
|
||
const stationRecipients = mergeRecipients(input.stationRecipients)
|
||
const dingTalkRecipients = mergeRecipients(input.dingTalkRecipients)
|
||
const rollout = input.rollout || getCurrentDingTalkRecipientRollout()
|
||
const missingRecipientAttention = rollout.enabled && rollout.fullRollout && dingTalkRecipients.length === 0
|
||
const attentionRecipients = missingRecipientAttention
|
||
? await findActiveStationUsersByRoles(client, ['admin'])
|
||
: []
|
||
if (
|
||
stationRecipients.length === 0 &&
|
||
dingTalkRecipients.length === 0 &&
|
||
attentionRecipients.length === 0
|
||
) return null
|
||
|
||
const baseVersion = compactNotificationText(input.dingTalk.messageVersion, 'v1', 30)
|
||
const contents = [input.dingTalk.content, ...(input.dingTalk.additionalContents || [])]
|
||
const deliveries = dingTalkRecipients.flatMap(recipient => contents.map((content, index) => {
|
||
const partSuffix = index ? `.part-${index + 1}` : ''
|
||
const messageVersion = baseVersion.slice(0, 30 - partSuffix.length) + partSuffix
|
||
const dingtalkUserId = recipient.person.source_userid.trim()
|
||
const idempotencyKey = `${input.eventType}:${input.businessId}:${dingtalkUserId}:${messageVersion}`
|
||
if (idempotencyKey.length > 160) {
|
||
throw new Error('通知幂等键超过160字符,请缩短事件名或消息版本')
|
||
}
|
||
return {
|
||
idempotency_key: idempotencyKey,
|
||
event_type: input.eventType,
|
||
business_type: input.businessType,
|
||
business_id: input.businessId,
|
||
recipient_user_id: recipient.id,
|
||
recipient_dingtalk_userid: dingtalkUserId,
|
||
provider_type: 'notification_center',
|
||
payload_json: JSON.stringify({
|
||
title: input.dingTalk.title,
|
||
content,
|
||
action_title: input.dingTalk.actionTitle,
|
||
action_url: input.actionUrl,
|
||
message_version: messageVersion
|
||
})
|
||
}
|
||
}))
|
||
|
||
const notification = stationRecipients.length > 0
|
||
? await client.notification.create({
|
||
data: {
|
||
title: input.title,
|
||
content: input.content,
|
||
type: input.businessType,
|
||
level: input.level || 'info',
|
||
action_url: input.actionUrl,
|
||
related_sync_job_id: input.relatedSyncJobId ?? null,
|
||
metadata: JSON.stringify({
|
||
event_type: input.eventType,
|
||
business_type: input.businessType,
|
||
business_id: input.businessId,
|
||
record_state: 'record',
|
||
attention_reason: null,
|
||
delivery_count: deliveries.length,
|
||
...(input.metadata || {})
|
||
}),
|
||
recipients: {
|
||
create: stationRecipients.map((recipient) => ({
|
||
user_id: recipient.id,
|
||
is_read: true,
|
||
read_at: new Date()
|
||
}))
|
||
}
|
||
}
|
||
})
|
||
: null
|
||
|
||
const attentionNotification = attentionRecipients.length > 0
|
||
? await client.notification.create({
|
||
data: {
|
||
title: `钉钉未发送:${input.title}`,
|
||
content: `${input.content}\n\n系统未找到有效的钉钉收件人,请管理员检查角色、员工绑定和在职状态。`,
|
||
type: 'dingtalk_delivery',
|
||
level: 'error',
|
||
action_url: '/settings?tab=users',
|
||
// 异常记录点击后应进入人员绑定处理页,不能被同步详情弹窗截获。
|
||
related_sync_job_id: null,
|
||
metadata: JSON.stringify({
|
||
event_type: input.eventType,
|
||
business_type: input.businessType,
|
||
business_id: input.businessId,
|
||
record_state: 'attention',
|
||
attention_reason: 'NO_VALID_DINGTALK_RECIPIENT',
|
||
delivery_count: deliveries.length
|
||
}),
|
||
recipients: {
|
||
create: attentionRecipients.map((recipient) => ({
|
||
user_id: recipient.id
|
||
}))
|
||
}
|
||
}
|
||
})
|
||
: null
|
||
|
||
if (deliveries.length > 0) {
|
||
await client.dingTalkDelivery.createMany({
|
||
data: deliveries,
|
||
skipDuplicates: true
|
||
})
|
||
}
|
||
|
||
return notification || attentionNotification
|
||
}
|