The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add tag importing
Tim Wilsona6c562c5a25b
diff --git a/apps/web/app/api/cron/import/csv/route.ts b/apps/web/app/api/cron/import/csv/route.tsindex 04e3baa2b1..0259ad4863 100644--- a/apps/web/app/api/cron/import/csv/route.ts+++ b/apps/web/app/api/cron/import/csv/route.ts@@ -8,6 +8,7 @@ import { ProcessedLinkProps, WorkspaceProps } from "@/lib/types";import { redis } from "@/lib/upstash";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";@@ -52,7 +53,11 @@ export async function POST(req: Request) {const response = await storage.fetch(url);- const [domains, defaultDomains] = await Promise.all([+ const [tags, domains, defaultDomains] = await Promise.all([+ prisma.tag.findMany({+ where: { projectId: workspace.id },+ select: { name: true },+ }),prisma.domain.findMany({where: { projectId: workspace.id },select: { slug: true },@@ -60,7 +65,9 @@ export async function POST(req: Request) {getDefaultDomains(workspace.id),]);+ const addedTags: string[] = [];const addedDomains: string[] = [];+let count = 0;await new Promise((resolve, reject) => {@@ -86,7 +93,7 @@ export async function POST(req: Request) {return;}- // Find links that already exist in the workspace (we still need to double check matching both domain and key)+ // Find links that already exist in the workspace (we check matching of *both* domain and key below)const alreadyCreatedLinks = await prisma.link.findMany({where: {domain: {@@ -102,6 +109,7 @@ export async function POST(req: Request) {},});+ // Find which links still need to be createdconst linksToCreate = data.filter((row) =>@@ -120,6 +128,35 @@ export async function POST(req: Request) {),);+ const selectedTags = [+ ...new Set(+ linksToCreate+ .map(+ ({ tags }) => tags?.split(",").map((tag) => tag.trim()) ?? [],+ )+ .flat(),+ ),+ ];++ // Find tags that need to be added to the workspace+ const tagsNotInWorkspace = selectedTags.filter(+ (tag) =>+ !tags.find((t) => t.name === tag) && !addedTags.includes(tag),+ );++ // Add missing tags to the workspace+ if (tagsNotInWorkspace.length > 0) {+ await prisma.tag.createMany({+ data: tagsNotInWorkspace.map((tag) => ({+ name: tag,+ color: randomBadgeColor(),+ projectId: workspace.id,+ })),+ });+ }++ addedTags.push(...tagsNotInWorkspace);+const selectedDomains = [...new Set(linksToCreate.map(({ domain }) => domain)),];@@ -132,6 +169,7 @@ export async function POST(req: Request) {!addedDomains.includes(domain),);+ // Add missing domains to the workspaceif (domainsNotInWorkspace.length > 0) {await Promise.allSettled([prisma.domain.createMany({@@ -150,6 +188,7 @@ export async function POST(req: Request) {addedDomains.push(...domainsNotInWorkspace);+ // Process all links, including domain linksconst processedLinks = await Promise.all([...domainsNotInWorkspace.map((domain) =>processLink({@@ -163,7 +202,7 @@ export async function POST(req: Request) {bulk: true,}),),- ...linksToCreate.map((link) =>+ ...linksToCreate.map(({ tags, ...link }) =>processLink({payload: createLinkBodySchema.parse({...link,@@ -173,6 +212,7 @@ export async function POST(req: Request) {.replace(/^https?:\/\//, "").split("/").at(-1),+ tagNames: tags || undefined,}),workspace: workspace as WorkspaceProps,userId,@@ -192,9 +232,9 @@ export async function POST(req: Request) {error,code,}));-// TODO: Use errorLinks+ // Creat all linksawait bulkCreateLinks({links: validLinks,});diff --git a/apps/web/app/api/cron/import/csv/utils.ts b/apps/web/app/api/cron/import/csv/utils.tsindex b08e6dccfd..8337712ea5 100644--- a/apps/web/app/api/cron/import/csv/utils.ts+++ b/apps/web/app/api/cron/import/csv/utils.ts@@ -1,146 +1 @@-import { bulkCreateLinks, processLink } from "@/lib/api/links";-import { qstash } from "@/lib/cron";-import { prisma } from "@/lib/prisma";-import { NewLinkProps, ProcessedLinkProps, WorkspaceProps } from "@/lib/types";-import { redis } from "@/lib/upstash";-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";-import { sendEmail } from "emails";-import LinksImported from "emails/links-imported";--export const importLinksFromCSV = async ({- workspaceId,- userId,- domain,- count = 0,-}: {- workspaceId: string;- userId: string;- domain: string;- count?: number;-}) => {- const [links, totalCount] = await Promise.all([- redis.lrange<NewLinkProps>(`import:csv:${workspaceId}`, count, count + 100),- redis.llen(`import:csv:${workspaceId}`),- ]);-- const workspace = (await prisma.project.findUnique({- where: {- id: workspaceId,- },- include: {- domains: true,- },- })) as unknown as WorkspaceProps;-- const processedLinks = await Promise.all(- links.map(async (link) =>- processLink({ payload: link, workspace, userId, bulk: true }),- ),- );-- const validLinks = processedLinks- .filter(({ error }) => error == null)- .map(({ link }) => link) as ProcessedLinkProps[];-- const alreadyCreatedLinks = await prisma.link.findMany({- where: {- domain,- key: {- in: validLinks.map((link) => link.key),- },- },- select: {- key: true,- },- });-- const importedLinks = await bulkCreateLinks({- links: validLinks.filter(- (link) => !alreadyCreatedLinks.some((l) => l.key === link.key),- ),- });-- count += links.length;-- console.log({- count,- totalCount,- importedLinks: importedLinks.length,- remainder: totalCount - count,- });-- // wait 500 ms before making another request- await new Promise((resolve) => setTimeout(resolve, 500));-- if (count >= totalCount) {- 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,- },- take: 5,- orderBy: {- createdAt: "desc",- },- },- },- });- const ownerEmail = workspace?.users[0].user.email ?? "";- const links = workspace?.links ?? [];-- await Promise.all([- // delete key from redis- redis.del(`import:csv:${workspaceId}`),-- // send email to user- sendEmail({- subject: `Your CSV links have been imported!`,- email: ownerEmail,- react: LinksImported({- email: ownerEmail,- provider: "CSV",- count,- links,- domains: [domain],- workspaceName: workspace?.name ?? "",- workspaceSlug: workspace?.slug ?? "",- }),- }),- ]);- return count;- } else {- // recursively call this function via qstash until nextPageToken is null- return await qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/csv`,- body: {- workspaceId,- userId,- domain,- count,- },- });- }-};+//diff --git a/apps/web/lib/ai/generate-csv-mapping.ts b/apps/web/lib/ai/generate-csv-mapping.tsindex 5e23932bcb..8ed21a672c 100644--- a/apps/web/lib/ai/generate-csv-mapping.ts+++ b/apps/web/lib/ai/generate-csv-mapping.ts@@ -27,6 +27,12 @@ export async function generateCsvMapping(.describe("The key/slug of the shortlink (a shortlink is: https://[domain]/[key]). Can be mapped to a full URL if there is not a separate key column",),+ tags: z+ .string()+ .optional()+ .describe(+ "A comma-separated list of tags for shortlink organization (NOT to be mapped to a description).",+ ),url: z.string().optional().describe("The full URL of the shortlink"),title: z.string().optional().describe("The title of the shortlink"),description: zdiff --git a/apps/web/lib/zod/schemas/import-csv.ts b/apps/web/lib/zod/schemas/import-csv.tsindex cd504400c4..a94679244a 100644--- a/apps/web/lib/zod/schemas/import-csv.ts+++ b/apps/web/lib/zod/schemas/import-csv.ts@@ -4,6 +4,7 @@ export const linkMappingSchema = z.object({domain: z.string(),url: z.string(),key: z.string(),+ tags: z.string().optional(),title: z.string().optional(),description: z.string().optional(),});diff --git a/apps/web/ui/modals/import-csv-modal/field-mapping.tsx b/apps/web/ui/modals/import-csv-modal/field-mapping.tsxindex 3f4808e9df..52adda8bf4 100644--- a/apps/web/ui/modals/import-csv-modal/field-mapping.tsx+++ b/apps/web/ui/modals/import-csv-modal/field-mapping.tsx@@ -75,17 +75,31 @@ function FieldRow({let values = firstRows?.map((row) => row[value]).filter(Boolean);- // Special split handling for domains and keys (should match backend)- if (field === "domain")- values = values.map((e) => e.replace(/^https?:\/\//, "").split("/")[0]);- if (field === "key")- values = values.map(- (e) =>+ switch (field) {+ case "domain":+ // Split by "/" and take the first part (excluding protocol)+ values = values.map((e) => e.replace(/^https?:\/\//, "").split("/")[0]);+ break;+ case "key":+ // Split by "/" and take the last part+ values = values.map(+ (e) =>+ e+ .replace(/^https?:\/\//, "")+ .split("/")+ .at(-1) as string,+ );+ break;+ case "tags":+ // Split by commas+ values = values.map((e) =>e- .replace(/^https?:\/\//, "")- .split("/")- .at(-1) as string,- );+ .split(",")+ .map((e) => e.trim())+ .join(" & "),+ );+ break;+ }values = values.map((e) => truncate(e, 16) as string);@@ -103,6 +117,9 @@ function FieldRow({content={`If your file doesn't have an independent ${field} column, you can map this to the full URL instead.`}/>)}+ {field === "tags" && (+ <InfoTooltip content="Tags may be comma-separated as long as they're escaped properly in the CSV file." />+ )}</span><div className="flex min-w-0 items-center"><Controllerdiff --git a/apps/web/ui/modals/import-csv-modal/index.tsx b/apps/web/ui/modals/import-csv-modal/index.tsxindex 6b501a8e79..5f1abc3928 100644--- a/apps/web/ui/modals/import-csv-modal/index.tsx+++ b/apps/web/ui/modals/import-csv-modal/index.tsx@@ -45,6 +45,10 @@ export const mappableFields = {label: "URL",required: true,},+ tags: {+ label: "Tags",+ required: false,+ },title: {label: "Title",required: false,@@ -157,9 +161,10 @@ function ImportCsvModal({<div className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16"><formonSubmit={handleSubmit(async (data) => {+ const loadingId = toast.loading(+ "Adding links to import queue...",+ );try {- toast.loading("Adding links to import queue...");-// Get signed upload URLconst uploadRes = await fetch(`/api/workspaces/${workspaceId}/import/csv/upload`,@@ -212,6 +217,8 @@ function ImportCsvModal({);} catch (error) {toast.error("Error adding links to import queue");+ } finally {+ toast.dismiss(loadingId);}})}className="flex flex-col space-y-4"diff --git a/apps/web/ui/modals/import-csv-modal/select-file.tsx b/apps/web/ui/modals/import-csv-modal/select-file.tsxindex 64e699b93e..3e66d7b98f 100644--- a/apps/web/ui/modals/import-csv-modal/select-file.tsx+++ b/apps/web/ui/modals/import-csv-modal/select-file.tsx@@ -1,18 +1,13 @@import { FileUpload, LoadingSpinner } from "@dub/ui";import { truncate } from "@dub/utils";+import Papa from "papaparse";import { useEffect, useState } from "react";import { Controller } from "react-hook-form";import { useCsvContext } from ".";export function SelectFile() {- const {- watch,- control,- fileColumns,- setFileColumns,- firstRows,- setFirstRows,- } = useCsvContext();+ const { watch, control, fileColumns, setFileColumns, setFirstRows } =+ useCsvContext();const file = watch("file");const [error, setError] = useState<string | null>(null);@@ -25,33 +20,28 @@ export function SelectFile() {readLines(file, 4).then((lines) => {- if (lines.length < 2) {+ const { data, meta } = Papa.parse(lines, {+ worker: false,+ skipEmptyLines: true,+ header: true,+ });++ if (!data || data.length < 2) {setError("CSV file must have at least 2 rows.");setFileColumns(null);setFirstRows(null);return;}- const split = lines[0].split(",");- if (split.length <= 1) {+ if (!meta || !meta.fields || meta.fields.length <= 1) {setError("Failed to retrieve CSV column data.");setFileColumns(null);setFirstRows(null);return;}- setFileColumns(split);- setFirstRows(- lines- .slice(1)- .map((line) =>- Object.fromEntries(- line- .split(",")- .map((value, idx) => [split[idx] ?? "unknown", value]),- ),- ),- );+ setFileColumns(meta.fields);+ setFirstRows(data);}).catch(() => {setError("Failed to read CSV file.");@@ -110,7 +100,7 @@ const listColumns = (columns: string[]) => {return allTruncated.join(", ");};-const readLines = async (file: File, count = 4): Promise<string[]> => {+const readLines = async (file: File, count = 4): Promise<string> => {const reader = file.stream().getReader();const decoder = new TextDecoder("utf-8");let { value: chunk, done: readerDone } = await reader.read();@@ -121,9 +111,9 @@ const readLines = async (file: File, count = 4): Promise<string[]> => {const lines = content.split("\n");if (lines.length >= count) {reader.cancel();- return lines.slice(0, count);+ return lines.slice(0, count).join("\n");}({ value: chunk, done: readerDone } = await reader.read());}- return result;+ return result.join("\n");};