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.

Add file and image attachments to partner/program messages (#4005)

Kiran K053de00df2d3
diff --git a/apps/web/app/(ee)/api/admin/payouts/get-payouts-timeseries.ts b/apps/web/app/(ee)/api/admin/payouts/get-payouts-timeseries.ts
index 5256f4931e..fa559dc71d 100644
--- a/apps/web/app/(ee)/api/admin/payouts/get-payouts-timeseries.ts
+++ b/apps/web/app/(ee)/api/admin/payouts/get-payouts-timeseries.ts
@@ -1,5 +1,5 @@
-import { sqlGranularityMap } from "@/lib/planetscale/granularity";
import { conn } from "@/lib/planetscale/connection";
+import { sqlGranularityMap } from "@/lib/planetscale/granularity";
import { InvoiceStatus } from "@dub/prisma/client";
import { ACME_PROGRAM_ID } from "@dub/utils";
import { format } from "date-fns";
diff --git a/apps/web/app/(ee)/api/cron/export/payouts/fetch-payouts-batch.ts b/apps/web/app/(ee)/api/cron/export/payouts/fetch-payouts-batch.ts
index bdf4eff6aa..2cabd75895 100644
--- a/apps/web/app/(ee)/api/cron/export/payouts/fetch-payouts-batch.ts
+++ b/apps/web/app/(ee)/api/cron/export/payouts/fetch-payouts-batch.ts
@@ -1,4 +1,7 @@
-import { getPayouts, ParsedPayoutsFilters } from "@/lib/api/payouts/get-payouts";
+import {
+ getPayouts,
+ ParsedPayoutsFilters,
+} from "@/lib/api/payouts/get-payouts";
export async function* fetchPayoutsBatch(
{
diff --git a/apps/web/app/(ee)/api/cron/export/payouts/route.ts b/apps/web/app/(ee)/api/cron/export/payouts/route.ts
index 4493ace234..16704a756f 100644
--- a/apps/web/app/(ee)/api/cron/export/payouts/route.ts
+++ b/apps/web/app/(ee)/api/cron/export/payouts/route.ts
@@ -1,7 +1,7 @@
import { convertToCSV } from "@/lib/analytics/utils/convert-to-csv";
+import { createDownloadableExport } from "@/lib/api/create-downloadable-export";
import { formatPayoutsForExport } from "@/lib/api/payouts/format-payouts-for-export";
import { parsePayoutsQuery } from "@/lib/api/payouts/get-payouts";
-import { createDownloadableExport } from "@/lib/api/create-downloadable-export";
import { generateExportFilename } from "@/lib/api/utils/generate-export-filename";
import { generateRandomString } from "@/lib/api/utils/generate-random-string";
import { withCron } from "@/lib/cron/with-cron";
diff --git a/apps/web/app/(ee)/api/messages/route.ts b/apps/web/app/(ee)/api/messages/route.ts
index e7729a0d2e..cffed06101 100644
--- a/apps/web/app/(ee)/api/messages/route.ts
+++ b/apps/web/app/(ee)/api/messages/route.ts
@@ -1,6 +1,7 @@
import { partnerReachableByProgramWhereInput } from "@/lib/api/partners/partner-reachable-by-program-where-input";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { withWorkspace } from "@/lib/auth";
+import { enrichMessage } from "@/lib/messages/enrich";
import {
PartnerMessagesSchema,
getPartnerMessagesQuerySchema,
@@ -46,6 +47,7 @@ export const GET = withWorkspace(
include: {
senderPartner: true,
senderUser: true,
+ attachments: true,
},
orderBy: {
[sortBy]: sortOrder,
@@ -55,35 +57,35 @@ export const GET = withWorkspace(
},
});
- return NextResponse.json(
- PartnerMessagesSchema.parse(
- partners
- // Sort by unread first, then by most recent message
- .sort((a, b) => {
- const aUnread = a.messages.some(
- (m) => m.senderPartnerId && !m.readInApp,
- );
- const bUnread = b.messages.some(
- (m) => m.senderPartnerId && !m.readInApp,
- );
+ const sortedMessages = partners
+ // Sort by unread first, then by most recent message
+ .sort((a, b) => {
+ const aUnread = a.messages.some(
+ (m) => m.senderPartnerId && !m.readInApp,
+ );
+ const bUnread = b.messages.some(
+ (m) => m.senderPartnerId && !m.readInApp,
+ );
- if (aUnread !== bUnread) {
- return aUnread ? -1 : 1;
- }
+ if (aUnread !== bUnread) {
+ return aUnread ? -1 : 1;
+ }
- return sortOrder === "desc"
- ? (b.messages?.[0]?.[sortBy]?.getTime() ?? 0) -
- (a.messages?.[0]?.[sortBy]?.getTime() ?? 0)
- : (a.messages?.[0]?.[sortBy]?.getTime() ?? 0) -
- (b.messages?.[0]?.[sortBy]?.getTime() ?? 0);
- })
- // Map to {partner, messages}
- .map(({ messages, ...partner }) => ({
- partner,
- messages,
- })),
- ),
+ return sortOrder === "desc"
+ ? (b.messages?.[0]?.[sortBy]?.getTime() ?? 0) -
+ (a.messages?.[0]?.[sortBy]?.getTime() ?? 0)
+ : (a.messages?.[0]?.[sortBy]?.getTime() ?? 0) -
+ (b.messages?.[0]?.[sortBy]?.getTime() ?? 0);
+ });
+
+ const enriched = await Promise.all(
+ sortedMessages.map(async ({ messages, ...partner }) => ({
+ partner,
+ messages: await Promise.all(messages.map(enrichMessage)),
+ })),
);
+
+ return NextResponse.json(PartnerMessagesSchema.parse(enriched));
},
{
requiredPermissions: ["messages.read"],
diff --git a/apps/web/app/(ee)/api/partner-profile/messages/route.ts b/apps/web/app/(ee)/api/partner-profile/messages/route.ts
index 57265f90f7..a0ef36ae8b 100644
--- a/apps/web/app/(ee)/api/partner-profile/messages/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/messages/route.ts
@@ -1,4 +1,5 @@
import { withPartnerProfile } from "@/lib/auth/partner";
+import { enrichMessage } from "@/lib/messages/enrich";
import {
ProgramMessagesSchema,
getProgramMessagesQuerySchema,
@@ -77,6 +78,7 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
include: {
senderPartner: true,
senderUser: true,
+ attachments: true,
},
orderBy: {
[sortBy]: sortOrder,
@@ -86,33 +88,33 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
},
});
- return NextResponse.json(
- ProgramMessagesSchema.parse(
- programs
- // Sort by unread first, then by most recent message
- .sort((a, b) => {
- const aUnread = a.messages.some(
- (m) => !m.senderPartnerId && !m.readInApp,
- );
- const bUnread = b.messages.some(
- (m) => !m.senderPartnerId && !m.readInApp,
- );
+ const sortedMessages = programs
+ // Sort by unread first, then by most recent message
+ .sort((a, b) => {
+ const aUnread = a.messages.some(
+ (m) => !m.senderPartnerId && !m.readInApp,
+ );
+ const bUnread = b.messages.some(
+ (m) => !m.senderPartnerId && !m.readInApp,
+ );
- if (aUnread !== bUnread) {
- return aUnread ? -1 : 1;
- }
+ if (aUnread !== bUnread) {
+ return aUnread ? -1 : 1;
+ }
+
+ return sortOrder === "desc"
+ ? (b.messages?.[0]?.[sortBy]?.getTime() ?? 0) -
+ (a.messages?.[0]?.[sortBy]?.getTime() ?? 0)
+ : (a.messages?.[0]?.[sortBy]?.getTime() ?? 0) -
+ (b.messages?.[0]?.[sortBy]?.getTime() ?? 0);
+ });
- return sortOrder === "desc"
- ? (b.messages?.[0]?.[sortBy]?.getTime() ?? 0) -
- (a.messages?.[0]?.[sortBy]?.getTime() ?? 0)
- : (a.messages?.[0]?.[sortBy]?.getTime() ?? 0) -
- (b.messages?.[0]?.[sortBy]?.getTime() ?? 0);
- })
- // Map to {program, messages}
- .map(({ messages, ...program }) => ({
- program,
- messages,
- })),
- ),
+ const enriched = await Promise.all(
+ sortedMessages.map(async ({ messages, ...program }) => ({
+ program,
+ messages: await Promise.all(messages.map(enrichMessage)),
+ })),
);
+
+ return NextResponse.json(ProgramMessagesSchema.parse(enriched));
});
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.tsx
index ad9a9d7ae8..8911803126 100644
--- 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.tsx
@@ -3,6 +3,7 @@
import { parseActionError } from "@/lib/actions/parse-action-errors";
import { markProgramMessagesReadAction } from "@/lib/actions/partners/mark-program-messages-read";
import { messageProgramAction } from "@/lib/actions/partners/message-program";
+import { uploadPartnerMessageAttachmentAction } from "@/lib/actions/partners/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";
@@ -11,6 +12,7 @@ import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
import { useProgramMessages } from "@/lib/swr/use-program-messages";
import useUser from "@/lib/swr/use-user";
import { ProgramEnrollmentProps } from "@/lib/types";
+import { PARTNER_ALLOWED_ATTACHMENT_TYPES } from "@/lib/zod/schemas/messages";
import { INACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";
import { useMessagesContext } from "@/ui/messages/messages-context";
import { MessagesPanel } from "@/ui/messages/messages-panel";
@@ -18,6 +20,7 @@ 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,
@@ -38,7 +41,7 @@ import {
import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
import { redirect, useParams } from "next/navigation";
-import { useState } from "react";
+import { useCallback, useState } from "react";
import { toast } from "sonner";
import { v4 as uuid } from "uuid";
@@ -137,6 +140,84 @@ export function PartnerMessagesProgramPageClient() {
},
});
+ 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);
@@ -210,6 +291,10 @@ export function PartnerMessagesProgramPageClient() {
currentUserType="partner"
currentUserId={partner?.id || ""}
program={program}
+ pendingAttachments={pendingAttachments}
+ onAddFiles={handleAddFiles}
+ onRemoveAttachment={handleRemoveAttachment}
+ allowedFileTypes={PARTNER_ALLOWED_ATTACHMENT_TYPES}
{...(shouldShowExternalSupportEmptyState && messages?.length
? {
footerSlot: (
@@ -219,7 +304,7 @@ export function PartnerMessagesProgramPageClient() {
),
}
: {})}
- onSendMessage={async (message) => {
+ onSendMessage={async (message, attachments) => {
const createdAt = new Date();
try {
@@ -228,6 +313,7 @@ export function PartnerMessagesProgramPageClient() {
const result = await sendMessage({
programSlug,
text: message,
+ attachments,
});
if (result?.data?.message) {
@@ -276,6 +362,12 @@ export function PartnerMessagesProgramPageClient() {
name: partner!.name,
image: partner!.image || null,
},
+ attachments: attachments.map((a, i) => ({
+ id: `tmp_att_${i}`,
+ messageId: "",
+ ...a,
+ createdAt,
+ })),
},
],
},
@@ -285,6 +377,7 @@ export function PartnerMessagesProgramPageClient() {
},
);
+ setPendingAttachments([]);
mutatePrefix("/api/partner-profile/messages");
} catch (e) {
console.log(`Failed to send message: ${e}`);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/messages/[partnerId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/messages/[partnerId]/page-client.tsx
index ce3ebc19d8..07fc705d20 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/messages/[partnerId]/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/messages/[partnerId]/page-client.tsx
@@ -3,12 +3,14 @@
import { parseActionError } from "@/lib/actions/parse-action-errors";
import { markPartnerMessagesReadAction } from "@/lib/actions/partners/mark-partner-messages-read";
import { messagePartnerAction } from "@/lib/actions/partners/message-partner";
+import { uploadMessageAttachmentAction } from "@/lib/actions/partners/upload-message-attachment";
import { mutatePrefix } from "@/lib/swr/mutate";
import usePartner from "@/lib/swr/use-partner";
import { usePartnerMessages } from "@/lib/swr/use-partner-messages";
import useProgram from "@/lib/swr/use-program";
import useUser from "@/lib/swr/use-user";
import useWorkspace from "@/lib/swr/use-workspace";
+import { PROGRAM_ALLOWED_ATTACHMENT_TYPES } from "@/lib/zod/schemas/messages";
import { useMessagesContext } from "@/ui/messages/messages-context";
import { MessagesPanel } from "@/ui/messages/messages-panel";
import { ToggleSidePanelButton } from "@/ui/messages/toggle-side-panel-button";
@@ -17,13 +19,14 @@ import { PartnerInfoGroup } from "@/ui/partners/partner-info-group";
import { PartnerInfoSection } from "@/ui/partners/partner-info-section";
import { PartnerInfoStats } from "@/ui/partners/partner-info-stats";
import { X } from "@/ui/shared/icons";
+import { PendingAttachment } from "@/ui/shared/message-input";
import { Button } from "@dub/ui";
import { ChevronLeft } from "@dub/ui/icons";
import { cn } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
import { redirect, useParams, useSearchParams } from "next/navigation";
-import { useState } from "react";
+import { useCallback, useState } from "react";
import { toast } from "sonner";
import { v4 as uuid } from "uuid";
@@ -82,6 +85,84 @@ export function ProgramMessagesPartnerPageClient() {
},
});
+ const { executeAsync: uploadAttachment } = useAction(
+ uploadMessageAttachmentAction,
+ {
+ 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({
+ workspaceId: workspaceId!,
+ fileName: file.name,
+ contentType:
+ file.type as (typeof PROGRAM_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 (err) {
+ setPendingAttachments((prev) => prev.filter((a) => a.id !== id));
+ toast.error(
+ `Failed to upload file: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ }
+ },
+ [workspaceId, uploadAttachment],
+ );
+
+ const handleRemoveAttachment = useCallback((id: string) => {
+ setPendingAttachments((prev) => prev.filter((a) => a.id !== id));
+ }, []);
+
const { setCurrentPanel } = useMessagesContext();
const [isRightPanelOpen, setIsRightPanelOpen] = useState(true);
@@ -144,8 +225,12 @@ export function ProgramMessagesPartnerPageClient() {
currentUserId={user?.id || ""}
program={program}
partner={partner}
+ pendingAttachments={pendingAttachments}
+ onAddFiles={handleAddFiles}
+ onRemoveAttachment={handleRemoveAttachment}
+ allowedFileTypes={PROGRAM_ALLOWED_ATTACHMENT_TYPES}
defaultValue={defaultMessage}
- onSendMessage={async (message) => {
+ onSendMessage={async (message, attachments) => {
const createdAt = new Date();
try {
@@ -155,6 +240,7 @@ export function ProgramMessagesPartnerPageClient() {
workspaceId: workspaceId!,
partnerId,
text: message,
+ attachments,
});
if (result?.data?.message) {
@@ -199,6 +285,12 @@ export function ProgramMessagesPartnerPageClient() {
name: user!.name,
image: user!.image || null,
},
+ attachments: attachments.map((a, i) => ({
+ id: `tmp_att_${i}`,
+ messageId: "",
+ ...a,
+ createdAt,
+ })),
},
],
},
@@ -208,6 +300,7 @@ export function ProgramMessagesPartnerPageClient() {
},
);
+ setPendingAttachments([]);
mutatePrefix("/api/messages");
} catch (e) {
console.log(`Failed to send message: ${e}`);
diff --git a/apps/web/lib/actions/partners/message-partner.ts b/apps/web/lib/actions/partners/message-partner.ts
index 8ccce4b858..d43800506c 100644
--- a/apps/web/lib/actions/partners/message-partner.ts
+++ b/apps/web/lib/actions/partners/message-partner.ts
@@ -18,16 +18,23 @@ import {
import { authActionClient } from "../safe-action";
import { throwIfNoPermission } from "../throw-if-no-permission";
-const schema = messagePartnerSchema.extend({
- workspaceId: z.string(),
-});
+const schema = messagePartnerSchema
+ .extend({
+ workspaceId: z.string(),
+ })
+ .refine(
+ (data) => data.text.trim().length > 0 || data.attachments.length > 0,
+ {
+ message: "Message must contain text or at least one attachment.",
+ },
+ );
// Message a partner
export const messagePartnerAction = authActionClient
.inputSchema(schema)
.action(async ({ parsedInput, ctx }) => {
const { workspace, user } = ctx;
- const { partnerId, text } = parsedInput;
+ const { partnerId, text, attachments } = parsedInput;
throwIfNoPermission({
role: workspace.role,
@@ -114,6 +121,14 @@ export const messagePartnerAction = authActionClient
});
}
+ const keyPrefix = `messages/${programId}/`;
+
+ for (const attachment of attachments) {
+ if (!attachment.storageKey.startsWith(keyPrefix)) {
+ throw new Error("Invalid attachment storage key.");
+ }
+ }
+
const message = await prisma.message.create({
data: {
id: createId({ prefix: "msg_" }),
@@ -121,10 +136,22 @@ export const messagePartnerAction = authActionClient
partnerId,
senderUserId: user.id,
text,
+ ...(attachments.length > 0 && {
+ attachments: {
+ create: attachments.map((att) => ({
+ id: createId({ prefix: "msa_" }),
+ storageKey: att.storageKey,
+ name: att.name,
+ size: att.size,
+ type: att.type,
+ })),
+ },
+ }),
},
include: {
senderUser: true,
senderPartner: true,
+ attachments: true,
},
});
diff --git a/apps/web/lib/actions/partners/message-program.ts b/apps/web/lib/actions/partners/message-program.ts
index 05fbd08b4e..ad8c33ce53 100644
--- a/apps/web/lib/actions/partners/message-program.ts
+++ b/apps/web/lib/actions/partners/message-program.ts
@@ -11,12 +11,17 @@ import {
} from "../../zod/schemas/messages";
import { authPartnerActionClient } from "../safe-action";
+const schema = messageProgramSchema.refine(
+ (data) => data.text.trim().length > 0 || data.attachments.length > 0,
+ { message: "Message must contain text or at least one attachment." },
+);
+
// Message a program
export const messageProgramAction = authPartnerActionClient
- .inputSchema(messageProgramSchema)
+ .inputSchema(schema)
.action(async ({ parsedInput, ctx }) => {
const { partner, user } = ctx;
- const { programSlug, text } = parsedInput;
+ const { programSlug, text, attachments } = parsedInput;
const program = await prisma.program.findFirstOrThrow({
select: {
@@ -59,6 +64,14 @@ export const messageProgramAction = authPartnerActionClient
},
});
+ const keyPrefix = `messages/${program.id}/`;
+
+ for (const attachment of attachments) {
+ if (!attachment.storageKey.startsWith(keyPrefix)) {
+ throw new Error("Invalid attachment storage key.");
+ }
+ }
+
const message = await prisma.message.create({
data: {
id: createId({ prefix: "msg_" }),
@@ -67,10 +80,22 @@ export const messageProgramAction = authPartnerActionClient
senderPartnerId: partner.id,
senderUserId: user.id,
text,
+ ...(attachments.length > 0 && {
+ attachments: {
+ create: attachments.map((att) => ({
+ id: createId({ prefix: "msa_" }),
+ storageKey: att.storageKey,
+ name: att.name,
+ size: att.size,
+ type: att.type,
+ })),
+ },
+ }),
},
include: {
senderUser: true,
senderPartner: true,
+ attachments: true,
},
});
diff --git a/apps/web/lib/actions/partners/upload-message-attachment.ts b/apps/web/lib/actions/partners/upload-message-attachment.ts
new file mode 100644
index 0000000000..93749f9d83
--- /dev/null
+++ b/apps/web/lib/actions/partners/upload-message-attachment.ts
@@ -0,0 +1,62 @@
+"use server";
+
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { sanitizeFileName } from "@/lib/messages/utils";
+import { storage } from "@/lib/storage";
+import { ratelimit } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
+import {
+ MAX_ATTACHMENT_NAME_LENGTH,
+ MAX_ATTACHMENT_SIZE_BYTES,
+ PROGRAM_ALLOWED_ATTACHMENT_TYPES,
+} from "@/lib/zod/schemas/messages";
+import { nanoid } from "@dub/utils";
+import * as z from "zod/v4";
+import { authActionClient } from "../safe-action";
+import { throwIfNoPermission } from "../throw-if-no-permission";
+
+const schema = z.object({
+ workspaceId: z.string(),
+ fileName: z.string().trim().min(1).max(MAX_ATTACHMENT_NAME_LENGTH),
+ contentType: z.enum(PROGRAM_ALLOWED_ATTACHMENT_TYPES),
+ contentLength: z.number().int().positive().max(MAX_ATTACHMENT_SIZE_BYTES),
+});
+
+const rateLimitPolicy = RATELIMIT_POLICIES.messageAttachmentUpload;
+
+export const uploadMessageAttachmentAction = authActionClient
+ .inputSchema(schema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { workspace, user } = ctx;
+ const { fileName, contentType, contentLength } = parsedInput;
+
+ throwIfNoPermission({
+ role: workspace.role,
+ requiredPermissions: ["messages.write"],
+ });
+
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ const { success } = await ratelimit(
+ rateLimitPolicy.attempts,
+ rateLimitPolicy.window,
+ ).limit(`${rateLimitPolicy.keyPrefix}:${user.id}`);
+
+ if (!success) {
+ throw new Error("Too many file uploads. Please try again later.");
+ }
+
+ const storageKey = `messages/${programId}/${nanoid(10)}/${sanitizeFileName(fileName)}`;
+
+ const signedUrl = await storage.getSignedUploadUrl({
+ key: storageKey,
+ bucket: "private",
+ contentLength,
+ contentType,
+ });
+
+ return {
+ signedUrl,
+ storageKey,
+ };
+ });
diff --git a/apps/web/lib/actions/partners/upload-partner-message-attachment.ts b/apps/web/lib/actions/partners/upload-partner-message-attachment.ts
new file mode 100644
index 0000000000..2297799455
--- /dev/null
+++ b/apps/web/lib/actions/partners/upload-partner-message-attachment.ts
@@ -0,0 +1,89 @@
+"use server";
+
+import { sanitizeFileName } from "@/lib/messages/utils";
+import { storage } from "@/lib/storage";
+import { ratelimit } from "@/lib/upstash";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
+import {
+ MAX_ATTACHMENT_NAME_LENGTH,
+ MAX_ATTACHMENT_SIZE_BYTES,
+ PARTNER_ALLOWED_ATTACHMENT_TYPES,
+} from "@/lib/zod/schemas/messages";
+import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
+import * as z from "zod/v4";
+import { authPartnerActionClient } from "../safe-action";
+
+const schema = z.object({
+ programSlug: z.string(),
+ fileName: z.string().trim().min(1).max(MAX_ATTACHMENT_NAME_LENGTH),
+ contentType: z.enum(PARTNER_ALLOWED_ATTACHMENT_TYPES),
+ contentLength: z.number().int().positive().max(MAX_ATTACHMENT_SIZE_BYTES),
+});
+
+const rateLimitPolicy = RATELIMIT_POLICIES.messageAttachmentUpload;
+
+export const uploadPartnerMessageAttachmentAction = authPartnerActionClient
+ .inputSchema(schema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { partner } = ctx;
+ const { programSlug, fileName, contentType, contentLength } = parsedInput;
+
+ const { success } = await ratelimit(
+ rateLimitPolicy.attempts,
+ rateLimitPolicy.window,
+ ).limit(`${rateLimitPolicy.keyPrefix}:${partner.id}`);
+
+ if (!success) {
+ throw new Error("Too many file uploads. Please try again later.");
+ }
+
+ const program = await prisma.program.findFirstOrThrow({
+ select: {
+ id: true,
+ },
+ where: {
+ slug: programSlug,
+ partners: {
+ none: {
+ partnerId: partner.id,
+ status: "banned",
+ },
+ },
+ OR: [
+ {
+ messagingEnabledAt: {
+ not: null,
+ },
+ partners: {
+ some: {
+ partnerId: partner.id,
+ },
+ },
+ },
+ {
+ messages: {
+ some: {
+ partnerId: partner.id,
+ senderPartnerId: null,
+ },
+ },
+ },
+ ],
+ },
+ });
+
+ const storageKey = `messages/${program.id}/${nanoid(10)}/${sanitizeFileName(fileName)}`;
+
+ const signedUrl = await storage.getSignedUploadUrl({
+ key: storageKey,
+ bucket: "private",
+ contentLength,
+ contentType,
+ });
+
+ return {
+ signedUrl,
+ storageKey,
+ };
+ });
diff --git a/apps/web/lib/api/create-id.ts b/apps/web/lib/api/create-id.ts
index e10a8cb281..3165325eaa 100644
--- a/apps/web/lib/api/create-id.ts
+++ b/apps/web/lib/api/create-id.ts
@@ -38,6 +38,7 @@ const prefixes = [
"bnty_sub_", // bounty submission
"wf_", // workflow
"msg_", // message
+ "msa_", // message attachment
"em_", // notification email,
"cmp_", // campaign
"fr_", // fraud rule
diff --git a/apps/web/lib/api/payouts/get-payouts.ts b/apps/web/lib/api/payouts/get-payouts.ts
index 538aefe7f3..3fcdbb6993 100644
--- a/apps/web/lib/api/payouts/get-payouts.ts
+++ b/apps/web/lib/api/payouts/get-payouts.ts
@@ -1,5 +1,5 @@
-import { getEffectivePayoutMode } from "@/lib/api/payouts/get-effective-payout-mode";
import { DubApiError } from "@/lib/api/errors";
+import { getEffectivePayoutMode } from "@/lib/api/payouts/get-effective-payout-mode";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { payoutsQuerySchema } from "@/lib/zod/schemas/payouts";
import { prisma } from "@dub/prisma";
diff --git a/apps/web/lib/messages/enrich.ts b/apps/web/lib/messages/enrich.ts
new file mode 100644
index 0000000000..11ee328b44
--- /dev/null
+++ b/apps/web/lib/messages/enrich.ts
@@ -0,0 +1,22 @@
+import { storage } from "@/lib/storage";
+import { Message, MessageAttachment } from "@dub/prisma/client";
+
+export async function enrichMessage(
+ message: Message & { attachments: MessageAttachment[] },
+) {
+ return {
+ ...message,
+ attachments: await Promise.all(message.attachments.map(enrichAttachment)),
+ };
+}
+
+async function enrichAttachment(att: MessageAttachment) {
+ return {
+ ...att,
+ signedUrl: await storage.getSignedDownloadUrl({
+ key: att.storageKey,
+ bucket: "private",
+ expiresIn: 3600,
+ }),
+ };
+}
diff --git a/apps/web/lib/messages/utils.ts b/apps/web/lib/messages/utils.ts
new file mode 100644
index 0000000000..bc209575a7
--- /dev/null
+++ b/apps/web/lib/messages/utils.ts
@@ -0,0 +1,24 @@
+import {
+ ATTACHMENT_MIME_TYPE_LABELS,
+ PREVIEWABLE_IMAGE_TYPES,
+} from "../zod/schemas/messages";
+
+// Normalize a user-supplied file name
+export function sanitizeFileName(name: string): string {
+ return name
+ .trim()
+ .replace(/\s+/g, " ")
+ .replace(/[\x00-\x1F\x7F/\\?#%]/g, (ch) => encodeURIComponent(ch));
+}
+
+export function getAttachmentTypeLabel(mimeType: string): string {
+ return (
+ ATTACHMENT_MIME_TYPE_LABELS[mimeType] ||
+ mimeType.split("/").pop()?.toUpperCase() ||
+ "FILE"
+ );
+}
+
+export function isPreviewableImageType(mimeType: string): boolean {
+ return PREVIEWABLE_IMAGE_TYPES.has(mimeType);
+}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 034008e7d1..d9f57c38e9 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -132,7 +132,7 @@ import {
ABTestVariantsSchema,
createLinkBodySchema,
} from "./zod/schemas/links";
-import { MessageSchema } from "./zod/schemas/messages";
+import { MessageAttachmentSchema, MessageSchema } from "./zod/schemas/messages";
import { createOAuthAppSchema, oAuthAppSchema } from "./zod/schemas/oauth";
import {
NetworkPartnerSchema,
@@ -755,6 +755,8 @@ export type BountySubmissionsQueryFilters = z.infer<
export type Message = z.infer<typeof MessageSchema>;
+export type MessageAttachment = z.infer<typeof MessageAttachmentSchema>;
+
export type CampaignList = z.infer<typeof CampaignListSchema>;
export type Campaign = z.infer<typeof CampaignSchema>;
diff --git a/apps/web/lib/upstash/ratelimit-policies.ts b/apps/web/lib/upstash/ratelimit-policies.ts
index f5922189dc..458c034133 100644
--- a/apps/web/lib/upstash/ratelimit-policies.ts
+++ b/apps/web/lib/upstash/ratelimit-policies.ts
@@ -5,6 +5,12 @@ export const RATELIMIT_POLICIES = {
keyPrefix: "rl:program:application:image:upload",
},
+ messageAttachmentUpload: {
+ attempts: 20,
+ window: "1 h",
+ keyPrefix: "rl:message:attachment:upload",
+ },
+
// TODO:
// Centralize rate limiting policies
} as const;
diff --git a/apps/web/lib/zod/schemas/messages.ts b/apps/web/lib/zod/schemas/messages.ts
index ab838738a4..412d2346d7 100644
--- a/apps/web/lib/zod/schemas/messages.ts
+++ b/apps/web/lib/zod/schemas/messages.ts
@@ -6,7 +6,65 @@ import { UserSchema } from "./users";
export const MAX_MESSAGE_LENGTH = 2000;
-const messageTextSchema = z.string().min(1);
+export const MAX_ATTACHMENTS_PER_MESSAGE = 5;
+
+export const MAX_ATTACHMENT_SIZE_BYTES = 10 * 1024 * 1024; // 10MB
+
+export const MAX_ATTACHMENT_NAME_LENGTH = 255;
+
+export const PROGRAM_ALLOWED_ATTACHMENT_TYPES = [
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+ "application/pdf",
+] as const;
+
+export const PARTNER_ALLOWED_ATTACHMENT_TYPES = [
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+] as const;
+
+export const ATTACHMENT_MIME_TYPE_LABELS: Record<string, string> = {
+ "application/pdf": "PDF",
+ "image/png": "PNG",
+ "image/jpeg": "JPG",
+ "image/webp": "WEBP",
+};
+
+// MIME types that are safe to render as inline image previews.
+export const PREVIEWABLE_IMAGE_TYPES = new Set([
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+]);
+
+export const ATTACHMENT_MIME_TYPE_COLOR: Record<string, string> = {
+ "application/pdf": "bg-red-600",
+ "image/png": "bg-blue-600",
+ "image/jpeg": "bg-blue-500",
+ "image/webp": "bg-blue-500",
+};
+
+const messageTextSchema = z.string().max(MAX_MESSAGE_LENGTH);
+
+export const MessageAttachmentSchema = z.object({
+ id: z.string(),
+ messageId: z.string(),
+ storageKey: z.string(),
+ signedUrl: z.string().optional(),
+ name: z.string(),
+ size: z.number(),
+ type: z.string(),
+ createdAt: z.date(),
+});
+
+export const messageAttachmentInputSchema = z.object({
+ storageKey: z.string().min(1),
+ name: z.string().min(1).max(255),
+ size: z.number().int().positive().max(MAX_ATTACHMENT_SIZE_BYTES),
+ type: z.string().min(1),
+});
export const MessageSchema = z.object({
id: z.string(),
@@ -14,7 +72,7 @@ export const MessageSchema = z.object({
partnerId: z.string(),
senderPartnerId: z.string().nullable(),
senderUserId: z.string(),
- text: messageTextSchema,
+ text: z.string(),
subject: z.string().nullable(),
type: z.enum(MessageType),
readInApp: z.date().nullable(),
@@ -31,6 +89,7 @@ export const MessageSchema = z.object({
name: true,
image: true,
}).nullable(),
+ attachments: z.array(MessageAttachmentSchema).default([]),
});
export const PartnerMessagesSchema = z.array(
@@ -57,7 +116,11 @@ export const countMessagesQuerySchema = z.object({
export const messagePartnerSchema = z.object({
partnerId: z.string(),
- text: messageTextSchema.max(MAX_MESSAGE_LENGTH),
+ text: messageTextSchema,
+ attachments: z
+ .array(messageAttachmentInputSchema)
+ .max(MAX_ATTACHMENTS_PER_MESSAGE)
+ .default([]),
});
export const ProgramMessagesSchema = z.array(
@@ -82,5 +145,9 @@ export const getProgramMessagesQuerySchema = z.object({
export const messageProgramSchema = z.object({
programSlug: z.string(),
- text: messageTextSchema.max(MAX_MESSAGE_LENGTH),
+ text: messageTextSchema,
+ attachments: z
+ .array(messageAttachmentInputSchema)
+ .max(MAX_ATTACHMENTS_PER_MESSAGE)
+ .default([]),
});
diff --git a/apps/web/ui/messages/message-attachments.tsx b/apps/web/ui/messages/message-attachments.tsx
new file mode 100644
index 0000000000..befc41762a
--- /dev/null
+++ b/apps/web/ui/messages/message-attachments.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { getAttachmentTypeLabel } from "@/lib/messages/utils";
+import { MessageAttachment } from "@/lib/types";
+import { ATTACHMENT_MIME_TYPE_COLOR } from "@/lib/zod/schemas/messages";
+import { formatFileSize } from "@dub/utils";
+import { cn } from "@dub/utils/src";
+import { Download, File } from "lucide-react";
+import { toast } from "sonner";
+import { ZoomImage } from "../shared/zoom-image";
+
+async function downloadFile(url: string, filename: string) {
+ try {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Download failed (${response.status})`);
+ }
+
+ const blob = await response.blob();
+ const blobUrl = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = blobUrl;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(blobUrl);
+ } catch {
+ toast.error("Failed to download file. Please try again.");
+ }
+}
+
+export function MessageImageAttachments({
+ attachments,
+}: {
+ attachments: MessageAttachment[];
+}) {
+ return (
+ <div className="flex max-w-[min(100%,512px)] flex-col gap-1">
+ {attachments.map((img) => (
+ <div key={img.id} className="group relative">
+ {img.signedUrl ? (
+ <>
+ <ZoomImage
+ src={img.signedUrl}
+ alt={img.name}
+ className="max-h-64 w-full cursor-pointer rounded-lg border border-neutral-200 object-cover"
+ />
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ downloadFile(img.signedUrl!, img.name);
+ }}
+ className="absolute right-2 top-2 flex size-7 items-center justify-center rounded-md bg-white/70 text-neutral-600 opacity-0 backdrop-blur-sm transition-opacity hover:bg-white/90 group-hover:opacity-100"
+ >
+ <Download className="size-3.5" />
+ </button>
+ </>
+ ) : (
+ <div className="h-40 w-full animate-pulse rounded-lg bg-neutral-200" />
+ )}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+export function MessageFileAttachments({
+ attachments,
+}: {
+ attachments: MessageAttachment[];
+}) {
+ return (
+ <div className="flex max-w-[min(100%,512px)] flex-col gap-2">
+ {attachments.map((file) => (
+ <button
+ key={file.id}
+ type="button"
+ disabled={!file.signedUrl}
+ onClick={() =>
+ file.signedUrl && downloadFile(file.signedUrl, file.name)
+ }
+ className={cn(
+ "flex items-center gap-2 rounded-lg border border-neutral-200 bg-neutral-50 px-3 py-2 text-left transition-colors",
+ file.signedUrl
+ ? "hover:bg-neutral-100"
+ : "cursor-default opacity-60",
+ )}
+ >
+ <FileTypeBadge type={file.type} />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="text-content-default truncate text-sm font-medium">
+ {file.name}
+ </span>
+ <span className="text-content-subtle text-xs font-medium">
+ {formatFileSize(file.size, 1)}
+ </span>
+ </div>
+ <div className="border-bg-subtle rounded-lg border bg-white px-3 py-2">
+ <Download className="text-content-emphasis size-4 shrink-0" />
+ </div>
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function FileTypeBadge({ type }: { type: string }) {
+ return (
+ <div
+ className={cn(
+ "flex size-10 shrink-0 flex-col items-center justify-center gap-1 rounded-lg p-2 text-xs font-semibold uppercase text-white",
+ ATTACHMENT_MIME_TYPE_COLOR[type] || "bg-neutral-500",
+ )}
+ >
+ <File className="size-3 shrink-0" />
+ <span>{getAttachmentTypeLabel(type)}</span>
+ </div>
+ );
+}
diff --git a/apps/web/ui/messages/messages-panel.tsx b/apps/web/ui/messages/messages-panel.tsx
index 3f41e78598..95e5b7612a 100644
--- a/apps/web/ui/messages/messages-panel.tsx
+++ b/apps/web/ui/messages/messages-panel.tsx
@@ -1,4 +1,10 @@
-import { Message, PartnerProps, ProgramProps } from "@/lib/types";
+import { isPreviewableImageType } from "@/lib/messages/utils";
+import {
+ Message,
+ MessageAttachment,
+ PartnerProps,
+ ProgramProps,
+} from "@/lib/types";
import {
AnimatedSizeContainer,
Check2,
@@ -10,7 +16,11 @@ import {
import { OG_AVATAR_URL, cn, formatDateTime } from "@dub/utils";
import { ChevronRight } from "lucide-react";
import { Fragment, ReactNode, useMemo, useRef, useState } from "react";
-import { MessageInput } from "../shared/message-input";
+import { MessageInput, PendingAttachment } from "../shared/message-input";
+import {
+ MessageFileAttachments,
+ MessageImageAttachments,
+} from "./message-attachments";
import { MessageMarkdown } from "./message-markdown";
interface Sender {
@@ -31,18 +41,32 @@ export function MessagesPanel({
defaultValue,
error,
footerSlot,
+ pendingAttachments,
+ onAddFiles,
+ onRemoveAttachment,
+ allowedFileTypes,
}: {
messages?: (Message & { delivered?: boolean })[];
currentUserType: "partner" | "user";
currentUserId: string;
program?: Pick<ProgramProps, "logo" | "name">;
partner?: Pick<PartnerProps, "name">;
- onSendMessage: (message: string) => void;
+ onSendMessage: (
+ message: string,
+ attachments: Pick<
+ MessageAttachment,
+ "storageKey" | "name" | "size" | "type"
+ >[],
+ ) => void;
placeholder?: string;
defaultValue?: string;
error?: any;
/** When set, replaces the message composer (e.g. read-only enrollment states). */
footerSlot?: ReactNode;
+ pendingAttachments?: PendingAttachment[];
+ onAddFiles?: (files: File[]) => void;
+ onRemoveAttachment?: (id: string) => void;
+ allowedFileTypes?: readonly string[];
}) {
const { isMobile } = useMediaQuery();
const scrollRef = useRef<HTMLDivElement>(null);
@@ -59,10 +83,16 @@ export function MessagesPanel({
[placeholder, currentUserType, program?.name, partner?.name],
);
- const sendMessage = (message: string) => {
+ const sendMessage = (
+ message: string,
+ attachments: Pick<
+ MessageAttachment,
+ "storageKey" | "name" | "size" | "type"
+ >[],
+ ) => {
if (!messages) return false;
- onSendMessage(message);
+ onSendMessage(message, attachments);
scrollRef.current?.scrollTo({ top: 0 });
};
@@ -214,19 +244,47 @@ export function MessagesPanel({
showStatusIndicator={showStatusIndicator}
program={program}
/>
- {/* Message box */}
- <div
- className={cn(
- "max-w-[min(100%,512px)] rounded-xl px-4 py-2.5 text-sm",
- isMySide
- ? "rounded-br bg-neutral-700"
- : "rounded-bl bg-neutral-100",
- )}
- >
- <MessageMarkdown invert={isMySide}>
- {message.text}
- </MessageMarkdown>
- </div>
+ {/* Message bubble — text only */}
+ {message.text && (
+ <div
+ className={cn(
+ "max-w-[min(100%,512px)] rounded-xl px-4 py-2.5 text-sm",
+ isMySide
+ ? "rounded-br bg-neutral-700"
+ : "rounded-bl bg-neutral-100",
+ )}
+ >
+ <MessageMarkdown invert={isMySide}>
+ {message.text}
+ </MessageMarkdown>
+ </div>
+ )}
+ {/* Attachments — rendered outside the bubble */}
+ {(() => {
+ const imageAttachments =
+ message.attachments?.filter((a) =>
+ isPreviewableImageType(a.type),
+ ) ?? [];
+ const fileAttachments =
+ message.attachments?.filter(
+ (a) => !isPreviewableImageType(a.type),
+ ) ?? [];
+
+ return (
+ <>
+ {imageAttachments.length > 0 && (
+ <MessageImageAttachments
+ attachments={imageAttachments}
+ />
+ )}
+ {fileAttachments.length > 0 && (
+ <MessageFileAttachments
+ attachments={fileAttachments}
+ />
+ )}
+ </>
+ );
+ })()}
</div>
</div>
)}
@@ -245,6 +303,10 @@ export function MessagesPanel({
placeholder={personalizedPlaceholder}
onSendMessage={sendMessage}
autoFocus={!isMobile}
+ attachments={pendingAttachments}
+ onAddFiles={onAddFiles}
+ onRemoveAttachment={onRemoveAttachment}
+ allowedFileTypes={allowedFileTypes}
defaultValue={defaultValue}
/>
</div>
@@ -322,7 +384,7 @@ function MessageAvatar({
<Tooltip content={avatarName}>
<div className="relative shrink-0">
<img
- src={avatarImage ?? `${OG_AVATAR_URL}${avatarName}`}
+ src={avatarImage || `${OG_AVATAR_URL}${avatarName}`}
alt={`${avatarName} avatar`}
className="size-8 rounded-full"
draggable={false}
diff --git a/apps/web/ui/partners/partner-link-selector.tsx b/apps/web/ui/partners/partner-link-selector.tsx
index 63cca71a6d..58a776a55b 100644
--- a/apps/web/ui/partners/partner-link-selector.tsx
+++ b/apps/web/ui/partners/partner-link-selector.tsx
@@ -86,7 +86,8 @@ export function PartnerLinkSelector({
}, [selectedLink]);
const showLoadingPlaceholder =
- (selectedLinkId && !selectedLink) || (!selectedLinkId && isValidating && !links);
+ (selectedLinkId && !selectedLink) ||
+ (!selectedLinkId && isValidating && !links);
return (
<>
diff --git a/apps/web/ui/partners/program-eligibility-card.tsx b/apps/web/ui/partners/program-eligibility-card.tsx
index 32bb9f5dae..e5f3c1ceb9 100644
--- a/apps/web/ui/partners/program-eligibility-card.tsx
+++ b/apps/web/ui/partners/program-eligibility-card.tsx
@@ -27,7 +27,10 @@ function formatConditionContent(
key={code}
className="inline-flex h-7 items-center gap-1.5 rounded-full bg-blue-100 px-2.5 text-xs font-medium text-blue-900"
>
- <CountryFlag countryCode={code} className="size-3.5 rounded-full" />
+ <CountryFlag
+ countryCode={code}
+ className="size-3.5 rounded-full"
+ />
{COUNTRIES[code] ?? code}
</span>
))}
diff --git a/apps/web/ui/shared/message-input.tsx b/apps/web/ui/shared/message-input.tsx
index 6d8977de33..2b93ebbda0 100644
--- a/apps/web/ui/shared/message-input.tsx
+++ b/apps/web/ui/shared/message-input.tsx
@@ -1,8 +1,18 @@
-import { MAX_MESSAGE_LENGTH } from "@/lib/zod/schemas/messages";
+import {
+ getAttachmentTypeLabel,
+ isPreviewableImageType,
+} from "@/lib/messages/utils";
+import {
+ ATTACHMENT_MIME_TYPE_COLOR,
+ MAX_ATTACHMENTS_PER_MESSAGE,
+ MAX_MESSAGE_LENGTH,
+ messageAttachmentInputSchema,
+} from "@/lib/zod/schemas/messages";
import {
ArrowTurnLeft,
Button,
FaceSmile,
+ LoadingCircle,
RichTextArea,
RichTextProvider,
RichTextToolbar,
@@ -10,16 +20,31 @@ import {
useRichTextContext,
useScrollProgress,
} from "@dub/ui";
-import { cn, nFormatter } from "@dub/utils";
+import { cn, formatFileSize, nFormatter } from "@dub/utils";
+import { File, Paperclip, X } from "lucide-react";
import {
+ DragEvent,
useCallback,
useEffect,
+ useMemo,
useRef,
useState,
type RefObject,
} from "react";
+import { toast } from "sonner";
+import * as z from "zod/v4";
import { EmojiPicker } from "../shared/emoji-picker";
+export type PendingAttachment = Omit<
+ z.infer<typeof messageAttachmentInputSchema>,
+ "storageKey"
+> & {
+ id: string;
+ file: File;
+ storageKey?: string;
+ uploading: boolean;
+};
+
export function MessageInput({
onSendMessage,
defaultValue,
@@ -28,18 +53,33 @@ export function MessageInput({
placeholder = "Type a message...",
sendButtonText = "Send",
className,
+ attachments = [],
+ onAddFiles,
+ onRemoveAttachment,
+ allowedFileTypes,
+ maxAttachments = MAX_ATTACHMENTS_PER_MESSAGE,
}: {
- onSendMessage: (message: string) => void | false;
+ onSendMessage: (
+ message: string,
+ attachments: z.infer<typeof messageAttachmentInputSchema>[],
+ ) => void | false;
defaultValue?: string;
onCancel?: () => void;
autoFocus?: boolean;
placeholder?: string;
sendButtonText?: string;
className?: string;
+ attachments?: PendingAttachment[];
+ onAddFiles?: (files: File[]) => void;
+ onRemoveAttachment?: (id: string) => void;
+ allowedFileTypes?: readonly string[];
+ maxAttachments?: number;
}) {
const richTextRef = useRef<{ setContent: (content: any) => void }>(null);
+ const fileInputRef = useRef<HTMLInputElement>(null);
const [typedMessage, setTypedMessage] = useState(defaultValue || "");
const [emojiPickerOpen, setEmojiPickerOpenState] = useState(false);
+ const [dragActive, setDragActive] = useState(false);
const [cursorRect, setCursorRect] = useState<{
top: number;
bottom: number;
@@ -54,25 +94,107 @@ export function MessageInput({
setEmojiPickerOpenState(open);
}, []);
- const isSendDisabled = typedMessage.trim().length >= MAX_MESSAGE_LENGTH;
+ const hasCompletedAttachments = attachments.some(
+ (a) => !a.uploading && a.storageKey,
+ );
+ const hasUploading = attachments.some((a) => a.uploading);
+ const hasText = typedMessage.trim().length > 0;
+ const isTooLong = typedMessage.trim().length >= MAX_MESSAGE_LENGTH;
+
+ const isSendDisabled =
+ (!hasText && !hasCompletedAttachments) || isTooLong || hasUploading;
const sendMessage = () => {
+ if (isSendDisabled) return;
+
const message = typedMessage.trim();
- if (!message || message.length >= MAX_MESSAGE_LENGTH) return;
+ const completedAttachments = attachments
+ .filter((a) => !a.uploading && a.storageKey)
+ .map((a) => ({
+ storageKey: a.storageKey!,
+ name: a.name,
+ size: a.size,
+ type: a.type,
+ }));
- if (onSendMessage(message) !== false) {
+ if (!message && completedAttachments.length === 0) return;
+
+ if (onSendMessage(message, completedAttachments) !== false) {
setTypedMessage("");
richTextRef.current?.setContent("");
}
};
+ const handleFiles = useCallback(
+ (files: FileList | File[]) => {
+ if (!onAddFiles) return;
+
+ const fileArray = Array.from(files);
+ const remaining = maxAttachments - attachments.length;
+
+ if (remaining <= 0) {
+ toast.error(`Maximum ${maxAttachments} attachments per message`);
+ return;
+ }
+
+ const filesToAdd = fileArray.slice(0, remaining);
+ if (fileArray.length > remaining) {
+ toast.error(`Maximum ${maxAttachments} attachments per message`);
+ }
+
+ onAddFiles(filesToAdd);
+ },
+ [onAddFiles, attachments.length, maxAttachments],
+ );
+
+ const handleDragEvent = useCallback((e: DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }, []);
+
+ const acceptString = useMemo(
+ () => (allowedFileTypes ? allowedFileTypes.join(",") : undefined),
+ [allowedFileTypes],
+ );
+
return (
<div
className={cn(
- "border-border-subtle overflow-hidden rounded-xl border focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",
+ "border-border-subtle relative overflow-hidden rounded-xl border focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",
className,
)}
+ onDragOver={(e) => {
+ handleDragEvent(e);
+ if (onAddFiles) setDragActive(true);
+ }}
+ onDragEnter={(e) => {
+ handleDragEvent(e);
+ if (onAddFiles) setDragActive(true);
+ }}
+ onDragLeave={(e) => {
+ handleDragEvent(e);
+ setDragActive(false);
+ }}
+ onDrop={(e) => {
+ handleDragEvent(e);
+ setDragActive(false);
+ if (e.dataTransfer.files?.length) {
+ handleFiles(e.dataTransfer.files);
+ }
+ }}
>
+ {/* Drag overlay */}
+ {dragActive && onAddFiles && (
+ <div className="absolute inset-0 z-10 flex items-center justify-center rounded-xl border-2 border-dashed border-neutral-400 bg-neutral-50/90">
+ <div className="text-center">
+ <p className="text-sm font-medium text-neutral-600">
+ Drop to upload
+ </p>
+ <p className="text-xs text-neutral-400">Upload files up to 10MB</p>
+ </div>
+ </div>
+ )}
+
<RichTextProvider
ref={richTextRef}
features={["bold", "italic", "links"]}
@@ -123,12 +245,28 @@ export function MessageInput({
<MessageInputEditorOverflowFades />
</div>
+ {/* Attachment preview strip */}
+ {attachments.length > 0 && (
+ <div className="scrollbar-hide flex gap-2 overflow-x-auto px-3 py-2">
+ {attachments.map((att) => (
+ <AttachmentChip
+ key={att.id}
+ attachment={att}
+ onRemove={() => onRemoveAttachment?.(att.id)}
+ />
+ ))}
+ </div>
+ )}
+
<div className="flex items-center justify-between gap-4 p-3">
<MessageInputToolbar
emojiPickerOpen={emojiPickerOpen}
setEmojiPickerOpen={setEmojiPickerOpen}
stripColonOnEmojiPickRef={stripColonOnEmojiPickRef}
cursorRect={cursorRect}
+ onAttachClick={
+ onAddFiles ? () => fileInputRef.current?.click() : undefined
+ }
/>
<div className="flex items-center justify-between gap-2">
{onCancel && (
@@ -176,9 +314,11 @@ export function MessageInput({
</span>
}
disabledTooltip={
- typedMessage.trim().length >= MAX_MESSAGE_LENGTH
+ isTooLong
? `Message must be less than ${nFormatter(MAX_MESSAGE_LENGTH)} characters`
- : undefined
+ : hasUploading
+ ? "Please wait for uploads to complete"
+ : undefined
}
onClick={sendMessage}
className="h-8 w-fit rounded-lg px-4"
@@ -186,6 +326,104 @@ export function MessageInput({
</div>
</div>
</RichTextProvider>
+
+ {/* Hidden file input */}
+ {onAddFiles && (
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ accept={acceptString}
+ className="hidden"
+ onChange={(e) => {
+ if (e.target.files?.length) {
+ handleFiles(e.target.files);
+ }
+ e.target.value = "";
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+function AttachmentChip({
+ attachment,
+ onRemove,
+}: {
+ attachment: PendingAttachment;
+ onRemove: () => void;
+}) {
+ const isImage = isPreviewableImageType(attachment.type);
+ const previewUrl = useMemo(
+ () => (isImage ? URL.createObjectURL(attachment.file) : null),
+ [attachment.file, isImage],
+ );
+
+ useEffect(() => {
+ return () => {
+ if (previewUrl) URL.revokeObjectURL(previewUrl);
+ };
+ }, [previewUrl]);
+
+ if (isImage && previewUrl) {
+ return (
+ <div className="relative shrink-0">
+ {attachment.uploading && (
+ <div className="absolute inset-0 z-[1] flex items-center justify-center rounded-lg bg-white/80">
+ <LoadingCircle className="size-4" />
+ </div>
+ )}
+ <img
+ src={previewUrl}
+ alt={attachment.name}
+ className="size-14 rounded-lg border border-neutral-200 object-cover"
+ />
+ <button
+ type="button"
+ onClick={onRemove}
+ className="absolute -right-1.5 -top-1.5 z-[2] flex size-5 items-center justify-center rounded-full border border-neutral-200 bg-white text-neutral-400 shadow-sm transition-colors hover:text-neutral-600"
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="relative flex shrink-0 items-center gap-2 rounded-lg border border-neutral-200 bg-neutral-50 px-2 py-1.5">
+ {attachment.uploading && (
+ <div className="absolute inset-0 z-[1] flex items-center justify-center rounded-lg bg-white/80">
+ <LoadingCircle className="size-4" />
+ </div>
+ )}
+
+ <div
+ className={cn(
+ "flex size-8 shrink-0 flex-col items-center justify-center gap-0.5 rounded text-[8px] font-semibold uppercase text-white",
+ ATTACHMENT_MIME_TYPE_COLOR[attachment.type] || "bg-neutral-500",
+ )}
+ >
+ <File className="size-2.5 shrink-0" />
+ <span>{getAttachmentTypeLabel(attachment.type)}</span>
+ </div>
+
+ <div className="flex max-w-[120px] flex-col">
+ <span className="truncate text-xs font-medium text-neutral-700">
+ {attachment.name}
+ </span>
+ <span className="text-[10px] text-neutral-400">
+ {formatFileSize(attachment.size, 1)}
+ </span>
+ </div>
+
+ <button
+ type="button"
+ onClick={onRemove}
+ className="ml-1 rounded-full p-0.5 text-neutral-400 transition-colors hover:bg-neutral-200 hover:text-neutral-600"
+ >
+ <X className="size-3" />
+ </button>
</div>
);
}
@@ -277,6 +515,7 @@ function MessageInputToolbar({
setEmojiPickerOpen,
stripColonOnEmojiPickRef,
cursorRect,
+ onAttachClick,
}: {
emojiPickerOpen: boolean;
setEmojiPickerOpen: (open: boolean) => void;
@@ -287,6 +526,7 @@ function MessageInputToolbar({
left: number;
right: number;
} | null;
+ onAttachClick?: () => void;
}) {
const { editor } = useRichTextContext();
@@ -323,6 +563,18 @@ function MessageInputToolbar({
<RichTextToolbarButton icon={FaceSmile} label="Emoji" />
</EmojiPicker>
}
+ toolsEnd={
+ onAttachClick ? (
+ <button
+ type="button"
+ onClick={onAttachClick}
+ className="flex size-7 items-center justify-center rounded-md text-neutral-500 transition-colors hover:bg-neutral-100 hover:text-neutral-700"
+ title="Attach file"
+ >
+ <Paperclip className="size-4" />
+ </button>
+ ) : undefined
+ }
/>
);
}
diff --git a/packages/prisma/schema/message.prisma b/packages/prisma/schema/message.prisma
index ce502143d4..9040100fde 100644
--- a/packages/prisma/schema/message.prisma
+++ b/packages/prisma/schema/message.prisma
@@ -25,9 +25,24 @@ model Message {
senderUser User @relation(fields: [senderUserId], references: [id], onDelete: Cascade)
senderPartner Partner? @relation("SenderPartner", fields: [senderPartnerId], references: [id], onDelete: Cascade)
emails NotificationEmail[]
+ attachments MessageAttachment[]
@@index([programId, partnerId])
@@index(partnerId)
@@index(senderPartnerId)
@@index(senderUserId)
}
+
+model MessageAttachment {
+ id String @id
+ messageId String
+ storageKey String @db.Text
+ name String
+ size Int
+ type String
+ createdAt DateTime @default(now())
+
+ message Message @relation(fields: [messageId], references: [id], onDelete: Cascade)
+
+ @@index(messageId)
+}