import "server-only"; import { and, asc, eq, isNull, lt, lte, sql } from "drizzle-orm"; import { db } from "@/lib/db"; import { canvasFeedback } from "@/lib/db/schema"; import { notificationCenterConfigured, notificationCenterRequest, NotificationCenterError, type NotificationPayload, } from "@/lib/notifications/notification-center"; import { CanvasFeedbackError } from "./feedback-context"; import { feedbackStatusMessage, formatFeedbackTime, type FeedbackReceipt, type FeedbackSnapshot, } from "./feedback-contract"; type FeedbackRow = typeof canvasFeedback.$inferSelect; const backoffMs = [60_000, 300_000, 900_000, 1800_000, 1800_000]; const clip = (value: string, length: number) => value.length > length ? `${value.slice(0, length)}…(完整内容见反馈详情)` : value; const quote = (value: string) => value .replace(/\r\n?/g, "\n") .split("\n") .map((line) => `> ${line}`) .join("\n"); export function buildFeedbackNotification(input: { id: string; description: string; snapshot: FeedbackSnapshot; createdAt: string; appUrl: string; }): NotificationPayload { const { reporter, project, request } = input.snapshot; const content = [ `**反馈人:** ${reporter.name} · ${reporter.department || "未登记部门"}`, `**反馈时间:** ${formatFeedbackTime(input.createdAt)}`, `**画布:** ${project.title}`, `**请求时间:** ${request?.createdAt ? formatFeedbackTime(request.createdAt) : "未关联请求"}`, `**请求号:** ${request?.requestId || "尚未获取;可通过消息或任务编号排查"}`, `**状态 / 模型:** ${request?.status || "页面问题"} / ${request?.model || "未记录"}`, `**处理耗时:** ${request?.durationMs != null ? `${(request.durationMs / 1000).toFixed(1)} 秒` : "未记录或尚未结束"}`, `**用户说明**\n${quote(clip(input.description || "用户未补充说明", 900))}`, `**请求内容**\n${quote(clip(request?.prompt || "未关联具体请求", 1600))}`, `**错误信息**\n${quote(clip(request?.error || input.snapshot.client.errors.join("\n") || "未记录明确错误", 600))}`, `**反馈编号:** ${input.id}`, `**页面版本:** ${input.snapshot.client.pageVersion}`, ].join("\n\n"); return { idempotencyKey: `canvas-feedback:${input.id}:v1`, recipientAlias: "魔礼红", title: "画布问题反馈", content: clip(content, 4400), actionTitle: "查看完整反馈", actionUrl: `${input.appUrl.replace(/\/$/, "")}/feedback/${input.id}`, }; } export const feedbackReceipt = (row: FeedbackRow): FeedbackReceipt => { const status = row.deliveryId && row.status === "pending" ? "accepted" : row.status; return { id: row.id, deliveryId: row.deliveryId, status, message: feedbackStatusMessage(status, row.lastErrorCode), }; }; export async function findCanvasFeedback(id: string) { return ( (await db.select().from(canvasFeedback).where(eq(canvasFeedback.id, id)).limit(1))[0] || null ); } export async function saveCanvasFeedback(input: { id: string; userId: string; description: string; snapshot: FeedbackSnapshot; appUrl: string; }) { const createdAt = new Date(); await db .insert(canvasFeedback) .values({ id: input.id, userId: input.userId, projectId: input.snapshot.project.id, description: input.description, snapshot: input.snapshot, notification: buildFeedbackNotification({ ...input, createdAt: createdAt.toISOString() }), createdAt, }) .onConflictDoNothing({ target: canvasFeedback.id }); const row = await findCanvasFeedback(input.id); if (!row || row.userId !== input.userId || row.projectId !== input.snapshot.project.id) throw new CanvasFeedbackError("反馈编号不可用", 409); // The persisted notification is immutable so a lost response can be retried safely. return row; } export async function deliverCanvasFeedback(id: string) { const [claimed] = await db .update(canvasFeedback) .set({ attempts: sql`${canvasFeedback.attempts} + 1`, nextAttemptAt: new Date(Date.now() + 60_000), }) .where( and( eq(canvasFeedback.id, id), eq(canvasFeedback.status, "pending"), isNull(canvasFeedback.deliveryId), lte(canvasFeedback.nextAttemptAt, new Date()), lt(canvasFeedback.attempts, 5), ), ) .returning(); if (!claimed) return; try { const delivery = await notificationCenterRequest( "POST", "/v1/notifications", claimed.notification, ); await db .update(canvasFeedback) .set({ deliveryId: delivery.id, status: delivery.status, lastErrorCode: delivery.lastErrorCode || null, }) .where(eq(canvasFeedback.id, id)); } catch (error) { const failure = error instanceof NotificationCenterError ? error : new NotificationCenterError("NOTIFICATION_CONNECTION_FAILED", true); await db .update(canvasFeedback) .set({ status: failure.retryable && claimed.attempts < 5 ? "pending" : "failed", lastErrorCode: failure.code, nextAttemptAt: new Date(Date.now() + backoffMs[Math.min(claimed.attempts - 1, 4)]), }) .where(and(eq(canvasFeedback.id, id), isNull(canvasFeedback.deliveryId))); } } export async function refreshCanvasFeedback(row: FeedbackRow) { if (!row.deliveryId) { await deliverCanvasFeedback(row.id); } else if (!["read", "failed"].includes(row.status)) { try { const delivery = await notificationCenterRequest( "GET", `/v1/notifications/${encodeURIComponent(row.deliveryId)}`, ); await db .update(canvasFeedback) .set({ status: delivery.status, lastErrorCode: delivery.lastErrorCode || null }) .where(eq(canvasFeedback.id, row.id)); } catch { /* A status lookup failure does not invalidate the accepted notification. */ } } return (await findCanvasFeedback(row.id))!; } export async function runCanvasFeedbackDelivery() { if (!notificationCenterConfigured()) return; const rows = await db .select({ id: canvasFeedback.id }) .from(canvasFeedback) .where( and( eq(canvasFeedback.status, "pending"), isNull(canvasFeedback.deliveryId), lte(canvasFeedback.nextAttemptAt, new Date()), lt(canvasFeedback.attempts, 5), ), ) .orderBy(asc(canvasFeedback.createdAt)) .limit(10); for (const row of rows) await deliverCanvasFeedback(row.id); }