From e4d26b7b5e8c9b6a0bee056c734de47e372158a9 Mon Sep 17 00:00:00 2001 From: Raj Patel Date: Wed, 21 Oct 2026 19:05:11 -0700 Subject: [PATCH] Send seller invite automatically after bulk approval --- app/(site)/admin/actions.test.ts | 25 ++++++++-- app/(site)/admin/actions.ts | 9 +++- app/(site)/admin/imports/ImportForms.tsx | 10 +++- app/(site)/admin/imports/page.tsx | 23 ++++++---- lib/importer/admin.ts | 58 +++++++++++++++--------- lib/importer/adminInvite.test.ts | 37 +++++++++++++++ 6 files changed, 124 insertions(+), 38 deletions(-) create mode 100644 lib/importer/adminInvite.test.ts diff --git a/app/(site)/admin/actions.test.ts b/app/(site)/admin/actions.test.ts index a5c47c2..d1482ed 100644 --- a/app/(site)/admin/actions.test.ts +++ b/app/(site)/admin/actions.test.ts @@ -1,14 +1,14 @@ import { beforeEach, expect, it, vi } from "vitest"; -const mocks = vi.hoisted(() => ({ user: vi.fn(), admin: vi.fn(), dismiss: vi.fn(), retry: vi.fn(), after: vi.fn(), revalidate: vi.fn() })); +const mocks = vi.hoisted(() => ({ user: vi.fn(), admin: vi.fn(), dismiss: vi.fn(), retry: vi.fn(), after: vi.fn(), revalidate: vi.fn(), bulk: vi.fn(), approve: vi.fn(), reject: vi.fn(), redirect: vi.fn() })); vi.mock("server-only", () => ({})); -vi.mock("next/navigation", () => ({ notFound: () => { throw new Error("404"); }, redirect: vi.fn() })); +vi.mock("next/navigation", () => ({ notFound: () => { throw new Error("404"); }, redirect: mocks.redirect })); vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidate })); vi.mock("next/server", () => ({ after: mocks.after })); vi.mock("@/lib/auth", () => ({ requireUser: mocks.user })); -vi.mock("@/lib/importer/admin", () => ({ isAdmin: mocks.admin, approve: vi.fn(), reject: vi.fn(), sendInvite: vi.fn() })); +vi.mock("@/lib/importer/admin", () => ({ isAdmin: mocks.admin, approve: mocks.approve, reject: mocks.reject, approveSaleAndInvite: mocks.bulk, sendInvite: vi.fn() })); vi.mock("@/lib/importer/queue", () => ({ dismissSource: mocks.dismiss, retrySource: mocks.retry })); vi.mock("@/lib/importer/importer", () => ({ finishListservRun: vi.fn(), readDeck: vi.fn(), startDeck: vi.fn(), startListservRun: vi.fn() })); -import { sourceAction } from "./actions"; +import { sourceAction, reviewAction } from "./actions"; const id = "10000000-0000-4000-8000-000000000001"; const form = (decision: string, sourceId = id) => { const f = new FormData(); f.set("decision", decision); f.set("sourceId", sourceId); return f; }; beforeEach(() => { vi.resetAllMocks(); mocks.user.mockResolvedValue({ netid: "rp4348" }); mocks.admin.mockReturnValue(true); }); @@ -41,3 +41,20 @@ it("keeps rows with unreviewed listings visible", async () => { mocks.dismiss.mockRejectedValue(new Error("Review the remaining items first.")); expect(await sourceAction(undefined, form("done"))).toEqual({error: "Review the remaining items first."}); }); + +it("bulk approval uses the automatic invite flow and shows its result",async()=>{ + mocks.bulk.mockResolvedValue("Items approved. Test invite sent."); + mocks.redirect.mockImplementation(()=>{throw new Error("redirect");}); + await expect(reviewAction(form("approve"))).rejects.toThrow("redirect"); + expect(mocks.bulk).toHaveBeenCalledWith(id); + expect(mocks.redirect).toHaveBeenCalledWith("/admin/imports?notice=Items%20approved.%20Test%20invite%20sent."); + expect(mocks.approve).not.toHaveBeenCalled(); +}); +it("non-admins cannot trigger bulk approval emails",async()=>{ + mocks.admin.mockReturnValue(false);await expect(reviewAction(form("approve"))).rejects.toThrow("404");expect(mocks.bulk).not.toHaveBeenCalled(); +}); +it("single-item approvals and bulk rejections do not send automatic invites",async()=>{ + const f=new FormData();f.set("decision","approve");f.append("id",id);await reviewAction(f); + expect(mocks.approve).toHaveBeenCalledWith([id]); + await reviewAction(form("reject"));expect(mocks.bulk).not.toHaveBeenCalled();expect(mocks.reject).toHaveBeenCalled(); +}); diff --git a/app/(site)/admin/actions.ts b/app/(site)/admin/actions.ts index ddb0edb..de4a17b 100644 --- a/app/(site)/admin/actions.ts +++ b/app/(site)/admin/actions.ts @@ -5,7 +5,7 @@ import { notFound, redirect } from "next/navigation"; import { revalidatePath } from "next/cache"; import { after } from "next/server"; import { requireUser } from "@/lib/auth"; -import { approve, isAdmin, reject, sendInvite } from "@/lib/importer/admin"; +import { approveSaleAndInvite, approve, isAdmin, reject, sendInvite } from "@/lib/importer/admin"; import { finishListservRun, readDeck, startDeck, startListservRun } from "@/lib/importer/importer"; import { dismissSource, retrySource } from "@/lib/importer/queue"; import { deckIdsIn } from "@/lib/importer/rules"; @@ -68,6 +68,13 @@ export async function inviteAction(_: ImportState, f: FormData): Promise ); } + +export function ApproveAllButton({ children, outline = false }: { children: ReactNode; outline?: boolean }) { + const { pending } = useFormStatus(); + return ; +} diff --git a/app/(site)/admin/imports/page.tsx b/app/(site)/admin/imports/page.tsx index 7b33560..976a789 100644 --- a/app/(site)/admin/imports/page.tsx +++ b/app/(site)/admin/imports/page.tsx @@ -8,17 +8,19 @@ import { netidFromEmail } from "@/lib/importer/rules"; import { formatCents } from "@/lib/rules"; import { AutoRefresh } from "../../_components/AutoRefresh"; import { reviewAction } from "../actions"; -import { ImportForms, InviteButton, SourceButton } from "./ImportForms"; +import { ImportForms, InviteButton, SourceButton, ApproveAllButton } from "./ImportForms"; /* Listserv imports: run them, approve or reject each item before anyone sees it (the admin's approval is the consent to republish), and invite each sale's poster to claim it. */ -export default function ImportsPage() { +type ImportSearch = Promise<{ notice?: string | string[] }>; + +export default function ImportsPage({ searchParams }: { searchParams: ImportSearch }) { return (
loading…

}> - +
@@ -26,7 +28,9 @@ export default function ImportsPage() { ); } -async function Imports() { +async function Imports({ searchParams }: { searchParams: ImportSearch }) { + const params = await searchParams; + const notice = typeof params.notice === "string" ? params.notice : null; const user = await requireUser("/admin/imports"); if (!isAdmin(user.netid)) notFound(); const [queue, runs] = await Promise.all([reviewQueue(), recentRuns()]); @@ -40,6 +44,7 @@ async function Imports() { <> {(runGoing || reading) && }

listserv imports

+ {notice &&

{notice}

}

items from sale decks, and from sales written in an email with photos, wait here until you approve them. approving one publishes it with the contact details from the seller’s own post (only signed-in users see those). send the seller an invite to claim their sale; while @@ -97,12 +102,11 @@ async function Imports() { {/* everything from this seller's sale in one click, without scrolling past it */} {items.length > 1 && (

+ {items.map((it) => ( ))} - + approve all {items.length} from {source.authorName ?? "this sale"}
)} {source.status === "done" && netidFromEmail(source.authorEmail) && ( @@ -154,12 +158,11 @@ async function Imports() { ))}
+ {items.map((it) => ( ))} - + approve all {items.length} diff --git a/lib/importer/admin.ts b/lib/importer/admin.ts index 7e4fdbf..b369dba 100644 --- a/lib/importer/admin.ts +++ b/lib/importer/admin.ts @@ -138,29 +138,43 @@ async function deleteListings(rows: Row[]) { /* Email the person who posted the sale an invite to join and manage it. In test mode (the default) it goes to INVITE_TEST_RECIPIENT, not them. */ -export async function sendInvite(sourceId: string): Promise<{ to: string; test: boolean }> { - const source = await sourceFor(sourceId); - if (!source) throw new Error("No such sale."); - if (!netidFromEmail(source.authorEmail)) throw new Error("This sale has no princeton.edu address to invite."); - const items = await step("count sale items", () => sql()`select id from listings where import_source_id = ${sourceId} and seller_netid = ${IMPORT_ACCOUNT}`); - if (!items.length) throw new Error("Nothing from this sale is left to manage."); - // a double click (SendGrid has no "send once" key): one invite a minute per sale - if (source.invitedAt && Date.now() - new Date(source.invitedAt).getTime() < 60_000) { - throw new Error("An invite for this sale went out less than a minute ago."); - } - const { to, test } = inviteRecipient(source.authorEmail!, process.env); - const mail = inviteEmail({ - name: source.authorName, - sale: source.subject ?? "your sale", - count: items.length, - url: `${env.appUrl()}/welcome/${source.id}`, - intended: source.authorEmail!, - test, +export async function sendInvite(sourceId: string, options: { once?: boolean } = {}): Promise<{ to: string; test: boolean; alreadySent?: boolean }> { + if (!UUID.test(sourceId)) throw new Error("No such sale."); + // Serialize manual and automatic sends for this sale, including across servers. + return sql().begin(async (tx) => { + const [row] = await tx`select * from import_sources where id = ${sourceId} for update`; + if (!row) throw new Error("No such sale."); + const source = toSource(row); + if (!netidFromEmail(source.authorEmail)) throw new Error("This sale has no princeton.edu address to invite."); + const { to, test } = inviteRecipient(source.authorEmail!, process.env); + if (options.once && source.invitedAt && source.invitedTo === to) return { to, test, alreadySent: true }; + const items = await tx`select id from listings where import_source_id = ${sourceId} and seller_netid = ${IMPORT_ACCOUNT} and status = 'active'`; + if (!items.length) throw new Error("There are no approved, unclaimed items from this sale to invite the seller to manage."); + if (source.invitedAt && Date.now() - new Date(source.invitedAt).getTime() < 60_000) { + throw new Error("An invite for this sale went out less than a minute ago."); + } + const mail = inviteEmail({ name: source.authorName, sale: source.subject ?? "your sale", count: items.length, + url: `${env.appUrl()}/welcome/${source.id}`, intended: source.authorEmail!, test }); + await sendMail({ to, ...mail, idempotencyKey: `invite/${source.id}/${Math.floor(Date.now() / 60_000)}` }); + await tx`update import_sources set invited_at = now(), invited_to = ${to} where id = ${source.id}`; + return { to, test }; }); - // a double click within the minute sends once - await sendMail({ to, ...mail, idempotencyKey: `invite/${source.id}/${Math.floor(Date.now() / 60_000)}` }); - await step("record invite", () => sql()`update import_sources set invited_at = now(), invited_to = ${to} where id = ${source.id}`); - return { to, test }; +} + +export async function approveSaleAndInvite(sourceId: string): Promise { + if (!UUID.test(sourceId)) throw new Error("Invalid sale."); + const [eligible] = await sql()`select id from import_sources where id = ${sourceId} and submitted_by is null and status = 'done'`; + if (!eligible) throw new Error("This sale is not ready for admin approval."); + await step("approve sale", () => sql()`update listings set status = 'active' + where import_source_id = ${sourceId} and status = 'review' + and exists (select 1 from import_sources where id = ${sourceId} and submitted_by is null and status = 'done')`); + try { + const result = await sendInvite(sourceId, { once: true }); + if (result.alreadySent) return "Items approved. An invite was already sent; no duplicate email was sent."; + return result.test ? `Items approved. Test invite sent to ${result.to} (not the seller).` : `Items approved. Invite sent to ${result.to}.`; + } catch (e) { + return `Items approved, but the invite was not sent: ${e instanceof Error ? e.message : String(e)}. Use send invite to retry.`; + } } /* ---- on the listing page ---- */ diff --git a/lib/importer/adminInvite.test.ts b/lib/importer/adminInvite.test.ts new file mode 100644 index 0000000..79c0800 --- /dev/null +++ b/lib/importer/adminInvite.test.ts @@ -0,0 +1,37 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +const m=vi.hoisted(()=>({query:vi.fn(),send:vi.fn()})); +vi.mock("server-only",()=>({})); +vi.mock("../db",()=>({sql:()=>Object.assign((first:unknown,...values:unknown[])=>Array.isArray(first)&&"raw" in first?m.query(first,...values):first,{begin:async(fn:(tx:unknown)=>unknown)=>fn((first:unknown,...values:unknown[])=>m.query(first,...values))})})); +vi.mock("../mail",()=>({sendMail:m.send})); +import { approveSaleAndInvite, sendInvite } from "./admin"; +const id="10000000-0000-4000-8000-000000000001"; +const source={id,kind:"deck",author_email:"seller@princeton.edu",subject:"Sale",author_name:"Seller",invited_at:null,invited_to:null}; +beforeEach(()=>{vi.resetAllMocks();vi.stubEnv("APP_URL","https://retail.tigerapps.org");vi.stubEnv("INVITES_TO_SELLERS","");vi.stubEnv("INVITE_TEST_RECIPIENT","rp4348@princeton.edu");}); +it("publishes the sale before sending one automatic test invite",async()=>{ + m.query.mockResolvedValueOnce([{id}]).mockResolvedValueOnce([{id:"item"}]).mockResolvedValueOnce([source]).mockResolvedValueOnce([{id:"item"}]).mockResolvedValueOnce([]); + const result=await approveSaleAndInvite(id); + expect(result).toContain("Test invite");expect(m.send).toHaveBeenCalledTimes(1);expect(m.send.mock.calls[0][0].to).toBe("rp4348@princeton.edu"); + expect(m.query.mock.calls[1][0].join("")).toContain("status = 'active'"); +}); +it("does not automatically resend an invite already delivered to that recipient",async()=>{ + m.query.mockResolvedValueOnce([ {...source,invited_at:"2026-10-01T00:00:00Z",invited_to:"rp4348@princeton.edu"} ]); + const result=await sendInvite(id,{once:true});expect(result.alreadySent).toBe(true);expect(m.send).not.toHaveBeenCalled(); +}); +it("reports email failure while leaving approval successful",async()=>{ + m.query.mockResolvedValueOnce([{id}]).mockResolvedValueOnce([{id:"item"}]).mockResolvedValueOnce([source]).mockResolvedValueOnce([{id:"item"}]);m.send.mockRejectedValue(new Error("mail unavailable")); + expect(await approveSaleAndInvite(id)).toContain("Items approved, but the invite was not sent: mail unavailable"); +}); +it("does not send if the source has no approved unclaimed listings",async()=>{ + m.query.mockResolvedValueOnce([source]).mockResolvedValueOnce([]); + await expect(sendInvite(id,{once:true})).rejects.toThrow("approved");expect(m.send).not.toHaveBeenCalled(); +}); + +afterEach(()=>vi.unstubAllEnvs()); +it("does not approve or invite an unfinished or seller-owned source",async()=>{ + m.query.mockResolvedValueOnce([]);await expect(approveSaleAndInvite(id)).rejects.toThrow("not ready");expect(m.send).not.toHaveBeenCalled();expect(m.query).toHaveBeenCalledTimes(1); +}); +it("locks the source while sending and records delivery only after success",async()=>{ + m.query.mockResolvedValueOnce([source]).mockResolvedValueOnce([{id:"item"}]).mockResolvedValueOnce([]); + await sendInvite(id,{once:true});expect(m.query.mock.calls[0][0].join("")).toContain("for update"); + expect(m.send.mock.invocationCallOrder[0]).toBeLessThan(m.query.mock.invocationCallOrder[2]); +});