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 error links email

Tim Wilsonaa06b35b78eb
diff --git a/apps/web/app/api/cron/import/csv/route.ts b/apps/web/app/api/cron/import/csv/route.ts
index 0259ad4863..407220d983 100644
--- a/apps/web/app/api/cron/import/csv/route.ts
+++ b/apps/web/app/api/cron/import/csv/route.ts
@@ -10,11 +10,10 @@ import { linkMappingSchema } from "@/lib/zod/schemas/import-csv";
import { createLinkBodySchema } from "@/lib/zod/schemas/links";
import { randomBadgeColor } from "@/ui/links/tag-badge";
import { log } from "@dub/utils";
-import { sendEmail } from "emails";
-import LinksImported from "emails/links-imported";
import { NextResponse } from "next/server";
import Papa from "papaparse";
import { Readable } from "stream";
+import { sendCsvImportEmails } from "./utils";
export const dynamic = "force-dynamic";
@@ -27,29 +26,32 @@ export async function POST(req: Request) {
if (!id || !url) throw new Error("Missing ID or URL for the import file");
+ const map = (row: Record<string, string>) => {
+ return {
+ ...Object.fromEntries(
+ Object.entries(mapping).map(([key, value]) => [key, row[value]]),
+ ),
+ domain: row[mapping.domain]?.replace(/^https?:\/\//, "").split("/")[0],
+ key:
+ row[mapping.key]
+ ?.replace(/^https?:\/\//, "")
+ .split("/")
+ .at(-1) ?? "",
+ tags: mapping.tags
+ ? row[mapping.tags]?.split(",").map((tag) => tag.trim())
+ : undefined,
+ };
+ };
+
let cursor = parseInt(
(await redis.get(`import:csv:${workspaceId}:${id}:cursor`)) ?? "0",
);
+ let count = cursor; // Count the total number of links added
+
const workspace = (await prisma.project.findUniqueOrThrow({
where: { id: workspaceId },
- include: {
- users: {
- where: {
- role: "owner",
- },
- select: {
- user: {
- select: {
- email: true,
- },
- },
- },
- },
- },
- })) as WorkspaceProps & { users: { user: { email: string } }[] };
-
- const ownerEmail = workspace?.users[0].user.email ?? "";
+ })) as WorkspaceProps;
const response = await storage.fetch(url);
@@ -68,8 +70,6 @@ export async function POST(req: Request) {
const addedTags: string[] = [];
const addedDomains: string[] = [];
- let count = 0;
-
await new Promise((resolve, reject) => {
Papa.parse(Readable.fromWeb(response.body as any), {
header: true,
@@ -100,7 +100,7 @@ export async function POST(req: Request) {
in: domains.map((domain) => domain.slug),
},
key: {
- in: data.map((row) => row[mapping.key]),
+ in: data.map((row) => map(row).key),
},
},
select: {
@@ -111,32 +111,22 @@ export async function POST(req: Request) {
// Find which links still need to be created
const linksToCreate = data
+ .map((row) => map(row))
.filter(
- (row) =>
+ (link) =>
!alreadyCreatedLinks.some(
- (l) =>
- l.domain === row[mapping.domain] &&
- l.key === row[mapping.key],
+ (l) => l.domain === link.domain && l.key === link.key,
),
- )
- .map((row) =>
- Object.fromEntries(
- Object.entries(mapping).map(([key, value]) => [
- key,
- row[value],
- ]),
- ),
);
const selectedTags = [
...new Set(
linksToCreate
- .map(
- ({ tags }) => tags?.split(",").map((tag) => tag.trim()) ?? [],
- )
- .flat(),
+ .map(({ tags }) => tags)
+ .flat()
+ .filter(Boolean),
),
- ];
+ ] as string[];
// Find tags that need to be added to the workspace
const tagsNotInWorkspace = selectedTags.filter(
@@ -206,12 +196,6 @@ export async function POST(req: Request) {
processLink({
payload: createLinkBodySchema.parse({
...link,
- // Special splitting for domains/keys so they can map from a full URL
- domain: link.domain.replace(/^https?:\/\//, "").split("/")[0],
- key: link.key
- .replace(/^https?:\/\//, "")
- .split("/")
- .at(-1),
tagNames: tags || undefined,
}),
workspace: workspace as WorkspaceProps,
@@ -227,14 +211,21 @@ export async function POST(req: Request) {
let errorLinks = processedLinks
.filter(({ error }) => error != null)
- .map(({ link, error, code }) => ({
- link,
+ .map(({ link: { domain, key }, error }) => ({
+ domain,
+ key,
error,
- code,
}));
- // TODO: Use errorLinks
- // Creat all links
+ // Keep track of error links
+ if (errorLinks.length > 0) {
+ await redis.rpush(
+ `import:csv:${workspaceId}:${id}:failed`,
+ ...errorLinks,
+ );
+ }
+
+ // Create all links
await bulkCreateLinks({
links: validLinks,
});
@@ -249,20 +240,30 @@ export async function POST(req: Request) {
});
});
- await redis.del(`import:csv:${workspaceId}:${id}:cursor`);
-
- sendEmail({
- subject: `Your CSV links have been imported!`,
- email: ownerEmail,
- react: LinksImported({
- email: ownerEmail,
- provider: "CSV",
- count,
- links: [],
- domains: addedDomains,
- workspaceName: workspace?.name ?? "",
- workspaceSlug: workspace?.slug ?? "",
- }),
+ const errorLinks = (await redis.lrange(
+ `import:csv:${workspaceId}:${id}:failed`,
+ 0,
+ -1,
+ )) as any;
+
+ sendCsvImportEmails({
+ workspaceId,
+ count,
+ domains: addedDomains,
+ errorLinks:
+ Array.isArray(errorLinks) && errorLinks.length > 0 ? errorLinks : [],
+ });
+
+ // Clear out storage file and redis keys
+ const clearResults = await Promise.allSettled([
+ storage.delete(url),
+ redis.del(`import:csv:${workspaceId}:${id}:cursor`),
+ redis.del(`import:csv:${workspaceId}:${id}:failed`),
+ ]);
+ clearResults.forEach((result, idx) => {
+ if (result.status === "rejected") {
+ console.error(`Error clearing CSV import data (${idx})`, result.reason);
+ }
});
return NextResponse.json({
diff --git a/apps/web/app/api/cron/import/csv/utils.ts b/apps/web/app/api/cron/import/csv/utils.ts
index 8337712ea5..28def14a58 100644
--- a/apps/web/app/api/cron/import/csv/utils.ts
+++ b/apps/web/app/api/cron/import/csv/utils.ts
@@ -1 +1,92 @@
-//
+import { prisma } from "@/lib/prisma";
+import { sendEmail } from "emails";
+import { LinksImportErrors } from "emails/links-import-errors";
+import LinksImported from "emails/links-imported";
+
+export async function sendCsvImportEmails({
+ workspaceId,
+ count,
+ domains,
+ errorLinks,
+}: {
+ workspaceId: string;
+ count: number;
+ domains: string[];
+ errorLinks: {
+ domain: string;
+ key: string;
+ error: string;
+ }[];
+}) {
+ const workspace = await prisma.project.findUnique({
+ where: {
+ id: workspaceId,
+ },
+ select: {
+ name: true,
+ slug: true,
+ users: {
+ where: {
+ role: "owner",
+ },
+ select: {
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ },
+ links: {
+ select: {
+ domain: true,
+ key: true,
+ createdAt: true,
+ },
+ where: {
+ domain: {
+ in: domains,
+ },
+ },
+ take: 5,
+ orderBy: {
+ createdAt: "desc",
+ },
+ },
+ },
+ });
+
+ const ownerEmail = workspace?.users[0].user.email ?? "";
+
+ if (count > 0) {
+ sendEmail({
+ subject: `Your CSV links have been imported!`,
+ email: ownerEmail,
+ from: "[email protected]", // TODO: REMOVE THIS!!!!
+ react: LinksImported({
+ email: ownerEmail,
+ provider: "CSV",
+ count,
+ links: workspace?.links ?? [],
+ domains,
+ workspaceName: workspace?.name ?? "",
+ workspaceSlug: workspace?.slug ?? "",
+ }),
+ });
+ }
+
+ if (errorLinks.length > 0) {
+ sendEmail({
+ subject: `Some CSV links failed to import`,
+ email: ownerEmail,
+ from: "[email protected]", // TODO: REMOVE THIS!!!!
+ react: LinksImportErrors({
+ email: ownerEmail,
+ provider: "CSV",
+ errorLinks,
+ workspaceName: workspace?.name ?? "",
+ workspaceSlug: workspace?.slug ?? "",
+ }),
+ });
+ }
+}
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/import/csv/upload/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/import/csv/upload/route.ts
index f22c9b3221..e45d9a68c2 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/import/csv/upload/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/import/csv/upload/route.ts
@@ -5,8 +5,8 @@ import { NextResponse } from "next/server";
// POST /api/workspaces/[idOrSlug]/import/csv/upload – get a signed URL to upload a CSV file
export const GET = withWorkspace(async ({ req, workspace, session }) => {
const id = new Date().getTime();
- const url = await storage.getSignedUrl({
- key: `workspaces/${workspace.id}/import/csv/${id}.csv`,
- });
+ const url = await storage.getSignedUrl(
+ `workspaces/${workspace.id}/import/csv/${id}.csv`,
+ );
return NextResponse.json({ url, id });
});
diff --git a/apps/web/emails/index.ts b/apps/web/emails/index.ts
index 19f0def350..bbf0a94062 100644
--- a/apps/web/emails/index.ts
+++ b/apps/web/emails/index.ts
@@ -40,11 +40,12 @@ export const sendEmail = async ({
return client.sendEmail({
From:
- from || marketing
+ from ||
+ (marketing
: process.env.NEXT_PUBLIC_IS_DUB
- : `${process.env.NEXT_PUBLIC_APP_NAME} <system@${process.env.NEXT_PUBLIC_APP_DOMAIN}>`,
+ : `${process.env.NEXT_PUBLIC_APP_NAME} <system@${process.env.NEXT_PUBLIC_APP_DOMAIN}>`),
To: email,
Bcc: bcc,
ReplyTo: process.env.NEXT_PUBLIC_IS_DUB
diff --git a/apps/web/emails/links-import-errors.tsx b/apps/web/emails/links-import-errors.tsx
new file mode 100644
index 0000000000..a26e5b5b3c
--- /dev/null
+++ b/apps/web/emails/links-import-errors.tsx
@@ -0,0 +1,120 @@
+import { DUB_WORDMARK, linkConstructor, truncate } from "@dub/utils";
+import {
+ Body,
+ Column,
+ Container,
+ Head,
+ Heading,
+ Hr,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Row,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+import Footer from "./components/footer";
+
+const MAX_ERROR_LINKS = 20;
+
+export function LinksImportErrors({
+ email,
+ provider = "CSV",
+ errorLinks,
+ workspaceName,
+ workspaceSlug,
+}: {
+ email: string;
+ provider: "CSV" | "Bitly" | "Short.io" | "Rebrandly";
+ errorLinks: {
+ domain: string;
+ key: string;
+ error: string;
+ }[];
+ workspaceName: string;
+ workspaceSlug: string;
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>Your {provider} links have been imported</Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[500px] rounded border border-solid border-gray-200 px-10 py-5">
+ <Section className="mt-8">
+ <Img
+ src={DUB_WORDMARK}
+ height="40"
+ alt="Dub"
+ className="mx-auto my-0"
+ />
+ </Section>
+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
+ Some {provider} links have failed to import
+ </Heading>
+ <Text className="text-sm leading-6 text-black">
+ The following{" "}
+ {Intl.NumberFormat("en-us").format(errorLinks.length)} links from{" "}
+ {provider} failed to import into your Dub.co workspace,{" "}
+ <Link
+ href={`https://app.dub.co/${workspaceSlug}`}
+ className="font-medium text-blue-600 no-underline"
+ >
+ {workspaceName}↗
+ </Link>
+ .
+ </Text>
+ <Section>
+ <Row className="pb-2">
+ <Column align="left" className="text-sm text-gray-500">
+ Link
+ </Column>
+ <Column align="right" className="text-sm text-gray-500">
+ Error
+ </Column>
+ </Row>
+ {errorLinks
+ .slice(0, MAX_ERROR_LINKS)
+ .map(({ domain, key, error }, index) => (
+ <div key={index}>
+ <Row>
+ <Column align="left" className="text-sm font-medium">
+ {truncate(
+ linkConstructor({ domain, key, pretty: true }),
+ 40,
+ )}
+ </Column>
+ <Column
+ align="right"
+ className="text-sm text-gray-600"
+ suppressHydrationWarning
+ >
+ {error}
+ </Column>
+ </Row>
+ {index !== errorLinks.length - 1 && (
+ <Hr className="my-2 w-full border border-gray-200" />
+ )}
+ </div>
+ ))}
+ </Section>
+ {errorLinks.length > MAX_ERROR_LINKS && (
+ <Section className="my-8 text-center">
+ <Text className="text-sm leading-6 text-black">
+ ...and {errorLinks.length - MAX_ERROR_LINKS} more errors
+ </Text>
+ </Section>
+ )}
+ <Text className="text-sm leading-6 text-black">
+ Please reply to this email for additional help with your CSV
+ import.
+ </Text>
+ <Footer email={email} />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/apps/web/emails/links-imported.tsx b/apps/web/emails/links-imported.tsx
index 289cd56708..c7ee7e9cca 100644
--- a/apps/web/emails/links-imported.tsx
+++ b/apps/web/emails/links-imported.tsx
@@ -128,7 +128,7 @@ export default function LinksImported({
))}
</Section>
)}
- {links.length > 5 && (
+ {count > 5 && (
<Section className="my-8 text-center">
<Link
className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
diff --git a/apps/web/lib/storage.ts b/apps/web/lib/storage.ts
index 1208b26bcc..fb2e57d98d 100644
--- a/apps/web/lib/storage.ts
+++ b/apps/web/lib/storage.ts
@@ -53,22 +53,6 @@ class StorageClient {
}
}
- async getSignedUrl({ key }: { key: string }) {
- const url = new URL(`${process.env.STORAGE_ENDPOINT}/${key}`);
-
- // 10 minutes expiration
- url.searchParams.set("X-Amz-Expires", "600");
-
- const signed = await this.client.sign(url.toString(), {
- method: "PUT",
- aws: {
- signQuery: true,
- },
- });
-
- return signed.url;
- }
-
async fetch(key: string) {
return this.client.fetch(`${process.env.STORAGE_ENDPOINT}/${key}`);
}
diff --git a/apps/web/ui/modals/import-csv-modal/field-mapping.tsx b/apps/web/ui/modals/import-csv-modal/field-mapping.tsx
index ee9041d8e8..473ec3d2bf 100644
--- a/apps/web/ui/modals/import-csv-modal/field-mapping.tsx
+++ b/apps/web/ui/modals/import-csv-modal/field-mapping.tsx
@@ -2,8 +2,14 @@
import { generateCsvMapping } from "@/lib/ai/generate-csv-mapping";
import { Button, IconMenu, InfoTooltip, Popover, Tooltip } from "@dub/ui";
-import { Check, LoadingSpinner, Magnifier, TableIcon } from "@dub/ui/src/icons";
-import { truncate } from "@dub/utils";
+import {
+ Check,
+ LoadingSpinner,
+ Magnifier,
+ TableIcon,
+ Xmark,
+} from "@dub/ui/src/icons";
+import { cn, truncate } from "@dub/utils";
import { readStreamableValue } from "ai/rsc";
import { ChevronDown } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
@@ -131,22 +137,35 @@ function FieldRow({
align="end"
content={
<div className="w-full p-2 md:w-48">
- {fileColumns?.map((column) => (
- <button
- key={column}
- onClick={() => {
- field.onChange(column);
- setIsOpen(false);
- }}
- className="flex w-full items-center justify-between space-x-2 rounded-md px-1 py-2 hover:bg-gray-100 active:bg-gray-200"
- >
- <IconMenu
- text={column}
- icon={<TableIcon className="h-4 w-4 flex-none" />}
- />
- {field.value === column && <Check className="h-4 w-4" />}
- </button>
- ))}
+ {[
+ ...(fileColumns || []),
+ ...(field.value ? ["None"] : []),
+ ]?.map((column) => {
+ const Icon = column !== "None" ? TableIcon : Xmark;
+ return (
+ <button
+ key={column}
+ onClick={() => {
+ field.onChange(
+ column !== "None" ? column : undefined,
+ );
+ setIsOpen(false);
+ }}
+ className={cn(
+ "flex w-full items-center justify-between space-x-2 rounded-md px-1 py-2 hover:bg-gray-100 active:bg-gray-200",
+ column === "None" && "text-gray-400",
+ )}
+ >
+ <IconMenu
+ text={column}
+ icon={<Icon className="h-4 w-4 flex-none" />}
+ />
+ {field.value === column && (
+ <Check className="h-4 w-4" />
+ )}
+ </button>
+ );
+ })}
</div>
}
openPopover={isOpen}
diff --git a/packages/ui/src/icons/nucleo/index.ts b/packages/ui/src/icons/nucleo/index.ts
index 5582509f93..4090f23018 100644
--- a/packages/ui/src/icons/nucleo/index.ts
+++ b/packages/ui/src/icons/nucleo/index.ts
@@ -70,3 +70,4 @@ export * from "./users6";
export * from "./watch";
export * from "./window";
export * from "./window-settings";
+export * from "./xmark";
diff --git a/packages/ui/src/icons/nucleo/xmark.tsx b/packages/ui/src/icons/nucleo/xmark.tsx
new file mode 100644
index 0000000000..4bdf953b2f
--- /dev/null
+++ b/packages/ui/src/icons/nucleo/xmark.tsx
@@ -0,0 +1,38 @@
+import { SVGProps } from "react";
+
+export function Xmark(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ height="18"
+ width="18"
+ viewBox="0 0 18 18"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <g fill="currentColor">
+ <line
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ x1="14"
+ x2="4"
+ y1="4"
+ y2="14"
+ />
+ <line
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ x1="4"
+ x2="14"
+ y1="4"
+ y2="14"
+ />
+ </g>
+ </svg>
+ );
+}