From 28abe59aa536707befde0e20c654341524d7c916 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 24 Nov 2026 12:30:41 +0000 Subject: [PATCH 1/4] feat(reports): mock New reports switch with dates and activation limits Admin Publishing gets a New reports row (Off, On, Between dates), a timezone, and limits on activations per day, week, month or the whole time open, each rolling or calendar. While closed, the Publish page says the period is over, and New report, Next and Activate wait. Mock state lives in localStorage. --- .../sections/notifications-fields.tsx | 2 +- components/reports/admin-settings.tsx | 3 + components/reports/intake-notice.tsx | 107 +++++++ components/reports/new-report-settings.tsx | 265 ++++++++++++++++++ components/reports/next-button.tsx | 19 +- components/reports/publish-flow.tsx | 40 ++- lib/reports/intake.ts | 165 +++++++++++ messages/en-GB.json | 101 ++++++- messages/en-US.json | 101 ++++++- 9 files changed, 790 insertions(+), 13 deletions(-) create mode 100644 components/reports/intake-notice.tsx create mode 100644 components/reports/new-report-settings.tsx create mode 100644 lib/reports/intake.ts diff --git a/components/evidence-libraries/configuration/sections/notifications-fields.tsx b/components/evidence-libraries/configuration/sections/notifications-fields.tsx index 921c94cf1..b2f2e89e5 100644 --- a/components/evidence-libraries/configuration/sections/notifications-fields.tsx +++ b/components/evidence-libraries/configuration/sections/notifications-fields.tsx @@ -129,7 +129,7 @@ function listTimezones() { return timezones; } -function TimezonePicker({id, invalid, value, onChange}: {id: string; invalid: boolean; value: string; onChange: (timezone: string) => void}) { +export function TimezonePicker({id, invalid, value, onChange}: {id: string; invalid: boolean; value: string; onChange: (timezone: string) => void}) { const t = useTranslations("libraryNotificationSettings"); const [open, setOpen] = useState(false); const current = currentNames[value] ?? value; diff --git a/components/reports/admin-settings.tsx b/components/reports/admin-settings.tsx index 19e5207e0..fb792d9b7 100644 --- a/components/reports/admin-settings.tsx +++ b/components/reports/admin-settings.tsx @@ -19,6 +19,7 @@ import { StatusChip } from "@/components/evidence-libraries/configuration/status import { Field } from "@/components/evidence-libraries/configuration/section-card"; import { PublicationForm } from "@/components/evidence-libraries/configuration/sections/publication-section"; import { IdentifierSettings } from "@/components/reports/identifier-settings"; +import { NewReportSettings } from "@/components/reports/new-report-settings"; import { connectedOf } from "@/lib/reports/identifiers"; import { MarkdownContent } from "@/components/markdown-content"; import { Button } from "@/components/ui/button"; @@ -164,6 +165,8 @@ function SettingsView({ settings, autumn }: { settings: Settings; /** Autumn's d + + diff --git a/components/reports/intake-notice.tsx b/components/reports/intake-notice.tsx new file mode 100644 index 000000000..5b7f664b0 --- /dev/null +++ b/components/reports/intake-notice.tsx @@ -0,0 +1,107 @@ +"use client"; + +// What the Publish page says while new reports are closed (lib/reports/intake.ts): above the list, on a draft, and as +// the reason beside a Next or Activate that waits. MOCK (mock/new-report-limits). + +import { createContext, useContext } from "react"; +import { useFormatter, useTranslations } from "next-intl"; +import { Ban, CalendarClock, FileText, Hourglass } from "@/components/icons"; +import { ListEmpty } from "@/components/evidence-libraries/list-controls"; +import { Button } from "@/components/ui/button"; +import { StatusChip } from "@/components/evidence-libraries/configuration/status-chip"; +import { useIntakeState, type IntakeState } from "@/lib/reports/intake"; +import { cn } from "@/lib/utils"; + +type Closed = Exclude; + +const useWhen = () => { + const format = useFormatter(); + return (at: number) => format.dateTime(at, { weekday: "short", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }); +}; + +/** Why a new report can't start or a draft go on now, in a few words for beside the button; null while they can. */ +export function useIntakeShut(): string | null { + const t = useTranslations("publishReports.flow.intake.shut"); + const when = useWhen(); + const state = useIntakeState(); + if (state.open) return null; + if (state.why === "off") return t("off"); + if (state.why === "notYet") return t("notYet", { date: when(state.at) }); + if (state.why === "full" && state.reopensAt !== null) return t("next", { date: when(state.reopensAt) }); + return t("over"); +} + +/** The reason a draft's Next waits, given to every Next on the page (NextButton). Null while a draft can go on. */ +export const IntakeShut = createContext(null); +export const useShutNext = () => useContext(IntakeShut); + +/** The title and words for a closed state, and the date a chip gives, if any. */ +export function useIntakeWords(state: Closed) { + const t = useTranslations("publishReports.flow.intake"); + const when = useWhen(); + if (state.why === "off") return { icon: Ban, title: t("off.title"), body: t("off.body"), chip: null }; + if (state.why === "notYet") return { icon: CalendarClock, title: t("notYet.title"), body: t("notYet.body"), chip: t("opens", { date: when(state.at) }) }; + if (state.why === "ended") return { icon: Hourglass, title: t("over.title"), body: t("ended.body"), chip: t("closed", { date: when(state.at) }) }; + return { icon: Hourglass, title: t("over.title"), body: t(state.reopensAt === null ? "full.last" : "full.body"), chip: state.reopensAt === null ? null : t("next", { date: when(state.reopensAt) }) }; +} + +/** The notice above the list or a draft: what is closed, why, and when it opens again. */ +export function IntakeNotice({ className }: { className?: string }) { + const state = useIntakeState(); + if (state.open) return null; + return ; +} + +function ClosedNotice({ state, className }: { state: Closed; className?: string }) { + const { icon: Icon, title, body, chip } = useIntakeWords(state); + return ( +
+ + + + {title} + {body} + + + {chip ? ( + + {chip} + + ) : null} +
+ ); +} + +/** The Publish page's new report while new reports are closed: why, when they open again, and the way to the list. */ +export function IntakeClosedPage({ hasReports, onReports }: { hasReports: boolean; onReports: () => void }) { + const state = useIntakeState(); + const t = useTranslations("publishReports.flow"); + if (state.open) return null; + return ; +} + +function ClosedPage({ state, hasReports, onReports, yourReports }: { state: Closed; hasReports: boolean; onReports: () => void; yourReports: string }) { + const { icon, title, body, chip } = useIntakeWords(state); + return ( + + {chip ? ( + + {chip} + + ) : null} + {hasReports ? ( + + ) : null} + + } + > + {title} + + ); +} diff --git a/components/reports/new-report-settings.tsx b/components/reports/new-report-settings.tsx new file mode 100644 index 000000000..d6986396a --- /dev/null +++ b/components/reports/new-report-settings.tsx @@ -0,0 +1,265 @@ +"use client"; + +// Settings > Admin > Publishing: whether new reports are open, between which dates, and how many activations each +// period takes. MOCK (mock/new-report-limits): saved in this browser (lib/reports/intake.ts), so the Publish page in +// another tab follows it. + +import { useId, useState } from "react"; +import { useFormatter, useTranslations } from "next-intl"; +import { Ban, CalendarClock, CircleCheck, Clock3, Gauge, Globe2, Hourglass, Plus, TimerReset, Trash2 } from "@/components/icons"; +import { LIST, Segmented, Zone } from "@/components/settings/parts"; +import { StatusChip } from "@/components/evidence-libraries/configuration/status-chip"; +import { TimezonePicker } from "@/components/evidence-libraries/configuration/sections/notifications-fields"; +import { FieldMessage } from "@/components/reports/form"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { TooltipHint } from "@/components/ui/tooltip"; +import { SEEDED, fromLocalInput, saveIntake, stateOf, toLocalInput, usesOf, useIntake, useNow, type Intake, type IntakeState, type Limit, type LimitUse, type Period } from "@/lib/reports/intake"; +import { cn } from "@/lib/utils"; + +/** A date and time as the admin reads it, in the timezone the settings use. */ +function useWhen(timeZone: string) { + const format = useFormatter(); + return (at: number) => format.dateTime(at, { weekday: "short", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", timeZone }); +} + +export function NewReportSettings() { + const t = useTranslations("publishReports.settings.intake"); + const intake = useIntake(); + const now = useNow(); + const state = stateOf(intake, now); + const when = useWhen(intake.timezone); + const set = (patch: Partial) => saveIntake({ ...intake, ...patch }); + const setLimit = (id: string, patch: Partial) => set({ limits: intake.limits.map((limit) => (limit.id === id ? { ...limit, ...patch } : limit)) }); + const add = () => { + // The first limit is the one most need: the whole time open between dates, or a week. Another is most often a day. + const period: Period = intake.limits.length ? "day" : intake.mode === "dates" ? "window" : "week"; + set({ limits: [...intake.limits, { id: crypto.randomUUID(), count: 1000, period, reset: "calendar", used: SEEDED[period] }] }); + }; + // The timezone matters only where something is read on a clock: the dates, or a period that starts at midnight. + const clocked = intake.mode === "dates" || intake.limits.some((limit) => limit.period !== "window" && limit.reset === "calendar"); + const uses = usesOf(intake, now); + + return ( + }> +
    +
  • + + {t("when")} + {t(`hint.${intake.mode}`)} + + set({ mode })} + options={[ + { id: "off", label: t("mode.off"), icon: Ban }, + { id: "on", label: t("mode.on"), icon: CircleCheck }, + { id: "dates", label: t("mode.dates"), icon: CalendarClock }, + ]} + /> +
  • + {intake.mode === "dates" ? : null} + {clocked ? ( +
  • + + + + {t("timezone")} + + {t("timezoneHint")} + + + set({ timezone })} /> + +
  • + ) : null} +
+ +
+
+

{t("limits")}

+ +
+
    + {intake.limits.length ? ( + intake.limits.map((limit) => ( + use.id === limit.id)!} dates={intake.mode === "dates"} when={when} onChange={(patch) => setLimit(limit.id, patch)} onRemove={() => set({ limits: intake.limits.filter((kept) => kept.id !== limit.id) })} /> + )) + ) : ( +
  • + + {t("noLimits")} +
  • + )} +
+

{t("limitsHint")}

