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
25 changes: 21 additions & 4 deletions app/(site)/admin/actions.test.ts
Original file line number Diff line number Diff line change
@@ -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); });
Expand Down Expand Up @@ -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();
});
9 changes: 8 additions & 1 deletion app/(site)/admin/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -68,6 +68,13 @@ export async function inviteAction(_: ImportState, f: FormData): Promise<ImportS

export async function reviewAction(f: FormData) {
await requireAdmin();
if (f.get("decision") === "approve" && f.get("sourceId")) {
let notice: string;
try { notice = await approveSaleAndInvite(String(f.get("sourceId"))); }
catch (e) { notice = `Approval failed: ${e instanceof Error ? e.message : String(e)}`; }
revalidatePath("/", "layout");
redirect(`/admin/imports?notice=${encodeURIComponent(notice)}`);
}
const ids = f.getAll("id").map(String);
if (f.get("decision") === "approve") await approve(ids);
else await reject(ids);
Expand Down
10 changes: 9 additions & 1 deletion app/(site)/admin/imports/ImportForms.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";
import { useActionState } from "react";
import { useActionState, type ReactNode } from "react";
import { useFormStatus } from "react-dom";
import { importLinkAction, inviteAction, sourceAction, runNowAction, type ImportState } from "../actions";

export function ImportForms({ engineConfigured }: { engineConfigured: boolean }) {
Expand Down Expand Up @@ -81,3 +82,10 @@ export function SourceButton({ sourceId, decision, disabled = false }: { sourceI
</form>
);
}

export function ApproveAllButton({ children, outline = false }: { children: ReactNode; outline?: boolean }) {
const { pending } = useFormStatus();
return <button className={`btn ${outline ? "btn-outline" : "btn-primary"}`} name="decision" value="approve" disabled={pending}>
{pending ? "approving & sending…" : children}
</button>;
}
23 changes: 13 additions & 10 deletions app/(site)/admin/imports/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,29 @@ 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 (
<div className="wf">
<div className="wrap" style={{ paddingTop: 24 }}>
<Suspense fallback={<p className="sub">loading…</p>}>
<Imports />
<Imports searchParams={searchParams} />
</Suspense>
<div style={{ height: 70 }} />
</div>
</div>
);
}

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()]);
Expand All @@ -40,6 +44,7 @@ async function Imports() {
<>
{(runGoing || reading) && <AutoRefresh />}
<h1 className="sec-title">listserv imports</h1>
{notice && <p className="note" role="status">{notice}</p>}
<p className="sub" style={{ marginTop: 4 }}>
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&rsquo;s own post (only signed-in users see those). send the seller an invite to claim their sale; while
Expand Down Expand Up @@ -97,12 +102,11 @@ async function Imports() {
{/* everything from this seller's sale in one click, without scrolling past it */}
{items.length > 1 && (
<form action={reviewAction}>
<input type="hidden" name="sourceId" value={source.id} />
{items.map((it) => (
<input key={it.id} type="hidden" name="id" value={it.id} />
))}
<button className="btn btn-primary" name="decision" value="approve" style={{ padding: "6px 14px" }}>
approve all {items.length} from {source.authorName ?? "this sale"}
</button>
<ApproveAllButton>approve all {items.length} from {source.authorName ?? "this sale"}</ApproveAllButton>
</form>
)}
{source.status === "done" && netidFromEmail(source.authorEmail) && (
Expand Down Expand Up @@ -154,12 +158,11 @@ async function Imports() {
))}
</div>
<form action={reviewAction} style={{ display: "flex", gap: 10, marginTop: 12 }}>
<input type="hidden" name="sourceId" value={source.id} />
{items.map((it) => (
<input key={it.id} type="hidden" name="id" value={it.id} />
))}
<button className="btn btn-outline" name="decision" value="approve">
approve all {items.length}
</button>
<ApproveAllButton outline>approve all {items.length}</ApproveAllButton>
<button className="btn btn-ghost" name="decision" value="reject">
reject all
</button>
Expand Down
58 changes: 36 additions & 22 deletions lib/importer/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()<Row[]>`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<Row[]>`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<Row[]>`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<string> {
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 ---- */
Expand Down
37 changes: 37 additions & 0 deletions lib/importer/adminInvite.test.ts
Original file line number Diff line number Diff line change
@@ -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]);
});
Loading