126 lines
5.9 KiB
TypeScript
126 lines
5.9 KiB
TypeScript
import { isSystemAdmin } from '@/lib/department-permission'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { getPublicAppOrigin } from '@/lib/public-app-url'
|
|
import { submitYouyidianNotification } from '@/lib/youyidian-notification-center'
|
|
import { DesktopClientError } from './contract.mjs'
|
|
import { feedbackIdSchema, parseDesktopFeedback } from './feedback-contract'
|
|
|
|
function configuredFeedbackRecipients(): string[] {
|
|
const configured = [
|
|
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID ?? '',
|
|
...(process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS ?? '').split(','),
|
|
].map(id => id.trim()).filter(Boolean)
|
|
return Array.from(new Set(configured))
|
|
}
|
|
|
|
async function feedbackNotificationRecipients() {
|
|
const configured = configuredFeedbackRecipients()
|
|
if (configured.length) return configured
|
|
|
|
const admins = await prisma.user.findMany({
|
|
where: {
|
|
isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true,
|
|
dingtalkUserId: { not: null }, NOT: { dingtalkUserId: '' },
|
|
},
|
|
select: { id: true, dingtalkUserId: true, realName: true, username: true },
|
|
})
|
|
return Array.from(new Set(admins.map(admin => admin.dingtalkUserId?.trim()).filter((id): id is string => Boolean(id))))
|
|
}
|
|
|
|
function notificationText(value: unknown, limit: number) {
|
|
if (typeof value !== 'string') return ''
|
|
return Array.from(value.replace(/\s+/g, ' ').trim()).slice(0, limit).join('')
|
|
.replace(/[\\`*_\[\]~#<>]/g, '\\$&')
|
|
}
|
|
|
|
export async function submitDesktopFeedback(ownerId: string, raw: string) {
|
|
const data = parseDesktopFeedback(raw)
|
|
const { feedbackId } = data
|
|
const { count } = await prisma.desktopClientFeedback.createMany({
|
|
data: { ...data, ownerId },
|
|
skipDuplicates: true,
|
|
})
|
|
const record = await prisma.desktopClientFeedback.findFirst({
|
|
where: { feedbackId, ownerId },
|
|
select: { feedbackId: true, status: true, createdAt: true, owner: { select: { realName: true, username: true } } },
|
|
})
|
|
if (!record) throw new DesktopClientError('反馈编号不可用', 409, 'feedback_id_conflict')
|
|
|
|
const detailPath = `/feedback/${feedbackId}`
|
|
if (count === 1) {
|
|
try {
|
|
const recipients = await feedbackNotificationRecipients()
|
|
if (!recipients.length) {
|
|
console.warn('[desktop-feedback] 没有可用的钉钉收件人', { feedbackId })
|
|
} else {
|
|
const project = data.snapshot.project
|
|
const projectName = project && typeof project === 'object' && !Array.isArray(project) ? project.name : undefined
|
|
const versionBase = notificationText(data.snapshot.clientVersion, 48) || '未提供'
|
|
const commitShort = notificationText(data.snapshot.commit, 7)
|
|
const versionLine = commitShort ? `${versionBase} (${commitShort})` : versionBase
|
|
const agentDaemon = data.snapshot.agentDaemon
|
|
const daemonStderr = agentDaemon && typeof agentDaemon === 'object' && !Array.isArray(agentDaemon)
|
|
? agentDaemon.stderrSummary
|
|
: undefined
|
|
const currentErrorText = notificationText(data.snapshot.currentError, 120)
|
|
|| notificationText(daemonStderr, 120)
|
|
const lines = [
|
|
`反馈人:${notificationText(record.owner.realName || record.owner.username, 80)}`,
|
|
`项目:${notificationText(projectName, 120) || '未提供'}`,
|
|
`客户端版本:${versionLine}`,
|
|
`摘要:${notificationText(data.summary, 120)}`,
|
|
`反馈编号:${feedbackId}`,
|
|
]
|
|
if (currentErrorText) lines.push(`当前报错:${currentErrorText}`)
|
|
const content = lines.join('\n')
|
|
const actionUrl = `${getPublicAppOrigin()}${detailPath}`
|
|
await Promise.all(recipients.map(async recipientUserId => {
|
|
const idempotencyKey = recipients.length === 1
|
|
? `desktop-feedback:${feedbackId}`
|
|
: `desktop-feedback:${feedbackId}:${recipientUserId}`
|
|
let errorCode = 'delivery_failed'
|
|
try {
|
|
const result = await submitYouyidianNotification({
|
|
idempotencyKey, recipientUserId, title: '小壹问题反馈', content, actionTitle: '查看反馈', actionUrl,
|
|
})
|
|
if (result.status !== 'failed') return
|
|
} catch {
|
|
errorCode = 'notification_request_failed'
|
|
}
|
|
console.warn('[desktop-feedback] 通知投递失败', { feedbackId, recipientUserId, errorCode })
|
|
}))
|
|
}
|
|
} catch {
|
|
console.warn('[desktop-feedback] 通知准备失败', { feedbackId, errorCode: 'notification_preparation_failed' })
|
|
}
|
|
}
|
|
return { feedback: { feedbackId, status: record.status, createdAt: record.createdAt, detailPath } }
|
|
}
|
|
|
|
export async function loadDesktopFeedback(id: string, viewerId: string) {
|
|
const parsedId = feedbackIdSchema.safeParse(id)
|
|
if (!parsedId.success) return { status: 404 } as const
|
|
|
|
const viewer = await prisma.user.findUnique({
|
|
where: { id: viewerId },
|
|
select: { role: true, isSuperAdmin: true, isActive: true, status: true, archivedAt: true, dingtalkUserId: true },
|
|
})
|
|
if (!viewer?.isActive || viewer.status !== 'active' || viewer.archivedAt) return { status: 403 } as const
|
|
|
|
const feedbackId = parsedId.data
|
|
const dingtalkId = viewer.dingtalkUserId?.trim()
|
|
const canReadAll = viewer.isSuperAdmin
|
|
|| isSystemAdmin(viewer.role)
|
|
|| (Boolean(dingtalkId) && configuredFeedbackRecipients().includes(dingtalkId!))
|
|
const feedback = await prisma.desktopClientFeedback.findFirst({
|
|
where: { feedbackId, ...(canReadAll ? {} : { ownerId: viewerId }) },
|
|
include: { owner: { select: { realName: true, username: true } } },
|
|
})
|
|
if (feedback) return { status: 200, feedback } as const
|
|
// For an ordinary viewer, only check existence so a 403 never loads another user's snapshot.
|
|
const exists = !canReadAll && await prisma.desktopClientFeedback.findUnique({
|
|
where: { feedbackId }, select: { feedbackId: true },
|
|
})
|
|
return exists ? { status: 403 } as const : { status: 404 } as const
|
|
}
|