Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions backend/src/api/fundraiser/__tests__/fundraiser.router.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import request from "supertest";
import express, { Express } from "express";
import { Decimal } from "decimal.js";
import type { ReferralOrder } from "common";
import fundraiserRouter from "../fundraiser.router";
import {
prismaMock,
mockSupabaseAuth,
createMockSupabaseUser,
} from "../../../__tests__";

const FUNDRAISER_ID = "423e4567-e89b-12d3-a456-426614174000";
const REFERRER_ID = "123e4567-e89b-12d3-a456-426614174000";

const createOrder = (
state: Pick<ReferralOrder, "paymentStatus" | "pickedUp">
): ReferralOrder => ({
...state,
items: [{ quantity: 2, item: { price: new Decimal("3.50") } }],
});

const createReferralRow = (referral: {
approved: boolean;
orders: ReferralOrder[];
}) => ({
id: "523e4567-e89b-12d3-a456-426614174000",
createdAt: new Date("2024-01-01T00:00:00.000Z"),
fundraiserId: FUNDRAISER_ID,
referrerId: REFERRER_ID,
...referral,
});

describe("Fundraiser Router", () => {
let app: Express;

beforeEach(() => {
app = express();
app.use(express.json());
app.use("/api/fundraiser", fundraiserRouter);
});

describe("GET /api/fundraiser/:id/referrals/me", () => {
const logInAsReferrer = () => {
mockSupabaseAuth.getUser.mockResolvedValue({
data: { user: createMockSupabaseUser(REFERRER_ID) },
});
};

const getOwnReferralCount = () =>
request(app)
.get(`/api/fundraiser/${FUNDRAISER_ID}/referrals/me`)
.set("Authorization", "Bearer valid-token");

it("should return 401 when the user is not logged in", async () => {
const response = await request(app)
.get(`/api/fundraiser/${FUNDRAISER_ID}/referrals/me`)
.expect(401);

expect(response.body.data).toBeUndefined();
});

it("should return 404 when the user is not a referrer for the fundraiser", async () => {
logInAsReferrer();
prismaMock.referral.findUnique.mockResolvedValue(null);

const response = await getOwnReferralCount().expect(404);

expect(response.body.message).toBe("Referral not found");
expect(response.body.data).toBeUndefined();
});

it("should return 403 without a count when the referral is still pending", async () => {
logInAsReferrer();
prismaMock.referral.findUnique.mockResolvedValue(
createReferralRow({
approved: false,
orders: [
createOrder({ paymentStatus: "CONFIRMED", pickedUp: true }),
],
})
);

const response = await getOwnReferralCount().expect(403);

expect(response.body.message).toBe("Referral is not approved");
expect(response.body.data).toBeUndefined();
});

it("should return only the number of paid or picked up orders for an approved referrer", async () => {
logInAsReferrer();
prismaMock.referral.findUnique.mockResolvedValue(
createReferralRow({
approved: true,
orders: [
createOrder({ paymentStatus: "CONFIRMED", pickedUp: false }),
createOrder({ paymentStatus: "CONFIRMED", pickedUp: true }),
createOrder({ paymentStatus: "UNVERIFIABLE", pickedUp: true }),
createOrder({ paymentStatus: "PENDING", pickedUp: true }),
createOrder({ paymentStatus: "PENDING", pickedUp: false }),
createOrder({ paymentStatus: "UNVERIFIABLE", pickedUp: false }),
],
})
);

const response = await getOwnReferralCount().expect(200);

expect(response.body.data).toEqual({ orderCount: 4 });
});

it("should return a count of zero for an approved referrer with no orders", async () => {
logInAsReferrer();
prismaMock.referral.findUnique.mockResolvedValue(
createReferralRow({ approved: true, orders: [] })
);

const response = await getOwnReferralCount().expect(200);

expect(response.body.data).toEqual({ orderCount: 0 });
});

it("should look up the referral of the logged-in user for the fundraiser in the URL", async () => {
logInAsReferrer();
prismaMock.referral.findUnique.mockResolvedValue(
createReferralRow({ approved: true, orders: [] })
);

await getOwnReferralCount().expect(200);

expect(prismaMock.referral.findUnique).toHaveBeenCalledWith(
expect.objectContaining({
where: {
fundraiserId_referrerId: {
fundraiserId: FUNDRAISER_ID,
referrerId: REFERRER_ID,
},
},
})
);
});
});
});
41 changes: 41 additions & 0 deletions backend/src/api/fundraiser/__tests__/referralQuantities.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Decimal } from "decimal.js";
import { getReferralQuantities } from "common";

