The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Extract throwIfApplicationBlocked into its own module and add unit tests
Kiran K963adde437dd
diff --git a/apps/web/lib/actions/partners/create-program-application.ts b/apps/web/lib/actions/partners/create-program-application.tsindex 14c51f9290..d8d2b15b1e 100644--- a/apps/web/lib/actions/partners/create-program-application.ts+++ b/apps/web/lib/actions/partners/create-program-application.ts@@ -20,6 +20,7 @@ import {formatWebsiteAndSocialsFields,} from "@/lib/partners/format-application-form-data";import { prisma } from "@/lib/prisma";+import { throwIfApplicationBlocked } from "@/lib/program-applications/throw-if-application-blocked";import {ProgramApplicationFormData,ProgramApplicationFormDataWithValues,@@ -33,7 +34,6 @@ import {} from "@/lib/zod/schemas/program-application";import { programApplicationFormWebsiteAndSocialsFieldWithValueSchema } from "@/lib/zod/schemas/program-application-form";import { createProgramApplicationSchema } from "@/lib/zod/schemas/programs";-import { STANDARD_REAPPLICATION_DAYS } from "@dub/utils";import {Partner,PartnerGroup,@@ -249,78 +249,6 @@ export const createProgramApplicationAction = actionClientreturn application;});-function throwIfCannotApply({- enrollment,- groupId,- rejectedAt,-}: {- enrollment:- | Pick<ProgramEnrollment, "status" | "groupId" | "reapplicationTimeframe">- | null- | undefined;- groupId: string; // New group ID the partner is applying to- rejectedAt?: Date | null; // Last application rejection date-}) {- if (!enrollment) {- return;- }-- switch (enrollment.status) {- case ProgramEnrollmentStatus.pending:- throw new Error(- "You have an existing application for this program. Please wait for it to be reviewed.",- );- case ProgramEnrollmentStatus.rejected:- if (enrollment.reapplicationTimeframe === ReapplicationTimeframe.never) {- throw new Error("You cannot reapply to this program.");- }-- // TODO: Improve this message to use the absolute day remaining.- if (- enrollment.reapplicationTimeframe === ReapplicationTimeframe.standard- ) {- throw new Error(- `You can reapply to this program after ${STANDARD_REAPPLICATION_DAYS} days.`,- );- }-- // Instant reapplication timeframe will be reapplied immediately, so we don't need to handle it here.- return;- case ProgramEnrollmentStatus.invited:- throw new Error("You have a pending invitation to join this program.");- case ProgramEnrollmentStatus.declined:- throw new Error(- "You have declined your invitation to join this program. Please contact program owner to re-invite you.",- );- case ProgramEnrollmentStatus.approved:- if (enrollment.groupId === groupId) {- throw new Error("You're already in this group.");- }-- if (- !rejectedAt ||- enrollment.reapplicationTimeframe === ReapplicationTimeframe.instant- ) {- return;- }-- if (enrollment.reapplicationTimeframe === ReapplicationTimeframe.never) {- throw new Error("You cannot reapply to this program.");- }-- if (addDays(rejectedAt, STANDARD_REAPPLICATION_DAYS) > new Date()) {- throw new Error(- `You can reapply to this program after ${STANDARD_REAPPLICATION_DAYS} days.`,- );- }- return;- default:- throw new Error(- `You cannot apply to this program again because your enrollment is ${enrollment.status}.`,- );- }-}-async function createApplicationAndEnrollment({workspace,program,@@ -339,7 +267,7 @@ async function createApplicationAndEnrollment({data: z.infer<typeof createProgramApplicationSchema>;inAppApplication?: boolean;}) {- throwIfCannotApply({+ throwIfApplicationBlocked({enrollment: partner.programs.find((p) => p.programId === program.id),groupId: group.id,});@@ -415,7 +343,7 @@ async function createApplicationAndEnrollment({rejectedAt = latestApplicationRejection?.reviewedAt ?? null;}- throwIfCannotApply({+ throwIfApplicationBlocked({enrollment,groupId: group.id,rejectedAt,diff --git a/apps/web/lib/program-applications/throw-if-application-blocked.ts b/apps/web/lib/program-applications/throw-if-application-blocked.tsnew file mode 100644index 0000000000..b176433f08--- /dev/null+++ b/apps/web/lib/program-applications/throw-if-application-blocked.ts@@ -0,0 +1,86 @@+import { STANDARD_REAPPLICATION_DAYS } from "@dub/utils";+import {+ ProgramEnrollment,+ ProgramEnrollmentStatus,+ ReapplicationTimeframe,+} from "@prisma/client";+import { addDays } from "date-fns";++/**+ * Throws if the partner's existing enrollment prevents a new application to `groupId`.+ *+ * Approved partners applying to another group are held to the stored+ * `reapplicationTimeframe`, measured from `rejectedAt` (the latest rejected+ * application's `reviewedAt`). Omit `rejectedAt` to skip that window.+ */+export function throwIfApplicationBlocked({+ enrollment,+ groupId,+ rejectedAt,+}: {+ enrollment:+ | Pick<ProgramEnrollment, "status" | "groupId" | "reapplicationTimeframe">+ | null+ | undefined;+ groupId: string; // New group ID the partner is applying to+ rejectedAt?: Date | null; // Last application rejection date+}) {+ if (!enrollment) {+ return;+ }++ switch (enrollment.status) {+ case ProgramEnrollmentStatus.pending:+ throw new Error(+ "You have an existing application for this program. Please wait for it to be reviewed.",+ );+ case ProgramEnrollmentStatus.rejected:+ if (enrollment.reapplicationTimeframe === ReapplicationTimeframe.never) {+ throw new Error("You cannot reapply to this program.");+ }++ // TODO: Improve this message to use the absolute day remaining.+ if (+ enrollment.reapplicationTimeframe === ReapplicationTimeframe.standard+ ) {+ throw new Error(+ `You can reapply to this program after ${STANDARD_REAPPLICATION_DAYS} days.`,+ );+ }++ // Instant reapplication timeframe will be reapplied immediately, so we don't need to handle it here.+ return;+ case ProgramEnrollmentStatus.invited:+ throw new Error("You have a pending invitation to join this program.");+ case ProgramEnrollmentStatus.declined:+ throw new Error(+ "You have declined your invitation to join this program. Please contact program owner to re-invite you.",+ );+ case ProgramEnrollmentStatus.approved:+ if (enrollment.groupId === groupId) {+ throw new Error("You're already in this group.");+ }++ if (+ !rejectedAt ||+ enrollment.reapplicationTimeframe === ReapplicationTimeframe.instant+ ) {+ return;+ }++ if (enrollment.reapplicationTimeframe === ReapplicationTimeframe.never) {+ throw new Error("You cannot reapply to this program.");+ }++ if (addDays(rejectedAt, STANDARD_REAPPLICATION_DAYS) > new Date()) {+ throw new Error(+ `You can reapply to this program after ${STANDARD_REAPPLICATION_DAYS} days.`,+ );+ }+ return;+ default:+ throw new Error(+ `You cannot apply to this program again because your enrollment is ${enrollment.status}.`,+ );+ }+}diff --git a/apps/web/tests/partners/throw-if-application-blocked.test.ts b/apps/web/tests/partners/throw-if-application-blocked.test.tsnew file mode 100644index 0000000000..96e013b173--- /dev/null+++ b/apps/web/tests/partners/throw-if-application-blocked.test.ts@@ -0,0 +1,261 @@+import { throwIfApplicationBlocked } from "@/lib/program-applications/throw-if-application-blocked";+import { STANDARD_REAPPLICATION_DAYS } from "@dub/utils";+import {+ ProgramEnrollmentStatus,+ ReapplicationTimeframe,+} from "@prisma/client";+import { addMinutes, subDays, subMinutes } from "date-fns";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const NOW = new Date("2026-06-15T12:00:00.000Z");+const TARGET_GROUP_ID = "grp_target";+const OTHER_GROUP_ID = "grp_other";++const PENDING_MESSAGE =+ "You have an existing application for this program. Please wait for it to be reviewed.";+const NEVER_MESSAGE = "You cannot reapply to this program.";+const STANDARD_MESSAGE = `You can reapply to this program after ${STANDARD_REAPPLICATION_DAYS} days.`;+const SAME_GROUP_MESSAGE = "You're already in this group.";++function enrollment(+ status: ProgramEnrollmentStatus,+ reapplicationTimeframe: ReapplicationTimeframe = ReapplicationTimeframe.standard,+ groupId: string | null = OTHER_GROUP_ID,+) {+ return { status, groupId, reapplicationTimeframe };+}++describe("throwIfApplicationBlocked", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it.each([null, undefined])("allows when enrollment is %s", (value) => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: value,+ groupId: TARGET_GROUP_ID,+ rejectedAt: subDays(NOW, 1),+ }),+ ).not.toThrow();+ });++ describe("pending", () => {+ it.each(Object.values(ReapplicationTimeframe))(+ "blocks with %s timeframe",+ (timeframe) => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(ProgramEnrollmentStatus.pending, timeframe),+ groupId: TARGET_GROUP_ID,+ }),+ ).toThrow(PENDING_MESSAGE);+ },+ );+ });++ describe("rejected", () => {+ it("blocks permanently with never timeframe", () => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(+ ProgramEnrollmentStatus.rejected,+ ReapplicationTimeframe.never,+ ),+ groupId: TARGET_GROUP_ID,+ }),+ ).toThrow(NEVER_MESSAGE);+ });++ it("blocks with standard timeframe regardless of rejectedAt", () => {+ for (const rejectedAt of [null, subDays(NOW, 1), subDays(NOW, 90)]) {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(+ ProgramEnrollmentStatus.rejected,+ ReapplicationTimeframe.standard,+ ),+ groupId: TARGET_GROUP_ID,+ rejectedAt,+ }),+ ).toThrow(STANDARD_MESSAGE);+ }+ });++ it("allows with instant timeframe", () => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(+ ProgramEnrollmentStatus.rejected,+ ReapplicationTimeframe.instant,+ ),+ groupId: TARGET_GROUP_ID,+ rejectedAt: subDays(NOW, 1),+ }),+ ).not.toThrow();+ });+ });++ it("blocks invited enrollments", () => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(ProgramEnrollmentStatus.invited),+ groupId: TARGET_GROUP_ID,+ }),+ ).toThrow("You have a pending invitation to join this program.");+ });++ it("blocks declined enrollments", () => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(ProgramEnrollmentStatus.declined),+ groupId: TARGET_GROUP_ID,+ }),+ ).toThrow(+ "You have declined your invitation to join this program. Please contact program owner to re-invite you.",+ );+ });++ it.each([+ ProgramEnrollmentStatus.banned,+ ProgramEnrollmentStatus.deactivated,+ ProgramEnrollmentStatus.archived,+ ])("blocks %s enrollments", (status) => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(status, ReapplicationTimeframe.instant),+ groupId: TARGET_GROUP_ID,+ }),+ ).toThrow(+ `You cannot apply to this program again because your enrollment is ${status}.`,+ );+ });++ describe("approved", () => {+ it.each(Object.values(ReapplicationTimeframe))(+ "blocks applying to the current group with %s timeframe",+ (timeframe) => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(+ ProgramEnrollmentStatus.approved,+ timeframe,+ TARGET_GROUP_ID,+ ),+ groupId: TARGET_GROUP_ID,+ rejectedAt: subDays(NOW, 1),+ }),+ ).toThrow(SAME_GROUP_MESSAGE);+ },+ );++ it.each(Object.values(ReapplicationTimeframe))(+ "allows another group without a rejection date (%s timeframe)",+ (timeframe) => {+ for (const rejectedAt of [undefined, null]) {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(+ ProgramEnrollmentStatus.approved,+ timeframe,+ ),+ groupId: TARGET_GROUP_ID,+ rejectedAt,+ }),+ ).not.toThrow();+ }+ },+ );++ it("allows another group immediately with instant timeframe", () => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(+ ProgramEnrollmentStatus.approved,+ ReapplicationTimeframe.instant,+ ),+ groupId: TARGET_GROUP_ID,+ rejectedAt: NOW,+ }),+ ).not.toThrow();+ });++ it("blocks another group with never timeframe, even after the standard window", () => {+ for (const rejectedAt of [subDays(NOW, 1), subDays(NOW, 90)]) {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(+ ProgramEnrollmentStatus.approved,+ ReapplicationTimeframe.never,+ ),+ groupId: TARGET_GROUP_ID,+ rejectedAt,+ }),+ ).toThrow(NEVER_MESSAGE);+ }+ });++ describe("standard timeframe", () => {+ const standardEnrollment = enrollment(+ ProgramEnrollmentStatus.approved,+ ReapplicationTimeframe.standard,+ );++ it.each([+ ["just now", NOW],+ ["1 day ago", subDays(NOW, 1)],+ [+ "1 minute before the window ends",+ addMinutes(subDays(NOW, STANDARD_REAPPLICATION_DAYS), 1),+ ],+ ])("blocks another group when rejected %s", (_label, rejectedAt) => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: standardEnrollment,+ groupId: TARGET_GROUP_ID,+ rejectedAt,+ }),+ ).toThrow(STANDARD_MESSAGE);+ });++ it.each([+ [+ "exactly when the window ends",+ subDays(NOW, STANDARD_REAPPLICATION_DAYS),+ ],+ [+ "1 minute after the window ends",+ subMinutes(subDays(NOW, STANDARD_REAPPLICATION_DAYS), 1),+ ],+ ["90 days ago", subDays(NOW, 90)],+ ])("allows another group when rejected %s", (_label, rejectedAt) => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: standardEnrollment,+ groupId: TARGET_GROUP_ID,+ rejectedAt,+ }),+ ).not.toThrow();+ });++ it("treats an enrollment with no group as another group", () => {+ expect(() =>+ throwIfApplicationBlocked({+ enrollment: enrollment(+ ProgramEnrollmentStatus.approved,+ ReapplicationTimeframe.standard,+ null,+ ),+ groupId: TARGET_GROUP_ID,+ rejectedAt: subDays(NOW, 1),+ }),+ ).toThrow(STANDARD_MESSAGE);+ });+ });+ });+});