diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index d4477628a..9757be908 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -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"; @@ -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; diff --git a/convex/billing/autumn.ts b/convex/billing/autumn.ts index 0c46e3a00..b01f9ef7c 100644 --- a/convex/billing/autumn.ts +++ b/convex/billing/autumn.ts @@ -4,6 +4,7 @@ */ import { createError } from "../lib/errors"; +import { reportField } from "./stripeRest"; export type AutumnBalance = { next_reset_at?: number | null; @@ -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 @@ -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 } } : {}), }, diff --git a/convex/billing/stripeRest.ts b/convex/billing/stripeRest.ts index f0eb6e9ad..6f34ec196 100644 --- a/convex/billing/stripeRest.ts +++ b/convex/billing/stripeRest.ts @@ -3,6 +3,8 @@ // page that comes back to the report, how its invoice stands, and how its Checkout session does. type Stripe = Record; +/** 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 } = {}) { const key = process.env.STRIPE_SECRET_KEY; @@ -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; @@ -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 { + 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 diff --git a/convex/migrations/reportIssn.test.ts b/convex/migrations/reportIssn.test.ts new file mode 100644 index 000000000..054d70ffe --- /dev/null +++ b/convex/migrations/reportIssn.test.ts @@ -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"); + }); +}); diff --git a/convex/migrations/reportIssn.ts b/convex/migrations/reportIssn.ts new file mode 100644 index 000000000..67415365f --- /dev/null +++ b/convex/migrations/reportIssn.ts @@ -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 => { + 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 }; + }, +}); diff --git a/convex/reports/activation.test.ts b/convex/reports/activation.test.ts index c94999de4..c64c4747f 100644 --- a/convex/reports/activation.test.ts +++ b/convex/reports/activation.test.ts @@ -56,6 +56,8 @@ 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) => { @@ -63,13 +65,16 @@ function autumnStub({ monthly = 0, kept = 0, card = false, dropFirstQuote = fals 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 | 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") { @@ -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); @@ -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. */ @@ -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")]); diff --git a/convex/reports/activation.ts b/convex/reports/activation.ts index 29a08eb0d..4a6b69786 100644 --- a/convex/reports/activation.ts +++ b/convex/reports/activation.ts @@ -25,7 +25,7 @@ import { readCatalog } from "../billing/catalog"; import { balancePartsValidator } from "../billing/validators"; import { isLockNotFound } from "../billing/charge"; import { holdingPurchaseLock, payableCustomer, unlessDeclined } from "../billing/purchases"; -import { bankPage, chargeOf, checkoutId, checkoutOf, expireCheckout, invoicePage, stripeFunds, voidDeclined, voidInvoice } from "../billing/stripeRest"; +import { bankPage, chargeOf, checkoutId, checkoutOf, expireCheckout, invoicePage, invoicesName, stripeFunds, voidDeclined, voidInvoice } from "../billing/stripeRest"; import { PUBLICATION_FEATURE, PUBLICATION_TOP_UP_PLAN } from "../../lib/billing/plans"; import { BOUGHT_MIN, CODE_MAX, PRICE_MAX, STRIPE_MIN, cents, costLines, costOf, nothingToPay, payment, stageOf, type PayWith } from "../../lib/reports/report"; import { canRegister } from "../../lib/reports/settings"; @@ -34,7 +34,7 @@ import { MOVED_ON, activatingOwner, byKey, changing, mayChange, paymentOf, touch import { becameReady, notify } from "./mail"; import { register } from "./registering"; import { accountsOf } from "./registration"; -import { humanReviewOf, limitsOf, reportSettings } from "./settings"; +import { humanReviewOf, limitsOf, reportSettings, seriesFor } from "./settings"; import { refuseClosed } from "./intake"; import { billLinesValidator, payWithValidator } from "./validators"; @@ -254,7 +254,8 @@ const chargeValidator = v.object({ invoice: v.string(), total: v.number(), curre /** Puts the report live and registers its DOI, as its first activation. */ async function putLive(ctx: MutationCtx, report: Doc<"reports">) { - await touch(ctx, report, { status: "live", activatedAt: Date.now() }); + // With the ISSN its series has now, which it keeps whatever the series gets later. + await touch(ctx, report, { status: "live", activatedAt: Date.now(), issn: (await seriesFor(ctx, report)).issn }); await register(ctx, report); await notify(ctx, report._id, "live"); await notify(ctx, report._id, "live-author"); @@ -803,7 +804,18 @@ async function activateAs(ctx: ActionCtx, actor: Actor, { key, payWith, code: ty // it takes its admin's, who is the one activating. if (cardless && !customer.email && first.email) await autumn.customer(first.customerId, { email: first.email }); // With no saved card and something to pay, Autumn answers Stripe's page for it, which comes back to the report. - const charged = await autumn.attach({ customerId: first.customerId, planId: PUBLICATION_TOP_UP_PLAN, quantity: dollars(bought), code, idempotencyKey: nameOf(activationId), report: key, successUrl: backTo(first.prefix, key, activationId), checkout: { locale, saved: elsewhere }, ...(cardless && free && { unbilled: true }) }).catch(refusedCode(code)); + // An invoice Autumn makes now, for a saved card or the account's credit, names the report through the + // customer's default field, which comes off after; Stripe's page names it itself (`autumn.attach`). Asked + // again later too, so an action that dies here leaves no field for the customer's next invoice. + const invoiced = !elsewhere && (!cardless || free) ? customer.stripe_id : undefined; + if (invoiced) { + await ctx.scheduler.runAfter(FIELD_OFF_MS, internal.reports.activation.unnameInvoices, { workspaceId, customer: invoiced, report: key }); + await invoicesName(invoiced, key, true); + } + const charged = await autumn + .attach({ customerId: first.customerId, planId: PUBLICATION_TOP_UP_PLAN, quantity: dollars(bought), code, idempotencyKey: nameOf(activationId), report: key, successUrl: backTo(first.prefix, key, activationId), checkout: { locale, saved: elsewhere }, ...(cardless && free && { unbilled: true }) }) + .catch(refusedCode(code)) + .finally(() => (invoiced ? invoicesName(invoiced, key, false) : undefined)); // Declined, its invoice is voided so the decline changes nothing: the next try, with another card or a code, // isn't held up by an invoice left open. if (charged.required_action?.code === "payment_failed" && charged.invoice?.stripe_id) await voidDeclined(charged.invoice.stripe_id); @@ -892,6 +904,28 @@ export const approvedOnly = internalMutation({ /** How long an activation waits for another of its workspace's to finish: far longer than one takes, unless a bank is asked. */ const LOCK_WAIT_MS = 20_000; +/** How long after a charge its report's field is taken off the customer's invoices again, in case the action that set it died. */ +const FIELD_OFF_MS = 2 * 60_000; + +/** How many times that is asked again when Stripe can't be reached or another purchase holds the workspace. */ +const FIELD_OFF_TRIES = 5; + +/** + * Stops a customer's invoices naming a report (billing/stripeRest.ts `invoicesName`), under the workspace's purchase + * lock: between reading the field and taking it off, no later charge of the workspace sets its own. Asked again + * while it can't be done. + * ponytail: a purchase that isn't a report's, made in the minutes after Stripe refused both this and the charge's own + * clearing, still takes the field; clear it before every purchase if that ever shows on an invoice. + */ +export const unnameInvoices = internalAction({ + args: { workspaceId: v.id("workspaces"), customer: v.string(), report: v.string(), attempt: v.optional(v.number()) }, + returns: v.null(), + handler: async (ctx, { workspaceId, customer, report, attempt = 0 }) => { + const off = await holdingPurchaseLock(ctx, workspaceId, () => invoicesName(customer, report, false), LOCK_WAIT_MS).catch(() => false); + if (!off && attempt < FIELD_OFF_TRIES) await ctx.scheduler.runAfter(FIELD_OFF_MS, internal.reports.activation.unnameInvoices, { workspaceId, customer, report, attempt: attempt + 1 }); + return null; + }, +}); /** An error that means nothing was bought: our own refusals, a declined card, a code or a request Autumn refused. */ const boughtNothing = (error: unknown) => error instanceof ConvexError || (error instanceof AutumnError && error.status >= 400 && error.status < 500); diff --git a/convex/reports/paper.test.ts b/convex/reports/paper.test.ts index d865c9aeb..dc8d51df6 100644 --- a/convex/reports/paper.test.ts +++ b/convex/reports/paper.test.ts @@ -203,7 +203,7 @@ describe("a report's page", () => { await expect(world.author.mutation(api.library.mutations.setPaperInCollection, { workspaceId: world.own, paper: { paper: `report:${waiting.key}`, title: "A guess" }, collectionId, inCollection: true })).rejects.toMatchObject({ data: expect.objectContaining({ code: "NOT_FOUND", message: "No report published on Openscholar has this key." }) }); }); - it("brings its saved copies in step with a reviewer's edit while withdrawn, and with the series' new ISSN", async () => { + it("brings its saved copies in step with a reviewer's edit while withdrawn, and leaves them the ISSN it went live with", async () => { vi.useFakeTimers(); try { const world = await setup(); @@ -213,13 +213,12 @@ describe("a report's page", () => { const page = await world.t.query(api.reports.paper.get, { key }); if (page?.state !== "live") throw new Error("The report isn't live"); await decide(world, key, "withdraw"); + // The series got its ISSN since the report went live. + await world.reviewer.mutation(api.reports.settings.update, { series: { issn: "2049-3630" } }); await world.reviewer.mutation(api.reports.review.editDetails, { key, seenAt: (await row(world.t, key)).updatedAt, metadata: { ...page.metadata, title: "Shade trees, retitled" } }); await world.t.finishAllScheduledFunctions(vi.runAllTimers); expect((await copy()).title).toBe("Withdrawn: Shade trees, retitled"); - - await world.reviewer.mutation(api.reports.settings.update, { series: { issn: "2049-3630" } }); - await world.t.finishAllScheduledFunctions(vi.runAllTimers); - expect(JSON.parse((await copy()).paperData!)).toMatchObject({ primary_location: { source: { issn_l: "2049-3630" } } }); + expect(JSON.parse((await copy()).paperData!)).toMatchObject({ primary_location: { source: { issn_l: null } } }); } finally { vi.useRealTimers(); } diff --git a/convex/reports/registration.test.ts b/convex/reports/registration.test.ts index 22516c5d7..2901e99ed 100644 --- a/convex/reports/registration.test.ts +++ b/convex/reports/registration.test.ts @@ -240,6 +240,19 @@ describe("registering a live report", () => { expect(await world.t.mutation(internal.reports.registration.begin, { reportId, rev: before })).toBeNull(); }); + it("sends a correction with the ISSN the report went live with, never one its series got since", async () => { + const world = await setup(); + const { key, reportId } = await live(world); + await settled(world); + await world.reviewer.mutation(api.reports.settings.update, { series: { issn: "2049-3630" } }); + await world.reviewer.mutation(api.reports.review.editDetails, { key, seenAt: (await row(world.t, key)).updatedAt, metadata: details("A corrected title") }); + await world.t.run((ctx) => ctx.db.patch("reports", reportId, { registrationLease: undefined })); + expect(await world.t.mutation(internal.reports.registration.begin, { reportId, rev: await revOf(world, reportId) })).toMatchObject({ series: { issn: "" } }); + // One that goes live from then on carries it. In the organisation, as a plan starts one report a day. + const next = await live(world, world.author, world.lab); + expect(await world.t.mutation(internal.reports.registration.begin, { reportId: next.reportId, rev: await revOf(world, next.reportId) })).toMatchObject({ series: { issn: "2049-3630" } }); + }); + it("goes to its registrars again when it is withdrawn and when it is reinstated", async () => { const world = await setup(); const { key, reportId } = await live(world); diff --git a/convex/reports/searchIndex.test.ts b/convex/reports/searchIndex.test.ts index c7d71f968..7545e4ec9 100644 --- a/convex/reports/searchIndex.test.ts +++ b/convex/reports/searchIndex.test.ts @@ -87,14 +87,18 @@ describe("the search index's feed of reports", () => { expect(Number.isInteger(all.seriesChangedAt)).toBe(true); }); - it("says when the series changed, which every record names", async () => { + it("says when the series changed, and leaves a live report the ISSN it went live with", async () => { const world = await setup(); - await live(world); + const { key } = await live(world); const before = (await page(world, { after: null, limit: 200 })).seriesChangedAt; await world.reviewer.mutation(api.reports.settings.update, { series: { issn: "2049-3630" } }); + // In the organisation, as a plan starts one report a day. + const later = await live(world, world.author, world.lab); const next = await page(world, { all: true, cursor: null, limit: 200 }); expect(next.seriesChangedAt).toBeGreaterThan(before); - expect(next.items[0]!.record).toMatchObject({ series: { issn: "2049-3630" } }); + const record = (of: string) => next.items.find((item) => item.key === of)!.record; + expect(record(key)).toMatchObject({ series: { issn: null } }); + expect(record(later.key)).toMatchObject({ series: { issn: "2049-3630" } }); }); it("gives a report again when Zenodo's DOI for it arrives after it went live", async () => { diff --git a/convex/reports/searchIndex.ts b/convex/reports/searchIndex.ts index 2d94d2255..c446e5543 100644 --- a/convex/reports/searchIndex.ts +++ b/convex/reports/searchIndex.ts @@ -57,7 +57,7 @@ const pageValidator = v.object({ after: v.union(positionValidator, v.null()), cursor: v.union(v.string(), v.null()), done: v.boolean(), - /** When the series' settings last changed: a new ISSN changes every record, though no report's own `updatedAt` moves. */ + /** When the series' settings last changed: a new name changes the record of a report signed before reports kept theirs, though no report's own `updatedAt` moves. */ seriesChangedAt: v.number(), }); diff --git a/convex/reports/settings.ts b/convex/reports/settings.ts index d05fc16b6..f713a2bbc 100644 --- a/convex/reports/settings.ts +++ b/convex/reports/settings.ts @@ -165,13 +165,14 @@ export async function humanReviewOf(ctx: QueryCtx, workspaceId: Id<"workspaces"> } /** - * Reads the series each of a list's reports was signed in, as it stands: the name and publisher it was signed under, - * and the ISSN that series has now, its workspace's own or the series'. A workspace's settings are read once. + * Reads the series each of a list's reports was signed in: the name and publisher it was signed under, and the ISSN + * it went live with. One not yet live reads the ISSN that series has now, its workspace's own or the series'. A + * workspace's settings are read once. */ export function seriesReader(ctx: QueryCtx, site: Pick) { const read = new Map, Promise | undefined>>(); - return async (report: Pick, "workspaceId" | "seriesName" | "publisher" | "ownSeries">) => { - if (!report.ownSeries) return seriesOf(report, site); + return async (report: Pick, "workspaceId" | "seriesName" | "publisher" | "ownSeries" | "issn">) => { + if (!report.ownSeries || report.issn !== undefined) return seriesOf(report, site); if (!read.has(report.workspaceId)) read.set(report.workspaceId, ownRow(ctx, report.workspaceId).then((kept) => kept?.series)); return seriesOf(report, (await read.get(report.workspaceId)) ?? site); }; @@ -179,7 +180,7 @@ export function seriesReader(ctx: QueryCtx, site: Pick) /** The series one report was signed in (`seriesReader`). */ export const seriesFor = async (ctx: QueryCtx, report: Parameters>[0]) => seriesReader(ctx, (await reportSettings(ctx)).series)(report); -/** When any series' settings last changed, the series' own or a workspace's: a new ISSN changes every record of its reports. */ +/** When any series' settings last changed, the series' own or a workspace's: a new name changes the record of every report signed before reports kept theirs. */ export async function settingsChangedAt(ctx: QueryCtx) { const row = await ctx.db.query("reportSettings").first(); const latest = await ctx.db.query("workspaceReportSettings").withIndex("by_updatedAt").order("desc").first(); @@ -551,8 +552,9 @@ export const update = mutation({ if (problem) throw createError("VALIDATION_ERROR", SERIES_PROBLEM[problem]); const named: Series = { ...kept.now, ...typed }; await kept.save(named); - // Every report's saved copies name its series and its ISSN (./saved.ts). - if (named.name !== kept.now.name || named.issn !== kept.now.issn) await ctx.scheduler.runAfter(0, internal.reports.saved.followAll, {}); + // A report's saved copies name its series (./saved.ts), and one signed before reports kept their series' name + // takes the new one. A new ISSN changes none: a live report keeps the one it went live with. + if (named.name !== kept.now.name) await ctx.scheduler.runAfter(0, internal.reports.saved.followAll, {}); } if (identifiers) { const kept = await editing(ctx, workspaceId, "identifiers"); diff --git a/convex/reports/validators.ts b/convex/reports/validators.ts index ab245fd2c..131266f4f 100644 --- a/convex/reports/validators.ts +++ b/convex/reports/validators.ts @@ -313,6 +313,12 @@ export const reportFields = { publisher: v.optional(v.string()), /** It was signed under its workspace's own Series section, whose ISSN it takes; without, the series' own. */ ownSeries: v.optional(v.literal(true)), + /** + * The ISSN its series had the moment it went live, empty for none. It keeps that one: an ISSN the series gets later + * never reaches the page, the feed or the registrations of a report already published. Until it goes live it has + * none here, and reads the series' as it is (`seriesOf`). + */ + issn: v.optional(v.string()), /** No byline was asked for when it was signed: its PDF goes as it is, and nothing looks for the line in it. */ bylineOff: v.optional(v.literal(true)), /** What it was signed for cost nothing then: its agreement leaves out the fee section, and it stays free whatever the settings charge later (lib/reports/report.ts `costOf`). */ diff --git a/lib/reports/settings.ts b/lib/reports/settings.ts index d1df91b33..87a7d28db 100644 --- a/lib/reports/settings.ts +++ b/lib/reports/settings.ts @@ -189,11 +189,12 @@ export const startWords = (perDay: number, kind: WorkspaceKind) => { export const canRegister = (publication: PublicationSettings, identifiers: Identifiers = DEFAULT_IDENTIFIERS) => settingsProblem(withAccounts(identifiers, publication)) === null; /** * The series a report is published in: the name and publisher it was signed under, which its byline prints, and the - * ISSN as the series has it now. One signed before publishers were kept is Openscholar's. + * ISSN it went live with, which a later ISSN never replaces. One not yet live reads the ISSN the series has now, and + * one signed before publishers were kept is Openscholar's. */ -export const seriesOf = (report: { seriesName?: string; publisher?: string }, series: Pick) => { +export const seriesOf = (report: { seriesName?: string; publisher?: string; issn?: string }, series: Pick) => { const name = report.seriesName ?? series.name; - return { name, issn: issnOf({ name, issn: series.issn }), publisher: report.publisher ?? PUBLISHER }; + return { name, issn: issnOf({ name, issn: report.issn ?? series.issn }), publisher: report.publisher ?? PUBLISHER }; }; /** * A series' ISSN as anything shows or sends it: an ISSN is a series', so with no series name there is none, whatever diff --git a/messages/af.json b/messages/af.json index 034e2b2ac..5abb6a532 100644 --- a/messages/af.json +++ b/messages/af.json @@ -6564,7 +6564,7 @@ "seriesSaved": "Reeksnaam gestoor", "seriesName": "Reeksnaam", "issn": "ISSN", - "issnHint": "Laat leeg totdat die reeks 'n ISSN kry. Tot dan laat die eienaarsreël die ISSN uit.", + "issnHint": "Laat leeg totdat die reeks 'n ISSN kry. Tot dan laat die eienaarsreël die ISSN uit. Verslae wat reeds gepubliseer is, kry nie 'n nuwe een nie.", "issnSaved": "ISSN gestoor", "enterByline": "Tik die eienaarsreël.", "bylineNeedsDoi": "Die eienaarsreël moet {doi} bevat, wat elke verslag se DOI word.", diff --git a/messages/ar.json b/messages/ar.json index 0961abbd5..9a04867b8 100644 --- a/messages/ar.json +++ b/messages/ar.json @@ -6564,7 +6564,7 @@ "seriesSaved": "تم حفظ اسم السلسلة", "seriesName": "اسم السلسلة", "issn": "ISSN", - "issnHint": "اتركه فارغًا حتى تحصل السلسلة على ISSN. حتى ذلك الحين لا يذكر سطر الإسناد رقم ISSN.", + "issnHint": "اتركه فارغًا حتى تحصل السلسلة على ISSN. حتى ذلك الحين لا يذكر سطر الإسناد رقم ISSN. التقارير المنشورة من قبل لا تأخذ رقمًا جديدًا.", "issnSaved": "تم حفظ ISSN", "enterByline": "أدخل سطر الإسناد.", "bylineNeedsDoi": "يجب أن يحتوي سطر الإسناد على {doi}، الذي يصبح معرّف DOI لكل تقرير.", diff --git a/messages/de.json b/messages/de.json index d0cf16f0a..9b2eac93f 100644 --- a/messages/de.json +++ b/messages/de.json @@ -6564,7 +6564,7 @@ "seriesSaved": "Name der Reihe gespeichert", "seriesName": "Name der Reihe", "issn": "ISSN", - "issnHint": "Leer lassen, bis die Reihe eine hat. Bis dahin nennen Quellenzeilen keine ISSN.", + "issnHint": "Leer lassen, bis die Reihe eine hat. Bis dahin nennen Quellenzeilen keine ISSN. Bereits veröffentlichte Berichte übernehmen keine neue.", "issnSaved": "ISSN gespeichert", "enterByline": "Gib die Quellenzeile ein.", "bylineNeedsDoi": "Die Quellenzeile braucht {doi}, woraus die DOI jedes Berichts wird.", diff --git a/messages/en-GB.json b/messages/en-GB.json index 6d69bc804..7146dc58f 100644 --- a/messages/en-GB.json +++ b/messages/en-GB.json @@ -6563,7 +6563,7 @@ "seriesSaved": "Series name saved", "seriesName": "Series name", "issn": "ISSN", - "issnHint": "Leave empty until the series has one. Bylines leave the ISSN out until then.", + "issnHint": "Leave empty until the series has one. Bylines leave the ISSN out until then. Reports already published don't take a new one.", "issnSaved": "ISSN saved", "enterByline": "Enter the byline.", "bylineNeedsDoi": "The byline needs {doi} in it, which becomes each report's DOI.", diff --git a/messages/en-US.json b/messages/en-US.json index 0e73a4007..e9f4dcc3b 100644 --- a/messages/en-US.json +++ b/messages/en-US.json @@ -6563,7 +6563,7 @@ "seriesSaved": "Series name saved", "seriesName": "Series name", "issn": "ISSN", - "issnHint": "Leave empty until the series has one. Bylines leave the ISSN out until then.", + "issnHint": "Leave empty until the series has one. Bylines leave the ISSN out until then. Reports already published don't take a new one.", "issnSaved": "ISSN saved", "enterByline": "Enter the byline.", "bylineNeedsDoi": "The byline needs {doi} in it, which becomes each report's DOI.", diff --git a/messages/es.json b/messages/es.json index d3f5f06b8..fdca9e5d1 100644 --- a/messages/es.json +++ b/messages/es.json @@ -6564,7 +6564,7 @@ "seriesSaved": "Nombre de la serie guardado", "seriesName": "Nombre de la serie", "issn": "ISSN", - "issnHint": "Déjalo vacío hasta que la serie tenga uno. Mientras tanto, las líneas de autoría no mencionan el ISSN.", + "issnHint": "Déjalo vacío hasta que la serie tenga uno. Mientras tanto, las líneas de autoría no mencionan el ISSN. Los informes ya publicados no adoptan uno nuevo.", "issnSaved": "ISSN guardado", "enterByline": "Escribe la línea de autoría.", "bylineNeedsDoi": "La línea de autoría necesita {doi}, que se convierte en el DOI de cada informe.", diff --git a/messages/fr.json b/messages/fr.json index bf3b574b0..9b438899c 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -6563,7 +6563,7 @@ "seriesSaved": "Nom de la collection enregistré", "seriesName": "Nom de la collection", "issn": "ISSN", - "issnHint": "Laissez vide tant que la série n'en a pas. D'ici là, les mentions n'indiquent pas d'ISSN.", + "issnHint": "Laissez vide tant que la série n'en a pas. D'ici là, les mentions n'indiquent pas d'ISSN. Les rapports déjà publiés n'en reçoivent pas de nouveau.", "issnSaved": "ISSN enregistré", "enterByline": "Saisissez la mention.", "bylineNeedsDoi": "La mention doit contenir {doi}, qui devient le DOI de chaque rapport.", diff --git a/messages/hi.json b/messages/hi.json index 1f6280f09..e52f750db 100644 --- a/messages/hi.json +++ b/messages/hi.json @@ -6563,7 +6563,7 @@ "seriesSaved": "शृंखला का नाम सहेजा गया", "seriesName": "शृंखला का नाम", "issn": "ISSN", - "issnHint": "जब तक शृंखला को ISSN न मिले, खाली छोड़ें। तब तक उल्लेख में ISSN नहीं लिखा जाएगा।", + "issnHint": "जब तक शृंखला को ISSN न मिले, खाली छोड़ें। तब तक उल्लेख में ISSN नहीं लिखा जाएगा। पहले से प्रकाशित रिपोर्टों पर नया ISSN लागू नहीं होता।", "issnSaved": "ISSN सहेजा गया", "enterByline": "उल्लेख लिखें।", "bylineNeedsDoi": "उल्लेख में {doi} होना चाहिए, जो हर रिपोर्ट का DOI बनता है।", diff --git a/messages/ja.json b/messages/ja.json index c6594344f..fa343c60b 100644 --- a/messages/ja.json +++ b/messages/ja.json @@ -6563,7 +6563,7 @@ "seriesSaved": "シリーズ名を保存しました", "seriesName": "シリーズ名", "issn": "ISSN", - "issnHint": "シリーズに ISSN が付くまで空のままにしてください。それまではクレジット行に ISSN は入りません。", + "issnHint": "シリーズに ISSN が付くまで空のままにしてください。それまではクレジット行に ISSN は入りません。公開済みのレポートには新しい ISSN は付きません。", "issnSaved": "ISSN を保存しました", "enterByline": "クレジット行を入力してください。", "bylineNeedsDoi": "クレジット行には {doi} が必要です。これが各レポートの DOI になります。", diff --git a/messages/pt.json b/messages/pt.json index 8758df5c8..a9ae2686c 100644 --- a/messages/pt.json +++ b/messages/pt.json @@ -6564,7 +6564,7 @@ "seriesSaved": "Nome da série guardado", "seriesName": "Nome da série", "issn": "ISSN", - "issnHint": "Deixe vazio até a série ter um. Até lá, as linhas de crédito não indicam o ISSN.", + "issnHint": "Deixe vazio até a série ter um. Até lá, as linhas de crédito não indicam o ISSN. Os relatórios já publicados não recebem um novo.", "issnSaved": "ISSN guardado", "enterByline": "Escreva a linha de crédito.", "bylineNeedsDoi": "A linha de crédito precisa de {doi}, que se torna o DOI de cada relatório.", diff --git a/messages/sw.json b/messages/sw.json index 59a01c3fe..fee95062f 100644 --- a/messages/sw.json +++ b/messages/sw.json @@ -6564,7 +6564,7 @@ "seriesSaved": "Jina la mfululizo limehifadhiwa", "seriesName": "Jina la mfululizo", "issn": "ISSN", - "issnHint": "Acha tupu hadi mfululizo upate ISSN. Hadi hapo, mstari wa utambulisho hautaji ISSN.", + "issnHint": "Acha tupu hadi mfululizo upate ISSN. Hadi hapo, mstari wa utambulisho hautaji ISSN. Ripoti zilizokwisha chapishwa hazipati ISSN mpya.", "issnSaved": "ISSN imehifadhiwa", "enterByline": "Andika mstari wa utambulisho.", "bylineNeedsDoi": "Mstari wa utambulisho unahitaji {doi} ndani yake, ambayo inakuwa DOI ya kila ripoti.", diff --git a/messages/zh.json b/messages/zh.json index 0878e9a2e..771f8044e 100644 --- a/messages/zh.json +++ b/messages/zh.json @@ -6563,7 +6563,7 @@ "seriesSaved": "系列名称已保存", "seriesName": "系列名称", "issn": "ISSN", - "issnHint": "在系列获得 ISSN 之前请留空。在此之前,署名行不写 ISSN。", + "issnHint": "在系列获得 ISSN 之前请留空。在此之前,署名行不写 ISSN。已发布的报告不会采用新的 ISSN。", "issnSaved": "ISSN 已保存", "enterByline": "请输入署名行。", "bylineNeedsDoi": "署名行需要包含 {doi},它会变成每份报告的 DOI。", diff --git a/messages/zu.json b/messages/zu.json index a52e8af68..994d4e481 100644 --- a/messages/zu.json +++ b/messages/zu.json @@ -6563,7 +6563,7 @@ "seriesSaved": "Igama lochungechunge lilondoloziwe", "seriesName": "Igama lochungechunge", "issn": "ISSN", - "issnHint": "Shiya kungenalutho kuze kube uchungechunge luthola i-ISSN. Kuze kube yileso sikhathi, umugqa womnikazi awusho i-ISSN.", + "issnHint": "Shiya kungenalutho kuze kube uchungechunge luthola i-ISSN. Kuze kube yileso sikhathi, umugqa womnikazi awusho i-ISSN. Imibiko esishicilelwe ayiyithathi i-ISSN entsha.", "issnSaved": "I-ISSN ilondoloziwe", "enterByline": "Thayipha umugqa womnikazi.", "bylineNeedsDoi": "Umugqa womnikazi udinga i-{doi}, eba yi-DOI yombiko ngamunye.",