describe("getReferralQuantities", () => {
it("should count and total only paid or picked up orders, and report every linked order", () => {
const quantities = getReferralQuantities([
{
paymentStatus: "CONFIRMED",
pickedUp: false,
items: [{ quantity: 2, item: { price: new Decimal("3.50") } }],
},
{
paymentStatus: "UNVERIFIABLE",
pickedUp: true,
items: [
{ quantity: 1, item: { price: new Decimal("10.00") } },
{ quantity: 3, item: { price: new Decimal("2.00") } },
],
},
{
paymentStatus: "PENDING",
pickedUp: false,
items: [{ quantity: 1, item: { price: new Decimal("10.00") } }],
},
]);

expect(quantities).toEqual({
orderCount: 2,
amountRaised: 23,
attributedOrderCount: 3,
});
});

it("should report zero for a referrer with no orders", () => {
expect(getReferralQuantities([])).toEqual({
orderCount: 0,
amountRaised: 0,
attributedOrderCount: 0,
});
});
});
34 changes: 34 additions & 0 deletions backend/src/api/fundraiser/fundraiser.handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
getReferral,
approveReferral,
deleteReferral,
getReferralWithOrders,
getFundraiserItemsWithAvailability,
} from "./fundraiser.services";
import {
Expand All @@ -48,7 +49,9 @@ import {
CreatePickupEventBody,
UpdatePickupEventBody,
ReferralSchema,
ReferralCountSchema,
ItemWithAvailabilitySchema,
getReferralQuantities,
} from "common";
import { getOrganization } from "../organization/organization.services";
import { z } from "zod";
Expand Down Expand Up @@ -887,6 +890,37 @@ export const deleteReferralHandler = async (
res.status(200).json({ message: "Referral deleted successfully" });
};

export const getOwnReferralCountHandler = async (
req: Request<FundraiserRouteParams, any, {}, {}>,
res: Response
) => {
const referral = await getReferralWithOrders({
fundraiserId: req.params.id,
referrerId: res.locals.user!.id,
});
if (!referral) {
res.status(404).json({ message: "Referral not found" });
return;
}

if (!referral.approved) {
res.status(403).json({ message: "Referral is not approved" });
return;
}

const parsedCount = ReferralCountSchema.safeParse(
getReferralQuantities(referral.orders)
);
if (!parsedCount.success) {
res.status(500).json({ message: "Couldn't parse referral count" });
return;
}

res
.status(200)
.json({ message: "Referral count retrieved", data: parsedCount.data });
};

export const getFundraiserItemsAvailabilityHandler = async (
req: Request<FundraiserRouteParams, any, {}, {}>,
res: Response
Expand Down
8 changes: 8 additions & 0 deletions backend/src/api/fundraiser/fundraiser.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
createReferralHandler,
approveReferralHandler,
deleteReferralHandler,
getOwnReferralCountHandler,
getFundraiserItemsAvailabilityHandler,
} from "./fundraiser.handlers";
import { authenticate } from "../../middleware/authenticate";
Expand Down Expand Up @@ -163,6 +164,13 @@ fundraiserRouter.get(
asyncHandler(getFundraiserAnalyticsHandler)
);

fundraiserRouter.get(
"/:id/referrals/me",
validate({ params: FundraiserRouteParams }),
authenticate,
asyncHandler(getOwnReferralCountHandler)
);

// Create a referral request
fundraiserRouter.post(
"/:id/referrals",
Expand Down
23 changes: 23 additions & 0 deletions backend/src/api/fundraiser/fundraiser.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,29 @@ export const deleteReferral = async (referralId: string) => {
return referral;
};

export const getReferralWithOrders = async (referralKey: {
fundraiserId: string;
referrerId: string;
}) => {
const referral = await prisma.referral.findUnique({
where: { fundraiserId_referrerId: referralKey },
select: {
approved: true,
orders: {
select: {
paymentStatus: true,
pickedUp: true,
items: {
select: { quantity: true, item: { select: { price: true } } },
},
},
},
},
});

return referral;
};

export const getFundraiserItemsWithAvailability = async (
fundraiserId: string
) => {
Expand Down
4 changes: 4 additions & 0 deletions common/schemas/fundraiser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ export const ReferralSchema = z.object({
referrer: UserSchema,
});

export const ReferralCountSchema = z.object({
orderCount: z.number().int().nonnegative(),
});

export const BasicFundraiserSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1).max(255),
Expand Down
30 changes: 30 additions & 0 deletions common/schemas/order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,36 @@ export const CompleteOrderSchema = BasicOrderSchema.extend({
),
});

type CompleteOrder = z.infer<typeof CompleteOrderSchema>;

export type ReferralOrder = Pick<CompleteOrder, "paymentStatus" | "pickedUp"> & {
items: {
quantity: number;
item: Pick<CompleteOrder["items"][number]["item"], "price">;
}[];
};

export const getReferralQuantities = (orders: ReferralOrder[]) => {
const countedOrders = orders.filter(
(order) => order.paymentStatus === "CONFIRMED" || order.pickedUp,
);
const amountRaised = countedOrders.reduce(
(total, order) =>
total +
order.items.reduce(
(sum, { item, quantity }) => sum + Number(item.price) * quantity,
0,
),
0,
);

return {
orderCount: countedOrders.length,
amountRaised,
attributedOrderCount: orders.length,
};
};

// CRUD BODIES:

export const CreateOrderBody = z.object({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
Expand Down Expand Up @@ -27,11 +28,13 @@ export function FundraiserReferralCard({
token,
userId,
isPast,
referralOrderCount,
}: {
fundraiser: z.infer<typeof CompleteFundraiserSchema>;
token: string;
userId: string;
isPast: boolean;
referralOrderCount: number | null;
}) {
const pathname = usePathname();
const [referralOpen, setReferralOpen] = useState(false);
Expand Down Expand Up @@ -99,13 +102,24 @@ export function FundraiserReferralCard({
Sign Up
</Button>
) : (
<Button
disabled={isPast}
className="cursor-pointer font-light text-sm lg:text-md lg:mt-0 w-full lg:w-auto"
onClick={() => copyToClipboard(link)}
>
Copy Referral Link
</Button>
<div className="flex flex-col gap-2 lg:flex-row lg:items-center lg:gap-4">
{referralOrderCount !== null && (
<Badge
variant="outline"
className="justify-center border-transparent bg-green-100 px-3 py-1 text-sm text-green-900 lg:whitespace-nowrap"
>
You&apos;ve referred {referralOrderCount} confirmed{" "}
{referralOrderCount === 1 ? "order" : "orders"}
</Badge>
)}
<Button
disabled={isPast}
className="cursor-pointer font-light text-sm lg:text-md lg:mt-0 w-full lg:w-auto"
onClick={() => copyToClipboard(link)}
>
Copy Referral Link
</Button>
</div>
)}
</div>
</CardContent>
Expand Down
Loading
Loading