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.

a separate endpoint to pull sales data

Kiran K52909db04ce6
diff --git a/apps/web/lib/actions/partners/create-manual-payout.ts b/apps/web/lib/actions/partners/create-manual-payout.ts
index fb3ca2f49b..60da5c0f13 100644
--- a/apps/web/lib/actions/partners/create-manual-payout.ts
+++ b/apps/web/lib/actions/partners/create-manual-payout.ts
@@ -9,17 +9,23 @@ import { createManualPayoutSchema } from "@/lib/zod/schemas/payouts";
import { Payout } from "@prisma/client";
import { authActionClient } from "../safe-action";
+const schema = createManualPayoutSchema.refine(
+ (data) => {
+ return data.type === "custom" || (data.start && data.end);
+ },
+ {
+ message: "Please select a date range",
+ path: ["start"],
+ },
+);
+
export const createManualPayoutAction = authActionClient
- .schema(createManualPayoutSchema)
+ .schema(schema)
.action(async ({ parsedInput, ctx }) => {
const { workspace } = ctx;
const { programId, partnerId, start, end, type, amount, description } =
parsedInput;
- if (["clicks", "leads", "sales"].includes(type) && (!start || !end)) {
- throw new Error("Please select a date range to create a payout.");
- }
-
const [_, programEnrollment] = await Promise.all([
getProgramOrThrow({
workspaceId: workspace.id,
@@ -46,17 +52,27 @@ export const createManualPayoutAction = authActionClient
let payout: Payout | undefined = undefined;
+ // Create a payout for sales
+ if (type === "sales") {
+ payout = await createSalesPayout({
+ programId,
+ partnerId,
+ periodStart: start!,
+ periodEnd: end!,
+ });
+ }
+
// Create a payout for clicks, leads, and custom events
- if (["clicks", "leads", "custom"].includes(type)) {
+ else {
let quantity: number | undefined = undefined;
if (type === "clicks" || type === "leads") {
const count = await getAnalytics({
linkId: programEnrollment.linkId,
- event: type as any,
+ event: type,
groupBy: "count",
- start: start as Date,
- end: end as Date,
+ start,
+ end,
});
quantity = count[type];
@@ -75,23 +91,13 @@ export const createManualPayoutAction = authActionClient
quantity,
amount: amountInCents,
total: amountInCents + fee,
- periodEnd: end as Date,
- periodStart: start as Date,
+ periodStart: start,
+ periodEnd: end,
description,
},
});
}
- // Create a payout for sales
- else if (type === "sales") {
- payout = await createSalesPayout({
- programId,
- partnerId,
- periodStart: start as Date,
- periodEnd: end as Date,
- });
- }
-
if (!payout) {
throw new Error("Failed to create payout. Please try again.");
}
diff --git a/apps/web/lib/zod/schemas/payouts.ts b/apps/web/lib/zod/schemas/payouts.ts
index d78ae40b71..9a81c2dc85 100644
--- a/apps/web/lib/zod/schemas/payouts.ts
+++ b/apps/web/lib/zod/schemas/payouts.ts
@@ -6,12 +6,12 @@ export const createManualPayoutSchema = z.object({
workspaceId: z.string(),
programId: z.string(),
partnerId: z.string({ required_error: "Please select a partner" }),
- start: parseDateSchema.nullable(),
- end: parseDateSchema.nullable(),
- type: z.nativeEnum(PayoutType),
+ start: parseDateSchema.optional(),
+ end: parseDateSchema.optional(),
amount: z.preprocess(
(val) => parseFloat(val as string),
z.number().default(0),
),
+ type: z.nativeEnum(PayoutType),
description: z.string().max(5000).nullable(),
-});
+})
\ No newline at end of file
diff --git a/apps/web/ui/partners/create-payout-sheet.tsx b/apps/web/ui/partners/create-payout-sheet.tsx
index 0d0b7e65ae..ba5c3dae4d 100644
--- a/apps/web/ui/partners/create-payout-sheet.tsx
+++ b/apps/web/ui/partners/create-payout-sheet.tsx
@@ -24,6 +24,7 @@ import {
formatDate,
} from "@dub/utils";
import { nFormatter } from "@dub/utils/src/functions";
+import { zodResolver } from "@hookform/resolvers/zod";
import { PayoutType } from "@prisma/client";
import {
endOfMonth,
@@ -53,14 +54,28 @@ interface CreatePayoutSheetProps {
setIsOpen: Dispatch<SetStateAction<boolean>>;
}
-const schema = createManualPayoutSchema.pick({
- partnerId: true,
- type: true,
- start: true,
- end: true,
- amount: true,
- description: true,
-});
+const schema = createManualPayoutSchema
+ .pick({
+ partnerId: true,
+ type: true,
+ amount: true,
+ description: true,
+ })
+ .and(
+ z.object({
+ start: z.date().optional(),
+ end: z.date().optional(),
+ }),
+ )
+ .refine(
+ (data) => {
+ return data.type === "custom" || (data.start && data.end);
+ },
+ {
+ message: "Please select a date range",
+ path: ["start"],
+ },
+ );
type FormData = z.infer<typeof schema>;
@@ -76,9 +91,10 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
handleSubmit,
watch,
setValue,
- formState: { errors },
clearErrors,
+ formState: { errors },
} = useForm<FormData>({
+ resolver: zodResolver(schema),
defaultValues: {
type: "sales",
amount:
@@ -88,11 +104,7 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
},
});
- const partnerId = watch("partnerId");
- const payoutType = watch("type");
- const start = watch("start");
- const end = watch("end");
- const amount = watch("amount");
+ const { partnerId, type: payoutType, start, end, amount } = watch();
const partnerOptions = useMemo(() => {
return partners?.map((partner) => ({
@@ -121,7 +133,9 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
undefined,
{ revalidate: true },
);
+
const payoutId = res.data?.id;
+
if (payoutId) {
queryParams({ set: { payoutId } });
}
@@ -137,8 +151,8 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
...data,
workspaceId,
programId: program.id,
- start: data.start ? data.start.toISOString() : null,
- end: data.end ? data.end.toISOString() : null,
+ start: data.start?.toISOString(),
+ end: data.end?.toISOString(),
});
}
};
@@ -156,8 +170,8 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
workspaceId: workspaceId!,
event: payoutType,
linkId: selectedPartner.link.id,
- start: start?.toISOString() || "",
- end: end?.toISOString() || "",
+ start: start?.toISOString(),
+ end: end?.toISOString(),
}).toString()}`,
fetcher,
);
@@ -173,8 +187,8 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
`/api/programs/${program?.id}/sales/amount?${new URLSearchParams({
workspaceId: workspaceId!,
partnerId: selectedPartner.id,
- start: start?.toISOString() || "",
- end: end?.toISOString() || "",
+ start: start?.toISOString(),
+ end: end?.toISOString(),
}).toString()}`,
fetcher,
);
@@ -374,12 +388,15 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
}
onChange={(range, preset) => {
if (preset) {
- setValue("start", preset.dateRange.from!);
- setValue("end", preset.dateRange.to!);
+ setValue("start", preset.dateRange.from);
+ setValue("end", preset.dateRange.to);
} else if (range) {
- setValue("start", range.from!);
- setValue("end", range.to!);
+ setValue("start", range.from);
+ setValue("end", range.to);
}
+
+ clearErrors("start");
+ clearErrors("end");
}}
align="end"
presets={[
@@ -416,7 +433,11 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
},
},
]}
+ hasError={!!(errors.start || errors.end)}
/>
+ {(errors.start || errors.end) && (
+ <p className="text-xs text-red-600">{errors.start?.message}</p>
+ )}
</div>
<div className="flex flex-col gap-2">
@@ -434,6 +455,10 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
setValue("type", type);
+ if (type === "custom") {
+ clearErrors(["start", "end"]);
+ }
+
if (
type === "sales" &&
program?.commissionAmount &&
@@ -441,7 +466,7 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
) {
setValue("amount", program.commissionAmount / 100);
} else {
- // @ts-expect-error
+ // @ts-ignore
setValue("amount", null);
}
}}
@@ -473,9 +498,12 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
"pr-[6.5rem]",
payoutType === "custom" && "pr-12",
!isPercentBased && "pl-6",
+ errors.amount &&
+ "border-red-600 focus:border-red-500 focus:ring-red-600",
)}
{...register("amount", {
required: true,
+ valueAsNumber: true,
})}
autoComplete="off"
placeholder="5"
@@ -536,7 +564,7 @@ function CreatePayoutSheetContent({ setIsOpen }: CreatePayoutSheetProps) {
text="Create payout"
className="w-fit"
loading={isExecuting}
- disabled={!partnerId || isExecuting}
+ disabled={isExecuting || isValidating}
/>
</div>
</div>