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.

Hook up link exports

Tim Wilson20309a44f252
diff --git a/apps/web/app/api/links/export/route.ts b/apps/web/app/api/links/export/route.ts
new file mode 100644
index 0000000000..050533665b
--- /dev/null
+++ b/apps/web/app/api/links/export/route.ts
@@ -0,0 +1,132 @@
+import { INTERVAL_DATA } from "@/lib/analytics/constants";
+import { convertToCSV } from "@/lib/analytics/utils";
+import { getDomainOrThrow } from "@/lib/api/domains/get-domain-or-throw";
+import { throwIfClicksUsageExceeded } from "@/lib/api/links/usage-checks";
+import { withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { linksExportQuerySchema } from "@/lib/zod/schemas/links";
+import { linkConstructor } from "@dub/utils";
+
+// GET /api/links/export – export links to CSV
+export const GET = withWorkspace(
+ async ({ searchParams, workspace }) => {
+ throwIfClicksUsageExceeded(workspace);
+
+ const {
+ domain,
+ tagIds,
+ search,
+ sort,
+ userId,
+ showArchived,
+ withTags,
+ start,
+ end,
+ interval,
+ columns,
+ } = linksExportQuerySchema.parse(searchParams);
+
+ if (domain) {
+ await getDomainOrThrow({ workspace, domain });
+ }
+
+ const links = await prisma.link.findMany({
+ select: {
+ id: columns.includes("id"),
+ domain: columns.includes("link"),
+ key: columns.includes("link"),
+ url: columns.includes("url"),
+ clicks: columns.includes("clicks"),
+ createdAt: columns.includes("createdAt"),
+ updatedAt: columns.includes("updatedAt"),
+ ...(columns.includes("tags") && {
+ tags: {
+ select: {
+ tag: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ },
+ },
+ },
+ }),
+ archived: columns.includes("archived"),
+ },
+ where: {
+ projectId: workspace.id,
+ archived: showArchived ? undefined : false,
+ createdAt: {
+ gte: start ?? INTERVAL_DATA[interval ?? "all"].startDate,
+ lte: end ?? new Date(),
+ },
+ ...(domain && { domain }),
+ ...(search && {
+ OR: [
+ {
+ key: { contains: search },
+ },
+ {
+ url: { contains: search },
+ },
+ ],
+ }),
+ ...(withTags && {
+ tags: {
+ some: {},
+ },
+ }),
+ ...(tagIds &&
+ tagIds.length > 0 && {
+ tags: { some: { tagId: { in: tagIds } } },
+ }),
+ ...(userId && { userId }),
+ },
+ orderBy: {
+ [sort]: "desc",
+ },
+ });
+
+ const csvData = convertToCSV(
+ links.map((link) => {
+ // Use a Map to maintain order of keys
+ let result = new Map([
+ ...(columns.includes("link")
+ ? [
+ [
+ "link",
+ linkConstructor({ domain: link.domain, key: link.key }),
+ ] as [string, string],
+ ]
+ : []),
+ ...Object.entries(link),
+ ]);
+
+ if (columns.includes("link")) {
+ result.delete("domain");
+ result.delete("key");
+ }
+
+ if (columns.includes("tags")) {
+ result.set(
+ "tags",
+ link.tags.map((tag) => (tag as any).tag.name).join(", "),
+ );
+ }
+
+ return Object.fromEntries(result.entries());
+ }),
+ );
+
+ return new Response(csvData, {
+ headers: {
+ "Content-Type": "application/csv",
+ "Content-Disposition": `attachment; filename=links_export.csv`,
+ },
+ });
+ },
+ {
+ requiredScopes: ["links.read"],
+ },
+);
diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.ts
index da6c2954bc..e8246e43ed 100644
--- a/apps/web/lib/analytics/constants.ts
+++ b/apps/web/lib/analytics/constants.ts
@@ -1,3 +1,5 @@
+import { DUB_FOUNDING_DATE } from "@dub/utils";
+
export const intervals = [
"24h",
"7d",
@@ -73,7 +75,7 @@ export const INTERVAL_DATA: Record<
},
all: {
// Dub.co founding date
- startDate: new Date("2022-09-22"),
+ startDate: DUB_FOUNDING_DATE,
granularity: "month",
},
};
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index 5275f5a810..19d439440e 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -6,7 +6,12 @@ import {
intervals,
} from "@/lib/analytics/constants";
import z from "@/lib/zod";
-import { COUNTRY_CODES, capitalize } from "@dub/utils";
+import {
+ COUNTRY_CODES,
+ DUB_FOUNDING_DATE,
+ capitalize,
+ formatDate,
+} from "@dub/utils";
import { booleanQuerySchema } from "./misc";
import { parseDateSchema } from "./utils";
@@ -79,15 +84,9 @@ export const analyticsQuerySchema = z.object({
"The interval to retrieve analytics for. Takes precedence over start and end. If undefined, defaults to 24h.",
),
start: parseDateSchema
- .refine(
- (value: Date) => {
- const foundingDate = new Date("2022-09-22T00:00:00.000Z"); // Dub.co founding date
- return value >= foundingDate;
- },
- {
- message: "The start date cannot be earlier than September 22, 2022.",
- },
- )
+ .refine((value: Date) => value >= DUB_FOUNDING_DATE, {
+ message: `The start date cannot be earlier than ${formatDate(DUB_FOUNDING_DATE)}.`,
+ })
.optional()
.describe("The start date and time when to retrieve analytics from."),
end: parseDateSchema
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index fd3b9bfbe9..9409623fe3 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -1,8 +1,17 @@
import z from "@/lib/zod";
-import { COUNTRY_CODES, validDomainRegex } from "@dub/utils";
+import {
+ COUNTRY_CODES,
+ DUB_FOUNDING_DATE,
+ formatDate,
+ validDomainRegex,
+} from "@dub/utils";
import { booleanQuerySchema } from "./misc";
import { TagSchema } from "./tags";
-import { parseUrlSchema, parseUrlSchemaAllowEmpty } from "./utils";
+import {
+ parseDateSchema,
+ parseUrlSchema,
+ parseUrlSchemaAllowEmpty,
+} from "./utils";
export const getUrlQuerySchema = z.object({
url: parseUrlSchema,
@@ -91,6 +100,27 @@ export const getLinksCountQuerySchema = LinksQuerySchema.merge(
}),
);
+export const linksExportQuerySchema = getLinksQuerySchema
+ .omit({ page: true })
+ .merge(
+ z.object({
+ columns: z
+ .string()
+ .transform((v) => v.split(","))
+ .describe("The columns to export."),
+ start: parseDateSchema
+ .refine((value: Date) => value >= DUB_FOUNDING_DATE, {
+ message: `The start date cannot be earlier than ${formatDate(DUB_FOUNDING_DATE)}.`,
+ })
+ .optional()
+ .describe("The start date of creation to retrieve links from."),
+ end: parseDateSchema
+ .describe("The end date of creation to retrieve links from.")
+ .optional(),
+ interval: z.string().optional().describe("The interval for the export."),
+ }),
+ );
+
export const domainKeySchema = z.object({
domain: z
.string()
diff --git a/apps/web/ui/modals/export-links-modal.tsx b/apps/web/ui/modals/export-links-modal.tsx
index f90cadb076..a99238ee21 100644
--- a/apps/web/ui/modals/export-links-modal.tsx
+++ b/apps/web/ui/modals/export-links-modal.tsx
@@ -1,14 +1,6 @@
import { INTERVAL_DATA, INTERVAL_DISPLAYS } from "@/lib/analytics/constants";
import useWorkspace from "@/lib/swr/use-workspace";
-import {
- Button,
- Checkbox,
- DateRangePicker,
- Logo,
- Modal,
- useMediaQuery,
-} from "@dub/ui";
-import va from "@vercel/analytics";
+import { Button, Checkbox, DateRangePicker, Logo, Modal } from "@dub/ui";
import {
Dispatch,
SetStateAction,
@@ -25,6 +17,7 @@ const columns = [
{ id: "url", label: "Destination URL" },
{ id: "clicks", label: "Clicks" },
{ id: "createdAt", label: "Created at" },
+ { id: "id", label: "Link ID" },
{ id: "updatedAt", label: "Updated at" },
{ id: "tags", label: "Tags" },
{ id: "archived", label: "Archived" },
@@ -33,12 +26,12 @@ const columns = [
const defaultColumns = ["link", "url", "clicks", "createdAt"];
type FormData = {
- columns: string[];
dateRange: {
from?: Date;
to?: Date;
interval?: string;
};
+ columns: string[];
};
function ExportLinksModal({
@@ -49,59 +42,64 @@ function ExportLinksModal({
setShowExportLinksModal: Dispatch<SetStateAction<boolean>>;
}) {
const { id: workspaceId } = useWorkspace();
- const { isMobile } = useMediaQuery();
const dateRangePickerId = useId();
const checkboxId = useId();
const {
- register,
control,
handleSubmit,
- formState: { errors },
+ formState: { isLoading },
} = useForm<FormData>({
defaultValues: {
- columns: defaultColumns,
dateRange: {
interval: "all",
},
+ columns: defaultColumns,
},
});
- const [loading, setLoading] = useState(false);
+ const onSubmit = handleSubmit(async (data) => {
+ const lid = toast.loading("Exporting links...");
+ try {
+ const queryString = new URLSearchParams({
+ ...(workspaceId && { workspaceId }),
+ ...(data.dateRange.from && data.dateRange.to
+ ? {
+ start: data.dateRange.from.toISOString(),
+ end: data.dateRange.to.toISOString(),
+ }
+ : {
+ interval: data.dateRange.interval ?? "all",
+ }),
+ columns: (data.columns.length ? data.columns : defaultColumns).join(
+ ",",
+ ),
+ });
+ const response = await fetch(`/api/links/export?${queryString}`, {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
- const onSubmit = handleSubmit((data) => {
- setLoading(true);
- const queryString = new URLSearchParams({
- ...(workspaceId && { workspaceId }),
- ...(data.dateRange.from && data.dateRange.to
- ? {
- from: data.dateRange.from.toISOString(),
- to: data.dateRange.to.toISOString(),
- }
- : {
- interval: data.dateRange.interval ?? "all",
- }),
- columns: (data.columns.length ? data.columns : defaultColumns).join(","),
- }).toString();
- fetch(`/api/links/export?${queryString}`, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(data),
- })
- .then(async (res) => {
- if (res.status === 200 || res.status === 201) {
- va.track("Exported links");
- toast.success("Links exported successfully");
- setShowExportLinksModal(false);
- } else {
- const { error } = await res.json();
- toast.error(error.message);
- }
- })
- // TODO: catch
- .finally(() => setLoading(false));
+ if (!response.ok) {
+ throw new Error(response.statusText);
+ }
+
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `Dub Links Export - ${new Date().toISOString()}.csv`;
+ a.click();
+
+ toast.success("Exported successfully");
+ } catch (error) {
+ console.error(error);
+ toast.error(error);
+ } finally {
+ toast.dismiss(lid);
+ }
});
return (
@@ -149,9 +147,9 @@ function ExportLinksModal({
? field.value.interval ?? "all"
: undefined
}
- onChange={(dateRange, preset) =>
- field.onChange(preset ? { interval: preset.id } : dateRange)
- }
+ onChange={(dateRange, preset) => {
+ field.onChange(preset ? { interval: preset.id } : dateRange);
+ }}
presets={INTERVAL_DISPLAYS.map(({ display, value }) => ({
id: value,
label: display,
@@ -171,7 +169,7 @@ function ExportLinksModal({
name="columns"
control={control}
render={({ field }) => (
- <div className="mt-2 grid grid-cols-1 gap-x-4 gap-y-2 sm:grid-cols-2">
+ <div className="xs:grid-cols-2 mt-2 grid grid-cols-1 gap-x-4 gap-y-2">
{columns.map(({ id, label }) => (
<div key={id} className="group flex gap-2">
<Checkbox
@@ -198,7 +196,7 @@ function ExportLinksModal({
)}
/>
</div>
- <Button loading={loading} text="Export links" />
+ <Button loading={isLoading} text="Export links" />
</form>
</Modal>
);
diff --git a/packages/ui/src/checkbox.tsx b/packages/ui/src/checkbox.tsx
index 9b46855c79..19e27eda4d 100644
--- a/packages/ui/src/checkbox.tsx
+++ b/packages/ui/src/checkbox.tsx
@@ -13,7 +13,7 @@ const Checkbox = React.forwardRef<
<CheckboxPrimitive.Root
ref={ref}
className={cn(
- "peer h-5 w-5 shrink-0 rounded-md border border-gray-200 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-blue-500",
+ "peer h-5 w-5 shrink-0 rounded-md border border-gray-200 bg-white outline-none focus-visible:border-black disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-blue-500",
className,
)}
{...props}
diff --git a/packages/ui/src/date-picker/date-range-picker.tsx b/packages/ui/src/date-picker/date-range-picker.tsx
index 08f661d18b..511be22cb4 100644
--- a/packages/ui/src/date-picker/date-range-picker.tsx
+++ b/packages/ui/src/date-picker/date-range-picker.tsx
@@ -46,7 +46,7 @@ const DateRangePickerInner = ({
const [range, setRange] = useState<DateRange | undefined>(
preset?.dateRange ?? value ?? defaultValue ?? undefined,
);
- const [month, setMonth] = useState<Date | undefined>(range?.from);
+ const [month, setMonth] = useState<Date | undefined>(range?.to);
const initialRange = useMemo(() => {
return range;
@@ -66,8 +66,8 @@ const DateRangePickerInner = ({
}, [presets, presetId]);
useEffect(() => {
- if (!open) setMonth(range?.from);
- else if (range) setMonth(range.from);
+ if (!open) setMonth(range?.to);
+ else if (range) setMonth(range.to);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
diff --git a/packages/utils/src/constants/misc.ts b/packages/utils/src/constants/misc.ts
index 2b43d97dab..37e87c425c 100644
--- a/packages/utils/src/constants/misc.ts
+++ b/packages/utils/src/constants/misc.ts
@@ -30,3 +30,5 @@ export const DICEBEAR_AVATAR_URL =
export const PAGINATION_LIMIT = 100;
export const TWO_WEEKS_IN_SECONDS = 60 * 60 * 24 * 14;
+
+export const DUB_FOUNDING_DATE = new Date("2022-09-22T00:00:00.000Z");