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.

show bounty awaiting review count on card

Steven Tey11d07ef0caa8
diff --git a/apps/web/app/(ee)/api/bounties/route.ts b/apps/web/app/(ee)/api/bounties/route.ts
index 8897f1b3b9..9d15317b78 100644
--- a/apps/web/app/(ee)/api/bounties/route.ts
+++ b/apps/web/app/(ee)/api/bounties/route.ts
@@ -32,7 +32,8 @@ export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
- const { partnerId } = getBountiesQuerySchema.parse(searchParams);
+ const { partnerId, includeSubmissionsCount } =
+ getBountiesQuerySchema.parse(searchParams);
const programEnrollment = partnerId
? await getProgramEnrollmentOrThrow({
@@ -44,56 +45,87 @@ export const GET = withWorkspace(
})
: null;
- const bounties = await prisma.bounty.findMany({
- where: {
- programId,
- // Filter only bounties the specified partner is eligible for
- ...(programEnrollment && {
- OR: [
- {
- groups: {
- none: {},
+ const [bounties, allBountiesSubmissionsCount] = await Promise.all([
+ prisma.bounty.findMany({
+ where: {
+ programId,
+ // Filter only bounties the specified partner is eligible for
+ ...(programEnrollment && {
+ OR: [
+ {
+ groups: {
+ none: {},
+ },
},
- },
- {
- groups: {
- some: {
- groupId:
- programEnrollment.groupId ||
- programEnrollment.program.defaultGroupId,
+ {
+ groups: {
+ some: {
+ groupId:
+ programEnrollment.groupId ||
+ programEnrollment.program.defaultGroupId,
+ },
},
},
+ ],
+ }),
+ },
+ include: {
+ groups: {
+ select: {
+ groupId: true,
},
- ],
- }),
- },
- include: {
- groups: {
- select: {
- groupId: true,
},
},
- _count: {
- select: {
- submissions: {
- where: {
- status: {
- in: ["submitted", "approved"],
- },
+ }),
+ includeSubmissionsCount
+ ? prisma.bountySubmission.groupBy({
+ by: ["bountyId", "status"],
+ where: {
+ programId,
+ status: {
+ in: ["submitted", "approved"],
},
},
- },
- },
- },
- });
+ _count: {
+ status: true,
+ },
+ })
+ : null,
+ ]);
+
+ const aggregateSubmissionsCountForBounty = (bountyId: string) => {
+ if (!allBountiesSubmissionsCount) {
+ return null;
+ }
+ const bountySubmissions = allBountiesSubmissionsCount.filter(
+ (s) => s.bountyId === bountyId,
+ );
+ const total = bountySubmissions.reduce(
+ (sum, s) => sum + s._count.status,
+ 0,
+ );
+ const submitted =
+ bountySubmissions.find((s) => s.status === "submitted")?._count
+ .status ?? 0;
+ const approved =
+ bountySubmissions.find((s) => s.status === "approved")?._count.status ??
+ 0;
+ return {
+ total,
+ submitted,
+ approved,
+ };
+ };
- const data = bounties.map((bounty) =>
- BountyListSchema.parse({
+ const data = bounties.map((bounty) => {
+ return BountyListSchema.parse({
...bounty,
groups: bounty.groups.map(({ groupId }) => ({ id: groupId })),
- submissionsCount: bounty._count.submissions,
- }),
- );
+ ...(allBountiesSubmissionsCount && {
+ submissionsCountData: aggregateSubmissionsCountForBounty(bounty.id),
+ }),
+ });
+ });
return NextResponse.json(data);
},
@@ -181,8 +213,7 @@ export const POST = withWorkspace(
data: {
id: createId({ prefix: "wf_" }),
programId,
- trigger:
- WORKFLOW_ATTRIBUTE_TRIGGER[performanceCondition.attribute],
+ trigger: WORKFLOW_ATTRIBUTE_TRIGGER[performanceCondition.attribute],
triggerConditions: [performanceCondition],
actions: [action],
},
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 67a782a94a..45e64139c2 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
@@ -27,6 +27,10 @@ export function BountyInfo() {
?.reduce((acc, curr) => acc + curr.count, 0);
}, [submissionsCount]);
+ const readyForReviewSubmissions = useMemo(() => {
+ return submissionsCount?.find((s) => s.status === "submitted")?.count ?? 0;
+ }, [submissionsCount]);
+
if (loading) {
return <BountyInfoSkeleton />;
}
@@ -78,8 +82,17 @@ export function BountyInfo() {
<span className="font-medium text-neutral-700">
{nFormatter(bounty.partnersCount, { full: true })}
</span>{" "}
- {pluralize("partner", bounty.partnersCount ?? 0)}{" "}
- {bounty.type === "performance" ? "completed" : "submitted"}
+ {pluralize("submission", bounty.partnersCount ?? 0)}
+ {readyForReviewSubmissions > 0 && (
+ <>
+ {" "}
+ (
+ <span className="font-medium text-neutral-700">
+ {nFormatter(readyForReviewSubmissions, { full: true })}
+ </span>{" "}
+ awaiting review)
+ </>
+ )}
</div>
</div>
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
index bf38973e23..2d467444b8 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/[bountyId]/bounty-submissions-table.tsx
@@ -3,6 +3,10 @@
import { PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES } from "@/lib/api/bounties/performance-bounty-scope-attributes";
import { isCurrencyAttribute } from "@/lib/api/workflows/utils";
import useBounty from "@/lib/swr/use-bounty";
+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 { BountySubmissionProps } from "@/lib/types";
@@ -29,6 +33,7 @@ import {
formatDate,
nFormatter,
} from "@dub/utils";
+import { BountySubmissionStatus } from "@prisma/client";
import { Row } from "@tanstack/react-table";
import { useParams } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
@@ -55,16 +60,14 @@ export function BountySubmissionsTable() {
// Decide the columns to show based on the bounty type
const showColumns = useMemo(() => {
- const columns = ["partner", "group", "status"];
+ const columns = ["partner", "group", "status", "completedAt", "reviewedAt"];
if (!bounty) {
return columns;
}
- if (bounty.type === "submission") {
- columns.push(...["createdAt", "reviewedAt"]);
- } else if (bounty.type === "performance") {
- columns.push(...["completedAt", "performanceMetrics"]);
+ if (bounty.type === "performance") {
+ columns.push("performanceMetrics");
}
return columns;
@@ -81,11 +84,13 @@ export function BountySubmissionsTable() {
? PERFORMANCE_BOUNTY_SCOPE_ATTRIBUTES[performanceCondition.attribute]
: "Progress";
- const sortBy =
- searchParams.get("sortBy") || bounty?.type === "performance"
- ? metricColumnId
- : "createdAt";
- const sortOrder = searchParams.get("sortOrder") === "asc" ? "asc" : "desc";
+ const status = (searchParams.get("status") ||
+ "submitted") as BountySubmissionStatus;
+ const sortBy = searchParams.get("sortBy") || "completedAt";
+ const sortOrder = searchParams.get("sortOrder") === "desc" ? "desc" : "asc";
+
+ const { submissionsCount } =
+ useBountySubmissionsCount<SubmissionsCountByStatus[]>();
const { filters, activeFilters, onSelect, onRemove, onRemoveAll } =
useBountySubmissionFilters({ bounty });
@@ -100,6 +105,8 @@ export function BountySubmissionsTable() {
{
workspaceId,
sortBy,
+ sortOrder,
+ status,
},
{ exclude: ["submissionId"] },
)}`
@@ -216,23 +223,23 @@ export function BountySubmissionsTable() {
]
: []),
- ...(showColumns.includes("createdAt")
+ ...(showColumns.includes("completedAt")
? [
{
- id: "createdAt",
- header: "Submitted",
+ id: "completedAt",
+ header:
+ bounty?.type === "performance" ? "Completed" : "Submitted",
cell: ({ row }) => {
- if (!row.original.createdAt || row.original.status === "draft")
- return "-";
+ if (!row.original.completedAt) return "-";
return (
<TimestampTooltip
- timestamp={row.original.createdAt}
+ timestamp={row.original.completedAt}
side="left"
delayDuration={150}
>
<span>
- {formatDate(row.original.createdAt, { month: "short" })}
+ {formatDate(row.original.completedAt, { month: "short" })}
</span>
</TimestampTooltip>
);
@@ -241,22 +248,6 @@ export function BountySubmissionsTable() {
]
: []),
- ...(showColumns.includes("completedAt")
- ? [
- {
- id: "completedAt",
- header: "Completed",
- accessorFn: (d: BountySubmissionProps) => {
- if (!d.completedAt) {
- return "-";
- }
-
- return formatDate(d.completedAt, { month: "short" });
- },
- },
- ]
- : []),
-
...(showColumns.includes("performanceMetrics")
? [
{
@@ -357,10 +348,12 @@ export function BountySubmissionsTable() {
scroll: false,
});
},
- sortableColumns:
- bounty?.type === "submission"
- ? ["createdAt"]
- : ["createdAt", "leads", "conversions", "saleAmount", "commissions"],
+ sortableColumns: [
+ "completedAt",
+ ...(bounty?.type === "performance"
+ ? ["leads", "conversions", "saleAmount", "commissions"]
+ : []),
+ ],
sortBy,
sortOrder,
onSortChange: ({ sortBy, sortOrder }) =>
@@ -377,7 +370,7 @@ export function BountySubmissionsTable() {
thClassName: "border-l-0",
tdClassName: "border-l-0",
resourceName: (p) => `submission${p ? "s" : ""}`,
- rowCount: submissions?.length || 0,
+ rowCount: submissionsCount?.find((s) => s.status === status)?.count || 0,
loading: isLoading || isBountyLoading,
error: error ? "Failed to load bounty submissions" : undefined,
});
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 9daea20c34..1f27590a3b 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
@@ -1,6 +1,10 @@
"use client";
import { mutatePrefix } from "@/lib/swr/mutate";
+import {
+ SubmissionsCountByStatus,
+ useBountySubmissionsCount,
+} from "@/lib/swr/use-bounty-submissions-count";
import useWorkspace from "@/lib/swr/use-workspace";
import { BountyExtendedProps } from "@/lib/types";
import { useConfirmModal } from "@/ui/modals/confirm-modal";
@@ -8,7 +12,7 @@ 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 { useState } from "react";
+import { useMemo, useState } from "react";
import { toast } from "sonner";
import { useBountySheet } from "./add-edit-bounty-sheet";
@@ -27,6 +31,15 @@ export function BountyActionButton({
const { id: workspaceId } = useWorkspace();
const { setShowCreateBountySheet, BountySheet } = useBountySheet({ bounty });
+ const { submissionsCount } = useBountySubmissionsCount<
+ SubmissionsCountByStatus[]
+ >({
+ enabled: Boolean(bounty),
+ });
+ const totalSubmissions = useMemo(() => {
+ return submissionsCount?.reduce((acc, curr) => acc + curr.count, 0) ?? 0;
+ }, [submissionsCount]);
+
const { confirmModal: deleteModal, setShowConfirmModal: setShowDeleteModal } =
useConfirmModal({
title: "Delete bounty",
@@ -86,7 +99,7 @@ export function BountyActionButton({
setShowDeleteModal(true);
}}
disabledTooltip={
- bounty.submissionsCount > 0
+ totalSubmissions > 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 663abec290..5b15bf5286 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
@@ -48,13 +48,16 @@ export function BountyCard({ bounty }: { bounty: BountyListProps }) {
<BountyThumbnailImage bounty={bounty} />
</div>
- {/* {bounty.pendingSubmissions > 0 ? (
- <SubmissionsCountBadge count={bounty.pendingSubmissions} />
- ) : null} */}
-
{bounty.endsAt && new Date(bounty.endsAt) < new Date() ? (
<BountyEndedBadge endsAt={bounty.endsAt} />
) : null}
+
+ {bounty.submissionsCountData &&
+ bounty.submissionsCountData.submitted > 0 ? (
+ <SubmissionsCountBadge
+ count={bounty.submissionsCountData.submitted}
+ />
+ ) : null}
</div>
<div className="flex flex-col gap-1.5">
@@ -85,12 +88,14 @@ export function BountyCard({ bounty }: { bounty: BountyListProps }) {
<div className="text-content-subtle flex items-center gap-2 text-sm font-medium">
<Users className="size-3.5" />
<div className="h-5">
- {bounty.submissionsCount === totalPartnersForBounty ? (
+ {bounty.submissionsCountData?.total === totalPartnersForBounty ? (
<>All</>
) : (
<>
<span className="text-content-default">
- {nFormatter(bounty.submissionsCount, { full: true })}
+ {nFormatter(bounty.submissionsCountData?.total ?? 0, {
+ full: true,
+ })}
</span>{" "}
of
</>
@@ -122,7 +127,8 @@ 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)}
+ {nFormatter(count, { full: true })} {pluralize("submission", count)}{" "}
+ awaiting review
</div>
</div>
);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-list.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-list.tsx
index a7cbcae507..b5f9379ba0 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-list.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/bounty-list.tsx
@@ -19,7 +19,9 @@ export function BountyList() {
isLoading,
error,
} = useSWR<BountyListProps[]>(
- workspaceId ? `/api/bounties?workspaceId=${workspaceId}` : null,
+ workspaceId
+ ? `/api/bounties?${new URLSearchParams({ workspaceId, includeSubmissionsCount: "true" }).toString()}`
+ : null,
fetcher,
{
keepPreviousData: true,
diff --git a/apps/web/lib/api/bounties/get-bounty-submissions.ts b/apps/web/lib/api/bounties/get-bounty-submissions.ts
index 5f41689b3b..7be2e0e9a5 100644
--- a/apps/web/lib/api/bounties/get-bounty-submissions.ts
+++ b/apps/web/lib/api/bounties/get-bounty-submissions.ts
@@ -18,7 +18,7 @@ export async function getBountySubmissions({
const submissions = await prisma.bountySubmission.findMany({
where: {
bountyId,
- ...(status ? { status } : { status: "submitted" }),
+ status,
...(groupId && {
programEnrollment: {
groupId,
@@ -32,7 +32,8 @@ export async function getBountySubmissions({
programEnrollment: true,
},
orderBy: {
- [sortBy === "createdAt" ? "createdAt" : "performanceCount"]: sortOrder,
+ [sortBy === "completedAt" ? "completedAt" : "performanceCount"]:
+ sortOrder,
},
skip: (page - 1) * pageSize,
take: pageSize,
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 2ec1c52bda..a368273314 100644
--- a/apps/web/lib/api/bounties/get-bounty-with-details.ts
+++ b/apps/web/lib/api/bounties/get-bounty-with-details.ts
@@ -58,17 +58,7 @@ export const getBountyWithDetails = async ({
WHERE bountyId = b.id
),
JSON_ARRAY()
- ) AS groups,
-
- -- Bounty submissions total count
- COALESCE(
- (
- SELECT COUNT(*)
- FROM BountySubmission
- WHERE bountyId = b.id
- ),
- 0
- ) AS submissions
+ ) AS groups
FROM Bounty b
LEFT JOIN Workflow wf ON wf.id = b.workflowId
@@ -103,6 +93,5 @@ export const getBountyWithDetails = async ({
performanceCondition,
groups: bounty.groups.filter((group) => group !== null) ?? [],
partnersCount: Number(bounty.partners),
- submissionsCount: Number(bounty.submissions),
};
};
diff --git a/apps/web/lib/zod/schemas/bounties.ts b/apps/web/lib/zod/schemas/bounties.ts
index 37dd430f03..5232099bc9 100644
--- a/apps/web/lib/zod/schemas/bounties.ts
+++ b/apps/web/lib/zod/schemas/bounties.ts
@@ -8,7 +8,7 @@ import {
import { z } from "zod";
import { CommissionSchema } from "./commissions";
import { GroupSchema } from "./groups";
-import { getPaginationQuerySchema } from "./misc";
+import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";
import { EnrolledPartnerSchema } from "./partners";
import { UserSchema } from "./users";
import { parseDateSchema } from "./utils";
@@ -29,7 +29,7 @@ export const REJECT_BOUNTY_SUBMISSION_REASONS = {
} as const;
export const BOUNTY_SUBMISSIONS_SORT_BY_COLUMNS = [
- "createdAt",
+ "completedAt",
"leads",
"conversions",
"saleAmount",
@@ -108,14 +108,21 @@ export const BountySchema = z.object({
export const getBountiesQuerySchema = z.object({
partnerId: z.string().optional(),
+ includeSubmissionsCount: booleanQuerySchema.optional().default("false"),
});
// used in GET /bounties
export const BountyListSchema = BountySchema.extend({
- submissionsCount: z.number().default(0),
+ submissionsCountData: z
+ .object({
+ total: z.number().default(0),
+ submitted: z.number().default(0),
+ approved: z.number().default(0),
+ })
+ .optional(),
});
-export const BountySchemaExtended = BountyListSchema.extend({
+export const BountySchemaExtended = BountySchema.extend({
partnersCount: z.number().default(0),
});
@@ -170,8 +177,8 @@ export const rejectBountySubmissionSchema = z.object({
export const getBountySubmissionsQuerySchema = z
.object({
- sortBy: z.enum(BOUNTY_SUBMISSIONS_SORT_BY_COLUMNS).default("createdAt"),
- sortOrder: z.enum(["asc", "desc"]).default("desc"),
+ sortBy: z.enum(BOUNTY_SUBMISSIONS_SORT_BY_COLUMNS).default("completedAt"),
+ sortOrder: z.enum(["asc", "desc"]).default("asc"),
status: z.nativeEnum(BountySubmissionStatus).optional(),
groupId: z.string().optional(),
})