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
2 changes: 2 additions & 0 deletions convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,7 @@ import type * as migrations_publicationBalance from "../migrations/publicationBa
import type * as migrations_recordApprovedQueries from "../migrations/recordApprovedQueries.js";
import type * as migrations_reportAuthorNames from "../migrations/reportAuthorNames.js";
import type * as migrations_reportIntake from "../migrations/reportIntake.js";
import type * as migrations_reportIssn from "../migrations/reportIssn.js";
import type * as migrations_revokeDeletedOrganizationMemberships from "../migrations/revokeDeletedOrganizationMemberships.js";
import type * as migrations_rotateKeptFiles from "../migrations/rotateKeptFiles.js";
import type * as migrations_screeningFacets from "../migrations/screeningFacets.js";
Expand Down Expand Up @@ -929,6 +930,7 @@ declare const fullApi: ApiFromModules<{
"migrations/recordApprovedQueries": typeof migrations_recordApprovedQueries;
"migrations/reportAuthorNames": typeof migrations_reportAuthorNames;
"migrations/reportIntake": typeof migrations_reportIntake;
"migrations/reportIssn": typeof migrations_reportIssn;
"migrations/revokeDeletedOrganizationMemberships": typeof migrations_revokeDeletedOrganizationMemberships;
"migrations/rotateKeptFiles": typeof migrations_rotateKeptFiles;
"migrations/screeningFacets": typeof migrations_screeningFacets;
Expand Down
13 changes: 11 additions & 2 deletions convex/billing/autumn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/

import { createError } from "../lib/errors";
import { reportField } from "./stripeRest";

export type AutumnBalance = {
next_reset_at?: number | null;
Expand Down Expand Up @@ -353,7 +354,11 @@ export const autumn = {
quantity?: { feature: string; amount: number };
/** A promotion code of an Autumn reward, taken off the charge. */
code?: string;
/** The report a purchase pays for, kept on Stripe's invoice (metadata `report`): Stripe's receipt can't name it, and a finalized invoice takes no memo. */
/**
* The report a purchase pays for, named on Stripe's invoice: in its metadata (`report`), and in a field at its head
* (`reportField`). An invoice made on Stripe's checkout takes the field here; one Autumn makes itself takes the
* customer's default (billing/stripeRest.ts `invoicesName`), since a finalized invoice takes no text.
*/
report?: string;
/**
* Billed by invoice and given at once, for a purchase quoted at nothing to a customer with no card, after a code or
Expand Down Expand Up @@ -384,7 +389,11 @@ export const autumn = {
// Used only when Autumn sends the person to Stripe's checkout: a customer with no card on file. No checkout has
// Stripe's own promotion code box: a code goes through the Publish page's voucher field, which takes an event's
// code once a person; typed on Stripe's page it would skip that check, and nothing would record its use.
checkout_session_params: { ...(args.checkout ? checkoutParams(args.checkout) : {}), allow_promotion_codes: false },
checkout_session_params: {
...(args.checkout ? checkoutParams(args.checkout) : {}),
allow_promotion_codes: false,
...(args.report && { invoice_creation: { enabled: true, invoice_data: { custom_fields: [reportField(args.report)], metadata: { report: args.report } } } }),
},
...promotion(args.code),
...(args.report ? { metadata: { report: args.report } } : {}),
},
Expand Down
33 changes: 33 additions & 0 deletions convex/billing/stripeRest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// page that comes back to the report, how its invoice stands, and how its Checkout session does.

type Stripe = Record<string, unknown>;
/** How long a request to Stripe is waited for. */
const STRIPE_WAIT_MS = 20_000;

async function stripe(path: string, init: { method?: "GET" | "POST"; form?: Record<string, string> } = {}) {
const key = process.env.STRIPE_SECRET_KEY;
Expand All @@ -11,6 +13,8 @@ async function stripe(path: string, init: { method?: "GET" | "POST"; form?: Reco
method: init.method ?? (init.form ? "POST" : "GET"),
headers: { Authorization: `Bearer ${key}` },
...(init.form && { body: new URLSearchParams(init.form) }),
// Stripe answers in a second or two: a request that hangs is given up, so nothing waits on it for minutes.
signal: AbortSignal.timeout(STRIPE_WAIT_MS),
});
if (!response.ok) throw new Error(`Stripe answered ${response.status}: ${(await response.text()).slice(0, 300)}`);
return (await response.json()) as Stripe;
Expand Down Expand Up @@ -40,6 +44,35 @@ export async function voidDeclined(invoice: string) {
}
}

/** The field at the head of an invoice that names the report it pays for. */
export const reportField = (report: string) => ({ name: "Report", value: report });

/**
* Has the invoices Stripe makes for a customer name a report (`on`), or stops them naming it. A paid invoice takes no
* text, and Autumn charges a saved card, or bills an account's credit, with an invoice it makes itself: the field is
* the customer's default for the moment of that charge, under the workspace's purchase lock, and comes off after.
* Taking it off leaves a field that names another report by now. A failure never stops a charge: the invoice goes
* without its field, or the field is taken off by the later asking (reports/activation.ts `unnameInvoices`). Whether
* it was done.
*/
export async function invoicesName(customer: string, report: string, on: boolean): Promise<boolean> {
const path = `customers/${encodeURIComponent(customer)}`;
const { name, value } = reportField(report);
try {
if (on) {
// ponytail: replaces default fields set on the customer in Stripe's dashboard, which nothing sets today; read them first and put them back if that changes.
await stripe(path, { form: { "invoice_settings[custom_fields][0][name]": name, "invoice_settings[custom_fields][0][value]": value } });
return true;
}
const fields = ((await stripe(path)).invoice_settings as { custom_fields?: Array<{ name: string; value: string }> | null } | undefined)?.custom_fields ?? [];
if (fields.some((field) => field.name === name && field.value === value)) await stripe(path, { form: { "invoice_settings[custom_fields]": "" } });
return true;
} catch (error) {
console.error(JSON.stringify({ event: on ? "invoice-field-not-set" : "invoice-field-not-cleared", customer, report, error: String(error).slice(0, 400) }));
return false;
}
}

/**
* What a Stripe customer has toward a charge: the credit on its balance in US dollars, which Stripe takes an invoice
* from before the card (a refund of a plan's unused days, say), 0 for none; and its currency when that isn't US
Expand Down
26 changes: 26 additions & 0 deletions convex/migrations/reportIssn.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { api, internal } from "../_generated/api";
import { checked, live, passed, row, setup } from "../reports/reports.test-support";

describe("reports that went live before they kept their ISSN", () => {
it("get the one their series has now and keep it, and a draft gets none", async () => {
const world = await setup();
const published = await live(world);
// In the organisation, as a plan starts one report a day.
const draft = await checked(world, [passed("byline"), passed("harm")], world.author, world.lab);
// As a report read before the field was kept.
await world.t.run((ctx) => ctx.db.patch("reports", published.reportId, { issn: undefined }));
await world.reviewer.mutation(api.reports.settings.update, { series: { issn: "2049-3630" } });

expect(await world.t.action(internal.migrations.reportIssn.run, { dryRun: true })).toBe(1);
expect((await row(world.t, published.key)).issn).toBeUndefined();
expect(await world.t.action(internal.migrations.reportIssn.run, { dryRun: false })).toBe(1);
expect((await row(world.t, published.key)).issn).toBe("2049-3630");
expect((await row(world.t, draft.key)).issn).toBeUndefined();

// The series' next ISSN isn't its: a second run finds nothing to do.
await world.reviewer.mutation(api.reports.settings.update, { series: { issn: "1234-5679" } });
expect(await world.t.action(internal.migrations.reportIssn.run, { dryRun: false })).toBe(0);
expect((await row(world.t, published.key)).issn).toBe("2049-3630");
});
});
47 changes: 47 additions & 0 deletions convex/migrations/reportIssn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { v } from "convex/values";
import { internal } from "../_generated/api";
import { internalAction, internalMutation } from "../lib/functions";
import { reportSettings, seriesReader } from "../reports/settings";

/**
* Gives each report that went live before reports kept their ISSN (`issn`) the one its series has now, empty for none,
* which is what its page and its registrations show today. From then on an ISSN the series gets never reaches it. Run
* once per deployment right after its Convex push, and before any series is given an ISSN, first with `dryRun` for
* the count:
* npx convex run migrations/reportIssn:run '{"dryRun":true}'
* npx convex run migrations/reportIssn:run '{"dryRun":false}'
* Safe to run again: a report that keeps one is left alone, and so is one that never went live.
*/
export const run = internalAction({
args: { dryRun: v.boolean() },
returns: v.number(),
handler: async (ctx, { dryRun }): Promise<number> => {
let kept = 0;
let cursor: string | null = null;
for (;;) {
const read: { kept: number; next: string | null } = await ctx.runMutation(internal.migrations.reportIssn.page, { cursor, dryRun });
kept += read.kept;
if (read.next === null) break;
cursor = read.next;
}
console.log(JSON.stringify({ event: "report-issn", dryRun, kept }));
return kept;
},
});

/** One page of reports: each that went live and keeps no ISSN gets its series' as it is now. Its `updatedAt` stays, since nothing it shows changes. */
export const page = internalMutation({
args: { cursor: v.union(v.string(), v.null()), dryRun: v.boolean() },
returns: v.object({ kept: v.number(), next: v.union(v.string(), v.null()) }),
handler: async (ctx, { cursor, dryRun }) => {
const seriesOf = seriesReader(ctx, (await reportSettings(ctx)).series);
const read = await ctx.db.query("reports").paginate({ cursor, numItems: 100 });
let kept = 0;
for (const report of read.page) {
if (report.activatedAt === undefined || report.issn !== undefined) continue;
kept++;
if (!dryRun) await ctx.db.patch("reports", report._id, { issn: (await seriesOf(report)).issn });
}
return { kept, next: read.isDone ? null : read.continueCursor };
},
});
24 changes: 21 additions & 3 deletions convex/reports/activation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,20 +56,25 @@ function autumnStub({ monthly = 0, kept = 0, card = false, dropFirstQuote = fals
let dropped = !dropFirstQuote;
/** How Stripe has the checkout session Autumn made. */
let session: "open" | "paid" | "expired" = "open";
/** The reports the customer's invoices name at Stripe, by its default field. */
let named: string[] = [];
const left = () => entries.reduce((sum, entry) => sum + entry.remaining, 0);
const add = (amount: number) => entries.push({ id: `bought-${entries.length}`, plan_id: TOP_UP, remaining: amount, prepaid_grant: amount, reset: { interval: "one_off", resets_at: null } });
vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
if (url.includes("api.stripe.com/v1/checkout/sessions/")) {
if (url.endsWith("/expire")) session = "expired";
return Response.json(session === "paid" ? { status: "complete", payment_status: "paid", invoice: "in_checkout" } : { status: session, payment_status: "unpaid", invoice: null });
}
if (stripeCurrency && url.includes("api.stripe.com/v1/customers/")) return Response.json({ id: "cus_test", currency: stripeCurrency, balance: -Math.round(credit * 100) });
if (stripeCurrency && url.includes("api.stripe.com/v1/customers/")) {
if (init?.method === "POST") named = [new URLSearchParams(String(init.body)).get("invoice_settings[custom_fields][0][value]")].filter((value) => value !== null);
return Response.json({ id: "cus_test", currency: stripeCurrency, balance: -Math.round(credit * 100), invoice_settings: { custom_fields: named.map((value) => ({ name: "Report", value })) } });
}
if (url.startsWith("https://api.stripe.com")) return Response.json({ id: "in_late", status: "paid", total: stripeTotal, amount_due: Math.max(0, stripeTotal - credit * 100), currency: "usd", payments: { data: [] } });
const path = url.split("/v1/")[1]!;
// AFEW26 is an event's code: its reward's id starts event_.
if (path === "rewards.list") return Response.json({ coupons: [{ id: "activation_free", promo_codes: [{ code: "FREEDOI" }] }, { id: "event_afew_2026", promo_codes: [{ code: "AFEW26" }] }], feature_grants: [] });
const key = (init?.headers as Record<string, string> | undefined)?.["Idempotency-Key"];
const body = JSON.parse(String(init?.body ?? "{}")) as { customer_id?: string; email?: string; feature_id?: string; required_balance?: number; lock?: { lock_id: string }; lock_id?: string; action?: string; discounts?: Array<{ promotion_code: string }>; invoice_mode?: unknown; redirect_mode?: string; checkout_session_params?: { saved_payment_method_options?: unknown }; customize?: { items?: Array<{ price?: { amount: number; billing_units: number } }> }; feature_quantities?: Array<{ feature_id: string; quantity: number }>; balance_id?: string; add_to_balance?: number };
const body = JSON.parse(String(init?.body ?? "{}")) as { customer_id?: string; email?: string; feature_id?: string; required_balance?: number; lock?: { lock_id: string }; lock_id?: string; action?: string; discounts?: Array<{ promotion_code: string }>; invoice_mode?: unknown; redirect_mode?: string; checkout_session_params?: { saved_payment_method_options?: unknown; invoice_creation?: { invoice_data: { custom_fields: Array<{ name: string; value: string }> } } }; customize?: { items?: Array<{ price?: { amount: number; billing_units: number } }> }; feature_quantities?: Array<{ feature_id: string; quantity: number }>; balance_id?: string; add_to_balance?: number };
const quantity = body.feature_quantities?.[0]?.quantity ?? 0;
const due = quantity * (1 - (OFF[body.discounts?.[0]?.promotion_code ?? ""] ?? 0));
if (path === "billing.preview_attach") {
Expand Down Expand Up @@ -103,7 +108,7 @@ function autumnStub({ monthly = 0, kept = 0, card = false, dropFirstQuote = fals
return Response.json({ success: true });
}
if (path === "billing.attach") {
asked.push({ path, quantity, priced: body.customize?.items?.[0]?.price, discounts: body.discounts, invoice_mode: body.invoice_mode, redirect: body.redirect_mode, saved: body.checkout_session_params?.saved_payment_method_options });
asked.push({ path, quantity, priced: body.customize?.items?.[0]?.price, discounts: body.discounts, invoice_mode: body.invoice_mode, redirect: body.redirect_mode, saved: body.checkout_session_params?.saved_payment_method_options, pageNames: body.checkout_session_params?.invoice_creation?.invoice_data.custom_fields.map((field) => field.value), invoiceNames: named });
// Something to pay and no card, or Stripe's page asked for by name: Stripe's page, and nothing given until it is paid.
if ((!card || body.redirect_mode === "always") && !body.invoice_mode) return Response.json({ payment_url: CHECKOUT });
if (!keys.has(key!)) add(quantity);
Expand All @@ -129,6 +134,8 @@ function autumnStub({ monthly = 0, kept = 0, card = false, dropFirstQuote = fals
asked,
/** Autumn gives dollars bought, as it does a moment after Stripe has the payment. */
give: add,
/** The reports the customer's invoices name now. */
invoiceNames: () => named,
/** What each of the customer's balances holds now, by its id. */
holds: () => Object.fromEntries(entries.map((entry) => [entry.id, entry.remaining])),
/** The person paid on Stripe's page: Autumn gives what was bought and has its invoice, paid. */
Expand Down Expand Up @@ -400,6 +407,17 @@ describe("activating a report", () => {
expect(autumn.asked.filter((call) => call.path === "billing.attach")).toMatchObject([{ quantity: 1.2 }]);
});

it("names the report on its invoice: Stripe's page is told to, and an invoice made for a saved card takes the customer's field, which comes off after", async () => {
const world = await setup();
const { key } = await checked(world, [passed("byline")]);
const autumn = autumnStub({ card: true, stripeCurrency: "usd" });
vi.stubEnv("STRIPE_SECRET_KEY", "sk_test_fake");
expect(await world.author.action(api.reports.activation.activate, { workspaceId: world.own, key, payWith: "card", price: 10, expect: 10, card: "4242" })).toEqual({ live: true });
vi.unstubAllGlobals();
expect(autumn.asked.filter((call) => call.path === "billing.attach")).toMatchObject([{ pageNames: [key], invoiceNames: [key] }]);
expect(autumn.invoiceNames()).toEqual([]);
});

it("says what a card bought past the price to reach Stripe's least charge went to the balance", async () => {
const world = await setup();
const { key } = await checked(world, [passed("byline")]);
Expand Down
Loading
Loading