Repository navigation
feat(events): keep finished events published but off the public feeds - #604
Merged
Merged
Conversation
Adds a stored, indexed, hidden `lastDate` sub-field to `scheduleFields()`,
recomputed on every write by a `computeLastDate` beforeChange field hook.
Value is the end of the final occurrence's *local* day (so an event running
today stays live until its own midnight), or `null` when the recurrence never
ends. The pure `lastOccurrenceEnd()` helper is the single definition; the
column is just its DB-queryable projection.
Termination is read off the built rule's own options rather than re-derived
from the sub-fields, so it can't drift from buildRRuleTemporal's conditions.
The hook computes from `{ ...previousSiblingDoc, ...siblingData }`: a field
beforeChange hook only receives the incoming patch and Payload materialises
`{}` for an omitted group, so reading siblingData alone would NULL lastDate
on every unrelated write.
Refs #603
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Nullable timestamp + btree index on events, app_cards and both version tables (scheduleFields is shared with AppCards). Nullable by design: the column degrades gracefully — a NULL reads as "never ends", so the feeds keep showing an un-backfilled event rather than hiding it — and any write to a row back-fills it via computeLastDate. Refs #603 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Replaces the `upcomingDates` finished-check with one shared definition: - `shouldFinish` moves from the ExpireEvents stage machine into `@/lib/schedule/scheduleStatus` — it's now shared with the public feeds and (once #599 lands) the registration gate, so it can't live inside one job. It keys off the schedule's last occurrence instead of the virtual `upcomingDates`, retiring the MAX_MONTHS_AHEAD false positive that made a monthly-every-12-months event read as finished while still running. - `notFinishedWhere(now)` is its SQL counterpart, over the stored column. A unit matrix pins the two to the same answers — they're separate implementations because a `where` can't call a function. - `finishEvent` no longer sets `_status: 'draft'`: a finished event stays published so its Atlas page keeps resolving for a late seeker following an old link. `finished` therefore joins PUBLISHED_STAGES. `shouldFinish` computes from the sub-fields rather than reading the stored column, so the nightly sweep is correct from the moment this ships, with no dependency on the backfill having run. `EventScheduleInput` moves to src/types/schedule.ts now that it has a second consumer, and becomes the parameter type of buildRRuleTemporal / lastOccurrenceEnd so reading a schedule off a document needs no cast. Refs #603 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Nothing unpublishes a finished event any more, so these two filters are the only thing keeping it off the map and out of listings: - `GET /api/events/geojson` ANDs `notFinishedWhere(now)` onto the caller's `where` unconditionally. Because it's part of the read rather than a post-read drop, `totalDocs` and pagination reflect the filtered set, and a caller's own `where` cannot bring finished events back into the map feed. - `excludeFinishedEvents` (beforeOperation) does the same for an API client's `find` / `count`, but with an opt-out: a `where` naming `schedule.lastDate` is honoured, so a client asking for past events gets them. `findByID` is untouched, so old Atlas links keep resolving. Two things Payload's behaviour dictated here, both verified against it: - `find` and `findByID` both reach a beforeOperation hook as `operation: 'read'`, so the list/single split is made on `findByID`'s `id` arg — the same trick `filterMeditationsByLocale` uses. Guarding on `'find'` silently matched nothing. - Only the dotted `schedule.lastDate` path is queryable; the nested-group shape is rejected upstream with "path cannot be queried". So the opt-out check needs no nested-form branch, and a test pins that rejection. Refs #603 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Covers the behaviour change directly: finishing sets `finished` + clears `nextCheckAt` and leaves `_status: 'published'` (with webPath/webUrl still non-null), an open-ended recurrence never finishes, and the unverified ladder still unpublishes at `urgent → expired` and trashes after the grace period. Verified non-vacuous: restoring `_status: 'draft'` in finishEvent fails the first case with "expected 'draft' to be 'published'". Also adds the missing `captureMessage` export to this spec's Sentry mock. `resolveRecipients` reports an absent region manager through it, so every region-escalating stage threw before reaching its assertions — no existing test drove one to completion, so the ladder never actually advanced here. It now does (advanced: 1, remindersSent: 1, failed: 0). Refs #603 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`POST /api/events/{id}/register` relied on the published-only access filter to
404 an unregistrable event. A finished event is now published, so that filter
no longer catches one whose schedule has run out — registration would have
succeeded for an event that is over. Rejects with 409 + "This event has ended"
instead: the event exists and is readable, its state just conflicts.
Doing this needed one supporting change. The endpoint's own event lookup
forwards the client `req` via `asTrustedReq`, so `excludeFinishedEvents` was
filtering the event out of it — collapsing the new 409 back into a 404. The
hook now exempts trusted reqs via a new `isTrustedReq` companion to
`asTrustedReq`: an endpoint doing its own lookup needs the true state to answer
precisely. This follows the split `validateClientOriginHook` documents —
result-shaping hooks honour the trusted flag, security gates don't.
Scope note: #599 owns the broader gating rules (capacity, external mode, a
course already under way) and lands the same refusal as `event_ended`; this
closes only the hole reopened here.
Refs #603
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Rows written before the column shipped hold NULL, which reads as "never ends" — so a finished event would stay on the public feeds until something recomputed it. `scripts/backfill-schedule-last-date.ts` walks `events` + `app-cards` and fixes them; reports by default, writes with `--force`. The routine lives in `src/lib/schedule/backfillLastDate.ts` rather than in the script: it spans two collections, so it belongs to neither one's folder, and keeping it out of the CLI makes it testable without the script's dotenv + config-bootstrap side effects. Two safety properties are pinned by tests rather than asserted: - `skipVerifyHook` on the write. Without it the Events `verifyOnSave` hook treats each backfilled row as a fresh verification and silently restarts every escalation cycle — removing the flag fails the test on a moved `nextCheckAt`. - Re-runnable. `lastOccurrenceEnd` has no clock, so a second pass reports 0 changed. Not verified by a live run: a dry run against the shared local dev DB blocks on drizzle's rename-vs-create prompt, because `push: true` wants to add the column that migration 20260730_170909 adds properly. The int tests cover the behaviour against a schema built from the current config. Refs #603 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The behaviour change is only discoverable if it's written down — an existing client whose `GET /api/events` result set shrinks needs to find out why from /api/docs, not from the source. - OpenAPI: the geojson description now states the exclusion, the definition of finished, the local-midnight rule, that `where` cannot override it there, and where the opt-out *does* work; register gains its 409. Guarded by tests/unit/openapi-custom-endpoints.spec.ts. - `.claude/rules/endpoints.md`: a passthrough may narrow the caller's `where` — filter inside the read (so totalDocs/pagination stay consistent), and state the opt-out convention (feeds unconditional, list reads yield to an explicit `where`). Plus the two Payload behaviours that bite: `find`/`findByID` both arrive as `operation: 'read'`, and trusted forwarded reads must be exempt. - `.claude/rules/api-clients.md`: per-read contract table + `isTrustedReq`. - `.claude/rules/collections.md`: `lastDate` alongside the virtuals, the read-termination-off-`options()` and partial-update traps, refreshed key files (also fixes a stale `scheduleField.ts` → `scheduleFields.ts` filename). - `.claude/docs/architecture.md`: adds the missing `ExpireEvents` section. - `tests/COVERAGE.md`: events row, a new ExpireEvents scheduled-job row, and the shouldFinish/notFinishedWhere agreement subject. - `.claude/rules/scripts.md`: the backfill script. Two claims in the ticket turned out not to hold, so nothing was changed for them: the `finished` copy in VerificationStageField/timeline.ts already said "no longer publicly listed", and architecture.md had no ExpireEvents section to correct. The genuinely stale copy was the admin notice telling managers to "republish" a finished event, and a comment in lifecycle/verify.ts. Refs #603 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- `lastOccurrenceEnd` calls `rule.options()` once instead of twice. - Drops the dead `EventScheduleInput` re-exports from scheduleHooks and icsBuilder — every consumer imports it from `@/types/schedule`. (The `ScheduleSubFields` re-export stays; SendSessionReminders and AppCards use it.) - Inlines the single-use `LAST_DATE_PATH` constant. Refs #603 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Found by measuring while triaging a review note, not by reading. The claim under test was "the backfill deletes historical exclusion records"; it doesn't — `cleanupExpiredExclusions` strips a >1-day-past exclusion on *every* write, including the original create, so such a row never had one to lose. What is real is subtler: `computeLastDate` runs against the incoming patch, so a create can store a `lastDate` that reflects an exclusion the same write is removing. The stored value is then not reproducible from the stored sub-fields (tail excluded at create → the earlier date; a recompute → the later one), and the first backfill pass rewrites it. Behaviourally inert — a stripped exclusion is by definition past, so both candidates are behind `now` and the event is finished either way — but it explains why a first pass can move a `lastDate` that looked fine, which would otherwise read as a bug. Refs #603 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🚅 Deployed to the SahajCloud-pr-604 environment in sahajcloud
|
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-604
July 30, 2026 20:44
Destroyed
`event-verification.int.spec.ts` asserted `_status: 'draft'` after the sweep marks an event finished — the exact contract #603 inverts. Now asserts `published` plus non-null webPath/webUrl, which is the point of the change: the event's Atlas page has to keep resolving for a late arrival. Caught by CI, not locally: my targeted integration set covered events, events-geojson, event-registration, expire-events and the backfill, but not event-verification, which also drives the ExpireEvents job. Refs #603 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-604
July 30, 2026 21:09
Destroyed
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-604
August 1, 2026 16:13
Destroyed
Ardnived
added a commit
that referenced
this pull request
Aug 3, 2026
Reconciles #599 (registration gating + fullness) with main's #603/#604 finished-event overhaul, which landed the same shared surface differently: - shouldFinish: took main's lastDate-based implementation (src/lib/schedule/scheduleStatus.ts) over my upcomingDates-based one; the gate's event_ended check + gating.ts now use it (typed via EventScheduleInput), and pass `now` through so the gate is evaluated at a single instant. - Finished-event contract: main keeps finished events *published* (off the feeds via excludeFinishedEvents / notFinishedWhere), the opposite of my original "finished ⇒ draft ⇒ 404" note. Flipped the Item-3 docs (Events.ts JSDoc, architecture.md) to match, and removed main's minimal stopgap ended-check in registerForEvent — my full gate (with a machine-readable code) supersedes it, as main's own comment anticipated. - Events hooks: combined main's excludeFinishedEvents (beforeOperation) with my syncEventFullness (beforeChange). - OpenAPI + tests: kept my 4-code register 409 doc/test and main's geojson finished-exclusion doc/test; refreshed the gating unit fixtures for the lastDate model. - Migration: dropped my 0722 registrations_full migration and regenerated it on top of main's schedule_last_date (0730) so the snapshot chain stays cumulative → 20260803_221051_registrations_full_flag. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Ardnived
added a commit
that referenced
this pull request
Nov 2, 2026
…1061) Backfills (owner confirmed both are done): delete scripts/backfill-region-breadcrumb-urls.ts (#640) and scripts/backfill-schedule-last-date.ts (#604), the src/lib routines only they used, their int specs, and the doc rows pointing at them. New writes fill breadcrumbs[].url and schedule.lastDate on their own, and region-canonical-url / events specs cover that live behaviour. seeds/tests harness: test-storyblok.sh and test-meditations.sh run importers that have had no CLI entry point since #156, so each "test" exited 0 having done nothing; check-db-stats.ts queried the music collections renamed in #180. Delete them with setup-test-db.ts and test-payload.config.ts (used only by them), rewrite the folder guide around the spec that stays, and drop the third buildConfig site from the systemEntities / access.md / postgresTestPool comments. Smaller: meditation-duration's "backfill migration logic" block re-implemented a migration deleted in #308 and called none of our code; seed-pagination's PaginationOptions block only read back an object literal; lemonfox-client's comment named transcribe.ts's old path. Co-authored-by: Claude Opus 5.5 <[email protected]>
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
schedule.lastDatecolumn (end of the final occurrence's local day) replaces the virtualupcomingDatescheck, retiring the 6-monthMAX_MONTHS_AHEADfalse positive.POST /api/events/{id}/registernow refuses an event that has ended (409) — the published-only access filter no longer catches it.Changes
src/fields/scheduleFields.ts,src/lib/schedule/scheduleHooks.ts— storedlastDatesub-field + the purelastOccurrenceEndit projects, and thecomputeLastDatebeforeChangehook.src/lib/schedule/scheduleStatus.ts(new) —shouldFinish, moved out of the ExpireEvents stage machine now that the feeds and registration share it.src/collections/Events/lifecycle/finished.ts(new) —notFinishedWhere, the SQL counterpart.src/collections/Events/endpoints/geojson.ts— unconditional filter (no opt-out).src/collections/Events/hooks/excludeFinishedEvents.ts(new) — clientfind/countdefault, with an explicit-whereopt-out.src/jobs/ExpireEvents/ExpireEvents.ts—finishEventno longer touches_status;finishedjoinsPUBLISHED_STAGES.src/lib/schedule/backfillLastDate.ts+scripts/backfill-schedule-last-date.ts(new) — recompute the column on existing rows.src/plugins/usage/hooks.ts—isTrustedReq, the companion predicate toasTrustedReq.Migration
src/migrations/20260730_170909_schedule_last_date.tsschedule_last_datetimestamp + btree index toevents,app_cardsand both version tables (scheduleFieldsis shared with AppCards). No data transformed.downdrops the indexes and columns.shouldFinishcomputes from the schedule sub-fields rather than reading the column, so the nightly sweep is correct from the moment this ships whether or not the backfill has run. A NULL column reads as "never ends", so an un-backfilled event stays visible (today's behaviour) rather than disappearing. Any write to a row back-fills it viacomputeLastDate.Test Results
event-verification.int.spec.tsasserted_status: 'draft'after a finish — the contract this PR inverts. My local targeted set covered events / events-geojson / event-registration / expire-events / backfill but not that spec, which also drives the ExpireEvents job.Notes for reviewer
Two mutation checks — the central claims aren't vacuous, verified by flipping the code:
_status: 'draft'infinishEventfails the new expire-events test (expected 'draft' to be 'published').skipVerifyHookfrom the backfill fails its test on a movednextCheckAt— without it, backfilling would silently restart every event's escalation cycle.Three Payload behaviours this had to accommodate (each verified against Payload, each a silent failure otherwise):
findandfindByIDboth reach abeforeOperationhook asoperation: 'read'. Guarding on'find'matched nothing — the list filter silently did nothing until the guard became'read'+'id' in args(the trickfilterMeditationsByLocaleuses).schedule.lastDatepath is queryable; the nested-group form is rejected upstream with "path cannot be queried". So the opt-out check needs no nested branch — a test pins that rejection.reqviaasTrustedReq, so the new list filter was hiding the event from the endpoint's own lookup and collapsing the 409 back into a 404. HenceisTrustedReq: result-shaping hooks honour the trusted flag, security gates deliberately don't (seevalidateClientOriginHook).Deviations from the ticket, all deliberate:
shouldFinishatsrc/lib/schedule/scheduleStatus.tsand anevent_ended(409) gate. I used the same path and export so whichever merges second is a small conflict, and feat(events): registration gating + fullness for atlas redesign #601's gate inherits thelastDatedefinition for free. My guard uses the same 409 + message shape so it collapses intoevaluateRegistrationGatecleanly.finishedcopy inVerificationStageField/timeline.tsalready said "no longer publicly listed", and.claude/docs/architecture.mdhad no ExpireEvents section to correct (I added the missing one). The genuinely stale copy was the admin notice telling managers to "republish" a finished event, plus a comment inlifecycle/verify.ts./api/eventsisn't annotated in OpenAPI. Custom paths merge into the generated spec by shallow spread, so adding a/api/eventsentry would replace the generated operation. The list-read default + opt-out is documented on the geojson operation's description instead (and in.claude/rules/api-clients.md). Annotating the generated path would need a new deep-merge/description seam in the openapi plugin — left out of scope.isPublishedStage/PUBLISHED_STAGEShave no consumers anywhere insrc/ortests/. The ticket asked for the copy fix, so I made it, but they're dead exports worth deleting separately.push: truewants to add the column that this migration adds properly. Covered instead bytests/int/schedule-last-date-backfill.int.spec.tsagainst a schema built from the current config.Reviews:
/simplify(4 fixes applied),/code-reviewat high effort over all 7 identified risk areas (clean),/security-reviewon the endpoint + trust-mechanism changes (clean — confirmedreq.contextis never populated from user input, so a client cannot forge a trusted req). One review note — "the backfill deletes historical exclusion records" — was measured and rejected:cleanupExpiredExclusionsstrips a >1-day-past exclusion on every write including the create, so such a row never had one to lose. Measuring it did surface a genuine wrinkle, now pinned by a test (see the last commit).Drive-by, not fixed:
.claude/rules/scripts.mdlists two scripts that no longer exist (repair-r2-meditation-filenames.ts,create-sample-page.ts). Left alone as unrelated to this ticket.Manual verification
The automated lanes cover the feeds, the sweep and registration. Worth an eyeball:
Open a finished event in the admin — the notice should read "…no longer listed publicly — its page still opens for anyone following an old link", and the stage tracker should show Finished while
_statusstays Published.Atlas manager sidebar counts should be unchanged (they bucket on
verificationStage, not_status).Against a seeded finished event (note
curl -g— theselect[...]brackets are glob metacharacters):Closes #603
🤖 Generated with Claude Code