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.

Added link filters (search, filter by domain), schema changes, etc.

Steven Tey01f1c045dbce
diff --git a/components/app/domains/domain-card-placeholder.tsx b/components/app/domains/domain-card-placeholder.tsx
new file mode 100644
index 0000000000..05e831118c
--- /dev/null
+++ b/components/app/domains/domain-card-placeholder.tsx
@@ -0,0 +1,26 @@
+export default function DomainCardPlaceholder() {
+ return (
+ <div className="flex flex-col space-y-3 rounded-lg border border-gray-200 bg-white px-5 py-8 sm:px-10">
+ <div className="flex flex-col justify-between space-y-4 sm:flex-row sm:space-x-4">
+ <div className="flex items-center space-x-2">
+ <div className="h-6 w-28 animate-pulse rounded-md bg-gray-200" />
+ <div className="h-6 w-32 animate-pulse rounded-full bg-gray-200" />
+ </div>
+ <div className="flex space-x-3">
+ <div className="h-9 w-24 animate-pulse rounded-md bg-gray-200" />
+ <div className="h-9 w-24 animate-pulse rounded-md bg-gray-200" />
+ </div>
+ </div>
+ <div className="flex h-10 items-center space-x-5">
+ <div className="flex items-center space-x-2">
+ <div className="h-6 w-6 animate-pulse rounded-full bg-gray-200" />
+ <div className="h-5 w-36 animate-pulse rounded-md bg-gray-200" />
+ </div>
+ <div className="flex items-center space-x-2">
+ <div className="h-6 w-6 animate-pulse rounded-full bg-gray-200" />
+ <div className="h-5 w-36 animate-pulse rounded-md bg-gray-200" />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/components/app/domains/domain-card.tsx b/components/app/domains/domain-card.tsx
index 0cd6fd7c25..cc2a9bf952 100644
--- a/components/app/domains/domain-card.tsx
+++ b/components/app/domains/domain-card.tsx
@@ -9,7 +9,12 @@ import {
XCircleFill,
} from "@/components/shared/icons";
import { DomainProps, DomainVerificationStatusProps } from "@/lib/types";
-import { capitalize, fetcher, getDomainWithoutWWW } from "@/lib/utils";
+import {
+ capitalize,
+ fetcher,
+ getDomainWithoutWWW,
+ truncate,
+} from "@/lib/utils";
import { useAddEditDomainModal } from "../modals/add-edit-domain-modal";
import DomainConfiguration from "./domain-configuration";
@@ -111,7 +116,10 @@ export default function DomainCard({ props }: { props: DomainProps }) {
rel="noreferrer"
className="text-sm font-medium text-gray-600"
>
- {getDomainWithoutWWW(target)}
+ {truncate(
+ target.replace(/^(?:https?:\/\/)?(?:www\.)?/i, ""),
+ 24,
+ )}
</a>
)}
</div>
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsx
index 025a920c8d..083684403d 100644
--- a/components/app/links/link-card.tsx
+++ b/components/app/links/link-card.tsx
@@ -21,7 +21,6 @@ import {
import Popover from "@/components/shared/popover";
import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import useProject from "@/lib/swr/use-project";
-import useUsage from "@/lib/swr/use-usage";
import { LinkProps } from "@/lib/types";
import {
fetcher,
@@ -41,9 +40,8 @@ export default function LinkCard({ props }: { props: LinkProps }) {
const router = useRouter();
const { slug } = router.query as { slug: string };
- const { isOwner } = useProject();
- const { verified, loading } = useDomains(domain);
- const { exceededUsage } = useUsage();
+ const { exceededUsage } = useProject();
+ const { verified, loading } = useDomains({ domain });
const linkRef = useRef<any>();
const entry = useIntersectionObserver(linkRef, {});
@@ -53,7 +51,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
isVisible &&
(slug
? `/api/projects/${slug}/links/${key}/stats/clicks?domain=${domain}`
- : `/api/edge/links/${key}/stats/clicks`),
+ : `/api/links/${key}/stats/clicks`),
fetcher,
{
fallbackData: props.clicks,
@@ -80,20 +78,20 @@ export default function LinkCard({ props }: { props: LinkProps }) {
return (
<div
ref={linkRef}
- className="relative rounded-lg border border-gray-100 bg-white p-3 pr-1 shadow transition-all hover:shadow-md sm:p-4"
+ className="relative rounded-lg border border-gray-100 bg-white p-3 pr-1 shadow transition-all hover:shadow-md sm:p-4 "
>
<LinkQRModal />
<AddEditLinkModal />
<ArchiveLinkModal />
<DeleteLinkModal />
- <div className="absolute top-0 left-0 flex h-full w-1.5 flex-col overflow-hidden rounded-l-lg">
+ {/* <div className="absolute top-0 left-0 flex h-full w-1.5 flex-col overflow-hidden rounded-l-lg">
{archived && <div className="h-full w-full bg-gray-400" />}
{expired ? (
<div className="h-full w-full bg-amber-500" />
) : (
<div className="h-full w-full bg-green-500" />
)}
- </div>
+ </div> */}
<li className="relative flex items-center justify-between">
<div className="relative flex shrink items-center space-x-2 sm:space-x-4">
<BlurImage
@@ -146,7 +144,9 @@ export default function LinkCard({ props }: { props: LinkProps }) {
<QR className="text-gray-700 transition-all group-hover:text-blue-800" />
</button>
<Link
- href={`/${`${slug}/${domain}` || "links"}/${encodeURI(key)}`}
+ href={`/${slug ? `${slug}/${domain}` : "links"}/${encodeURI(
+ key,
+ )}`}
className="flex items-center space-x-1 rounded-md bg-gray-100 px-2 py-0.5 transition-all duration-75 hover:scale-105 active:scale-100"
>
<Chart className="h-4 w-4" />
@@ -156,7 +156,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
</p>
</Link>
</div>
- <h3 className="max-w-[200px] truncate text-sm font-medium text-gray-700 md:max-w-md lg:max-w-2xl xl:max-w-3xl">
+ <h3 className="max-w-[200px] truncate text-sm font-medium text-gray-700 md:max-w-md xl:max-w-lg">
{url}
</h3>
</div>
@@ -176,13 +176,9 @@ export default function LinkCard({ props }: { props: LinkProps }) {
<Tooltip
content={
<TooltipContent
- title={
- isOwner
- ? "You have exceeded your usage limit. We're still collecting data on your existing links, but you need to upgrade to edit them."
- : "The owner of this project has exceeded their usage limit. We're still collecting data on all existing links, but they need to upgrade their plan to edit them."
- }
- cta={isOwner && "Upgrade"}
- ctaLink={isOwner && "/settings"}
+ title="Your project has exceeded its usage limit. We're still collecting data on your existing links, but you need to upgrade to edit them."
+ cta="Upgrade"
+ ctaLink={`/${slug}/settings/billing`}
/>
}
>
diff --git a/components/app/links/link-filters/index.tsx b/components/app/links/link-filters/index.tsx
index 108f87db98..b172febb0a 100644
--- a/components/app/links/link-filters/index.tsx
+++ b/components/app/links/link-filters/index.tsx
@@ -1,59 +1,169 @@
import { useRouter } from "next/router";
-import { useState } from "react";
+import { useRef, useState } from "react";
+import { nFormatter, setQueryString } from "@/lib/utils";
+import { ChevronRight, XCircle, Search } from "lucide-react";
+import useDomains from "@/lib/swr/use-domains";
import { AnimatePresence, motion } from "framer-motion";
-import { ChevronDown, Filter } from "@/components/shared/icons";
import { SWIPE_REVEAL_ANIMATION_SETTINGS } from "@/lib/constants";
-import LinkSort from "./link-sort";
-import StatusFilter from "./status-filter";
-import UserFilter from "./user-filter";
+import { useDebouncedCallback } from "use-debounce";
+import Link from "next/link";
export default function LinkFilters() {
+ const { domains } = useDomains({ includeLinkCount: true });
const router = useRouter();
- const { slug } = router.query as { slug?: string };
- const [showFilters, setShowFilters] = useState(false);
- return (
- <>
- {/* Mobile filters */}
- <button
- onClick={() => setShowFilters(!showFilters)}
- className="my-5 flex w-full items-center justify-between space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95 sm:hidden"
- >
- <div className="flex items-center space-x-2 text-gray-700">
- <Filter className="h-4 w-4 shrink-0" />
- <p className="text-sm">Filters</p>
+ const { slug, search, domain, status } = router.query;
+ const searchInputRef = useRef(); // this is a hack to clear the search input when the clear button is clicked
+
+ return domains ? (
+ <div className="grid w-full gap-6 rounded-md bg-white p-5 lg:divide-y lg:divide-gray-300">
+ <div className="grid gap-3">
+ <div className="flex items-center justify-between">
+ <h3 className="mt-2 ml-1 font-semibold">Filter Links</h3>
+ {(search || domain || status) && (
+ <ClearButton searchInputRef={searchInputRef} />
+ )}
</div>
- <ChevronDown
- className={`h-5 w-5 text-gray-400 ${
- showFilters ? "rotate-180 transform" : ""
- } transition-all duration-75`}
- />
- </button>
- <AnimatePresence>
- {showFilters && (
+ <SearchBox searchInputRef={searchInputRef} />
+ </div>
+ <FilterGroup
+ param="domain"
+ options={domains?.map(({ slug, _count }) => ({
+ value: slug,
+ count: _count.links,
+ }))}
+ cta={{
+ type: "link",
+ text: "Add a domain",
+ href: `/${slug}/domains`,
+ }}
+ />
+ </div>
+ ) : (
+ <div className="grid h-full gap-6 rounded-md bg-white p-5">
+ <div className="h-[300px] w-full animate-pulse rounded-md bg-gray-200" />
+ </div>
+ );
+}
+const SearchBox = ({ searchInputRef }: { searchInputRef }) => {
+ const router = useRouter();
+ const debounced = useDebouncedCallback((value) => {
+ setQueryString(router, "search", value);
+ }, 500);
+
+ return (
+ <div className="relative">
+ <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
+ <Search className="h-4 w-4 text-gray-400" />
+ </div>
+ <input
+ ref={searchInputRef}
+ type="text"
+ className="peer w-full rounded-md border border-gray-300 pl-10 text-sm text-black placeholder:text-gray-400 focus:border-black focus:ring-0"
+ placeholder="Search..."
+ defaultValue={router.query.search}
+ onChange={(e) => {
+ debounced(e.target.value);
+ }}
+ />
+ </div>
+ );
+};
+
+const FilterGroup = ({
+ param,
+ options,
+ cta,
+}: {
+ param: string;
+ options: { value: string; count: number }[];
+ cta: {
+ type: "link" | "button";
+ text: string;
+ href?: string;
+ action?: () => void;
+ };
+}) => {
+ const router = useRouter();
+ const [collapsed, setCollapsed] = useState(false);
+
+ return (
+ <fieldset className="pt-6">
+ <div className="flex h-8 items-center justify-between">
+ <button
+ onClick={() => {
+ setCollapsed(!collapsed);
+ }}
+ className="flex items-center space-x-2"
+ >
+ <ChevronRight
+ className={`${collapsed ? "" : "rotate-90"} h-5 w-5 transition-all`}
+ />
+ <h4 className="font-medium capitalize text-gray-900">{param}</h4>
+ </button>
+ </div>
+ <AnimatePresence initial={false}>
+ {!collapsed && (
<motion.div
- className="flex w-full flex-col space-y-2 border-t border-gray-200 py-5 sm:hidden"
+ className="mt-4 grid gap-2"
{...SWIPE_REVEAL_ANIMATION_SETTINGS}
>
- <LinkSort />
- <StatusFilter />
- {slug && <UserFilter />}
+ {options?.map(({ value, count }) => (
+ <div
+ key={value}
+ className="relative flex cursor-pointer items-center space-x-3 rounded-md bg-gray-50 transition-all hover:bg-gray-100"
+ >
+ <input
+ id={value}
+ name={value}
+ checked={
+ router.query[param] === value || options.length === 1
+ }
+ onChange={() => {
+ setQueryString(router, param, value);
+ }}
+ type="radio"
+ className="ml-3 h-4 w-4 cursor-pointer rounded-full border-gray-300 text-black focus:outline-none focus:ring-0"
+ />
+ <label
+ htmlFor={value}
+ className="flex w-full cursor-pointer justify-between px-3 py-2 pl-0 text-sm font-medium text-gray-700"
+ >
+ <p>{value}</p>
+ <p className="text-gray-500">{nFormatter(count)}</p>
+ </label>
+ </div>
+ ))}
+ {router.query.slug && (
+ <Link
+ href={cta.href}
+ className="rounded-md border border-gray-300 p-1 text-center text-sm"
+ >
+ {cta.text}
+ </Link>
+ )}
</motion.div>
)}
</AnimatePresence>
+ </fieldset>
+ );
+};
- {/* Desktop filters */}
- <div className="my-5 hidden w-full justify-end sm:flex">
- <LinkSort />
- {/* Weird workaround because if I put `space-x-2` in the parent it misaligns the popover dropdown */}
- <div className="w-4" />
- <StatusFilter />
- {slug && (
- <>
- <div className="w-4" />
- <UserFilter />
- </>
- )}
- </div>
- </>
+const ClearButton = ({ searchInputRef }: { searchInputRef }) => {
+ const router = useRouter();
+ const { slug } = router.query;
+ return (
+ <button
+ onClick={() => {
+ router.replace(`/${slug || "links"}`).then(() => {
+ searchInputRef.current.value = "";
+ });
+ }}
+ className="group flex items-center justify-center space-x-1 rounded-md border border-gray-500 px-2 py-1 transition-all hover:border-black"
+ >
+ <XCircle className="h-4 w-4 text-gray-500 transition-all group-hover:text-black" />
+ <p className="text-sm text-gray-500 transition-all group-hover:text-black">
+ Clear
+ </p>
+ </button>
);
-}
+};
diff --git a/components/app/links/link-filters/link-sort.tsx b/components/app/links/link-sort.tsx
similarity index 92%
rename from components/app/links/link-filters/link-sort.tsx
rename to components/app/links/link-sort.tsx
index 6f748d34d2..7aa6d64566 100644
--- a/components/app/links/link-filters/link-sort.tsx
+++ b/components/app/links/link-sort.tsx
@@ -70,7 +70,7 @@ export default function LinkSort() {
>
<button
onClick={() => setOpenPopover(!openPopover)}
- className="flex w-full items-center justify-between space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95 sm:w-48"
+ className="flex w-48 items-center justify-between space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95"
>
<IconMenu text="Sort by" icon={<Sort className="h-4 w-4 shrink-0" />} />
<ChevronDown
diff --git a/components/app/links/links-container.tsx b/components/app/links/links-container.tsx
index a2411ae2b6..71664bd377 100644
--- a/components/app/links/links-container.tsx
+++ b/components/app/links/links-container.tsx
@@ -8,54 +8,50 @@ import LinkCard from "./link-card";
import LinkCardPlaceholder from "./link-card-placeholder";
import LinkFilters from "./link-filters";
import NoLinksPlaceholder from "./no-links-placeholder";
-import { useMemo } from "react";
+import LinkSort from "./link-sort";
+import useLinks from "@/lib/swr/use-links";
+import IconMenu from "@/components/shared/icon-menu";
+import { ChevronDown, Filter } from "lucide-react";
export default function LinksContainer({
AddEditLinkButton,
}: {
AddEditLinkButton: () => JSX.Element;
}) {
- const router = useRouter();
- const { slug } = router.query as {
- slug: string;
- };
-
- const { project } = useProject();
-
- const { data: links } = useSWR<LinkProps[]>(
- slug
- ? `/api/projects/${slug}/links${getQueryString(router)}`
- : `/api/links${getQueryString(router)}`,
- fetcher,
- {
- // disable this because it keeps refreshing the state of the modal when its open
- revalidateOnFocus: false,
- },
- );
-
- const loading = useMemo(() => {
- if (slug) {
- // need to include `domain` because if not it flashes the "no links" placeholder
- return links && project ? false : true;
- } else {
- return links ? false : true;
- }
- }, [links, project, slug]);
+ const { links, loading } = useLinks();
return (
<MaxWidthWrapper className="pb-10">
- <LinkFilters />
- <ul className="grid grid-cols-1 gap-3">
- {loading ? (
- Array.from({ length: 5 }).map((_, i) => (
- <LinkCardPlaceholder key={i} />
- ))
- ) : links.length > 0 ? (
- links.map((props) => <LinkCard key={props.key} props={props} />)
- ) : (
- <NoLinksPlaceholder AddEditLinkButton={AddEditLinkButton} />
- )}
- </ul>
+ <div className="my-5 flex w-full justify-center lg:justify-end">
+ <button className="mr-5 flex flex-1 items-center justify-between space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95 lg:hidden">
+ <IconMenu
+ text="Filters"
+ icon={<Filter className="h-4 w-4 shrink-0" />}
+ />
+ <ChevronDown
+ className={`h-5 w-5 text-gray-400 ${
+ true ? "rotate-180 transform" : ""
+ } transition-all duration-75`}
+ />
+ </button>
+ <LinkSort />
+ </div>
+ <div className="grid grid-cols-1 gap-5 lg:grid-cols-7">
+ <div className="sticky top-32 col-span-2 hidden max-h-[500px] self-start rounded-lg border border-gray-100 bg-white shadow lg:block">
+ <LinkFilters />
+ </div>
+ <ul className="col-span-1 grid auto-rows-min grid-cols-1 gap-3 lg:col-span-5">
+ {loading ? (
+ Array.from({ length: 5 }).map((_, i) => (
+ <LinkCardPlaceholder key={i} />
+ ))
+ ) : links.length > 0 ? (
+ links.map((props) => <LinkCard key={props.id} props={props} />)
+ ) : (
+ <NoLinksPlaceholder AddEditLinkButton={AddEditLinkButton} />
+ )}
+ </ul>
+ </div>
</MaxWidthWrapper>
);
}
diff --git a/components/app/links/no-links-placeholder.tsx b/components/app/links/no-links-placeholder.tsx
index 9ad171e32a..51f6a3e6a2 100644
--- a/components/app/links/no-links-placeholder.tsx
+++ b/components/app/links/no-links-placeholder.tsx
@@ -8,7 +8,7 @@ export default function NoLinksPlaceholder({
return (
<div className="flex flex-col items-center justify-center rounded-md border border-gray-200 bg-white py-12">
<h2 className="z-10 text-xl font-semibold text-gray-700">
- You don't have any links yet!
+ No links found.
</h2>
<BlurImage
src="/_static/illustrations/call-waiting.svg"
@@ -18,6 +18,7 @@ export default function NoLinksPlaceholder({
className="pointer-events-none -my-8"
/>
<AddEditLinkButton />
+ <p className="mt-2 text-sm text-gray-500">or edit your search filters</p>
</div>
);
}
diff --git a/components/app/modals/accept-invite-modal.tsx b/components/app/modals/accept-invite-modal.tsx
index 1f57d84c14..b1c3be793c 100644
--- a/components/app/modals/accept-invite-modal.tsx
+++ b/components/app/modals/accept-invite-modal.tsx
@@ -59,7 +59,7 @@ function AcceptInviteModal({
headers: { "Content-Type": "application/json" },
}).then(() => {
toast.success("You now are a part of this project!");
- mutate(`/api/projects`);
+ mutate("/api/projects");
mutate(`/api/projects/${slug}`);
mutate(`/api/projects/${slug}/users`);
});
diff --git a/components/app/modals/add-edit-domain-modal.tsx b/components/app/modals/add-edit-domain-modal.tsx
index 45a44a17c2..a2e3ee6827 100644
--- a/components/app/modals/add-edit-domain-modal.tsx
+++ b/components/app/modals/add-edit-domain-modal.tsx
@@ -16,7 +16,6 @@ import Modal from "@/components/shared/modal";
import { DomainProps } from "@/lib/types";
import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import useProject from "@/lib/swr/use-project";
-import useUsage from "@/lib/swr/use-usage";
import { AnimatePresence, motion } from "framer-motion";
import { SWIPE_REVEAL_ANIMATION_SETTINGS } from "@/lib/constants";
import Switch from "@/components/shared/switch";
@@ -33,8 +32,7 @@ function AddEditDomainModal({
}) {
const router = useRouter();
const { slug } = router.query;
- const { project: { logo } = {}, isOwner } = useProject();
- const { plan } = useUsage();
+ const { logo, plan } = useProject();
const { domains } = useDomains();
const [data, setData] = useState<DomainProps>(
@@ -251,7 +249,7 @@ function AddEditDomainModal({
>
Landing Page
</label>
- {plan !== "Free" ? (
+ {plan !== "free" ? (
<div className="relative mt-1 rounded-md shadow-sm">
<input
type="url"
@@ -267,13 +265,9 @@ function AddEditDomainModal({
<Tooltip
content={
<TooltipContent
- title={`You can't configure a custom landing page on a free plan. ${
- isOwner
- ? "Upgrade to a Pro plan to proceed."
- : "Ask your project owner to upgrade to a Pro plan."
- }`}
- cta={isOwner && "Upgrade to Pro"}
- ctaLink={isOwner && "/settings"}
+ title="You can't configure a custom landing page on a free plan. Upgrade to a Pro plan to proceed."
+ cta="Upgrade to Pro"
+ ctaLink={`/${slug}/settings`}
/>
}
fullWidth
@@ -370,10 +364,16 @@ function AddEditDomainButton({
const router = useRouter();
const { slug } = router.query as { slug?: string };
- const { plan } = useUsage();
- const { domains } = useDomains();
+ const { plan } = useProject();
- return slug && plan === "Free" && domains?.length >= 1 ? (
+ return slug && plan && plan !== "free" ? (
+ <button
+ onClick={() => setShowAddEditDomainModal(true)}
+ className="rounded-md border border-black bg-black px-5 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black active:scale-95"
+ >
+ Add Domain
+ </button>
+ ) : (
<Tooltip
content={
<TooltipContent
@@ -384,20 +384,13 @@ function AddEditDomainButton({
}
>
<div className="cursor-not-allowed rounded-md border border-gray-200 px-5 py-2 text-sm font-medium text-gray-300 transition-all duration-75">
- Add
+ Add Domain
</div>
</Tooltip>
- ) : (
- <button
- onClick={() => setShowAddEditDomainModal(true)}
- className="rounded-md border border-black bg-black px-5 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black active:scale-95"
- >
- Add
- </button>
);
}
-export function useAddEditDomainModal({ props }: { props?: DomainProps }) {
+export function useAddEditDomainModal({ props }: { props?: DomainProps } = {}) {
const [showAddEditDomainModal, setShowAddEditDomainModal] = useState(false);
const AddEditDomainModalCallback = useCallback(() => {
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index deb6729e14..10bbec33f8 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -22,7 +22,6 @@ import {
import Modal from "@/components/shared/modal";
import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import useProject from "@/lib/swr/use-project";
-import useUsage from "@/lib/swr/use-usage";
import { LinkProps } from "@/lib/types";
import {
getApexDomain,
@@ -89,7 +88,7 @@ function AddEditLinkModal({
}
});
}
- }, [debouncedKey]);
+ }, [debouncedKey, domain]);
const generateRandomKey = useCallback(async () => {
setGeneratingKey(true);
@@ -251,7 +250,7 @@ function AddEditLinkModal({
domain: props.domain,
pretty: true,
})}`
- : "Add a new link"}
+ : "Create a new link"}
</h3>
</div>
@@ -502,7 +501,7 @@ function AddEditLinkModal({
<LoadingDots color="#808080" />
) : (
<p className="text-sm">
- {props ? "Save changes" : "Add link"}
+ {props ? "Save changes" : "Create link"}
</p>
)}
</button>
@@ -526,25 +525,20 @@ function AddEditLinkButton({
const router = useRouter();
const { slug } = router.query as { slug?: string };
- const { isOwner } = useProject();
- const { exceededUsage } = useUsage();
+ const { exceededUsage } = useProject();
return slug && exceededUsage ? ( // only show exceeded usage tooltip if user is on a project page
<Tooltip
content={
<TooltipContent
- title={
- isOwner
- ? "You have exceeded your usage limit. We're still collecting data on your existing links, but you need to upgrade to add more links."
- : "The owner of this project has exceeded their usage limit. We're still collecting data on all existing links, but they need to upgrade their plan to add more links."
- }
- cta={isOwner && "Upgrade"}
- ctaLink={isOwner && "/settings"}
+ title="Your project has exceeded its usage limit. We're still collecting data on your existing links, but you need to upgrade to add more links."
+ cta="Upgrade"
+ ctaLink={`/${slug}/settings/billing`}
/>
}
>
<div className="cursor-not-allowed rounded-md border border-gray-200 px-5 py-2 text-sm font-medium text-gray-300 transition-all duration-75">
- Add
+ Create link
</div>
</Tooltip>
) : (
@@ -552,7 +546,7 @@ function AddEditLinkButton({
onClick={() => setShowAddEditLinkModal(true)}
className="rounded-md border border-black bg-black px-5 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black active:scale-95"
>
- Add
+ Create link
</button>
);
}
@@ -565,7 +559,7 @@ export function useAddEditLinkModal({
props?: LinkProps;
hideXButton?: boolean;
homepageDemo?: boolean;
-}) {
+} = {}) {
const [showAddEditLinkModal, setShowAddEditLinkModal] = useState(false);
const AddEditLinkModalCallback = useCallback(() => {
diff --git a/components/app/modals/add-project-modal.tsx b/components/app/modals/add-project-modal.tsx
index 99c32c7917..a544970d67 100644
--- a/components/app/modals/add-project-modal.tsx
+++ b/components/app/modals/add-project-modal.tsx
@@ -104,7 +104,7 @@ function AddProjectModalHelper({
onSubmit={async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
setSaving(true);
- fetch(`/api/projects`, {
+ fetch("/api/projects", {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -112,7 +112,7 @@ function AddProjectModalHelper({
body: JSON.stringify(data),
}).then(async (res) => {
if (res.status === 200) {
- mutate(`/api/projects`);
+ mutate("/api/projects");
router.push(`/${slug}`);
} else if (res.status === 422) {
const {
@@ -274,7 +274,9 @@ function AddProjectModalHelper({
);
}
-export function useAddProjectModal({ closeWithX }: { closeWithX?: boolean }) {
+export function useAddProjectModal({
+ closeWithX,
+}: { closeWithX?: boolean } = {}) {
const [showAddProjectModal, setShowAddProjectModal] = useState(false);
const AddProjectModal = useCallback(() => {
diff --git a/components/app/modals/delete-link-modal.tsx b/components/app/modals/delete-link-modal.tsx
index c8ac559726..86a5f7e8e8 100644
--- a/components/app/modals/delete-link-modal.tsx
+++ b/components/app/modals/delete-link-modal.tsx
@@ -10,9 +10,9 @@ import { mutate } from "swr";
import BlurImage from "@/components/shared/blur-image";
import LoadingDots from "@/components/shared/icons/loading-dots";
import Modal from "@/components/shared/modal";
-import useProject from "@/lib/swr/use-project";
import { LinkProps } from "@/lib/types";
import { getApexDomain, getQueryString, linkConstructor } from "@/lib/utils";
+import { toast } from "react-hot-toast";
function DeleteLinkModal({
showDeleteLinkModal,
@@ -82,6 +82,9 @@ function DeleteLinkModal({
: `/api/links${getQueryString(router)}`,
);
setShowDeleteLinkModal(false);
+ } else {
+ const { error } = await res.json();
+ toast.error(error);
}
});
}}
diff --git a/components/app/modals/link-qr-modal.tsx b/components/app/modals/link-qr-modal.tsx
index 23eaf3a8f8..495f788b06 100644
--- a/components/app/modals/link-qr-modal.tsx
+++ b/components/app/modals/link-qr-modal.tsx
@@ -14,7 +14,6 @@ import Switch from "@/components/shared/switch";
import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import { QRCodeSVG, getQRAsCanvas, getQRAsSVGDataUri } from "@/lib/qr";
import useProject from "@/lib/swr/use-project";
-import useUsage from "@/lib/swr/use-usage";
import { SimpleLinkProps } from "@/lib/types";
import { getApexDomain, linkConstructor } from "@/lib/utils";
import IconMenu from "@/components/shared/icon-menu";
@@ -33,7 +32,7 @@ function LinkQRModalHelper({
props: SimpleLinkProps;
}) {
const anchorRef = useRef<HTMLAnchorElement>();
- const { project: { logo } = {} } = useProject();
+ const { logo } = useProject();
const { avatarUrl, apexDomain } = useMemo(() => {
try {
const apexDomain = getApexDomain(props.url);
@@ -174,8 +173,7 @@ function LinkQRModalHelper({
}
function AdvancedSettings({ qrData, setFgColor, setShowLogo }) {
- const { data: session } = useSession();
- const { plan } = session ? useUsage() : { plan: "free" };
+ const { plan } = useProject();
const [expanded, setExpanded] = useState(false);
const isApp = useMemo(() => {
@@ -208,7 +206,17 @@ function AdvancedSettings({ qrData, setFgColor, setShowLogo }) {
>
Logo
</label>
- {!plan || plan === "Free" ? (
+ {plan && plan !== "free" ? (
+ <div className="mt-1 flex items-center space-x-2">
+ <Switch
+ fn={setShowLogo}
+ trackDimensions="h-6 w-12"
+ thumbDimensions="w-5 h-5"
+ thumbTranslate="translate-x-6"
+ />
+ <p className="text-sm text-gray-600">Show Dub.sh Logo</p>
+ </div>
+ ) : (
<Tooltip
content={
<TooltipContent
@@ -229,16 +237,6 @@ function AdvancedSettings({ qrData, setFgColor, setShowLogo }) {
<p className="text-sm text-gray-600">Show Dub.sh Logo</p>
</div>
</Tooltip>
- ) : (
- <div className="mt-1 flex items-center space-x-2">
- <Switch
- fn={setShowLogo}
- trackDimensions="h-6 w-12"
- thumbDimensions="w-5 h-5"
- thumbTranslate="translate-x-6"
- />
- <p className="text-sm text-gray-600">Show Dub.sh Logo</p>
- </div>
)}
</div>
<div>
diff --git a/components/app/modals/stats-modal.tsx b/components/app/modals/stats-modal.tsx
index d80a28163f..f2007d7c89 100644
--- a/components/app/modals/stats-modal.tsx
+++ b/components/app/modals/stats-modal.tsx
@@ -49,7 +49,7 @@ function StatsModalHelper({
>
<X className="h-6 w-6" />
</button>
- <Stats atModalTop={atModalTop} domain="dub.sh" />
+ <Stats atModalTop={atModalTop} staticDomain="dub.sh" />
</div>
</Modal>
);
diff --git a/components/app/project-card.tsx b/components/app/project-card.tsx
index dc790ce7a5..2d16d49826 100644
--- a/components/app/project-card.tsx
+++ b/components/app/project-card.tsx
@@ -1,79 +1,93 @@
import Link from "next/link";
import useSWR from "swr";
import BlurImage from "@/components/shared/blur-image";
-import {
- CheckCircleFill,
- Link as LinkIcon,
- XCircleFill,
-} from "@/components/shared/icons";
+import { CheckCircleFill, XCircleFill } from "@/components/shared/icons";
import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
-import { ProjectProps } from "@/lib/types";
+import { ProjectWithDomainProps } from "@/lib/types";
import { fetcher, nFormatter } from "@/lib/utils";
+import { BarChart2, Globe, Link2 } from "lucide-react";
export default function ProjectCard({
name,
slug,
logo,
- domain,
- domainVerified,
-}: ProjectProps) {
+ usage,
+ domains,
+ primaryDomain,
+}: ProjectWithDomainProps) {
const { data: count } = useSWR<number>(
`/api/projects/${slug}/links/count`,
fetcher,
);
return (
- <Link key={slug} href={`/${slug}`}>
- <div className="flex justify-between rounded-lg bg-white p-6 shadow transition-all hover:shadow-md">
- <div className="flex items-center space-x-3">
- <BlurImage
- src={
- logo ||
- `https://www.google.com/s2/favicons?sz=64&domain_url=${domain}`
- }
- alt={slug}
- className="h-9 w-9 flex-shrink-0 overflow-hidden rounded-full"
- width={48}
- height={48}
- />
- <div>
- <h2 className="text-lg font-medium text-gray-700">{name}</h2>
- <div className="flex items-center">
- <p className="text-gray-500">{domain}</p>
- {domainVerified ? (
- <Tooltip content="Verified domain">
- <div className="flex w-8 justify-center">
- <CheckCircleFill className="h-5 w-5 text-blue-500" />
- </div>
- </Tooltip>
- ) : (
- <Tooltip
- content={
- <TooltipContent
- title="This domain is not correctly configured. Please configure your domain to
+ <Link
+ key={slug}
+ href={`/${slug}`}
+ className="flex flex-col space-y-10 rounded-lg bg-white p-6 shadow transition-all hover:shadow-lg"
+ >
+ <div className="flex items-center space-x-3">
+ <BlurImage
+ src={
+ logo ||
+ `https://www.google.com/s2/favicons?sz=64&domain_url=${primaryDomain?.slug}`
+ }
+ alt={slug}
+ className="h-10 w-10 flex-shrink-0 overflow-hidden rounded-full"
+ width={48}
+ height={48}
+ />
+ <div>
+ <h2 className="text-lg font-medium text-gray-700">{name}</h2>
+ <div className="flex items-center">
+ <p className="text-gray-500">{primaryDomain?.slug}</p>
+ {primaryDomain?.verified ? (
+ <Tooltip content="Verified domain">
+ <div className="flex w-8 justify-center">
+ <CheckCircleFill className="h-5 w-5 text-blue-500" />
+ </div>
+ </Tooltip>
+ ) : (
+ <Tooltip
+ content={
+ <TooltipContent
+ title="This domain is not correctly configured. Please configure your domain to
start adding links."
- cta="Configure Domain"
- ctaLink={`/${slug}/settings`}
- />
- }
- >
- <div className="flex w-8 justify-center">
- <XCircleFill className="h-5 w-5 text-gray-300" />
- </div>
- </Tooltip>
- )}
- </div>
+ cta="Configure Domain"
+ ctaLink={`/${slug}/settings`}
+ />
+ }
+ >
+ <div className="flex w-8 justify-center">
+ <XCircleFill className="h-5 w-5 text-gray-300" />
+ </div>
+ </Tooltip>
+ )}
</div>
</div>
- <div className="flex items-center space-x-2">
- <LinkIcon className="h-5 w-5 text-gray-600" />
+ </div>
+ <div className="flex items-center space-x-4">
+ <div className="flex items-center space-x-2 text-gray-500">
+ <Globe className="h-4 w-4" />
+ <h2 className="text-sm">
+ {nFormatter(domains.length)} domain{domains.length > 1 && "s"}
+ </h2>
+ </div>
+ <div className="flex items-center space-x-2 text-gray-500">
+ <Link2 className="h-4 w-4" />
{count || count === 0 ? (
- <h2 className="text-lg font-medium text-gray-700">
- {nFormatter(count)}
+ <h2 className="text-sm">
+ {nFormatter(count)} link{count != 1 && "s"}
</h2>
) : (
- <div className="h-5 w-4 animate-pulse rounded-md bg-gray-200" />
+ <div className="h-4 w-8 animate-pulse rounded-md bg-gray-200" />
)}
</div>
+ <div className="flex items-center space-x-2 text-gray-500">
+ <BarChart2 className="h-4 w-4" />
+ <h2 className="text-sm">
+ {nFormatter(usage)} click{usage != 1 && "s"}
+ </h2>
+ </div>
</div>
</Link>
);
diff --git a/components/app/settings/layout.tsx b/components/app/settings/layout.tsx
index 81c26b8b34..3e9474d094 100644
--- a/components/app/settings/layout.tsx
+++ b/components/app/settings/layout.tsx
@@ -32,6 +32,10 @@ export default function SettingsLayout({ children }: { children: ReactNode }) {
name: "General",
href: `/${slug}/settings`,
},
+ {
+ name: "Billing",
+ href: `/${slug}/settings/billing`,
+ },
{
name: "People",
href: `/${slug}/settings/people`,
diff --git a/components/app/settings/plan-usage.tsx b/components/app/settings/plan-usage.tsx
index feef0d09f1..823db3e614 100644
--- a/components/app/settings/plan-usage.tsx
+++ b/components/app/settings/plan-usage.tsx
@@ -8,17 +8,16 @@ import {
LoadingDots,
QuestionCircle,
} from "@/components/shared/icons";
-import Tooltip, { ProTiers } from "@/components/shared/tooltip";
-import { getPlanFromUsageLimit } from "@/lib/stripe/constants";
-import useUsage from "@/lib/swr/use-usage";
+import Tooltip from "@/components/shared/tooltip";
import { getFirstAndLastDay, nFormatter } from "@/lib/utils";
+import useProject from "@/lib/swr/use-project";
+import useDomains from "@/lib/swr/use-domains";
export default function PlanUsage() {
const router = useRouter();
- const {
- data: { usage, usageLimit, billingCycleStart, projectCount } = {},
- loading,
- } = useUsage();
+
+ const { plan, usage, usageLimit, billingCycleStart } = useProject();
+ const { domains } = useDomains();
const [clicked, setClicked] = useState(false);
@@ -38,8 +37,6 @@ export default function PlanUsage() {
return [];
}, [billingCycleStart]);
- const plan = usageLimit && getPlanFromUsageLimit(usageLimit);
-
const { UpgradePlanModal, setShowUpgradePlanModal } = useUpgradePlanModal();
return (
@@ -52,9 +49,9 @@ export default function PlanUsage() {
{plan ? (
<span
className={`capitalize ${
- plan.startsWith("Enterprise")
+ plan === "enterprise"
? "border-violet-600 bg-violet-600 text-white"
- : plan.startsWith("Pro")
+ : plan === "pro"
? "border-blue-500 bg-blue-500 text-white"
: "border-black bg-black text-white"
} rounded-full border px-2 py-0.5 text-xs font-medium`}
@@ -90,7 +87,7 @@ export default function PlanUsage() {
</div>
</Tooltip>
</div>
- {!loading ? (
+ {usageLimit ? (
<p className="text-sm text-gray-600">
{nFormatter(usage)} / {nFormatter(usageLimit)} clicks (
{((usage / usageLimit) * 100).toFixed(1)}%)
@@ -102,7 +99,7 @@ export default function PlanUsage() {
<motion.div
initial={{ width: 0 }}
animate={{
- width: !loading ? (usage / usageLimit) * 100 + "%" : "0%",
+ width: usageLimit ? (usage / usageLimit) * 100 + "%" : "0%",
}}
transition={{ duration: 0.5, type: "spring" }}
className={`${
@@ -112,48 +109,36 @@ export default function PlanUsage() {
</div>
</div>
<div className="p-10">
- <h3 className="font-medium">Number of Projects</h3>
+ <h3 className="font-medium">Number of Domains</h3>
<div className="mt-4 flex items-center">
- {projectCount ? (
+ {domains ? (
<p className="text-2xl font-semibold text-black">
- {nFormatter(projectCount)}
+ {nFormatter(domains.length)}
</p>
) : (
<div className="h-8 w-8 animate-pulse rounded-md bg-gray-200" />
)}
<Divider className="h-8 w-8 text-gray-500" />
- <Infinity className="h-8 w-8 text-gray-500" />
+ {plan === "free" ? (
+ <p className="text-2xl font-semibold text-black">1</p>
+ ) : (
+ <Infinity className="h-8 w-8 text-gray-500" />
+ )}
</div>
</div>
</div>
<div className="border-b border-gray-200" />
<div className="flex flex-col items-center justify-between space-y-3 px-10 py-4 text-center sm:flex-row sm:space-y-0 sm:text-left">
{plan ? (
- plan === "Pro 1M" ? (
- <p className="text-sm text-gray-500">
- For higher limits, contact us to upgrade to the Enterprise plan.
- </p>
- ) : (
- <p className="text-sm text-gray-500">
- {plan === "Free" ? "For " : "To "}
- <Tooltip content={<ProTiers usageLimit={usageLimit} />}>
- {/* TODO - a simpler version of the homepage slider */}
- <span className="cursor-default font-medium text-gray-700 underline underline-offset-2 hover:text-black">
- {plan === "Free"
- ? "increased limits"
- : "change your monthly click limits"}
- </span>
- </Tooltip>
- {plan === "Free"
- ? ", upgrade to a Pro subscription."
- : ", manage your subscription on Stripe."}
- </p>
- )
+ <p className="text-sm text-gray-500">
+ For higher limits, upgrade to the{" "}
+ {plan === "free" ? "Pro" : "Enterprise"} plan.
+ </p>
) : (
<div className="h-3 w-28 animate-pulse rounded-full bg-gray-200" />
)}
{plan ? (
- plan === "Free" ? (
+ plan === "free" ? (
<button
onClick={() => {
setShowUpgradePlanModal(true);
@@ -163,40 +148,30 @@ export default function PlanUsage() {
Upgrade
</button>
) : (
- <div className="flex space-x-3">
- {plan === "Pro 1M" && (
- <a
- href="mailto:[email protected]?subject=Upgrade%20to%20Enterprise%20Plan"
- className="flex h-9 w-24 items-center justify-center rounded-md border border-violet-600 bg-violet-600 text-sm text-white transition-all duration-150 ease-in-out hover:bg-white hover:text-violet-600 focus:outline-none"
- >
- Contact Us
- </a>
- )}
- <button
- onClick={() => {
- setClicked(true);
- fetch(`/api/stripe/manage-subscription`, {
- method: "POST",
+ <button
+ onClick={() => {
+ setClicked(true);
+ fetch(`/api/stripe/manage-subscription`, {
+ method: "POST",
+ })
+ .then(async (res) => {
+ const url = await res.json();
+ router.push(url);
})
- .then(async (res) => {
- const url = await res.json();
- router.push(url);
- })
- .catch((err) => {
- alert(err);
- setClicked(false);
- });
- }}
- disabled={clicked}
- className={`${
- clicked
- ? "cursor-not-allowed border-gray-200 bg-gray-100"
- : "border-black bg-black text-white hover:bg-white hover:text-black"
- } h-9 w-40 rounded-md border text-sm transition-all duration-150 ease-in-out focus:outline-none`}
- >
- {clicked ? <LoadingDots /> : "Manage Subscription"}
- </button>
- </div>
+ .catch((err) => {
+ alert(err);
+ setClicked(false);
+ });
+ }}
+ disabled={clicked}
+ className={`${
+ clicked
+ ? "cursor-not-allowed border-gray-200 bg-gray-100"
+ : "border-black bg-black text-white hover:bg-white hover:text-black"
+ } h-9 w-40 rounded-md border text-sm transition-all duration-150 ease-in-out focus:outline-none`}
+ >
+ {clicked ? <LoadingDots /> : "Manage Subscription"}
+ </button>
)
) : (
<div className="h-9 w-24 animate-pulse rounded-md bg-gray-200" />
diff --git a/components/app/settings/project-name.tsx b/components/app/settings/project-name.tsx
index 8701fe91ee..582c8bf0b5 100644
--- a/components/app/settings/project-name.tsx
+++ b/components/app/settings/project-name.tsx
@@ -9,7 +9,7 @@ export default function ProjectName() {
const router = useRouter();
const { slug } = router.query as { slug: string };
- const { project: { name } = {} } = useProject();
+ const { name } = useProject();
const [newName, setNewName] = useState(null);
useEffect(() => {
setNewName(name);
@@ -35,7 +35,7 @@ export default function ProjectName() {
}).then(async (res) => {
setSaving(false);
if (res.status === 200) {
- mutate(`/api/projects`);
+ mutate("/api/projects");
mutate(`/api/projects/${slug}`);
toast.success("Successfully updated project name");
}
diff --git a/components/app/settings/project-slug.tsx b/components/app/settings/project-slug.tsx
index f68578edd4..f7edbb90a1 100644
--- a/components/app/settings/project-slug.tsx
+++ b/components/app/settings/project-slug.tsx
@@ -33,7 +33,7 @@ export default function ProjectSlug() {
}).then(async (res) => {
setSaving(false);
if (res.status === 200) {
- mutate(`/api/projects`);
+ mutate("/api/projects");
router.push(`/${newSlug}/settings`);
toast.success("Successfully updated project slug");
} else if (res.status === 422) {
diff --git a/components/home/features.tsx b/components/home/features.tsx
index e70aaabda6..e2a13fe93e 100644
--- a/components/home/features.tsx
+++ b/components/home/features.tsx
@@ -1,12 +1,5 @@
import Link from "next/link";
-import {
- Airplay,
- Chart,
- QR,
- Users,
- Link as LinkIcon,
- Photo,
-} from "@/components/shared/icons";
+import { Airplay, Chart, QR, Users, Photo } from "@/components/shared/icons";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import { useState } from "react";
import Accordion from "@/components/shared/accordion";
@@ -14,6 +7,7 @@ import { AnimatePresence, motion } from "framer-motion";
import { useLinkQRModal } from "../app/modals/link-qr-modal";
import { DEFAULT_LINK_PROPS } from "@/lib/constants";
import { useAddEditLinkModal } from "../app/modals/add-edit-link-modal";
+import { Link2 } from "lucide-react";
const featureList = [
{
@@ -57,7 +51,7 @@ const featureList = [
{
key: "link",
title: "Powerful link builder",
- icon: <LinkIcon className="h-5 w-5 text-gray-600" />,
+ icon: <Link2 className="h-5 w-5 text-gray-600" />,
description:
"Build your links with UTM parameters, password protection, expiration dates, iOS/Android targeting, etc.",
cta: "View demo", //custom cta
diff --git a/components/layout/app/project-select.tsx b/components/layout/app/project-select.tsx
index fec4d07bb0..8fedd4cdc3 100644
--- a/components/layout/app/project-select.tsx
+++ b/components/layout/app/project-select.tsx
@@ -1,18 +1,16 @@
import { useRouter } from "next/router";
import { useMemo, useState } from "react";
import { useSession } from "next-auth/react";
-import useSWR from "swr";
import { useAddProjectModal } from "@/components/app/modals/add-project-modal";
import BlurImage from "@/components/shared/blur-image";
import { ChevronUpDown, PlusCircle, Tick } from "@/components/shared/icons";
import Popover from "@/components/shared/popover";
-import useUsage from "@/lib/swr/use-usage";
-import { ProjectProps } from "@/lib/types";
-import { fetcher } from "@/lib/utils";
+import { ProjectWithDomainProps } from "@/lib/types";
+import useProjects from "@/lib/swr/use-projects";
export default function ProjectSelect() {
- const { data: projects } = useSWR<ProjectProps[]>("/api/projects", fetcher);
- const { AddProjectModal, setShowAddProjectModal } = useAddProjectModal({});
+ const { projects } = useProjects();
+ const { AddProjectModal, setShowAddProjectModal } = useAddProjectModal();
const router = useRouter();
const { slug } = router.query as {
@@ -22,17 +20,27 @@ export default function ProjectSelect() {
const { data: session } = useSession();
const selected = useMemo(() => {
- return (
- projects?.find((project) => project.slug === slug) || {
+ if (slug && projects) {
+ const selectedProject = projects?.find(
+ (project) => project.slug === slug,
+ );
+ return {
+ ...selectedProject,
+ image:
+ selectedProject?.logo ||
+ `https://www.google.com/s2/favicons?sz=64&domain_url=${selectedProject?.primaryDomain?.slug}`,
+ };
+ } else {
+ return {
name: session?.user?.name || session?.user?.email,
slug: "/",
- domain: "dub.sh",
- logo:
+ image:
session?.user?.image ||
`https://avatars.dicebear.com/api/micah/${session?.user?.email}.svg`,
- }
- );
+ };
+ }
}, [slug, projects, session]);
+
const [openPopover, setOpenPopover] = useState(false);
if (!projects || !router.isReady)
@@ -62,10 +70,7 @@ export default function ProjectSelect() {
>
<div className="flex items-center justify-start space-x-3 pr-2">
<BlurImage
- src={
- selected.logo ||
- `https://www.google.com/s2/favicons?sz=64&domain_url=${selected.domain}`
- }
+ src={selected.image}
alt={selected.slug}
className="h-6 w-6 flex-none overflow-hidden rounded-full sm:h-8 sm:w-8"
width={48}
@@ -90,18 +95,16 @@ function ProjectList({
selected: {
name: string;
slug: string;
- domain: string;
- logo?: string;
+ image?: string;
};
- projects: ProjectProps[];
+ projects: ProjectWithDomainProps[];
setShowAddProjectModal?: (show: boolean) => void;
}) {
const router = useRouter();
- const { plan } = useUsage();
return (
<div className="relative mt-1 max-h-60 w-full overflow-auto rounded-md bg-white p-2 text-base sm:w-60 sm:text-sm sm:shadow-lg">
- {projects.map(({ name, slug, domain, logo }) => (
+ {projects.map(({ name, slug, logo, primaryDomain }) => (
<button
key={slug}
className={`relative flex w-full items-center space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200 ${
@@ -112,7 +115,7 @@ function ProjectList({
<BlurImage
src={
logo ||
- `https://www.google.com/s2/favicons?sz=64&domain_url=${domain}`
+ `https://www.google.com/s2/favicons?sz=64&domain_url=${primaryDomain?.slug}`
}
alt={slug}
className="h-7 w-7 overflow-hidden rounded-full"
@@ -133,16 +136,14 @@ function ProjectList({
) : null}
</button>
))}
- {!(plan === "Free" && projects.length >= 5) && (
- <button
- key="add"
- onClick={() => setShowAddProjectModal(true)}
- className="flex w-full cursor-pointer items-center space-x-2 rounded-md p-2 transition-all duration-75 hover:bg-gray-100"
- >
- <PlusCircle className="h-7 w-7 text-gray-600" />
- <span className="block truncate">Add a new project</span>
- </button>
- )}
+ <button
+ key="add"
+ onClick={() => setShowAddProjectModal(true)}
+ className="flex w-full cursor-pointer items-center space-x-2 rounded-md p-2 transition-all duration-75 hover:bg-gray-100"
+ >
+ <PlusCircle className="h-7 w-7 text-gray-600" />
+ <span className="block truncate">Add a new project</span>
+ </button>
</div>
);
}
diff --git a/components/stats/bar-chart.tsx b/components/stats/bar-chart.tsx
index 6217af28f0..dc24c99dec 100644
--- a/components/stats/bar-chart.tsx
+++ b/components/stats/bar-chart.tsx
@@ -41,11 +41,10 @@ const BarChart = ({ screenWidth }: { screenWidth?: number }) => {
interval?: string;
};
- const { endpoint } = useEndpoint();
+ const { endpoint, queryString } = useEndpoint();
const { data } = useSWR<{ start: Date; clicks: number }[]>(
- router.isReady &&
- `${endpoint}/timeseries${interval ? `?interval=${interval}` : ""}`,
+ router.isReady && `${endpoint}/timeseries${queryString}`,
fetcher,
);
diff --git a/components/stats/clicks.tsx b/components/stats/clicks.tsx
index 8ca3c0b6ce..db49bf9030 100644
--- a/components/stats/clicks.tsx
+++ b/components/stats/clicks.tsx
@@ -8,14 +8,10 @@ import useEndpoint from "@/lib/hooks/use-endpoint";
export default function Clicks() {
const router = useRouter();
- const { interval = "24h" } = router.query as {
- interval?: string;
- };
- const { endpoint } = useEndpoint();
+ const { endpoint, queryString } = useEndpoint();
const { data: totalClicks } = useSWR<number>(
- router.isReady &&
- `${endpoint}/clicks${interval ? `?interval=${interval}` : ""}`,
+ router.isReady && `${endpoint}/clicks${queryString}`,
fetcher,
);
diff --git a/components/stats/devices.tsx b/components/stats/devices.tsx
index 63d4be2464..60ce5f886c 100644
--- a/components/stats/devices.tsx
+++ b/components/stats/devices.tsx
@@ -14,23 +14,16 @@ export default function Devices() {
const [tab, setTab] = useState<DeviceTabs>("device");
const router = useRouter();
- const { interval } = router.query as {
- interval?: string;
- };
-
- const { endpoint } = useEndpoint();
+ const { endpoint, queryString } = useEndpoint();
const { data } = useSWR<
({
[key in DeviceTabs]: string;
} & { clicks: number })[]
- >(
- router.isReady && `${endpoint}/${tab}?interval=${interval || "24h"}`,
- fetcher,
- );
+ >(router.isReady && `${endpoint}/${tab}${queryString}`, fetcher);
const { data: totalClicks } = useSWR<number>(
- router.isReady && `${endpoint}/clicks?interval=${interval || "24h"}`,
+ router.isReady && `${endpoint}/clicks${queryString}`,
fetcher,
);
diff --git a/components/stats/index.tsx b/components/stats/index.tsx
index adfe06e4be..ca10852818 100644
--- a/components/stats/index.tsx
+++ b/components/stats/index.tsx
@@ -5,10 +5,16 @@ import Locations from "@/components/stats/locations";
import Referer from "@/components/stats/referer";
import Toggle from "@/components/stats/toggle";
-export default function Stats({ atModalTop }: { atModalTop?: boolean }) {
+export default function Stats({
+ atModalTop,
+ staticDomain,
+}: {
+ atModalTop?: boolean;
+ staticDomain?: string;
+}) {
return (
<div className="bg-gray-50 py-10">
- <Toggle atModalTop={atModalTop} domain={domain} />
+ <Toggle atModalTop={atModalTop} staticDomain={staticDomain} />
<div className="mx-auto grid max-w-4xl gap-5">
<Clicks />
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
diff --git a/components/stats/locations.tsx b/components/stats/locations.tsx
index 7fcefcf12a..b81f0ce6d7 100644
--- a/components/stats/locations.tsx
+++ b/components/stats/locations.tsx
@@ -14,19 +14,15 @@ export default function Locations() {
const [tab, setTab] = useState<LocationTabs>("country");
const router = useRouter();
- const { interval } = router.query as {
- interval?: string;
- };
-
- const { endpoint } = useEndpoint();
+ const { endpoint, queryString } = useEndpoint();
const { data } = useSWR<{ country: string; city: string; clicks: number }[]>(
- router.isReady && `${endpoint}/${tab}?interval=${interval || "24h"}`,
+ router.isReady && `${endpoint}/${tab}${queryString}`,
fetcher,
);
const { data: totalClicks } = useSWR<number>(
- router.isReady && `${endpoint}/clicks?interval=${interval || "24h"}`,
+ router.isReady && `${endpoint}/clicks${queryString}`,
fetcher,
);
diff --git a/components/stats/referer.tsx b/components/stats/referer.tsx
index 7b2c4678b2..c6a4b41fca 100644
--- a/components/stats/referer.tsx
+++ b/components/stats/referer.tsx
@@ -10,19 +10,15 @@ import useEndpoint from "@/lib/hooks/use-endpoint";
export default function Referer() {
const router = useRouter();
- const { interval } = router.query as {
- interval?: string;
- };
-
- const { endpoint } = useEndpoint();
+ const { endpoint, queryString } = useEndpoint();
const { data } = useSWR<{ referer: string; clicks: number }[]>(
- router.isReady && `${endpoint}/referer?interval=${interval || "24h"}`,
+ router.isReady && `${endpoint}/referer${queryString}`,
fetcher,
);
const { data: totalClicks } = useSWR<number>(
- router.isReady && `${endpoint}/clicks?interval=${interval || "24h"}`,
+ router.isReady && `${endpoint}/clicks${queryString}`,
fetcher,
);
diff --git a/components/stats/toggle.tsx b/components/stats/toggle.tsx
index 4040cf2142..c610d12b38 100644
--- a/components/stats/toggle.tsx
+++ b/components/stats/toggle.tsx
@@ -21,10 +21,10 @@ import useEndpoint from "@/lib/hooks/use-endpoint";
export default function Toggle({
atModalTop,
- domain: staticDomain,
+ staticDomain,
}: {
atModalTop?: boolean;
- domain?: string;
+ staticDomain?: string;
}) {
const router = useRouter();
const { key, interval = "24h" } = router.query as {
@@ -32,7 +32,7 @@ export default function Toggle({
interval?: string;
};
- const { pageType, domain } = useEndpoint(staticDomain);
+ const { basePath, domain } = useEndpoint(staticDomain);
const atTop = useScroll(80) || atModalTop;
const [openDatePopover, setOpenDatePopover] = useState(false);
@@ -44,7 +44,7 @@ export default function Toggle({
return (
<div
className={`z-20 mb-5 ${
- pageType === "stats" ? "top-0" : "top-[6.95rem]"
+ basePath.startsWith("/stats") ? "top-0" : "top-[6.95rem]"
} sticky bg-gray-50 py-3 sm:py-5 ${atTop ? "shadow-md" : ""}`}
>
<div className="mx-auto flex max-w-4xl flex-col items-center justify-between space-y-3 px-2.5 sm:flex-row sm:space-y-0 lg:px-0">
@@ -58,7 +58,7 @@ export default function Toggle({
<ExpandingArrow className="h-5 w-5" />
</a>
<div className="flex items-center">
- {pageType !== "stats" && key !== "_root" && (
+ {!basePath.startsWith("/stats") && key !== "_root" && (
<SharePopover domain={domain} />
)}
<Popover
@@ -75,9 +75,7 @@ export default function Toggle({
interval: slug,
},
},
- `/${pageType}/${encodeURI(
- router.query.key as string,
- )}?interval=${slug}`,
+ `${basePath}?interval=${slug}`,
{ shallow: true },
);
}}
@@ -124,16 +122,10 @@ const SharePopover = ({ domain }: { domain: string }) => {
const [openSharePopover, setopenSharePopoverPopover] = useState(false);
- const endpoint = useMemo(() => {
- if (slug) {
- return `/api/projects/${slug}/domains/${domain}/links/${key}/stats`;
- } else {
- return `/api/links/${key}/stats`;
- }
- }, [slug]);
+ const { endpoint, queryString } = useEndpoint(domain);
const { data: { publicStats } = {} } = useSWR<{ publicStats: boolean }>(
- endpoint,
+ endpoint + queryString,
fetcher,
);
@@ -187,7 +179,7 @@ const SharePopover = ({ domain }: { domain: string }) => {
<p className="font-semibold text-gray-800">Share Link</p>
<div className="divide-x-200 mt-2 flex items-center justify-between divide-x overflow-hidden rounded-md border border-gray-200 bg-gray-100">
<div className="overflow-scroll pl-2 scrollbar-hide">
- <p className="text-gray-600">
+ <p className="whitespace-nowrap text-gray-600">
https://{domain}/stats/{key}
</p>
</div>
diff --git a/lib/api/links.ts b/lib/api/links.ts
index 41abc63861..0718fc0d64 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -71,11 +71,15 @@ export async function getLinksForProject({
sort?: "createdAt" | "clicks"; // always descending for both
userId?: string;
}): Promise<LinkProps[]> {
+ console.log({ projectId, domain, status, tag, search, sort, userId });
const filters = getFiltersFromStatus(status);
return await prisma.link.findMany({
where: {
projectId,
- domain,
+ ...(domain && { domain }),
+ ...(search && {
+ OR: [{ key: { contains: search } }, { url: { contains: search } }],
+ }),
...filters,
// ...(tag && { tags: { has: tag } }),
// ...(search && {
diff --git a/lib/auth.ts b/lib/auth.ts
index 9de5713d43..5e5190b438 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -1,6 +1,5 @@
import { NextApiRequest, NextApiResponse } from "next";
import { unstable_getServerSession } from "next-auth/next";
-import { FREE_PLAN_PROJECT_LIMIT } from "@/lib/constants";
import prisma from "@/lib/prisma";
import { ProjectProps, UserProps } from "@/lib/types";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
@@ -33,11 +32,11 @@ const withProjectAuth =
handler: WithProjectNextApiHandler,
{
excludeGet, // if the action doesn't need to be gated for GET requests
- needProSubscription, // if the action needs a pro subscription
+ requiredPlan = ["free", "pro", "enterprise"], // if the action needs a specific plan
needNotExceededUsage, // if the action needs the user to not have exceeded their usage
}: {
excludeGet?: boolean;
- needProSubscription?: boolean;
+ requiredPlan?: Array<"free" | "pro" | "enterprise">;
needNotExceededUsage?: boolean;
} = {},
) =>
@@ -61,8 +60,10 @@ const withProjectAuth =
name: true,
slug: true,
logo: true,
- ownerUsageLimit: true,
- ownerExceededUsage: true,
+ usage: true,
+ usageLimit: true,
+ plan: true,
+ billingCycleStart: true,
users: {
where: {
userId: session.user.id,
@@ -104,15 +105,12 @@ const withProjectAuth =
// if the action doesn't need to be gated for GET requests, return handler now
if (req.method === "GET" && excludeGet) return handler(req, res, project);
- if (needNotExceededUsage || needProSubscription) {
- if (needNotExceededUsage && project.ownerExceededUsage) {
- return res.status(403).end("Unauthorized: Usage limits exceeded.");
- }
+ if (needNotExceededUsage && project.usage > project.usageLimit) {
+ return res.status(403).end("Unauthorized: Usage limits exceeded.");
+ }
- const freePlan = project.ownerUsageLimit === 1000;
- if (needProSubscription && freePlan) {
- return res.status(403).end("Unauthorized: Need pro subscription");
- }
+ if (!requiredPlan.includes(project.plan)) {
+ return res.status(403).end("Unauthorized: Need higher plan.");
}
return handler(req, res, project, session);
@@ -170,17 +168,6 @@ const withUserAuth =
},
})) as UserProps;
- const freePlan = user.usageLimit === 1000;
- if (
- needProSubscription &&
- freePlan &&
- user.projects.length >= FREE_PLAN_PROJECT_LIMIT
- ) {
- return res
- .status(403)
- .end("Unauthorized: Can't add more projects, need pro subscription");
- }
-
return handler(req, res, session, user);
}
diff --git a/lib/constants/index.ts b/lib/constants/index.ts
index 64f07b333e..d53e21e3c2 100644
--- a/lib/constants/index.ts
+++ b/lib/constants/index.ts
@@ -82,7 +82,6 @@ export const REDIRECT_HEADERS = {
},
};
-export const FREE_PLAN_PROJECT_LIMIT = 5;
export const FAVICON_FOLDER = "/_static/favicons";
export { default as COUNTRIES } from "./countries";
export { default as ccTLDs } from "./cctlds";
diff --git a/lib/hooks/use-endpoint.ts b/lib/hooks/use-endpoint.ts
index 3532b56d3c..4c14c4efaa 100644
--- a/lib/hooks/use-endpoint.ts
+++ b/lib/hooks/use-endpoint.ts
@@ -1,29 +1,41 @@
import { useRouter } from "next/router";
import { useMemo } from "react";
-import useProject from "@/lib/swr/use-project";
export default function useEndpoint(staticDomain?: string) {
const router = useRouter();
- const { slug, key } = router.query as {
+ const {
+ slug,
+ domain: domainSlug,
+ key,
+ interval = "24h",
+ } = router.query as {
slug?: string;
+ domain?: string;
key: string;
+ interval?: string;
};
- const { project: { domain: projectDomain } = {} } = useProject();
+ const queryString =
+ interval || domainSlug
+ ? `?${new URLSearchParams({
+ interval,
+ domain: domainSlug,
+ }).toString()}`
+ : "";
- const { pageType, domain, endpoint } = useMemo(() => {
- // Project link page, e.g. app.dub.sh/dub/github
- if (slug && key) {
+ const { basePath, domain, endpoint } = useMemo(() => {
+ // Project link page, e.g. app.dub.sh/dub/dub.sh/github
+ if (slug && domainSlug && key) {
return {
- pageType: slug,
- domain: projectDomain,
+ basePath: `/${slug}/${domainSlug}/${key}`,
+ domain: domainSlug,
endpoint: `/api/projects/${slug}/links/${key}/stats`,
};
// Generic Dub.sh link page, e.g. app.dub.sh/links/steven
} else if (key && router.asPath.startsWith("/links")) {
return {
- pageType: "links",
+ basePath: `/links/${key}`,
domain: "dub.sh",
endpoint: `/api/links/${key}/stats`,
};
@@ -31,15 +43,16 @@ export default function useEndpoint(staticDomain?: string) {
// Public stats page, e.g. dub.sh/stats/github
return {
- pageType: "stats",
+ basePath: `/stats/${key}`,
domain: staticDomain,
endpoint: `/api/edge/links/${key}/stats`,
};
}, [slug, key, router.asPath]);
return {
- pageType,
+ basePath,
domain,
endpoint,
+ queryString,
};
}
diff --git a/lib/swr/use-domains.ts b/lib/swr/use-domains.ts
index 7845fe4f38..85164b0466 100644
--- a/lib/swr/use-domains.ts
+++ b/lib/swr/use-domains.ts
@@ -4,7 +4,10 @@ import useSWR from "swr";
import { DomainProps } from "@/lib/types";
import { fetcher } from "@/lib/utils";
-export default function useDomains(domain?: string) {
+export default function useDomains({
+ domain,
+ includeLinkCount,
+}: { domain?: string; includeLinkCount?: boolean } = {}) {
const router = useRouter();
let { slug } = router.query as {
@@ -16,7 +19,10 @@ export default function useDomains(domain?: string) {
}
const { data: domains, error } = useSWR<DomainProps[]>(
- slug && `/api/projects/${slug}/domains`,
+ slug &&
+ `/api/projects/${slug}/domains${
+ includeLinkCount ? "?includeLinkCount=true" : ""
+ }`,
fetcher,
{
dedupingInterval: 30000,
@@ -30,8 +36,10 @@ export default function useDomains(domain?: string) {
[domains],
),
verified: domain
- ? domains?.find((d) => d.slug === domain)?.verified
- : domains?.find((d) => d.primary)?.verified,
+ ? // If a domain is passed, check if it's verified
+ domains?.find((d) => d.slug === domain)?.verified
+ : // If no domain is passed, check if any of the domains are verified
+ domains?.some((d) => d.verified),
loading: !domains && !error,
error,
};
diff --git a/lib/swr/use-link.ts b/lib/swr/use-link.ts
index a0268f4744..435afee271 100644
--- a/lib/swr/use-link.ts
+++ b/lib/swr/use-link.ts
@@ -1,5 +1,4 @@
import { useRouter } from "next/router";
-import { useMemo } from "react";
import useSWR from "swr";
import { LinkProps } from "@/lib/types";
import { fetcher } from "@/lib/utils";
diff --git a/lib/swr/use-links.ts b/lib/swr/use-links.ts
new file mode 100644
index 0000000000..b81c91a93d
--- /dev/null
+++ b/lib/swr/use-links.ts
@@ -0,0 +1,30 @@
+import { useRouter } from "next/router";
+import useSWR from "swr";
+import { LinkProps } from "@/lib/types";
+import { fetcher, getQueryString } from "@/lib/utils";
+
+export default function useLinks() {
+ const router = useRouter();
+
+ const { slug } = router.query as {
+ slug: string;
+ };
+
+ const { data: links } = useSWR<LinkProps[]>(
+ router.isReady &&
+ (slug
+ ? `/api/projects/${slug}/links${getQueryString(router)}`
+ : `/api/links${getQueryString(router)}`),
+ fetcher,
+ {
+ // disable this because it keeps refreshing the state of the modal when its open
+ revalidateOnFocus: false,
+ dedupingInterval: 30000,
+ },
+ );
+
+ return {
+ links,
+ loading: links ? false : true,
+ };
+}
diff --git a/lib/swr/use-project.ts b/lib/swr/use-project.ts
index 715dc4734d..69bba60aab 100644
--- a/lib/swr/use-project.ts
+++ b/lib/swr/use-project.ts
@@ -1,8 +1,8 @@
import { useRouter } from "next/router";
-import { useMemo } from "react";
import useSWR from "swr";
import { ProjectProps } from "@/lib/types";
import { fetcher } from "@/lib/utils";
+import { useMemo } from "react";
export default function useProject() {
const router = useRouter();
@@ -19,15 +19,15 @@ export default function useProject() {
},
);
- const isOwner = useMemo(() => {
- if (project && Array.isArray(project.users)) {
- return project.users[0].role === "owner";
+ const exceededUsage = useMemo(() => {
+ if (project) {
+ return project.usage > project.usageLimit;
}
}, [project]);
return {
- project,
- isOwner,
+ ...project,
+ exceededUsage,
error,
};
}
diff --git a/lib/swr/use-projects.ts b/lib/swr/use-projects.ts
new file mode 100644
index 0000000000..6f4610883e
--- /dev/null
+++ b/lib/swr/use-projects.ts
@@ -0,0 +1,20 @@
+import useSWR from "swr";
+import { ProjectWithDomainProps } from "@/lib/types";
+import { fetcher } from "@/lib/utils";
+
+export default function useProjects() {
+ const { data: projects } = useSWR<ProjectWithDomainProps[]>(
+ "/api/projects",
+ fetcher,
+ {
+ dedupingInterval: 30000,
+ },
+ );
+
+ return {
+ projects: projects?.map((project) => ({
+ ...project,
+ primaryDomain: project.domains.find((domain) => domain.primary),
+ })),
+ };
+}
diff --git a/lib/swr/use-usage.ts b/lib/swr/use-usage.ts
deleted file mode 100644
index 4e9d9ce5e4..0000000000
--- a/lib/swr/use-usage.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { useRouter } from "next/router";
-import { useMemo } from "react";
-import useSWR from "swr";
-import { getPlanFromUsageLimit } from "@/lib/stripe/constants";
-import { UsageProps } from "@/lib/types";
-import { fetcher } from "@/lib/utils";
-
-export default function useUsage() {
- const router = useRouter();
- const { slug } = router.query;
- const { data, error } = useSWR<UsageProps>(
- slug ? `/api/projects/${slug}/usage` : `/api/usage`,
- fetcher,
- );
-
- const exceededUsage = useMemo(() => {
- if (data) {
- return slug ? data.ownerExceededUsage : data.usage > data.usageLimit;
- }
- }, [data]);
-
- const plan = useMemo(() => {
- if (data) {
- return getPlanFromUsageLimit(
- slug ? data.ownerUsageLimit : data.usageLimit,
- );
- }
- }, [data]);
-
- return {
- data,
- exceededUsage,
- plan,
- loading: !error && !data,
- error,
- };
-}
diff --git a/lib/types.ts b/lib/types.ts
index da26706f75..9baaa64538 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -31,31 +31,42 @@ export interface ProjectProps {
id: string;
name: string;
slug: string;
- domain: string;
- domainVerified: boolean;
logo?: string;
+ usage: number;
+ usageLimit: number;
+ plan: "free" | "pro" | "enterprise";
+ billingCycleStart?: number;
+
+ // TO DELETE
ownerUsageLimit?: number;
ownerExceededUsage?: boolean;
+
users?: {
role: string;
}[];
}
+export interface ProjectWithDomainProps extends ProjectProps {
+ domains: DomainProps[];
+ primaryDomain: DomainProps;
+}
+
export interface UsageProps {
usage: number;
usageLimit: number;
- projectCount?: number;
+ plan: "free" | "pro" | "enterprise";
billingCycleStart?: number;
- ownerUsageLimit?: number;
- ownerExceededUsage?: boolean;
}
export interface UserProps {
id: string;
name: string;
email: string;
+
+ // TO DELETE
stripeId: string;
usageLimit: number;
+
joinedAt?: Date;
projects?: { projectId: string }[];
}
@@ -78,4 +89,7 @@ export interface DomainProps {
primary: boolean;
target?: string;
type: "redirect" | "rewrite";
+ _count?: {
+ links: number;
+ };
}
diff --git a/lib/utils.ts b/lib/utils.ts
index 09aabfbf0f..08b7b37cc4 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -224,14 +224,39 @@ export const getDomainWithoutWWW = (url: string) => {
};
export const getQueryString = (router: NextRouter) => {
- const { slug: omit, ...queryWithoutSlug } = router.query as {
- slug: string;
- [key: string]: string;
- };
- const queryString = new URLSearchParams(queryWithoutSlug).toString();
+ // here, we omit the slug from the query string because
+ // for some reason it breaks the router because of middleware rewrites
+ const { slug, ...queryWithoutSlug } = router.query as Record<string, string>;
+ const queryString = new URLSearchParams({
+ ...queryWithoutSlug,
+ }).toString();
return `${queryString ? "?" : ""}${queryString}`;
};
+export const setQueryString = (
+ router: NextRouter,
+ param: string,
+ value: string,
+) => {
+ if (param !== "page") delete router.query.page;
+ let newQuery;
+ if (value.length > 0) {
+ newQuery = {
+ ...router.query,
+ [param]: value,
+ };
+ } else {
+ delete router.query[param];
+ newQuery = { ...router.query };
+ }
+ // here, we omit the slug from the query string as well
+ const { slug, ...finalQuery } = newQuery;
+ router.replace({
+ pathname: `/${router.query.slug || "links"}`,
+ query: finalQuery,
+ });
+};
+
export const truncate = (str: string, length: number) => {
if (!str || str.length <= length) return str;
return `${str.slice(0, length)}...`;
diff --git a/package.json b/package.json
index b0574565d6..1bf6646ed5 100644
--- a/package.json
+++ b/package.json
@@ -45,6 +45,7 @@
"framer-motion": "^7.6.12",
"html-escaper": "^3.0.3",
"i": "^0.3.7",
+ "lucide-react": "^0.172.0",
"mailing-core": "^0.9.1",
"ms": "^2.1.3",
"next": "^13.2.4",
diff --git a/pages/_root/[domain].tsx b/pages/_root/[domain].tsx
index 0e8770ab56..461b44484a 100644
--- a/pages/_root/[domain].tsx
+++ b/pages/_root/[domain].tsx
@@ -89,17 +89,17 @@ export default function Placeholder({ domain }: { domain: string }) {
}
export const getStaticPaths = async () => {
- const domains = await prisma.project.findMany({
+ const domains = await prisma.domain.findMany({
where: {
- domainVerified: true,
- ownerUsageLimit: 1000,
+ verified: true,
+ target: null,
},
select: {
- domain: true,
+ slug: true,
},
});
return {
- paths: domains.map(({ domain }) => ({
+ paths: domains.map(({ slug: domain }) => ({
params: {
domain,
},
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index e13d1ba165..d5ad9a2062 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -18,13 +18,17 @@ export default withUserAuth(
async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
// GET /api/links – get all dub.sh links created by the user
if (req.method === "GET") {
- const { status, sort } = req.query as {
+ const { status, tag, search, sort } = req.query as {
status?: string;
+ tag?: string;
+ search?: string;
sort?: "createdAt" | "clicks";
};
const response = await getLinksForProject({
projectId: DUB_PROJECT_ID,
status,
+ tag,
+ search,
sort,
userId: session.user.id,
});
diff --git a/pages/api/projects/[slug]/domains/[domain]/root/index.ts b/pages/api/projects/[slug]/domains/[domain]/root/index.ts
index 91cb348fa0..2396fd5235 100644
--- a/pages/api/projects/[slug]/domains/[domain]/root/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/root/index.ts
@@ -30,7 +30,7 @@ export default withProjectAuth(
},
{
excludeGet: true,
+ requiredPlan: ["pro", "enterprise"],
needNotExceededUsage: true,
- needProSubscription: true,
},
);
diff --git a/pages/api/projects/[slug]/domains/[domain]/verify.ts b/pages/api/projects/[slug]/domains/[domain]/verify.ts
index 7ba14fec7e..a50ced9236 100644
--- a/pages/api/projects/[slug]/domains/[domain]/verify.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/verify.ts
@@ -59,24 +59,24 @@ export default withProjectAuth(
let prismaResponse = null;
if (!configJson.misconfigured) {
- prismaResponse = await prisma.project.update({
+ prismaResponse = await prisma.domain.update({
where: {
- slug,
+ slug: domain,
},
data: {
- domainVerified: true,
- domainLastChecked: new Date(),
+ verified: true,
+ lastChecked: new Date(),
},
});
} else {
status = "Invalid Configuration";
- prismaResponse = await prisma.project.update({
+ prismaResponse = await prisma.domain.update({
where: {
- slug,
+ slug: domain,
},
data: {
- domainVerified: false,
- domainLastChecked: new Date(),
+ verified: false,
+ lastChecked: new Date(),
},
});
}
diff --git a/pages/api/projects/[slug]/domains/index.ts b/pages/api/projects/[slug]/domains/index.ts
index fe1613b24d..cb7d41a4e9 100644
--- a/pages/api/projects/[slug]/domains/index.ts
+++ b/pages/api/projects/[slug]/domains/index.ts
@@ -9,6 +9,7 @@ export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
// GET /api/projects/[slug]/domains – get all domains for a project
if (req.method === "GET") {
+ const { includeLinkCount } = req.query;
const domains = await prisma.domain.findMany({
where: {
projectId: project.id,
@@ -19,6 +20,13 @@ export default withProjectAuth(
primary: true,
target: true,
type: true,
+ ...(includeLinkCount && {
+ _count: {
+ select: {
+ links: true,
+ },
+ },
+ }),
},
});
return res.status(200).json(domains);
@@ -77,6 +85,6 @@ export default withProjectAuth(
},
{
excludeGet: true,
- needProSubscription: true,
+ requiredPlan: ["pro", "enterprise"],
},
);
diff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.ts
index 9070402659..d295fc9a24 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -3,7 +3,6 @@ import { withProjectAuth } from "@/lib/auth";
import { removeDomain, deleteDomainLinks } from "@/lib/api/domains";
import prisma from "@/lib/prisma";
import { ProjectProps } from "@/lib/types";
-import cloudinary from "cloudinary";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
diff --git a/pages/api/projects/[slug]/links/[key]/archive.ts b/pages/api/projects/[slug]/links/[key]/archive.ts
index 616bc1cfff..74e7465958 100644
--- a/pages/api/projects/[slug]/links/[key]/archive.ts
+++ b/pages/api/projects/[slug]/links/[key]/archive.ts
@@ -3,18 +3,12 @@ import { archiveLink } from "@/lib/api/links";
import { withProjectAuth } from "@/lib/auth";
export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project) => {
+ async (req: NextApiRequest, res: NextApiResponse) => {
const { domain, key } = req.query as {
domain: string;
key: string;
};
- if (domain !== project.domain) {
- return res
- .status(400)
- .json({ error: "Domain does not match project domain" });
- }
-
if (req.method === "POST") {
const response = await archiveLink(domain, key);
return res.status(200).json(response);
diff --git a/pages/api/projects/[slug]/links/[key]/index.ts b/pages/api/projects/[slug]/links/[key]/index.ts
index c068ea27df..ac045e4f74 100644
--- a/pages/api/projects/[slug]/links/[key]/index.ts
+++ b/pages/api/projects/[slug]/links/[key]/index.ts
@@ -11,18 +11,12 @@ export const config = {
};
export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project) => {
+ async (req: NextApiRequest, res: NextApiResponse) => {
const { domain, key: oldKey } = req.query as {
domain: string;
key: string;
};
- if (domain !== project.domain) {
- return res
- .status(400)
- .json({ error: "Domain does not match project domain" });
- }
-
// PUT /api/projects/[slug]/domains/[domain]/links/[key] - edit a link
if (req.method === "PUT") {
let { key, url } = req.body;
diff --git a/pages/api/projects/[slug]/links/[key]/stats/index.ts b/pages/api/projects/[slug]/links/[key]/stats/index.ts
index 07f6dab951..a182fcc303 100644
--- a/pages/api/projects/[slug]/links/[key]/stats/index.ts
+++ b/pages/api/projects/[slug]/links/[key]/stats/index.ts
@@ -3,18 +3,12 @@ import { withProjectAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project) => {
+ async (req: NextApiRequest, res: NextApiResponse) => {
const { domain, key } = req.query as {
domain: string;
key: string;
};
- if (domain !== project.domain) {
- return res
- .status(400)
- .json({ error: "Domain does not match project domain" });
- }
-
// GET /api/projects/[slug]/domains/[domain]/links/[key]/stats - get a link's stats page privacy
if (req.method === "GET") {
const link = await prisma.link.findUnique({
@@ -48,7 +42,7 @@ export default withProjectAuth(
return res.status(200).json(response);
} else {
- res.setHeader("Allow", ["PUT"]);
+ res.setHeader("Allow", ["GET", "PUT"]);
return res
.status(405)
.json({ error: `Method ${req.method} Not Allowed` });
diff --git a/pages/api/projects/[slug]/links/index.ts b/pages/api/projects/[slug]/links/index.ts
index a5f829cfae..837d25ce97 100644
--- a/pages/api/projects/[slug]/links/index.ts
+++ b/pages/api/projects/[slug]/links/index.ts
@@ -12,7 +12,7 @@ export const config = {
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse, project, session) => {
- // GET /api/projects/[slug]/domains/[domain]/links - Get all links for a project
+ // GET /api/projects/[slug]/links - Get all links for a project
if (req.method === "GET") {
const { domain, status, tag, search, sort, userId } = req.query as {
domain?: string;
@@ -33,24 +33,27 @@ export default withProjectAuth(
});
return res.status(200).json(response);
- // POST /api/projects/[slug]/domains/[domain]/links – create a new link
+ // POST /api/projects/[slug]/links – create a new link
} else if (req.method === "POST") {
const { domain } = req.query as { domain: string };
let { key, url } = req.body;
if (!domain || !key || !url) {
return res.status(400).json({ error: "Missing domain or url or key" });
}
+
+ // Prevent the creation of recursive links
const { hostname, pathname } = new URL(url);
if (hostname === domain && pathname === `/${key}`) {
return res.status(400).json({ error: "Invalid url" });
}
+
const response = await addLink({
...req.body,
projectId: project.id,
userId: session.user.id,
});
if (response === null) {
- return res.status(400).json({ error: "Key already exists" });
+ return res.status(403).json({ error: "Key already exists" });
}
return res.status(200).json(response);
} else {
diff --git a/pages/api/projects/[slug]/usage.ts b/pages/api/projects/[slug]/usage.ts
deleted file mode 100644
index d601809717..0000000000
--- a/pages/api/projects/[slug]/usage.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import { withProjectAuth } from "@/lib/auth";
-import { ProjectProps } from "@/lib/types";
-
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
- const { slug } = req.query;
- if (!slug || typeof slug !== "string") {
- return res
- .status(400)
- .json({ error: "Missing or misconfigured project slug" });
- }
-
- // GET /api/projects/[slug]/usage – get the usage stats specific project (dependent on owner's plan)
- if (req.method === "GET") {
- return res.status(200).json(project);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index 134d4fba8b..d42e9f742b 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -17,6 +17,9 @@ export default withUserAuth(
},
},
},
+ include: {
+ domains: true,
+ },
});
return res.status(200).json(response);
@@ -80,7 +83,6 @@ export default withUserAuth(
name,
slug,
domain,
- ownerUsageLimit,
users: {
create: {
userId: session.user.id,
diff --git a/pages/api/usage/index.ts b/pages/api/usage/index.ts
deleted file mode 100644
index b424b7bff8..0000000000
--- a/pages/api/usage/index.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import { Session, withUserAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-
-export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
- // GET /api/usage – get a user's usage over all the projects they're an owner of
- if (req.method === "GET") {
- const response = await prisma.user.findUnique({
- where: {
- id: session.user.id,
- },
- select: {
- usage: true,
- usageLimit: true,
- billingCycleStart: true,
- projects: {
- where: {
- role: "owner",
- },
- },
- },
- });
- return res.status(200).json({
- ...response,
- projects: undefined,
- projectCount: response?.projects?.length || "0",
- });
- } else {
- res.setHeader("Allow", ["GET"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
diff --git a/pages/app/[slug]/[domain]/[key].tsx b/pages/app/[slug]/[domain]/[key].tsx
index da2c55a827..dd92d1cf3c 100644
--- a/pages/app/[slug]/[domain]/[key].tsx
+++ b/pages/app/[slug]/[domain]/[key].tsx
@@ -6,11 +6,9 @@ import { Lock } from "@/components/shared/icons";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import Stats from "@/components/stats";
import useProject from "@/lib/swr/use-project";
-import useUsage from "@/lib/swr/use-usage";
export default function StatsPage() {
- const { project, isOwner, error } = useProject();
- const { exceededUsage } = useUsage();
+ const { slug, exceededUsage, error } = useProject();
// handle error page
if (error && error.status === 404) {
@@ -28,9 +26,9 @@ export default function StatsPage() {
Stats Locked
</h1>
<p className="z-10 max-w-sm text-center text-sm text-gray-600">
- {isOwner
- ? "You have exceeded your usage limits. We're still collecting data on your link, but you need to upgrade to view them."
- : "The owner of this project has exceeded their usage limits. We're still collecting data on this link, but they need to upgrade to view them."}
+ Your project has exceeded your usage limits. We're still
+ collecting data on your link, but you need to upgrade to view
+ them.
</p>
<BlurImage
src="/_static/illustrations/video-park.svg"
@@ -39,18 +37,16 @@ export default function StatsPage() {
height={400}
className="-my-8"
/>
- {isOwner && (
- <Link
- href="/settings"
- className="z-10 rounded-md border border-black bg-black px-10 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black"
- >
- Upgrade now
- </Link>
- )}
+ <Link
+ href="/settings"
+ className="z-10 rounded-md border border-black bg-black px-10 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black"
+ >
+ Upgrade now
+ </Link>
</div>
</MaxWidthWrapper>
)}
- {project && !exceededUsage && <Stats />}
+ {slug && !exceededUsage && <Stats />}
</AppLayout>
);
}
diff --git a/pages/app/[slug]/domains.tsx b/pages/app/[slug]/domains.tsx
index a03c166059..bec161755b 100644
--- a/pages/app/[slug]/domains.tsx
+++ b/pages/app/[slug]/domains.tsx
@@ -5,11 +5,12 @@ import AppLayout from "components/layout/app";
import useProject from "@/lib/swr/use-project";
import DomainCard from "@/components/app/domains/domain-card";
import useDomains from "@/lib/swr/use-domains";
+import DomainCardPlaceholder from "@/components/app/domains/domain-card-placeholder";
export default function ProjectDomains() {
- const { project, error } = useProject();
+ const { id: projectId, error } = useProject();
- const { AddEditDomainModal, AddEditDomainButton } = useAddEditDomainModal({});
+ const { AddEditDomainModal, AddEditDomainButton } = useAddEditDomainModal();
if (error && error.status === 404) {
return <ErrorPage statusCode={404} />;
@@ -19,7 +20,7 @@ export default function ProjectDomains() {
return (
<AppLayout>
- {project && <AddEditDomainModal />}
+ {projectId && <AddEditDomainModal />}
<div className="flex h-36 items-center border-b border-gray-200 bg-white">
<MaxWidthWrapper>
<div className="flex items-center justify-between">
@@ -28,8 +29,8 @@ export default function ProjectDomains() {
</div>
</MaxWidthWrapper>
</div>
- {domains && (
- <MaxWidthWrapper className="py-10">
+ <MaxWidthWrapper className="py-10">
+ {domains ? (
<ul className="grid grid-cols-1 gap-3">
{domains.map((domain) => (
<li key={domain.slug}>
@@ -37,8 +38,10 @@ export default function ProjectDomains() {
</li>
))}
</ul>
- </MaxWidthWrapper>
- )}
+ ) : (
+ <DomainCardPlaceholder />
+ )}
+ </MaxWidthWrapper>
</AppLayout>
);
}
diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsx
index a0e7efe238..7557173211 100644
--- a/pages/app/[slug]/index.tsx
+++ b/pages/app/[slug]/index.tsx
@@ -10,9 +10,9 @@ import { useCompleteSetupModal } from "@/components/app/modals/complete-setup-mo
import useDomains from "@/lib/swr/use-domains";
export default function ProjectLinks() {
- const { project, error } = useProject();
+ const { slug, error } = useProject();
- const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal({});
+ const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal();
const { AcceptInviteModal, setShowAcceptInviteModal } =
useAcceptInviteModal();
const { CompleteSetupModal, setShowCompleteSetupModal } =
@@ -35,7 +35,7 @@ export default function ProjectLinks() {
return (
<AppLayout>
- {project && <AddEditLinkModal />}
+ {slug && <AddEditLinkModal />}
{!verified && <CompleteSetupModal />}
{error && (error.status === 409 || error.status === 410) && (
<AcceptInviteModal />
diff --git a/pages/app/[slug]/settings/billing.tsx b/pages/app/[slug]/settings/billing.tsx
new file mode 100644
index 0000000000..840326caf2
--- /dev/null
+++ b/pages/app/[slug]/settings/billing.tsx
@@ -0,0 +1,10 @@
+import SettingsLayout from "@/components/app/settings/layout";
+import PlanUsage from "@/components/app/settings/plan-usage";
+
+export default function ProjectBilling() {
+ return (
+ <SettingsLayout>
+ <PlanUsage />
+ </SettingsLayout>
+ );
+}
diff --git a/pages/app/index.tsx b/pages/app/index.tsx
index 6faee66e37..6b641ee48f 100644
--- a/pages/app/index.tsx
+++ b/pages/app/index.tsx
@@ -1,20 +1,14 @@
-import useSWR from "swr";
import { useAddProjectModal } from "@/components/app/modals/add-project-modal";
import NoProjectsPlaceholder from "@/components/app/no-projects-placeholder";
import ProjectCard from "@/components/app/project-card";
import ProjectCardPlaceholder from "@/components/app/project-card-placeholder";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import AppLayout from "components/layout/app";
-import { FREE_PLAN_PROJECT_LIMIT } from "@/lib/constants";
-import useUsage from "@/lib/swr/use-usage";
-import { ProjectProps } from "@/lib/types";
-import { fetcher } from "@/lib/utils";
+import useProjects from "@/lib/swr/use-projects";
export default function App() {
- const { data } = useSWR<ProjectProps[]>(`/api/projects`, fetcher);
- const { setShowAddProjectModal, AddProjectModal } = useAddProjectModal({});
- const { plan } = useUsage();
+ const { projects } = useProjects();
+ const { setShowAddProjectModal, AddProjectModal } = useAddProjectModal();
return (
<AppLayout>
@@ -23,40 +17,24 @@ export default function App() {
<MaxWidthWrapper>
<div className="flex items-center justify-between">
<h1 className="text-2xl text-gray-600">My Projects</h1>
- {plan === "Free" && data?.length >= FREE_PLAN_PROJECT_LIMIT ? (
- <Tooltip
- content={
- <TooltipContent
- title={`You can only have ${FREE_PLAN_PROJECT_LIMIT} projects on the Free plan. Upgrade to the Pro plan create more.`}
- cta="Upgrade"
- ctaLink={`/settings`}
- />
- }
- >
- <div className="cursor-not-allowed rounded-md border border-gray-200 px-5 py-2 text-sm font-medium text-gray-300 transition-all duration-75">
- Add
- </div>
- </Tooltip>
- ) : (
- <button
- onClick={() => setShowAddProjectModal(true)}
- className="rounded-md border border-black bg-black px-5 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black active:scale-95"
- >
- Add
- </button>
- )}
+ <button
+ onClick={() => setShowAddProjectModal(true)}
+ className="rounded-md border border-black bg-black px-5 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black active:scale-95"
+ >
+ Create project
+ </button>
</div>
</MaxWidthWrapper>
</div>
<MaxWidthWrapper>
<div
className={`my-10 grid grid-cols-1 ${
- data?.length === 0 ? "" : "lg:grid-cols-3"
+ projects?.length === 0 ? "" : "lg:grid-cols-3"
} gap-5`}
>
- {data ? (
- data.length > 0 ? (
- data.map((d) => <ProjectCard key={d.slug} {...d} />)
+ {projects ? (
+ projects.length > 0 ? (
+ projects.map((d) => <ProjectCard key={d.slug} {...d} />)
) : (
<NoProjectsPlaceholder
setShowAddProjectModal={setShowAddProjectModal}
diff --git a/pages/app/links/index.tsx b/pages/app/links/index.tsx
index e03f80cc37..128eef52de 100644
--- a/pages/app/links/index.tsx
+++ b/pages/app/links/index.tsx
@@ -4,7 +4,7 @@ import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import AppLayout from "components/layout/app";
export default function Links() {
- const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal({});
+ const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal();
return (
<AppLayout>
diff --git a/pages/app/settings.tsx b/pages/app/settings.tsx
index 68ba794ba3..2a09160840 100644
--- a/pages/app/settings.tsx
+++ b/pages/app/settings.tsx
@@ -1,4 +1,3 @@
-import PlanUsage from "@/components/app/settings/plan-usage";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import AppLayout from "components/layout/app";
@@ -12,11 +11,6 @@ export default function Settings() {
</div>
</MaxWidthWrapper>
</div>
- <MaxWidthWrapper>
- <div className="grid gap-5 py-10">
- <PlanUsage />
- </div>
- </MaxWidthWrapper>
</AppLayout>
);
}
diff --git a/pages/stats/[key].tsx b/pages/stats/[key].tsx
index a3444f87af..e5c78c9d3d 100644
--- a/pages/stats/[key].tsx
+++ b/pages/stats/[key].tsx
@@ -26,7 +26,7 @@ export default function StatsPage({
}}
>
<div className="bg-gray-50">
- <Stats domain={domain} />
+ <Stats staticDomain={domain} />
</div>
</HomeLayout>
);
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index dcab8162db..c69a0ce20b 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -77,39 +77,32 @@ model Project {
name String
slug String @unique
logo String?
+
+ // TO DELETE
domain String @unique
domainVerified Boolean @default(false)
domainLastChecked DateTime @default(now())
+
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
users ProjectUsers[]
invites ProjectInvite[]
usage Int @default(0)
+ usageLimit Int @default(1000)
+ plan String @default("free")
+ stripeId String? @unique // Stripe subscription ID
+ billingCycleStart Int? // day of the month when the billing cycle starts
+
+ // TO DELETE
ownerUsageLimit Int @default(1000)
ownerExceededUsage Boolean @default(false)
+
sentEmails SentEmail[]
domains Domain[]
links Link[]
tags Tag[]
}
-model Domain {
- id String @id @default(cuid())
- slug String @unique
- verified Boolean @default(false)
- target String?
- type String @default("redirect")
- project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
- projectId String?
- primary Boolean @default(false)
- links Link[]
- lastChecked DateTime @default(now())
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
-
- @@index(projectId)
-}
-
model ProjectInvite {
email String
expires DateTime
@@ -155,6 +148,24 @@ model SentEmail {
@@index([projectId])
}
+model Domain {
+ id String @id @default(cuid())
+ slug String @unique
+ verified Boolean @default(false)
+ target String?
+ type String @default("redirect")
+ description String?
+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ projectId String?
+ primary Boolean @default(false)
+ links Link[]
+ lastChecked DateTime @default(now())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index(projectId)
+}
+
model Link {
id String @id @default(cuid())
domain String // domain of the link (e.g. dub.sh) – also stored on Redis
diff --git a/yarn.lock b/yarn.lock
index 417ff9a4f4..4117f49129 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4186,6 +4186,11 @@ lru-cache@^7.4.4, lru-cache@^7.5.1, lru-cache@^7.7.1:
resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-7.14.1.tgz#8da8d2f5f59827edb388e63e459ac23d6d408fea"
integrity sha512-ysxwsnTKdAx96aTRdhDOCQfDgbHnt8SK0KY8SEjO0wHinhWOFTESbjVCMPbU1uGXg/ch4lifqx0wfjOawU2+WA==
+lucide-react@^0.172.0:
+ version "0.172.0"
+ resolved "https://registry.yarnpkg.com/lucide-react/-/lucide-react-0.172.0.tgz#25c98e3501cf8d6ea633ba8d6ab560526524a525"
+ integrity sha512-Rpc0RSYGEFFrcT2toNjSzYKZ40rfc0D7vYp6C27e86Qyh5TwtPs5LS14hnjweH1REk45AFNeVnU+z+rXvb93ug==
+
mailing-core@^0.9.1:
version "0.9.1"
resolved "https://registry.yarnpkg.com/mailing-core/-/mailing-core-0.9.1.tgz#522e7ee2ebab1b23d5b0f00a7e5324c755fc2eb8"