Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

fix support priority logic

Steven Teya9e74c98cf7f
diff --git a/apps/web/app/api/ai/support-chat/route.ts b/apps/web/app/api/ai/support-chat/route.ts
index 9f83697c63..0213ea3209 100644
--- a/apps/web/app/api/ai/support-chat/route.ts
+++ b/apps/web/app/api/ai/support-chat/route.ts
@@ -34,12 +34,12 @@ export const POST = withSession(async ({ req, session }) => {
getProgramPerformance: getProgramPerformanceTool,
getWorkspaceDetails: getWorkspaceDetailsTool,
createSupportTicket: createSupportTicketTool({
- context: globalContext?.chatLocation ?? "docs",
session,
messages: messages.map((msg) => ({
role: msg.role,
parts: "parts" in msg ? msg.parts : [],
})),
+ globalContext: globalContext || {},
}),
},
});
diff --git a/apps/web/lib/ai/create-support-ticket.ts b/apps/web/lib/ai/create-support-ticket.ts
index 3643e46ba2..b53b549a7a 100644
--- a/apps/web/lib/ai/create-support-ticket.ts
+++ b/apps/web/lib/ai/create-support-ticket.ts
@@ -1,38 +1,32 @@
import { createPlainThread } from "@/lib/plain/create-plain-thread";
-import { SupportChatContext } from "@/ui/support/types";
+import { prisma } from "@dub/prisma";
+import { currencyFormatter } from "@dub/utils";
import { ComponentDividerSpacingSize } from "@team-plain/typescript-sdk";
import { tool } from "ai";
import { z } from "zod";
import { Session } from "../auth/utils";
-
-const createSupportTicketInputSchema = z.object({
- summary: z
- .string()
- .describe(
- "A concise summary of the user's issue based on the conversation.",
- ),
- category: z
- .enum(["billing", "account", "bug", "feature", "other"])
- .describe("The category of the support request."),
-});
+import { GlobalChatContext } from "./build-system-prompt";
export type CreateSupportTicketOptions = {
- context: SupportChatContext;
session: Session;
messages: Array<{
role: string;
parts: Array<{ type: string; text?: string }>;
}>;
+ globalContext: GlobalChatContext;
};
export function createSupportTicketTool(options: CreateSupportTicketOptions) {
- const { context, session, messages } = options;
+ const { globalContext, session, messages } = options;
return tool({
description:
"Creates a support ticket in Plain when the AI cannot resolve the user's issue. Use this when the user explicitly asks to speak with a human, when the issue involves billing disputes, account access problems, or confirmed bugs.",
- inputSchema: createSupportTicketInputSchema,
- execute: async ({ summary, category }) => {
+ inputSchema: z.object({}),
+ execute: async () => {
+ const { accountType, selectedWorkspace, selectedProgram, chatLocation } =
+ globalContext;
+
const chatHistory = messages
.map((msg) => {
const text = msg.parts
@@ -43,6 +37,44 @@ export function createSupportTicketTool(options: CreateSupportTicketOptions) {
})
.join("\n\n");
+ const { priority, additionalMetadata } = await getPriorityAndMetadata(
+ accountType,
+ selectedWorkspace,
+ selectedProgram,
+ session.user.id,
+ );
+
+ const components: Array<Record<string, unknown>> = [
+ {
+ componentText: {
+ text: chatHistory.slice(0, 5000),
+ },
+ },
+ ];
+
+ if (Object.keys(additionalMetadata).length > 0) {
+ components.push(
+ {
+ componentDivider: {
+ dividerSpacingSize: ComponentDividerSpacingSize.L,
+ },
+ },
+ // chat location
+ {
+ componentRow: {
+ rowMainContent: [{ componentText: { text: "Chat Location" } }],
+ rowAsideContent: [{ componentText: { text: chatLocation } }],
+ },
+ },
+ ...Object.entries(additionalMetadata).map(([key, value]) => ({
+ componentRow: {
+ rowMainContent: [{ componentText: { text: key } }],
+ rowAsideContent: [{ componentText: { text: value } }],
+ },
+ })),
+ );
+ }
+
try {
await createPlainThread({
user: {
@@ -50,25 +82,8 @@ export function createSupportTicketTool(options: CreateSupportTicketOptions) {
name: session.user.name ?? "",
email: session.user.email,
},
- title: `[${context.toUpperCase()}] ${summary.slice(0, 80)}`,
- priority: 2,
- components: [
- {
- componentText: {
- text: `**Category:** ${category}\n\n**Summary:** ${summary}`,
- },
- },
- {
- componentDivider: {
- dividerSpacingSize: ComponentDividerSpacingSize.L,
- },
- },
- {
- componentText: {
- text: chatHistory.slice(0, 5000),
- },
- },
- ],
+ priority,
+ components,
});
return {
@@ -87,3 +102,110 @@ export function createSupportTicketTool(options: CreateSupportTicketOptions) {
},
});
}
+
+async function getPriorityAndMetadata(
+ accountType: "workspace" | "partner" | undefined,
+ selectedWorkspace: GlobalChatContext["selectedWorkspace"],
+ selectedProgram: GlobalChatContext["selectedProgram"],
+ userId: string,
+): Promise<{
+ priority: number;
+ additionalMetadata: Record<string, string>;
+}> {
+ let priority = 3;
+ const additionalMetadata: Record<string, string> = {};
+
+ if (accountType === "workspace" && selectedWorkspace?.slug) {
+ const workspace = await prisma.project.findUnique({
+ where: {
+ slug: selectedWorkspace.slug,
+ users: {
+ some: { userId },
+ },
+ },
+ });
+ if (workspace) {
+ switch (workspace.plan) {
+ case "enterprise":
+ case "advanced":
+ priority = 0;
+ break;
+ case "business":
+ priority = 1;
+ break;
+ case "pro":
+ priority = 2;
+ break;
+ }
+ Object.assign(additionalMetadata, {
+ "Workspace Name": workspace.name,
+ "Workspace Slug": workspace.slug,
+ "Workspace Plan": workspace.plan,
+ });
+ }
+ } else if (accountType === "partner" && selectedProgram?.slug) {
+ try {
+ const [enrollmentResult, payoutsSum] = await Promise.all([
+ prisma.programEnrollment.findFirst({
+ where: {
+ partner: {
+ users: { some: { userId } },
+ },
+ program: { slug: selectedProgram.slug },
+ },
+ include: {
+ program: {
+ include: {
+ groups: { where: { slug: "default" } },
+ },
+ },
+ partnerGroup: true,
+ },
+ }),
+ prisma.payout.aggregate({
+ where: {
+ partner: {
+ users: { some: { userId } },
+ },
+ status: {
+ in: ["processing", "processed", "sent", "completed"],
+ },
+ },
+ _sum: { amount: true },
+ }),
+ ]);
+
+ const partnerLifetimePayouts = payoutsSum._sum?.amount ?? 0;
+
+ if (partnerLifetimePayouts > 10_000_00) {
+ priority = 0;
+ } else if (partnerLifetimePayouts > 1_000_00) {
+ priority = 1;
+ } else if (partnerLifetimePayouts > 100_00) {
+ priority = 2;
+ }
+
+ if (enrollmentResult) {
+ const { program, partnerGroup } = enrollmentResult;
+ const holdingPeriodDays =
+ partnerGroup?.holdingPeriodDays ??
+ program.groups[0]?.holdingPeriodDays ??
+ 0;
+ Object.assign(additionalMetadata, {
+ "Program Name": program.name,
+ "Program Slug": program.slug,
+ ...(program.supportEmail
+ ? { "Program Support Email": program.supportEmail }
+ : {}),
+ "Program Holding Period Days": holdingPeriodDays.toString(),
+ "Program Min Payout Amount": program.minPayoutAmount.toString(),
+ "Partner Lifetime Payouts": currencyFormatter(partnerLifetimePayouts),
+ });
+ }
+ } catch {
+ // leave priority at 3 and additionalMetadata empty
+ }
+ }
+
+ return { priority, additionalMetadata };
+}
diff --git a/apps/web/ui/support/chat-interface.tsx b/apps/web/ui/support/chat-interface.tsx
index 0037f0fa4e..1954f1217d 100644
--- a/apps/web/ui/support/chat-interface.tsx
+++ b/apps/web/ui/support/chat-interface.tsx
@@ -13,13 +13,13 @@ import TextareaAutosize from "react-textarea-autosize";
import { toast } from "sonner";
import { Streamdown } from "streamdown";
import "streamdown/styles.css";
-import { MarkdownCodeBlock } from "./code-block";
import useSWR from "swr";
+import { MarkdownCodeBlock } from "./code-block";
import { SupportMessage } from "./message";
import { ProgramCombobox, ProgramSummary } from "./program-combobox";
import { extractSources, SourceCitations } from "./source-citations";
-import { StatusIndicator } from "./status-indicator";
import { StarterQuestions } from "./starter-questions";
+import { StatusIndicator } from "./status-indicator";
import { WorkspaceCombobox, WorkspaceSummary } from "./workspace-combobox";
type AccountType = "workspace" | "partner";
@@ -51,8 +51,10 @@ export function ChatInterface({
const hasPartnerProfile = !!session?.user?.["defaultPartnerId"];
let canChat: boolean;
- if (effectiveAccountType === "workspace") canChat = !!selection.selectedWorkspace;
- else if (effectiveAccountType === "partner") canChat = !!selection.selectedProgram;
+ if (effectiveAccountType === "workspace")
+ canChat = !!selection.selectedWorkspace;
+ else if (effectiveAccountType === "partner")
+ canChat = !!selection.selectedProgram;
else canChat = false;
const { messages, sendMessage, status, setMessages } = useChat({
@@ -93,9 +95,21 @@ export function ChatInterface({
};
const handleEscalate = () => {
- sendMessage({
- text: "I'd like to speak with a human support agent and create a support ticket.",
- });
+ sendMessage(
+ {
+ text: "I'd like to speak with a human support agent and create a support ticket.",
+ },
+ {
+ body: {
+ globalContext: {
+ ...selection,
+ chatLocation:
+ effectiveAccountType === "partner" ? "partners" : "app",
+ accountType: effectiveAccountType,
+ },
+ },
+ },
+ );
setTicketSubmitted(true);
};
@@ -116,7 +130,11 @@ export function ChatInterface({
if (selection.selectedProgram?.slug !== program.slug) setMessages([]);
setSelection((s) => ({
...s,
- selectedProgram: { id: program.id, slug: program.slug, name: program.name },
+ selectedProgram: {
+ id: program.id,
+ slug: program.slug,
+ name: program.name,
+ },
}));
};
@@ -146,7 +164,6 @@ export function ChatInterface({
const canEscalate =
canChat && messages.length >= 2 && status === "ready" && !ticketSubmitted;
-
if (isLoadingSession) {
return (
<div
@@ -328,7 +345,6 @@ export function ChatInterface({
)
: [];
-
// Skip user messages with no text, but keep assistant messages
// visible during tool calls (they temporarily have no text parts)
if (isUser && !textContent) return null;
@@ -352,7 +368,9 @@ export function ChatInterface({
);
return (
<StatusIndicator
- label={isSearching ? "Searching docs..." : "Thinking..."}
+ label={
+ isSearching ? "Searching docs..." : "Thinking..."
+ }
className="py-0.5"
/>
);
@@ -382,12 +400,12 @@ export function ChatInterface({
</a>
),
ul: ({ children }) => (
- <ul className="list-disc list-outside pl-6">
+ <ul className="list-outside list-disc pl-6">
{children}
</ul>
),
ol: ({ children }) => (
- <ol className="list-decimal list-outside pl-6">
+ <ol className="list-outside list-decimal pl-6">
{children}
</ol>
),