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.

improve `/bounties` endpoint latency

Steven Tey5e8c3a67b2d0
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index 31d1737874..f95ef80e63 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -1,4 +1,3 @@
-import { getBounties } from "@/lib/api/bounties/get-bounties";
import { createId } from "@/lib/api/create-id";
import { DubApiError } from "@/lib/api/errors";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
@@ -7,11 +6,7 @@ import { withWorkspace } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import { WorkflowAction } from "@/lib/types";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
-import {
- BountySchema,
- createBountySchema,
- getBountiesQuerySchema,
-} from "@/lib/zod/schemas/bounties";
+import { BountySchema, createBountySchema } from "@/lib/zod/schemas/bounties";
import {
WORKFLOW_ACTION_TYPES,
WORKFLOW_ATTRIBUTE_TRIGGER_MAP,
@@ -24,16 +19,35 @@ import { NextResponse } from "next/server";
// GET /api/bounties - get all bounties for a program
export const GET = withWorkspace(
- async ({ workspace, searchParams }) => {
+ async ({ workspace }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
- const parsedInput = getBountiesQuerySchema.parse(searchParams);
- const bounties = await getBounties({
- ...parsedInput,
- programId,
+ const bounties = await prisma.bounty.findMany({
+ where: {
+ programId,
+ },
+ include: {
+ groups: {
+ select: {
+ id: true,
+ },
+ },
+ _count: {
+ select: {
+ submissions: true,
+ },
+ },
+ },
});
- return NextResponse.json(bounties);
+ return NextResponse.json(
+ bounties.map((bounty) =>
+ BountySchema.parse({
+ ...bounty,
+ submissionsCount: bounty._count.submissions,
+ }),
+ ),
+ );
},
{
requiredPlan: [
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 a7d9678be0..d8b29d18d9 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,11 +1,7 @@
import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
import { mutatePrefix } from "@/lib/swr/mutate";
import useWorkspace from "@/lib/swr/use-workspace";
-import {
- BountyExtendedProps,
- BountyProps,
- BountySubmissionRequirement,
-} from "@/lib/types";
+import { BountyProps, BountySubmissionRequirement } from "@/lib/types";
import { createBountySchema } from "@/lib/zod/schemas/bounties";
import { workflowConditionSchema } from "@/lib/zod/schemas/workflows";
import {
@@ -45,7 +41,7 @@ import { z } from "zod";
type BountySheetProps = {
setIsOpen: Dispatch<SetStateAction<boolean>>;
- bounty?: BountyExtendedProps;
+ bounty?: BountyProps;
};
type FormData = z.infer<typeof createBountySchema>;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-action-button.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-action-button.tsx
index fd077de0c8..da1616d7c0 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-action-button.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-action-button.tsx
@@ -2,18 +2,18 @@
import { mutatePrefix } from "@/lib/swr/mutate";
import useWorkspace from "@/lib/swr/use-workspace";
-import { BountyExtendedProps } from "@/lib/types";
+import { BountyProps } from "@/lib/types";
import { useConfirmModal } from "@/ui/modals/confirm-modal";
import { ThreeDots } from "@/ui/shared/icons";
import { Button, MenuItem, Popover } from "@dub/ui";
import { PenWriting, Trash } from "@dub/ui/icons";
import { Command } from "cmdk";
-import { useMemo, useState } from "react";
+import { useState } from "react";
import { toast } from "sonner";
import { useBountySheet } from "./add-edit-bounty-sheet";
interface BountyActionButtonProps {
- bounty: BountyExtendedProps;
+ bounty: BountyProps;
className?: string;
buttonClassName?: string;
}
@@ -26,15 +26,6 @@ export function BountyActionButton({
const [isOpen, setIsOpen] = useState(false);
const { id: workspaceId } = useWorkspace();
const { setShowCreateBountySheet, BountySheet } = useBountySheet({ bounty });
- console.log("bounty.submissions", bounty.submissions);
-
- const hasSubmissions = useMemo(
- () =>
- (bounty.submissions?.pending ?? 0) > 0 ||
- (bounty.submissions?.approved ?? 0) > 0 ||
- (bounty.submissions?.rejected ?? 0) > 0,
- [bounty.submissions],
- );
const { confirmModal: deleteModal, setShowConfirmModal: setShowDeleteModal } =
useConfirmModal({
@@ -98,7 +89,7 @@ export function BountyActionButton({
setShowDeleteModal(true);
}}
disabledTooltip={
- hasSubmissions
+ bounty.submissionsCount > 0
? "Bounties with submissions cannot be deleted."
: undefined
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
index 852f2b64a3..0e575e3c6f 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-card.tsx
@@ -1,17 +1,14 @@
import useWorkspace from "@/lib/swr/use-workspace";
-import { BountyExtendedProps } from "@/lib/types";
+import { BountyProps } from "@/lib/types";
import { BountyThumbnailImage } from "@/ui/partners/bounties/bounty-thumbnail-image";
-import { Calendar6, CircleCheckFill, Users } from "@dub/ui/icons";
+import { Calendar6, Users } from "@dub/ui/icons";
import { formatDate, pluralize } from "@dub/utils";
import Link from "next/link";
import { BountyActionButton } from "./bounty-action-button";
-export function BountyCard({ bounty }: { bounty: BountyExtendedProps }) {
+export function BountyCard({ bounty }: { bounty: BountyProps }) {
const { slug: workspaceSlug } = useWorkspace();
- const { pending = 0, approved = 0, rejected = 0 } = bounty.submissions;
- const totalSubmissions = pending + approved + rejected;
-
return (
<div className="border-border-subtle hover:border-border-default relative cursor-pointer rounded-xl border bg-white p-5 transition-all hover:shadow-lg">
<Link
@@ -23,10 +20,8 @@ export function BountyCard({ bounty }: { bounty: BountyExtendedProps }) {
<BountyThumbnailImage bounty={bounty} />
</div>
- {pending > 0 ? (
- <PendingSubmissionsBadge count={pending} />
- ) : approved === bounty.partners ? (
- <CircleCheckFill className="absolute left-2 top-2 size-4 text-green-600" />
+ {bounty.submissionsCount > 0 ? (
+ <SubmissionsCountBadge count={bounty.submissionsCount} />
) : null}
</div>
@@ -51,15 +46,8 @@ export function BountyCard({ bounty }: { bounty: BountyExtendedProps }) {
<div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
<Users className="size-3.5" />
<div className="h-5">
- {approved === bounty.partners ? (
- <>All</>
- ) : (
- <>
- <span className="text-content-default">{approved}</span> of
- </>
- )}{" "}
- <span className="text-content-default">{bounty.partners}</span>{" "}
- {pluralize("partner", bounty.partners)} completed
+ Applied to {bounty.groups?.length ?? 0}{" "}
+ {pluralize("group", bounty.groups?.length ?? 0)}
</div>
</div>
</div>
@@ -74,11 +62,11 @@ export function BountyCard({ bounty }: { bounty: BountyExtendedProps }) {
);
}
-function PendingSubmissionsBadge({ count }: { count: number }) {
+function SubmissionsCountBadge({ count }: { count: number }) {
return (
<div className="absolute left-2 top-2 z-10">
<div className="flex h-5 items-center gap-1 rounded-md bg-blue-100 px-2 py-1 text-xs font-semibold text-blue-600">
- {count} {pluralize("submission", count)} for review
+ {count} {pluralize("submission", count)}
</div>
</div>
);
diff --git a/apps/web/lib/api/bounties/get-bounties.ts b/apps/web/lib/api/bounties/get-bounties.ts
deleted file mode 100644
index 0045164fd5..0000000000
--- a/apps/web/lib/api/bounties/get-bounties.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import {
- BountySchemaExtended,
- getBountiesQuerySchema,
-} from "@/lib/zod/schemas/bounties";
-import { prisma } from "@dub/prisma";
-import { Prisma } from "@prisma/client";
-import { z } from "zod";
-
-type BountyFilters = z.infer<typeof getBountiesQuerySchema> & {
- programId: string;
-};
-
-const sortColumnsMap = {
- createdAt: "b.createdAt",
-};
-
-export async function getBounties(filters: BountyFilters) {
- const { page, pageSize, sortBy, sortOrder, programId } = filters;
-
- const bounties: any[] = await prisma.$queryRaw`
- SELECT
- b.id,
- b.name,
- b.description,
- b.type,
- b.startsAt,
- b.endsAt,
- b.rewardAmount,
- b.submissionRequirements,
- wf.triggerConditions,
-
- -- Partners count
- COALESCE(
- (
- SELECT COUNT(pe.partnerId)
- FROM ProgramEnrollment pe
- WHERE pe.status IN ('approved', 'invited')
- AND (
- -- If bounty has specific groups, count only partners in those groups
- EXISTS (
- SELECT 1
- FROM BountyGroup bg
- WHERE bg.bountyId = b.id AND bg.groupId = pe.groupId
- )
- OR
- -- If bounty has no groups, count all approved/invited partners
- NOT EXISTS (
- SELECT 1
- FROM BountyGroup bg
- WHERE bg.bountyId = b.id
- )
- )
- ),
- 0
- ) AS partners,
-
- -- Bounty groups
- COALESCE(
- (
- SELECT JSON_ARRAYAGG(JSON_OBJECT('id', groupId))
- FROM BountyGroup
- WHERE bountyId = b.id
- ),
- JSON_ARRAY()
- ) AS groups,
-
- -- Bounty submissions count by status
- COALESCE(
- (
- SELECT JSON_OBJECT(
- 'pending', COALESCE(SUM(status = 'pending'), 0),
- 'approved', COALESCE(SUM(status = 'approved'), 0),
- 'rejected', COALESCE(SUM(status = 'rejected'), 0)
- )
- FROM BountySubmission
- WHERE bountyId = b.id
- ),
- JSON_OBJECT('pending', 0, 'approved', 0, 'rejected', 0)
- ) AS submissions
-
- FROM Bounty b
- LEFT JOIN BountyGroup bg ON bg.bountyId = b.id
- LEFT JOIN ProgramEnrollment pe ON pe.groupId = bg.groupId AND pe.status IN ('approved', 'invited')
- LEFT JOIN Workflow wf ON wf.id = b.workflowId
- WHERE b.programId = ${programId}
- GROUP BY b.id, b.name, b.description, b.type, b.startsAt, b.endsAt, b.rewardAmount, b.submissionRequirements
- ORDER BY ${Prisma.raw(sortColumnsMap[sortBy])} ${Prisma.raw(sortOrder)}
- LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}
- `;
-
- const results = bounties.map((bounty) => {
- const performanceCondition =
- bounty.triggerConditions?.length > 0 ? bounty.triggerConditions[0] : null;
-
- return {
- id: bounty.id,
- name: bounty.name,
- description: bounty.description,
- type: bounty.type,
- startsAt: bounty.startsAt,
- endsAt: bounty.endsAt,
- rewardAmount: bounty.rewardAmount,
- submissionRequirements: bounty.submissionRequirements,
- performanceCondition,
- groups: bounty.groups.filter((group) => group !== null),
- partners: Number(bounty.partners),
- submissions: bounty.submissions,
- };
- });
-
- return z.array(BountySchemaExtended).parse(results);
-}
diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.ts
index dcac2e60fe..a7df70d344 100644
--- a/apps/web/lib/zod/schemas/bounties.ts
+++ b/apps/web/lib/zod/schemas/bounties.ts
@@ -63,6 +63,14 @@ export const BountySchema = z.object({
rewardAmount: z.number(),
submissionRequirements: submissionRequirementsSchema.nullable(),
performanceCondition: workflowConditionSchema.nullable().default(null),
+ groups: z.array(GroupSchema.pick({ id: true })),
+ submissionsCount: z.number().default(0),
+});
+
+export const BountySchemaExtended = BountySchema.extend({
+ groups: z.array(GroupSchema.pick({ id: true })).nullable(),
+ partners: z.number().default(0),
+ submissions: z.record(z.nativeEnum(BountySubmissionStatus), z.number()),
});
const BountySubmissionSchema = z.object({
@@ -78,12 +86,6 @@ const BountySubmissionSchema = z.object({
rejectionNote: z.string().nullable(),
});
-export const BountySchemaExtended = BountySchema.extend({
- groups: z.array(GroupSchema.pick({ id: true })).nullable(),
- partners: z.number().default(0),
- submissions: z.record(z.nativeEnum(BountySubmissionStatus), z.number()),
-});
-
export const BountySubmissionExtendedSchema = z.object({
submission: BountySubmissionSchema.nullable(),
partner: EnrolledPartnerSchema.pick({
@@ -125,15 +127,6 @@ export const BountyWithPartnerDataSchema = BountySchema.extend({
}),
});
-export const BOUNTIES_MAX_PAGE_SIZE = 100;
-
-export const getBountiesQuerySchema = z
- .object({
- sortBy: z.enum(["createdAt"]).default("createdAt"),
- sortOrder: z.enum(["asc", "desc"]).default("desc"),
- })
- .merge(getPaginationQuerySchema({ pageSize: BOUNTIES_MAX_PAGE_SIZE }));
-
export const bountyStatsSchema = z.object({
id: z.string(),
submissions: z.number(),
diff --git a/package.json b/package.json
index f3aead635b..790341ed29 100644
--- a/package.json
+++ b/package.json
@@ -6,7 +6,7 @@
"build": "turbo build",
"dev": "turbo dev",
"lint": "turbo lint",
- "clean": "turbo clean",
+ "clean": "turbo clean && find . -name '.next' -type d -prune -exec rm -rf {} + 2>/dev/null || true",
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
"prettier-check": "prettier --check \"**/*.{ts,tsx,md}\"",
"publish-cli": "turbo build --filter='@dub/cli' && cd packages/cli && npm publish && cd ../../",