The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Improve partner messaging UX
Steven Tey3eeb1aecf065
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page-client.tsxdeleted file mode 100644index 548d50d379..0000000000--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page-client.tsx+++ /dev/null@@ -1,683 +0,0 @@-"use client";--import { parseActionError } from "@/lib/actions/parse-action-errors";-import { PARTNER_ALLOWED_ATTACHMENT_TYPES } from "@/lib/messages/constants";-import { useProgramMessages } from "@/lib/messages/hooks/use-program-messages";-import { markProgramMessagesReadAction } from "@/lib/messages/mark-program-messages-read";-import { messageProgramAction } from "@/lib/messages/message-program";-import { uploadPartnerMessageAttachmentAction } from "@/lib/messages/upload-partner-message-attachment";-import { constructPartnerLink } from "@/lib/partners/construct-partner-link";-import { mutatePrefix } from "@/lib/swr/mutate";-import usePartnerAnalytics from "@/lib/swr/use-partner-analytics";-import usePartnerProfile from "@/lib/swr/use-partner-profile";-import useProgramEnrollment from "@/lib/swr/use-program-enrollment";-import useUser from "@/lib/swr/use-user";-import { ProgramEnrollmentProps } from "@/lib/types";-import { INACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";-import { useMessagesContext } from "@/ui/messages/messages-context";-import { MessagesPanel } from "@/ui/messages/messages-panel";-import { ToggleSidePanelButton } from "@/ui/messages/toggle-side-panel-button";-import { ProgramHelpLinks } from "@/ui/partners/program-help-links";-import { ProgramRewardsPanel } from "@/ui/partners/program-rewards-panel";-import { X } from "@/ui/shared/icons";-import { PendingAttachment } from "@/ui/shared/message-input";-import { Button, Grid, useCopyToClipboard } from "@dub/ui";-import {- Check,- ChevronLeft,- Copy,- EnvelopeArrowRight,- MsgsDotted,-} from "@dub/ui/icons";-import {- OG_AVATAR_URL,- capitalize,- cn,- currencyFormatter,- formatDate,- getPrettyUrl,- nFormatter,-} from "@dub/utils";-import { useAction } from "next-safe-action/hooks";-import Link from "next/link";-import { redirect, useParams } from "next/navigation";-import { useCallback, useState } from "react";-import { toast } from "sonner";-import { v4 as uuid } from "uuid";--export function PartnerMessagesProgramPageClient() {- const { programSlug } = useParams() as { programSlug: string };-- const { user } = useUser();- const { partner } = usePartnerProfile();- const {- programEnrollment,- error: programEnrollmentError,- loading: programEnrollmentLoading,- } = useProgramEnrollment({- swrOpts: {- shouldRetryOnError: (err) => err.status !== 404,- },- });- const enrolledProgram = programEnrollment?.program;-- const {- executeAsync: markProgramMessagesRead,- isPending: isMarkingProgramMessagesRead,- } = useAction(markProgramMessagesReadAction);-- const {- programMessages,- error: errorMessages,- mutate: mutateProgramMessages,- } = useProgramMessages({- query: { programSlug, sortOrder: "asc" },- swrOpts: {- onSuccess: async (data) => {- // Mark unread messages from the program as read- if (- !isMarkingProgramMessagesRead &&- data?.[0]?.messages?.some(- (message) => !message.senderPartnerId && !message.readInApp,- )- ) {- await markProgramMessagesRead({- programSlug,- });- mutatePrefix("/api/partner-profile/messages");- }- },- },- });-- const program = programMessages?.[0]?.program;- const messages = programMessages?.[0]?.messages;-- const isBannedOrRejected = ["banned", "rejected"].includes(- programEnrollment?.status ?? "",- );- const shouldShowExternalSupportEmptyState =- program?.messagingEnabledAt === null || isBannedOrRejected;-- const ExternalSupportEmptyState = () => {- return (- <div className="flex size-full flex-col items-center justify-center px-4">- <MsgsDotted className="size-10 text-neutral-700" />- <div className="mt-6 max-w-md text-center">- <span className="text-content-emphasis text-base font-semibold">- {isBannedOrRejected- ? `This program has ${programEnrollment?.status} you`- : "This program uses external support"}- </span>- <p className="text-content-subtle text-sm font-medium">- {isBannedOrRejected- ? "For more information, please contact the program via email."- : "You can contact them directly via email."}- </p>- </div>- <a- href={- enrolledProgram?.supportEmail- ? `mailto:${enrolledProgram.supportEmail}`- : "#"- }- target="_blank"- >- <Button- className="mt-4 h-9 rounded-lg px-3"- variant="secondary"- text={isBannedOrRejected ? "Contact program" : "Email support"}- icon={<EnvelopeArrowRight className="size-4" />}- />- </a>- </div>- );- };-- const { executeAsync: sendMessage } = useAction(messageProgramAction, {- onError({ error }) {- toast.error(parseActionError(error, "Failed to send message"));- },- });-- const { executeAsync: uploadAttachment } = useAction(- uploadPartnerMessageAttachmentAction,- {- onError({ error }) {- toast.error(parseActionError(error, "Failed to upload file"));- },- },- );-- const [pendingAttachments, setPendingAttachments] = useState<- PendingAttachment[]- >([]);-- const handleAddFiles = useCallback(- async (files: File[]) => {- for (const file of files) {- const id = uuid();- const pending: PendingAttachment = {- id,- file,- name: file.name,- size: file.size,- type: file.type,- uploading: true,- };-- setPendingAttachments((prev) => [...prev, pending]);-- try {- const result = await uploadAttachment({- programSlug,- fileName: file.name,- contentType:- file.type as (typeof PARTNER_ALLOWED_ATTACHMENT_TYPES)[number],- contentLength: file.size,- });-- if (!result?.data) {- setPendingAttachments((prev) => prev.filter((a) => a.id !== id));- continue;- }-- const { signedUrl, storageKey } = result.data;-- const uploadResponse = await fetch(signedUrl, {- method: "PUT",- body: file,- headers: {- "Content-Type": file.type,- },- });-- if (!uploadResponse.ok) {- toast.error("Failed to upload file");- setPendingAttachments((prev) => prev.filter((a) => a.id !== id));- continue;- }-- setPendingAttachments((prev) =>- prev.map((a) =>- a.id === id ? { ...a, uploading: false, storageKey } : a,- ),- );- } catch (error) {- toast.error(- error instanceof Error ? error.message : "Failed to upload file",- );- setPendingAttachments((prev) => prev.filter((a) => a.id !== id));- }- }- },- [programSlug, uploadAttachment],- );-- const handleRemoveAttachment = useCallback((id: string) => {- setPendingAttachments((prev) => prev.filter((a) => a.id !== id));- }, []);-- const { setCurrentPanel } = useMessagesContext();- const [isRightPanelOpen, setIsRightPanelOpen] = useState(true);-- // Redirect if no messages and not enrolled, or messages error- if (- (programEnrollmentError && programMessages?.length === 0) ||- errorMessages- )- redirect(`/messages`);-- return (- <div- className="relative grid h-full"- style={{- gridTemplateColumns: "minmax(340px, 1fr) minmax(0, min-content)",- }}- >- <div className="flex h-full min-h-0 flex-col">- <div className="border-border-subtle flex h-12 shrink-0 items-center justify-between gap-4 border-b px-4 sm:h-16 sm:px-6">- <div className="flex min-w-0 items-center gap-2">- <button- type="button"- onClick={() => setCurrentPanel("index")}- className="@[800px]/page:hidden shrink-0 rounded-lg p-1.5 text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-neutral-900"- >- <ChevronLeft className="size-3.5" />- </button>- <div className="min-w-0">- <button- type="button"- onClick={() => setIsRightPanelOpen((o) => !o)}- disabled={!programEnrollment}- className="-mx-2 -my-1 flex items-center gap-2 rounded-lg px-2.5 py-1.5 transition-colors duration-100 enabled:hover:bg-black/5 enabled:active:bg-black/10"- >- {!program ? (- <>- <div className="size-7 animate-pulse rounded-full bg-neutral-200" />- <div className="h-7 w-36 animate-pulse rounded-md bg-neutral-200" />- </>- ) : (- <>- <img- src={program?.logo || "https://assets.dub.co/logo.png"}- alt={`${program?.name} logo`}- className="size-7 shrink-0 rounded-full"- />- <h2 className="text-content-emphasis text-lg font-semibold leading-7">- {program?.name ?? "Program"}- </h2>- </>- )}- </button>- </div>- </div>- {programEnrollment ? (- <ToggleSidePanelButton- isOpen={isRightPanelOpen}- onClick={() => setIsRightPanelOpen((o) => !o)}- />- ) : programEnrollmentError ? (- <ViewProgramButton programSlug={programSlug} />- ) : null}- </div>- {shouldShowExternalSupportEmptyState && messages?.length === 0 ? (- <ExternalSupportEmptyState />- ) : (- <div className="min-h-0 grow">- <MessagesPanel- messages={messages && partner && user ? messages : undefined}- error={errorMessages}- currentUserType="partner"- currentUserId={partner?.id || ""}- program={program}- pendingAttachments={pendingAttachments}- onAddFiles={handleAddFiles}- onRemoveAttachment={handleRemoveAttachment}- allowedFileTypes={PARTNER_ALLOWED_ATTACHMENT_TYPES}- {...(shouldShowExternalSupportEmptyState && messages?.length- ? {- footerSlot: (- <div className="py-12">- <ExternalSupportEmptyState />- </div>- ),- }- : {})}- onSendMessage={async (message, attachments) => {- const createdAt = new Date();-- try {- await mutateProgramMessages(- async (data) => {- const result = await sendMessage({- programSlug,- text: message,- attachments,- });-- if (result?.data?.message) {- return data- ? [- {- ...data[0],- messages: [- ...data[0].messages,- result.data.message,- ],- },- ]- : [];- }- },- {- optimisticData: (data) =>- data- ? [- {- ...data[0],- messages: [- ...data[0].messages,- {- delivered: false,- id: `tmp_${uuid()}`,- programId: program!.id,- partnerId: partner!.id,- text: message,- subject: null,- type: "direct",- readInApp: null,- readInEmail: null,- createdAt,- updatedAt: createdAt,- senderUserId: user!.id,- senderUser: {- id: user!.id,- name: user!.name,- image: user!.image || null,- },- senderPartnerId: partner!.id,- senderPartner: {- id: partner!.id,- name: partner!.name,- image: partner!.image || null,- },- attachments: attachments.map((a, i) => ({- id: `tmp_att_${i}`,- messageId: "",- ...a,- createdAt,- })),- },- ],- },- ]- : [],- rollbackOnError: true,- },- );-- setPendingAttachments([]);- mutatePrefix("/api/partner-profile/messages");- } catch (e) {- console.log(`Failed to send message: ${e}`);- toast.error(`Failed to send message: ${e}`);- }- }}- />- </div>- )}- </div>-- {/* Right panel - Profile */}- <div- className={cn(- "absolute right-0 top-0 h-full min-h-0 w-0 overflow-hidden bg-white shadow-lg transition-[width]",- "@[1082px]/page:shadow-none @[1082px]/page:relative",- isRightPanelOpen && "w-full sm:w-[400px]",- )}- >- <div className="border-border-subtle flex size-full min-h-0 w-full flex-col border-l sm:w-[400px]">- <div className="border-border-subtle flex h-12 shrink-0 items-center justify-between gap-4 border-b px-4 sm:h-16 sm:px-6">- <h2 className="text-content-emphasis text-lg font-semibold leading-7">- Program- </h2>- <div className="flex items-center gap-2">- <ViewProgramButton programSlug={programSlug} />- <button- type="button"- onClick={() => setIsRightPanelOpen(false)}- className="@[1082px]/page:hidden rounded-lg p-2 text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-neutral-900"- >- <X className="size-4" />- </button>- </div>- </div>- <div className="bg-bg-muted scrollbar-hide flex grow flex-col overflow-y-scroll">- {programEnrollmentLoading ? (- <ProgramInfoPanelSkeleton />- ) : programEnrollment ? (- <ProgramInfoPanel programEnrollment={programEnrollment} />- ) : null}- </div>- </div>- </div>- </div>- );-}--function ProgramInfoPanel({- programEnrollment,-}: {- programEnrollment: ProgramEnrollmentProps;-}) {- const program = programEnrollment.program;- const partnerLink = constructPartnerLink({- group: programEnrollment.group,- link: programEnrollment.links?.[0],- });-- const { data: statsTotals } = usePartnerAnalytics({- event: "composite",- interval: "all",- });-- const [copied, copyToClipboard] = useCopyToClipboard();-- return (- <>- {/* Program info */}- <div className="border-border-subtle relative shrink-0 overflow-hidden border-b">- <div className="absolute inset-y-0 right-0 w-96 [mask-image:radial-gradient(100%_100%_at_100%_0%,black_30%,transparent)]">- <Grid cellSize={20} className="text-neutral-200" />- </div>- <div className="relative flex flex-col gap-4 p-6">- <img- src={program.logo || `${OG_AVATAR_URL}${program.name}`}- alt={`${program.name} logo`}- className="size-10 rounded-full"- />- <div className="flex flex-col">- <span className="text-content-emphasis block truncate text-lg font-semibold">- {program.name}- </span>- <span className="text-content-subtle text-sm font-medium">- {INACTIVE_ENROLLMENT_STATUSES.includes(programEnrollment.status)- ? `You are ${programEnrollment.status} from this program`- : `Partner since ${formatDate(programEnrollment.createdAt)}`}- </span>- </div>- </div>- </div>-- {/* Referral link */}- {programEnrollment.links &&- programEnrollment.links.length > 0 &&- !INACTIVE_ENROLLMENT_STATUSES.includes(programEnrollment.status) && (- <div className="pl-6 pr-6 pt-7">- <div className="flex items-end justify-between">- <h3 className="text-content-emphasis text-sm font-semibold">- Referral link- </h3>- <Link- href={`/programs/${program.slug}/links`}- target="_blank"- className="text-sm font-medium text-neutral-500 hover:text-neutral-700"- >- View all- </Link>- </div>-- <div className="relative mt-2">- <input- type="text"- readOnly- value={getPrettyUrl(partnerLink)}- className="text-content-default focus:border-border-emphasis bg-bg-default block h-11 w-full rounded-xl border border-neutral-200 pl-3 pr-12 text-sm focus:outline-none focus:ring-neutral-500"- />- {/* Gradient fade overlay */}- <div className="pointer-events-none absolute right-12 top-1 h-8 w-10 bg-gradient-to-r from-transparent to-white" />- <button- type="button"- onClick={() => {- copyToClipboard(partnerLink);- toast.success("Link copied");- }}- className="absolute right-2 top-2 flex h-7 w-7 items-center justify-center rounded-lg bg-neutral-900 text-white transition-colors hover:bg-gray-800"- >- <div className="relative size-3">- <div- className={cn(- "absolute inset-0 transition-[transform,opacity]",- copied && "translate-y-1 opacity-0",- )}- >- <Copy className="size-3" />- </div>- <div- className={cn(- "absolute inset-0 transition-[transform,opacity]",- !copied && "translate-y-1 opacity-0",- )}- >- <Check className="size-3" />- </div>- </div>- </button>- </div>- </div>- )}-- {/* Stats */}- <div className="pl-6 pr-6 pt-7">- <h3 className="text-content-emphasis text-sm font-semibold">- Performance- </h3>- <div className="divide-border-subtle border-border-subtle mt-2 divide-y rounded-xl border">- <div className="divide-border-subtle grid grid-cols-3 divide-x">- {["clicks", "leads", "sales"].map((event) => (- <div key={event} className="flex flex-col px-3 py-2.5">- <span className="text-content-subtle text-xs font-medium">- {capitalize(event)}- </span>- {statsTotals ? (- <span className="text-content-emphasis text-sm font-medium">- {nFormatter(statsTotals?.[event], { full: true })}- </span>- ) : (- <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-200" />- )}- </div>- ))}- </div>- <div className="divide-border-subtle grid grid-cols-2 divide-x">- {[- { label: "Revenue", value: statsTotals?.saleAmount },- { label: "Earnings", value: programEnrollment.totalCommissions },- ].map(({ label, value }) => (- <div key={label} className="flex flex-col px-3 py-2.5">- <span className="text-content-subtle text-xs font-medium">- {label}- </span>- {value !== undefined ? (- <span className="text-content-emphasis text-sm font-medium">- {currencyFormatter(value)}- </span>- ) : (- <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-200" />- )}- </div>- ))}- </div>- </div>- </div>-- {/* Rewards */}- {!INACTIVE_ENROLLMENT_STATUSES.includes(programEnrollment.status) && (- <div className="pl-6 pr-6 pt-7">- <h3 className="text-content-emphasis text-sm font-semibold">- Rewards- </h3>- <div className="mt-1">- <ProgramRewardsPanel- rewards={programEnrollment.rewards ?? []}- discount={programEnrollment.discount}- />- </div>- </div>- )}-- {/* Help & support */}- <div className="border-border-subtle pl-6 pr-6 pt-7">- <h3 className="text-content-emphasis text-sm font-semibold">- Help and support- </h3>- <div className="-ml-2 mt-1">- <ProgramHelpLinks />- </div>- </div>- </>- );-}--function ProgramInfoPanelSkeleton() {- return (- <>- {/* Program info skeleton */}- <div className="border-border-subtle relative shrink-0 overflow-hidden border-b">- <div className="absolute inset-y-0 right-0 w-96 [mask-image:radial-gradient(100%_100%_at_100%_0%,black_30%,transparent)]">- <Grid cellSize={20} className="text-neutral-200" />- </div>- <div className="relative flex flex-col gap-4 p-6">- <div className="size-10 animate-pulse rounded-full bg-neutral-200" />- <div className="flex flex-col gap-2">- <div className="h-6 w-32 animate-pulse rounded-md bg-neutral-200" />- <div className="h-4 w-40 animate-pulse rounded-md bg-neutral-200" />- </div>- </div>- </div>-- {/* Referral link skeleton */}- <div className="pl-6 pr-6 pt-7">- <div className="flex items-end justify-between">- <div className="h-5 w-24 animate-pulse rounded-md bg-neutral-200" />- <div className="h-4 w-16 animate-pulse rounded-md bg-neutral-200" />- </div>- <div className="relative mt-2">- <div className="h-11 w-full animate-pulse rounded-xl bg-neutral-200" />- </div>- </div>-- {/* Stats skeleton */}- <div className="pl-6 pr-6 pt-7">- <div className="h-5 w-24 animate-pulse rounded-md bg-neutral-200" />- <div className="divide-border-subtle border-border-subtle mt-2 divide-y rounded-xl border">- <div className="divide-border-subtle grid grid-cols-3 divide-x">- {[...Array(3)].map((_, idx) => (- <div key={idx} className="flex flex-col px-3 py-2.5">- <div className="h-3 w-12 animate-pulse rounded-md bg-neutral-200" />- <div className="mt-1 h-5 w-16 animate-pulse rounded-md bg-neutral-200" />- </div>- ))}- </div>- <div className="divide-border-subtle grid grid-cols-2 divide-x">- {[...Array(2)].map((_, idx) => (- <div key={idx} className="flex flex-col px-3 py-2.5">- <div className="h-3 w-16 animate-pulse rounded-md bg-neutral-200" />- <div className="mt-1 h-5 w-20 animate-pulse rounded-md bg-neutral-200" />- </div>- ))}- </div>- </div>- </div>-- {/* Rewards skeleton */}- <div className="pl-6 pr-6 pt-7">- <div className="h-5 w-16 animate-pulse rounded-md bg-neutral-200" />- <div className="mt-1">- <div className="h-20 w-full animate-pulse rounded-lg bg-neutral-200" />- </div>- </div>-- {/* Help & support skeleton */}- <div className="border-border-subtle pl-6 pr-6 pt-7">- <div className="h-5 w-32 animate-pulse rounded-md bg-neutral-200" />- <div className="mt-1">- <div className="h-16 w-full animate-pulse rounded-lg bg-neutral-200" />- </div>- </div>- </>- );-}--function ViewProgramButton({ programSlug }: { programSlug: string }) {- return (- <Link href={`/programs/${programSlug}`} target="_blank">- <Button- variant="secondary"- text="View program"- className="h-8 rounded-lg px-3"- />- </Link>- );-}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page.tsxindex d7c4be8226..7d950b233c 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page.tsx@@ -1,5 +1,691 @@-import { PartnerMessagesProgramPageClient } from "./page-client";+"use client";++import { parseActionError } from "@/lib/actions/parse-action-errors";+import { PARTNER_ALLOWED_ATTACHMENT_TYPES } from "@/lib/messages/constants";+import { useProgramMessages } from "@/lib/messages/hooks/use-program-messages";+import { markProgramMessagesReadAction } from "@/lib/messages/mark-program-messages-read";+import { messageProgramAction } from "@/lib/messages/message-program";+import { uploadPartnerMessageAttachmentAction } from "@/lib/messages/upload-partner-message-attachment";+import { constructPartnerLink } from "@/lib/partners/construct-partner-link";+import { mutatePrefix } from "@/lib/swr/mutate";+import usePartnerAnalytics from "@/lib/swr/use-partner-analytics";+import usePartnerProfile from "@/lib/swr/use-partner-profile";+import useProgramEnrollment from "@/lib/swr/use-program-enrollment";+import useUser from "@/lib/swr/use-user";+import { ProgramEnrollmentProps } from "@/lib/types";+import { INACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";+import { useMessagesContext } from "@/ui/messages/messages-context";+import { MessagesPanel } from "@/ui/messages/messages-panel";+import { ToggleSidePanelButton } from "@/ui/messages/toggle-side-panel-button";+import { ProgramHelpLinks } from "@/ui/partners/program-help-links";+import { ProgramRewardsPanel } from "@/ui/partners/program-rewards-panel";+import { X } from "@/ui/shared/icons";+import { PendingAttachment } from "@/ui/shared/message-input";+import { Button, Grid, useCopyToClipboard } from "@dub/ui";+import {+ Check,+ ChevronLeft,+ Copy,+ EnvelopeArrowRight,+ LoadingSpinner,+ MsgsDotted,+} from "@dub/ui/icons";+import {+ OG_AVATAR_URL,+ capitalize,+ cn,+ currencyFormatter,+ formatDate,+ getPrettyUrl,+ nFormatter,+} from "@dub/utils";+import { useAction } from "next-safe-action/hooks";+import Link from "next/link";+import { redirect, useParams } from "next/navigation";+import { useCallback, useState } from "react";+import { toast } from "sonner";+import { v4 as uuid } from "uuid";export default function PartnerMessagesProgramPage() {- return <PartnerMessagesProgramPageClient />;+ const { programSlug } = useParams() as { programSlug: string };++ const { user } = useUser();+ const { partner } = usePartnerProfile();+ const { programEnrollment, error: programEnrollmentError } =+ useProgramEnrollment({+ swrOpts: {+ shouldRetryOnError: (err) => err.status !== 404,+ },+ });+ const enrolledProgram = programEnrollment?.program;++ const {+ executeAsync: markProgramMessagesRead,+ isPending: isMarkingProgramMessagesRead,+ } = useAction(markProgramMessagesReadAction);++ const {+ programMessages,+ error: errorMessages,+ mutate: mutateProgramMessages,+ } = useProgramMessages({+ query: { programSlug, sortOrder: "asc" },+ swrOpts: {+ onSuccess: async (data) => {+ // Mark unread messages from the program as read+ if (+ !isMarkingProgramMessagesRead &&+ data?.[0]?.messages?.some(+ (message) => !message.senderPartnerId && !message.readInApp,+ )+ ) {+ await markProgramMessagesRead({+ programSlug,+ });+ mutatePrefix("/api/partner-profile/messages");+ }+ },+ },+ });++ const program = programMessages?.[0]?.program;+ const messages = programMessages?.[0]?.messages;++ const isInactiveEnrollment =+ programEnrollment?.status &&+ INACTIVE_ENROLLMENT_STATUSES.includes(programEnrollment.status);++ const shouldShowExternalSupportEmptyState =+ isInactiveEnrollment || program?.messagingEnabledAt === null;++ const ExternalSupportEmptyState = () => {+ return (+ <div className="flex size-full flex-col items-center justify-center px-4">+ <MsgsDotted className="size-10 text-neutral-700" />+ <div className="mt-6 max-w-md text-center">+ <span className="text-content-emphasis text-base font-semibold">+ {isInactiveEnrollment+ ? `You have been ${programEnrollment.status} from this program`+ : "This program uses external support"}+ </span>+ <p className="text-content-subtle text-sm font-medium">+ {isInactiveEnrollment+ ? "For more information, please contact the program via email."+ : "You can contact them directly via email."}+ </p>+ </div>+ <a+ href={+ enrolledProgram?.supportEmail+ ? `mailto:${enrolledProgram.supportEmail}`+ : "#"+ }+ target="_blank"+ >+ <Button+ className="mt-4 h-9 rounded-lg px-3"+ variant="secondary"+ text={isInactiveEnrollment ? "Contact program" : "Email support"}+ icon={<EnvelopeArrowRight className="size-4" />}+ />+ </a>+ </div>+ );+ };++ const { executeAsync: sendMessage } = useAction(messageProgramAction, {+ onError({ error }) {+ toast.error(parseActionError(error, "Failed to send message"));+ },+ });++ const { executeAsync: uploadAttachment } = useAction(+ uploadPartnerMessageAttachmentAction,+ {+ onError({ error }) {+ toast.error(parseActionError(error, "Failed to upload file"));+ },+ },+ );++ const [pendingAttachments, setPendingAttachments] = useState<+ PendingAttachment[]+ >([]);++ const handleAddFiles = useCallback(+ async (files: File[]) => {+ for (const file of files) {+ const id = uuid();+ const pending: PendingAttachment = {+ id,+ file,+ name: file.name,+ size: file.size,+ type: file.type,+ uploading: true,+ };++ setPendingAttachments((prev) => [...prev, pending]);++ try {+ const result = await uploadAttachment({+ programSlug,+ fileName: file.name,+ contentType:+ file.type as (typeof PARTNER_ALLOWED_ATTACHMENT_TYPES)[number],+ contentLength: file.size,+ });++ if (!result?.data) {+ setPendingAttachments((prev) => prev.filter((a) => a.id !== id));+ continue;+ }++ const { signedUrl, storageKey } = result.data;++ const uploadResponse = await fetch(signedUrl, {+ method: "PUT",+ body: file,+ headers: {+ "Content-Type": file.type,+ },+ });++ if (!uploadResponse.ok) {+ toast.error("Failed to upload file");+ setPendingAttachments((prev) => prev.filter((a) => a.id !== id));+ continue;+ }++ setPendingAttachments((prev) =>+ prev.map((a) =>+ a.id === id ? { ...a, uploading: false, storageKey } : a,+ ),+ );+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Failed to upload file",+ );+ setPendingAttachments((prev) => prev.filter((a) => a.id !== id));+ }+ }+ },+ [programSlug, uploadAttachment],+ );++ const handleRemoveAttachment = useCallback((id: string) => {+ setPendingAttachments((prev) => prev.filter((a) => a.id !== id));+ }, []);++ const { setCurrentPanel } = useMessagesContext();+ const [isRightPanelOpen, setIsRightPanelOpen] = useState(true);++ // Redirect if no messages and not enrolled, or messages error+ if (+ (programEnrollmentError && programMessages?.length === 0) ||+ errorMessages+ ) {+ redirect(`/messages`);+ }++ return (+ <div+ className="relative grid h-full"+ style={{+ gridTemplateColumns: "minmax(340px, 1fr) minmax(0, min-content)",+ }}+ >+ <div className="flex h-full min-h-0 flex-col">+ <div className="border-border-subtle flex h-12 shrink-0 items-center justify-between gap-4 border-b px-4 sm:h-16 sm:px-6">+ <div className="flex min-w-0 items-center gap-2">+ <button+ type="button"+ onClick={() => setCurrentPanel("index")}+ className="@[800px]/page:hidden shrink-0 rounded-lg p-1.5 text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-neutral-900"+ >+ <ChevronLeft className="size-3.5" />+ </button>+ <div className="min-w-0">+ <button+ type="button"+ onClick={() => setIsRightPanelOpen((o) => !o)}+ disabled={!programEnrollment}+ className="-mx-2 -my-1 flex items-center gap-2 rounded-lg px-2.5 py-1.5 transition-colors duration-100 enabled:hover:bg-black/5 enabled:active:bg-black/10"+ >+ {!program ? (+ <>+ <div className="size-7 animate-pulse rounded-full bg-neutral-200" />+ <div className="h-7 w-36 animate-pulse rounded-md bg-neutral-200" />+ </>+ ) : (+ <>+ <img+ src={program?.logo || "https://assets.dub.co/logo.png"}+ alt={`${program?.name} logo`}+ className="size-7 shrink-0 rounded-full"+ />+ <h2 className="text-content-emphasis text-lg font-semibold leading-7">+ {program?.name ?? "Program"}+ </h2>+ </>+ )}+ </button>+ </div>+ </div>+ {programEnrollment ? (+ <ToggleSidePanelButton+ isOpen={isRightPanelOpen}+ onClick={() => setIsRightPanelOpen((o) => !o)}+ />+ ) : programEnrollmentError ? (+ <ViewProgramButton programSlug={programSlug} />+ ) : null}+ </div>+ {!programEnrollment ? (+ <div className="flex size-full items-center justify-center">+ <LoadingSpinner />+ </div>+ ) : shouldShowExternalSupportEmptyState && messages?.length === 0 ? (+ <ExternalSupportEmptyState />+ ) : (+ <div className="min-h-0 grow">+ <MessagesPanel+ messages={messages && partner && user ? messages : undefined}+ error={errorMessages}+ currentUserType="partner"+ currentUserId={partner?.id || ""}+ program={program}+ pendingAttachments={pendingAttachments}+ onAddFiles={handleAddFiles}+ onRemoveAttachment={handleRemoveAttachment}+ allowedFileTypes={PARTNER_ALLOWED_ATTACHMENT_TYPES}+ {...(shouldShowExternalSupportEmptyState && messages?.length+ ? {+ footerSlot: (+ <div className="py-12">+ <ExternalSupportEmptyState />+ </div>+ ),+ }+ : {})}+ onSendMessage={async (message, attachments) => {+ const createdAt = new Date();++ try {+ await mutateProgramMessages(+ async (data) => {+ const result = await sendMessage({+ programSlug,+ text: message,+ attachments,+ });++ if (result?.data?.message) {+ return data+ ? [+ {+ ...data[0],+ messages: [+ ...data[0].messages,+ result.data.message,+ ],+ },+ ]+ : [];+ }+ },+ {+ optimisticData: (data) =>+ data+ ? [+ {+ ...data[0],+ messages: [+ ...data[0].messages,+ {+ delivered: false,+ id: `tmp_${uuid()}`,+ programId: program!.id,+ partnerId: partner!.id,+ text: message,+ subject: null,+ type: "direct",+ readInApp: null,+ readInEmail: null,+ createdAt,+ updatedAt: createdAt,+ senderUserId: user!.id,+ senderUser: {+ id: user!.id,+ name: user!.name,+ image: user!.image || null,+ },+ senderPartnerId: partner!.id,+ senderPartner: {+ id: partner!.id,+ name: partner!.name,+ image: partner!.image || null,+ },+ attachments: attachments.map((a, i) => ({+ id: `tmp_att_${i}`,+ messageId: "",+ ...a,+ createdAt,+ })),+ },+ ],+ },+ ]+ : [],+ rollbackOnError: true,+ },+ );++ setPendingAttachments([]);+ mutatePrefix("/api/partner-profile/messages");+ } catch (e) {+ console.log(`Failed to send message: ${e}`);+ toast.error(`Failed to send message: ${e}`);+ }+ }}+ />+ </div>+ )}+ </div>++ {/* Right panel - Profile */}+ <div+ className={cn(+ "absolute right-0 top-0 h-full min-h-0 w-0 overflow-hidden bg-white shadow-lg transition-[width]",+ "@[1082px]/page:shadow-none @[1082px]/page:relative",+ isRightPanelOpen && "w-full sm:w-[400px]",+ )}+ >+ <div className="border-border-subtle flex size-full min-h-0 w-full flex-col border-l sm:w-[400px]">+ <div className="border-border-subtle flex h-12 shrink-0 items-center justify-between gap-4 border-b px-4 sm:h-16 sm:px-6">+ <h2 className="text-content-emphasis text-lg font-semibold leading-7">+ Program+ </h2>+ <div className="flex items-center gap-2">+ <ViewProgramButton programSlug={programSlug} />+ <button+ type="button"+ onClick={() => setIsRightPanelOpen(false)}+ className="@[1082px]/page:hidden rounded-lg p-2 text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-neutral-900"+ >+ <X className="size-4" />+ </button>+ </div>+ </div>+ <div className="bg-bg-muted scrollbar-hide flex grow flex-col overflow-y-scroll">+ {!programEnrollment ? (+ <ProgramInfoPanelSkeleton />+ ) : (+ <ProgramInfoPanel programEnrollment={programEnrollment} />+ )}+ </div>+ </div>+ </div>+ </div>+ );+}++function ProgramInfoPanel({+ programEnrollment,+}: {+ programEnrollment: ProgramEnrollmentProps;+}) {+ const program = programEnrollment.program;+ const partnerLink = constructPartnerLink({+ group: programEnrollment.group,+ link: programEnrollment.links?.[0],+ });++ const { data: statsTotals } = usePartnerAnalytics({+ event: "composite",+ interval: "all",+ });++ const [copied, copyToClipboard] = useCopyToClipboard();++ const isInactiveEnrollment = INACTIVE_ENROLLMENT_STATUSES.includes(+ programEnrollment.status,+ );++ return (+ <>+ {/* Program info */}+ <div className="border-border-subtle relative shrink-0 overflow-hidden border-b">+ <div className="absolute inset-y-0 right-0 w-96 [mask-image:radial-gradient(100%_100%_at_100%_0%,black_30%,transparent)]">+ <Grid cellSize={20} className="text-neutral-200" />+ </div>+ <div className="relative flex flex-col gap-4 p-6">+ <img+ src={program.logo || `${OG_AVATAR_URL}${program.name}`}+ alt={`${program.name} logo`}+ className="size-10 rounded-full"+ />+ <div className="flex flex-col">+ <span className="text-content-emphasis block truncate text-lg font-semibold">+ {program.name}+ </span>+ <span className="text-content-subtle text-sm font-medium">+ {isInactiveEnrollment+ ? `You are ${programEnrollment.status} from this program`+ : `Partner since ${formatDate(programEnrollment.createdAt)}`}+ </span>+ </div>+ </div>+ </div>++ {/* Referral link */}+ {programEnrollment.links &&+ programEnrollment.links.length > 0 &&+ !isInactiveEnrollment && (+ <div className="pl-6 pr-6 pt-7">+ <div className="flex items-end justify-between">+ <h3 className="text-content-emphasis text-sm font-semibold">+ Referral link+ </h3>+ <Link+ href={`/programs/${program.slug}/links`}+ target="_blank"+ className="text-sm font-medium text-neutral-500 hover:text-neutral-700"+ >+ View all+ </Link>+ </div>++ <div className="relative mt-2">+ <input+ type="text"+ readOnly+ value={getPrettyUrl(partnerLink)}+ className="text-content-default focus:border-border-emphasis bg-bg-default block h-11 w-full rounded-xl border border-neutral-200 pl-3 pr-12 text-sm focus:outline-none focus:ring-neutral-500"+ />+ {/* Gradient fade overlay */}+ <div className="pointer-events-none absolute right-12 top-1 h-8 w-10 bg-gradient-to-r from-transparent to-white" />+ <button+ type="button"+ onClick={() => {+ copyToClipboard(partnerLink);+ toast.success("Link copied");+ }}+ className="absolute right-2 top-2 flex h-7 w-7 items-center justify-center rounded-lg bg-neutral-900 text-white transition-colors hover:bg-gray-800"+ >+ <div className="relative size-3">+ <div+ className={cn(+ "absolute inset-0 transition-[transform,opacity]",+ copied && "translate-y-1 opacity-0",+ )}+ >+ <Copy className="size-3" />+ </div>+ <div+ className={cn(+ "absolute inset-0 transition-[transform,opacity]",+ !copied && "translate-y-1 opacity-0",+ )}+ >+ <Check className="size-3" />+ </div>+ </div>+ </button>+ </div>+ </div>+ )}++ {/* Stats */}+ <div className="pl-6 pr-6 pt-7">+ <h3 className="text-content-emphasis text-sm font-semibold">+ Performance+ </h3>+ <div className="divide-border-subtle border-border-subtle mt-2 divide-y rounded-xl border">+ <div className="divide-border-subtle grid grid-cols-3 divide-x">+ {["clicks", "leads", "sales"].map((event) => (+ <div key={event} className="flex flex-col px-3 py-2.5">+ <span className="text-content-subtle text-xs font-medium">+ {capitalize(event)}+ </span>+ {statsTotals ? (+ <span className="text-content-emphasis text-sm font-medium">+ {nFormatter(statsTotals?.[event], { full: true })}+ </span>+ ) : (+ <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-200" />+ )}+ </div>+ ))}+ </div>+ <div className="divide-border-subtle grid grid-cols-2 divide-x">+ {[+ { label: "Revenue", value: statsTotals?.saleAmount },+ { label: "Earnings", value: programEnrollment.totalCommissions },+ ].map(({ label, value }) => (+ <div key={label} className="flex flex-col px-3 py-2.5">+ <span className="text-content-subtle text-xs font-medium">+ {label}+ </span>+ {value !== undefined ? (+ <span className="text-content-emphasis text-sm font-medium">+ {currencyFormatter(value)}+ </span>+ ) : (+ <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-200" />+ )}+ </div>+ ))}+ </div>+ </div>+ </div>++ {/* Rewards */}+ {!isInactiveEnrollment && (+ <div className="pl-6 pr-6 pt-7">+ <h3 className="text-content-emphasis text-sm font-semibold">+ Rewards+ </h3>+ <div className="mt-1">+ <ProgramRewardsPanel+ rewards={programEnrollment.rewards ?? []}+ discount={programEnrollment.discount}+ />+ </div>+ </div>+ )}++ {/* Help & support */}+ <div className="border-border-subtle pl-6 pr-6 pt-7">+ <h3 className="text-content-emphasis text-sm font-semibold">+ Help and support+ </h3>+ <div className="-ml-2 mt-1">+ <ProgramHelpLinks />+ </div>+ </div>+ </>+ );+}++function ProgramInfoPanelSkeleton() {+ return (+ <>+ {/* Program info skeleton */}+ <div className="border-border-subtle relative shrink-0 overflow-hidden border-b">+ <div className="absolute inset-y-0 right-0 w-96 [mask-image:radial-gradient(100%_100%_at_100%_0%,black_30%,transparent)]">+ <Grid cellSize={20} className="text-neutral-200" />+ </div>+ <div className="relative flex flex-col gap-4 p-6">+ <div className="size-10 animate-pulse rounded-full bg-neutral-200" />+ <div className="flex flex-col gap-2">+ <div className="h-6 w-32 animate-pulse rounded-md bg-neutral-200" />+ <div className="h-4 w-40 animate-pulse rounded-md bg-neutral-200" />+ </div>+ </div>+ </div>++ {/* Referral link skeleton */}+ <div className="pl-6 pr-6 pt-7">+ <div className="flex items-end justify-between">+ <div className="h-5 w-24 animate-pulse rounded-md bg-neutral-200" />+ <div className="h-4 w-16 animate-pulse rounded-md bg-neutral-200" />+ </div>+ <div className="relative mt-2">+ <div className="h-11 w-full animate-pulse rounded-xl bg-neutral-200" />+ </div>+ </div>++ {/* Stats skeleton */}+ <div className="pl-6 pr-6 pt-7">+ <div className="h-5 w-24 animate-pulse rounded-md bg-neutral-200" />+ <div className="divide-border-subtle border-border-subtle mt-2 divide-y rounded-xl border">+ <div className="divide-border-subtle grid grid-cols-3 divide-x">+ {[...Array(3)].map((_, idx) => (+ <div key={idx} className="flex flex-col px-3 py-2.5">+ <div className="h-3 w-12 animate-pulse rounded-md bg-neutral-200" />+ <div className="mt-1 h-5 w-16 animate-pulse rounded-md bg-neutral-200" />+ </div>+ ))}+ </div>+ <div className="divide-border-subtle grid grid-cols-2 divide-x">+ {[...Array(2)].map((_, idx) => (+ <div key={idx} className="flex flex-col px-3 py-2.5">+ <div className="h-3 w-16 animate-pulse rounded-md bg-neutral-200" />+ <div className="mt-1 h-5 w-20 animate-pulse rounded-md bg-neutral-200" />+ </div>+ ))}+ </div>+ </div>+ </div>++ {/* Rewards skeleton */}+ <div className="pl-6 pr-6 pt-7">+ <div className="h-5 w-16 animate-pulse rounded-md bg-neutral-200" />+ <div className="mt-1">+ <div className="h-20 w-full animate-pulse rounded-lg bg-neutral-200" />+ </div>+ </div>++ {/* Help & support skeleton */}+ <div className="border-border-subtle pl-6 pr-6 pt-7">+ <div className="h-5 w-32 animate-pulse rounded-md bg-neutral-200" />+ <div className="mt-1">+ <div className="h-16 w-full animate-pulse rounded-lg bg-neutral-200" />+ </div>+ </div>+ </>+ );+}++function ViewProgramButton({ programSlug }: { programSlug: string }) {+ return (+ <Link href={`/programs/${programSlug}`} target="_blank">+ <Button+ variant="secondary"+ text="View program"+ className="h-8 rounded-lg px-3"+ />+ </Link>+ );}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/page-client.tsxdeleted file mode 100644index 08759c1334..0000000000--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/page-client.tsx+++ /dev/null@@ -1,31 +0,0 @@-"use client";--import { useMessagesContext } from "@/ui/messages/messages-context";-import { ChevronLeft, Msgs } from "@dub/ui/icons";--export function PartnerMessagesPageClient() {- const { setCurrentPanel } = useMessagesContext();-- return (- <div className="flex h-full flex-col">- <div className="border-border-subtle flex h-12 items-center gap-2 border-b px-4 sm:h-16 sm:px-6">- <button- type="button"- onClick={() => {- setCurrentPanel("index");- }}- className="@[800px]/page:hidden rounded-lg p-1.5 text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-neutral-900"- >- <ChevronLeft className="size-3.5" />- </button>- </div>-- <div className="flex grow flex-col items-center justify-center gap-4">- <Msgs className="text-content-muted size-10" />- <p className="text-content-muted text-sm font-medium">- Select or compose a message- </p>- </div>- </div>- );-}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/page.tsxindex bb8675d2f8..9c68889f92 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/page.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/page.tsx@@ -1,5 +1,31 @@-import { PartnerMessagesPageClient } from "./page-client";+"use client";-export default function PartnerMessages() {- return <PartnerMessagesPageClient />;+import { useMessagesContext } from "@/ui/messages/messages-context";+import { ChevronLeft, Msgs } from "@dub/ui/icons";++export default function PartnerMessagesPage() {+ const { setCurrentPanel } = useMessagesContext();++ return (+ <div className="flex h-full flex-col">+ <div className="border-border-subtle flex h-12 items-center gap-2 border-b px-4 sm:h-16 sm:px-6">+ <button+ type="button"+ onClick={() => {+ setCurrentPanel("index");+ }}+ className="@[800px]/page:hidden rounded-lg p-1.5 text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-neutral-900"+ >+ <ChevronLeft className="size-3.5" />+ </button>+ </div>++ <div className="flex grow flex-col items-center justify-center gap-4">+ <Msgs className="text-content-muted size-10" />+ <p className="text-content-muted text-sm font-medium">+ Select or compose a message+ </p>+ </div>+ </div>+ );}diff --git a/apps/web/lib/messages/message-program.ts b/apps/web/lib/messages/message-program.tsindex d040dc9422..76df794353 100644--- a/apps/web/lib/messages/message-program.ts+++ b/apps/web/lib/messages/message-program.ts@@ -7,6 +7,7 @@ import { prisma } from "@/lib/prisma";import { APP_DOMAIN_WITH_NGROK, INTERCOM_INTEGRATION_ID } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { authPartnerActionClient } from "../actions/safe-action";+import { INACTIVE_ENROLLMENT_STATUSES } from "../zod/schemas/partners";import { MessageSchema, messageProgramSchema } from "./schemas";import {mapMessageAttachmentsForCreate,@@ -25,7 +26,7 @@ export const messageProgramAction = authPartnerActionClientconst { partner, user } = ctx;const { programSlug, text, attachments } = parsedInput;- const program = await prisma.program.findFirstOrThrow({+ const program = await prisma.program.findFirst({select: {id: true,workspaceId: true,@@ -33,28 +34,24 @@ export const messageProgramAction = authPartnerActionClientwhere: {slug: programSlug,- // Partner is not banned from the program+ // partner is not banned, deactivated, or rejectedpartners: {- none: {+ some: {partnerId: partner.id,- status: "banned",+ status: {+ notIn: INACTIVE_ENROLLMENT_STATUSES,+ },},},OR: [- // Program has messaging enabled and partner is enrolled+ // program has messaging enabled{messagingEnabledAt: {not: null,},- partners: {- some: {- partnerId: partner.id,- },- },},-- // Partner has received a direct message from the program before+ // partner has received a direct message from the program before (invited status){messages: {some: {@@ -67,6 +64,10 @@ export const messageProgramAction = authPartnerActionClient},});+ if (!program) {+ throw new Error("You are not able to message this program.");+ }+const keyPrefix = `messages/${program.id}/`;for (const attachment of attachments) {