+
+
+ ); +} + +/** Where new reports stand, beside the heading. */ +function StateChip({ state, when, closesAt }: { state: IntakeState; when: (at: number) => string; closesAt: number | null }) { + const t = useTranslations("publishReports.settings.intake.state"); + if (state.open) return {closesAt === null ? t("open") : t("openUntil", { date: when(closesAt) })}; + if (state.why === "off") return {t("off")}; + if (state.why === "notYet") return {t("opens", { date: when(state.at) })}; + if (state.why === "ended") return {t("ended", { date: when(state.at) })}; + return {state.reopensAt === null ? t("full") : t("fullUntil", { date: when(state.reopensAt) })}; +} + +/** When new reports open and close, and where now is between them. */ +function DatesRow({ intake, now, onChange }: { intake: Intake; now: number; onChange: (patch: Partial) => void }) { + const t = useTranslations("publishReports.settings.intake"); + const format = useFormatter(); + const id = useId(); + const { timezone } = intake; + const [opens, setOpens] = useState(intake.opensAt === null ? "" : toLocalInput(intake.opensAt, timezone)); + const [closes, setCloses] = useState(intake.closesAt === null ? "" : toLocalInput(intake.closesAt, timezone)); + const opensAt = opens ? fromLocalInput(opens, timezone) : null; + const closesAt = closes ? fromLocalInput(closes, timezone) : null; + // A close still to come, and after the opening: anything else is said at the box and not saved. + const closeWrong = closesAt === null ? null : closesAt <= now ? t("closePast") : opensAt !== null && closesAt <= opensAt ? t("closeBeforeOpen") : null; + const commit = () => { + if (!closeWrong) onChange({ opensAt, closesAt }); + }; + const start = opensAt ?? now; + const span = closesAt !== null && closesAt > start ? closesAt - start : null; + const through = span === null ? 0 : Math.min(1, Math.max(0, (now - start) / span)); + return ( +
  • +
    + +
    + + setCloses(event.target.value)} + onBlur={commit} + aria-invalid={closeWrong ? true : undefined} + aria-describedby={closeWrong ? `${id}-closes-error` : `${id}-closes-hint`} + /> + {closeWrong ? {closeWrong} : {t("closesHint")}} +
    +
    + {/* Where now is between the two: a track that fills as the time runs. */} + {span !== null && !closeWrong ? ( +
    +
    +
    +
    +
    + {format.dateTime(start, { day: "numeric", month: "short", timeZone: timezone })} + + + {now < start ? t("startsIn", { time: format.relativeTime(start, now) }) : now >= closesAt! ? t("over") : t("left", { time: format.relativeTime(closesAt!, now) })} + + {format.dateTime(closesAt!, { day: "numeric", month: "short", timeZone: timezone })} +
    +
    + ) : null} +
  • + ); +} + +/** One limit: how many activations, in what period, counted how, and how far through it is. */ +function LimitRow({ use, dates, when, onChange, onRemove }: { use: LimitUse; /** New reports open between dates: "in total" is while they are. */ dates: boolean; when: (at: number) => string; onChange: (patch: Partial) => void; onRemove: () => void }) { + const t = useTranslations("publishReports.settings.intake"); + const format = useFormatter(); + const id = useId(); + const [count, setCount] = useState(String(use.count)); + const wrong = !/^\d+$/.test(count.trim()) || Number(count) < 1 ? t("countWrong") : null; + const commit = () => { + if (!wrong && Number(count) !== use.count) onChange({ count: Number(count) }); + }; + const share = Math.min(1, use.used / use.count); + return ( +
  • +
    +
    + setCount(event.target.value)} + onBlur={commit} + onKeyDown={(event) => event.key === "Enter" && event.currentTarget.blur()} + aria-invalid={wrong ? true : undefined} + aria-describedby={wrong ? `${id}-count-error` : undefined} + className="h-8 w-24 text-end tabular-nums" + /> + {t("activations", { count: Number(count) || 0 })} + + {use.period === "window" ? null : ( + onChange({ reset })} + options={[ + { id: "rolling", label: t(`rolling.${use.period}`), icon: TimerReset }, + { id: "calendar", label: t(`calendar.${use.period}`), icon: CalendarClock }, + ]} + /> + )} +
    + + + +
    + {wrong ? {wrong} : null} + {/* How much of this period it has taken, as a meter, with when the count starts again. */} +
    +
    +
    +
    +
    + + {t("used", { used: format.number(Math.min(use.used, use.count)), count: format.number(use.count) })} + + + {use.full ? {t("full")} : null} + {use.resetsAt !== null ? ( + + {t(use.reset === "calendar" ? "startsAgain" : "frees", { date: when(use.resetsAt) })} + + ) : ( + + {t(dates ? "untilClose" : "sinceOpen")} + + )} + +
    +
    +
  • + ); +} diff --git a/components/reports/next-button.tsx b/components/reports/next-button.tsx index 9b16bc71e..a82c45ed0 100644 --- a/components/reports/next-button.tsx +++ b/components/reports/next-button.tsx @@ -5,15 +5,19 @@ import { useTranslations } from "next-intl"; import { ArrowRight } from "@/components/icons"; import { Button } from "@/components/ui/button"; import { Working } from "@/components/settings/parts"; +import { TooltipHint } from "@/components/ui/tooltip"; +import { useShutNext } from "@/components/reports/intake-notice"; import { cn } from "@/lib/utils"; /** A step's way on: "Next" in a lighter end, then the step it leads to, as the Pay button sets its price apart. */ -/** A step's way on: shut only while it works (`busy`), never for what is missing, which a press says at the fields (`useStepForm`). */ +/** A step's way on: shut only while it works (`busy`), never for what is missing, which a press says at the fields (`useStepForm`), and while new reports are closed (`IntakeShut`). */ export function NextButton({ children, busy = false, className, disabled, ...props }: ComponentProps & { busy?: boolean }) { const t = useTranslations("publishReports.flow"); - return ( + // New reports closed: a draft waits for the next period, and says why beside its way on. + const shut = useShutNext(); + const button = ( // On a phone a long step ("Hlola imininingwane", or any at large text) wraps inside the button rather than leaving the card. - ); + return shut ? ( + + + {button} + + + ) : ( + button + ); } diff --git a/components/reports/publish-flow.tsx b/components/reports/publish-flow.tsx index 53ce74d69..e9f2d2c8c 100644 --- a/components/reports/publish-flow.tsx +++ b/components/reports/publish-flow.tsx @@ -43,6 +43,8 @@ import { AutoHeight } from "@/components/ui/auto-height"; import { SaveControl } from "@/components/library/save-control"; import { Button } from "@/components/ui/button"; import { NextButton } from "@/components/reports/next-button"; +import { IntakeClosedPage, IntakeNotice, IntakeShut, useIntakeShut } from "@/components/reports/intake-notice"; +import { useIntakeState } from "@/lib/reports/intake"; import { FieldMessage, StepNav, useStepForm } from "@/components/reports/form"; import { Checkbox } from "@/components/ui/checkbox"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; @@ -453,6 +455,9 @@ export function PublishFlow() { // and names nothing until the page knows whether its title sits beside a back arrow, so the title never moves // once it shows. The same shell stays mounted when the page arrives, so its card is already laid out and the // filters land where they belong at once (a new shell shows them in the card for a moment in Firefox). + // New reports closed for now (MOCK, lib/reports/intake.ts): read before the page can return early. + const intake = useIntakeState(); + const intakeShut = useIntakeShut(); if (!ready || !basics) { return ( @@ -509,9 +514,12 @@ export function PublishFlow() { setFresh(null); go({ view: null, report: "new", correct: null, step: null }); }; + // New reports closed for now (MOCK, lib/reports/intake.ts): nothing new starts, and a draft waits for the next period. + // A report not yet live, and never live before: the drafts that wait. + const waits = !!report && report.mine && report.status !== "live" && report.activatedAt === undefined && !intake.open; const hasReports = (counts?.all ?? 0) > 0; // Publishing switched off stops new reports. One already started keeps its address, and the list stays. - const closed = !basics.open && !listing && !report && !missing; + const closed = (!basics.open || !intake.open) && !listing && !report && !missing; return ( + intakeShut ? ( + + + + + + ) : ( + + ) ) : undefined } intro={!listing && !missing && !closed ? up("step")} humanReview={basics.humanReview} paying={!!terms?.paying && !chargeOver} onStep={toStep} /> : undefined} @@ -541,6 +560,7 @@ export function PublishFlow() { {listing ? (
    + {basics.open ? : null} {trouble.problem} go({ view: null, report: key, correct: (list ?? lastList)?.rows.find((row) => row.key === key)?.changes ? null : true })} onDiscard={(key) => (trouble.say(null), discard({ workspaceId: workspaceId!, key }).then(() => void toast.success(t("discarded")), trouble.failed(t("discardFailed"))))} - onNew={basics?.open ? another : undefined} + onNew={basics?.open && intake.open ? another : undefined} />
    ) : closed ? ( + basics.open ? ( + go({ view: "reports", report: null, correct: null })} /> + ) : ( {t("closedTitle")} + ) ) : missing ? ( {t("yourReports")} ) : null} - {elsewhere || !basics.open ? null : ( + {elsewhere || !basics.open || !intake.open ? null : ( @@ -609,8 +633,11 @@ export function PublishFlow() { {t("offNotice")}

    ) : null} + {/* New reports closed (MOCK): a draft says why its Next and Activate wait, and when the next period starts. */} + {basics.open && waits ? : null} {/* One set of screens for every report: going from one to another, or to a new report's agreement, is a change of screen like any other, and what belongs to one report is put away inside (Screens). */} + go({ step: "agreement" })} @@ -643,6 +670,7 @@ export function PublishFlow() { }} onCorrected={() => up("correct")} /> + {/* The report's bill stays under its cover from signing until it is live. */} {report && terms && beside ? : null} @@ -2039,7 +2067,9 @@ function Checks({ beside = null, rows, report, humanReview, terms, onActivate, o }; const [cancelling, cancel] = useTransition(); /** Why the report can't be paid for now, said on its button; null when it can. */ - const shut = terms?.paused ? t("activation.paused") : due > 0 && !terms?.sells ? t("activation.notForSale") : sum.bought > 0 && terms?.currency ? t("payment.currency", { currency: terms.currency }) : null; + // New reports closed (MOCK): Activate waits for the next period, and says so. + const intakeShut = useIntakeShut(); + const shut = intakeShut ?? (terms?.paused ? t("activation.paused") : due > 0 && !terms?.sells ? t("activation.notForSale") : sum.bought > 0 && terms?.currency ? t("payment.currency", { currency: terms.currency }) : null); // A code typed and not applied is the code field's to say: Activate takes the person there (`useStepForm`). const codeField = useId(); const { tried, go } = useStepForm(); diff --git a/lib/reports/intake.ts b/lib/reports/intake.ts new file mode 100644 index 000000000..a86de51e5 --- /dev/null +++ b/lib/reports/intake.ts @@ -0,0 +1,165 @@ +"use client"; + +// MOCK (mock/new-report-limits): whether new reports are open, held in this browser so the admin page and the +// Publish page agree without a server change. The real build keeps this on `reportSettings` and counts activations +// from `reportActivations`; `stateOf` and the calendar sums are what it would keep. + +import { useSyncExternalStore } from "react"; + +/** How long a limit's count runs: a day, a week, a month, or the whole time new reports are open. */ +export type Period = "day" | "week" | "month" | "window"; +/** Rolling counts the last day, week or month up to now; calendar starts again at midnight, on Monday, or on the 1st. */ +export type Reset = "rolling" | "calendar"; +export type Limit = { id: string; count: number; period: Period; reset: Reset; /** MOCK: activations already counted in its period. */ used: number }; +export type Intake = { + mode: "off" | "on" | "dates"; + /** With `dates`: when new reports open (none is at once) and close (none is never). */ + opensAt: number | null; + closesAt: number | null; + /** Where the dates and calendar periods are read. */ + timezone: string; + limits: Limit[]; +}; + +export type LimitUse = Limit & { full: boolean; /** When its count starts again; null for the whole time open. */ resetsAt: number | null }; +export type IntakeState = + | { open: true; uses: LimitUse[] } + | { open: false; why: "off" } + | { open: false; why: "notYet"; at: number } + | { open: false; why: "ended"; at: number } + | { open: false; why: "full"; uses: LimitUse[]; /** When the next period starts; null when none will. */ reopensAt: number | null }; + +const HOUR = 3_600_000; +const DAY = 24 * HOUR; + +/** The offset of a timezone from UTC at an instant, in milliseconds. */ +function offsetAt(at: number, timeZone: string) { + const name = new Intl.DateTimeFormat("en-US", { timeZone, timeZoneName: "longOffset" }).formatToParts(at).find((part) => part.type === "timeZoneName")?.value ?? "GMT"; + const match = /GMT([+-])(\d{2}):(\d{2})/.exec(name); + return match ? (match[1] === "-" ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3])) * 60_000 : 0; +} + +/** A wall-clock time in a timezone as an instant. Month from 0; days past the month's end roll on. */ +export function zoned(year: number, month: number, day: number, hour: number, minute: number, timeZone: string) { + const guess = Date.UTC(year, month, day, hour, minute); + return guess - offsetAt(guess - offsetAt(guess, timeZone), timeZone); +} + +/** An instant as the wall clock in a timezone: month from 1, weekday from 0 on Sunday. */ +function wall(at: number, timeZone: string) { + const parts = Object.fromEntries( + new Intl.DateTimeFormat("en-US", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", weekday: "short", hourCycle: "h23" }).formatToParts(at).map((part) => [part.type, part.value]), + ); + return { year: Number(parts.year), month: Number(parts.month), day: Number(parts.day), hour: Number(parts.hour), minute: Number(parts.minute), weekday: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(parts.weekday) }; +} + +/** The next midnight, Monday or 1st of the month in a timezone. */ +export function nextCalendarStart(period: "day" | "week" | "month", now: number, timeZone: string) { + const { year, month, day, weekday } = wall(now, timeZone); + if (period === "day") return zoned(year, month - 1, day + 1, 0, 0, timeZone); + if (period === "week") return zoned(year, month - 1, day + ((8 - weekday) % 7 || 7), 0, 0, timeZone); + return zoned(year, month, 1, 0, 0, timeZone); +} + +/** A `datetime-local` box's value for an instant in a timezone, and back. */ +export const toLocalInput = (at: number, timeZone: string) => { + const { year, month, day, hour, minute } = wall(at, timeZone); + const two = (n: number) => String(n).padStart(2, "0"); + return `${year}-${two(month)}-${two(day)}T${two(hour)}:${two(minute)}`; +}; +export const fromLocalInput = (value: string, timeZone: string) => { + const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(value); + return match ? zoned(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), timeZone) : null; +}; + +/** MOCK: activations a new limit starts with, so each period shows a believable count. */ +export const SEEDED: Record = { day: 37, week: 180, month: 640, window: 412 }; +/** MOCK: when a rolling count frees its first place: the oldest activation in it leaving the period. */ +const ROLLING_FREES: Record, number> = { day: 5 * HOUR, week: 2 * DAY + 3 * HOUR, month: 9 * DAY }; + +/** Each limit with how far through its period it is, and when its count starts again. */ +export function usesOf(intake: Intake, now: number): LimitUse[] { + const hour = Math.ceil(now / HOUR) * HOUR; + return intake.limits.map((limit): LimitUse => { + const resetsAt = limit.period === "window" ? null : limit.reset === "calendar" ? nextCalendarStart(limit.period, now, intake.timezone) : hour + ROLLING_FREES[limit.period]; + return { ...limit, full: limit.used >= limit.count, resetsAt }; + }); +} + +/** Whether a new report can start and a draft go on, at `now`, and why not. */ +export function stateOf(intake: Intake, now: number): IntakeState { + if (intake.mode === "off") return { open: false, why: "off" }; + if (intake.mode === "dates") { + if (intake.opensAt !== null && now < intake.opensAt) return { open: false, why: "notYet", at: intake.opensAt }; + if (intake.closesAt !== null && now >= intake.closesAt) return { open: false, why: "ended", at: intake.closesAt }; + } + const uses = usesOf(intake, now); + const full = uses.filter((use) => use.full); + if (!full.length) return { open: true, uses }; + // Every full limit has to start again before a report can go on: the latest of them, or never. + const reopensAt = full.some((use) => use.resetsAt === null) ? null : Math.max(...full.map((use) => use.resetsAt!)); + // A period that would start again after new reports close doesn't. + const closes = intake.mode === "dates" ? intake.closesAt : null; + return { open: false, why: "full", uses, reopensAt: reopensAt !== null && closes !== null && reopensAt >= closes ? null : reopensAt }; +} + +// The mock's store: this browser's localStorage, read the same in every tab. +const KEY = "mock:new-reports"; +const DEFAULT: Intake = { mode: "off", opensAt: null, closesAt: null, timezone: "UTC", limits: [] }; +let last: { raw: string | null; value: Intake } | null = null; +const listeners = new Set<() => void>(); + +function read(): Intake { + let raw: string | null = null; + try { + raw = localStorage.getItem(KEY); + } catch {} + if (last && last.raw === raw) return last.value; + let value: Intake; + try { + value = raw ? { ...DEFAULT, ...(JSON.parse(raw) as Partial) } : { ...DEFAULT, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }; + } catch { + value = DEFAULT; + } + last = { raw, value }; + return value; +} + +function subscribe(listener: () => void) { + listeners.add(listener); + // Another tab's change: the admin page in one, the Publish page in another. + window.addEventListener("storage", listener); + return () => { + listeners.delete(listener); + window.removeEventListener("storage", listener); + }; +} + +export function saveIntake(next: Intake) { + try { + localStorage.setItem(KEY, JSON.stringify(next)); + } catch {} + for (const listener of listeners) listener(); +} + +export function useIntake(): Intake { + return useSyncExternalStore(subscribe, read, () => DEFAULT); +} + +// The clock, read every 30 seconds: a period that ends while a page is open closes it there. +const TICK = 30_000; +function subscribeClock(listener: () => void) { + const timer = window.setInterval(listener, TICK); + return () => window.clearInterval(timer); +} +const tick = () => Math.floor(Date.now() / TICK) * TICK; + +/** Now, to the last 30 seconds. */ +export function useNow(): number { + return useSyncExternalStore(subscribeClock, tick, tick); +} + +/** Whether new reports are open now, for the Publish page. */ +export function useIntakeState(): IntakeState { + return stateOf(useIntake(), useNow()); +} diff --git a/messages/en-GB.json b/messages/en-GB.json index 0aa75e15e..b1af61e65 100644 --- a/messages/en-GB.json +++ b/messages/en-GB.json @@ -6584,7 +6584,75 @@ "priceThreeHint": "What publishing a report under an NC or ND licence, or the author's own open one, costs, in US dollars.", "prices": "Prices", "priceClosed": "Own licences that aren't open", - "priceClosedHint": "What publishing a report under the author's own licence that doesn't let anyone share it costs, in US dollars." + "priceClosedHint": "What publishing a report under the author's own licence that doesn't let anyone share it costs, in US dollars.", + "intake": { + "title": "New reports", + "when": "When they open", + "hint": { + "off": "Nobody can start or activate a report. Reports already started wait in Your reports.", + "on": "Anyone signed in can start and activate reports, within the limits below.", + "dates": "Open between these dates, within the limits below." + }, + "mode": { + "off": "Off", + "on": "On", + "dates": "Between dates" + }, + "timezone": "Timezone", + "timezoneHint": "The dates and calendar periods follow its clock", + "opens": "Opens", + "opensHint": "Leave empty to open them now", + "closes": "Closes", + "closesHint": "Leave empty to keep them open", + "closePast": "Pick a time still to come.", + "closeBeforeOpen": "Pick a time after they open.", + "startsIn": "Opens {time}", + "left": "Closes {time}", + "over": "Over", + "limits": "Limits", + "addLimit": "Add limit", + "noLimits": "No limit. Every report that's ready can be activated.", + "limitsHint": "Each limit counts activations. Once one is reached, new reports and activations wait for its next period.", + "countLabel": "Activations allowed", + "countWrong": "Enter a whole number, 1 or more.", + "activations": "{count, plural, one {activation} other {activations}}", + "periodLabel": "Period", + "period": { + "day": "a day", + "week": "a week", + "month": "a month", + "total": "in total", + "dates": "between the dates" + }, + "resetLabel": "How the period runs", + "rolling": { + "day": "Last 24 hours", + "week": "Last 7 days", + "month": "Last 30 days" + }, + "calendar": { + "day": "Midnight to midnight", + "week": "Monday to Sunday", + "month": "Calendar month" + }, + "remove": "Remove limit", + "usedLabel": "Activations in this period", + "used": "{used} of {count}", + "full": "Full", + "startsAgain": "Starts again {date}", + "frees": "Next place frees {date}", + "untilClose": "Until they close", + "sinceOpen": "Since they opened", + "state": { + "open": "Open", + "openUntil": "Open until {date}", + "off": "Off", + "opens": "Opens {date}", + "ended": "Ended {date}", + "full": "Full", + "fullUntil": "Full until {date}" + } + } }, "flow": { "steps": { @@ -7069,7 +7137,36 @@ "docidAgain": "Ask DOCiD again", "reservedDocid": "Minted by DOCiD", "copyDocid": "Copy the DOCiD", - "docidCopied": "DOCiD copied" + "docidCopied": "DOCiD copied", + "intake": { + "shut": { + "off": "New reports are closed", + "notYet": "New reports open {date}", + "next": "The next period starts {date}", + "over": "This period is over" + }, + "off": { + "title": "New reports are closed", + "body": "Reports you've started wait here until they open again." + }, + "notYet": { + "title": "New reports aren't open yet", + "body": "Reports you've started wait here until then." + }, + "over": { + "title": "This period is over" + }, + "ended": { + "body": "New reports are closed. Reports you've started wait here." + }, + "full": { + "body": "Every place in it is taken. Reports you've started wait for the next one.", + "last": "Every place in it is taken. Reports you've started wait here." + }, + "opens": "Opens {date}", + "closed": "Closed {date}", + "next": "Next period {date}" + } }, "meta": { "publish": "Publish | Openscholar", diff --git a/messages/en-US.json b/messages/en-US.json index 8a75665b0..3e55de0d0 100644 --- a/messages/en-US.json +++ b/messages/en-US.json @@ -6584,7 +6584,75 @@ "priceThreeHint": "What publishing a report under an NC or ND license, or the author's own open one, costs, in US dollars.", "prices": "Prices", "priceClosed": "Own licenses that aren't open", - "priceClosedHint": "What publishing a report under the author's own license that doesn't let anyone share it costs, in US dollars." + "priceClosedHint": "What publishing a report under the author's own license that doesn't let anyone share it costs, in US dollars.", + "intake": { + "title": "New reports", + "when": "When they open", + "hint": { + "off": "Nobody can start or activate a report. Reports already started wait in Your reports.", + "on": "Anyone signed in can start and activate reports, within the limits below.", + "dates": "Open between these dates, within the limits below." + }, + "mode": { + "off": "Off", + "on": "On", + "dates": "Between dates" + }, + "timezone": "Timezone", + "timezoneHint": "The dates and calendar periods follow its clock", + "opens": "Opens", + "opensHint": "Leave empty to open them now", + "closes": "Closes", + "closesHint": "Leave empty to keep them open", + "closePast": "Pick a time still to come.", + "closeBeforeOpen": "Pick a time after they open.", + "startsIn": "Opens {time}", + "left": "Closes {time}", + "over": "Over", + "limits": "Limits", + "addLimit": "Add limit", + "noLimits": "No limit. Every report that's ready can be activated.", + "limitsHint": "Each limit counts activations. Once one is reached, new reports and activations wait for its next period.", + "countLabel": "Activations allowed", + "countWrong": "Enter a whole number, 1 or more.", + "activations": "{count, plural, one {activation} other {activations}}", + "periodLabel": "Period", + "period": { + "day": "a day", + "week": "a week", + "month": "a month", + "total": "in total", + "dates": "between the dates" + }, + "resetLabel": "How the period runs", + "rolling": { + "day": "Last 24 hours", + "week": "Last 7 days", + "month": "Last 30 days" + }, + "calendar": { + "day": "Midnight to midnight", + "week": "Monday to Sunday", + "month": "Calendar month" + }, + "remove": "Remove limit", + "usedLabel": "Activations in this period", + "used": "{used} of {count}", + "full": "Full", + "startsAgain": "Starts again {date}", + "frees": "Next place frees {date}", + "untilClose": "Until they close", + "sinceOpen": "Since they opened", + "state": { + "open": "Open", + "openUntil": "Open until {date}", + "off": "Off", + "opens": "Opens {date}", + "ended": "Ended {date}", + "full": "Full", + "fullUntil": "Full until {date}" + } + } }, "flow": { "steps": { @@ -7069,7 +7137,36 @@ "docidAgain": "Ask DOCiD again", "reservedDocid": "Minted by DOCiD", "copyDocid": "Copy the DOCiD", - "docidCopied": "DOCiD copied" + "docidCopied": "DOCiD copied", + "intake": { + "shut": { + "off": "New reports are closed", + "notYet": "New reports open {date}", + "next": "The next period starts {date}", + "over": "This period is over" + }, + "off": { + "title": "New reports are closed", + "body": "Reports you've started wait here until they open again." + }, + "notYet": { + "title": "New reports aren't open yet", + "body": "Reports you've started wait here until then." + }, + "over": { + "title": "This period is over" + }, + "ended": { + "body": "New reports are closed. Reports you've started wait here." + }, + "full": { + "body": "Every place in it is taken. Reports you've started wait for the next one.", + "last": "Every place in it is taken. Reports you've started wait here." + }, + "opens": "Opens {date}", + "closed": "Closed {date}", + "next": "Next period {date}" + } }, "meta": { "publish": "Publish | Openscholar", From b4cde5a32da8c3d5c86bb2955e5635504a50e528 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 24 Nov 2026 13:12:00 +0000 Subject: [PATCH 2/4] feat(reports): open new reports between dates, with limits on activations New reports get their own setting on Admin > Publishing, separate from the Publish switch: off (the default), on, or between two dates, with any number of limits on activations a day, a week, a month or the whole time open, each rolling or calendar in a chosen timezone. Signing and Activate refuse while new reports are closed, counted in the mutation that takes the place. The Publish page works out the same from forAuthors and its clock: New report, a draft's Next and Activate wait, and the page says the period is over and when the next starts. migrations/reportIntake keeps new reports open where publishing was on. --- components/reports/admin-settings.tsx | 11 +- components/reports/intake-notice.tsx | 56 +++--- components/reports/new-report-settings.tsx | 164 ++++++++++++------ components/reports/publish-flow.tsx | 18 +- convex/_generated/api.d.ts | 4 + convex/migrations/reportIntake.ts | 26 +++ convex/reports/activation.test.ts | 14 ++ convex/reports/activation.ts | 3 + convex/reports/flow.test.ts | 13 ++ convex/reports/flow.ts | 2 + convex/reports/intake.ts | 84 +++++++++ convex/reports/reports.test-support.ts | 2 + convex/reports/settings.ts | 19 ++- convex/reports/validators.ts | 17 ++ convex/schema.ts | 4 +- lib/reports/intake.test.ts | 84 +++++++++ lib/reports/intake.ts | 189 ++++++++++----------- lib/reports/settings.ts | 2 + messages/af.json | 101 ++++++++++- messages/ar.json | 101 ++++++++++- messages/de.json | 101 ++++++++++- messages/en-GB.json | 4 +- messages/en-US.json | 4 +- messages/es.json | 101 ++++++++++- messages/fr.json | 101 ++++++++++- messages/hi.json | 101 ++++++++++- messages/ja.json | 101 ++++++++++- messages/pt.json | 101 ++++++++++- messages/sw.json | 101 ++++++++++- messages/zh.json | 101 ++++++++++- messages/zu.json | 101 ++++++++++- scripts/user-actions-exempt.json | 2 + 32 files changed, 1611 insertions(+), 222 deletions(-) create mode 100644 convex/migrations/reportIntake.ts create mode 100644 convex/reports/intake.ts create mode 100644 lib/reports/intake.test.ts diff --git a/components/reports/admin-settings.tsx b/components/reports/admin-settings.tsx index fb792d9b7..f44159139 100644 --- a/components/reports/admin-settings.tsx +++ b/components/reports/admin-settings.tsx @@ -19,7 +19,7 @@ import { StatusChip } from "@/components/evidence-libraries/configuration/status import { Field } from "@/components/evidence-libraries/configuration/section-card"; import { PublicationForm } from "@/components/evidence-libraries/configuration/sections/publication-section"; import { IdentifierSettings } from "@/components/reports/identifier-settings"; -import { NewReportSettings } from "@/components/reports/new-report-settings"; +import { NewReportSettings, useIntakeAdmin } from "@/components/reports/new-report-settings"; import { connectedOf } from "@/lib/reports/identifiers"; import { MarkdownContent } from "@/components/markdown-content"; import { Button } from "@/components/ui/button"; @@ -84,15 +84,16 @@ function Row({ label, hint, children, wide = false }: { label: string; hint?: st export function AdminPublishingSettings() { const { data: settings } = useProtectedQuery(api.reports.settings.admin, {}); const links = useQuery(api.admins.queries.links, {}); - if (!settings || links === undefined) return {null}; + const intake = useIntakeAdmin(); + if (!settings || links === undefined || !intake.data) return {null}; return ( - + ); } -function SettingsView({ settings, autumn }: { settings: Settings; /** Autumn's dashboard. */ autumn: string | null }) { +function SettingsView({ settings, autumn, intake }: { settings: Settings; /** Autumn's dashboard. */ autumn: string | null; /** New reports, read with the settings. */ intake: ComponentProps }) { const [nav, setNav] = useQueryStates(NAV); const t = useTranslations("publishReports.settings"); const format = useFormatter(); @@ -165,7 +166,7 @@ function SettingsView({ settings, autumn }: { settings: Settings; /** Autumn's d
    - + diff --git a/components/reports/intake-notice.tsx b/components/reports/intake-notice.tsx index 5b7f664b0..ffd266438 100644 --- a/components/reports/intake-notice.tsx +++ b/components/reports/intake-notice.tsx @@ -1,29 +1,49 @@ "use client"; -// What the Publish page says while new reports are closed (lib/reports/intake.ts): above the list, on a draft, and as -// the reason beside a Next or Activate that waits. MOCK (mock/new-report-limits). +// What the Publish page says while new reports are closed (lib/reports/intake.ts): above the list, on a draft, on a +// new report, and as the reason beside a Next or Activate that waits. -import { createContext, useContext } from "react"; +import { createContext, useContext, useSyncExternalStore } from "react"; import { useFormatter, useTranslations } from "next-intl"; import { Ban, CalendarClock, FileText, Hourglass } from "@/components/icons"; import { ListEmpty } from "@/components/evidence-libraries/list-controls"; -import { Button } from "@/components/ui/button"; import { StatusChip } from "@/components/evidence-libraries/configuration/status-chip"; -import { useIntakeState, type IntakeState } from "@/lib/reports/intake"; +import { Button } from "@/components/ui/button"; +import type { IntakeState } from "@/lib/reports/intake"; import { cn } from "@/lib/utils"; type Closed = Exclude; +// The clock, read every 30 seconds: a period that starts or ends while a page is open changes it there. +const TICK = 30_000; +function subscribeClock(listener: () => void) { + const timer = window.setInterval(listener, TICK); + return () => window.clearInterval(timer); +} +const tick = () => Math.floor(Date.now() / TICK) * TICK; + +/** Now, to the last 30 seconds. */ +export function useNow(): number { + return useSyncExternalStore(subscribeClock, tick, tick); +} + +/** Whether new reports are open on this page, worked out once where the page reads its settings (PublishFlow). */ +export const IntakeOpen = createContext({ open: true }); +/** The reason a draft's Next waits, given to every Next of a draft (NextButton). Null while a draft can go on. */ +export const IntakeShut = createContext(null); +export const useShutNext = () => useContext(IntakeShut); + const useWhen = () => { const format = useFormatter(); return (at: number) => format.dateTime(at, { weekday: "short", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }); }; -/** Why a new report can't start or a draft go on now, in a few words for beside the button; null while they can. */ -export function useIntakeShut(): string | null { +/** Why a new report can't start or a draft go on now, in a few words for beside the button; null while they can. `given` is for the page that provides it. */ +export function useIntakeShut(given?: IntakeState): string | null { const t = useTranslations("publishReports.flow.intake.shut"); const when = useWhen(); - const state = useIntakeState(); + const read = useContext(IntakeOpen); + const state = given ?? read; if (state.open) return null; if (state.why === "off") return t("off"); if (state.why === "notYet") return t("notYet", { date: when(state.at) }); @@ -31,12 +51,8 @@ export function useIntakeShut(): string | null { return t("over"); } -/** The reason a draft's Next waits, given to every Next on the page (NextButton). Null while a draft can go on. */ -export const IntakeShut = createContext(null); -export const useShutNext = () => useContext(IntakeShut); - -/** The title and words for a closed state, and the date a chip gives, if any. */ -export function useIntakeWords(state: Closed) { +/** The title and words for a closed state, and the date its chip gives, if any. */ +function useIntakeWords(state: Closed) { const t = useTranslations("publishReports.flow.intake"); const when = useWhen(); if (state.why === "off") return { icon: Ban, title: t("off.title"), body: t("off.body"), chip: null }; @@ -47,7 +63,7 @@ export function useIntakeWords(state: Closed) { /** The notice above the list or a draft: what is closed, why, and when it opens again. */ export function IntakeNotice({ className }: { className?: string }) { - const state = useIntakeState(); + const state = useContext(IntakeOpen); if (state.open) return null; return ; } @@ -74,13 +90,13 @@ function ClosedNotice({ state, className }: { state: Closed; className?: string /** The Publish page's new report while new reports are closed: why, when they open again, and the way to the list. */ export function IntakeClosedPage({ hasReports, onReports }: { hasReports: boolean; onReports: () => void }) { - const state = useIntakeState(); - const t = useTranslations("publishReports.flow"); + const state = useContext(IntakeOpen); if (state.open) return null; - return ; + return ; } -function ClosedPage({ state, hasReports, onReports, yourReports }: { state: Closed; hasReports: boolean; onReports: () => void; yourReports: string }) { +function ClosedPage({ state, hasReports, onReports }: { state: Closed; hasReports: boolean; onReports: () => void }) { + const t = useTranslations("publishReports.flow"); const { icon, title, body, chip } = useIntakeWords(state); return ( - {yourReports} + {t("yourReports")} ) : null} diff --git a/components/reports/new-report-settings.tsx b/components/reports/new-report-settings.tsx index d6986396a..b3a3ec254 100644 --- a/components/reports/new-report-settings.tsx +++ b/components/reports/new-report-settings.tsx @@ -1,21 +1,26 @@ "use client"; // Settings > Admin > Publishing: whether new reports are open, between which dates, and how many activations each -// period takes. MOCK (mock/new-report-limits): saved in this browser (lib/reports/intake.ts), so the Publish page in -// another tab follows it. +// period takes (lib/reports/intake.ts). Saved whole on each change (convex/reports/intake.ts `save`). import { useId, useState } from "react"; +import { useMutation } from "convex/react"; +import type { FunctionReturnType } from "convex/server"; import { useFormatter, useTranslations } from "next-intl"; +import { api } from "@/convex/_generated/api"; import { Ban, CalendarClock, CircleCheck, Clock3, Gauge, Globe2, Hourglass, Plus, TimerReset, Trash2 } from "@/components/icons"; import { LIST, Segmented, Zone } from "@/components/settings/parts"; import { StatusChip } from "@/components/evidence-libraries/configuration/status-chip"; import { TimezonePicker } from "@/components/evidence-libraries/configuration/sections/notifications-fields"; import { FieldMessage } from "@/components/reports/form"; +import { useNow } from "@/components/reports/intake-notice"; +import { useFailed } from "@/components/reports/words"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { TooltipHint } from "@/components/ui/tooltip"; -import { SEEDED, fromLocalInput, saveIntake, stateOf, toLocalInput, usesOf, useIntake, useNow, type Intake, type IntakeState, type Limit, type LimitUse, type Period } from "@/lib/reports/intake"; +import { useProtectedQuery } from "@/lib/auth/use-auth-query"; +import { LIMITS_MAX, LIMIT_COUNT_MAX, fromLocalInput, intakeAt, limitAt, toLocalInput, type Intake, type IntakeState, type Limit, type Period } from "@/lib/reports/intake"; import { cn } from "@/lib/utils"; /** A date and time as the admin reads it, in the timezone the settings use. */ @@ -24,28 +29,49 @@ function useWhen(timeZone: string) { return (at: number) => format.dateTime(at, { weekday: "short", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", timeZone }); } -export function NewReportSettings() { - const t = useTranslations("publishReports.settings.intake"); - const intake = useIntake(); +type Admin = FunctionReturnType; + +/** What the section reads, asked where the page waits for its settings, so the section is there when the page is. */ +export function useIntakeAdmin() { const now = useNow(); - const state = stateOf(intake, now); + // Counted to the minute: each minute asks again, and the last answer stays up until the next is in. + const minute = Math.floor(now / 60_000) * 60_000; + const { data } = useProtectedQuery(api.reports.intake.admin, { now: minute }); + const [held, setHeld] = useState(undefined); + if (data && data !== held) setHeld(data); + const shown = data ?? held; + return { data: shown, minute, now }; +} + +export function NewReportSettings({ data: { intake, uses }, minute, now }: { data: Admin; /** The minute the counts are for, which the query was asked with. */ minute: number; now: number }) { + const t = useTranslations("publishReports.settings.intake"); + const failed = useFailed(); const when = useWhen(intake.timezone); - const set = (patch: Partial) => saveIntake({ ...intake, ...patch }); + // A change shows at once and the server's answer follows; a refusal puts it back and says why. + const save = useMutation(api.reports.intake.save).withOptimisticUpdate((store, asked) => { + const shown = store.getQuery(api.reports.intake.admin, { now: minute }); + if (shown) store.setQuery(api.reports.intake.admin, { now: minute }, { ...shown, intake: { ...shown.intake, ...asked } }); + }); + const set = (patch: Partial) => { + const { openedAt: _, ...next } = { ...intake, ...patch }; + void save(next).catch(failed); + }; const setLimit = (id: string, patch: Partial) => set({ limits: intake.limits.map((limit) => (limit.id === id ? { ...limit, ...patch } : limit)) }); const add = () => { // The first limit is the one most need: the whole time open between dates, or a week. Another is most often a day. const period: Period = intake.limits.length ? "day" : intake.mode === "dates" ? "window" : "week"; - set({ limits: [...intake.limits, { id: crypto.randomUUID(), count: 1000, period, reset: "calendar", used: SEEDED[period] }] }); + set({ limits: [...intake.limits, { id: crypto.randomUUID(), count: 1000, period, reset: "calendar" }] }); }; + const counted = (id: string) => uses.find((use) => use.id === id); + const state = intakeAt(intake, Object.fromEntries(uses.map((use) => [use.id, use.nth])), now); // The timezone matters only where something is read on a clock: the dates, or a period that starts at midnight. const clocked = intake.mode === "dates" || intake.limits.some((limit) => limit.period !== "window" && limit.reset === "calendar"); - const uses = usesOf(intake, now); return ( }>
    • - + {t("when")} {t(`hint.${intake.mode}`)} @@ -60,7 +86,8 @@ export function NewReportSettings() { ]} />
    • - {intake.mode === "dates" ? : null} + {/* Keyed by what is saved, so a refused date goes back to it and a timezone changed reads the dates again. */} + {intake.mode === "dates" ? : null} {clocked ? (
    • @@ -80,14 +107,24 @@ export function NewReportSettings() {

      {t("limits")}

      -
        {intake.limits.length ? ( intake.limits.map((limit) => ( - use.id === limit.id)!} dates={intake.mode === "dates"} when={when} onChange={(patch) => setLimit(limit.id, patch)} onRemove={() => set({ limits: intake.limits.filter((kept) => kept.id !== limit.id) })} /> + setLimit(limit.id, patch)} + onRemove={() => set({ limits: intake.limits.filter((kept) => kept.id !== limit.id) })} + /> )) ) : (
      • @@ -122,25 +159,28 @@ function DatesRow({ intake, now, onChange }: { intake: Intake; now: number; onCh const [closes, setCloses] = useState(intake.closesAt === null ? "" : toLocalInput(intake.closesAt, timezone)); const opensAt = opens ? fromLocalInput(opens, timezone) : null; const closesAt = closes ? fromLocalInput(closes, timezone) : null; - // A close still to come, and after the opening: anything else is said at the box and not saved. - const closeWrong = closesAt === null ? null : closesAt <= now ? t("closePast") : opensAt !== null && closesAt <= opensAt ? t("closeBeforeOpen") : null; + // A new close still to come, and after the opening: anything else is said at the box and not saved. + const closeWrong = closesAt === null ? null : closesAt !== intake.closesAt && closesAt <= now ? t("closePast") : opensAt !== null && closesAt <= opensAt ? t("closeBeforeOpen") : null; const commit = () => { - if (!closeWrong) onChange({ opensAt, closesAt }); + if (!closeWrong && (opensAt !== intake.opensAt || closesAt !== intake.closesAt)) onChange({ opensAt, closesAt }); }; - const start = opensAt ?? now; - const span = closesAt !== null && closesAt > start ? closesAt - start : null; + const start = intake.opensAt ?? intake.openedAt ?? now; + const end = intake.closesAt; + const span = end !== null && end > start ? end - start : null; const through = span === null ? 0 : Math.min(1, Math.max(0, (now - start) / span)); return (
      • -
        - {/* Where now is between the two: a track that fills as the time runs. */} - {span !== null && !closeWrong ? ( + {/* Where now is between the two, as saved: a track that fills as the time runs. */} + {span !== null ? (
        -
        +
        {format.dateTime(start, { day: "numeric", month: "short", timeZone: timezone })} - {now < start ? t("startsIn", { time: format.relativeTime(start, now) }) : now >= closesAt! ? t("over") : t("left", { time: format.relativeTime(closesAt!, now) })} + {now < start ? t("startsIn", { time: format.relativeTime(start, now) }) : now >= end! ? t("over") : t("left", { time: format.relativeTime(end!, now) })} - {format.dateTime(closesAt!, { day: "numeric", month: "short", timeZone: timezone })} + {format.dateTime(end!, { day: "numeric", month: "short", timeZone: timezone })}
        ) : null} @@ -180,16 +226,22 @@ function DatesRow({ intake, now, onChange }: { intake: Intake; now: number; onCh } /** One limit: how many activations, in what period, counted how, and how far through it is. */ -function LimitRow({ use, dates, when, onChange, onRemove }: { use: LimitUse; /** New reports open between dates: "in total" is while they are. */ dates: boolean; when: (at: number) => string; onChange: (patch: Partial) => void; onRemove: () => void }) { +function LimitRow({ limit, used, full, startsAgain, dates, when, onChange, onRemove }: { limit: Limit; /** Activations counted in the period now. */ used: number; full: boolean; /** When its count starts again, or a rolling one has a place again; null when it doesn't. */ startsAgain: number | null; /** New reports open between dates: "in total" is while they are. */ dates: boolean; when: (at: number) => string; onChange: (patch: Partial) => void; onRemove: () => void }) { const t = useTranslations("publishReports.settings.intake"); const format = useFormatter(); const id = useId(); - const [count, setCount] = useState(String(use.count)); - const wrong = !/^\d+$/.test(count.trim()) || Number(count) < 1 ? t("countWrong") : null; + const [count, setCount] = useState(String(limit.count)); + const [was, setWas] = useState(limit.count); + // A count saved from elsewhere, or put back after a refusal, replaces the box unless something else is being typed. + if (limit.count !== was) { + setWas(limit.count); + if (Number(count) === was) setCount(String(limit.count)); + } + const typed = Number(count.trim()); + const wrong = !/^\d+$/.test(count.trim()) || typed < 1 || typed > LIMIT_COUNT_MAX ? t("countWrong", { max: format.number(LIMIT_COUNT_MAX) }) : null; const commit = () => { - if (!wrong && Number(count) !== use.count) onChange({ count: Number(count) }); + if (!wrong && typed !== limit.count) onChange({ count: typed }); }; - const share = Math.min(1, use.used / use.count); return (
      • @@ -206,8 +258,8 @@ function LimitRow({ use, dates, when, onChange, onRemove }: { use: LimitUse; /** aria-describedby={wrong ? `${id}-count-error` : undefined} className="h-8 w-24 text-end tabular-nums" /> - {t("activations", { count: Number(count) || 0 })} - onChange({ period: period as Period })}> @@ -218,14 +270,14 @@ function LimitRow({ use, dates, when, onChange, onRemove }: { use: LimitUse; /** {t(dates ? "period.dates" : "period.total")} - {use.period === "window" ? null : ( + {limit.period === "window" ? null : ( onChange({ reset })} options={[ - { id: "rolling", label: t(`rolling.${use.period}`), icon: TimerReset }, - { id: "calendar", label: t(`calendar.${use.period}`), icon: CalendarClock }, + { id: "rolling", label: t(`rolling.${limit.period}`), icon: TimerReset }, + { id: "calendar", label: t(`calendar.${limit.period}`), icon: CalendarClock }, ]} /> )} @@ -236,27 +288,33 @@ function LimitRow({ use, dates, when, onChange, onRemove }: { use: LimitUse; /**
        - {wrong ? {wrong} : null} + {wrong ? ( + + {wrong} + + ) : null} {/* How much of this period it has taken, as a meter, with when the count starts again. */}
        -
        -
        +
        +
        - - {t("used", { used: format.number(Math.min(use.used, use.count)), count: format.number(use.count) })} - + {t("used", { used: format.number(Math.min(used, limit.count)), count: format.number(limit.count) })} - {use.full ? {t("full")} : null} - {use.resetsAt !== null ? ( - - {t(use.reset === "calendar" ? "startsAgain" : "frees", { date: when(use.resetsAt) })} + {full ? ( + + {t("full")} - ) : ( + ) : null} + {limit.period === "window" ? ( {t(dates ? "untilClose" : "sinceOpen")} - )} + ) : startsAgain !== null ? ( + + {t(limit.reset === "calendar" ? "startsAgain" : "frees", { date: when(startsAgain) })} + + ) : null}
        diff --git a/components/reports/publish-flow.tsx b/components/reports/publish-flow.tsx index e9f2d2c8c..9405c9bf2 100644 --- a/components/reports/publish-flow.tsx +++ b/components/reports/publish-flow.tsx @@ -43,8 +43,8 @@ import { AutoHeight } from "@/components/ui/auto-height"; import { SaveControl } from "@/components/library/save-control"; import { Button } from "@/components/ui/button"; import { NextButton } from "@/components/reports/next-button"; -import { IntakeClosedPage, IntakeNotice, IntakeShut, useIntakeShut } from "@/components/reports/intake-notice"; -import { useIntakeState } from "@/lib/reports/intake"; +import { IntakeClosedPage, IntakeNotice, IntakeOpen, IntakeShut, useIntakeShut, useNow } from "@/components/reports/intake-notice"; +import { intakeAt, type IntakeState } from "@/lib/reports/intake"; import { FieldMessage, StepNav, useStepForm } from "@/components/reports/form"; import { Checkbox } from "@/components/ui/checkbox"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; @@ -447,6 +447,10 @@ export function PublishFlow() { /** The list is what shows: asked for, or still up while a report opens from it. */ const listing = listed || opening; + // Whether new reports are open now (lib/reports/intake.ts): the series' settings and limits, against the clock. + const clock = useNow(); + const intake: IntakeState = basics ? intakeAt(basics.intake, basics.nths, clock) : { open: true }; + const intakeShut = useIntakeShut(intake); const signedOut = isLoaded && !isSignedIn; // A link to a report or to the list is its workspace's to open: signing in comes back to it. if (signedOut && (view === "reports" || (asked !== null && asked !== "new"))) return ; @@ -455,9 +459,6 @@ export function PublishFlow() { // and names nothing until the page knows whether its title sits beside a back arrow, so the title never moves // once it shows. The same shell stays mounted when the page arrives, so its card is already laid out and the // filters land where they belong at once (a new shell shows them in the card for a moment in Firefox). - // New reports closed for now (MOCK, lib/reports/intake.ts): read before the page can return early. - const intake = useIntakeState(); - const intakeShut = useIntakeShut(); if (!ready || !basics) { return ( @@ -514,7 +515,6 @@ export function PublishFlow() { setFresh(null); go({ view: null, report: "new", correct: null, step: null }); }; - // New reports closed for now (MOCK, lib/reports/intake.ts): nothing new starts, and a draft waits for the next period. // A report not yet live, and never live before: the drafts that wait. const waits = !!report && report.mine && report.status !== "live" && report.activatedAt === undefined && !intake.open; const hasReports = (counts?.all ?? 0) > 0; @@ -522,6 +522,7 @@ export function PublishFlow() { const closed = (!basics.open || !intake.open) && !listing && !report && !missing; return ( + ) : null} - {/* New reports closed (MOCK): a draft says why its Next and Activate wait, and when the next period starts. */} + {/* New reports closed : a draft says why its Next and Activate wait, and when the next period starts. */} {basics.open && waits ? : null} {/* One set of screens for every report: going from one to another, or to a new report's agreement, is a change of screen like any other, and what belongs to one report is put away inside (Screens). */} @@ -677,6 +678,7 @@ export function PublishFlow() {
        )} + ); } @@ -2067,7 +2069,7 @@ function Checks({ beside = null, rows, report, humanReview, terms, onActivate, o }; const [cancelling, cancel] = useTransition(); /** Why the report can't be paid for now, said on its button; null when it can. */ - // New reports closed (MOCK): Activate waits for the next period, and says so. + // New reports closed: Activate waits for the next period, and says so. const intakeShut = useIntakeShut(); const shut = intakeShut ?? (terms?.paused ? t("activation.paused") : due > 0 && !terms?.sells ? t("activation.notForSale") : sum.bought > 0 && terms?.currency ? t("payment.currency", { currency: terms.currency }) : null); // A code typed and not applied is the code field's to say: Activate takes the person there (`useStepForm`). diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index af20258eb..5a3d34c28 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -364,6 +364,7 @@ import type * as migrations_pagedLibraryVersions from "../migrations/pagedLibrar import type * as migrations_placeRatings from "../migrations/placeRatings.js"; import type * as migrations_publicationBalance from "../migrations/publicationBalance.js"; import type * as migrations_recordApprovedQueries from "../migrations/recordApprovedQueries.js"; +import type * as migrations_reportIntake from "../migrations/reportIntake.js"; import type * as migrations_revokeDeletedOrganizationMemberships from "../migrations/revokeDeletedOrganizationMemberships.js"; import type * as migrations_rotateKeptFiles from "../migrations/rotateKeptFiles.js"; import type * as migrations_screeningOutcomes from "../migrations/screeningOutcomes.js"; @@ -401,6 +402,7 @@ import type * as reports_corrections from "../reports/corrections.js"; import type * as reports_fileAccess from "../reports/fileAccess.js"; import type * as reports_files from "../reports/files.js"; import type * as reports_flow from "../reports/flow.js"; +import type * as reports_intake from "../reports/intake.js"; import type * as reports_limits from "../reports/limits.js"; import type * as reports_mail from "../reports/mail.js"; import type * as reports_mailer from "../reports/mailer.js"; @@ -888,6 +890,7 @@ declare const fullApi: ApiFromModules<{ "migrations/placeRatings": typeof migrations_placeRatings; "migrations/publicationBalance": typeof migrations_publicationBalance; "migrations/recordApprovedQueries": typeof migrations_recordApprovedQueries; + "migrations/reportIntake": typeof migrations_reportIntake; "migrations/revokeDeletedOrganizationMemberships": typeof migrations_revokeDeletedOrganizationMemberships; "migrations/rotateKeptFiles": typeof migrations_rotateKeptFiles; "migrations/screeningOutcomes": typeof migrations_screeningOutcomes; @@ -925,6 +928,7 @@ declare const fullApi: ApiFromModules<{ "reports/fileAccess": typeof reports_fileAccess; "reports/files": typeof reports_files; "reports/flow": typeof reports_flow; + "reports/intake": typeof reports_intake; "reports/limits": typeof reports_limits; "reports/mail": typeof reports_mail; "reports/mailer": typeof reports_mailer; diff --git a/convex/migrations/reportIntake.ts b/convex/migrations/reportIntake.ts new file mode 100644 index 000000000..465fcdbc4 --- /dev/null +++ b/convex/migrations/reportIntake.ts @@ -0,0 +1,26 @@ +import { v } from "convex/values"; +import { internalMutation } from "../lib/functions"; +import { INTAKE_OFF } from "../../lib/reports/intake"; + +/** + * New reports got a switch of their own, off until an admin opens them (reports/intake.ts). On a deployment where + * publishing was already on, this opens them with no limit, so the deploy closes nothing; one with publishing off + * keeps them off. Run once per deployment right after its Convex push, then drop this file: + * npx convex run migrations/reportIntake:run + * Safe to run again: settings that have new reports saved are left as they are. + */ +export const run = internalMutation({ + args: {}, + returns: v.null(), + handler: async (ctx) => { + const row = await ctx.db.query("reportSettings").first(); + if (!row || row.intake) { + console.log(JSON.stringify({ event: "report-intake-migration", changed: false })); + return null; + } + const now = Date.now(); + await ctx.db.patch("reportSettings", row._id, { intake: { ...INTAKE_OFF, mode: row.enabled ? "on" : "off", openedAt: row.enabled ? now : null }, updatedAt: now }); + console.log(JSON.stringify({ event: "report-intake-migration", changed: true, mode: row.enabled ? "on" : "off" })); + return null; + }, +}); diff --git a/convex/reports/activation.test.ts b/convex/reports/activation.test.ts index 9e8d38ae3..62767e806 100644 --- a/convex/reports/activation.test.ts +++ b/convex/reports/activation.test.ts @@ -459,6 +459,20 @@ describe("activating a report", () => { expect(await activations(world)).toEqual([]); }); + it("waits for the next period once a limit's places are taken, counting only activations under way, waiting or live", async () => { + const world = await setup(); + const { key } = await checked(world, [passed("byline")]); + await world.reviewer.mutation(api.reports.intake.save, { mode: "on", opensAt: null, closesAt: null, timezone: "UTC", limits: [{ id: "day", count: 1, period: "day", reset: "rolling" }] }); + // Today's one place, taken by another workspace's report. + const taken = await world.t.run(async (ctx) => ctx.db.insert("reportActivations", { workspaceId: world.lab, reportId: (await ctx.db.query("reports").first())!._id, at: Date.now(), by: world.authorId, state: "live" })); + const begin = async () => world.t.mutation(internal.reports.activation.begin, { actor: await actorOf(world, "author", world.own), key, payWith: "balance", price: 10 }); + await expect(begin()).rejects.toMatchObject({ data: expect.objectContaining({ code: "FEATURE_DISABLED", reason: "intake" }) }); + expect(await activations(world)).toHaveLength(1); + // One the bank refused never took its place. + await world.t.run((ctx) => ctx.db.patch("reportActivations", taken, { state: "refused" })); + expect(await begin()).toBeTruthy(); + }); + it("takes a card's price from the balance once Autumn has given what it bought, never part of it, and never twice", 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 4f4bce6f3..bf63ea641 100644 --- a/convex/reports/activation.ts +++ b/convex/reports/activation.ts @@ -34,6 +34,7 @@ import { MOVED_ON, byKey, changing, mayChange, paymentOf, touch, voucherValidato import { notify } from "./mail"; import { register } from "./registering"; import { reportSettings } from "./settings"; +import { refuseClosed } from "./intake"; import { payWithValidator } from "./validators"; @@ -285,6 +286,8 @@ export const begin = internalMutation({ // reached, are that report's: nothing else is spent from the balance until they are taken. if (await owed(ctx, actor.workspaceId)) throw createError("CONFLICT", "An earlier report's payment is still being finished. Try again in a few minutes."); if ((await priceFor(ctx, report)) !== price) throw createError("CONFLICT", "This report's price changed since this page read it. Check what is due, then activate again.", { reason: "changed" }); + // New reports closed, or this period's places taken: it waits for the next. Read here, with the row that takes the place. + await refuseClosed(ctx, (await reportSettings(ctx)).intake); return await ctx.db.insert("reportActivations", { workspaceId: actor.workspaceId, reportId: report._id, at: Date.now(), by: actor.userId, state: "charging", payWith, price, ...(code && { code }) }); }, }); diff --git a/convex/reports/flow.test.ts b/convex/reports/flow.test.ts index 65c5fd70d..9bc4b39ae 100644 --- a/convex/reports/flow.test.ts +++ b/convex/reports/flow.test.ts @@ -34,6 +34,19 @@ describe("starting a report", () => { expect(await world.t.run((ctx) => startsLeft(ctx, world.own, Date.now()))).toMatchObject({ left: 1 }); }); + it("is refused while new reports are closed, though publishing is on, and starts once they open", async () => { + const world = await setup(); + const intake = (patch: Partial>[1]>) => world.reviewer.mutation(api.reports.intake.save, { mode: "on", opensAt: null, closesAt: null, timezone: "UTC", limits: [], ...patch }); + const closed = { data: expect.objectContaining({ code: "FEATURE_DISABLED", reason: "intake" }) }; + await intake({ mode: "off" }); + await expect(sign(world.author, world.own)).rejects.toMatchObject(closed); + await intake({ mode: "dates", opensAt: Date.now() + 3_600_000 }); + await expect(sign(world.author, world.own)).rejects.toMatchObject(closed); + expect(await world.t.run((ctx) => ctx.db.query("reports").take(5))).toHaveLength(0); + await intake({ mode: "dates", opensAt: Date.now() - 1, closesAt: Date.now() + 3_600_000 }); + expect(await sign(world.author, world.own)).toBe("R100001"); + }); + it("keeps a discarded report's start used", async () => { const world = await setup(); const key = await sign(world.author, world.own); diff --git a/convex/reports/flow.ts b/convex/reports/flow.ts index febed5122..38ad35ac5 100644 --- a/convex/reports/flow.ts +++ b/convex/reports/flow.ts @@ -21,6 +21,7 @@ import { choosesLicence } from "../../lib/reports/agreement"; import { DETAILS_MAX_BYTES, DETAIL_CAPS, REPORT_TYPES, DETAIL_TEXT, EARLIEST_YEAR, FILE_NAME_MAX, REPORTS_PER_PAGE, REVIEW_TEXT_MAX, SIGNER_NAME_MAX, STAGES, CODE_MAX, DEFAULT_LICENCE, canDiscard, licenceOf, ownLicence, type Licence, fileAccessOf, fileHidden, fileOut, isCalendarDay, keptAccess, keptFileAddress, opensFurther, readersGetFile, utcDay, type FileAccess, isOrcid, keyOf, providersOf, stageOf, type Metadata, type Stage, doiIn, linkHref, dateParts, isAuthor } from "../../lib/reports/report"; import { isCoverShape } from "../../lib/papers/cover"; import { countStart, startsLeft } from "./limits"; +import { intakeOf, refuseClosed } from "./intake"; import { MAX_PDF_BYTES, MAX_PDF_MB } from "../../lib/files/limits"; import { formVersion } from "./corrections"; import { notify } from "./mail"; @@ -234,6 +235,7 @@ export const sign = workspaceMutation({ await refuseApps(ctx); const settings = await settingsRow(ctx); if (!settings.enabled || !canRegister(settings.publication, settings.identifiers)) throw createError("FEATURE_DISABLED", "Publishing is off for now."); + await refuseClosed(ctx, intakeOf(settings)); if (version !== settings.agreement.version) throw createError("CONFLICT", "The agreement changed while you were reading it. Read the new one, then sign."); const signer = name.trim(); if (!signer) throw createError("VALIDATION_ERROR", "Type your name to sign."); diff --git a/convex/reports/intake.ts b/convex/reports/intake.ts new file mode 100644 index 000000000..3a9773fb9 --- /dev/null +++ b/convex/reports/intake.ts @@ -0,0 +1,84 @@ +// Whether new reports are open (lib/reports/intake.ts): off, on, or between dates, with limits on activations a day, +// a week, a month or the whole time open. Admins set it at Settings > Admin > Publishing. Signing a new report and +// activating one refuse while it is closed; the Publish page works out the same from what `forAuthors` sends. +import { v } from "convex/values"; +import { mutation, query, type QueryCtx } from "../lib/functions"; +import { requireAdmin } from "../admins/access"; +import { refuseApps } from "../lib/auth"; +import { createError } from "../lib/errors"; +import { intakeAt, intakeProblem, nthsOf, usedAt, type Intake, type IntakeState } from "../../lib/reports/intake"; +import { REPORT_DEFAULTS } from "../../lib/reports/settings"; +import { intakeFields, intakeValidator, limitUsesValidator } from "./validators"; +import { reportSettings, saveSettings, settingsRow } from "./settings"; + +/** The activations a limit counts: one under way, one waiting on its payment, and one that went live. */ +const COUNTED = ["charging", "pending", "live"] as const; + +/** Intake as saved, or off when none is: new reports stay closed until an admin opens them. */ +export const intakeOf = (row: { intake?: Intake } | null) => row?.intake ?? REPORT_DEFAULTS.intake; + +/** + * The times of the latest activations that count, newest first: as many as the largest limit, which is all any limit + * needs (`nthsOf`). None without a limit. + */ +export async function latestActivations(ctx: QueryCtx, intake: Intake): Promise { + const most = Math.max(0, ...intake.limits.map((limit) => limit.count)); + if (intake.mode === "off" || most === 0) return []; + const lists = await Promise.all(COUNTED.map((state) => ctx.db.query("reportActivations").withIndex("by_state_and_at", (q) => q.eq("state", state)).order("desc").take(most))); + return lists + .flat() + .map((row) => row.at) + .sort((a, b) => b - a) + .slice(0, most); +} + +const CLOSED: Record["why"], string> = { + off: "New reports are closed for now. Your report keeps its place.", + notYet: "New reports aren't open yet. Your report keeps its place.", + ended: "This period for new reports is over. Your report keeps its place.", + full: "This period for new reports is over. Your report keeps its place until the next one.", +}; + +/** + * Refuses a new report, or an activation, while new reports are closed. Read in the mutation that starts it, so two + * people taking the last place at once can't both have it: the second is run again and refused. + */ +export async function refuseClosed(ctx: QueryCtx, intake: Intake) { + const state = intakeAt(intake, nthsOf(intake.limits, await latestActivations(ctx, intake)), Date.now()); + if (!state.open) throw createError("FEATURE_DISABLED", CLOSED[state.why], { reason: "intake" }); +} + +/** + * What the admin's New reports section shows: the settings, and for each limit the activations counted in its period + * at `now`, which the page gives to the minute, and its `nth`. + */ +export const admin = query({ + args: { now: v.number() }, + returns: v.object({ intake: intakeValidator, uses: limitUsesValidator }), + handler: async (ctx, { now }) => { + await refuseApps(ctx); + await requireAdmin(ctx); + const { intake } = await reportSettings(ctx); + const latest = await latestActivations(ctx, intake); + return { intake, uses: intake.limits.map((limit) => ({ id: limit.id, used: usedAt(limit, intake, latest, now), nth: latest[limit.count - 1] ?? null })) }; + }, +}); + +/** Saves the whole of New reports at once: its parts depend on each other (`intakeProblem`). */ +export const save = mutation({ + args: { ...intakeFields }, + returns: v.null(), + handler: async (ctx, asked) => { + await refuseApps(ctx); + await requireAdmin(ctx); + const row = await settingsRow(ctx); + const saved = intakeOf(row); + const now = Date.now(); + // Switched on, or from on to between dates and back, "in total" counts from now. + const intake: Intake = { ...asked, openedAt: asked.mode !== "off" && asked.mode !== saved.mode ? now : saved.openedAt }; + const problem = intakeProblem(intake, now, saved); + if (problem) throw createError("VALIDATION_ERROR", problem); + await saveSettings(ctx, row._id, { intake }); + return null; + }, +}); diff --git a/convex/reports/reports.test-support.ts b/convex/reports/reports.test-support.ts index de02dce96..46b29adc8 100644 --- a/convex/reports/reports.test-support.ts +++ b/convex/reports/reports.test-support.ts @@ -33,6 +33,8 @@ export async function setup({ humanReview = false } = {}) { ...REPORT_DEFAULTS, enabled: true, humanReview, + // New reports open with no limit, as most tests need; a test of the limits sets its own. + intake: { ...REPORT_DEFAULTS.intake, mode: "on", openedAt: 0 }, publication: { zenodo: { mode: "off", license: "cc-by-4.0", defaultIdentifierPolicy: "mint-zenodo" }, crossref: { mode: "sandbox", prefix: "10.53832", suffixNamespace: "openscholar-r", depositorName: "d", email: "d@test.local", registrant: "r" } }, updatedAt: 1, }); diff --git a/convex/reports/settings.ts b/convex/reports/settings.ts index 61b7b627f..4a2f396d2 100644 --- a/convex/reports/settings.ts +++ b/convex/reports/settings.ts @@ -16,7 +16,9 @@ import { keptCustomOf, keptCustomValidator, publicationSettingsValidator } from import type { Effort } from "../../lib/ai/core/call-options"; import { AGREEMENT_MAX, CHECK_NAME_MAX, CHECK_TEXT_MAX, MAX_CHECKS, REPORT_DEFAULTS, SERIES_TEXT_MAX, canRegister, isIssn, type Check } from "../../lib/reports/settings"; import { DEFAULT_PRICES, PRICE_MAX, isPrice } from "../../lib/reports/report"; -import { checkNamesValidator, checkSummariesValidator, identifiersValidator, pricesValidator, seriesValidator } from "./validators"; +import { checkNamesValidator, checkSummariesValidator, identifiersValidator, intakeValidator, nthsValidator, pricesValidator, seriesValidator } from "./validators"; +import { latestActivations } from "./intake"; +import { nthsOf } from "../../lib/reports/intake"; /** What a check runs as: a decision model answers it, or an LLM that returns a structured answer. */ const CHECK_TASK = "screening"; @@ -43,7 +45,7 @@ export async function settingsRow(ctx: MutationCtx) { return (await ctx.db.get("reportSettings", id))!; } -const save = (ctx: MutationCtx, id: Awaited>["_id"], fields: Partial>, "_id" | "_creationTime">>) => +export const saveSettings = (ctx: MutationCtx, id: Awaited>["_id"], fields: Partial>, "_id" | "_creationTime">>) => ctx.db.patch("reportSettings", id, { ...fields, updatedAt: Date.now() }); /** @@ -170,6 +172,9 @@ export const forAuthors = query({ identifiers: identifiersValidator, agreement: v.object({ version: v.number(), text: v.string() }), checks: checkNamesValidator, + /** Whether new reports are open, and for each limit when the activation that fills it was made (lib/reports/intake.ts `nthsOf`): the page works out from these and its clock whether a new report or a draft waits. */ + intake: intakeValidator, + nths: nthsValidator, }), handler: async (ctx) => { const settings = await reportSettings(ctx); @@ -181,6 +186,8 @@ export const forAuthors = query({ identifiers: withAccounts(settings.identifiers, settings.publication), agreement: { version: settings.agreement.version, text: settings.agreement.text }, checks: settings.checks.filter((check) => check.enabled).map(({ id, name, blocking }) => ({ id, name, blocking })), + intake: settings.intake, + nths: nthsOf(settings.intake.limits, await latestActivations(ctx, settings.intake)), }; }, }); @@ -218,7 +225,7 @@ export const update = mutation({ // Every report's saved copies name the series and its ISSN (./saved.ts). if (named && (named.name !== row.series.name || named.issn !== row.series.issn)) await ctx.scheduler.runAfter(0, internal.reports.saved.followAll, {}); const kept = identifiers && keptIdentifiers(identifiers, row.publication); - await save(ctx, row._id, { + await saveSettings(ctx, row._id, { ...(kept && { identifiers: kept }), ...(prices && { prices: { ...(row.prices ?? DEFAULT_PRICES), ...prices } }), ...(enabled !== undefined && { enabled }), @@ -240,7 +247,7 @@ export const setMetadataModel = mutation({ requireEffort(model, effort); requireTaskModel(model, READING_TASK); const row = await settingsRow(ctx); - await save(ctx, row._id, { metadataModelId: model.modelId, metadataEffort: effort }); + await saveSettings(ctx, row._id, { metadataModelId: model.modelId, metadataEffort: effort }); return null; }, }); @@ -249,7 +256,7 @@ export const setMetadataModel = mutation({ async function saveChecks(ctx: MutationCtx, row: Awaited>, checks: Check[]) { const checksVersion = row.checksVersion + 1; await ctx.db.insert("reportCheckVersions", { version: checksVersion, checks }); - await save(ctx, row._id, { checks, checksVersion }); + await saveSettings(ctx, row._id, { checks, checksVersion }); } /** Adds a check, or changes the one with `id`. A new one goes last. */ @@ -340,7 +347,7 @@ export const setAgreement = mutation({ if (agreed === row.agreement.text) return null; const version = row.agreement.version + 1; await ctx.db.insert("reportAgreementVersions", { version, text: agreed }); - await save(ctx, row._id, { agreement: { version, text: agreed, updatedAt: Date.now() } }); + await saveSettings(ctx, row._id, { agreement: { version, text: agreed, updatedAt: Date.now() } }); return null; }, }); diff --git a/convex/reports/validators.ts b/convex/reports/validators.ts index 39d0b9cfa..a69cdb989 100644 --- a/convex/reports/validators.ts +++ b/convex/reports/validators.ts @@ -5,6 +5,7 @@ import { FUNDER_TYPES } from "@opendeved/doi-sync-core/docid"; import { capped } from "../lib/listCaps"; import { affiliationValidator } from "../lib/validators"; import { MAX_CHECKS } from "../../lib/reports/settings"; +import { INTAKE_MODES, LIMITS_MAX, PERIODS, RESETS } from "../../lib/reports/intake"; import { CHANGE_STAGES, DETAIL_CAPS, LICENCE_NAMES, PERSON_KINDS, RELATION_KINDS, REPORTS_PER_PAGE, STAGES, STATUSES, STEPS, PAY_WITH } from "../../lib/reports/report"; /** A check as kept: `lib/reports/settings.ts` says what each part means. */ @@ -44,6 +45,20 @@ export const identifiersValidator = v.object({ }); export const pricesValidator = v.object({ standard: v.number(), other: v.number(), closed: v.optional(v.number()) }); +/** Whether new reports are open, as an admin saves it (lib/reports/intake.ts says what each part means). */ +export const intakeFields = { + mode: v.union(...INTAKE_MODES.map((mode) => v.literal(mode))), + opensAt: v.union(v.number(), v.null()), + closesAt: v.union(v.number(), v.null()), + timezone: v.string(), + limits: capped(v.array(v.object({ id: v.string(), count: v.number(), period: v.union(...PERIODS.map((period) => v.literal(period))), reset: v.union(...RESETS.map((reset) => v.literal(reset))) })), LIMITS_MAX), +}; +export const intakeValidator = v.object({ ...intakeFields, openedAt: v.union(v.number(), v.null()) }); +/** Each limit's `nth` by its id (lib/reports/intake.ts `nthsOf`): what the Publish page works out whether a limit is full from. */ +export const nthsValidator = capped(v.record(v.string(), v.union(v.number(), v.null())), LIMITS_MAX); +/** Each limit as the admin's meter shows it: the activations counted in its period now, and its `nth`. */ +export const limitUsesValidator = capped(v.array(v.object({ id: v.string(), used: v.number(), nth: v.union(v.number(), v.null()) })), LIMITS_MAX); + /** The one settings row, once an admin changes something. Until then the series runs on `REPORT_DEFAULTS`. */ export const reportSettingsFields = { enabled: v.boolean(), @@ -61,6 +76,8 @@ export const reportSettingsFields = { prices: v.optional(pricesValidator), /** Which identifier services each report gets; none saved is DEFAULT_IDENTIFIERS (lib/reports/identifiers.ts). */ identifiers: v.optional(identifiersValidator), + /** Whether new reports are open; none saved is off (`REPORT_DEFAULTS`). */ + intake: v.optional(intakeValidator), // Free activations a day, from before a workspace had a balance in Autumn: cleared by migrations/publicationBalance, then dropped. perDay: v.optional(v.number()), orgPerDay: v.optional(v.number()), diff --git a/convex/schema.ts b/convex/schema.ts index ddeedf5ac..2b75bc3d6 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -643,7 +643,9 @@ export default defineSchema({ refund: v.optional(v.object({ card: v.number(), credit: v.number(), at: v.number() })), }) .index("by_workspaceId_and_state", ["workspaceId", "state"]) - .index("by_reportId", ["reportId"]), + .index("by_reportId", ["reportId"]) + // The latest that count against a limit on new reports (reports/intake.ts). + .index("by_state_and_at", ["state", "at"]), // The reports themselves. A row here is what a list reads; `reportDetails` holds what opening one reads. reports: defineTable(reportFields) diff --git a/lib/reports/intake.test.ts b/lib/reports/intake.test.ts new file mode 100644 index 000000000..cd950080b --- /dev/null +++ b/lib/reports/intake.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from "vitest"; +import { INTAKE_OFF, calendarStart, intakeAt, intakeProblem, nthsOf, usedAt, type Intake, type Limit } from "./intake"; + +const at = (iso: string) => Date.parse(iso); +const DAY = 86_400_000; +const open = (patch: Partial = {}): Intake => ({ ...INTAKE_OFF, mode: "on", openedAt: at("2026-11-01T00:00Z"), ...patch }); +const limit = (patch: Partial): Limit => ({ id: "a", count: 2, period: "week", reset: "calendar", ...patch }); + +describe("calendarStart", () => { + it("starts the week on Monday at midnight in the timezone, not in UTC", () => { + // Tuesday 24 November, noon UTC, is Tuesday evening in Tokyo: its week began Monday 23rd at 00:00 JST. + expect(calendarStart("week", at("2026-11-24T12:00Z"), "Asia/Tokyo")).toBe(at("2026-11-22T15:00Z")); + expect(calendarStart("week", at("2026-11-24T12:00Z"), "Asia/Tokyo", 1)).toBe(at("2026-11-29T15:00Z")); + // Monday 01:00 in Tokyo is still Sunday in UTC: the week has just begun there. + expect(calendarStart("week", at("2026-11-29T16:00Z"), "Asia/Tokyo")).toBe(at("2026-11-29T15:00Z")); + }); + + it("follows a clock change: midnights either side of New York's switch to summer time are 23 hours apart", () => { + const now = at("2026-03-08T12:00Z"); + expect(calendarStart("day", now, "America/New_York")).toBe(at("2026-03-08T05:00Z")); + expect(calendarStart("day", now, "America/New_York", 1)).toBe(at("2026-03-09T04:00Z")); + }); + + it("starts the month on the 1st, and the next one across the year's end", () => { + expect(calendarStart("month", at("2026-12-20T10:00Z"), "UTC")).toBe(at("2026-12-01T00:00Z")); + expect(calendarStart("month", at("2026-12-20T10:00Z"), "UTC", 1)).toBe(at("2027-01-01T00:00Z")); + }); +}); + +describe("intakeAt", () => { + const now = at("2026-11-24T12:00Z"); + + it("waits for the opening date and stops at the closing one", () => { + const dates = open({ mode: "dates", opensAt: at("2026-11-30T08:00Z"), closesAt: at("2026-12-04T17:00Z") }); + expect(intakeAt(dates, {}, now)).toEqual({ open: false, why: "notYet", at: dates.opensAt }); + expect(intakeAt(dates, {}, at("2026-12-01T00:00Z"))).toEqual({ open: true }); + expect(intakeAt(dates, {}, at("2026-12-04T17:00Z"))).toEqual({ open: false, why: "ended", at: dates.closesAt }); + expect(intakeAt(INTAKE_OFF, {}, now)).toEqual({ open: false, why: "off" }); + }); + + it("is full while the activation that filled a calendar week is in it, until next Monday", () => { + const week = open({ limits: [limit({})] }); + expect(intakeAt(week, { a: at("2026-11-23T09:00Z") }, now)).toEqual({ open: false, why: "full", reopensAt: at("2026-11-30T00:00Z") }); + // The second latest was made last week: this week has one, a place left. + expect(intakeAt(week, { a: at("2026-11-20T09:00Z") }, now)).toEqual({ open: true }); + expect(intakeAt(week, { a: null }, now)).toEqual({ open: true }); + }); + + it("frees a rolling place when the activation that filled it is 7 days old", () => { + const rolling = open({ limits: [limit({ reset: "rolling" })] }); + const filled = at("2026-11-20T09:00Z"); + expect(intakeAt(rolling, { a: filled }, now)).toEqual({ open: false, why: "full", reopensAt: filled + 7 * DAY }); + expect(intakeAt(rolling, { a: filled }, filled + 7 * DAY)).toEqual({ open: true }); + }); + + it("never reopens a limit on the whole time open, nor one whose next period starts after new reports close", () => { + const total = open({ limits: [limit({ period: "window" })] }); + expect(intakeAt(total, { a: at("2026-11-02T00:00Z") }, now)).toEqual({ open: false, why: "full", reopensAt: null }); + // Filled before new reports were switched on this time: those don't count. + expect(intakeAt(total, { a: at("2026-10-30T00:00Z") }, now)).toEqual({ open: true }); + const shortWindow = open({ mode: "dates", closesAt: at("2026-11-27T17:00Z"), limits: [limit({})] }); + expect(intakeAt(shortWindow, { a: at("2026-11-23T09:00Z") }, now)).toEqual({ open: false, why: "full", reopensAt: null }); + }); +}); + +describe("usedAt and nthsOf", () => { + it("count only the activations in the period, from the latest", () => { + const week = open({ limits: [limit({ count: 3 })] }); + const latest = [at("2026-11-24T08:00Z"), at("2026-11-23T01:00Z"), at("2026-11-22T23:00Z"), at("2026-11-10T00:00Z")]; + expect(usedAt(week.limits[0], week, latest, at("2026-11-24T12:00Z"))).toBe(2); + expect(nthsOf(week.limits, latest)).toEqual({ a: latest[2] }); + }); +}); + +describe("intakeProblem", () => { + it("refuses a new closing time already past, but keeps one saved before", () => { + const now = at("2026-11-24T12:00Z"); + const past = open({ mode: "dates", closesAt: at("2026-11-20T00:00Z") }); + expect(intakeProblem(past, now, INTAKE_OFF)).not.toBeNull(); + expect(intakeProblem(past, now, past)).toBeNull(); + expect(intakeProblem(open({ timezone: "Mars/Olympus" }), now, INTAKE_OFF)).not.toBeNull(); + expect(intakeProblem(open({ limits: [limit({ count: 0 })] }), now, INTAKE_OFF)).not.toBeNull(); + }); +}); diff --git a/lib/reports/intake.ts b/lib/reports/intake.ts index a86de51e5..72b46e6c7 100644 --- a/lib/reports/intake.ts +++ b/lib/reports/intake.ts @@ -1,36 +1,37 @@ -"use client"; +// Whether new reports are open (Settings > Admin > Publishing, "New reports"): off, on, or on between two dates, with +// limits on how many reports are activated in a day, a week, a month or the whole time open. Convex refuses with it +// (convex/reports/intake.ts) and the Publish page says with it why a new report or a draft waits. Nothing here reads +// the clock: `now` is given, so a page works it out again as time passes and a query never goes stale. -// MOCK (mock/new-report-limits): whether new reports are open, held in this browser so the admin page and the -// Publish page agree without a server change. The real build keeps this on `reportSettings` and counts activations -// from `reportActivations`; `stateOf` and the calendar sums are what it would keep. +export const INTAKE_MODES = ["off", "on", "dates"] as const; +/** How long a limit's count runs: a day, a week, a month, or the whole time new reports are open. */ +export const PERIODS = ["day", "week", "month", "window"] as const; +/** Rolling counts the last 24 hours, 7 days or 30 days; calendar starts again at midnight, on Monday, or on the 1st. */ +export const RESETS = ["rolling", "calendar"] as const; +export type Period = (typeof PERIODS)[number]; +export type Reset = (typeof RESETS)[number]; -import { useSyncExternalStore } from "react"; +/** The most limits, and the most activations one counts: the latest that many are read each time one is checked. */ +export const LIMITS_MAX = 10; +export const LIMIT_COUNT_MAX = 5000; -/** How long a limit's count runs: a day, a week, a month, or the whole time new reports are open. */ -export type Period = "day" | "week" | "month" | "window"; -/** Rolling counts the last day, week or month up to now; calendar starts again at midnight, on Monday, or on the 1st. */ -export type Reset = "rolling" | "calendar"; -export type Limit = { id: string; count: number; period: Period; reset: Reset; /** MOCK: activations already counted in its period. */ used: number }; +export type Limit = { id: string; count: number; period: Period; reset: Reset }; export type Intake = { - mode: "off" | "on" | "dates"; - /** With `dates`: when new reports open (none is at once) and close (none is never). */ + mode: (typeof INTAKE_MODES)[number]; + /** With `dates`: when new reports open (none is from `openedAt`) and close (none is never). */ opensAt: number | null; closesAt: number | null; /** Where the dates and calendar periods are read. */ timezone: string; limits: Limit[]; + /** When new reports were last switched on: where "in total" counts from when no opening date is set. */ + openedAt: number | null; }; -export type LimitUse = Limit & { full: boolean; /** When its count starts again; null for the whole time open. */ resetsAt: number | null }; -export type IntakeState = - | { open: true; uses: LimitUse[] } - | { open: false; why: "off" } - | { open: false; why: "notYet"; at: number } - | { open: false; why: "ended"; at: number } - | { open: false; why: "full"; uses: LimitUse[]; /** When the next period starts; null when none will. */ reopensAt: number | null }; +export const INTAKE_OFF: Intake = { mode: "off", opensAt: null, closesAt: null, timezone: "UTC", limits: [], openedAt: null }; -const HOUR = 3_600_000; -const DAY = 24 * HOUR; +const DAY = 24 * 3_600_000; +const ROLLING: Record, number> = { day: DAY, week: 7 * DAY, month: 30 * DAY }; /** The offset of a timezone from UTC at an instant, in milliseconds. */ function offsetAt(at: number, timeZone: string) { @@ -53,12 +54,22 @@ function wall(at: number, timeZone: string) { return { year: Number(parts.year), month: Number(parts.month), day: Number(parts.day), hour: Number(parts.hour), minute: Number(parts.minute), weekday: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(parts.weekday) }; } -/** The next midnight, Monday or 1st of the month in a timezone. */ -export function nextCalendarStart(period: "day" | "week" | "month", now: number, timeZone: string) { +/** Whether a timezone is one the clock knows. */ +export function isTimezone(timeZone: string) { + try { + new Intl.DateTimeFormat("en-US", { timeZone }); + return true; + } catch { + return false; + } +} + +/** The midnight, Monday or 1st of the month that starts the calendar period `now` is in, in a timezone; `ahead` 1 is the next one. */ +export function calendarStart(period: Exclude, now: number, timeZone: string, ahead: 0 | 1 = 0) { const { year, month, day, weekday } = wall(now, timeZone); - if (period === "day") return zoned(year, month - 1, day + 1, 0, 0, timeZone); - if (period === "week") return zoned(year, month - 1, day + ((8 - weekday) % 7 || 7), 0, 0, timeZone); - return zoned(year, month, 1, 0, 0, timeZone); + if (period === "day") return zoned(year, month - 1, day + ahead, 0, 0, timeZone); + if (period === "week") return zoned(year, month - 1, day - ((weekday + 6) % 7) + 7 * ahead, 0, 0, timeZone); + return zoned(year, month - 1 + ahead, 1, 0, 0, timeZone); } /** A `datetime-local` box's value for an instant in a timezone, and back. */ @@ -72,94 +83,66 @@ export const fromLocalInput = (value: string, timeZone: string) => { return match ? zoned(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), timeZone) : null; }; -/** MOCK: activations a new limit starts with, so each period shows a believable count. */ -export const SEEDED: Record = { day: 37, week: 180, month: 640, window: 412 }; -/** MOCK: when a rolling count frees its first place: the oldest activation in it leaving the period. */ -const ROLLING_FREES: Record, number> = { day: 5 * HOUR, week: 2 * DAY + 3 * HOUR, month: 9 * DAY }; - -/** Each limit with how far through its period it is, and when its count starts again. */ -export function usesOf(intake: Intake, now: number): LimitUse[] { - const hour = Math.ceil(now / HOUR) * HOUR; - return intake.limits.map((limit): LimitUse => { - const resetsAt = limit.period === "window" ? null : limit.reset === "calendar" ? nextCalendarStart(limit.period, now, intake.timezone) : hour + ROLLING_FREES[limit.period]; - return { ...limit, full: limit.used >= limit.count, resetsAt }; - }); +/** Where "in total" counts from: the opening date, or when new reports were switched on. */ +const windowStart = (intake: Intake) => (intake.mode === "dates" && intake.opensAt !== null ? intake.opensAt : (intake.openedAt ?? 0)); + +/** Whether an activation made at `at` counts in a limit's period at `now`: a rolling period leaves out its first instant, which is exactly 24 hours, 7 days or 30 days ago. */ +function counts(limit: Limit, intake: Intake, at: number, now: number) { + if (limit.period === "window") return at >= windowStart(intake); + return limit.reset === "rolling" ? at > now - ROLLING[limit.period] : at >= calendarStart(limit.period, now, intake.timezone); +} + +/** + * Where a limit stands at `now`, from `nth`: when the activation that would fill it was made, counting back from the + * latest (the `count`-th latest), or null with fewer than that ever. It is full while that one is in its period, and a + * rolling one has a place again once that one leaves it. + */ +export function limitAt(limit: Limit, intake: Intake, nth: number | null, now: number) { + const full = nth !== null && counts(limit, intake, nth, now); + const startsAgain = limit.period === "window" ? null : limit.reset === "calendar" ? calendarStart(limit.period, now, intake.timezone, 1) : full ? nth! + ROLLING[limit.period] : null; + return { full, startsAgain }; } -/** Whether a new report can start and a draft go on, at `now`, and why not. */ -export function stateOf(intake: Intake, now: number): IntakeState { +export type IntakeState = + | { open: true } + | { open: false; why: "off" } + | { open: false; why: "notYet"; at: number } + | { open: false; why: "ended"; at: number } + | { open: false; why: "full"; /** When a place opens again; null when none will before new reports close, or ever. */ reopensAt: number | null }; + +/** Whether a new report can start and a draft go on at `now`, and why not. `nths` is each limit's `nth`, by its id. */ +export function intakeAt(intake: Intake, nths: Record, now: number): IntakeState { if (intake.mode === "off") return { open: false, why: "off" }; if (intake.mode === "dates") { if (intake.opensAt !== null && now < intake.opensAt) return { open: false, why: "notYet", at: intake.opensAt }; if (intake.closesAt !== null && now >= intake.closesAt) return { open: false, why: "ended", at: intake.closesAt }; } - const uses = usesOf(intake, now); - const full = uses.filter((use) => use.full); - if (!full.length) return { open: true, uses }; - // Every full limit has to start again before a report can go on: the latest of them, or never. - const reopensAt = full.some((use) => use.resetsAt === null) ? null : Math.max(...full.map((use) => use.resetsAt!)); - // A period that would start again after new reports close doesn't. + const full = intake.limits.map((limit) => limitAt(limit, intake, nths[limit.id] ?? null, now)).filter((limit) => limit.full); + if (!full.length) return { open: true }; + // Every full limit has to have a place again before a report can go on: the latest of them, or never. + const reopensAt = full.some((limit) => limit.startsAgain === null) ? null : Math.max(...full.map((limit) => limit.startsAgain!)); const closes = intake.mode === "dates" ? intake.closesAt : null; - return { open: false, why: "full", uses, reopensAt: reopensAt !== null && closes !== null && reopensAt >= closes ? null : reopensAt }; -} - -// The mock's store: this browser's localStorage, read the same in every tab. -const KEY = "mock:new-reports"; -const DEFAULT: Intake = { mode: "off", opensAt: null, closesAt: null, timezone: "UTC", limits: [] }; -let last: { raw: string | null; value: Intake } | null = null; -const listeners = new Set<() => void>(); - -function read(): Intake { - let raw: string | null = null; - try { - raw = localStorage.getItem(KEY); - } catch {} - if (last && last.raw === raw) return last.value; - let value: Intake; - try { - value = raw ? { ...DEFAULT, ...(JSON.parse(raw) as Partial) } : { ...DEFAULT, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }; - } catch { - value = DEFAULT; - } - last = { raw, value }; - return value; + return { open: false, why: "full", reopensAt: reopensAt !== null && closes !== null && reopensAt >= closes ? null : reopensAt }; } -function subscribe(listener: () => void) { - listeners.add(listener); - // Another tab's change: the admin page in one, the Publish page in another. - window.addEventListener("storage", listener); - return () => { - listeners.delete(listener); - window.removeEventListener("storage", listener); - }; -} - -export function saveIntake(next: Intake) { - try { - localStorage.setItem(KEY, JSON.stringify(next)); - } catch {} - for (const listener of listeners) listener(); -} - -export function useIntake(): Intake { - return useSyncExternalStore(subscribe, read, () => DEFAULT); -} - -// The clock, read every 30 seconds: a period that ends while a page is open closes it there. -const TICK = 30_000; -function subscribeClock(listener: () => void) { - const timer = window.setInterval(listener, TICK); - return () => window.clearInterval(timer); -} -const tick = () => Math.floor(Date.now() / TICK) * TICK; +/** Each limit's `nth` from the times of the latest activations, newest first. */ +export const nthsOf = (limits: Limit[], latest: number[]) => Object.fromEntries(limits.map((limit) => [limit.id, latest[limit.count - 1] ?? null])); -/** Now, to the last 30 seconds. */ -export function useNow(): number { - return useSyncExternalStore(subscribeClock, tick, tick); +/** How many activations a limit has counted in the period `now` is in, from the latest activations, newest first. */ +export function usedAt(limit: Limit, intake: Intake, latest: number[], now: number) { + let used = 0; + while (used < latest.length && counts(limit, intake, latest[used], now)) used++; + return used; } -/** Whether new reports are open now, for the Publish page. */ -export function useIntakeState(): IntakeState { - return stateOf(useIntake(), useNow()); +/** What is wrong with intake settings an admin saves, in words for them; null when they can be kept. */ +export function intakeProblem(intake: Intake, now: number, saved: Intake): string | null { + if (!isTimezone(intake.timezone)) return "Pick a timezone from the list."; + if (intake.limits.length > LIMITS_MAX) return `Keep to ${LIMITS_MAX} limits.`; + if (intake.limits.some((limit) => !Number.isInteger(limit.count) || limit.count < 1 || limit.count > LIMIT_COUNT_MAX)) return `A limit is a whole number of activations, from 1 to ${LIMIT_COUNT_MAX.toLocaleString("en")}.`; + if (new Set(intake.limits.map((limit) => limit.id)).size !== intake.limits.length) return "Each limit needs its own id."; + if (intake.opensAt !== null && intake.closesAt !== null && intake.closesAt <= intake.opensAt) return "Pick a closing time after they open."; + // A closing time already past is kept as it was saved, but a new one has to be still to come. + if (intake.closesAt !== null && intake.closesAt !== saved.closesAt && intake.closesAt <= now) return "Pick a closing time still to come."; + return null; } diff --git a/lib/reports/settings.ts b/lib/reports/settings.ts index 8a4c67570..8a2bc8577 100644 --- a/lib/reports/settings.ts +++ b/lib/reports/settings.ts @@ -6,6 +6,7 @@ import { JEV_MODEL } from "../ai/decisions"; import { DEFAULT_AGREEMENT } from "./agreement-text"; import { DEFAULT_PRICES, type Licence } from "./report"; import { DEFAULT_IDENTIFIERS, settingsProblem, withAccounts, type Identifiers } from "./identifiers"; +import { INTAKE_OFF } from "./intake"; /** A licence as the byline names it: a Creative Commons one by its short name, an author's own with its address too, since its name alone says nothing of what it allows. */ export const licenceInByline = (licence: Licence) => (typeof licence === "string" ? licence : `${licence.name} (${licence.url})`); @@ -123,6 +124,7 @@ export const REPORT_DEFAULTS = { publication: NO_PUBLICATION, prices: DEFAULT_PRICES, identifiers: DEFAULT_IDENTIFIERS, + intake: INTAKE_OFF, metadataModelId: DEFAULT_TEXT_MODEL, metadataEffort: DEFAULT_TEXT_EFFORT as Effort | undefined, checks: DEFAULT_CHECKS, diff --git a/messages/af.json b/messages/af.json index c3389f656..5c1b57219 100644 --- a/messages/af.json +++ b/messages/af.json @@ -6585,7 +6585,75 @@ "priceThreeHint": "Wat dit kos om 'n verslag onder 'n NC- of ND-lisensie, of die outeur se eie oop lisensie, te publiseer, in Amerikaanse dollar.", "prices": "Pryse", "priceClosed": "Eie lisensies wat nie oop is nie", - "priceClosedHint": "Wat dit kos om 'n verslag onder die outeur se eie lisensie wat niemand toelaat om dit te deel nie, te publiseer, in Amerikaanse dollar." + "priceClosedHint": "Wat dit kos om 'n verslag onder die outeur se eie lisensie wat niemand toelaat om dit te deel nie, te publiseer, in Amerikaanse dollar.", + "intake": { + "title": "Nuwe verslae", + "when": "Wanneer hulle oop is", + "hint": { + "off": "Niemand kan 'n verslag begin of aktiveer nie. Verslae wat reeds begin is, wag in Jou verslae.", + "on": "Enigiemand wat aangemeld is, kan verslae begin en aktiveer, binne die perke hieronder.", + "dates": "Oop tussen hierdie datums, binne die perke hieronder." + }, + "mode": { + "off": "Af", + "on": "Aan", + "dates": "Tussen datums" + }, + "timezone": "Tydsone", + "timezoneHint": "Die datums en kalendertydperke volg sy horlosie", + "opens": "Gaan oop", + "opensHint": "Laat leeg om hulle nou oop te maak", + "closes": "Sluit", + "closesHint": "Laat leeg om hulle oop te hou", + "closePast": "Kies 'n tyd wat nog moet kom.", + "closeBeforeOpen": "Kies 'n tyd nadat hulle oopgaan.", + "startsIn": "Gaan oop {time}", + "left": "Sluit {time}", + "over": "Verby", + "limits": "Perke", + "addLimit": "Voeg perk by", + "noLimits": "Geen perk nie. Elke verslag wat gereed is, kan geaktiveer word.", + "limitsHint": "Elke perk tel aktiverings. Sodra een bereik is, wag nuwe verslae en aktiverings vir sy volgende tydperk.", + "countLabel": "Toegelate aktiverings", + "countWrong": "Tik 'n heelgetal van 1 tot {max}.", + "activations": "{count, plural, one {aktivering} other {aktiverings}}", + "periodLabel": "Tydperk", + "period": { + "day": "per dag", + "week": "per week", + "month": "per maand", + "total": "altesaam", + "dates": "tussen die datums" + }, + "resetLabel": "Hoe die tydperk loop", + "rolling": { + "day": "Laaste 24 uur", + "week": "Laaste 7 dae", + "month": "Laaste 30 dae" + }, + "calendar": { + "day": "Middernag tot middernag", + "week": "Maandag tot Sondag", + "month": "Kalendermaand" + }, + "remove": "Verwyder perk", + "usedLabel": "Aktiverings in hierdie tydperk", + "used": "{used} van {count}", + "full": "Vol", + "startsAgain": "Begin weer {date}", + "frees": "'n Plek kom vry {date}", + "untilClose": "Totdat hulle sluit", + "sinceOpen": "Sedert hulle oopgegaan het", + "state": { + "open": "Oop", + "openUntil": "Oop tot {date}", + "off": "Af", + "opens": "Gaan oop {date}", + "ended": "Geëindig {date}", + "full": "Vol", + "fullUntil": "Vol tot {date}" + } + } }, "flow": { "steps": { @@ -7070,7 +7138,36 @@ "docidAgain": "Vra DOCiD weer", "reservedDocid": "Deur DOCiD toegeken", "copyDocid": "Kopieer die DOCiD", - "docidCopied": "DOCiD gekopieer" + "docidCopied": "DOCiD gekopieer", + "intake": { + "shut": { + "off": "Nuwe verslae is gesluit", + "notYet": "Nuwe verslae gaan oop {date}", + "next": "Die volgende tydperk begin {date}", + "over": "Hierdie tydperk is verby" + }, + "off": { + "title": "Nuwe verslae is gesluit", + "body": "Verslae wat jy begin het, wag hier totdat hulle weer oopgaan." + }, + "notYet": { + "title": "Nuwe verslae is nog nie oop nie", + "body": "Verslae wat jy begin het, wag tot dan hier." + }, + "over": { + "title": "Hierdie tydperk is verby" + }, + "ended": { + "body": "Nuwe verslae is gesluit. Verslae wat jy begin het, wag hier." + }, + "full": { + "body": "Elke plek daarin is gevat. Verslae wat jy begin het, wag vir die volgende tydperk.", + "last": "Elke plek daarin is gevat. Verslae wat jy begin het, wag hier." + }, + "opens": "Gaan oop {date}", + "closed": "Gesluit {date}", + "next": "Volgende tydperk {date}" + } }, "meta": { "publish": "Publiseer | Openscholar", diff --git a/messages/ar.json b/messages/ar.json index ef2c61444..a3b975360 100644 --- a/messages/ar.json +++ b/messages/ar.json @@ -6585,7 +6585,75 @@ "priceThreeHint": "تكلفة نشر تقرير بموجب ترخيص NC أو ND، أو بموجب الترخيص المفتوح الخاص بالمؤلف، بالدولار الأمريكي.", "prices": "الأسعار", "priceClosed": "التراخيص الخاصة غير المفتوحة", - "priceClosedHint": "تكلفة نشر تقرير بموجب الترخيص الخاص بالمؤلف الذي لا يسمح لأحد بمشاركته، بالدولار الأمريكي." + "priceClosedHint": "تكلفة نشر تقرير بموجب الترخيص الخاص بالمؤلف الذي لا يسمح لأحد بمشاركته، بالدولار الأمريكي.", + "intake": { + "title": "التقارير الجديدة", + "when": "متى تكون مفتوحة", + "hint": { + "off": "لا يمكن لأحد بدء تقرير أو تفعيله. التقارير التي بدأت تنتظر في تقاريرك.", + "on": "يمكن لأي شخص سجّل الدخول بدء التقارير وتفعيلها، ضمن الحدود أدناه.", + "dates": "مفتوحة بين هذين التاريخين، ضمن الحدود أدناه." + }, + "mode": { + "off": "مغلقة", + "on": "مفتوحة", + "dates": "بين تاريخين" + }, + "timezone": "المنطقة الزمنية", + "timezoneHint": "تتبع التواريخ وفترات التقويم ساعتها", + "opens": "تفتح", + "opensHint": "اتركه فارغًا لفتحها الآن", + "closes": "تُغلق", + "closesHint": "اتركه فارغًا لإبقائها مفتوحة", + "closePast": "اختر وقتًا لم يأتِ بعد.", + "closeBeforeOpen": "اختر وقتًا بعد فتحها.", + "startsIn": "تفتح {time}", + "left": "تُغلق {time}", + "over": "انتهت", + "limits": "الحدود", + "addLimit": "إضافة حد", + "noLimits": "لا يوجد حد. يمكن تفعيل كل تقرير جاهز.", + "limitsHint": "يعدّ كل حد عمليات التفعيل. عند بلوغ أحدها، تنتظر التقارير الجديدة وعمليات التفعيل فترته التالية.", + "countLabel": "عمليات التفعيل المسموح بها", + "countWrong": "أدخل عددًا صحيحًا من 1 إلى {max}.", + "activations": "{count, plural, one {تفعيل} other {عمليات تفعيل}}", + "periodLabel": "الفترة", + "period": { + "day": "في اليوم", + "week": "في الأسبوع", + "month": "في الشهر", + "total": "إجمالًا", + "dates": "بين التاريخين" + }, + "resetLabel": "كيف تُحسب الفترة", + "rolling": { + "day": "آخر 24 ساعة", + "week": "آخر 7 أيام", + "month": "آخر 30 يومًا" + }, + "calendar": { + "day": "من منتصف الليل إلى منتصف الليل", + "week": "من الاثنين إلى الأحد", + "month": "الشهر التقويمي" + }, + "remove": "إزالة الحد", + "usedLabel": "عمليات التفعيل في هذه الفترة", + "used": "{used} من {count}", + "full": "ممتلئ", + "startsAgain": "يبدأ من جديد {date}", + "frees": "يتوفر مكان {date}", + "untilClose": "حتى تُغلق", + "sinceOpen": "منذ فتحها", + "state": { + "open": "مفتوحة", + "openUntil": "مفتوحة حتى {date}", + "off": "مغلقة", + "opens": "تفتح {date}", + "ended": "انتهت {date}", + "full": "ممتلئ", + "fullUntil": "ممتلئ حتى {date}" + } + } }, "flow": { "steps": { @@ -7070,7 +7138,36 @@ "docidAgain": "اطلب من DOCiD مجددًا", "reservedDocid": "مُنح من DOCiD", "copyDocid": "نسخ DOCiD", - "docidCopied": "تم نسخ DOCiD" + "docidCopied": "تم نسخ DOCiD", + "intake": { + "shut": { + "off": "التقارير الجديدة مغلقة", + "notYet": "تفتح التقارير الجديدة {date}", + "next": "تبدأ الفترة التالية {date}", + "over": "انتهت هذه الفترة" + }, + "off": { + "title": "التقارير الجديدة مغلقة", + "body": "تنتظر التقارير التي بدأتها هنا حتى تُفتح من جديد." + }, + "notYet": { + "title": "التقارير الجديدة لم تُفتح بعد", + "body": "تنتظر التقارير التي بدأتها هنا حتى ذلك الحين." + }, + "over": { + "title": "انتهت هذه الفترة" + }, + "ended": { + "body": "التقارير الجديدة مغلقة. تنتظر التقارير التي بدأتها هنا." + }, + "full": { + "body": "شُغلت كل الأماكن فيها. تنتظر التقارير التي بدأتها الفترة التالية.", + "last": "شُغلت كل الأماكن فيها. تنتظر التقارير التي بدأتها هنا." + }, + "opens": "تفتح {date}", + "closed": "أُغلقت {date}", + "next": "الفترة التالية {date}" + } }, "meta": { "publish": "نشر | Openscholar", diff --git a/messages/de.json b/messages/de.json index b10f04f22..9d0c28838 100644 --- a/messages/de.json +++ b/messages/de.json @@ -6585,7 +6585,75 @@ "priceThreeHint": "Was die Veröffentlichung eines Berichts unter einer NC- oder ND-Lizenz oder unter der eigenen offenen Lizenz der Autorin oder des Autors kostet, in US-Dollar.", "prices": "Preise", "priceClosed": "Eigene Lizenzen, die nicht offen sind", - "priceClosedHint": "Was die Veröffentlichung eines Berichts unter der eigenen Lizenz der Autorin oder des Autors kostet, die niemandem erlaubt, ihn zu teilen, in US-Dollar." + "priceClosedHint": "Was die Veröffentlichung eines Berichts unter der eigenen Lizenz der Autorin oder des Autors kostet, die niemandem erlaubt, ihn zu teilen, in US-Dollar.", + "intake": { + "title": "Neue Berichte", + "when": "Wann sie offen sind", + "hint": { + "off": "Niemand kann einen Bericht beginnen oder aktivieren. Begonnene Berichte warten unter Ihre Berichte.", + "on": "Alle Angemeldeten können Berichte beginnen und aktivieren, innerhalb der Grenzen unten.", + "dates": "Offen zwischen diesen Daten, innerhalb der Grenzen unten." + }, + "mode": { + "off": "Aus", + "on": "An", + "dates": "Zwischen Daten" + }, + "timezone": "Zeitzone", + "timezoneHint": "Die Daten und Kalenderzeiträume richten sich nach ihrer Uhr", + "opens": "Öffnet", + "opensHint": "Leer lassen, um sie jetzt zu öffnen", + "closes": "Schließt", + "closesHint": "Leer lassen, um sie offen zu halten", + "closePast": "Wählen Sie einen Zeitpunkt in der Zukunft.", + "closeBeforeOpen": "Wählen Sie einen Zeitpunkt nach der Öffnung.", + "startsIn": "Öffnet {time}", + "left": "Schließt {time}", + "over": "Vorbei", + "limits": "Grenzen", + "addLimit": "Grenze hinzufügen", + "noLimits": "Keine Grenze. Jeder fertige Bericht kann aktiviert werden.", + "limitsHint": "Jede Grenze zählt Aktivierungen. Ist eine erreicht, warten neue Berichte und Aktivierungen auf ihren nächsten Zeitraum.", + "countLabel": "Erlaubte Aktivierungen", + "countWrong": "Geben Sie eine ganze Zahl von 1 bis {max} ein.", + "activations": "{count, plural, one {Aktivierung} other {Aktivierungen}}", + "periodLabel": "Zeitraum", + "period": { + "day": "pro Tag", + "week": "pro Woche", + "month": "pro Monat", + "total": "insgesamt", + "dates": "zwischen den Daten" + }, + "resetLabel": "Wie der Zeitraum gezählt wird", + "rolling": { + "day": "Letzte 24 Stunden", + "week": "Letzte 7 Tage", + "month": "Letzte 30 Tage" + }, + "calendar": { + "day": "Mitternacht bis Mitternacht", + "week": "Montag bis Sonntag", + "month": "Kalendermonat" + }, + "remove": "Grenze entfernen", + "usedLabel": "Aktivierungen in diesem Zeitraum", + "used": "{used} von {count}", + "full": "Voll", + "startsAgain": "Beginnt neu {date}", + "frees": "Ein Platz wird frei {date}", + "untilClose": "Bis sie schließen", + "sinceOpen": "Seit sie geöffnet sind", + "state": { + "open": "Offen", + "openUntil": "Offen bis {date}", + "off": "Aus", + "opens": "Öffnet {date}", + "ended": "Beendet {date}", + "full": "Voll", + "fullUntil": "Voll bis {date}" + } + } }, "flow": { "steps": { @@ -7070,7 +7138,36 @@ "docidAgain": "DOCiD erneut fragen", "reservedDocid": "Von DOCiD vergeben", "copyDocid": "DOCiD kopieren", - "docidCopied": "DOCiD kopiert" + "docidCopied": "DOCiD kopiert", + "intake": { + "shut": { + "off": "Neue Berichte sind geschlossen", + "notYet": "Neue Berichte öffnen {date}", + "next": "Der nächste Zeitraum beginnt {date}", + "over": "Dieser Zeitraum ist vorbei" + }, + "off": { + "title": "Neue Berichte sind geschlossen", + "body": "Ihre begonnenen Berichte warten hier, bis sie wieder öffnen." + }, + "notYet": { + "title": "Neue Berichte sind noch nicht offen", + "body": "Ihre begonnenen Berichte warten bis dahin hier." + }, + "over": { + "title": "Dieser Zeitraum ist vorbei" + }, + "ended": { + "body": "Neue Berichte sind geschlossen. Ihre begonnenen Berichte warten hier." + }, + "full": { + "body": "Alle Plätze sind vergeben. Ihre begonnenen Berichte warten auf den nächsten Zeitraum.", + "last": "Alle Plätze sind vergeben. Ihre begonnenen Berichte warten hier." + }, + "opens": "Öffnet {date}", + "closed": "Geschlossen {date}", + "next": "Nächster Zeitraum {date}" + } }, "meta": { "publish": "Veröffentlichen | Openscholar", diff --git a/messages/en-GB.json b/messages/en-GB.json index b1af61e65..08532cdae 100644 --- a/messages/en-GB.json +++ b/messages/en-GB.json @@ -6614,7 +6614,7 @@ "noLimits": "No limit. Every report that's ready can be activated.", "limitsHint": "Each limit counts activations. Once one is reached, new reports and activations wait for its next period.", "countLabel": "Activations allowed", - "countWrong": "Enter a whole number, 1 or more.", + "countWrong": "Enter a whole number from 1 to {max}.", "activations": "{count, plural, one {activation} other {activations}}", "periodLabel": "Period", "period": { @@ -6640,7 +6640,7 @@ "used": "{used} of {count}", "full": "Full", "startsAgain": "Starts again {date}", - "frees": "Next place frees {date}", + "frees": "A place frees {date}", "untilClose": "Until they close", "sinceOpen": "Since they opened", "state": { diff --git a/messages/en-US.json b/messages/en-US.json index 3e55de0d0..ca7fde1be 100644 --- a/messages/en-US.json +++ b/messages/en-US.json @@ -6614,7 +6614,7 @@ "noLimits": "No limit. Every report that's ready can be activated.", "limitsHint": "Each limit counts activations. Once one is reached, new reports and activations wait for its next period.", "countLabel": "Activations allowed", - "countWrong": "Enter a whole number, 1 or more.", + "countWrong": "Enter a whole number from 1 to {max}.", "activations": "{count, plural, one {activation} other {activations}}", "periodLabel": "Period", "period": { @@ -6640,7 +6640,7 @@ "used": "{used} of {count}", "full": "Full", "startsAgain": "Starts again {date}", - "frees": "Next place frees {date}", + "frees": "A place frees {date}", "untilClose": "Until they close", "sinceOpen": "Since they opened", "state": { diff --git a/messages/es.json b/messages/es.json index cb85f1df4..6ee6b307b 100644 --- a/messages/es.json +++ b/messages/es.json @@ -6585,7 +6585,75 @@ "priceThreeHint": "Lo que cuesta publicar un informe con una licencia NC o ND, o con la licencia abierta propia del autor, en dólares estadounidenses.", "prices": "Precios", "priceClosed": "Licencias propias que no son abiertas", - "priceClosedHint": "Lo que cuesta publicar un informe con la licencia propia del autor que no permite que nadie lo comparta, en dólares estadounidenses." + "priceClosedHint": "Lo que cuesta publicar un informe con la licencia propia del autor que no permite que nadie lo comparta, en dólares estadounidenses.", + "intake": { + "title": "Informes nuevos", + "when": "Cuándo están abiertos", + "hint": { + "off": "Nadie puede empezar ni activar un informe. Los informes ya empezados esperan en Tus informes.", + "on": "Cualquier persona con sesión iniciada puede empezar y activar informes, dentro de los límites de abajo.", + "dates": "Abiertos entre estas fechas, dentro de los límites de abajo." + }, + "mode": { + "off": "Desactivado", + "on": "Activado", + "dates": "Entre fechas" + }, + "timezone": "Zona horaria", + "timezoneHint": "Las fechas y los periodos de calendario siguen su hora", + "opens": "Apertura", + "opensHint": "Déjalo vacío para abrirlos ahora", + "closes": "Cierre", + "closesHint": "Déjalo vacío para mantenerlos abiertos", + "closePast": "Elige un momento futuro.", + "closeBeforeOpen": "Elige un momento posterior a la apertura.", + "startsIn": "Abre {time}", + "left": "Cierra {time}", + "over": "Terminado", + "limits": "Límites", + "addLimit": "Añadir límite", + "noLimits": "Sin límite. Cualquier informe listo se puede activar.", + "limitsHint": "Cada límite cuenta activaciones. Cuando se alcanza uno, los informes nuevos y las activaciones esperan a su próximo periodo.", + "countLabel": "Activaciones permitidas", + "countWrong": "Escribe un número entero del 1 al {max}.", + "activations": "{count, plural, one {activación} other {activaciones}}", + "periodLabel": "Periodo", + "period": { + "day": "al día", + "week": "a la semana", + "month": "al mes", + "total": "en total", + "dates": "entre las fechas" + }, + "resetLabel": "Cómo se cuenta el periodo", + "rolling": { + "day": "Últimas 24 horas", + "week": "Últimos 7 días", + "month": "Últimos 30 días" + }, + "calendar": { + "day": "De medianoche a medianoche", + "week": "De lunes a domingo", + "month": "Mes natural" + }, + "remove": "Quitar límite", + "usedLabel": "Activaciones en este periodo", + "used": "{used} de {count}", + "full": "Completo", + "startsAgain": "Vuelve a empezar {date}", + "frees": "Se libera una plaza {date}", + "untilClose": "Hasta el cierre", + "sinceOpen": "Desde la apertura", + "state": { + "open": "Abierto", + "openUntil": "Abierto hasta {date}", + "off": "Desactivado", + "opens": "Abre {date}", + "ended": "Terminó {date}", + "full": "Completo", + "fullUntil": "Completo hasta {date}" + } + } }, "flow": { "steps": { @@ -7070,7 +7138,36 @@ "docidAgain": "Volver a pedírselo a DOCiD", "reservedDocid": "Asignado por DOCiD", "copyDocid": "Copiar el DOCiD", - "docidCopied": "DOCiD copiado" + "docidCopied": "DOCiD copiado", + "intake": { + "shut": { + "off": "Los informes nuevos están cerrados", + "notYet": "Los informes nuevos abren {date}", + "next": "El próximo periodo empieza {date}", + "over": "Este periodo ha terminado" + }, + "off": { + "title": "Los informes nuevos están cerrados", + "body": "Los informes que has empezado esperan aquí hasta que vuelvan a abrir." + }, + "notYet": { + "title": "Los informes nuevos aún no están abiertos", + "body": "Los informes que has empezado esperan aquí hasta entonces." + }, + "over": { + "title": "Este periodo ha terminado" + }, + "ended": { + "body": "Los informes nuevos están cerrados. Los informes que has empezado esperan aquí." + }, + "full": { + "body": "Todas las plazas están ocupadas. Los informes que has empezado esperan al próximo periodo.", + "last": "Todas las plazas están ocupadas. Los informes que has empezado esperan aquí." + }, + "opens": "Abre {date}", + "closed": "Cerró {date}", + "next": "Próximo periodo {date}" + } }, "meta": { "publish": "Publicar | Openscholar", diff --git a/messages/fr.json b/messages/fr.json index 9fce9db0b..28344d311 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -6584,7 +6584,75 @@ "priceThreeHint": "Ce que coûte la publication d’un rapport sous une licence NC ou ND, ou sous la licence ouverte propre à son auteur, en dollars américains.", "prices": "Prix", "priceClosed": "Licences propres non ouvertes", - "priceClosedHint": "Ce que coûte la publication d’un rapport sous la licence propre à son auteur qui ne permet à personne de le partager, en dollars américains." + "priceClosedHint": "Ce que coûte la publication d’un rapport sous la licence propre à son auteur qui ne permet à personne de le partager, en dollars américains.", + "intake": { + "title": "Nouveaux rapports", + "when": "Quand ils sont ouverts", + "hint": { + "off": "Personne ne peut commencer ni activer de rapport. Les rapports déjà commencés attendent dans Vos rapports.", + "on": "Toute personne connectée peut commencer et activer des rapports, dans les limites ci-dessous.", + "dates": "Ouverts entre ces dates, dans les limites ci-dessous." + }, + "mode": { + "off": "Désactivé", + "on": "Activé", + "dates": "Entre deux dates" + }, + "timezone": "Fuseau horaire", + "timezoneHint": "Les dates et les périodes calendaires suivent son heure", + "opens": "Ouverture", + "opensHint": "Laissez vide pour les ouvrir maintenant", + "closes": "Fermeture", + "closesHint": "Laissez vide pour les garder ouverts", + "closePast": "Choisissez un moment à venir.", + "closeBeforeOpen": "Choisissez un moment après l'ouverture.", + "startsIn": "Ouvre {time}", + "left": "Ferme {time}", + "over": "Terminé", + "limits": "Limites", + "addLimit": "Ajouter une limite", + "noLimits": "Aucune limite. Tout rapport prêt peut être activé.", + "limitsHint": "Chaque limite compte les activations. Une fois une limite atteinte, les nouveaux rapports et les activations attendent sa prochaine période.", + "countLabel": "Activations autorisées", + "countWrong": "Saisissez un nombre entier de 1 à {max}.", + "activations": "{count, plural, one {activation} other {activations}}", + "periodLabel": "Période", + "period": { + "day": "par jour", + "week": "par semaine", + "month": "par mois", + "total": "au total", + "dates": "entre les dates" + }, + "resetLabel": "Comment la période est comptée", + "rolling": { + "day": "24 dernières heures", + "week": "7 derniers jours", + "month": "30 derniers jours" + }, + "calendar": { + "day": "De minuit à minuit", + "week": "Du lundi au dimanche", + "month": "Mois civil" + }, + "remove": "Supprimer la limite", + "usedLabel": "Activations sur cette période", + "used": "{used} sur {count}", + "full": "Complet", + "startsAgain": "Repart à zéro {date}", + "frees": "Une place se libère {date}", + "untilClose": "Jusqu'à la fermeture", + "sinceOpen": "Depuis l'ouverture", + "state": { + "open": "Ouvert", + "openUntil": "Ouvert jusqu'au {date}", + "off": "Désactivé", + "opens": "Ouvre le {date}", + "ended": "Terminé le {date}", + "full": "Complet", + "fullUntil": "Complet jusqu'au {date}" + } + } }, "flow": { "steps": { @@ -7069,7 +7137,36 @@ "docidAgain": "Redemander à DOCiD", "reservedDocid": "Attribué par DOCiD", "copyDocid": "Copier le DOCiD", - "docidCopied": "DOCiD copié" + "docidCopied": "DOCiD copié", + "intake": { + "shut": { + "off": "Les nouveaux rapports sont fermés", + "notYet": "Les nouveaux rapports ouvrent le {date}", + "next": "La prochaine période commence le {date}", + "over": "Cette période est terminée" + }, + "off": { + "title": "Les nouveaux rapports sont fermés", + "body": "Les rapports que vous avez commencés attendent ici jusqu'à leur réouverture." + }, + "notYet": { + "title": "Les nouveaux rapports ne sont pas encore ouverts", + "body": "Les rapports que vous avez commencés attendent ici d'ici là." + }, + "over": { + "title": "Cette période est terminée" + }, + "ended": { + "body": "Les nouveaux rapports sont fermés. Les rapports que vous avez commencés attendent ici." + }, + "full": { + "body": "Toutes les places sont prises. Les rapports que vous avez commencés attendent la prochaine période.", + "last": "Toutes les places sont prises. Les rapports que vous avez commencés attendent ici." + }, + "opens": "Ouvre le {date}", + "closed": "Fermé le {date}", + "next": "Prochaine période le {date}" + } }, "meta": { "publish": "Publier | Openscholar", diff --git a/messages/hi.json b/messages/hi.json index 2fad2ec74..8e39fc85c 100644 --- a/messages/hi.json +++ b/messages/hi.json @@ -6584,7 +6584,75 @@ "priceThreeHint": "NC या ND लाइसेंस, या लेखक के अपने खुले लाइसेंस के तहत रिपोर्ट प्रकाशित करने की लागत, अमेरिकी डॉलर में।", "prices": "कीमतें", "priceClosed": "अपने लाइसेंस जो खुले नहीं हैं", - "priceClosedHint": "लेखक के अपने उस लाइसेंस के तहत रिपोर्ट प्रकाशित करने की लागत जो किसी को इसे साझा करने नहीं देता, अमेरिकी डॉलर में।" + "priceClosedHint": "लेखक के अपने उस लाइसेंस के तहत रिपोर्ट प्रकाशित करने की लागत जो किसी को इसे साझा करने नहीं देता, अमेरिकी डॉलर में।", + "intake": { + "title": "नई रिपोर्टें", + "when": "कब खुली हैं", + "hint": { + "off": "कोई भी रिपोर्ट शुरू या सक्रिय नहीं कर सकता। पहले से शुरू की गई रिपोर्टें आपकी रिपोर्टें में इंतज़ार करती हैं।", + "on": "साइन इन किया हुआ कोई भी व्यक्ति नीचे की सीमाओं के भीतर रिपोर्टें शुरू और सक्रिय कर सकता है।", + "dates": "इन तारीखों के बीच खुली, नीचे की सीमाओं के भीतर।" + }, + "mode": { + "off": "बंद", + "on": "चालू", + "dates": "तारीखों के बीच" + }, + "timezone": "समय क्षेत्र", + "timezoneHint": "तारीखें और कैलेंडर अवधियाँ इसकी घड़ी से चलती हैं", + "opens": "खुलती हैं", + "opensHint": "अभी खोलने के लिए खाली छोड़ें", + "closes": "बंद होती हैं", + "closesHint": "खुली रखने के लिए खाली छोड़ें", + "closePast": "आने वाला कोई समय चुनें।", + "closeBeforeOpen": "खुलने के बाद का कोई समय चुनें।", + "startsIn": "{time} खुलती हैं", + "left": "{time} बंद होती हैं", + "over": "खत्म", + "limits": "सीमाएँ", + "addLimit": "सीमा जोड़ें", + "noLimits": "कोई सीमा नहीं। तैयार हर रिपोर्ट सक्रिय की जा सकती है।", + "limitsHint": "हर सीमा सक्रियणों को गिनती है। किसी एक तक पहुँचने पर नई रिपोर्टें और सक्रियण उसकी अगली अवधि का इंतज़ार करते हैं।", + "countLabel": "अनुमत सक्रियण", + "countWrong": "1 से {max} तक की पूरी संख्या लिखें।", + "activations": "{count, plural, one {सक्रियण} other {सक्रियण}}", + "periodLabel": "अवधि", + "period": { + "day": "प्रति दिन", + "week": "प्रति सप्ताह", + "month": "प्रति माह", + "total": "कुल", + "dates": "तारीखों के बीच" + }, + "resetLabel": "अवधि कैसे गिनी जाती है", + "rolling": { + "day": "पिछले 24 घंटे", + "week": "पिछले 7 दिन", + "month": "पिछले 30 दिन" + }, + "calendar": { + "day": "आधी रात से आधी रात", + "week": "सोमवार से रविवार", + "month": "कैलेंडर माह" + }, + "remove": "सीमा हटाएँ", + "usedLabel": "इस अवधि के सक्रियण", + "used": "{count} में से {used}", + "full": "भरी हुई", + "startsAgain": "{date} फिर से शुरू", + "frees": "{date} एक जगह खाली होगी", + "untilClose": "बंद होने तक", + "sinceOpen": "खुलने के बाद से", + "state": { + "open": "खुली", + "openUntil": "{date} तक खुली", + "off": "बंद", + "opens": "{date} खुलेंगी", + "ended": "{date} को खत्म", + "full": "भरी हुई", + "fullUntil": "{date} तक भरी हुई" + } + } }, "flow": { "steps": { @@ -7069,7 +7137,36 @@ "docidAgain": "DOCiD से फिर पूछें", "reservedDocid": "DOCiD द्वारा दिया गया", "copyDocid": "DOCiD कॉपी करें", - "docidCopied": "DOCiD कॉपी हो गया" + "docidCopied": "DOCiD कॉपी हो गया", + "intake": { + "shut": { + "off": "नई रिपोर्टें बंद हैं", + "notYet": "नई रिपोर्टें {date} खुलेंगी", + "next": "अगली अवधि {date} शुरू होगी", + "over": "यह अवधि खत्म हो गई है" + }, + "off": { + "title": "नई रिपोर्टें बंद हैं", + "body": "आपकी शुरू की गई रिपोर्टें फिर से खुलने तक यहाँ इंतज़ार करती हैं।" + }, + "notYet": { + "title": "नई रिपोर्टें अभी खुली नहीं हैं", + "body": "तब तक आपकी शुरू की गई रिपोर्टें यहाँ इंतज़ार करती हैं।" + }, + "over": { + "title": "यह अवधि खत्म हो गई है" + }, + "ended": { + "body": "नई रिपोर्टें बंद हैं। आपकी शुरू की गई रिपोर्टें यहाँ इंतज़ार करती हैं।" + }, + "full": { + "body": "इसकी हर जगह भर चुकी है। आपकी शुरू की गई रिपोर्टें अगली अवधि का इंतज़ार करती हैं।", + "last": "इसकी हर जगह भर चुकी है। आपकी शुरू की गई रिपोर्टें यहाँ इंतज़ार करती हैं।" + }, + "opens": "{date} खुलेंगी", + "closed": "{date} को बंद", + "next": "अगली अवधि {date}" + } }, "meta": { "publish": "प्रकाशित करें | Openscholar", diff --git a/messages/ja.json b/messages/ja.json index 232fd768e..fbc49e2c6 100644 --- a/messages/ja.json +++ b/messages/ja.json @@ -6584,7 +6584,75 @@ "priceThreeHint": "NC または ND ライセンス、または著者独自のオープンライセンスでレポートを公開する料金(米ドル)。", "prices": "料金", "priceClosed": "オープンでない独自ライセンス", - "priceClosedHint": "誰にも共有を認めない著者独自のライセンスでレポートを公開する料金(米ドル)。" + "priceClosedHint": "誰にも共有を認めない著者独自のライセンスでレポートを公開する料金(米ドル)。", + "intake": { + "title": "新しいレポート", + "when": "受付期間", + "hint": { + "off": "誰もレポートを開始・有効化できません。開始済みのレポートは「あなたのレポート」で待機します。", + "on": "サインインしている人は誰でも、下の上限の範囲でレポートを開始・有効化できます。", + "dates": "この期間中、下の上限の範囲で受け付けます。" + }, + "mode": { + "off": "オフ", + "on": "オン", + "dates": "期間を指定" + }, + "timezone": "タイムゾーン", + "timezoneHint": "日付とカレンダー期間はこの時刻に従います", + "opens": "開始", + "opensHint": "空欄にすると今すぐ受付を開始します", + "closes": "終了", + "closesHint": "空欄にすると受付を続けます", + "closePast": "これから先の日時を選んでください。", + "closeBeforeOpen": "開始より後の日時を選んでください。", + "startsIn": "{time}に開始", + "left": "{time}に終了", + "over": "終了", + "limits": "上限", + "addLimit": "上限を追加", + "noLimits": "上限はありません。準備ができたレポートはすべて有効化できます。", + "limitsHint": "各上限は有効化の数を数えます。いずれかに達すると、新しいレポートと有効化は次の期間まで待機します。", + "countLabel": "許可する有効化の数", + "countWrong": "1 から {max} までの整数を入力してください。", + "activations": "{count, plural, other {件の有効化}}", + "periodLabel": "期間", + "period": { + "day": "1日あたり", + "week": "1週間あたり", + "month": "1か月あたり", + "total": "合計", + "dates": "指定期間中" + }, + "resetLabel": "期間の数え方", + "rolling": { + "day": "直近24時間", + "week": "直近7日間", + "month": "直近30日間" + }, + "calendar": { + "day": "0時から0時まで", + "week": "月曜から日曜まで", + "month": "暦月" + }, + "remove": "上限を削除", + "usedLabel": "この期間の有効化", + "used": "{used} / {count}", + "full": "満員", + "startsAgain": "{date}にリセット", + "frees": "{date}に枠が空きます", + "untilClose": "終了まで", + "sinceOpen": "開始から", + "state": { + "open": "受付中", + "openUntil": "{date}まで受付中", + "off": "オフ", + "opens": "{date}に開始", + "ended": "{date}に終了", + "full": "満員", + "fullUntil": "{date}まで満員" + } + } }, "flow": { "steps": { @@ -7069,7 +7137,36 @@ "docidAgain": "DOCiD にもう一度依頼", "reservedDocid": "DOCiD が発行", "copyDocid": "DOCiD をコピー", - "docidCopied": "DOCiD をコピーしました" + "docidCopied": "DOCiD をコピーしました", + "intake": { + "shut": { + "off": "新しいレポートの受付は停止中です", + "notYet": "新しいレポートの受付は{date}に始まります", + "next": "次の期間は{date}に始まります", + "over": "この期間は終了しました" + }, + "off": { + "title": "新しいレポートの受付は停止中です", + "body": "開始したレポートは、受付が再開されるまでここで待機します。" + }, + "notYet": { + "title": "新しいレポートの受付はまだ始まっていません", + "body": "それまで、開始したレポートはここで待機します。" + }, + "over": { + "title": "この期間は終了しました" + }, + "ended": { + "body": "新しいレポートの受付は終了しました。開始したレポートはここで待機します。" + }, + "full": { + "body": "この期間の枠はすべて埋まりました。開始したレポートは次の期間まで待機します。", + "last": "この期間の枠はすべて埋まりました。開始したレポートはここで待機します。" + }, + "opens": "{date}に開始", + "closed": "{date}に終了", + "next": "次の期間 {date}" + } }, "meta": { "publish": "公開 | Openscholar", diff --git a/messages/pt.json b/messages/pt.json index 1022607b2..db5fb147a 100644 --- a/messages/pt.json +++ b/messages/pt.json @@ -6585,7 +6585,75 @@ "priceThreeHint": "Quanto custa publicar um relatório sob uma licença NC ou ND, ou sob a licença aberta do próprio autor, em dólares americanos.", "prices": "Preços", "priceClosed": "Licenças próprias que não são abertas", - "priceClosedHint": "Quanto custa publicar um relatório sob a licença do próprio autor que não permite que ninguém o compartilhe, em dólares americanos." + "priceClosedHint": "Quanto custa publicar um relatório sob a licença do próprio autor que não permite que ninguém o compartilhe, em dólares americanos.", + "intake": { + "title": "Novos relatórios", + "when": "Quando estão abertos", + "hint": { + "off": "Ninguém pode começar nem ativar um relatório. Os relatórios já começados aguardam em Seus relatórios.", + "on": "Qualquer pessoa com sessão iniciada pode começar e ativar relatórios, dentro dos limites abaixo.", + "dates": "Abertos entre estas datas, dentro dos limites abaixo." + }, + "mode": { + "off": "Desligado", + "on": "Ligado", + "dates": "Entre datas" + }, + "timezone": "Fuso horário", + "timezoneHint": "As datas e os períodos de calendário seguem o seu relógio", + "opens": "Abertura", + "opensHint": "Deixe vazio para abri-los agora", + "closes": "Encerramento", + "closesHint": "Deixe vazio para mantê-los abertos", + "closePast": "Escolha um momento futuro.", + "closeBeforeOpen": "Escolha um momento depois da abertura.", + "startsIn": "Abre {time}", + "left": "Fecha {time}", + "over": "Encerrado", + "limits": "Limites", + "addLimit": "Adicionar limite", + "noLimits": "Sem limite. Qualquer relatório pronto pode ser ativado.", + "limitsHint": "Cada limite conta ativações. Quando um é atingido, novos relatórios e ativações aguardam o próximo período.", + "countLabel": "Ativações permitidas", + "countWrong": "Digite um número inteiro de 1 a {max}.", + "activations": "{count, plural, one {ativação} other {ativações}}", + "periodLabel": "Período", + "period": { + "day": "por dia", + "week": "por semana", + "month": "por mês", + "total": "no total", + "dates": "entre as datas" + }, + "resetLabel": "Como o período é contado", + "rolling": { + "day": "Últimas 24 horas", + "week": "Últimos 7 dias", + "month": "Últimos 30 dias" + }, + "calendar": { + "day": "De meia-noite a meia-noite", + "week": "De segunda a domingo", + "month": "Mês do calendário" + }, + "remove": "Remover limite", + "usedLabel": "Ativações neste período", + "used": "{used} de {count}", + "full": "Cheio", + "startsAgain": "Recomeça {date}", + "frees": "Uma vaga se libera {date}", + "untilClose": "Até o encerramento", + "sinceOpen": "Desde a abertura", + "state": { + "open": "Aberto", + "openUntil": "Aberto até {date}", + "off": "Desligado", + "opens": "Abre {date}", + "ended": "Encerrado em {date}", + "full": "Cheio", + "fullUntil": "Cheio até {date}" + } + } }, "flow": { "steps": { @@ -7070,7 +7138,36 @@ "docidAgain": "Pedir de novo ao DOCiD", "reservedDocid": "Atribuído pelo DOCiD", "copyDocid": "Copiar o DOCiD", - "docidCopied": "DOCiD copiado" + "docidCopied": "DOCiD copiado", + "intake": { + "shut": { + "off": "Novos relatórios estão fechados", + "notYet": "Novos relatórios abrem {date}", + "next": "O próximo período começa {date}", + "over": "Este período terminou" + }, + "off": { + "title": "Novos relatórios estão fechados", + "body": "Os relatórios que você começou aguardam aqui até reabrirem." + }, + "notYet": { + "title": "Novos relatórios ainda não estão abertos", + "body": "Os relatórios que você começou aguardam aqui até lá." + }, + "over": { + "title": "Este período terminou" + }, + "ended": { + "body": "Novos relatórios estão fechados. Os relatórios que você começou aguardam aqui." + }, + "full": { + "body": "Todas as vagas foram ocupadas. Os relatórios que você começou aguardam o próximo período.", + "last": "Todas as vagas foram ocupadas. Os relatórios que você começou aguardam aqui." + }, + "opens": "Abre {date}", + "closed": "Fechou {date}", + "next": "Próximo período {date}" + } }, "meta": { "publish": "Publicar | Openscholar", diff --git a/messages/sw.json b/messages/sw.json index 0a727cee2..65b81d3e8 100644 --- a/messages/sw.json +++ b/messages/sw.json @@ -6585,7 +6585,75 @@ "priceThreeHint": "Gharama ya kuchapisha ripoti chini ya leseni ya NC au ND, au leseni wazi ya mwandishi mwenyewe, kwa dola za Marekani.", "prices": "Bei", "priceClosed": "Leseni za mwandishi zisizo wazi", - "priceClosedHint": "Gharama ya kuchapisha ripoti chini ya leseni ya mwandishi mwenyewe isiyoruhusu mtu yeyote kuishiriki, kwa dola za Marekani." + "priceClosedHint": "Gharama ya kuchapisha ripoti chini ya leseni ya mwandishi mwenyewe isiyoruhusu mtu yeyote kuishiriki, kwa dola za Marekani.", + "intake": { + "title": "Ripoti mpya", + "when": "Zinapokuwa wazi", + "hint": { + "off": "Hakuna anayeweza kuanzisha wala kuwasha ripoti. Ripoti zilizoanzishwa zinasubiri katika Ripoti zako.", + "on": "Yeyote aliyeingia anaweza kuanzisha na kuwasha ripoti, ndani ya mipaka iliyo hapa chini.", + "dates": "Wazi kati ya tarehe hizi, ndani ya mipaka iliyo hapa chini." + }, + "mode": { + "off": "Zima", + "on": "Washa", + "dates": "Kati ya tarehe" + }, + "timezone": "Saa za eneo", + "timezoneHint": "Tarehe na vipindi vya kalenda hufuata saa yake", + "opens": "Inafunguliwa", + "opensHint": "Acha tupu kuzifungua sasa", + "closes": "Inafungwa", + "closesHint": "Acha tupu kuziacha wazi", + "closePast": "Chagua wakati ujao.", + "closeBeforeOpen": "Chagua wakati baada ya kufunguliwa.", + "startsIn": "Inafunguliwa {time}", + "left": "Inafungwa {time}", + "over": "Imekwisha", + "limits": "Mipaka", + "addLimit": "Ongeza kikomo", + "noLimits": "Hakuna kikomo. Kila ripoti iliyo tayari inaweza kuwashwa.", + "limitsHint": "Kila kikomo huhesabu uwashaji. Kimoja kikifikiwa, ripoti mpya na uwashaji husubiri kipindi chake kijacho.", + "countLabel": "Uwashaji unaoruhusiwa", + "countWrong": "Andika namba kamili kutoka 1 hadi {max}.", + "activations": "{count, plural, one {uwashaji} other {uwashaji}}", + "periodLabel": "Kipindi", + "period": { + "day": "kwa siku", + "week": "kwa wiki", + "month": "kwa mwezi", + "total": "jumla", + "dates": "kati ya tarehe" + }, + "resetLabel": "Jinsi kipindi kinavyohesabiwa", + "rolling": { + "day": "Saa 24 zilizopita", + "week": "Siku 7 zilizopita", + "month": "Siku 30 zilizopita" + }, + "calendar": { + "day": "Usiku wa manane hadi usiku wa manane", + "week": "Jumatatu hadi Jumapili", + "month": "Mwezi wa kalenda" + }, + "remove": "Ondoa kikomo", + "usedLabel": "Uwashaji katika kipindi hiki", + "used": "{used} kati ya {count}", + "full": "Imejaa", + "startsAgain": "Inaanza upya {date}", + "frees": "Nafasi inapatikana {date}", + "untilClose": "Hadi zitakapofungwa", + "sinceOpen": "Tangu zilipofunguliwa", + "state": { + "open": "Wazi", + "openUntil": "Wazi hadi {date}", + "off": "Imezimwa", + "opens": "Inafunguliwa {date}", + "ended": "Iliisha {date}", + "full": "Imejaa", + "fullUntil": "Imejaa hadi {date}" + } + } }, "flow": { "steps": { @@ -7070,7 +7138,36 @@ "docidAgain": "Iombe DOCiD tena", "reservedDocid": "Imetolewa na DOCiD", "copyDocid": "Nakili DOCiD", - "docidCopied": "DOCiD imenakiliwa" + "docidCopied": "DOCiD imenakiliwa", + "intake": { + "shut": { + "off": "Ripoti mpya zimefungwa", + "notYet": "Ripoti mpya zitafunguliwa {date}", + "next": "Kipindi kijacho kinaanza {date}", + "over": "Kipindi hiki kimekwisha" + }, + "off": { + "title": "Ripoti mpya zimefungwa", + "body": "Ripoti ulizoanzisha zinasubiri hapa hadi zifunguliwe tena." + }, + "notYet": { + "title": "Ripoti mpya bado hazijafunguliwa", + "body": "Ripoti ulizoanzisha zinasubiri hapa hadi wakati huo." + }, + "over": { + "title": "Kipindi hiki kimekwisha" + }, + "ended": { + "body": "Ripoti mpya zimefungwa. Ripoti ulizoanzisha zinasubiri hapa." + }, + "full": { + "body": "Nafasi zote zimechukuliwa. Ripoti ulizoanzisha zinasubiri kipindi kijacho.", + "last": "Nafasi zote zimechukuliwa. Ripoti ulizoanzisha zinasubiri hapa." + }, + "opens": "Inafunguliwa {date}", + "closed": "Ilifungwa {date}", + "next": "Kipindi kijacho {date}" + } }, "meta": { "publish": "Chapisha | Openscholar", diff --git a/messages/zh.json b/messages/zh.json index 2026ade5f..b729f7662 100644 --- a/messages/zh.json +++ b/messages/zh.json @@ -6584,7 +6584,75 @@ "priceThreeHint": "以 NC 或 ND 许可证,或作者自有的开放许可证发布报告的费用,以美元计。", "prices": "价格", "priceClosed": "不开放的自有许可证", - "priceClosedHint": "以作者自有、不允许任何人分享的许可证发布报告的费用,以美元计。" + "priceClosedHint": "以作者自有、不允许任何人分享的许可证发布报告的费用,以美元计。", + "intake": { + "title": "新报告", + "when": "开放时间", + "hint": { + "off": "任何人都不能开始或激活报告。已开始的报告在“你的报告”中等待。", + "on": "任何已登录的人都可以开始和激活报告,但不超过下方的限额。", + "dates": "在这些日期之间开放,不超过下方的限额。" + }, + "mode": { + "off": "关闭", + "on": "开启", + "dates": "在日期之间" + }, + "timezone": "时区", + "timezoneHint": "日期和日历周期按此时区计算", + "opens": "开放", + "opensHint": "留空则立即开放", + "closes": "关闭", + "closesHint": "留空则保持开放", + "closePast": "请选择一个尚未到来的时间。", + "closeBeforeOpen": "请选择开放之后的时间。", + "startsIn": "{time}开放", + "left": "{time}关闭", + "over": "已结束", + "limits": "限额", + "addLimit": "添加限额", + "noLimits": "没有限额。每份准备好的报告都可以激活。", + "limitsHint": "每个限额统计激活次数。达到任一限额后,新报告和激活会等待下一个周期。", + "countLabel": "允许的激活次数", + "countWrong": "请输入 1 到 {max} 之间的整数。", + "activations": "{count, plural, other {次激活}}", + "periodLabel": "周期", + "period": { + "day": "每天", + "week": "每周", + "month": "每月", + "total": "总计", + "dates": "在日期之间" + }, + "resetLabel": "周期的计算方式", + "rolling": { + "day": "过去 24 小时", + "week": "过去 7 天", + "month": "过去 30 天" + }, + "calendar": { + "day": "午夜到午夜", + "week": "周一到周日", + "month": "日历月" + }, + "remove": "删除限额", + "usedLabel": "本周期的激活次数", + "used": "{used} / {count}", + "full": "已满", + "startsAgain": "{date}重新开始", + "frees": "{date}空出一个名额", + "untilClose": "直到关闭", + "sinceOpen": "自开放以来", + "state": { + "open": "开放中", + "openUntil": "开放至 {date}", + "off": "已关闭", + "opens": "{date}开放", + "ended": "已于 {date}结束", + "full": "已满", + "fullUntil": "已满,至 {date}" + } + } }, "flow": { "steps": { @@ -7069,7 +7137,36 @@ "docidAgain": "再次请求 DOCiD", "reservedDocid": "由 DOCiD 发放", "copyDocid": "复制 DOCiD", - "docidCopied": "已复制 DOCiD" + "docidCopied": "已复制 DOCiD", + "intake": { + "shut": { + "off": "新报告已关闭", + "notYet": "新报告于 {date}开放", + "next": "下一个周期于 {date}开始", + "over": "本周期已结束" + }, + "off": { + "title": "新报告已关闭", + "body": "你已开始的报告会在这里等待,直到重新开放。" + }, + "notYet": { + "title": "新报告尚未开放", + "body": "在此之前,你已开始的报告会在这里等待。" + }, + "over": { + "title": "本周期已结束" + }, + "ended": { + "body": "新报告已关闭。你已开始的报告在这里等待。" + }, + "full": { + "body": "本周期的名额已全部用完。你已开始的报告会等待下一个周期。", + "last": "本周期的名额已全部用完。你已开始的报告在这里等待。" + }, + "opens": "{date}开放", + "closed": "已于 {date}关闭", + "next": "下一个周期 {date}" + } }, "meta": { "publish": "发布 | Openscholar", diff --git a/messages/zu.json b/messages/zu.json index b97f88a3b..7041e0693 100644 --- a/messages/zu.json +++ b/messages/zu.json @@ -6584,7 +6584,75 @@ "priceThreeHint": "Okubiza ukushicilela umbiko ngaphansi kwelayisensi ye-NC noma ye-ND, noma ilayisensi evulekile yombhali uqobo, ngamadola aseMelika.", "prices": "Amanani", "priceClosed": "Amalayisensi ombhali angavulekile", - "priceClosedHint": "Okubiza ukushicilela umbiko ngaphansi kwelayisensi yombhali uqobo engavumeli muntu ukwabelana ngawo, ngamadola aseMelika." + "priceClosedHint": "Okubiza ukushicilela umbiko ngaphansi kwelayisensi yombhali uqobo engavumeli muntu ukwabelana ngawo, ngamadola aseMelika.", + "intake": { + "title": "Imibiko emisha", + "when": "Lapho ivuliwe", + "hint": { + "off": "Akekho ongaqala noma enze kusebenze umbiko. Imibiko eseqaliwe ilinde Emibikweni yakho.", + "on": "Noma ubani ongene ngemvume angaqala futhi enze kusebenze imibiko, ngaphakathi kwemikhawulo engezansi.", + "dates": "Ivuliwe phakathi kwalezi zinsuku, ngaphakathi kwemikhawulo engezansi." + }, + "mode": { + "off": "Valiwe", + "on": "Vuliwe", + "dates": "Phakathi kwezinsuku" + }, + "timezone": "Izoni yesikhathi", + "timezoneHint": "Izinsuku nezikhathi zekhalenda zilandela iwashi layo", + "opens": "Iyavuleka", + "opensHint": "Shiya kungenalutho ukuze uyivule manje", + "closes": "Iyavalwa", + "closesHint": "Shiya kungenalutho ukuze ihlale ivuliwe", + "closePast": "Khetha isikhathi esisazofika.", + "closeBeforeOpen": "Khetha isikhathi ngemva kokuvulwa.", + "startsIn": "Iyavuleka {time}", + "left": "Iyavalwa {time}", + "over": "Kuphelile", + "limits": "Imikhawulo", + "addLimit": "Engeza umkhawulo", + "noLimits": "Awukho umkhawulo. Wonke umbiko olungile ungenziwa usebenze.", + "limitsHint": "Umkhawulo ngamunye ubala ukwenziwa kusebenze. Uma omunye ufinyelelwa, imibiko emisha nokwenziwa kusebenze kulinda isikhathi sawo esilandelayo.", + "countLabel": "Ukwenziwa kusebenze okuvunyelwe", + "countWrong": "Faka inombolo ephelele kusuka ku-1 kuya ku-{max}.", + "activations": "{count, plural, one {ukwenziwa kusebenze} other {ukwenziwa kusebenze}}", + "periodLabel": "Isikhathi", + "period": { + "day": "ngosuku", + "week": "ngeviki", + "month": "ngenyanga", + "total": "sekukonke", + "dates": "phakathi kwezinsuku" + }, + "resetLabel": "Indlela isikhathi esibalwa ngayo", + "rolling": { + "day": "Amahora angu-24 adlule", + "week": "Izinsuku ezingu-7 ezedlule", + "month": "Izinsuku ezingu-30 ezedlule" + }, + "calendar": { + "day": "Phakathi kwamabili kuya phakathi kwamabili", + "week": "UMsombuluko kuya ISonto", + "month": "Inyanga yekhalenda" + }, + "remove": "Susa umkhawulo", + "usedLabel": "Ukwenziwa kusebenze kulesi sikhathi", + "used": "{used} kokungu-{count}", + "full": "Kugcwele", + "startsAgain": "Iqala kabusha {date}", + "frees": "Kukhululeka indawo {date}", + "untilClose": "Kuze kuvalwe", + "sinceOpen": "Selokhu kwavulwa", + "state": { + "open": "Kuvuliwe", + "openUntil": "Kuvuliwe kuze kube ngu-{date}", + "off": "Kuvaliwe", + "opens": "Kuvuleka {date}", + "ended": "Kuphele {date}", + "full": "Kugcwele", + "fullUntil": "Kugcwele kuze kube ngu-{date}" + } + } }, "flow": { "steps": { @@ -7069,7 +7137,36 @@ "docidAgain": "Cela i-DOCiD futhi", "reservedDocid": "Inikezwe yi-DOCiD", "copyDocid": "Kopisha i-DOCiD", - "docidCopied": "I-DOCiD ikopishiwe" + "docidCopied": "I-DOCiD ikopishiwe", + "intake": { + "shut": { + "off": "Imibiko emisha ivaliwe", + "notYet": "Imibiko emisha ivuleka {date}", + "next": "Isikhathi esilandelayo siqala {date}", + "over": "Lesi sikhathi siphelile" + }, + "off": { + "title": "Imibiko emisha ivaliwe", + "body": "Imibiko oyiqalile ilinde lapha ize ivulwe futhi." + }, + "notYet": { + "title": "Imibiko emisha ayikavulwa", + "body": "Imibiko oyiqalile ilinde lapha kuze kube yileso sikhathi." + }, + "over": { + "title": "Lesi sikhathi siphelile" + }, + "ended": { + "body": "Imibiko emisha ivaliwe. Imibiko oyiqalile ilinde lapha." + }, + "full": { + "body": "Zonke izindawo kuso zithathiwe. Imibiko oyiqalile ilinde isikhathi esilandelayo.", + "last": "Zonke izindawo kuso zithathiwe. Imibiko oyiqalile ilinde lapha." + }, + "opens": "Iyavuleka {date}", + "closed": "Ivaliwe {date}", + "next": "Isikhathi esilandelayo {date}" + } }, "meta": { "publish": "Shicilela | Openscholar", diff --git a/scripts/user-actions-exempt.json b/scripts/user-actions-exempt.json index 86814fb27..661f618f3 100644 --- a/scripts/user-actions-exempt.json +++ b/scripts/user-actions-exempt.json @@ -281,6 +281,8 @@ "reports/settings:saveCheck": "Site administration, for Openscholar's own admins on the admin pages.", "reports/settings:setAgreement": "Site administration, for Openscholar's own admins on the admin pages.", "reports/settings:setMetadataModel": "Site administration, for Openscholar's own admins on the admin pages.", + "reports/intake:admin": "Site administration, for Openscholar's own admins on the admin pages.", + "reports/intake:save": "Site administration, for Openscholar's own admins on the admin pages.", "reports/settings:update": "Site administration, for Openscholar's own admins on the admin pages.", "reports/settings:switchCheck": "Site administration, for Openscholar's own admins on the admin pages.", "reports/flow:sign": "Publishing a report under a signed agreement, with its PDF and its checks: done on the Publish page, where the person reads what they sign and sees what goes public.", From cdcb5e1ef127e727404836d63f441db5bd783e02 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 24 Nov 2026 13:20:08 +0000 Subject: [PATCH 3/4] fix(reports): new reports settings from review Saves send only what changed, so one admin's change never puts back another's. A day whose midnight a clock change skips starts at the first instant after the gap. The payment dialog closes when the last place is taken, the closed notice opens by height under the step trail and above the list, an organisation admin sees it on a member's draft, and up to 50 limits. --- components/reports/new-report-settings.tsx | 6 ++---- components/reports/publish-flow.tsx | 22 +++++++++++++++------- convex/reports/intake.ts | 16 +++++++++++++--- lib/reports/intake.test.ts | 5 +++++ lib/reports/intake.ts | 14 +++++++++++--- 5 files changed, 46 insertions(+), 17 deletions(-) diff --git a/components/reports/new-report-settings.tsx b/components/reports/new-report-settings.tsx index b3a3ec254..6cff1f620 100644 --- a/components/reports/new-report-settings.tsx +++ b/components/reports/new-report-settings.tsx @@ -52,10 +52,8 @@ export function NewReportSettings({ data: { intake, uses }, minute, now }: { dat const shown = store.getQuery(api.reports.intake.admin, { now: minute }); if (shown) store.setQuery(api.reports.intake.admin, { now: minute }, { ...shown, intake: { ...shown.intake, ...asked } }); }); - const set = (patch: Partial) => { - const { openedAt: _, ...next } = { ...intake, ...patch }; - void save(next).catch(failed); - }; + // Only what changed is sent: the server keeps the rest as saved. + const set = (patch: Partial>) => void save(patch).catch(failed); const setLimit = (id: string, patch: Partial) => set({ limits: intake.limits.map((limit) => (limit.id === id ? { ...limit, ...patch } : limit)) }); const add = () => { // The first limit is the one most need: the whole time open between dates, or a week. Another is most often a day. diff --git a/components/reports/publish-flow.tsx b/components/reports/publish-flow.tsx index 9405c9bf2..0db410e14 100644 --- a/components/reports/publish-flow.tsx +++ b/components/reports/publish-flow.tsx @@ -515,8 +515,8 @@ export function PublishFlow() { setFresh(null); go({ view: null, report: "new", correct: null, step: null }); }; - // A report not yet live, and never live before: the drafts that wait. - const waits = !!report && report.mine && report.status !== "live" && report.activatedAt === undefined && !intake.open; + // A report not yet live, and never live before: the drafts that wait, whoever opens them (an organisation's admin activates a member's). + const waits = !!report && report.status !== "live" && report.activatedAt === undefined && !intake.open; const hasReports = (counts?.all ?? 0) > 0; // Publishing switched off stops new reports. One already started keeps its address, and the list stays. const closed = (!basics.open || !intake.open) && !listing && !report && !missing; @@ -556,12 +556,21 @@ export function PublishFlow() { ) ) : undefined } - intro={!listing && !missing && !closed ? up("step")} humanReview={basics.humanReview} paying={!!terms?.paying && !chargeOver} onStep={toStep} /> : undefined} + intro={ + !listing && !missing && !closed ? ( + <> + up("step")} humanReview={basics.humanReview} paying={!!terms?.paying && !chargeOver} onStep={toStep} /> + {/* New reports closed: a draft says why its Next and Activate wait, and when the next period starts. Closing while + the page is open (the last place taken) opens it by height, so nothing below jumps. */} + {basics.open && waits ?
        : null}
        + + ) : undefined + } > {listing ? (
        - {basics.open ? : null} + {basics.open && !intake.open ?
        : null}
        {trouble.problem} ) : null} - {/* New reports closed : a draft says why its Next and Activate wait, and when the next period starts. */} - {basics.open && waits ? : null} {/* One set of screens for every report: going from one to another, or to a new report's agreement, is a change of screen like any other, and what belongs to one report is put away inside (Screens). */} @@ -2272,7 +2279,8 @@ function Checks({ beside = null, rows, report, humanReview, terms, onActivate, o // Asks before the charge: a saved card is charged as soon as it's confirmed, with no page of Stripe's in // between. With none saved, confirming goes on to Stripe's page, and the dialog says so. { await refuseApps(ctx); @@ -75,7 +84,8 @@ export const save = mutation({ const saved = intakeOf(row); const now = Date.now(); // Switched on, or from on to between dates and back, "in total" counts from now. - const intake: Intake = { ...asked, openedAt: asked.mode !== "off" && asked.mode !== saved.mode ? now : saved.openedAt }; + const merged = { ...saved, ...asked }; + const intake: Intake = { ...merged, openedAt: merged.mode !== "off" && merged.mode !== saved.mode ? now : saved.openedAt }; const problem = intakeProblem(intake, now, saved); if (problem) throw createError("VALIDATION_ERROR", problem); await saveSettings(ctx, row._id, { intake }); diff --git a/lib/reports/intake.test.ts b/lib/reports/intake.test.ts index cd950080b..5aa7a5086 100644 --- a/lib/reports/intake.test.ts +++ b/lib/reports/intake.test.ts @@ -21,6 +21,11 @@ describe("calendarStart", () => { expect(calendarStart("day", now, "America/New_York", 1)).toBe(at("2026-03-09T04:00Z")); }); + it("starts a day whose midnight a clock change skips at the first instant of it", () => { + // Santiago goes from UTC-4 to UTC-3 at midnight on 6 September 2026: the day starts at 01:00, 04:00 UTC. + expect(calendarStart("day", at("2026-09-06T12:00Z"), "America/Santiago")).toBe(at("2026-09-06T04:00Z")); + }); + it("starts the month on the 1st, and the next one across the year's end", () => { expect(calendarStart("month", at("2026-12-20T10:00Z"), "UTC")).toBe(at("2026-12-01T00:00Z")); expect(calendarStart("month", at("2026-12-20T10:00Z"), "UTC", 1)).toBe(at("2027-01-01T00:00Z")); diff --git a/lib/reports/intake.ts b/lib/reports/intake.ts index 72b46e6c7..53b97c8a0 100644 --- a/lib/reports/intake.ts +++ b/lib/reports/intake.ts @@ -12,7 +12,7 @@ export type Period = (typeof PERIODS)[number]; export type Reset = (typeof RESETS)[number]; /** The most limits, and the most activations one counts: the latest that many are read each time one is checked. */ -export const LIMITS_MAX = 10; +export const LIMITS_MAX = 50; export const LIMIT_COUNT_MAX = 5000; export type Limit = { id: string; count: number; period: Period; reset: Reset }; @@ -40,10 +40,18 @@ function offsetAt(at: number, timeZone: string) { return match ? (match[1] === "-" ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3])) * 60_000 : 0; } -/** A wall-clock time in a timezone as an instant. Month from 0; days past the month's end roll on. */ +/** + * A wall-clock time in a timezone as an instant. Month from 0; days past the month's end roll on. A time a clock + * change skips (Santiago's midnight on its first day of summer time) is the first instant after the gap. + */ export function zoned(year: number, month: number, day: number, hour: number, minute: number, timeZone: string) { const guess = Date.UTC(year, month, day, hour, minute); - return guess - offsetAt(guess - offsetAt(guess, timeZone), timeZone); + // The instant under the offset before the change and under the one after: the wall clock reads `guess` at one of + // them, or, in a gap, at neither, and the later one is where the skipped time lands. + const first = guess - offsetAt(guess, timeZone); + const candidates = [first, guess - offsetAt(first, timeZone)]; + const shows = candidates.filter((at) => at + offsetAt(at, timeZone) === guess); + return shows.length ? Math.min(...shows) : Math.max(...candidates); } /** An instant as the wall clock in a timezone: month from 1, weekday from 0 on Sunday. */ From ae5888d87c422d0602cc9299a3d971f751794880 Mon Sep 17 00:00:00 2001 From: sickerine Date: Tue, 24 Nov 2026 13:43:17 +0000 Subject: [PATCH 4/4] perf(reports): work out a limit's period start once, not per activation At 50 limits and 5,000 activations the admin's counts took seconds, each row asking the calendar again; once per limit they take 16 ms. --- lib/reports/intake.ts | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/lib/reports/intake.ts b/lib/reports/intake.ts index 53b97c8a0..6a82331ee 100644 --- a/lib/reports/intake.ts +++ b/lib/reports/intake.ts @@ -94,10 +94,21 @@ export const fromLocalInput = (value: string, timeZone: string) => { /** Where "in total" counts from: the opening date, or when new reports were switched on. */ const windowStart = (intake: Intake) => (intake.mode === "dates" && intake.opensAt !== null ? intake.opensAt : (intake.openedAt ?? 0)); -/** Whether an activation made at `at` counts in a limit's period at `now`: a rolling period leaves out its first instant, which is exactly 24 hours, 7 days or 30 days ago. */ -function counts(limit: Limit, intake: Intake, at: number, now: number) { - if (limit.period === "window") return at >= windowStart(intake); - return limit.reset === "rolling" ? at > now - ROLLING[limit.period] : at >= calendarStart(limit.period, now, intake.timezone); +/** + * Whether an activation counts in a limit's period at `now`, worked out once for the period: a rolling period leaves + * out its first instant, which is exactly 24 hours, 7 days or 30 days ago. + */ +function countsFrom(limit: Limit, intake: Intake, now: number): (at: number) => boolean { + if (limit.period === "window") { + const start = windowStart(intake); + return (at) => at >= start; + } + if (limit.reset === "rolling") { + const after = now - ROLLING[limit.period]; + return (at) => at > after; + } + const start = calendarStart(limit.period, now, intake.timezone); + return (at) => at >= start; } /** @@ -106,7 +117,7 @@ function counts(limit: Limit, intake: Intake, at: number, now: number) { * rolling one has a place again once that one leaves it. */ export function limitAt(limit: Limit, intake: Intake, nth: number | null, now: number) { - const full = nth !== null && counts(limit, intake, nth, now); + const full = nth !== null && countsFrom(limit, intake, now)(nth); const startsAgain = limit.period === "window" ? null : limit.reset === "calendar" ? calendarStart(limit.period, now, intake.timezone, 1) : full ? nth! + ROLLING[limit.period] : null; return { full, startsAgain }; } @@ -138,8 +149,9 @@ export const nthsOf = (limits: Limit[], latest: number[]) => Object.fromEntries( /** How many activations a limit has counted in the period `now` is in, from the latest activations, newest first. */ export function usedAt(limit: Limit, intake: Intake, latest: number[], now: number) { + const counts = countsFrom(limit, intake, now); let used = 0; - while (used < latest.length && counts(limit, intake, latest[used], now)) used++; + while (used < latest.length && counts(latest[used])) used++; return used; }