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.

move to server actions

Kiran Kaac135120f9d
diff --git a/apps/web/app/api/programs/[programId]/rewards/route.ts b/apps/web/app/api/programs/[programId]/rewards/route.ts
index c946744955..88dc48d48d 100644
--- a/apps/web/app/api/programs/[programId]/rewards/route.ts
+++ b/apps/web/app/api/programs/[programId]/rewards/route.ts
@@ -1,8 +1,6 @@
-import { DubApiError } from "@/lib/api/errors";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
-import { createId, parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
-import { createRewardSchema, rewardSchema } from "@/lib/zod/schemas/rewards";
+import { rewardSchema } from "@/lib/zod/schemas/rewards";
import { prisma } from "@dub/prisma";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -22,101 +20,5 @@ export const GET = withWorkspace(async ({ workspace, params }) => {
},
});
- return NextResponse.json([]);
-});
-
-// POST /api/programs/[programId]/rewards - create a new reward
-export const POST = withWorkspace(async ({ workspace, params, req }) => {
- const { programId } = params;
-
- const program = await getProgramOrThrow({
- workspaceId: workspace.id,
- programId,
- });
-
- const { partnerIds, isDefault, ...data } = createRewardSchema.parse(
- await parseRequestBody(req),
- );
-
- let programEnrollments: { id: string }[] = [];
-
- if (partnerIds) {
- programEnrollments = await prisma.programEnrollment.findMany({
- where: {
- programId,
- partnerId: {
- in: partnerIds,
- },
- },
- select: {
- id: true,
- },
- });
-
- if (programEnrollments.length !== partnerIds.length) {
- throw new DubApiError({
- code: "bad_request",
- message: "Invalid partner IDs provided.",
- });
- }
- }
-
- if (isDefault) {
- if (program.defaultRewardId) {
- throw new DubApiError({
- code: "bad_request",
- message: `A program can only have one default reward and you've already set one with id ${program.defaultRewardId}.`,
- });
- }
-
- if (data.event !== "sale") {
- throw new DubApiError({
- code: "bad_request",
- message: "Default reward must be of type `sale`.",
- });
- }
-
- if (partnerIds && partnerIds.length > 0) {
- throw new DubApiError({
- code: "bad_request",
- message: "Default reward should not be partner specific.",
- });
- }
- }
-
- // TODO:
- // Partners can't be more than one reward of the same type.
-
- const reward = await prisma.reward.create({
- data: {
- ...data,
- id: createId({ prefix: "rew_" }),
- programId,
- ...(programEnrollments && {
- partners: {
- createMany: {
- data: programEnrollments.map(({ id }) => ({
- programEnrollmentId: id,
- })),
- },
- },
- }),
- },
- });
-
- if (isDefault) {
- await prisma.program.update({
- where: {
- id: programId,
- },
- data: {
- defaultRewardId: reward.id,
- },
- });
- }
-
- // TODO:
- // Send an email to the partners about the reward being created.
-
- return NextResponse.json(rewardSchema.parse(reward));
+ return NextResponse.json(z.array(rewardSchema).parse(rewards));
});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/rewards/reward-settings.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/rewards/reward-settings.tsx
index 5f0b21bb42..e333b857a3 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/rewards/reward-settings.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/settings/rewards/reward-settings.tsx
@@ -2,9 +2,11 @@
import useProgram from "@/lib/swr/use-program";
import useRewards from "@/lib/swr/use-rewards";
-import { Reward as RewardType } from "@dub/prisma/client";
+import { useRewardSheet } from "@/ui/partners/add-edit-reward-sheet";
+import { EventType, Reward as RewardType } from "@dub/prisma/client";
import { Badge, Button, IconMenu, MoneyBill, Popover } from "@dub/ui";
-import { BoltFill, CurrencyDollar, Gear3, Users2 } from "@dub/ui/icons";
+import { BoltFill, CurrencyDollar, Users2 } from "@dub/ui/icons";
+import { Gift } from "lucide-react";
import { useState } from "react";
export function RewardSettings() {
@@ -16,35 +18,6 @@ export function RewardSettings() {
);
}
-const EmptyState = ({ icon: Icon, title, description }: { icon: any; title: string; description: string }) => {
- return (
- <div className="flex h-[200px] flex-col items-center justify-center gap-4 rounded-lg bg-neutral-50 p-4">
- <div className="flex size-12 items-center justify-center rounded-full border border-neutral-200 bg-white">
- <Icon className="size-5 text-neutral-600" />
- </div>
- <div className="flex flex-col items-center space-y-2">
- <h3 className="text-sm font-medium text-neutral-600">{title}</h3>
- <p className="text-center text-sm text-neutral-500">{description}</p>
- </div>
- </div>
- );
-};
-
-const RewardSkeleton = () => {
- return (
- <div className="flex animate-pulse items-center gap-4 rounded-lg border border-neutral-200 p-4">
- <div className="flex size-10 items-center justify-center rounded-full border border-neutral-200 bg-neutral-50" />
- <div className="flex flex-1 items-center justify-between">
- <div className="space-y-3">
- <div className="h-4 w-64 rounded bg-neutral-100" />
- <div className="h-4 w-32 rounded bg-neutral-100" />
- </div>
- <div className="h-6 w-24 rounded-full bg-neutral-100" />
- </div>
- </div>
- );
-};
-
const SaleReward = () => {
const { program } = useProgram();
const { rewards, loading } = useRewards();
@@ -64,21 +37,14 @@ const SaleReward = () => {
The default rewarded offered to all partners
</p>
</div>
- {!program?.defaultRewardId && !loading && (
- <Button text="Create default reward" variant="primary" />
- )}
</div>
{loading ? (
<RewardSkeleton />
- ) : program?.defaultRewardId ? (
- defaultReward ? (
- <Reward reward={defaultReward} />
- ) : (
- <RewardSkeleton />
- )
+ ) : defaultReward ? (
+ <Reward reward={defaultReward} />
) : (
<EmptyState
- icon={Gear3}
+ event="sale"
title="No default reward created"
description="Create a default reward that will be offered to all partners"
/>
@@ -122,9 +88,8 @@ const AdditionalRewards = () => {
</div>
) : (
<EmptyState
- icon={MoneyBill}
- title="No additional rewards"
- description="Create additional rewards for specific partners or reward groups"
+ title="Additional Rewards"
+ description="No additional rewards have been added yet"
/>
)}
</div>
@@ -164,67 +129,133 @@ const Reward = ({ reward }: { reward: RewardType }) => {
const CreateRewardButton = () => {
const [openPopover, setOpenPopover] = useState(false);
+ const [selectedEvent, setSelectedEvent] = useState<EventType | null>(null);
+ const { rewardSheet, setIsOpen } = useRewardSheet({
+ event: selectedEvent || "sale", // default to sale, but it won't show unless setIsOpen is true
+ });
const rewardTypes = [
{
key: "click",
text: "Click reward",
icon: <BoltFill className="size-4 text-neutral-600" />,
+ event: "click" as const,
},
{
key: "lead",
text: "Lead reward",
icon: <Users2 className="size-4 text-neutral-600" />,
+ event: "lead" as const,
},
{
key: "sale",
text: "Sale reward",
icon: <CurrencyDollar className="size-4 text-neutral-600" />,
+ event: "sale" as const,
},
];
return (
- <Popover
- content={
- <div className="w-full p-2 md:w-48">
- <div className="grid gap-px">
- {rewardTypes.map((type) => (
- <button
- key={type.key}
- className="w-full rounded-md p-2 text-left text-sm hover:bg-neutral-100 active:bg-neutral-200"
- onClick={() => {
- setOpenPopover(false);
- // TODO: Handle reward creation
- }}
- >
- <IconMenu text={type.text} icon={type.icon} />
- </button>
- ))}
+ <>
+ <Popover
+ content={
+ <div className="w-full p-2 md:w-48">
+ <div className="grid gap-px">
+ {rewardTypes.map((type) => (
+ <button
+ key={type.key}
+ className="w-full rounded-md p-2 text-left text-sm hover:bg-neutral-100 active:bg-neutral-200"
+ onClick={() => {
+ setSelectedEvent(type.event);
+ setIsOpen(true);
+ setOpenPopover(false);
+ }}
+ >
+ <IconMenu text={type.text} icon={type.icon} />
+ </button>
+ ))}
+ </div>
</div>
- </div>
- }
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- align="end"
- >
- <button
- onClick={() => setOpenPopover(!openPopover)}
- className="group inline-flex items-center justify-center gap-1 rounded-md bg-black px-4 py-1.5 text-sm font-medium text-white transition-all hover:bg-gray-700 active:bg-gray-800"
+ }
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ align="end"
>
- <span>Create reward</span>
- <svg
- className="h-4 w-4 transition-all group-hover:rotate-180"
- xmlns="http://www.w3.org/2000/svg"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
+ <button
+ onClick={() => setOpenPopover(!openPopover)}
+ className="group inline-flex items-center justify-center gap-1 rounded-md bg-black px-4 py-1.5 text-sm font-medium text-white transition-all hover:bg-gray-700 active:bg-gray-800"
>
- <polyline points="6 9 12 15 18 9"></polyline>
- </svg>
- </button>
- </Popover>
+ <span>Create reward</span>
+ <svg
+ className="h-4 w-4 transition-all group-hover:rotate-180"
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <polyline points="6 9 12 15 18 9"></polyline>
+ </svg>
+ </button>
+ </Popover>
+ {rewardSheet}
+ </>
+ );
+};
+
+const RewardSkeleton = () => {
+ return (
+ <div className="flex animate-pulse items-center gap-4 rounded-lg border border-neutral-200 p-4">
+ <div className="flex size-10 items-center justify-center rounded-full border border-neutral-200 bg-neutral-50" />
+ <div className="flex flex-1 items-center justify-between">
+ <div className="space-y-3">
+ <div className="h-4 w-64 rounded bg-neutral-100" />
+ <div className="h-4 w-32 rounded bg-neutral-100" />
+ </div>
+ <div className="h-6 w-24 rounded-full bg-neutral-100" />
+ </div>
+ </div>
+ );
+};
+
+const EmptyState = ({
+ title,
+ description,
+ event,
+}: {
+ title: string;
+ description: string;
+ event?: EventType;
+}) => {
+ if (event === "sale") {
+ return (
+ <div className="flex items-center justify-between gap-4 rounded-lg bg-neutral-50 p-4">
+ <div className="flex items-center gap-4">
+ <div className="flex size-10 items-center justify-center rounded-full border border-neutral-300">
+ <MoneyBill className="size-5 text-neutral-600" />
+ </div>
+ <p className="text-sm text-neutral-600">No default reward created</p>
+ </div>
+ <Button
+ text="Create default reward"
+ variant="primary"
+ className="h-[32px] w-fit"
+ />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col items-center justify-center gap-4 rounded-lg bg-neutral-50 py-12">
+ <div className="flex items-center justify-center">
+ <Gift className="size-6 text-neutral-800" />
+ </div>
+ <div className="flex flex-col items-center gap-1 px-4 text-center">
+ <p className="text-base font-medium text-neutral-900">{title}</p>
+ <p className="text-sm text-neutral-600">{description}</p>
+ </div>
+ </div>
);
};
diff --git a/apps/web/lib/actions/partners/create-reward.ts b/apps/web/lib/actions/partners/create-reward.ts
new file mode 100644
index 0000000000..cc9eb2bc47
--- /dev/null
+++ b/apps/web/lib/actions/partners/create-reward.ts
@@ -0,0 +1,110 @@
+"use server";
+
+import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
+import { createId } from "@/lib/api/utils";
+import { createRewardSchema } from "@/lib/zod/schemas/rewards";
+import { prisma } from "@dub/prisma";
+import { z } from "zod";
+import { authActionClient } from "../safe-action";
+
+const schema = createRewardSchema.and(
+ z.object({
+ workspaceId: z.string(),
+ programId: z.string(),
+ }),
+);
+
+export const createRewardAction = authActionClient
+ .schema(schema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace } = ctx;
+ const {
+ programId,
+ event,
+ isDefault,
+ partnerIds,
+ amount,
+ type,
+ maxDuration,
+ } = parsedInput;
+
+ const program = await getProgramOrThrow({
+ workspaceId: workspace.id,
+ programId,
+ });
+
+ let programEnrollments: { id: string }[] = [];
+
+ if (partnerIds) {
+ programEnrollments = await prisma.programEnrollment.findMany({
+ where: {
+ programId,
+ partnerId: {
+ in: partnerIds,
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (programEnrollments.length !== partnerIds.length) {
+ throw new Error("Invalid partner IDs provided.");
+ }
+ }
+
+ if (isDefault) {
+ if (program.defaultRewardId) {
+ throw new Error(
+ `A program can only have one default reward and you've already set one with id ${program.defaultRewardId}.`,
+ );
+ }
+
+ if (event !== "sale") {
+ throw new Error("Default reward must be of type `sale`.");
+ }
+
+ if (partnerIds && partnerIds.length > 0) {
+ throw new Error("Default reward should not be partner specific.");
+ }
+ }
+
+ // TODO:
+ // Partners can't be more than one reward of the same type.
+
+ const reward = await prisma.reward.create({
+ data: {
+ id: createId({ prefix: "rew_" }),
+ programId,
+ event,
+ type,
+ amount,
+ maxDuration,
+ ...(programEnrollments && {
+ partners: {
+ createMany: {
+ data: programEnrollments.map(({ id }) => ({
+ programEnrollmentId: id,
+ })),
+ },
+ },
+ }),
+ },
+ });
+
+ if (isDefault) {
+ await prisma.program.update({
+ where: {
+ id: programId,
+ },
+ data: {
+ defaultRewardId: reward.id,
+ },
+ });
+ }
+
+ // TODO:
+ // Send an email to partners who are eligible for the reward.
+
+ console.log("New reward created", reward);
+ });
diff --git a/apps/web/ui/partners/add-edit-reward-sheet.tsx b/apps/web/ui/partners/add-edit-reward-sheet.tsx
new file mode 100644
index 0000000000..f6773caaaa
--- /dev/null
+++ b/apps/web/ui/partners/add-edit-reward-sheet.tsx
@@ -0,0 +1,251 @@
+"use client";
+
+import { createRewardAction } from "@/lib/actions/partners/create-reward";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import usePartners from "@/lib/swr/use-partners";
+import useProgram from "@/lib/swr/use-program";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { createRewardSchema } from "@/lib/zod/schemas/rewards";
+import { X } from "@/ui/shared/icons";
+import { EventType } from "@dub/prisma/client";
+import { Button, CircleCheckFill, Sheet } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { Dispatch, SetStateAction, useRef, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+
+// TODO:
+// Can create 1 “all partner” reward
+// Can create infinite “specific parter” rewards
+// Partners can’t be on more than one “specific reward”
+
+interface RewardSheetProps {
+ setIsOpen: Dispatch<SetStateAction<boolean>>;
+ event: EventType;
+}
+
+type FormData = z.infer<typeof createRewardSchema>;
+
+const partnerTypes = [
+ {
+ key: "all",
+ label: "All Partners",
+ description: "Everyone is eligible",
+ },
+ {
+ key: "specific",
+ label: "Specific Partners",
+ description: "Select who is eligible",
+ },
+] as const;
+
+function RewardSheetContent({ setIsOpen, event }: RewardSheetProps) {
+ const { program } = useProgram();
+ const { data: partners } = usePartners();
+ const { id: workspaceId } = useWorkspace();
+ const formRef = useRef<HTMLFormElement>(null);
+ const [selectedPartnerType, setSelectedPartnerType] =
+ useState<(typeof partnerTypes)[number]["key"]>("all");
+
+ const {
+ register,
+ handleSubmit,
+ watch,
+ setValue,
+ clearErrors,
+ formState: { errors },
+ } = useForm<FormData>({
+ defaultValues: {
+ type: "flat",
+ isDefault: false,
+ maxDuration: null,
+ partnerIds: [],
+ event,
+ },
+ });
+
+ const { executeAsync, isPending } = useAction(createRewardAction, {
+ onSuccess: async (res) => {
+ setIsOpen(false);
+ toast.success("Successfully created reward!");
+ await mutatePrefix(`/api/programs/${program?.id}/rewards`);
+ },
+ onError({ error }) {
+ toast.error(error.serverError);
+ },
+ });
+
+ const onSubmit = async (data: FormData) => {
+ if (!workspaceId || !program) {
+ toast.error("Please fill all required fields");
+ return;
+ }
+
+ await executeAsync({
+ workspaceId,
+ programId: program.id,
+ ...data,
+ amount: data.amount * 100,
+ });
+ };
+
+ const [partnerIds, amount, type, isDefault] = watch([
+ "partnerIds",
+ "amount",
+ "type",
+ "isDefault",
+ ]);
+
+ const buttonDisabled = isPending || amount == null;
+ const isAllPartners = partnerIds && partnerIds.length >= 0;
+
+ console.log(errors);
+
+ return (
+ <form
+ ref={formRef}
+ onSubmit={handleSubmit(onSubmit)}
+ className="flex h-full flex-col"
+ >
+ <div>
+ <div className="flex items-start justify-between border-b border-neutral-200 p-6">
+ <Sheet.Title className="text-xl font-semibold">
+ {`Create ${event} reward`}
+ </Sheet.Title>
+ <Sheet.Close asChild>
+ <Button
+ variant="outline"
+ icon={<X className="size-5" />}
+ className="h-auto w-fit p-1"
+ />
+ </Sheet.Close>
+ </div>
+ <div className="flex flex-col gap-4 p-6">
+ <div>
+ <label
+ htmlFor="amount"
+ className="text-sm font-medium text-neutral-800"
+ >
+ {`Amount per ${event}`}
+ </label>
+ <div className="relative mt-2 rounded-md shadow-sm">
+ {type === "flat" && (
+ <span className="absolute inset-y-0 left-0 flex items-center pl-3 text-sm text-neutral-400">
+ $
+ </span>
+ )}
+ <input
+ className={cn(
+ "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ errors.amount &&
+ "border-red-600 focus:border-red-500 focus:ring-red-600",
+ type === "flat" ? "pl-6 pr-12" : "pr-7",
+ )}
+ {...register("amount", {
+ required: true,
+ valueAsNumber: true,
+ min: 0,
+ max: type === "flat" ? 1000 : 100,
+ })}
+ />
+ <span className="absolute inset-y-0 right-0 flex items-center pr-3 text-sm text-neutral-400">
+ {type === "flat" ? "USD" : "%"}
+ </span>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
+ {partnerTypes.map((partnerType) => {
+ const isSelected = selectedPartnerType === partnerType.key;
+
+ return (
+ <label
+ key={partnerType.label}
+ className={cn(
+ "relative flex w-full cursor-pointer items-start gap-0.5 rounded-md border border-neutral-200 bg-white p-3 text-neutral-600 hover:bg-neutral-50",
+ "transition-all duration-150",
+ isSelected &&
+ "border-black bg-neutral-50 text-neutral-900 ring-1 ring-black",
+ )}
+ >
+ <input
+ type="radio"
+ value={partnerType.label}
+ className="hidden"
+ checked={isSelected}
+ onChange={(e) => {
+ if (e.target.checked) {
+ setSelectedPartnerType(partnerType.key);
+ }
+ }}
+ />
+ <div className="flex grow flex-col text-sm">
+ <span className="font-medium">{partnerType.label}</span>
+ <span>{partnerType.description}</span>
+ </div>
+ <CircleCheckFill
+ className={cn(
+ "-mr-px -mt-px flex size-4 scale-75 items-center justify-center rounded-full opacity-0 transition-[transform,opacity] duration-150",
+ isSelected && "scale-100 opacity-100",
+ )}
+ />
+ </label>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+
+ <div className="flex grow flex-col justify-end">
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 p-5">
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => setIsOpen(false)}
+ text="Cancel"
+ className="w-fit"
+ disabled={isPending}
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ text="Create reward"
+ className="w-fit"
+ loading={isPending}
+ disabled={buttonDisabled}
+ />
+ </div>
+ </div>
+ </form>
+ );
+}
+
+export function RewardSheet({
+ isOpen,
+ nested,
+ ...rest
+}: RewardSheetProps & {
+ isOpen: boolean;
+ nested?: boolean;
+}) {
+ return (
+ <Sheet open={isOpen} onOpenChange={rest.setIsOpen} nested={nested}>
+ <RewardSheetContent {...rest} />
+ </Sheet>
+ );
+}
+
+export function useRewardSheet(
+ props: { nested?: boolean } & Omit<RewardSheetProps, "setIsOpen">,
+) {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return {
+ rewardSheet: (
+ <RewardSheet setIsOpen={setIsOpen} isOpen={isOpen} {...props} />
+ ),
+ setIsOpen,
+ };
+}