diff --git a/backend/prisma/migrations/20261122120000_add_seller_costs/migration.sql b/backend/prisma/migrations/20261122120000_add_seller_costs/migration.sql new file mode 100644 index 00000000..9cc5e2ee --- /dev/null +++ b/backend/prisma/migrations/20261122120000_add_seller_costs/migration.sql @@ -0,0 +1,5 @@ +-- AlterTable +ALTER TABLE "fundraisers" ADD COLUMN "expenses" MONEY; + +-- AlterTable +ALTER TABLE "items" ADD COLUMN "unit_cost" MONEY; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 952078e7..733bf00e 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -56,6 +56,8 @@ model Fundraiser { description String published Boolean @default(false) goalAmount Decimal? @map("goal_amount") @db.Money + // Seller-entered fixed costs (booth fees, bulk ingredients, ...). Null = not entered. + expenses Decimal? @db.Money imageUrls String[] @map("image_urls") buyingStartsAt DateTime @map("buying_starts_at") buyingEndsAt DateTime @map("buying_ends_at") @@ -123,6 +125,8 @@ model Item { offsale Boolean @default(false) limit Int? price Decimal @db.Money + // Seller-entered cost to make/buy one unit. Null = not entered. + unitCost Decimal? @map("unit_cost") @db.Money category ItemCategory @default(OTHER) createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") diff --git a/backend/src/api/fundraiser/__tests__/fundraiser.handlers.test.ts b/backend/src/api/fundraiser/__tests__/fundraiser.handlers.test.ts new file mode 100644 index 00000000..38157671 --- /dev/null +++ b/backend/src/api/fundraiser/__tests__/fundraiser.handlers.test.ts @@ -0,0 +1,126 @@ +import { Decimal } from "decimal.js"; +import { + mockResponse, + createMockOrganization, + createMockUser, +} from "../../../__tests__"; +import { + getFundraiserCostsHandler, + getFundraiserItemsHandler, + updateFundraiserItemHandler, +} from "../fundraiser.handlers"; +import * as fundraiserServices from "../fundraiser.services"; + +jest.mock("../fundraiser.services"); +jest.mock("../../../utils/email", () => ({ + sendAnnouncementEmail: jest.fn(), + sendVenmoSetupEmail: jest.fn(), +})); + +const adminId = "123e4567-e89b-12d3-a456-426614174000"; +const strangerId = "123e4567-e89b-12d3-a456-426614174009"; +const fundraiserId = "423e4567-e89b-12d3-a456-426614174000"; +const itemId = "523e4567-e89b-12d3-a456-426614174000"; + +const fundraiser = { + id: fundraiserId, + published: true, + organization: { + ...createMockOrganization(), + admins: [createMockUser({ id: adminId })], + }, +}; + +const dbItem = { + id: itemId, + name: "Cookie", + description: "Chocolate chip", + price: new Decimal(3), + unitCost: new Decimal(1.25), + imageUrl: null, + offsale: false, + limit: null, + category: "DESSERTS", + fundraiserId, +}; + +describe("Fundraiser cost handlers", () => { + beforeEach(() => { + jest.clearAllMocks(); + (fundraiserServices.getFundraiser as jest.Mock).mockResolvedValue(fundraiser); + }); + + describe("getFundraiserCostsHandler", () => { + const req: any = { params: { id: fundraiserId } }; + + it("returns costs to org admins", async () => { + (fundraiserServices.getFundraiserCosts as jest.Mock).mockResolvedValue({ + expenses: new Decimal(40), + items: [{ id: itemId, unitCost: new Decimal(1.25) }], + }); + const res = mockResponse(); + res.locals.user = { id: adminId }; + + await getFundraiserCostsHandler(req, res); + + expect(res.status).toHaveBeenCalledWith(200); + const { data } = res.json.mock.calls[0][0]; + expect(Number(data.expenses)).toBe(40); + expect(Number(data.items[0].unitCost)).toBe(1.25); + }); + + it("rejects non-admins", async () => { + const res = mockResponse(); + res.locals.user = { id: strangerId }; + + await getFundraiserCostsHandler(req, res); + + expect(res.status).toHaveBeenCalledWith(403); + expect(fundraiserServices.getFundraiserCosts).not.toHaveBeenCalled(); + }); + }); + + it("never exposes unit cost on the public items endpoint", async () => { + (fundraiserServices.getFundraiserItems as jest.Mock).mockResolvedValue([dbItem]); + const res = mockResponse(); + + await getFundraiserItemsHandler({ params: { id: fundraiserId } } as any, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json.mock.calls[0][0].data[0]).not.toHaveProperty("unitCost"); + }); + + it("allows editing unit cost on a published fundraiser and invalidates analytics", async () => { + (fundraiserServices.getFundraiserItemForFundraiser as jest.Mock).mockResolvedValue(dbItem); + (fundraiserServices.validatePublishedFundraiserItemUpdate as jest.Mock).mockReturnValue({ + valid: true, + }); + (fundraiserServices.updateFundraiserItem as jest.Mock).mockResolvedValue({ + ...dbItem, + unitCost: new Decimal(2), + }); + const res = mockResponse(); + res.locals.user = { id: adminId }; + + await updateFundraiserItemHandler( + { + params: { fundraiserId, itemId }, + body: { + name: "Cookie", + description: "Chocolate chip", + price: new Decimal(3), + offsale: false, + unitCost: new Decimal(2), + category: "DESSERTS", + }, + } as any, + res + ); + + expect(res.status).toHaveBeenCalledWith(200); + expect(Number(res.json.mock.calls[0][0].data.unitCost)).toBe(2); + expect(fundraiserServices.invalidateFundraiserAnalyticsCache).toHaveBeenCalledWith( + fundraiserId + ); + }); +}); diff --git a/backend/src/api/fundraiser/__tests__/fundraiser.services.test.ts b/backend/src/api/fundraiser/__tests__/fundraiser.services.test.ts new file mode 100644 index 00000000..5189855d --- /dev/null +++ b/backend/src/api/fundraiser/__tests__/fundraiser.services.test.ts @@ -0,0 +1,342 @@ +import { Decimal } from "decimal.js"; +import { prismaMock } from "../../../__tests__"; +import memclient from "../../../utils/memjs"; +import { + calculateAndCacheFundraiserAnalytics, + computeProfit, + createFundraiserItem, + hasCompleteCostData, + updateCacheForOrderConfirmation, + updateCacheForOrderPickup, + updateFundraiser, + updateFundraiserItem, +} from "../fundraiser.services"; + +jest.mock("../../../utils/memjs", () => ({ + __esModule: true, + default: { get: jest.fn(), set: jest.fn(), delete: jest.fn() }, +})); + +const mockMem = memclient as unknown as { + get: jest.Mock; + set: jest.Mock; + delete: jest.Mock; +}; + +const fundraiserId = "423e4567-e89b-12d3-a456-426614174000"; +const cookieId = "523e4567-e89b-12d3-a456-426614174000"; +const shirtId = "523e4567-e89b-12d3-a456-426614174001"; + +const item = (id: string, name: string, price: number, unitCost: number | null) => ({ + id, + name, + price: new Decimal(price), + unitCost: unitCost === null ? null : new Decimal(unitCost), +}); + +const order = ( + overrides: { pickedUp?: boolean; paymentStatus?: string }, + items: Array<{ quantity: number; item: ReturnType }> +) => ({ + pickedUp: false, + paymentStatus: "PENDING", + createdAt: new Date("2026-11-01T12:00:00.000Z"), + items, + ...overrides, +}); + +const setup = ({ + expenses, + items, + orders, +}: { + expenses: number | null; + items: ReturnType[]; + orders: ReturnType[]; +}) => { + prismaMock.order.findMany.mockResolvedValue(orders as any); + prismaMock.fundraiser.findUnique.mockResolvedValue({ + id: fundraiserId, + goalAmount: new Decimal(500), + expenses: expenses === null ? null : new Decimal(expenses), + buyingStartsAt: new Date("2026-11-01"), + buyingEndsAt: new Date("2026-11-30"), + } as any); + prismaMock.item.findMany.mockResolvedValue(items as any); +}; + +describe("Fundraiser cost & profit", () => { + beforeEach(() => { + jest.clearAllMocks(); + mockMem.set.mockResolvedValue(true); + }); + + describe("hasCompleteCostData", () => { + it("is true when fundraiser expenses are set, even if items lack unit costs", () => { + expect(hasCompleteCostData(0, [{ unitCost: null }])).toBe(true); + }); + + it("is true when every item has a unit cost", () => { + expect( + hasCompleteCostData(null, [{ unitCost: new Decimal(1) }, { unitCost: new Decimal(0) }]) + ).toBe(true); + }); + + it("is false when no expenses and any item lacks a unit cost", () => { + expect( + hasCompleteCostData(null, [{ unitCost: new Decimal(1) }, { unitCost: null }]) + ).toBe(false); + }); + + it("is false when there are no items and no expenses", () => { + expect(hasCompleteCostData(null, [])).toBe(false); + }); + }); + + describe("computeProfit", () => { + it("subtracts item costs and expenses from revenue", () => { + expect( + computeProfit({ revenue: 100, itemCost: 30.5, expenses: 20, hasCostData: true }) + ).toBe(49.5); + }); + + it("returns null instead of an estimate without cost data", () => { + expect( + computeProfit({ revenue: 100, itemCost: 0, expenses: null, hasCostData: false }) + ).toBeNull(); + }); + + it("can be negative when costs exceed revenue", () => { + expect( + computeProfit({ revenue: 10, itemCost: 0, expenses: 25, hasCostData: true }) + ).toBe(-15); + }); + + it("rounds to cents", () => { + expect( + computeProfit({ revenue: 0.3, itemCost: 0.1, expenses: 0.1, hasCostData: true }) + ).toBe(0.1); + }); + }); + + describe("calculateAndCacheFundraiserAnalytics", () => { + it("computes profit from unit costs and expenses over confirmed/picked-up orders only", async () => { + const cookie = item(cookieId, "Cookie", 3, 1); + const shirt = item(shirtId, "Shirt", 20, 8); + setup({ + expenses: 10, + items: [cookie, shirt], + orders: [ + order({ paymentStatus: "CONFIRMED" }, [{ quantity: 4, item: cookie }]), // 12 rev, 4 cost + order({ pickedUp: true }, [{ quantity: 1, item: shirt }]), // 20 rev, 8 cost + order({}, [{ quantity: 10, item: shirt }]), // pending: not counted + ], + }); + + const analytics = await calculateAndCacheFundraiserAnalytics(fundraiserId); + + expect(analytics.total_revenue).toBe(32); + expect(analytics.item_cost).toBe(12); + expect(analytics.expenses).toBe(10); + expect(analytics.has_cost_data).toBe(true); + expect(analytics.profit).toBe(10); // 32 - 12 - 10 + expect(analytics.pending_orders).toBe(1); + }); + + it("returns null profit (no 20% estimate) when the seller hasn't entered costs", async () => { + const cookie = item(cookieId, "Cookie", 3, null); + setup({ + expenses: null, + items: [cookie], + orders: [order({ paymentStatus: "CONFIRMED" }, [{ quantity: 10, item: cookie }])], + }); + + const analytics = await calculateAndCacheFundraiserAnalytics(fundraiserId); + + expect(analytics.total_revenue).toBe(30); + expect(analytics.has_cost_data).toBe(false); + expect(analytics.profit).toBeNull(); + }); + + it("returns null profit when only some items have unit costs and no expenses", async () => { + const cookie = item(cookieId, "Cookie", 3, 1); + const shirt = item(shirtId, "Shirt", 20, null); + setup({ + expenses: null, + items: [cookie, shirt], + orders: [order({ paymentStatus: "CONFIRMED" }, [{ quantity: 2, item: cookie }])], + }); + + const analytics = await calculateAndCacheFundraiserAnalytics(fundraiserId); + + expect(analytics.profit).toBeNull(); + }); + + it("treats items without unit costs as covered by expenses", async () => { + const cookie = item(cookieId, "Cookie", 3, null); + setup({ + expenses: 5, + items: [cookie], + orders: [order({ paymentStatus: "CONFIRMED" }, [{ quantity: 10, item: cookie }])], + }); + + const analytics = await calculateAndCacheFundraiserAnalytics(fundraiserId); + + expect(analytics.profit).toBe(25); + }); + + it("uses current unit costs, so past orders reflect edited costs", async () => { + const cookie = item(cookieId, "Cookie", 3, 1); + const pastOrder = order({ paymentStatus: "CONFIRMED" }, [{ quantity: 10, item: cookie }]); + setup({ expenses: null, items: [cookie], orders: [pastOrder] }); + expect((await calculateAndCacheFundraiserAnalytics(fundraiserId)).profit).toBe(20); + + const edited = item(cookieId, "Cookie", 3, 2); + setup({ + expenses: null, + items: [edited], + orders: [{ ...pastOrder, items: [{ quantity: 10, item: edited }] }], + }); + expect((await calculateAndCacheFundraiserAnalytics(fundraiserId)).profit).toBe(10); + }); + + it("caches under a versioned key", async () => { + setup({ expenses: null, items: [], orders: [] }); + await calculateAndCacheFundraiserAnalytics(fundraiserId); + expect(mockMem.set).toHaveBeenCalledWith( + `fundraiser_analytics_v2_${fundraiserId}`, + expect.any(String), + { expires: 300 } + ); + }); + }); + + describe("incremental cache updates", () => { + const cached = (overrides: Record = {}) => ({ + total_revenue: 30, + total_orders: 2, + orders_picked_up: 0, + items: {}, + pending_orders: 1, + profit: 10, + has_cost_data: true, + item_cost: 10, + expenses: 10, + goal_amount: 500, + sale_data: {}, + revenue_data: {}, + start_date: new Date(), + end_date: new Date(), + ...overrides, + }); + + const savedAnalytics = () => JSON.parse(mockMem.set.mock.calls[0][1]); + + it("adds the order's item cost to profit on payment confirmation", async () => { + mockMem.get.mockResolvedValue({ value: Buffer.from(JSON.stringify(cached())) }); + + await updateCacheForOrderConfirmation(fundraiserId, { + pickedUp: false, + createdAt: new Date("2026-11-02T00:00:00.000Z"), + items: [{ quantity: 2, item: { name: "Shirt", price: new Decimal(20), unitCost: new Decimal(8) } }], + }); + + const saved = savedAnalytics(); + expect(saved.total_revenue).toBe(70); + expect(saved.item_cost).toBe(26); + expect(saved.profit).toBe(34); // 70 - 26 - 10 + }); + + it("adds the order's item cost to profit on pickup of an unconfirmed order", async () => { + mockMem.get.mockResolvedValue({ value: Buffer.from(JSON.stringify(cached())) }); + + await updateCacheForOrderPickup( + fundraiserId, + { + createdAt: new Date("2026-11-02T00:00:00.000Z"), + items: [{ quantity: 1, item: { name: "Cookie", price: new Decimal(3), unitCost: new Decimal(1) } }], + }, + "PENDING" + ); + + const saved = savedAnalytics(); + expect(saved.total_revenue).toBe(33); + expect(saved.profit).toBe(12); // 33 - 11 - 10 + }); + + it("keeps profit null when cost data is missing", async () => { + mockMem.get.mockResolvedValue({ + value: Buffer.from( + JSON.stringify(cached({ has_cost_data: false, profit: null, expenses: null, item_cost: 0 })) + ), + }); + + await updateCacheForOrderConfirmation(fundraiserId, { + pickedUp: false, + createdAt: new Date("2026-11-02T00:00:00.000Z"), + items: [{ quantity: 1, item: { name: "Cookie", price: new Decimal(3), unitCost: null } }], + }); + + expect(savedAnalytics().profit).toBeNull(); + }); + }); + + describe("persisting costs", () => { + it("stores a unit cost when creating an item, defaulting to null", async () => { + prismaMock.item.create.mockResolvedValue({} as any); + const base = { + fundraiserId, + name: "Cookie", + description: "", + price: new Decimal(3), + offsale: false, + category: "DESSERTS" as const, + }; + + await createFundraiserItem({ ...base, unitCost: new Decimal(1.25) }); + expect(prismaMock.item.create.mock.calls[0][0].data.unitCost).toEqual(new Decimal(1.25)); + + await createFundraiserItem(base); + expect(prismaMock.item.create.mock.calls[1][0].data.unitCost).toBeNull(); + }); + + it("leaves unit cost unchanged when omitted and clears it when null", async () => { + prismaMock.item.update.mockResolvedValue({} as any); + const base = { + itemId: cookieId, + name: "Cookie", + description: "", + price: new Decimal(3), + offsale: false, + category: "DESSERTS" as const, + }; + + await updateFundraiserItem(base); + expect(prismaMock.item.update.mock.calls[0][0].data.unitCost).toBeUndefined(); + + await updateFundraiserItem({ ...base, unitCost: null }); + expect(prismaMock.item.update.mock.calls[1][0].data.unitCost).toBeNull(); + }); + + it("leaves expenses unchanged when omitted and clears them when null", async () => { + prismaMock.fundraiser.update.mockResolvedValue({} as any); + const base = { + fundraiserId, + name: "Bake Sale", + description: "", + imageUrls: [], + buyingStartsAt: new Date(), + buyingEndsAt: new Date(), + }; + + await updateFundraiser(base); + expect(prismaMock.fundraiser.update.mock.calls[0][0].data.expenses).toBeUndefined(); + + await updateFundraiser({ ...base, expenses: null }); + expect(prismaMock.fundraiser.update.mock.calls[1][0].data.expenses).toBeNull(); + + await updateFundraiser({ ...base, expenses: new Decimal(40) }); + expect(prismaMock.fundraiser.update.mock.calls[2][0].data.expenses).toEqual(new Decimal(40)); + }); + }); +}); diff --git a/backend/src/api/fundraiser/fundraiser.handlers.ts b/backend/src/api/fundraiser/fundraiser.handlers.ts index 5d684482..344f7f9b 100644 --- a/backend/src/api/fundraiser/fundraiser.handlers.ts +++ b/backend/src/api/fundraiser/fundraiser.handlers.ts @@ -32,6 +32,7 @@ import { approveReferral, deleteReferral, getFundraiserItemsWithAvailability, + getFundraiserCosts, } from "./fundraiser.services"; import { AnnouncementSchema, @@ -49,6 +50,8 @@ import { UpdatePickupEventBody, ReferralSchema, ItemWithAvailabilitySchema, + SellerItemSchema, + FundraiserCostsSchema, } from "common"; import { getOrganization } from "../organization/organization.services"; import { z } from "zod"; @@ -241,6 +244,9 @@ export const updateFundraiserHandler = async ( return; } + // Expenses or goal may have changed, so profit must be recomputed + await invalidateFundraiserAnalyticsCache(req.params.id); + // Send Venmo setup email if venmoEmail was edited if (venmoEmailEdited) { try { @@ -470,8 +476,11 @@ export const createFundraiserItemHandler = async ( return; } - // remove irrelevant fields - const parsedItem = CompleteItemSchema.safeParse(item); + // A new item without a unit cost can change whether profit is computable + await invalidateFundraiserAnalyticsCache(req.params.id); + + // remove irrelevant fields (admin-only route, so unit cost is included) + const parsedItem = SellerItemSchema.safeParse(item); if (!parsedItem.success) { res.status(500).json({ message: "Couldn't parse item" }); return; @@ -551,8 +560,11 @@ export const updateFundraiserItemHandler = async ( return; } - // remove irrelevant fields - const parsedItem = CompleteItemSchema.safeParse(item); + // Unit cost edits recompute profit for all past orders + await invalidateFundraiserAnalyticsCache(req.params.fundraiserId); + + // remove irrelevant fields (admin-only route, so unit cost is included) + const parsedItem = SellerItemSchema.safeParse(item); if (!parsedItem.success) { res.status(500).json({ message: "Couldn't parse item" }); return; @@ -608,6 +620,8 @@ export const deleteFundraiserItemHandler = async ( return; } + await invalidateFundraiserAnalyticsCache(req.params.fundraiserId); + res.status(200).json({ message: "Successfully deleted fundraiser item", }); @@ -754,6 +768,43 @@ export const getFundraiserAnalyticsHandler = async ( } }; +export const getFundraiserCostsHandler = async ( + req: Request, + res: Response +) => { + const fundraiser = await getFundraiser(req.params.id); + if (!fundraiser) { + res.status(404).json({ message: "Fundraiser not found" }); + return; + } + + // Costs reveal the seller's margins, so only org admins can read them + if ( + !fundraiser.organization.admins.some( + (admin) => admin.id === res.locals.user!.id + ) + ) { + res.status(403).json({ message: "Unauthorized to view fundraiser costs" }); + return; + } + + const costs = await getFundraiserCosts(req.params.id); + if (!costs) { + res.status(404).json({ message: "Fundraiser not found" }); + return; + } + + const parsedCosts = FundraiserCostsSchema.safeParse(costs); + if (!parsedCosts.success) { + res.status(500).json({ message: "Couldn't parse fundraiser costs" }); + return; + } + + res + .status(200) + .json({ message: "Fundraiser costs retrieved", data: parsedCosts.data }); +}; + export const createReferralHandler = async ( req: Request, any, {}, {}>, res: Response diff --git a/backend/src/api/fundraiser/fundraiser.router.ts b/backend/src/api/fundraiser/fundraiser.router.ts index ebb7a8f2..ef0cf747 100644 --- a/backend/src/api/fundraiser/fundraiser.router.ts +++ b/backend/src/api/fundraiser/fundraiser.router.ts @@ -38,6 +38,7 @@ import { approveReferralHandler, deleteReferralHandler, getFundraiserItemsAvailabilityHandler, + getFundraiserCostsHandler, } from "./fundraiser.handlers"; import { authenticate } from "../../middleware/authenticate"; import { @@ -163,6 +164,14 @@ fundraiserRouter.get( asyncHandler(getFundraiserAnalyticsHandler) ); +// Seller-only cost data (unit costs + expenses), admin only +fundraiserRouter.get( + "/:id/costs", + validate({ params: FundraiserRouteParams }), + authenticate, + asyncHandler(getFundraiserCostsHandler) +); + // Create a referral request fundraiserRouter.post( "/:id/referrals", diff --git a/backend/src/api/fundraiser/fundraiser.services.ts b/backend/src/api/fundraiser/fundraiser.services.ts index 9f5f76a1..fdca44b2 100644 --- a/backend/src/api/fundraiser/fundraiser.services.ts +++ b/backend/src/api/fundraiser/fundraiser.services.ts @@ -12,9 +12,61 @@ import { import { z } from "zod"; import memclient from "../../utils/memjs"; -// Extract profit margin constant for the protif calculation in the analytics -// This constant can be easily mocked for profit calculation in backend test to ensure that different margin values work -export const PROFIT_MARGIN = 0.2; +// v2: analytics gained cost fields; bumping the key keeps older cache entries +// (without them) from being incrementally updated after deploy. +const analyticsCacheKey = (fundraiserId: string) => + `fundraiser_analytics_v2_${fundraiserId}`; + +const roundMoney = (value: number) => Math.round(value * 100) / 100; + +/** + * Whether the seller has entered enough cost data to compute a real profit. + * Either a fundraiser-level expenses total is set (items without a unit cost + * are then assumed to be covered by it), or every item has a unit cost. + */ +export const hasCompleteCostData = ( + expenses: number | null, + items: Array<{ unitCost: unknown }> +) => + expenses !== null || + (items.length > 0 && items.every((item) => item.unitCost != null)); + +/** + * Profit from seller-entered costs, or null if costs aren't entered. + * profit = revenue - sum(quantity * unitCost) - expenses + */ +export const computeProfit = ({ + revenue, + itemCost, + expenses, + hasCostData, +}: { + revenue: number; + itemCost: number; + expenses: number | null; + hasCostData: boolean; +}): number | null => + hasCostData ? roundMoney(revenue - itemCost - (expenses ?? 0)) : null; + +const orderItemsCost = ( + items: Array<{ quantity: number; item: { unitCost?: unknown } }> +) => + items.reduce( + (sum, orderItem) => + sum + + orderItem.quantity * + (orderItem.item.unitCost == null ? 0 : Number(orderItem.item.unitCost)), + 0 + ); + +const refreshProfit = (analytics: FundraiserAnalytics) => { + analytics.profit = computeProfit({ + revenue: analytics.total_revenue, + itemCost: analytics.item_cost, + expenses: analytics.expenses, + hasCostData: analytics.has_cost_data, + }); +}; export const getFundraiser = async (fundraiserId: string) => { const fundraiser = await prisma.fundraiser.findUnique({ @@ -154,6 +206,7 @@ export const createFundraiser = async ( venmoUsername: fundraiserBody.venmoUsername, venmoEmail: fundraiserBody.venmoEmail, goalAmount: fundraiserBody.goalAmount, + expenses: fundraiserBody.expenses ?? null, imageUrls: fundraiserBody.imageUrls, buyingStartsAt: fundraiserBody.buyingStartsAt, buyingEndsAt: fundraiserBody.buyingEndsAt, @@ -211,6 +264,8 @@ export const updateFundraiser = async ( venmoUsername: fundraiserBody.venmoUsername ?? null, venmoEmail: fundraiserBody.venmoEmail ?? null, goalAmount: fundraiserBody.goalAmount ?? null, + // undefined leaves expenses unchanged, null clears them + expenses: fundraiserBody.expenses, imageUrls: fundraiserBody.imageUrls, buyingStartsAt: fundraiserBody.buyingStartsAt, buyingEndsAt: fundraiserBody.buyingEndsAt, @@ -288,6 +343,7 @@ export const createFundraiserItem = async ( price: itemBody.price, imageUrl: itemBody.imageUrl, limit: itemBody.limit ?? null, + unitCost: itemBody.unitCost ?? null, category: itemBody.category, fundraiser: { connect: { @@ -335,6 +391,8 @@ export const updateFundraiserItem = async ( imageUrl: itemBody.imageUrl ?? null, offsale: itemBody.offsale, limit: itemBody.limit !== undefined ? itemBody.limit : undefined, + // undefined leaves unit cost unchanged, null clears it + unitCost: itemBody.unitCost, category: itemBody.category, }, }); @@ -493,6 +551,21 @@ export const deleteReferral = async (referralId: string) => { return referral; }; +export const getFundraiserCosts = async (fundraiserId: string) => { + const fundraiser = await prisma.fundraiser.findUnique({ + where: { id: fundraiserId }, + select: { + expenses: true, + items: { + select: { id: true, unitCost: true }, + orderBy: { createdAt: "asc" }, + }, + }, + }); + + return fundraiser; +}; + export const getFundraiserItemsWithAvailability = async ( fundraiserId: string ) => { @@ -593,7 +666,11 @@ export interface FundraiserAnalytics { orders_picked_up: number; items: Record; // units sold for each item pending_orders: number; - profit: number; + // null when the seller hasn't entered costs; never an estimate + profit: number | null; + has_cost_data: boolean; + item_cost: number; // sum of quantity * unitCost over counted orders + expenses: number | null; goal_amount: number; sale_data: Record; // orders sold on a particular day revenue_data: Record; // revenue earned on a particular day @@ -609,18 +686,25 @@ export interface FundraiserAnalytics { export const calculateAndCacheFundraiserAnalytics = async ( fundraiserId: string ) => { - const [orders, fundraiser] = await Promise.all([ + const [orders, fundraiser, items] = await Promise.all([ getFundraiserOrders(fundraiserId), getFundraiser(fundraiserId), + getFundraiserItems(fundraiserId), ]); + const expenses = + fundraiser?.expenses == null ? null : Number(fundraiser.expenses); + const analytics: FundraiserAnalytics = { total_revenue: 0, total_orders: orders.length, orders_picked_up: 0, items: {}, pending_orders: 0, - profit: 0, + profit: null, + has_cost_data: hasCompleteCostData(expenses, items), + item_cost: 0, + expenses, goal_amount: Number(fundraiser?.goalAmount) ?? 0, sale_data: {}, revenue_data: {}, @@ -646,8 +730,9 @@ export const calculateAndCacheFundraiserAnalytics = async ( (analytics.items[orderItem.item.name] || 0) + orderItem.quantity; }); - // The total revenue should only consider the orders that are picked up or paid· + // Revenue and costs only consider the orders that are picked up or paid analytics.total_revenue += orderTotal; + analytics.item_cost += orderItemsCost(order.items); // Track revenue by date only for paid or picked up orders const orderDate = order.createdAt.toISOString().split("T")[0]; @@ -662,10 +747,9 @@ export const calculateAndCacheFundraiserAnalytics = async ( analytics.sale_data[orderDate] = (analytics.sale_data[orderDate] || 0) + 1; }); - analytics.profit = - Math.round(analytics.total_revenue * PROFIT_MARGIN * 100) / 100; + refreshProfit(analytics); - const cacheKey = `fundraiser_analytics_${fundraiserId}`; + const cacheKey = analyticsCacheKey(fundraiserId); try { await memclient.set(cacheKey, JSON.stringify(analytics), { expires: 300 }); // Cache expires after 5 minutes } catch (error) { @@ -681,7 +765,7 @@ export const calculateAndCacheFundraiserAnalytics = async ( */ export const getFundraiserAnalytics = async (fundraiserId: string) => { // Fundraiser specific id to access the cache - const cacheKey = `fundraiser_analytics_${fundraiserId}`; + const cacheKey = analyticsCacheKey(fundraiserId); try { const cached = await memclient.get(cacheKey); @@ -705,7 +789,7 @@ export const getFundraiserAnalytics = async (fundraiserId: string) => { export const invalidateFundraiserAnalyticsCache = async ( fundraiserId: string ) => { - const cacheKey = `fundraiser_analytics_${fundraiserId}`; + const cacheKey = analyticsCacheKey(fundraiserId); try { console.log("Invalidating cache for key:", cacheKey); const result = await memclient.delete(cacheKey); @@ -750,7 +834,7 @@ export const updateCacheForNewOrder = async ( fundraiserId: string, orderDate: Date ) => { - const cacheKey = `fundraiser_analytics_${fundraiserId}`; + const cacheKey = analyticsCacheKey(fundraiserId); try { // Peek at cache - only update if it exists const analytics = await peekCachedAnalytics(cacheKey); @@ -794,12 +878,13 @@ export const updateCacheForOrderPickup = async ( item: { name: string; price: number | any; + unitCost?: number | any; }; }>; }, paymentStatus: string ) => { - const cacheKey = `fundraiser_analytics_${fundraiserId}`; + const cacheKey = analyticsCacheKey(fundraiserId); try { // Peek at cache - only update if it exists const analytics = await peekCachedAnalytics(cacheKey); @@ -825,8 +910,8 @@ export const updateCacheForOrderPickup = async ( if (paymentStatus !== "CONFIRMED") { analytics.pending_orders--; analytics.total_revenue += orderTotal; - analytics.profit = - Math.round(analytics.total_revenue * PROFIT_MARGIN * 100) / 100; + analytics.item_cost += orderItemsCost(order.items); + refreshProfit(analytics); // Update revenue data by date const dateKey = order.createdAt.toISOString().split("T")[0]; @@ -860,11 +945,12 @@ export const updateCacheForOrderConfirmation = async ( item: { name: string; price: number | any; + unitCost?: number | any; }; }>; } ) => { - const cacheKey = `fundraiser_analytics_${fundraiserId}`; + const cacheKey = analyticsCacheKey(fundraiserId); try { // Peek at cache - only update if it exists const analytics = await peekCachedAnalytics(cacheKey); @@ -894,8 +980,8 @@ export const updateCacheForOrderConfirmation = async ( // Update counters and revenue analytics.pending_orders--; analytics.total_revenue += orderTotal; - analytics.profit = - Math.round(analytics.total_revenue * PROFIT_MARGIN * 100) / 100; + analytics.item_cost += orderItemsCost(order.items); + refreshProfit(analytics); // Update revenue data by date const dateKey = order.createdAt.toISOString().split("T")[0]; diff --git a/backend/src/api/order/order.services.ts b/backend/src/api/order/order.services.ts index 7f166584..1c38faf7 100644 --- a/backend/src/api/order/order.services.ts +++ b/backend/src/api/order/order.services.ts @@ -364,6 +364,7 @@ export const completeOrderPickup = async (orderId: string) => { name: true, description: true, price: true, + unitCost: true, imageUrl: true, offsale: true, category: true, @@ -455,6 +456,7 @@ export const undoOrderPickup = async (orderId: string) => { name: true, description: true, price: true, + unitCost: true, imageUrl: true, offsale: true, category: true, @@ -488,6 +490,7 @@ const confirmedOrderInclude = { select: { name: true, price: true, + unitCost: true, }, }, }, diff --git a/common/schemas/fundraiser.ts b/common/schemas/fundraiser.ts index ae79179e..8112ffe0 100644 --- a/common/schemas/fundraiser.ts +++ b/common/schemas/fundraiser.ts @@ -81,6 +81,8 @@ export const CreateFundraiserBody = z.object({ .pipe(z.string().email().optional()), imageUrls: z.array(z.string().url()), goalAmount: MoneySchema.optional(), + // Seller-only fixed costs. Never returned by public fundraiser endpoints. + expenses: MoneySchema.nullish(), buyingStartsAt: z.coerce.date(), buyingEndsAt: z.coerce.date(), organizationId: z.string().uuid(), @@ -106,6 +108,8 @@ export const UpdateFundraiserBody = z.object({ ) .pipe(z.string().email().optional()), goalAmount: MoneySchema.optional(), + // undefined leaves expenses unchanged, null clears them + expenses: MoneySchema.nullish(), imageUrls: z.array(z.string().url()), buyingStartsAt: z.coerce.date(), buyingEndsAt: z.coerce.date(), @@ -118,6 +122,8 @@ export const CreateFundraiserItemBody = z.object({ imageUrl: z.string().url().optional(), offsale: z.boolean(), limit: z.number().int().positive().optional(), + // Seller-only unit cost. Never returned by public item endpoints. + unitCost: MoneySchema.nullish(), category: ItemCategorySchema, }); @@ -128,9 +134,25 @@ export const UpdateFundraiserItemBody = z.object({ imageUrl: z.string().url().optional(), offsale: z.boolean(), limit: z.number().int().positive().nullable().optional(), + // undefined leaves unit cost unchanged, null clears it + unitCost: MoneySchema.nullish(), category: ItemCategorySchema, }); +// Seller-only cost data (admin-only endpoint). Kept out of the public +// fundraiser/item schemas so buyers never see a seller's margins. +export const FundraiserCostsSchema = z.object({ + expenses: MoneySchema.nullable(), + items: z.array( + z.object({ + id: z.string().uuid(), + unitCost: MoneySchema.nullable(), + }) + ), +}); + +export type FundraiserCosts = z.infer; + export const CreateAnnouncementBody = z.object({ message: z.string(), }); diff --git a/common/schemas/item.ts b/common/schemas/item.ts index 7a2d5831..c1824333 100644 --- a/common/schemas/item.ts +++ b/common/schemas/item.ts @@ -30,4 +30,11 @@ export const ItemWithAvailabilitySchema = CompleteItemSchema.extend({ available: z.number().nullable(), }); +// Seller-side view of an item, including the seller-only unit cost. +export const SellerItemSchema = CompleteItemSchema.extend({ + unitCost: MoneySchema.nullish(), +}); + +export type SellerItem = z.infer; + export type ItemWithAvailability = z.infer; diff --git a/frontend/src/app/seller/fundraiser/[id]/analytics/components/ProfitGoalChart.tsx b/frontend/src/app/seller/fundraiser/[id]/analytics/components/ProfitGoalChart.tsx index 49f9765e..1d453af3 100644 --- a/frontend/src/app/seller/fundraiser/[id]/analytics/components/ProfitGoalChart.tsx +++ b/frontend/src/app/seller/fundraiser/[id]/analytics/components/ProfitGoalChart.tsx @@ -7,6 +7,7 @@ import { ChartTooltip, ChartTooltipContent, } from "@/components/ui/chart"; +import { formatMoney, profitGoalProgress } from "@/lib/profit"; interface ProfitGoalChartProps { profit: number; @@ -25,25 +26,23 @@ export function ProfitGoalChart({ profit, goalAmount }: ProfitGoalChartProps) { }, }; - // Calculate profit percentage (capped at 100%) - const profitPercentage = - goalAmount && goalAmount > 0 - ? Math.min((profit / goalAmount) * 100, 100) - : 0; + const { percentage: profitPercentage, remaining } = profitGoalProgress( + profit, + goalAmount + ); const remainingPercentage = 100 - profitPercentage; - const remaining = (goalAmount || 0) - profit; const chartData = [ { name: "Profit", value: profitPercentage, - displayValue: `$${profit.toFixed(2)}`, + displayValue: formatMoney(profit), fill: "#15803d", }, { name: "Remaining", value: remainingPercentage, - displayValue: `$${remaining.toFixed(2)}`, + displayValue: formatMoney(remaining), fill: "#e5e7eb", }, ]; @@ -89,22 +88,20 @@ export function ProfitGoalChart({ profit, goalAmount }: ProfitGoalChartProps) { y={viewBox.cy} textAnchor="middle" dominantBaseline="middle"> + {/* Goal sits on its own line so cents fit inside the ring */} - ${profit} - - /{goalAmount || 0} - + y={(viewBox.cy || 0) - 8} + className="fill-foreground text-2xl font-semibold"> + {formatMoney(profit)} - profit + {goalAmount && goalAmount > 0 + ? `of ${formatMoney(goalAmount)} goal` + : "profit"} ); diff --git a/frontend/src/app/seller/fundraiser/[id]/analytics/components/RealtimeAnalyticsWrapper.tsx b/frontend/src/app/seller/fundraiser/[id]/analytics/components/RealtimeAnalyticsWrapper.tsx index f8c83384..14780008 100644 --- a/frontend/src/app/seller/fundraiser/[id]/analytics/components/RealtimeAnalyticsWrapper.tsx +++ b/frontend/src/app/seller/fundraiser/[id]/analytics/components/RealtimeAnalyticsWrapper.tsx @@ -19,7 +19,11 @@ interface FundraiserAnalytics { orders_picked_up: number; items: Record; pending_orders: number; - profit: number; + // null when the seller hasn't entered costs; never an estimate + profit: number | null; + has_cost_data: boolean; + item_cost: number; + expenses: number | null; goal_amount: number; sale_data: Record; revenue_data: Record; @@ -48,6 +52,12 @@ export function RealtimeAnalyticsWrapper({ const [orders, setOrders] = useState(initialOrders); const supabase = useMemo(() => createClient(), []); + // router.refresh() (e.g. after saving costs in the edit modal) re-fetches + // analytics on the server; sync them in so profit updates without a reload + useEffect(() => { + setAnalytics(initialAnalytics); + }, [initialAnalytics]); + useEffect(() => { const refetchData = async (forceRefresh = false) => { try { @@ -241,15 +251,26 @@ export function RealtimeAnalyticsWrapper({ Profit Goal
- + {analytics.profit === null ? ( +
+

Add costs to see profit

+

+ Click Edit and enter your fundraiser's expenses, or a + cost per unit for every item. Until then, only revenue is + shown. +

+
+ ) : ( + + )}
diff --git a/frontend/src/app/seller/fundraiser/[id]/components/EditFundraiserModal.tsx b/frontend/src/app/seller/fundraiser/[id]/components/EditFundraiserModal.tsx index 61791dbb..4ba760be 100644 --- a/frontend/src/app/seller/fundraiser/[id]/components/EditFundraiserModal.tsx +++ b/frontend/src/app/seller/fundraiser/[id]/components/EditFundraiserModal.tsx @@ -6,7 +6,7 @@ import { toast } from "sonner"; import { z } from "zod"; import { useEffect, useState } from "react"; import { mutationFetch } from "@/lib/fetcher"; -import { CompleteFundraiserSchema, CompleteItemSchema } from "common"; +import { CompleteFundraiserSchema, SellerItem, SellerItemSchema } from "common"; import MultiStepForm from "@/components/custom/MultiStepForm"; import { FundraiserBasicInfoForm } from "@/app/seller/org/[id]/create-fundraiser/components/FundraiserBasicInfoForm"; import { FundraiserVenmoInfoForm } from "@/app/seller/org/[id]/create-fundraiser/components/FundraiserVenmoInfoForm"; @@ -29,6 +29,7 @@ import { diffSavedItems } from "@/lib/item-changes"; export function EditFundraiserModal({ token, fundraiser, + fundraiserExpenses, currentFundraiserItems, open, setOpen, @@ -36,7 +37,8 @@ export function EditFundraiserModal({ }: { token: string; fundraiser: z.infer; - currentFundraiserItems: z.infer[]; + fundraiserExpenses: z.infer["expenses"]; + currentFundraiserItems: SellerItem[]; open: boolean; setOpen: React.Dispatch>; step: number; @@ -49,6 +51,7 @@ export function EditFundraiserModal({ description: fundraiser.description, imageUrls: fundraiser.imageUrls ?? [], goalAmount: fundraiser.goalAmount ?? undefined, + expenses: fundraiserExpenses ?? null, buyingStartsAt: fundraiser.buyingStartsAt, buyingEndsAt: fundraiser.buyingEndsAt, organizationId: fundraiser.organization.id, @@ -56,19 +59,20 @@ export function EditFundraiserModal({ venmoUsername: fundraiser.venmoUsername ?? undefined, pickupEvents: fundraiser.pickupEvents ?? [], }); - const [fundraiserItems, setFundraiserItems] = useState< - z.infer[] - >(currentFundraiserItems); + const [fundraiserItems, setFundraiserItems] = useState( + currentFundraiserItems, + ); const [pickupEvents, setPickupEvents] = useState< z.infer[] >(fundraiser.pickupEvents); const [formFundraiserItems, setFormFundraiserItems] = useState< z.infer[] >( - currentFundraiserItems.map(({ id, imageUrl, limit, ...rest }) => ({ + currentFundraiserItems.map(({ id, imageUrl, limit, unitCost, ...rest }) => ({ ...rest, imageUrl: imageUrl ?? undefined, limit: limit ?? undefined, + unitCost: unitCost ?? null, })), ); const [isSubmitting, setIsSubmitting] = useState(false); @@ -105,6 +109,8 @@ export function EditFundraiserModal({ venmoEmail: formData.venmoEmail === "" ? null : formData.venmoEmail, venmoUsername: formData.venmoUsername === "" ? null : formData.venmoUsername, + // Send null (not undefined) so clearing the field clears expenses + expenses: formData.expenses ?? null, } as typeof formData & { venmoEmail: string | null; venmoUsername: string | null; @@ -202,6 +208,7 @@ export function EditFundraiserModal({ imageUrl: item.imageUrl ?? undefined, offsale: item.offsale, limit: item.limit ?? null, + unitCost: item.unitCost ?? null, category: item.category, }, }, @@ -222,11 +229,11 @@ export function EditFundraiserModal({ `/fundraiser/${fundraiser.id}/items/create`, { token, body: pending.data }, ); - return itemResult.data as z.infer; + return SellerItemSchema.parse(itemResult.data); }), ); - const createdItems: z.infer[] = []; + const createdItems: SellerItem[] = []; createItemResults.forEach((result) => { if (result.status === "fulfilled") { createdItems.push(result.value); @@ -270,10 +277,11 @@ export function EditFundraiserModal({ useEffect(() => { setFormFundraiserItems( - fundraiserItems.map(({ id, imageUrl, limit, ...rest }) => ({ + fundraiserItems.map(({ id, imageUrl, limit, unitCost, ...rest }) => ({ ...rest, imageUrl: imageUrl ?? undefined, limit: limit ?? undefined, + unitCost: unitCost ?? null, })), ); }, [fundraiserItems]); diff --git a/frontend/src/app/seller/fundraiser/[id]/components/EditItems.tsx b/frontend/src/app/seller/fundraiser/[id]/components/EditItems.tsx index bc8a7545..4c05d8be 100644 --- a/frontend/src/app/seller/fundraiser/[id]/components/EditItems.tsx +++ b/frontend/src/app/seller/fundraiser/[id]/components/EditItems.tsx @@ -7,7 +7,7 @@ import { CardHeader, CardTitle, } from "@/components/ui/card"; -import { CompleteItemSchema, CreateFundraiserItemBody } from "common"; +import { CreateFundraiserItemBody, SellerItem } from "common"; import { Dispatch, SetStateAction, useState } from "react"; import { z } from "zod"; import { PlusCircle, X, ShoppingCart, Pencil } from "lucide-react"; @@ -28,6 +28,7 @@ export const DEFAULT_ITEM_VALUES = { imageUrl: undefined, offsale: false, limit: undefined, + unitCost: null, category: undefined, }; @@ -46,8 +47,8 @@ export function FundraiserEditItemsForm({ }: { token: string; fundraiserId: string; - items: z.infer[]; - setItems: Dispatch[]>>; + items: SellerItem[]; + setItems: Dispatch>; isPublished?: boolean; onAddPendingItem?: OnAddPendingItem; onUpdatePendingItem?: OnUpdatePendingItem; @@ -83,6 +84,7 @@ export function FundraiserEditItemsForm({ imageUrl: item.imageUrl ?? undefined, offsale: item.offsale, limit: item.limit ?? undefined, + unitCost: item.unitCost ?? null, category: item.category, }); setOpen(true); @@ -90,7 +92,7 @@ export function FundraiserEditItemsForm({ // Handles removing item from the UI // The API call to remove the item is in EditFundraiserModal where we batch all the delete API calls - const handleRemoveItem = (item: z.infer) => { + const handleRemoveItem = (item: SellerItem) => { // Remove item from the local state array // The item card is removed from this tab setItems((prev) => prev.filter((i) => i.id !== item.id)); @@ -167,6 +169,11 @@ export function FundraiserEditItemsForm({

${Number(item.price).toFixed(2)}

+ {item.unitCost != null && ( +

+ Cost: ${Number(item.unitCost).toFixed(2)} +

+ )} {item.limit != null && (

Cap: {item.limit} diff --git a/frontend/src/app/seller/fundraiser/[id]/components/FundraiserHeader.tsx b/frontend/src/app/seller/fundraiser/[id]/components/FundraiserHeader.tsx index 97ab3b0a..8fbf53cf 100644 --- a/frontend/src/app/seller/fundraiser/[id]/components/FundraiserHeader.tsx +++ b/frontend/src/app/seller/fundraiser/[id]/components/FundraiserHeader.tsx @@ -3,8 +3,9 @@ import { Button } from "@/components/ui/button"; import { CompleteFundraiserSchema, - CompleteItemSchema, + FundraiserCosts, PickupEventSchema, + SellerItem, } from "common"; import { Calendar, MapPin } from "lucide-react"; import { format } from "date-fns"; @@ -22,10 +23,12 @@ export function FundraiserHeader({ token, fundraiser, fundraiserItems, + fundraiserExpenses, }: { token: string; fundraiser: z.infer; - fundraiserItems: z.infer[]; + fundraiserItems: SellerItem[]; + fundraiserExpenses: FundraiserCosts["expenses"]; }) { const [isSubmitting, setIsSubmitting] = useState(false); const [openEdit, setOpenEdit] = useState(false); @@ -75,6 +78,7 @@ export function FundraiserHeader({ key={editKey} token={token} fundraiser={fundraiser} + fundraiserExpenses={fundraiserExpenses} currentFundraiserItems={fundraiserItems} open={openEdit} setOpen={setOpenEdit} diff --git a/frontend/src/app/seller/fundraiser/[id]/components/ItemDialog.tsx b/frontend/src/app/seller/fundraiser/[id]/components/ItemDialog.tsx index c37ef275..f27c233e 100644 --- a/frontend/src/app/seller/fundraiser/[id]/components/ItemDialog.tsx +++ b/frontend/src/app/seller/fundraiser/[id]/components/ItemDialog.tsx @@ -16,7 +16,7 @@ import { import UploadImageComponent from "@/components/custom/UploadImageComponent"; import { InfoTooltip } from "@/components/custom/MoreInfoToolTip"; import { UseFormReturn } from "react-hook-form"; -import { CompleteItemSchema, CreateFundraiserItemBody } from "common"; +import { CreateFundraiserItemBody, SellerItem } from "common"; import { z } from "zod"; import { toast } from "sonner"; import { DEFAULT_ITEM_VALUES } from "./EditItems"; @@ -69,10 +69,8 @@ type FundraiserItemDialogProps = ItemDialogSharedProps & { persistence?: "fundraiser"; token: string; fundraiserId: string; - items: z.infer[]; - setItems: React.Dispatch< - SetStateAction[]> - >; + items: SellerItem[]; + setItems: React.Dispatch>; editingIndex: number | null; isPublished?: boolean; onAddPendingItem?: OnAddPendingItem; @@ -137,7 +135,7 @@ export function ItemDialog( if (mode === "add" || editingIndex === null) { // Create a temporary item for display const tempId = `temp-${Date.now()}`; - const tempItem: z.infer = { + const tempItem: SellerItem = { id: tempId, name: item.name, description: item.description, @@ -145,6 +143,7 @@ export function ItemDialog( imageUrl: item.imageUrl, offsale: false, limit: item.limit ?? null, + unitCost: item.unitCost == null ? null : new Decimal(item.unitCost), category: item.category, }; setItems((prev) => [...prev, tempItem]); @@ -189,6 +188,8 @@ export function ItemDialog( imageUrl: item.imageUrl, offsale: editingItem.offsale, limit: item.limit !== undefined ? item.limit : null, + // Cost is seller-only, so it stays editable after publishing + unitCost: item.unitCost ?? null, category: item.category, }, } @@ -203,13 +204,14 @@ export function ItemDialog( } // Update item in local state - const updatedItem: z.infer = { + const updatedItem: SellerItem = { ...editingItem, name: item.name, description: item.description, price: new Decimal(item.price), imageUrl: item.imageUrl, limit: item.limit !== undefined ? item.limit : null, + unitCost: item.unitCost == null ? null : new Decimal(item.unitCost), category: item.category, }; setItems((prev) => @@ -378,6 +380,39 @@ export function ItemDialog( )} /> + ( + +

+ Cost per Unit (Optional) + +
+ + { + field.onChange( + e.target.value === "" + ? null + : parseFloat(e.target.value) + ); + }} + /> + + + + )} + /> + ; pending_orders: number; - profit: number; + profit: number | null; + has_cost_data: boolean; + item_cost: number; + expenses: number | null; goal_amount: number; sale_data: Record; revenue_data: Record; @@ -57,7 +61,7 @@ export default async function FundraiserAnalyticsPage({ // Fetch data in parallel // TODO: refactor fundraiseranalytics into a zod schema and validate it here instead of individually validating orders/items/fundraiser - const [fundraiser, analytics, orders, items] = await Promise.all([ + const [fundraiser, analytics, orders, items, costs] = await Promise.all([ serverFetch(`/fundraiser/${fundraiserId}`, { token: session.access_token, schema: CompleteFundraiserSchema, @@ -73,8 +77,21 @@ export default async function FundraiserAnalyticsPage({ token: session.access_token, schema: CompleteItemSchema.array(), }), + // Seller-only costs come from an admin-only endpoint so buyers never see them + serverFetch(`/fundraiser/${fundraiserId}/costs`, { + token: session.access_token, + schema: FundraiserCostsSchema, + }), ]); + const unitCostById = new Map( + costs.items.map((item) => [item.id, item.unitCost]), + ); + const sellerItems = items.map((item) => ({ + ...item, + unitCost: unitCostById.get(item.id) ?? null, + })); + return ( diff --git a/frontend/src/app/seller/org/[id]/create-fundraiser/components/FundraiserAddItemsForm.tsx b/frontend/src/app/seller/org/[id]/create-fundraiser/components/FundraiserAddItemsForm.tsx index aec9a879..8a8a7c57 100644 --- a/frontend/src/app/seller/org/[id]/create-fundraiser/components/FundraiserAddItemsForm.tsx +++ b/frontend/src/app/seller/org/[id]/create-fundraiser/components/FundraiserAddItemsForm.tsx @@ -61,6 +61,7 @@ export function FundraiserAddItemsForm({ imageUrl: item.imageUrl, offsale: item.offsale, limit: item.limit, + unitCost: item.unitCost ?? null, category: item.category, }); setOpen(true); @@ -135,6 +136,11 @@ export function FundraiserAddItemsForm({

${Number(item.price).toFixed(2)}

+ {item.unitCost != null && ( +

+ Cost: ${Number(item.unitCost).toFixed(2)} +

+ )} {item.limit != null && (

Cap: {item.limit} diff --git a/frontend/src/app/seller/org/[id]/create-fundraiser/components/FundraiserBasicInfoForm.tsx b/frontend/src/app/seller/org/[id]/create-fundraiser/components/FundraiserBasicInfoForm.tsx index 86da1680..d547f7bf 100644 --- a/frontend/src/app/seller/org/[id]/create-fundraiser/components/FundraiserBasicInfoForm.tsx +++ b/frontend/src/app/seller/org/[id]/create-fundraiser/components/FundraiserBasicInfoForm.tsx @@ -142,7 +142,7 @@ export function FundraiserBasicInfoForm({ Goal Amount (Optional){" "} - + + ( + + + Expenses (Optional){" "} + + + + { + field.onChange( + e.target.value === "" + ? null + : parseFloat(e.target.value), + ); + }} + /> + + + + )} + /> +

Buying Period{" "} diff --git a/frontend/src/app/seller/org/[id]/create-fundraiser/components/ReviewFundraiserForm.tsx b/frontend/src/app/seller/org/[id]/create-fundraiser/components/ReviewFundraiserForm.tsx index 8244cc93..584fd98b 100644 --- a/frontend/src/app/seller/org/[id]/create-fundraiser/components/ReviewFundraiserForm.tsx +++ b/frontend/src/app/seller/org/[id]/create-fundraiser/components/ReviewFundraiserForm.tsx @@ -54,6 +54,18 @@ export function ReviewFundraiserForm({ : "No goal set"}

+
+

Expenses

+

+ {formData.expenses != null + ? `$${Number(formData.expenses).toFixed(2)}` + : "Not provided"} +

+

Description

{item.description}

+ {item.unitCost != null && ( +

+ Cost: ${Number(item.unitCost).toFixed(2)} +

+ )}

$ diff --git a/frontend/src/lib/item-changes.test.ts b/frontend/src/lib/item-changes.test.ts index fb0a6836..bf0ceec4 100644 --- a/frontend/src/lib/item-changes.test.ts +++ b/frontend/src/lib/item-changes.test.ts @@ -52,6 +52,30 @@ describe("diffSavedItems", () => { expect(updated).toEqual([]); }); + it("detects unit cost being added, changed, or cleared", () => { + const { updated } = diffSavedItems( + [ + item("a", { unitCost: null }), + item("b", { unitCost: "1.00" }), + item("c", { unitCost: "1.00" }), + ], + [ + item("a", { unitCost: 1 }), + item("b", { unitCost: 2 }), + item("c", { unitCost: null }), + ], + ); + expect(updated.map((i) => i.id)).toEqual(["a", "b", "c"]); + }); + + it("treats equal unit costs in different formats, and null vs undefined, as unchanged", () => { + const { updated } = diffSavedItems( + [item("a", { unitCost: "1.50" }), item("b", { unitCost: null })], + [item("a", { unitCost: 1.5 }), item("b", { unitCost: undefined })], + ); + expect(updated).toEqual([]); + }); + it("ignores temp items", () => { expect( diffSavedItems([item("a")], [item("a"), item("temp-123")]), diff --git a/frontend/src/lib/item-changes.ts b/frontend/src/lib/item-changes.ts index 1d42ab22..f400237e 100644 --- a/frontend/src/lib/item-changes.ts +++ b/frontend/src/lib/item-changes.ts @@ -6,9 +6,15 @@ type SavedItem = { imageUrl?: string | null; offsale: boolean; limit?: number | null; + unitCost?: { toString(): string } | number | string | null; category: string; }; +const sameMoney = (a: SavedItem["unitCost"], b: SavedItem["unitCost"]) => + a == null || b == null + ? (a ?? null) === (b ?? null) + : Number(a.toString()) === Number(b.toString()); + function sameItem(a: SavedItem, b: SavedItem) { return ( a.name === b.name && @@ -17,6 +23,7 @@ function sameItem(a: SavedItem, b: SavedItem) { (a.imageUrl ?? null) === (b.imageUrl ?? null) && a.offsale === b.offsale && (a.limit ?? null) === (b.limit ?? null) && + sameMoney(a.unitCost, b.unitCost) && a.category === b.category ); } diff --git a/frontend/src/lib/profit.test.ts b/frontend/src/lib/profit.test.ts new file mode 100644 index 00000000..6e20002d --- /dev/null +++ b/frontend/src/lib/profit.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { formatMoney, profitGoalProgress } from "./profit"; + +describe("profitGoalProgress", () => { + it("reports progress toward the goal", () => { + expect(profitGoalProgress(25, 100)).toEqual({ percentage: 25, remaining: 75 }); + }); + + it("caps at 100% once the goal is passed", () => { + expect(profitGoalProgress(150, 100)).toEqual({ percentage: 100, remaining: 0 }); + }); + + it("floors at 0% when costs exceed revenue", () => { + expect(profitGoalProgress(-20, 100)).toEqual({ percentage: 0, remaining: 120 }); + }); + + it("handles a missing goal", () => { + expect(profitGoalProgress(50, null)).toEqual({ percentage: 0, remaining: 0 }); + expect(profitGoalProgress(50, NaN)).toEqual({ percentage: 0, remaining: 0 }); + }); +}); + +describe("formatMoney", () => { + it("formats positive and negative amounts", () => { + expect(formatMoney(12.5)).toBe("$12.50"); + expect(formatMoney(-3)).toBe("-$3.00"); + }); +}); diff --git a/frontend/src/lib/profit.ts b/frontend/src/lib/profit.ts new file mode 100644 index 00000000..81ad94bf --- /dev/null +++ b/frontend/src/lib/profit.ts @@ -0,0 +1,24 @@ +// Profit is computed on the backend from seller-entered costs. It is null when +// the seller hasn't entered enough cost data; we never show an estimate. + +export type ProfitGoalProgress = { + // Share of the goal reached, clamped to [0, 100] so losses and overshoot + // still render as a valid ring + percentage: number; + remaining: number; +}; + +export function profitGoalProgress( + profit: number, + goalAmount: number | null | undefined, +): ProfitGoalProgress { + const goal = goalAmount && goalAmount > 0 ? goalAmount : 0; + const percentage = + goal > 0 ? Math.min(Math.max((profit / goal) * 100, 0), 100) : 0; + return { percentage, remaining: Math.max(goal - profit, 0) }; +} + +export function formatMoney(value: number): string { + const sign = value < 0 ? "-" : ""; + return `${sign}$${Math.abs(value).toFixed(2)}`; +}