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 last 12 months, add validDateRangeForPlan, getDayDifference

Steven Tey41d3124b0d49
diff --git a/apps/web/app/api/analytics/[endpoint]/route.ts b/apps/web/app/api/analytics/[endpoint]/route.ts
index ab89f130b9..0aa3a6c947 100644
--- a/apps/web/app/api/analytics/[endpoint]/route.ts
+++ b/apps/web/app/api/analytics/[endpoint]/route.ts
@@ -1,4 +1,4 @@
-import { getAnalytics } from "@/lib/analytics";
+import { getAnalytics, validDateRangeForPlan } from "@/lib/analytics";
import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
@@ -14,28 +14,47 @@ export const GET = withWorkspace(
const { endpoint } = analyticsEndpointSchema.parse(params);
const parsedParams = getAnalyticsQuerySchema.parse(searchParams);
- const { domain, key, interval, startDate, endDate } = parsedParams;
+ const { domain, key, interval, start, end } = parsedParams;
// Either interval can be provided, or both start and end date
- if (
- (interval && startDate && endDate) ||
- (startDate && !endDate) ||
- (!startDate && endDate)
- ) {
+ if ((interval && start && end) || (start && !end) || (!start && end)) {
throw new DubApiError({
code: "unprocessable_entity",
message: "Either provide interval or start and end date, not both",
});
}
- // return 403 if workspace is on the free plan and interval is 90d or allI do
+ // Free plan users can only get analytics for 30 days
+ if (
+ workspace.plan === "free" &&
+ !validDateRangeForPlan({
+ plan: workspace.plan,
+ interval,
+ start,
+ end,
+ })
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message:
+ "You can only get analytics for up to 30 days on a Free plan. Upgrade to Pro or Business to get analytics for longer periods.",
+ });
+ }
+
+ // Pro plan users can only get analytics for 1 year
if (
- workspace?.plan === "free" &&
- (interval === "all" || interval === "90d")
+ workspace.plan === "pro" &&
+ !validDateRangeForPlan({
+ plan: workspace.plan,
+ interval,
+ start,
+ end,
+ })
) {
throw new DubApiError({
code: "forbidden",
- message: "Require higher plan",
+ message:
+ "You can only get analytics for up to 1 year on a Pro plan. Upgrade to Business to get analytics for longer periods.",
});
}
diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.ts
new file mode 100644
index 0000000000..f5d986d412
--- /dev/null
+++ b/apps/web/lib/analytics/constants.ts
@@ -0,0 +1,100 @@
+export const intervals = [
+ "1h",
+ "24h",
+ "7d",
+ "30d",
+ "90d",
+ "1y",
+ "all",
+] as const;
+
+export const INTERVALS = [
+ {
+ display: "Last hour",
+ value: "1h",
+ },
+ {
+ display: "Last 24 hours",
+ value: "24h",
+ },
+ {
+ display: "Last 7 days",
+ value: "7d",
+ },
+ {
+ display: "Last 30 days",
+ value: "30d",
+ },
+ {
+ display: "Last 3 months",
+ value: "90d",
+ },
+ {
+ display: "Last 12 months",
+ value: "1y",
+ },
+ {
+ display: "All Time",
+ value: "all",
+ },
+];
+
+export const intervalData = {
+ "1h": {
+ startDate: new Date(Date.now() - 3600000),
+ granularity: "minute",
+ },
+ "24h": {
+ startDate: new Date(Date.now() - 86400000),
+ granularity: "hour",
+ },
+ "7d": {
+ startDate: new Date(Date.now() - 604800000),
+ granularity: "day",
+ },
+ "30d": {
+ startDate: new Date(Date.now() - 2592000000),
+ granularity: "day",
+ },
+ "90d": {
+ startDate: new Date(Date.now() - 7776000000),
+ granularity: "day",
+ },
+ "1y": {
+ startDate: new Date(Date.now() - 31556952000),
+ granularity: "month",
+ },
+ all: {
+ // Dub.co founding date
+ startDate: new Date("2022-09-22"),
+ granularity: "month",
+ },
+};
+
+export const VALID_TINYBIRD_ENDPOINTS = [
+ "clicks",
+ "timeseries",
+ "country",
+ "city",
+ "device",
+ "browser",
+ "os",
+ "referer",
+ "top_links",
+ "top_urls",
+ // "top_aliases",
+] as const;
+
+export const VALID_ANALYTICS_FILTERS = [
+ "country",
+ "city",
+ "url",
+ "alias",
+ "device",
+ "browser",
+ "os",
+ "referer",
+ "tagId",
+ "qr",
+ "root",
+];
diff --git a/apps/web/lib/analytics.ts b/apps/web/lib/analytics/get-analytics.ts
similarity index 57%
rename from apps/web/lib/analytics.ts
rename to apps/web/lib/analytics/get-analytics.ts
index 1cfd3ebf24..a37c1769a1 100644
--- a/apps/web/lib/analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -1,97 +1,12 @@
-import { DATABASE_URL, conn } from "./planetscale";
-import z from "./zod";
-import { getAnalyticsQuerySchema } from "./zod/schemas/analytics";
-
-export const intervals = ["1h", "24h", "7d", "30d", "90d", "all"] as const;
-
-export type IntervalProps = (typeof intervals)[number];
-
-export const INTERVALS = [
- {
- display: "Last hour",
- value: "1h",
- },
- {
- display: "Last 24 hours",
- value: "24h",
- },
- {
- display: "Last 7 days",
- value: "7d",
- },
- {
- display: "Last 30 days",
- value: "30d",
- },
- {
- display: "Last 3 months",
- value: "90d",
- },
- {
- display: "All Time",
- value: "all",
- },
-];
-
-export const intervalData = {
- "1h": {
- startDate: new Date(Date.now() - 3600000),
- granularity: "minute",
- },
- "24h": {
- startDate: new Date(Date.now() - 86400000),
- granularity: "hour",
- },
- "7d": {
- startDate: new Date(Date.now() - 604800000),
- granularity: "day",
- },
- "30d": {
- startDate: new Date(Date.now() - 2592000000),
- granularity: "day",
- },
- "90d": {
- startDate: new Date(Date.now() - 7776000000),
- granularity: "day",
- },
- all: {
- // Dub.co founding date
- startDate: new Date("2022-09-22"),
- granularity: "month",
- },
-};
-
-export type LocationTabs = "country" | "city";
-export type TopLinksTabs = "link" | "url";
-export type DeviceTabs = "device" | "browser" | "os" | "ua";
-
-export const VALID_TINYBIRD_ENDPOINTS = [
- "clicks",
- "timeseries",
- "country",
- "city",
- "device",
- "browser",
- "os",
- "referer",
- "top_links",
- "top_urls",
- // "top_aliases",
-] as const;
-
-export const VALID_ANALYTICS_FILTERS = [
- "country",
- "city",
- "url",
- "alias",
- "device",
- "browser",
- "os",
- "referer",
- "tagId",
- "qr",
- "root",
-];
+import { getDaysDifference } from "@dub/utils";
+import { DATABASE_URL, conn } from "../planetscale";
+import z from "../zod";
+import { getAnalyticsQuerySchema } from "../zod/schemas/analytics";
+import {
+ VALID_ANALYTICS_FILTERS,
+ VALID_TINYBIRD_ENDPOINTS,
+ intervalData,
+} from "./constants";
export const getAnalytics = async ({
workspaceId,
@@ -99,8 +14,8 @@ export const getAnalytics = async ({
domain,
endpoint,
interval,
- startDate,
- endDate,
+ start,
+ end,
...rest
}: z.infer<typeof getAnalyticsQuerySchema> & {
workspaceId?: string;
@@ -149,6 +64,7 @@ export const getAnalytics = async ({
} else if (domain) {
url.searchParams.append("domain", domain);
}
+
if (interval) {
url.searchParams.append(
"start",
@@ -165,14 +81,19 @@ export const getAnalytics = async ({
url.searchParams.append("granularity", intervalData[interval].granularity);
}
- if (startDate && endDate) {
+ if (start && end) {
url.searchParams.append(
"start",
- startDate.toString().replace("T", " ").replace("Z", ""),
+ start.toString().replace("T", " ").replace("Z", ""),
);
url.searchParams.append(
"end",
- endDate.toString().replace("T", " ").replace("Z", ""),
+ end.toString().replace("T", " ").replace("Z", ""),
+ );
+
+ url.searchParams.append(
+ "granularity",
+ getDaysDifference(start, end) > 180 ? "month" : "day",
);
}
diff --git a/apps/web/lib/analytics/index.ts b/apps/web/lib/analytics/index.ts
new file mode 100644
index 0000000000..ab8f164405
--- /dev/null
+++ b/apps/web/lib/analytics/index.ts
@@ -0,0 +1,4 @@
+export * from "./constants";
+export * from "./get-analytics";
+export * from "./types";
+export * from "./utils";
diff --git a/apps/web/lib/analytics/types.ts b/apps/web/lib/analytics/types.ts
new file mode 100644
index 0000000000..a202321f90
--- /dev/null
+++ b/apps/web/lib/analytics/types.ts
@@ -0,0 +1,6 @@
+import { intervals } from "./constants";
+
+export type IntervalProps = (typeof intervals)[number];
+export type LocationTabs = "country" | "city";
+export type TopLinksTabs = "link" | "url";
+export type DeviceTabs = "device" | "browser" | "os" | "ua";
diff --git a/apps/web/lib/analytics/utils.ts b/apps/web/lib/analytics/utils.ts
new file mode 100644
index 0000000000..9209c22f6f
--- /dev/null
+++ b/apps/web/lib/analytics/utils.ts
@@ -0,0 +1,33 @@
+import { getDaysDifference } from "@dub/utils";
+
+export const validDateRangeForPlan = ({
+ plan,
+ interval,
+ start,
+ end,
+}: {
+ plan?: string | null;
+ interval?: string;
+ start?: Date | null;
+ end?: Date | null;
+}) => {
+ if (
+ (!plan || plan === "free") &&
+ (interval === "all" ||
+ interval === "90d" ||
+ interval === "1y" ||
+ (start && end && getDaysDifference(start, end) > 30))
+ ) {
+ return false;
+ }
+
+ if (
+ plan === "pro" &&
+ (interval === "all" ||
+ (start && end && getDaysDifference(start, end) > 365))
+ ) {
+ return false;
+ }
+
+ return true;
+};
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index 3d8f718697..c70d259756 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -2,6 +2,7 @@ import { intervals, VALID_TINYBIRD_ENDPOINTS } from "@/lib/analytics";
import z from "@/lib/zod";
import { COUNTRY_CODES } from "@dub/utils";
import { booleanQuerySchema } from "./misc";
+import { parseDateSchema } from "./utils";
export const getAnalyticsQuerySchema = z.object({
domain: z.string().optional().describe("The domain of the short link."),
@@ -20,14 +21,11 @@ export const getAnalyticsQuerySchema = z.object({
.enum(intervals)
.optional()
.describe("The interval to retrieve analytics for."),
- startDate: z
- .string()
- .datetime()
+ start: parseDateSchema
.refine(
- (value) => {
- const inputDate = new Date(value);
+ (value: Date) => {
const foundingDate = new Date("2022-09-22T00:00:00.000Z"); // Dub.co founding date
- return inputDate >= foundingDate;
+ return value >= foundingDate;
},
{
message: "The start date cannot be earlier than September 22, 2022.",
@@ -35,14 +33,11 @@ export const getAnalyticsQuerySchema = z.object({
)
.optional()
.describe("The start date and time when to retrieve analytics from."),
- endDate: z
- .string()
- .datetime()
+ end: parseDateSchema
.refine(
- (value) => {
+ (value: Date) => {
const todaysDate = new Date();
- const inputDate = new Date(value);
- return inputDate <= todaysDate;
+ return value <= todaysDate;
},
{
message: "The end date cannot be in future.",
diff --git a/apps/web/lib/zod/schemas/domains.ts b/apps/web/lib/zod/schemas/domains.ts
index b707df6792..323e389982 100644
--- a/apps/web/lib/zod/schemas/domains.ts
+++ b/apps/web/lib/zod/schemas/domains.ts
@@ -1,5 +1,5 @@
import z from "@/lib/zod";
-import { parseUrlSchema } from "./links";
+import { parseUrlSchema } from "./utils";
export const DomainSchema = z.object({
id: z.string().describe("The unique identifier of the domain."),
diff --git a/apps/web/lib/zod/schemas/index.ts b/apps/web/lib/zod/schemas/index.ts
index 6ca1a9ed66..952367e0da 100644
--- a/apps/web/lib/zod/schemas/index.ts
+++ b/apps/web/lib/zod/schemas/index.ts
@@ -4,4 +4,5 @@ export * from "./links";
export * from "./misc";
export * from "./qr";
export * from "./tags";
+export * from "./utils";
export * from "./workspaces";
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index 0235612897..1032cd34fd 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -1,17 +1,8 @@
import z from "@/lib/zod";
-import {
- COUNTRY_CODES,
- getUrlFromString,
- isValidUrl,
- validDomainRegex,
-} from "@dub/utils";
+import { COUNTRY_CODES, validDomainRegex } from "@dub/utils";
import { booleanQuerySchema } from "./misc";
import { TagSchema } from "./tags";
-
-export const parseUrlSchema = z
- .string()
- .transform((v) => getUrlFromString(v))
- .refine((v) => isValidUrl(v), { message: "Invalid URL" });
+import { parseUrlSchema } from "./utils";
export const getUrlQuerySchema = z.object({
url: parseUrlSchema,
diff --git a/apps/web/lib/zod/schemas/utils.ts b/apps/web/lib/zod/schemas/utils.ts
new file mode 100644
index 0000000000..e64c6fe830
--- /dev/null
+++ b/apps/web/lib/zod/schemas/utils.ts
@@ -0,0 +1,12 @@
+import z from "@/lib/zod";
+import { getUrlFromString, isValidUrl, parseDateTime } from "@dub/utils";
+
+export const parseUrlSchema = z
+ .string()
+ .transform((v) => getUrlFromString(v))
+ .refine((v) => isValidUrl(v), { message: "Invalid URL" });
+
+export const parseDateSchema = z
+ .string()
+ .transform((v) => parseDateTime(v))
+ .refine((v) => !!v, { message: "Invalid date" });
diff --git a/apps/web/ui/analytics/clicks-chart.tsx b/apps/web/ui/analytics/clicks-chart.tsx
index 894636c0c4..21854a18ad 100644
--- a/apps/web/ui/analytics/clicks-chart.tsx
+++ b/apps/web/ui/analytics/clicks-chart.tsx
@@ -34,6 +34,7 @@ export default function ClicksChart() {
hour: "numeric",
minute: "numeric",
});
+ case "1y":
case "all":
return date.toLocaleDateString("en-US", {
month: "short",
diff --git a/apps/web/ui/analytics/date-range-picker.tsx b/apps/web/ui/analytics/date-range-picker.tsx
index 3cabefe907..f27e9db13d 100644
--- a/apps/web/ui/analytics/date-range-picker.tsx
+++ b/apps/web/ui/analytics/date-range-picker.tsx
@@ -1,4 +1,4 @@
-import { INTERVALS } from "@/lib/analytics";
+import { INTERVALS, validDateRangeForPlan } from "@/lib/analytics";
import useWorkspace from "@/lib/swr/use-workspace";
import {
IconMenu,
@@ -8,7 +8,7 @@ import {
TooltipContent,
useRouterStuff,
} from "@dub/ui";
-import { APP_DOMAIN, cn } from "@dub/utils";
+import { APP_DOMAIN, cn, getNextPlan } from "@dub/utils";
import { Calendar, ChevronDown, Lock } from "lucide-react";
import Link from "next/link";
import { useContext, useMemo, useState } from "react";
@@ -34,15 +34,16 @@ export default function DateRangePicker() {
content={
<div className="grid w-full p-2 md:w-48">
{INTERVALS.map(({ display, value }) =>
- (value === "all" || value === "90d") &&
- (!plan || plan === "free") &&
- !admin ? (
+ !validDateRangeForPlan({
+ plan,
+ interval: value,
+ }) && !admin ? (
<Tooltip
key={value}
content={
<TooltipContent
- title={`${display} stats can only be viewed on a Pro plan or higher. Upgrade now to view all-time stats.`}
- cta="Upgrade to Pro"
+ title={`${display} stats can only be viewed on a ${value === "all" ? "Business" : getNextPlan(plan).name} plan or higher. Upgrade now to view all-time stats.`}
+ cta={`Upgrade to ${value === "all" ? "Business" : getNextPlan(plan).name}`}
{...(isPublicStatsPage
? {
href: APP_DOMAIN,
@@ -52,7 +53,10 @@ export default function DateRangePicker() {
setOpenDatePopover(false);
queryParams({
set: {
- upgrade: "pro",
+ upgrade:
+ value === "all"
+ ? "business"
+ : getNextPlan(plan).name.toLowerCase(),
},
});
},
diff --git a/packages/utils/src/constants/pricing.tsx b/packages/utils/src/constants/pricing.tsx
index 520ed5184b..5a144e8aa6 100644
--- a/packages/utils/src/constants/pricing.tsx
+++ b/packages/utils/src/constants/pricing.tsx
@@ -339,7 +339,8 @@ export const getPlanDetails = (plan: string) => {
)!;
};
-export const getNextPlan = (plan: string) => {
+export const getNextPlan = (plan?: string | null) => {
+ if (!plan) return PRO_PLAN;
return PLANS[
PLANS.findIndex((p) => p.name.toLowerCase() === plan.toLowerCase()) + 1
];
diff --git a/packages/utils/src/functions/datetime.ts b/packages/utils/src/functions/datetime.ts
index 68fe48003a..1eb8174b97 100644
--- a/packages/utils/src/functions/datetime.ts
+++ b/packages/utils/src/functions/datetime.ts
@@ -38,6 +38,12 @@ export const formatDateTime = (datetime: Date | string) => {
});
};
+// Function to get the number of days between two dates
+export const getDaysDifference = (startDate: Date, endDate: Date) => {
+ const diffTime = Math.abs(endDate.getTime() - startDate.getTime());
+ return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
+};
+
export const getFirstAndLastDay = (day: number) => {
const today = new Date();
const currentDay = today.getDate();