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 group support to bounties and update API/mutation logic

Kiran Kee9ac5531f36
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index 7cff391e4e..329a6049ba 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -12,27 +12,15 @@ import { z } from "zod";
export const GET = withWorkspace(async ({ workspace }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
- let bounties = await prisma.bounty.findMany({
+ const bounties = await prisma.bounty.findMany({
where: {
programId,
},
orderBy: {
createdAt: "desc",
},
- include: {
- _count: {
- select: {
- submissions: true,
- },
- },
- },
});
- bounties = bounties.map((bounty) => ({
- ...bounty,
- submissionsCount: bounty._count.submissions,
- }));
-
return NextResponse.json(z.array(BountySchema).parse(bounties));
});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx
index 2e2b08908a..c7320e1849 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx
@@ -1,4 +1,5 @@
import useWorkspace from "@/lib/swr/use-workspace";
+import { BountyProps } from "@/lib/types";
import {
createBountySchema,
SUBMISSION_REQUIREMENTS,
@@ -11,7 +12,7 @@ import {
} from "@/ui/partners/program-sheet-accordion";
import { AmountInput } from "@/ui/shared/amount-input";
import { X } from "@/ui/shared/icons";
-import { useApiRequest } from "@/ui/shared/use-api-mutation";
+import { useApiMutation } from "@/ui/shared/use-api-mutation";
import {
AnimatedSizeContainer,
Button,
@@ -24,6 +25,7 @@ import {
import { cn } from "@dub/utils";
import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
+import { toast } from "sonner";
import { z } from "zod";
type BountySheetProps = {
@@ -51,6 +53,7 @@ const ACCORDION_ITEMS = [
"bounty-type",
"bounty-details",
"submission-requirements",
+ "groups",
];
function BountySheetContent({ setIsOpen }: BountySheetProps) {
@@ -59,7 +62,7 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
const [requireImage, setRequireImage] = useState(false);
const [requireUrl, setRequireUrl] = useState(false);
const [openAccordions, setOpenAccordions] = useState(ACCORDION_ITEMS);
- const { makeRequest, loading } = useApiRequest();
+ const { makeRequest, isSubmitting } = useApiMutation<BountyProps>();
const {
handleSubmit,
@@ -130,9 +133,12 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
await makeRequest("/api/bounties", {
method: "POST",
body: data,
- successMessage: "Bounty created successfully!",
onSuccess: () => {
setIsOpen(false);
+ toast.success("Bounty created successfully!");
+ },
+ onError: (message) => {
+ toast.error(message);
},
});
};
@@ -336,7 +342,7 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
errors.description &&
"border-red-600 focus:border-red-500 focus:ring-red-600",
)}
- placeholder="Add details for this bounty"
+ placeholder="Provide any bounty requirements to the partner"
{...register("description", {
setValueAs: (value) => (value === "" ? null : value),
})}
@@ -397,6 +403,21 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
</div>
</ProgramSheetAccordionContent>
</ProgramSheetAccordionItem>
+
+ <ProgramSheetAccordionItem value="groups">
+ <ProgramSheetAccordionTrigger>
+ Groups
+ </ProgramSheetAccordionTrigger>
+ <ProgramSheetAccordionContent>
+ <div className="space-y-6">
+ <p className="text-sm text-neutral-600">
+ Configure group settings for this bounty.
+ </p>
+
+ {/* Add your groups-related content here */}
+ </div>
+ </ProgramSheetAccordionContent>
+ </ProgramSheetAccordionItem>
</ProgramSheetAccordion>
</div>
</div>
@@ -409,7 +430,7 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
onClick={() => setIsOpen(false)}
text="Cancel"
className="w-fit"
- disabled={loading}
+ disabled={isSubmitting}
/>
<Button
@@ -417,7 +438,7 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
variant="primary"
text="Create bounty"
className="w-fit"
- loading={loading}
+ loading={isSubmitting}
disabled={shouldDisableSubmit}
disabledTooltip={
shouldDisableSubmit
diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.ts
index 62bf510b07..7cce3fc67c 100644
--- a/apps/web/lib/zod/schemas/bounties.ts
+++ b/apps/web/lib/zod/schemas/bounties.ts
@@ -37,8 +37,6 @@ export const BountySchema = z.object({
startsAt: z.date(),
endsAt: z.date().nullable(),
rewardAmount: z.number(),
- submissionsCount: z.number(),
- // partnersCount: z.number(),
});
export const BountySubmissionSchema = z.object({
diff --git a/apps/web/ui/shared/use-api-mutation.ts b/apps/web/ui/shared/use-api-mutation.ts
index 36341846e6..9338fdd723 100644
--- a/apps/web/ui/shared/use-api-mutation.ts
+++ b/apps/web/ui/shared/use-api-mutation.ts
@@ -1,25 +1,12 @@
import useWorkspace from "@/lib/swr/use-workspace";
import { useCallback, useState } from "react";
-import { toast } from "sonner";
-interface ApiRequestOptions<TBody> {
+interface ApiRequestOptions<TBody, TResponse = any> {
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
body?: TBody;
headers?: Record<string, string>;
- showToast?: boolean;
- successMessage?: string;
- onSuccess?: () => void;
- onError?: () => void;
-}
-
-interface ApiResponse<T> {
- data: T | null;
- error: string | null;
- loading: boolean;
- makeRequest: (
- endpoint: string,
- options?: ApiRequestOptions<any>,
- ) => Promise<void>;
+ onSuccess?: (data: TResponse) => void;
+ onError?: (message: string) => void;
}
interface ApiError {
@@ -34,40 +21,35 @@ const debug = (...args: any[]) => {
}
};
-export function useApiRequest<
- TResponse = any,
- TBody = any,
->(): ApiResponse<TResponse> {
+export function useApiMutation<TResponse = any, TBody = any>() {
const { id: workspaceId } = useWorkspace();
- const [data, setData] = useState<TResponse | null>(null);
- const [error, setError] = useState<string | null>(null);
- const [loading, setLoading] = useState(false);
+ const [isSubmitting, setIsSubmitting] = useState(false);
const makeRequest = useCallback(
- async (endpoint: string, options: ApiRequestOptions<TBody> = {}) => {
- const {
+ async (
+ endpoint: string,
+ {
method = "GET",
body,
headers,
- successMessage,
- showToast = true,
onSuccess,
onError,
- } = options;
-
- setLoading(true);
- setError(null);
- setData(null);
+ }: ApiRequestOptions<TBody, TResponse> = {},
+ ) => {
+ setIsSubmitting(true);
try {
- debug("Starting request", {
- endpoint,
- method,
- body,
- headers,
- });
+ const url = new URL(endpoint, window.location.origin);
+
+ if (workspaceId) {
+ url.searchParams.set("workspaceId", workspaceId);
+ }
- const response = await fetch(`${endpoint}?workspaceId=${workspaceId}`, {
+ if (body) {
+ debug("Request body", body);
+ }
+
+ const response = await fetch(url.toString(), {
method,
headers: {
"Content-Type": "application/json",
@@ -76,50 +58,37 @@ export function useApiRequest<
body: body ? JSON.stringify(body) : undefined,
});
- // Handle error
if (!response.ok) {
const { error } = (await response.json()) as ApiError;
+
throw new Error(
- error.message || `Request failed with status ${response.status}`,
+ error?.message || `Request failed with status ${response.status}`,
);
}
- // Handle success
- const data = (await response.json()) as TResponse;
- setData(data);
- onSuccess?.();
+ const responseData = (await response.json()) as TResponse;
- if (showToast) {
- toast.success(successMessage || "Request completed successfully.");
- }
-
- debug("Response received", data);
- } catch (error) {
- setError(
- error instanceof Error
- ? error.message
- : "Something went wrong. Please try again.",
- );
+ debug("Response data", responseData);
- onError?.();
+ onSuccess?.(responseData);
+ } catch (err) {
+ const message =
+ err instanceof Error
+ ? err.message
+ : "Something went wrong. Please try again.";
- if (showToast) {
- toast.error(error.message);
- }
+ debug("Request error", err);
- debug("Error occurred", error);
+ onError?.(message);
} finally {
- setLoading(false);
- debug("Request finished");
+ setIsSubmitting(false);
}
},
- [],
+ [workspaceId],
);
return {
- data,
- error,
- loading,
+ isSubmitting,
makeRequest,
};
}
diff --git a/packages/prisma/schema/bounty.prisma b/packages/prisma/schema/bounty.prisma
index ae4ffc1101..9838d20d22 100644
--- a/packages/prisma/schema/bounty.prisma
+++ b/packages/prisma/schema/bounty.prisma
@@ -29,11 +29,24 @@ model Bounty {
program Program @relation(fields: [programId], references: [id], onDelete: Cascade)
submissions BountySubmission[]
+ groups BountyGroup[]
@@index(programId)
@@index(workflowId)
}
+model BountyGroup {
+ id String @id @default(cuid())
+ bountyId String
+ groupId String
+
+ bounty Bounty @relation(fields: [bountyId], references: [id], onDelete: Cascade)
+ partnerGroup PartnerGroup @relation(fields: [groupId], references: [id], onDelete: Cascade)
+
+ @@unique([bountyId, groupId])
+ @@index([groupId])
+}
+
model BountySubmission {
id String @id @default(cuid())
programId String
diff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prisma
index 461d183968..58e5f872c2 100644
--- a/packages/prisma/schema/partner.prisma
+++ b/packages/prisma/schema/partner.prisma
@@ -97,3 +97,21 @@ model PartnerNotificationPreferences {
partnerUser PartnerUser @relation(fields: [partnerUserId], references: [id], onDelete: Cascade)
}
+
+// TODO: Copy the full tab from https://github.com/dubinc/dub/pull/2735
+model PartnerGroup {
+ id String @id @default(cuid())
+ programId String
+ name String
+ slug String
+ color String?
+ clickRewardId String? @unique
+ leadRewardId String? @unique
+ saleRewardId String? @unique
+ discountId String? @unique
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ bounties BountyGroup[]
+
+ @@unique([programId, slug])
+}