import { api, type BulkResult } from "../api/client"; import { readableError } from "./errors"; import { toast } from "./toast"; type Call = (body: Record) => Promise; /** * Runs a bulk action and says how it went, with an Undo button that sends back the body the server handed over with its answer. What was left alone is said too, * with why — so "12 of 14" is never a mystery. `reload` is called after the action and after an undo, so the page shows what is true. */ export async function doBulk(options: { call: Call; body: Record; done: (r: BulkResult) => string; reload: () => void }): Promise { try { const r = await options.call(options.body); const why = [...new Set(r.skipped.map((s) => s.reason))]; const skipped = r.skipped.length > 0 ? ` ${r.skipped.length} left alone: ${why.slice(0, 2).join("; ")}${why.length > 2 ? "…" : ""}.` : ""; const message = r.changed > 0 ? options.done(r) + skipped : `Nothing changed.${skipped}`; const undo = r.undo; toast.success( message, undo ? { label: "Undo", onClick: async () => { try { await options.call(undo); toast.info("Undone."); } catch (err) { toast.error(readableError(err)); } finally { options.reload(); } }, } : undefined, ); options.reload(); return r; } catch (err) { toast.error(readableError(err)); return null; } } export const bulk = api.bulk; export const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;