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 bounties to audit logs, finalize bounty response schema

Steven Tey2cf55c0c6e1a
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
index 87e440ccdc..40b118c5ab 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
@@ -1,3 +1,4 @@
+import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { getBountyWithDetails } from "@/lib/api/bounties/get-bounty-with-details";
import { DubApiError } from "@/lib/api/errors";
import { throwIfInvalidGroupIds } from "@/lib/api/groups/throw-if-invalid-group-ids";
@@ -45,7 +46,7 @@ export const GET = withWorkspace(
// PATCH /api/bounties/[bountyId] - update a bounty
export const PATCH = withWorkspace(
- async ({ workspace, params, req }) => {
+ async ({ workspace, params, req, session }) => {
const { bountyId } = params;
const programId = getDefaultProgramIdOrThrow(workspace);
@@ -94,7 +95,7 @@ export const PATCH = withWorkspace(
});
}
- const updatedBounty = await prisma.$transaction(async (tx) => {
+ const data = await prisma.$transaction(async (tx) => {
const updatedBounty = await tx.bounty.update({
where: {
id: bounty.id,
@@ -118,6 +119,10 @@ export const PATCH = withWorkspace(
},
}),
},
+ include: {
+ workflow: true,
+ groups: true,
+ },
});
if (updatedBounty.workflowId && performanceCondition) {
@@ -137,17 +142,36 @@ export const PATCH = withWorkspace(
};
});
+ const updatedBounty = BountySchema.parse({
+ ...data,
+ groups: data.groups.map(({ groupId }) => ({ id: groupId })),
+ performanceCondition: data.workflow?.triggerConditions?.[0],
+ });
+
waitUntil(
Promise.allSettled([
+ recordAuditLog({
+ workspaceId: workspace.id,
+ programId,
+ action: "bounty.updated",
+ description: `Bounty ${bounty.id} updated`,
+ actor: session?.user,
+ targets: [
+ {
+ type: "bounty",
+ id: bounty.id,
+ metadata: updatedBounty,
+ },
+ ],
+ }),
sendWorkspaceWebhook({
workspace,
trigger: "bounty.updated",
- data: BountySchema.parse(updatedBounty),
+ data: updatedBounty,
}),
// if bounty.startsAt was updated, publish a new message to the queue
- updatedBounty.startsAt &&
- updatedBounty.startsAt !== bounty.startsAt &&
+ updatedBounty.startsAt.getTime() !== bounty.startsAt.getTime() &&
qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/bounties/notify-partners`,
body: {
@@ -158,7 +182,7 @@ export const PATCH = withWorkspace(
]),
);
- return NextResponse.json(BountySchema.parse(updatedBounty));
+ return NextResponse.json(updatedBounty);
},
{
requiredPlan: [
diff --git a/apps/web/app/(ee)/api/bounties/count/route.ts b/apps/web/app/(ee)/api/bounties/count/submissions/route.ts
similarity index 77%
rename from apps/web/app/(ee)/api/bounties/count/route.ts
rename to apps/web/app/(ee)/api/bounties/count/submissions/route.ts
index c7ba39124d..aefafc998b 100644
--- a/apps/web/app/(ee)/api/bounties/count/route.ts
+++ b/apps/web/app/(ee)/api/bounties/count/submissions/route.ts
@@ -5,22 +5,24 @@ import { BountySubmissionStatus } from "@dub/prisma/client";
import { NextResponse } from "next/server";
import { z } from "zod";
-const bountiesCountQuerySchema = z.object({
- groupBy: z.enum(["status", "bountyId"]).optional().default("status"),
+const bountiesSubmissionsCountQuerySchema = z.object({
+ bountyId: z.string().optional(),
});
const statuses = Object.values(BountySubmissionStatus);
-// GET /api/bounties/count
+// GET /api/bounties/count/submissions – get the total bounty submissions count by status (potentially filtered by bountyId)
export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
- const { groupBy } = bountiesCountQuerySchema.parse(searchParams);
+ const { bountyId } =
+ bountiesSubmissionsCountQuerySchema.parse(searchParams);
const count = await prisma.bountySubmission.groupBy({
by: ["status"],
where: {
programId,
+ bountyId,
},
_count: true,
});
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index d0dae5b40f..7f298b3e9c 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -1,3 +1,4 @@
+import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
import { createId } from "@/lib/api/create-id";
import { DubApiError } from "@/lib/api/errors";
import { throwIfInvalidGroupIds } from "@/lib/api/groups/throw-if-invalid-group-ids";
@@ -69,7 +70,7 @@ export const GET = withWorkspace(
// POST /api/bounties - create a bounty
export const POST = withWorkspace(
- async ({ workspace, req }) => {
+ async ({ workspace, req, session }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
const {
@@ -147,15 +148,40 @@ export const POST = withWorkspace(
},
}),
},
+ include: {
+ workflow: true,
+ groups: true,
+ },
});
});
+ const createdBounty = BountySchema.parse({
+ ...bounty,
+ groups: bounty.groups.map(({ groupId }) => ({ id: groupId })),
+ performanceCondition: bounty.workflow?.triggerConditions?.[0],
+ });
+
waitUntil(
Promise.allSettled([
+ recordAuditLog({
+ workspaceId: workspace.id,
+ programId,
+ action: "bounty.created",
+ description: `Bounty ${bounty.id} created`,
+ actor: session?.user,
+ targets: [
+ {
+ type: "bounty",
+ id: bounty.id,
+ metadata: createdBounty,
+ },
+ ],
+ }),
+
sendWorkspaceWebhook({
workspace,
trigger: "bounty.created",
- data: BountySchema.parse(bounty),
+ data: createdBounty,
}),
qstash.publishJSON({
@@ -168,7 +194,7 @@ export const POST = withWorkspace(
]),
);
- return NextResponse.json(BountySchema.parse(bounty));
+ return NextResponse.json(createdBounty);
},
{
requiredPlan: [
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
index 8c9833e084..41a5ab1893 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-info.tsx
@@ -1,14 +1,29 @@
"use client";
import useBounty from "@/lib/swr/use-bounty";
+import {
+ SubmissionsCountByStatus,
+ useBountySubmissionsCount,
+} from "@/lib/swr/use-bounty-submissions-count";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
import { formatDate, pluralize } from "@dub/utils";
import { CalendarDays, Users } from "lucide-react";
+import { useMemo } from "react";
import { BountyActionButton } from "../bounty-action-button";
export function BountyInfo() {
const { bounty, loading } = useBounty();
+ const { submissionsCount } = useBountySubmissionsCount<
+ SubmissionsCountByStatus[]
+ >({
+ enabled: Boolean(bounty),
+ });
+
+ const totalSubmissions = useMemo(() => {
+ return submissionsCount?.reduce((acc, curr) => acc + curr.count, 0);
+ }, [submissionsCount]);
+
if (loading) {
return <BountyInfoSkeleton />;
}
@@ -17,9 +32,6 @@ export function BountyInfo() {
return null;
}
- const { pending = 0, approved = 0, rejected = 0 } = bounty.submissions;
- const totalSubmissions = pending + approved + rejected;
-
return (
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:gap-6">
<div className="relative flex size-20 shrink-0 items-center justify-center rounded-lg bg-neutral-100 p-3">
@@ -45,14 +57,18 @@ export function BountyInfo() {
<div className="flex items-center space-x-2">
<Users className="size-4 shrink-0" />
<div className="text-sm text-neutral-500">
- <span className="font-medium text-neutral-700">
- {totalSubmissions}
- </span>{" "}
+ {totalSubmissions === undefined ? (
+ <div className="h-5 w-32 animate-pulse rounded bg-neutral-200" />
+ ) : (
+ <span className="font-medium text-neutral-700">
+ {totalSubmissions}
+ </span>
+ )}{" "}
of{" "}
<span className="font-medium text-neutral-700">
- {bounty.partners}
+ {bounty.partnersCount}
</span>{" "}
- {pluralize("partner", bounty.partners ?? 0)} completed
+ {pluralize("partner", bounty.partnersCount ?? 0)} completed
</div>
</div>
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx
index 886c0ee405..58d3e559de 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/use-bounty-submission-filters.tsx
@@ -1,10 +1,14 @@
+import {
+ SubmissionsCountByStatus,
+ useBountySubmissionsCount,
+} from "@/lib/swr/use-bounty-submissions-count";
import useGroups from "@/lib/swr/use-groups";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyExtendedProps } from "@/lib/types";
import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
import { CircleDotted, useRouterStuff } from "@dub/ui";
-import { CircleCheck, CircleHalfDottedCheck, Users6 } from "@dub/ui/icons";
-import { cn } from "@dub/utils";
+import { Users6 } from "@dub/ui/icons";
+import { cn, nFormatter } from "@dub/utils";
import { useCallback, useMemo } from "react";
import { BOUNTY_SUBMISSION_STATUS_BADGES } from "./bounty-submission-status-badges";
@@ -13,12 +17,14 @@ export function useBountySubmissionFilters({
}: {
bounty?: BountyExtendedProps;
}) {
- console.log("bounty?.groups", bounty?.groups);
- const { slug } = useWorkspace();
const { searchParamsObj, queryParams } = useRouterStuff();
+ const { slug } = useWorkspace();
const { groups } = useGroups();
+ const { submissionsCount } =
+ useBountySubmissionsCount<SubmissionsCountByStatus[]>();
+
const filters = useMemo(
() => [
{
@@ -26,32 +32,29 @@ export function useBountySubmissionFilters({
icon: CircleDotted,
label: "Status",
options:
- bounty?.type === "submission"
- ? Object.entries(BOUNTY_SUBMISSION_STATUS_BADGES).map(
- ([value, { label, icon: Icon, iconClassName }]) => ({
- value,
- label,
- icon: (
- <Icon
- className={cn("size-4 bg-transparent", iconClassName)}
- />
- ),
- }),
- )
- : [
- {
- value: "approved",
- label: "Completed",
- icon: <CircleCheck className="size-4 text-green-600" />,
- },
+ bounty?.type === "submission" && submissionsCount
+ ? submissionsCount.map(({ status, count }) => {
{
- value: "pending",
- label: "Incomplete",
- icon: (
- <CircleHalfDottedCheck className="size-4 text-orange-600" />
- ),
- },
- ],
+ const {
+ label,
+ icon: Icon,
+ iconClassName,
+ } = BOUNTY_SUBMISSION_STATUS_BADGES[status];
+ return {
+ value: status,
+ label,
+ icon: (
+ <Icon
+ className={cn("size-4 bg-transparent", iconClassName)}
+ />
+ ),
+ right: nFormatter(count, {
+ full: true,
+ }),
+ };
+ }
+ })
+ : null,
},
{
key: "groupId",
@@ -74,7 +77,7 @@ export function useBountySubmissionFilters({
}) ?? null,
},
],
- [bounty, groups, slug],
+ [bounty, submissionsCount, groups, slug],
);
const activeFilters = useMemo(() => {
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 d2c0f37268..8777fdbe0b 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
@@ -301,26 +301,28 @@ function BountySheetContent({ setIsOpen, bounty }: BountySheetProps) {
onValueChange={setOpenAccordions}
className="space-y-6"
>
- <ProgramSheetAccordionItem value="bounty-type">
- <ProgramSheetAccordionTrigger>
- Bounty type
- </ProgramSheetAccordionTrigger>
- <ProgramSheetAccordionContent>
- <div className="space-y-4">
- <p className="text-content-default text-sm">
- Set how the bounty will be completed
- </p>
- <CardSelector
- options={BOUNTY_TYPES}
- value={watch("type")}
- onChange={(value: FormData["type"]) =>
- setValue("type", value)
- }
- name="bounty-type"
- />
- </div>
- </ProgramSheetAccordionContent>
- </ProgramSheetAccordionItem>
+ {!bounty && ( // cannot change type for existing bounties
+ <ProgramSheetAccordionItem value="bounty-type">
+ <ProgramSheetAccordionTrigger>
+ Bounty type
+ </ProgramSheetAccordionTrigger>
+ <ProgramSheetAccordionContent>
+ <div className="space-y-4">
+ <p className="text-content-default text-sm">
+ Set how the bounty will be completed
+ </p>
+ <CardSelector
+ options={BOUNTY_TYPES}
+ value={watch("type")}
+ onChange={(value: FormData["type"]) =>
+ setValue("type", value)
+ }
+ name="bounty-type"
+ />
+ </div>
+ </ProgramSheetAccordionContent>
+ </ProgramSheetAccordionItem>
+ )}
<ProgramSheetAccordionItem value="bounty-details">
<ProgramSheetAccordionTrigger>
diff --git a/apps/web/lib/api/audit-logs/schemas.ts b/apps/web/lib/api/audit-logs/schemas.ts
index 3baaf45aac..3e7376412c 100644
--- a/apps/web/lib/api/audit-logs/schemas.ts
+++ b/apps/web/lib/api/audit-logs/schemas.ts
@@ -1,3 +1,4 @@
+import { BountySchema } from "@/lib/zod/schemas/bounties";
import { CommissionSchema } from "@/lib/zod/schemas/commissions";
import { DiscountSchema } from "@/lib/zod/schemas/discount";
import { GroupSchema } from "@/lib/zod/schemas/groups";
@@ -73,6 +74,11 @@ const actionSchema = z.enum([
"group.created",
"group.updated",
"group.deleted",
+
+ // Bounties
+ "bounty.created",
+ "bounty.updated",
+ "bounty.deleted",
]);
export const auditLogTarget = z.union([
@@ -156,6 +162,12 @@ export const auditLogTarget = z.union([
discountId: z.string().nullish(),
}),
}),
+
+ z.object({
+ type: z.literal("bounty"),
+ id: z.string(),
+ metadata: BountySchema,
+ }),
]);
export const recordAuditLogInputSchema = z.object({
diff --git a/apps/web/lib/api/bounties/get-bounty-with-details.ts b/apps/web/lib/api/bounties/get-bounty-with-details.ts
index 2129e27734..af77851d22 100644
--- a/apps/web/lib/api/bounties/get-bounty-with-details.ts
+++ b/apps/web/lib/api/bounties/get-bounty-with-details.ts
@@ -57,18 +57,14 @@ export const getBountyWithDetails = async ({
JSON_ARRAY()
) AS groups,
- -- Bounty submissions count by status
+ -- Bounty submissions total count
COALESCE(
(
- SELECT JSON_OBJECT(
- 'pending', COALESCE(SUM(status = 'pending'), 0),
- 'approved', COALESCE(SUM(status = 'approved'), 0),
- 'rejected', COALESCE(SUM(status = 'rejected'), 0)
- )
+ SELECT COUNT(*)
FROM BountySubmission
WHERE bountyId = b.id
),
- JSON_OBJECT('pending', 0, 'approved', 0, 'rejected', 0)
+ 0
) AS submissions
FROM Bounty b
@@ -99,7 +95,7 @@ export const getBountyWithDetails = async ({
submissionRequirements: bounty.submissionRequirements,
performanceCondition,
groups: bounty.groups.filter((group) => group !== null) ?? [],
- partners: Number(bounty.partners),
- submissions: bounty.submissions,
+ partnersCount: Number(bounty.partners),
+ submissionsCount: Number(bounty.submissions),
};
};
diff --git a/apps/web/lib/swr/use-bounty-submissions-count.ts b/apps/web/lib/swr/use-bounty-submissions-count.ts
index bdb68704fa..c1fa10322b 100644
--- a/apps/web/lib/swr/use-bounty-submissions-count.ts
+++ b/apps/web/lib/swr/use-bounty-submissions-count.ts
@@ -1,6 +1,7 @@
import { BountySubmissionStatus } from "@dub/prisma/client";
import { useRouterStuff } from "@dub/ui";
import { fetcher } from "@dub/utils";
+import { useParams } from "next/navigation";
import useSWR from "swr";
import useWorkspace from "./use-workspace";
@@ -10,21 +11,21 @@ export interface SubmissionsCountByStatus {
}
export function useBountySubmissionsCount<T>({
- enabled,
+ enabled = true,
}: {
enabled?: boolean;
} = {}) {
+ const { bountyId } = useParams();
const { id: workspaceId } = useWorkspace();
const { getQueryString } = useRouterStuff();
- const shouldFetch = Boolean(enabled && workspaceId);
-
const { data: submissionsCount, error } = useSWR<T>(
- shouldFetch
- ? `/api/bounties/count${getQueryString({
- workspaceId,
- })}`
- : null,
+ enabled &&
+ workspaceId &&
+ `/api/bounties/count/submissions${getQueryString({
+ workspaceId,
+ ...(bountyId ? { bountyId } : {}),
+ })}`,
fetcher,
{
keepPreviousData: true,
diff --git a/apps/web/lib/webhook/sample-events/bounty-created.json b/apps/web/lib/webhook/sample-events/bounty-created.json
index a41173c4f5..f50e921832 100644
--- a/apps/web/lib/webhook/sample-events/bounty-created.json
+++ b/apps/web/lib/webhook/sample-events/bounty-created.json
@@ -1,10 +1,16 @@
{
"id": "bnty_1K39DGZG3MHY9RP4PD0AS2C5P",
- "name": "Earn $100 after generating 20 total conversions",
- "description": "Earn $100 after generating 20 total conversions. This is a test bounty.",
- "type": "performance",
+ "name": "Create a video about Dub and earn $500",
+ "description": "Create a video about Dub and earn $500. This is a test bounty.",
+ "type": "submission",
"startsAt": "2025-08-01T17:34:00.000Z",
"endsAt": "2025-09-01T17:34:00.000Z",
- "rewardAmount": 10000,
- "submissionRequirements": null
+ "rewardAmount": 50000,
+ "submissionRequirements": ["image", "url"],
+ "performanceCondition": null,
+ "groups": [
+ {
+ "id": "grp_1K2E25381GVMG7HHM057TB92F"
+ }
+ ]
}
diff --git a/apps/web/lib/webhook/sample-events/bounty-updated.json b/apps/web/lib/webhook/sample-events/bounty-updated.json
index a41173c4f5..d216da994a 100644
--- a/apps/web/lib/webhook/sample-events/bounty-updated.json
+++ b/apps/web/lib/webhook/sample-events/bounty-updated.json
@@ -1,10 +1,16 @@
{
"id": "bnty_1K39DGZG3MHY9RP4PD0AS2C5P",
- "name": "Earn $100 after generating 20 total conversions",
- "description": "Earn $100 after generating 20 total conversions. This is a test bounty.",
- "type": "performance",
+ "name": "Create a video about Dub and earn $1,000",
+ "description": "Create a video about Dub and earn $1,000. This is a live bounty.",
+ "type": "submission",
"startsAt": "2025-08-01T17:34:00.000Z",
"endsAt": "2025-09-01T17:34:00.000Z",
- "rewardAmount": 10000,
- "submissionRequirements": null
+ "rewardAmount": 100000,
+ "submissionRequirements": ["image", "url"],
+ "performanceCondition": null,
+ "groups": [
+ {
+ "id": "grp_1K2E25381GVMG7HHM057TB92F"
+ }
+ ]
}
diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.ts
index 68e2a6365c..7d1c237d90 100644
--- a/apps/web/lib/zod/schemas/bounties.ts
+++ b/apps/web/lib/zod/schemas/bounties.ts
@@ -64,19 +64,18 @@ export const BountySchema = z.object({
startsAt: z.date(),
endsAt: z.date().nullable(),
rewardAmount: z.number(),
- submissionRequirements: submissionRequirementsSchema.nullable(),
+ performanceCondition: workflowConditionSchema.nullable().default(null),
+ submissionRequirements: submissionRequirementsSchema.nullable().default(null),
+ groups: z.array(GroupSchema.pick({ id: true })),
});
// used in GET /bounties
export const BountyListSchema = BountySchema.extend({
- groups: z.array(GroupSchema.pick({ id: true })),
submissionsCount: z.number().default(0),
});
export const BountySchemaExtended = BountyListSchema.extend({
- partners: z.number().default(0),
- submissions: z.record(z.nativeEnum(BountySubmissionStatus), z.number()),
- performanceCondition: workflowConditionSchema.nullable().default(null),
+ partnersCount: z.number().default(0),
});
export const BountySubmissionSchema = z.object({