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 10 AI credits for free plan

Steven Tey23fc7b89f882
diff --git a/apps/web/app/api/ai/link/route.ts b/apps/web/app/api/ai/link/route.ts
index 08181401f9..0da764f001 100644
--- a/apps/web/app/api/ai/link/route.ts
+++ b/apps/web/app/api/ai/link/route.ts
@@ -1,8 +1,12 @@
-import { getWorkspaceViaEdge } from "@/lib/planetscale";
+import {
+ getWorkspaceViaEdge,
+ incrementWorkspaceAIUsage,
+} from "@/lib/planetscale";
import { getSearchParams } from "@dub/utils";
import { OpenAIStream, StreamingTextResponse } from "ai";
import { NextRequest } from "next/server";
import OpenAI from "openai";
+import { internal_runWithWaitUntil as waitUntil } from "next/dist/server/web/internal-edge-wait-until";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
@@ -16,9 +20,15 @@ export async function POST(req: NextRequest) {
const { workspaceId } = searchParams;
const workspace = await getWorkspaceViaEdge(workspaceId);
- // this endpoint is only available for paid plans
- if (!workspace || workspace.plan === "free") {
- return new Response("Requires higher plan", { status: 403 });
+ if (!workspace) {
+ return new Response("Workspace not found", { status: 404 });
+ }
+
+ if (workspace.aiUsage > workspace.aiLimit) {
+ return new Response(
+ "Exceeded AI usage limit. Upgrade to a higher plan to get more AI credits.",
+ { status: 429 },
+ );
}
try {
@@ -47,6 +57,8 @@ export async function POST(req: NextRequest) {
const stream = OpenAIStream(response);
+ waitUntil(async () => await incrementWorkspaceAIUsage(workspaceId));
+
return new StreamingTextResponse(stream);
} catch (error) {
return new Response(error.message, { status: 500 });
diff --git a/apps/web/app/api/ai/metatags/route.ts b/apps/web/app/api/ai/metatags/route.ts
index 0cfa7f491b..c2d6ad570b 100644
--- a/apps/web/app/api/ai/metatags/route.ts
+++ b/apps/web/app/api/ai/metatags/route.ts
@@ -1,8 +1,12 @@
-import { getWorkspaceViaEdge } from "@/lib/planetscale";
+import {
+ getWorkspaceViaEdge,
+ incrementWorkspaceAIUsage,
+} from "@/lib/planetscale";
import { getSearchParams } from "@dub/utils";
import { OpenAIStream, StreamingTextResponse } from "ai";
import { NextRequest } from "next/server";
import OpenAI from "openai";
+import { internal_runWithWaitUntil as waitUntil } from "next/dist/server/web/internal-edge-wait-until";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
@@ -16,9 +20,15 @@ export async function POST(req: NextRequest) {
const { workspaceId } = searchParams;
const workspace = await getWorkspaceViaEdge(workspaceId);
- // this endpoint is only available for paid plans
- if (!workspace || workspace.plan === "free") {
- return new Response("Requires higher plan", { status: 403 });
+ if (!workspace) {
+ return new Response("Workspace not found", { status: 404 });
+ }
+
+ if (workspace.aiUsage > workspace.aiLimit) {
+ return new Response(
+ "Exceeded AI usage limit. Upgrade to a higher plan to get more AI credits.",
+ { status: 429 },
+ );
}
try {
@@ -47,6 +57,8 @@ export async function POST(req: NextRequest) {
const stream = OpenAIStream(response);
+ waitUntil(async () => await incrementWorkspaceAIUsage(workspaceId));
+
return new StreamingTextResponse(stream);
} catch (error) {
return new Response(error.message, { status: 500 });
diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.ts
index ee911b2b63..b71c42f291 100644
--- a/apps/web/lib/planetscale.ts
+++ b/apps/web/lib/planetscale.ts
@@ -24,6 +24,15 @@ export const getWorkspaceViaEdge = async (workspaceId: string) => {
: null;
};
+export const incrementWorkspaceAIUsage = async (workspaceId: string) => {
+ if (!DATABASE_URL) return null;
+
+ return await conn.execute(
+ "UPDATE Project p SET p.aiUsage = p.aiUsage + 1 WHERE id = ?",
+ [workspaceId.replace("ws_", "")],
+ );
+};
+
export const getDomainViaEdge = async (domain: string) => {
if (!DATABASE_URL) return null;
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index c365455eff..2c53b6bbf0 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -74,6 +74,8 @@ export interface WorkspaceProps {
logo: string | null;
usage: number;
usageLimit: number;
+ aiUsage: number;
+ aiLimit: number;
linksUsage: number;
linksLimit: number;
domainsLimit: number;
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 9399205326..56ee942ec7 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -93,6 +93,8 @@ model Project {
billingCycleStart Int // day of the month when the billing cycle starts
usage Int @default(0)
usageLimit Int @default(1000)
+ aiUsage Int @default(0)
+ aiLimit Int @default(10)
linksUsage Int @default(0)
linksLimit Int @default(25)
domainsLimit Int @default(3)
diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsx
index 961b0396eb..acf14532ef 100644
--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx
@@ -58,7 +58,7 @@ import PasswordSection from "./password-section";
import Preview from "./preview";
import TagsSection from "./tags-section";
import UTMSection from "./utm-section";
-import { useChat, useCompletion } from "ai/react";
+import { useCompletion } from "ai/react";
function AddEditLinkModal({
showAddEditLinkModal,
@@ -148,6 +148,9 @@ function AddEditLinkModal({
complete,
} = useCompletion({
api: `/api/ai/link?workspaceId=${workspaceId}`,
+ onError: (error) => {
+ toast.error(error.message);
+ },
onFinish: (_, completion) => {
setGeneratedKeys((prev) => [...prev, completion]);
},
@@ -510,39 +513,16 @@ function AddEditLinkModal({
)}
<Tooltip
content={
- !plan || plan === "free" ? (
- <TooltipContent
- title={`AI Short Link generation is only available on ${process.env.NEXT_PUBLIC_APP_NAME}'s Pro plan. Upgrade to Pro to use this feature.`}
- cta="Upgrade to Pro"
- {...(plan === "free"
- ? {
- onClick: () =>
- queryParams({
- set: {
- upgrade: "pro",
- },
- }),
- }
- : {
- href: `${HOME_DOMAIN}/pricing`,
- })}
- />
- ) : !url ? (
- "Please enter a destination URL to generate AI Short Link."
- ) : (
- "Create Short Link with AI"
- )
+ !url
+ ? "Please enter a destination URL to generate AI Short Link."
+ : "Create Short Link with AI"
}
>
<button
className="ml-2 flex h-6 w-6 items-center justify-center rounded-md text-gray-500 transition-colors duration-75 hover:bg-gray-100 active:bg-gray-200 disabled:cursor-not-allowed"
onClick={generateAIKey}
disabled={
- generatingAIKey ||
- generatingRandomKey ||
- !plan ||
- plan === "free" ||
- !url
+ generatingAIKey || generatingRandomKey || !url
}
type="button"
>
diff --git a/apps/web/ui/modals/add-edit-link-modal/og-section.tsx b/apps/web/ui/modals/add-edit-link-modal/og-section.tsx
index b21dd03bf4..88c6243ee1 100644
--- a/apps/web/ui/modals/add-edit-link-modal/og-section.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/og-section.tsx
@@ -17,16 +17,11 @@ import { TooltipContent } from "@dub/ui/src/tooltip";
import { FADE_IN_ANIMATION_SETTINGS, HOME_DOMAIN } from "@dub/utils";
import { motion } from "framer-motion";
import { Link2 } from "lucide-react";
-import {
- Dispatch,
- SetStateAction,
- useCallback,
- useEffect,
- useState,
-} from "react";
+import { Dispatch, SetStateAction, useEffect, useState } from "react";
import TextareaAutosize from "react-textarea-autosize";
import UnsplashSearch from "./unsplash-search";
import { useCompletion } from "ai/react";
+import { toast } from "sonner";
export default function OGSection({
props,
@@ -51,6 +46,9 @@ export default function OGSection({
} = useCompletion({
api: `/api/ai/metatags?workspaceId=${workspaceId}`,
id: "metatags-title-ai",
+ onError: (error) => {
+ toast.error(error.message);
+ },
});
const generateTitle = async () => {
@@ -72,6 +70,9 @@ export default function OGSection({
} = useCompletion({
api: `/api/ai/metatags?workspaceId=${workspaceId}`,
id: "metatags-description-ai",
+ onError: (error) => {
+ toast.error(error.message);
+ },
});
const generateDescription = async () => {