Skip to content

feat(events): CSV class import as a Payload collection driven by jobs - #912

Merged
sydevs-bot merged 76 commits into
mainfrom
claude/feat-907-event-imports
Oct 20, 2026
Merged

sydevs-bot merged 76 commits into
mainfrom
claude/feat-907-event-imports

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A volunteer uploads a CSV of classes. A background job turns each row into a draft class, filed under the city region its town belongs to. The import's page then lists every row: what it created, or why it was skipped. From there the volunteer publishes the drafts that are right and cleans up the rest.

  • No plugin. It started on @payloadcms/plugin-import-export and replaced it, because we used a thin slice of the plugin and worked around it in several places. See "Why not the plugin" below.
  • No regions created. A town with no city region is skipped, with a link to create the city.
  • No file kept. The CSV is parsed at upload and stored nowhere.

How it works

Starting an import

  • Entry points. An import starts from Import classes in the Events list menu, or from the Import classes button in a region's Events tab, which pre-fills the target region (?targetRegion=<id>).
  • Who. Any active manager who may create classes can start one. The Target Region picker offers only the regions they manage and the regions below them. Payload's own relationship validator enforces the same scope, composed on create only (targetRegion.ts).

The upload (csv/upload.ts)

Refused in the form:

  • a file that is not .csv;
  • UTF-16, or anything that is not UTF-8;
  • an empty or header-only file;
  • unknown, missing or duplicated columns;
  • a value split by an unquoted comma;
  • more than 500 rows.

Then:

  • Cleaned. Blank rows and the template's help row are dropped, and invisible characters are stripped from header cells.
  • Stored. The rows go into a hidden rows field, each with its spreadsheet line. The file is stored nowhere: disableLocalStorage, and no storage adapter.

The job (task.ts, prepare.ts), importEvents on the default queue

  1. Cell checks. One Zod schema per concern checks each row's cells (csv/fieldChecks.ts, csv/schedule.ts). These are the checks no Events field can make: what a spreadsheet does to a cell, which columns an event type owes, and the rules across the schedule columns.
  2. Location. It geocodes the address (Mapbox, four at a time), finds the timezone, and files the row under the matching city region.
  3. Payload's own validation. It builds the class and runs Payload's field validation on it (validate.ts, via beforeChangeTraverseFields). This step is needed because a draft create skips validation. Every Events rule, such as lengths, URLs, emails, select options and schedule ranges, is enforced in Payload's words under the CSV column that held the value.
  4. Duplicates. It checks for duplicates against classes already listed and against earlier rows of the file. Only then does it find or create the row's managerEmail manager, so a skipped row opens no account.
  5. Create. Each class is created as the uploader, with their roles for the import's locale. Each create is its own transaction. The job keeps the exact class id for every created row and Payload's full reason for every refused one: a 403 becomes "you are not allowed to add classes in this row's city", and a duplicate links its twin.
  6. Finish. The job writes the results and the status, clears rows, and emails the uploader.

A geocoder outage or a missing target fails the whole import with that sentence. Drafts already created are kept, so they can still be published or cleaned up.

The result (components/admin/EventImport/)

  • Rows. One line per CSV row, coloured by outcome. Columns:

    • the title, which opens the class in a drawer;
    • the city and schedule;
    • the manager, which opens in a drawer;
    • a status sentence.
  • Notes under a status. "Listed as unverified" appears when a published class has no manager. "Placed at the street, not the building" appears when the address matched only the street.

  • Toolbar:

    • Publish (#) covers the ticked drafts. A draft placed only at the street takes no checkbox.
    • Clean Up (#) deletes every unticked draft.
    • Download Skipped Rows (#) gives back a CSV to fix and upload again, built on the server.

    Publish and Clean Up both confirm first and go through REST as the signed-in manager, in the admin locale.

  • Status. Pending, Review, Completed or Failed. A hook on events moves an import between Review and Completed as its drafts are published or deleted, wherever that happens.

Access

  • Restricted collection. imports is in RESTRICTED_COLLECTIONS.
  • Create. Allowed to an active manager who may create events. atlas-manager gains imports: create, without which the access plugin hides the collection.
  • Read and delete. Admins, and the managers of the target region's subtree.
  • Update. Nobody.

The summary email

Counts of classes created, duplicates and errors, and one Review and publish button that opens the import.

The CSV format

  • Schedule columns use the Events field names and values.
    • recurrenceType takes DAILY, WEEKLY or MONTHLY, or blank for a one-off class.
    • weekdays takes codes from MO,TU,WE,TH,FR,SA,SU.
    • interval and untilDate work as their Events fields do.
  • Strict formats. Dates must be YYYY-MM-DD and times 24-hour HH:MM, so "9:30" and "7pm" are refused.
  • Active classes only. There is no inactive column, and date and startTime are required.
  • Columns tied to Events. Each column names the Events field it writes. The event types, recurrence values and weekdays are read from the collection (csv/columns.ts).
  • Templates. The template and the skipped-rows file are generated from that column list (csv/template.ts). tests/unit/event-import-template.spec.ts holds public/event-import-template.csv to the generated version.

Changes outside the importer

  • The duplicate rule (collections/Events/hooks/refuseDuplicateClass.ts). A beforeValidate hook on Events refuses a class that repeats another in the same region. The key is type, recurrence, weekdays, local start time, place, and date or cadence. It runs for drafts and updates too.
    • Existing twin pairs in production will refuse edits until someone reconciles them. That is the accepted decision.
    • It selects only the stored columns it compares. Selecting the whole schedule group computed the virtual icalRule and upcomingDates for every class in the region on every save, which made a 500-row import take over ten minutes.
  • Regions. The Events tab's heading carries the Import classes button (ImportClassesLabel).
  • Schedule fields. scheduleFields.ts exports WEEKDAY_OPTIONS and RECURRENCE_OPTIONS.
  • Access. resolveOwnedRegionIds is exported from @/plugins/access.

Why not the plugin

It gave us an upload collection, a job and a create loop. Here is what it cost:

  • Shared run state. Its hooks receive no import document, so we wrapped its task, carried the run on the shared request, and allowed one import at a time.
  • A parse to undo. It turned postcodes like 10999 into numbers.
  • Lost error details. It reduced every failed row to one line.
  • No created ids. It returned no class ids, so rows were matched to classes by creation order.
  • A status write to hold back. It wrote a status before our results were stored.
  • Fields to strip. It added fields we had to remove or hide, and an unused exports collection.
  • A public file. It needed the CSV at a public R2 URL.

The replacement is about 150 lines shorter, keeps exact ids and full errors, and stores no file.

Email previews

The "ready to review" email, sent through the real sendImportSummary by scripts/preview-event-import-emails.ts. Mailpit keeps them for 7 days, and MAILPIT_UI_AUTH opens them.

Scenario Preview
Every row became a draft view
Drafts, duplicates and errors view
One class (singular wording) view
Nothing created (asks for attention instead) view

Contract impact

src/payload-types.ts changes, all additive for consumers:

  • Event.importBatch, which is number | Import;
  • the new Import, EventImportResults and EventImportRows types;
  • the importEvents and sweepEventImports task types.

WeMeditateWeb and SahajAtlasWeb re-sync the file after merge, and neither reads the new types.

Migration

Seven migrations come from this branch, applied in order. The first three belong to the first design, the next three take its tables down to the current shape, and the last only heals the snapshot. The full chain applied cleanly to an empty database.

Migration What it does
20261010_013059_event_imports, 20261010_025807_event_import_jobs, 20261017_161838_event_import_analyze_slug The first design's event_imports collection and job slugs
20261019_182311_import_plugin Replaces event_imports with imports, adds events.import_batch_id, and swaps the job slugs
20261020_002253_event_import_results Adds results and error, makes the target and uploader nullable, and sets the status values
20261020_172522_event_import_own_job Drops the plugin's columns and the exports tables, adds rows, and swaps the job slugs to importEvents. It is hand-edited to delete jobs queued under the old slugs before the enum recast
20261020_181806_merge_main_snapshot Snapshot only, after merging main (below)

Merged with main, and the snapshot healed. Main's 20261017_* lesson migrations sort between this branch's migrations, so the newest snapshot lacked their schema. 20261020_181806_merge_main_snapshot has no DDL and only carries the merged snapshot. A probe migrate:create now writes nothing.

Both orders were checked on scratch databases:

  • The full chain from empty. It applied cleanly.
  • Production's order. Main's chain went on first, with queued transcribeMeditation and cleanupJobs jobs, then this branch's migrations. They applied cleanly and the jobs survived the enum recasts.

Test results

Lane Result
pnpm lint, typecheck, typecheck:tests pass
pnpm test:unit 2,772 pass, after merging main
event-imports.int.spec.ts 27 pass in about 45 s
role-based-access, collections-smoke, payload-system-access, event-verification, events pass

event-imports.int.spec.ts covers:

  • each refusal at upload;
  • region-scoped read;
  • per-row permission refusals;
  • every outcome: created, duplicate of a listed class, duplicate of an earlier row, missing city, bad cell;
  • Payload's own field refusals under their columns, which pins beforeChangeTraverseFields;
  • a geocoder outage;
  • a 500-row file;
  • the retention sweep.

On the dev server with real Mapbox lookups, a mixed 500-row UK file finished in about 4 minutes: 455 created, 25 duplicates, 20 errors. The result page renders all 500 rows in about 4.7 s and is about 36,000 px tall. Pagination or status filters for that page are proposed as a follow-up.

Manual verification

  1. As an atlas-manager, open a region you manage, open its Events tab, and click Import classes. The target region should be pre-filled, and the picker should offer only your subtree.
  2. Upload public/event-import-template.csv with its example row edited into a real class, plus one row with startTime 7pm and one in a town with no city region. The page should wait, then list three rows: one created, one "must be HH:MM", and one "no city region … create it first", which opens a region drawer.
  3. Tick the draft and click Publish (1). Status should move to Completed once no draft is left.
  4. Click Download Skipped Rows (2) and re-upload the file after fixing it.
  5. Check Mailpit for the summary email: counts, and one link to the import.

Closes #907

🤖 Generated with Claude Code

…, and the migration

Phase 1 of #907. `event-imports` is an upload collection: the uploaded CSV is
the document, Payload's own create form is the upload UI, and the storage
plugin puts the file in R2. `parseUpload` turns the file into `rows` and sets
`status: 'resolving'`; `stampManager` writes the uploader onto `manager`, which
is this collection's whole access story — `getDocManagerFields` recognises that
name, so the uploader reads and updates their own batches with no
collection-level `access` block and no collection-wide `read` grant.
`validateTargetRegion` asks the access plugin whether the caller manages the
target rather than deriving a second answer to it.

The pure domain core is cherry-picked from `claude/feat-828-event-import`
unchanged, with its unit specs: `csv/`, `resolve/`, `propose/`, `commit/`, and
the `src/lib/` additions each step reads. Three substitutions the ticket calls
for land with it — `p-retry` for the geocoder's hand-rolled backoff loop,
`csv-stringify` for the template's own RFC 4180 quoting, and `newListingAdoption`
for the restated unverified-event defaults.

`batchRequest.ts` is not lifted: its endpoint half (`failure`, `batchIdOf`,
the ownership refusals) has no caller once the jobs own the work, and its
region reads do. Those move to `subtree.ts` under their own name.

Two cuts to the CSV's schedule columns, per the ticket:

* `date` is required for every `scheduleType` but `inactive`. Deriving "the
  next matching weekday" made one CSV build a different first occurrence on
  each day it was uploaded, which no reviewer could see on the row.
* No ordinal months. `monthWeek` is gone from the columns and the template, and
  `monthly` recurs on `date`'s day of the month. The CMS still stores "the 2nd
  Tuesday"; reaching it took a column, a second set of refusals and a
  cross-check, for a shape no surveyed region's classes use.

Also dropped with their reason gone: the overwrite branch (an import never
modifies an existing class, so `eventOverwriteData`, `committed.action` and the
`overwritten` tally go), the invitation opt-in (`queueOnManagerField` already
queues one when `Events.manager` is set), and the chunking constants.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FEitCNK3iByzH8Tckuc2h4
…d the review's fixes

`targetRegion` declared a `filterOptions` and a custom `validate`, which is the
combination that enforces nothing: `validateFilterOptions` — the half that
applies the narrowing at save time — lives inside Payload's own `relationship`
validator, and `sanitize.js` installs that only when the field supplies no
`validate` of its own. So the picker was narrowed and an API `PATCH` naming any
region id was accepted.

`hooks/targetRegion.ts` now holds both halves together and composes the standard
validator, so the refusal comes from the one mechanism this repo decides region
ownership with (`ownedRegionFilterOptions`) rather than a second answer derived
from `userManagesDocument`. That also narrows the picker to the caller's own
subtree, drops a deep import of the access plugin's internals, and stops paying
two `regions` reads on every later save — `access.update: () => false` already
refuses a re-point, and Payload back-fills the stored value before `validate`
runs, so the validator is create-only.

`src/collections/AGENTS.md` records the trap beside the `maxLength` version of
it, which is the same shape one step less costly.

The rest, from the four-lens review:

* The template shipped an example row its own parser refused — requiring `date`
  left the example's blank. `tests/unit/event-import-template.spec.ts` pins the
  whole template through `parseImportCsv` and the schedule mapper, and goes red
  with the blank put back.
* `parseUpload` wrote `progress: null`, and Payload's field pass descends into a
  group with the group as `siblingData` — so every create threw
  `Cannot read properties of null` with nothing naming the field.
* The generated migration's `down` dropped a constraint its own
  `DROP TABLE … CASCADE` had already removed, which aborts the whole batch
  rollback (`tests/unit/migration-down-cascade.spec.ts`, #682).
* `isWeekNumber` lost its only caller with the `monthWeek` column; the
  `date is required` guard moves into `buildFor` once instead of three times;
  `summary.ts` calls `duplicateAction` rather than restating it; `isCommittable`
  reads positively now the choice is two-way.
* `commit/scope.ts`'s ⚠ cited `refuseUnownedTarget`, a symbol this branch drops.
* `resolve/duplicates.ts` still offered an overwrite the schema refuses.
* `subtree.ts` → `regionReads.ts`: four of its six exports are not subtree-scoped,
  and the file's own header already said what it is.
* `time.ts`'s claim that both start/end comparisons were consolidated is true now
  that `registrationDetails.ts` reads `minutesOfDay` instead of its own copy;
  `HHMM_PATTERN` and `GapPolicy` stop being exported, since publishing the
  grammar invites the fourth copy of it.

`tests/int/event-imports.int.spec.ts` covers the upload, the stamp, the target's
two refusals and the `manager`-field grant — including that a region's *other*
manager is refused outright rather than handed an empty list, which phase 4's
`join` has to reckon with.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FEitCNK3iByzH8Tckuc2h4
… the public bucket

`storagePlugin` passed `disablePayloadAccessControl: true` for every collection
in `STORAGE_BACKENDS`, and adding `event-imports` to that map inherited it. The
flag is what stops `cloudStoragePlugin` mounting a handler on Payload's own
`/api/<slug>/file/<filename>` route, so R2 became the only way to the bytes —
and `storagePlugin` passes no prefix, so objects sit flat at the root of the
bucket `assets.sydevelopers.com` fronts. An import CSV holds contact names,
phone numbers and email addresses for every class in it, which is precisely
what naming the collection in `RESTRICTED_COLLECTIONS` exists to withhold: the
row was closed and the file was not.

`PAYLOAD_SERVED_COLLECTIONS` is the opt-out. For a member, Payload serves the
file and `checkFileAccess` runs the collection's own `read` — including the
`Where` the document-manager grant returns, applied as a constraint on the
document behind the filename, so the batch's `manager` decides who may fetch
the CSV. The document never advertised the public URL (the R2 adapter defines
no `generateURL`), so what this closes is reachability by anyone holding or
guessing the filename, not a published link.

**That fix was inert on its own.** `r2NativeAdapter`'s `staticHandler`
composed `<collection>/<filename>` while `handleUpload` and `handleDelete`
composed the factory's own `prefix` — none, today — so the gated route fetched
a key nothing had ever written and answered 404 for every file. It went
unnoticed because no collection had ever mounted that handler; the first one
to want a gated download is the first that this being wrong would break, and
the break would send everyone back to the public URL.

Both are pinned, and both specs were checked by putting the defect back:

* `tests/unit/storage-payload-served.spec.ts` reads the module's own table,
  because the integration lane **cannot** cover the flag — `storagePlugin`
  returns before `cloudStoragePlugin` whenever a Cloudflare credential is
  missing, which is every local and CI run. Emptying the set leaves the
  integration spec green and turns this one red.
* `tests/unit/r2-adapter-keys.spec.ts` asserts the three handlers agree on one
  key, with and without a prefix, rather than against a literal.
* `tests/int/event-imports.int.spec.ts` covers the half no pure test can state:
  that `checkFileAccess` applies the doc-manager `Where` to the document behind
  the filename — anonymous 403, another manager 403, the holder 200. Its
  docblock says what it does not cover.
* The same spec now refuses a published `sahaj-atlas-client` key reading the
  collection, read back through `overrideAccess: false` rather than asserted
  from `hasPermission` (#821, #822).

`docs/rules/storage.md` carries all three facts, including that this changes
which URL is handed out and not whether the object is private — the bytes stay
in the shared bucket behind six base36 characters of `Math.random()`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FEitCNK3iByzH8Tckuc2h4
@railway-app

railway-app Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-912 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Oct 20, 2026 at 11:44 pm UTC
1 service not affected by this PR
  • mailpit

…summary email

Phase 2 of #907. The browser no longer drives any of this work: a batch's
stage moves through one `beforeChange` hook, and the geocoding and the
writes are Payload jobs on their own `imports` queue.

`transitionStatus` is the gate `status` never had. The field carries only
`admin.readOnly`, and the uploader holds document-level `update` through the
`manager` field — so before this a `PATCH` could name any status and rewrite
`rows` within the Ajv schema. Inert while nothing read them; the moment a job
dispatches on `status` and trusts `rows[].resolved`, it is a way to file a
class under any region and claim another import's exactly-once key. The hook
owns the transition table and the reviewer's own delta: in `proposedRegions`
only a rename or a mapping, in `rows` only a duplicate's skip-or-import.

`ResolveEventImport` is #874's resolve and propose endpoints with the
chunking, the lease and the time budget gone. Geocoding runs four at a time
(`p-map`); the duplicate match runs after it, sequentially, so a file's
answers no longer depend on which request returned first — the chunked
version keyed them on chunk boundaries.

`CommitEventImport` is #874's commit and finish without the chunking or the
overwrite branch. One worker per job row replaces the lease
(`enableConcurrencyControl`), `importKey` is checked before every create so a
retry adopts rather than repeats, and the deferred Cloudflare purge is paid
back once per tag at the end.

`SweepEventImports` deletes a discarded batch and anything untouched for 30
days, whatever its status: what sets the window is the CSV's contact details,
and a finished batch keeps them no more legitimately than a failed one.

One email replaces #874's two, to the uploader with the admins copied and no
attachment — the batch now survives the commit until the sweep, so the
skipped rows are a download on its own page. `cc` had to be added to the
Resend adapter's hand-written field mapping, where an unmapped field is
dropped in silence.

`runScreeningQueueAfterCommit` is generalised to
`@/lib/jobs/runQueueAfterCommit` and becomes a one-line wrapper.

A second migration rather than a reshaped first: both task-slug enums need
the three new values, and phase 1's migration has already applied on the PR
preview, where regenerating it crash-loops the boot (#633).

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0129s1BT4vyN8fW34rzijJ3a
…on gate

Each was reachable through `PATCH /api/event-imports/:id` by the batch's own
uploader, who holds document-level `update`.

- **A new file onto a batch a job was already working was accepted and
  silently discarded.** `parseUpload` asks for `resolving`, so a re-upload
  during a resolve is no status change at all: the table waved it through,
  `enqueueImportJobs` queued nothing because nothing was entered, and the job
  already running wrote its own stale rows back over the corrected ones. A
  file is now accepted only onto a batch in review or failed.
- **A worker killed mid-run left the batch unreachable forever.** Payload
  claims a job row with `processing: true` and never resets it, so nothing
  re-ran it, and `resolving` and `committing` had no outgoing transition at
  all — no discard, no retry, no re-upload. `discarded` is now reachable from
  both, and each job re-reads the status before its terminal write, so a
  discard that lands mid-run wins rather than being overwritten.
- **`proposedRegions: null` crashed the hook** instead of being refused,
  since the comparison dereferenced the absent side. Clearing the tree is not
  an edit the review offers.
- **One line submitted twice dropped another without saying so.** The count
  matched and every submitted line existed, so each per-row check passed
  while the missing line left the document — a class dropped from the import,
  absent from the report and from the email.

Two more, neither reachable by a caller:

- The resolve job stored a reason only for a geocoder outage, so any other
  fault ended as `failed` with an empty `error` — the one state `jobContext`
  exists to prevent. Every fault now stores a message before it rethrows.
- The summary email summed `duplicates + errors` to decide whether to show
  the skipped section, and a row can carry both. The sum is gone; the two
  counts were already shown separately.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0129s1BT4vyN8fW34rzijJ3a
… mapping

Three surfaces this phase makes stale rather than merely adds to:

- `docs/rules/email.md`'s "Currently mapped" list is what stops the next
  template losing a field to the Resend adapter's hand-written mapping, so
  `cc` belongs in it the same commit that adds it.
- `docs/architecture.md`'s scheduled-jobs list is where the queues are
  described, including the one hazard the queue cannot state itself: a killed
  worker's job row stays claimed, which is why `discarded` is reachable from
  a status a job holds.
- `src/AGENTS.md` enumerates every folder under `src/lib/`, and `jobs/` is a
  new one.

`src/collections/AGENTS.md`, `docs/rules/admin-ui.md` and
`docs/rules/access.md` are phase 5's, and nothing in this phase makes them
wrong yet.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0129s1BT4vyN8fW34rzijJ3a
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-912 October 10, 2026 03:18 Destroyed
…not sum

The template has no Mailpit preview script — the ticket drops #874's — so a
render spec is the only thing that sees it at all. Four cases: the uploader
and both links, the twenty-line cap and the count beyond it, the section
appearing for errors alone, and nothing at all when nothing was skipped.

The third is the one worth keeping. A row can carry both a duplicate match
and an error, so a summed "rows skipped" over-counts the lines; restoring the
sum turns that case red.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0129s1BT4vyN8fW34rzijJ3a
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-912 October 10, 2026 03:22 Destroyed
…tion

`event-imports` needs six stage-dependent buttons, and Meditations already
carried two bespoke components for the same shape — a create screen that
offers "Next step" and hides Publish. `WorkflowActions` takes the stages as
data in `clientProps`, so a staged collection declares its buttons instead of
shipping another component.

Three things the shape had to answer:

- **`clientProps`, not `admin.custom`.** An edit-view slot is not a field, so
  there is no `field.admin.custom` to read, and a collection's top-level
  `custom` never reaches the client — `createClientCollectionConfig` strips
  it. `renderDocumentSlots` passes a `RawPayloadComponent`'s own `clientProps`
  through, which is why the declarations are objects rather than path strings.
- **An empty stage array is not a missing one.** `resolving: []` is a running
  batch with no action; a stage the declaration never names falls through to
  `fallback`. Collapsing the two would offer Payload's own Save at `resolving`,
  a transition `transitionStatus` refuses.
- **An unsaved document is `__create__` whatever the status field holds.**
  `event-imports` defaults `status` to `resolving`, the stage the resolve job
  owns, so keying on the value alone gives the create form a running batch's
  buttons.

The contract lives in `stages.ts` rather than beside the component: every
export of a `'use client'` module reaches a server module as a client
reference, so a collection config reading `CREATE_STAGE` off the component
would key its map on an object. Same split as `UserSubmissions/statuses.ts`.

`event-imports` also offers Discard while a job holds the batch, which the
ticket's own declaration left empty. Payload never releases a job row it
claimed, so without it a worker killed mid-run leaves a batch no transition
can move — the hole phase 2 widened `ALLOWED` to close, unreachable from the
only screen an admin would look at.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WbMmZNiaaXmuUhYXVDdkNW
…button rules

`/code-review high` over the phase's own commit. The first is the one that
mattered: the Discard I added to `resolving` and `committing` could not work.

**A move out of a stage with no review now keeps the stored rows.** The admin
form posts the whole document, so Discard carries the `rows` the browser
loaded — and `transitionStatus` refuses an edit to a batch that is not in
review. A batch is discarded from `resolving` precisely when a worker died
mid-run, and by then the resolve job has written answers the open page never
saw, so the save was refused over rows the caller never touched. The one
button that rescues a stranded batch was itself stranded. Retry out of
`failed` shares the mechanism.

Both directions are pinned: a `PATCH` that moves nothing still has its edits
checked, which is what refuses an edit to a finished batch. Dropping either
half of the condition turns one of the two new cases red.

**The declaration and the table are now checked, not asserted.** The slot's
comment claimed the two had to agree while nothing made it so. The
integration spec reads the real `clientProps.stages` against the exported
`ALLOWED` in both directions — a button offering a refused target, and a
target the table allows that no button offers. `resolving` is exempt in the
second: re-resolving needs a corrected file, which no button can carry.

Two smaller ones, both rules Payload's own document-control buttons apply:

- **Nothing submits mid-upload.** `uploadStatus === 'uploading'` was dropped
  from the disabled condition; on this collection the document *is* its file,
  so a click during a paste-from-URL fetch posted the batch without the CSV.
- **An empty stage renders nothing, not an empty row.** `[]` is truthy, so
  Meditations' create-stage Publish slot rendered a childless flex container
  where `UpdateOnlyPublishButton` returned `null` — a stray gap in
  `.doc-controls__controls`, invisible to a count of buttons. The spec now
  asserts the markup.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WbMmZNiaaXmuUhYXVDdkNW
…py fix rests on

`/simplify` across reuse, simplification, efficiency and altitude.

**`WorkflowActionsProps` is generic over the stage vocabulary.** It took a bare
`Record<string, …>`, so `commiting:` compiled and silently rendered the
fallback. Each declaration now names its own stages —
`WorkflowActionsProps<ImportStage>`, `<typeof CREATE_STAGE>` — and a misspelled
key is a type error. Checked by misspelling one.

**The invariant behind the stale-copy carve-out is now pinned.** That fix keeps
the stored rows for a move out of a stage with no review, and refuses an edit to
such a stage otherwise — so it holds only while every button outside `review` is
a move. A plain "Save changes" on `failed` would post the browser's rows as an
edit and be refused: the stranded-batch bug again, in the one path that rescues
it. The integration spec now requires a `status` override on every action
outside `review`, and a zero-override button there turns it red.

**One notion of create-vs-update, spelled as Payload spells it.** `useOperation()`
replaces `Boolean(id)`; Payload derives that provider from the id
(`views/Edit/index.js:163`), so it is the same fact, and the disabled rule now
matches `SaveButton`'s own line rather than restating it differently. An absent
provider reads as the create stage, pinned by its own case.

**`UPDATE_STAGE` is gone.** Nothing keyed a `stages` map on it, so returning it
was always a lookup miss — behaviourally identical to naming no stage, which
already renders the fallback. Two reviewers found it independently.

Declined, with reasons: `confirm` stays `window.confirm` rather than
`ConfirmationModal` (the reviewer's call — see the PR body); `overrides` stays
required, because optional would give `{}` and omitted two different meanings;
`'save'` stays in `FALLBACKS`, completing Payload's three; `SubmissionActions`'
duplicate shell is #909's.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WbMmZNiaaXmuUhYXVDdkNW
Phase 4 of #907. The batch's own edit form becomes the review screen: four
Payload Field components, one per field they edit, and an Import tab on
Regions that is the only way a volunteer reaches a batch at all.

`RowsTable` and `RegionTree` write form state, so the edits they offer are
exactly the deltas `hooks/reviewerEdits.ts` accepts — a duplicate's
skip-or-import, and a node's rename or mapping. `RegionTree` composes
`applyTreeEdits`, the same function the write side composes, rather than
patching the one node: a rename reassigns slugs across siblings and a mapping
can prune an empty state, so a patch would store a tree the commit walks past.

`RegionTreeField` is a server component because the mappable regions are a
tree read, narrowed to the levels the proposal holds. #874 asked the same
question from an endpoint the browser called on every edit.

`ImportProgress` is what makes the flow work without a reload: the resolve job
writes from a worker, so an open form holds the document as it was at the
create. It polls two columns and refreshes the form once the status settles.

The template is a checked-in file rather than an endpoint, with a drift case
that prints what to paste — so a renamed column cannot ship a template the
parser refuses, which is the whole reason `columns.ts` is one constant.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LFS2VJixNGs1VPYPeSA9MM
…s join

The components are markup over these: which status a line reads as, which
lines a reviewer has to look at, what the progress poll asks for, and the two
files the batch page hands back. Each case was checked by reintroducing the
defect it names — nine of them, since three specs written for this feature's
earlier phases passed against the very bugs they were for.

The join is read through `Regions.imports`, not by querying `event-imports`:
`on: 'targetRegion'` is the half that decides whose batches a region shows, and
a direct query would pass with the join pointed at any field at all. Checked by
pointing it at `manager`.

`src/payload-types.ts` is regenerated. The only new content is that join and
its result shape; the rest of the diff is the generator hoisting `EventImport`
above the collections that now reference it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LFS2VJixNGs1VPYPeSA9MM
… and a wrong row

Phase 5 of #907.

`docs/rules/admin-ui.md` gains the two patterns this ticket established: a
`tabs` tab holding a `join` as the entire entry point to an admin-hidden
collection, and `WorkflowActions`' per-stage button declaration. The join-tab
section states the three things that decide whether the native "Add new" is
right, since `Regions` now has one tab where it is and three where it is not.

It also loses a row that was wrong. `ProgressBar` sat in the built-ins table
under Loading, but it is the route-transition bar: no props, value from
`RouteTransitionProvider`. Anyone reaching for it to show a job's progress
finds that out by writing the component first.

`src/collections/AGENTS.md` gains the rule behind `reviewerEdits.ts`: a JSON
column a person edits cannot be protected by field access, and the three
reasons the comparing hook has the shape it has. Each of the three was a hole
this feature shipped and closed.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LFS2VJixNGs1VPYPeSA9MM
`/simplify` across reuse, simplification, efficiency and altitude. Four
findings mattered.

**The review table was spelling the refusals itself.** `commit/rows.ts`'
`skipReasons` exists for exactly this caller — its ⚠ says the review and the
report are read minutes apart by the same person, so a second spelling reads as
the commit having found a different fault from the one they approved skipping.
The Notes column now goes through it, and `duplicateMatchNote` carries the one
wording of what a row repeats for both sides. `rowModel.ts` keeps only the
table's own vocabulary; `CommitRow`, `duplicateAction` and `tallyTree` replace
the second names this phase had given them. `tallyTree` had no consumer at all
— it was exported for this surface.

**`skipReasons` moved from `commit/summary.ts` to `commit/rows.ts`**, because
`RowsTable` is a client component and `summary.ts` reaches
`@/lib/utilities/validationFailure`, which value-imports `ValidationError` from
`payload`. Pulling the server package into an admin chunk is the deploy-only
failure `src/AGENTS.md` records; `rows.ts` imports types only.

**`applyTreeEdits` is imported on the click, not at the top.** It reaches
`propose/slugs.ts`, the only importer of `any-ascii` — about 214 KiB gzipped of
transliteration tables, measured, which sat in this edit view's eager chunk for
a button pressed two or three times per batch. `csv-stringify`'s browser build
(18 KiB gz) moves off the eager path the same way.

**`RegionTreeField` reads nothing outside `review`.** Its two reads feed only
the rename and map controls, which the client renders only while the batch is
the reviewer's — and a batch spends the rest of its life finished, so a country's
every city was going into the flight payload of a page with no control on it.
What remains runs as one `Promise.all`, and the target is read for its name
rather than through `loadTarget`, which walks the ancestor chain to resolve a
scope this caller discards.

**The Import tab moved to `src/collections/Regions/importTab.ts`.** A field of
`Regions.tabs` has one consumer, so by `src/AGENTS.md`'s organization rules it
is Regions' own code — declaring it under `EventImports/` made the repo's only
collection-to-collection import, the edge rule 4 names. The shared thing is one
pure predicate, in the direction the repo allows.

Smaller: `FieldShell` replaces three copies of the field wrapper, one of which
hard-coded `read-only` and one of which labelled a different path; one
`useBatchReadOnly` hook instead of the `'review'` literal in two components;
`ImportProgress` polls only a batch a job holds and uses `clearRouteCache`
rather than reaching past it to `router.refresh()`; it sits on the `progress`
group rather than beside a hidden copy of it; the progress URL is built with
`qs-esm`, as `ThumbnailCell` does; one `UTF8_BOM` in `csv/columns.ts`;
`SelectInput` for the tree's map control; a label where a read-only
react-select was being mounted per matched row; `rowStatus` once per row.

Declined: pushing the slug namespace to the server (it changes the write gate —
see the PR body), and generating the CSV template rather than committing it
(#907 decided the static file and its drift test).

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LFS2VJixNGs1VPYPeSA9MM
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-912 October 10, 2026 05:47 Destroyed
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 10, 2026
@sydevs-bot

sydevs-bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running
CI fix 2

recent dispatches
  • 23:20Z resolve-conflicts · attempt 1 · session · done
  • 23:20Z resolve-conflicts · attempt 1 · session
  • 18:46Z resolve-conflicts · attempt 1 · session · done
  • 18:46Z resolve-conflicts · attempt 1 · session
  • 00:50Z address-review · attempt 1 · session · done

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 Adversarial review

This is #907 built as #907 describes it. The five phases land the Payload-native rebuild the ticket asked for, both documented deviations beat the ticket's own text (stacking the second migration avoids #633; csv/skippedCsv.ts gives the CSV one spelling for both sides), and nothing the ticket ruled out came back — no endpoints, no lease, no RegionImport/.

The contract holds. src/payload-types.ts has zero removed lines, so the contractSync PRs into WeMeditateWeb and SahajAtlasWeb cannot break a consumer.

One aggregate question. components/admin/EventImport/ is ten files and the two jobs are eight, where the ticket named five and three. Each extra is a pure half extracted because no lane mounts a component — individually forced. Would one jsdom spec over RowsTable and RegionTree buy back more than the four pure modules cost to carry?

Findings

  • should-fix — hooks/transitionStatus.ts:191: the sibling-slug pre-flight refuses a commit for a collision the commit recovers from. Answers your open question in the opposite direction — delete the check, do not add a server-side re-slug.
  • should-fix — RegionTree.tsx:187: prints a slug freeSlug may overwrite. Drop it from the label rather than widen the namespace.

What was checked

Read whole: the three hooks, jobContext, regionReads, importTab, the four admin pure modules, ImportProgress, and the storage, email, cache and UserSubmissions edits. Traced the slug path from propose/slugs.ts into commit/regions.ts. Grepped every consumer of skippedCsv, buildImportTemplate, jobContext, regionReads. The imports autoRun is live at jobs/queues.ts:51, not payload.config.ts as the ticket says. Access is covered in event-imports.int.spec.ts, though the ticket named a separate spec.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 10, 2026
The tree printed each node's slug, and that slug is derived in the browser
against a namespace `takenSlugsFor` documents as deliberately incomplete — the
target's subtree plus the proposal, never every `regions` slug. `freeSlug` and
`createRegion` re-slug at the commit, so the value beside a node was a guess
the reviewer could neither control nor rely on. A reviewer decides a node's
name and what it maps onto; the slug is not theirs to read.

The namespace stays as it is: it is what keeps a rename from colliding inside
the proposal, and shipping every region's slug to the browser to pre-empt a
collision the commit already recovers from would be paid for on every load.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KbisH8hYotyFpVrZcnWXvK
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-912 October 10, 2026 06:12 Destroyed
- status is pending, review, completed or failed. A finished import that
  created classes is `review`; a hook on `events` moves it to `completed`
  once none of its classes is a draft, and back to `review` if one becomes
  a draft again — from the result table, a drawer, the Events list or a job
- the plugin's `partial` is gone; the migration (`20261020_002253`,
  replacing the unpushed `230637`) maps stored values by whether drafts
  remain before recasting the enum
- a row the uploader may not write is refused with "you are not allowed to
  add classes in this row's city" instead of Payload's bare refusal
- an integration case narrows the uploader's regions between upload and
  run: the Berlin row is created, the Hamburg row refused, and the import
  is left in review

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Ardnived

Copy link
Copy Markdown
Contributor

Rebuilt on @payloadcms/plugin-import-export — please review again

@sydevs-bot review

⚠ The PR description above describes the previous design and is now stale. This comment is the current account of the branch. Everything below landed in 7c46f602..5b26d02e.

Why

The first version of the importer carried its own collection, a status machine, a region-proposal engine, three jobs, and a review screen that compared JSON edits field by field. The goal for this codebase is as little custom code as possible, leaning on Payload and on established libraries. The importer now runs on Payload's own import plugin. Across src/, excluding generated types and migration snapshots, the rebuild adds 2,967 lines and removes 9,677.

How it works now

  • Upload — imports, the plugin's upload collection, labelled Event Imports. A volunteer starts an import from the plugin's "Import" item on the Events list. Bulk upload and upload-from-URL are off. The file is checked and cleaned before it is stored (src/plugins/eventImport/csv/upload.ts):
    • Refused in the form: files that are not .csv, UTF-16, not UTF-8, empty or header-only. Also unknown, missing or duplicated columns, a value split by an unquoted comma, and more than 500 rows.
    • Cleaned: blank rows and the template's help row are removed, and invisible characters are stripped from header cells.
    • Line numbers: every row keeps its spreadsheet line in a #line column, so results name the line the volunteer sees.
  • Job — the plugin's createCollectionImport task, running one import at a time. A wrapper loads the import document onto req.context, because the plugin's hooks receive only the rows and req. After an import finishes, the queue is kicked again so a waiting import starts. For each row, the before hook (hooks/beforeImport.ts):
    1. Checks the values, then geocodes the address (Mapbox v6, four at a time) and finds the timezone at that point.
    2. Files the row under the city region whose Mapbox place id matches. No regions are created. A town with no city region is skipped with a "create it first" link. A city target refuses rows from other towns.
    3. Builds the class through newEventDefaults as a draft.
    4. Checks for duplicates with the Events rule (findDuplicateClass), both against classes already listed and against earlier rows of the same file.
    5. Only then finds or creates the row's managerEmail manager, so skipped rows open no accounts.
    6. Hands the row to the plugin, which creates it as the uploader with overrideAccess: false.
  • Result (importCollection.ts, finish.ts, results.ts, components/admin/EventImport/) — one line per CSV row, coloured by status:
    • Columns: title (opens a drawer), city and schedule, manager (opens a drawer), and a status sentence. The sentence reads "Created …", "Published …", "Error: …", "Duplicate of …" or "Deleted after the import".
    • Notes under the status: "Listed as unverified because the class has no manager", and "Placed at the street, not the building" for an approximate geocode.
    • Toolbar: Publish (#), Clean Up (#) and Download Skipped Rows (#). Publish covers only the ticked drafts. A draft placed only at the street takes no checkbox, so it can't be bulk-published. Clean Up deletes every unticked draft, including those. Both actions confirm first and go through the REST API as the signed-in manager, in the admin locale.
  • Status — Pending, Review, Completed or Failed.
    • Leaving Pending: only finish.ts can move an import out of Pending, so the page never shows a finished import whose results aren't stored yet.
    • Review and Completed: a hook on events moves the import between them as its drafts are published or deleted, wherever that happens.
    • Failed: the import stopped or created nothing. A failure partway still lists the drafts it had already created.
  • Access — atlas-manager gains imports: create. Without that grant, the access plugin hides the collection and its pages return 404. The collection's own access limits reading and deleting to the uploader and admins; nobody may update. Creating an import requires an active manager who may create events. imports and exports are in RESTRICTED_COLLECTIONS.
  • Duplicates, everywhere — refuseDuplicateClass, a beforeValidate hook on Events, refuses a class that repeats another in the same region. The key is type, recurrence, weekdays, local start time and street. It runs for drafts and updates too. This is a deliberate product decision. Existing twin pairs in production will refuse edits, and expiry and registration writes, until someone reconciles them.
  • Retention — SweepEventImports deletes imports, and their files, 30 days after the last update.

Removed

These went, with their tests:

  • the collection and its status machine
  • the proposal engine (propose/*) and region creation
  • the JSON edit gate (reviewerEdits, transitionStatus)
  • the AnalyzeEventImport and CommitEventImport jobs
  • Events.importKey, cache/defer.ts, lib/eventVerification/adoption.ts and FieldShell
  • subdivision handling in lib/geography
  • most of the geocoder's confidence and subdivision fields
  • the latitude, longitude and timezone CSV columns
  • the any-ascii and @turf/* dependencies

csv-parse is now a runtime dependency.

How it was checked

  • Code review: a /code-review high pass. The approved findings are fixed in dda0affb.
  • Battle tests: CSVs run against the dev server, as an admin and as an atlas-manager. They covered file formats, every value and schedule rule, two simultaneous imports, wrong file types, the size limit, and per-row permission refusals. They confirmed and fixed these bugs:
    • Volunteers got a 404 on Event Imports.
    • Two imports running at once wrote into each other's rows.
    • A blank row swallowed the row after it.
    • A header with an invisible character lost its whole column.
    • .xls files failed with "Invalid JSON format".
    • Empty files finished as "completed".
    • Stray manager accounts were created for skipped rows.
    • A published class with an unpublished edit read as a draft.
  • Integration: tests/int/event-imports.int.spec.ts has 26 cases. One narrows the uploader's regions between upload and run, then checks that the Berlin row is created and the Hamburg row is refused with a reason.
  • Unit: tests/unit/event-import-upload.spec.ts covers the upload checks, and event-import-results.spec.ts covers matching rows to results.
  • Gate: lint, typecheck, typecheck:tests and test:unit (2,781 tests) are green. The Events, verification, expiry, access and smoke integration specs touched by the new hooks pass. Eight older integration specs had fixtures that the duplicate rule now refused; they were given distinct times or streets.

Migrations

  • 20261019_182311_import_plugin was already pushed. It swaps event_imports for the plugin's tables, adds events.import_batch_id, and removes the old job slugs. 8fe3108f fixed a constraint drop in it that ran after CASCADE had already removed the constraint.
  • 20261020_002253_event_import_results is new and edited by hand:
    • adds results and error
    • drops skipped_rows and the plugin's summary_* columns
    • makes target_region_id and manager_id nullable, so a region named by an import can still be deleted
    • replaces the status enum with pending, review, completed and failed. Before recasting, an UPDATE maps stored partial and completed rows by whether the import still has drafts.

Please look hardest at

  1. The run on req.context, and exclusive concurrency (plugins/eventImport/index.ts). Payload gives every job in a run the same req, so is exclusive: true enough? The plugin's own disableJobsQueue sync path is not used.
  2. How Pending is held. A beforeChange hook on imports (IMPORT_FINISH) keeps the status at Pending unless the write carries finish.ts's marker. Can the plugin, or anything else, still move it?
  3. Matching classes to rows by creation order (results.ts). The plugin creates rows one at a time in order. On a count mismatch, no row gets a link, and a warning is logged.
  4. refreshFromEvent runs on every Events afterChange and afterDelete that carries an importBatch. It is skipped inside the import job. Check its cost on bulk writes, and its behaviour inside transactions.
  5. Reads that bypass access. The result field reads classes, versions and managers with overrideAccess: true, because only the uploader and admins can open an import. Links are still checked by each drawer's own access.
  6. Public CSV files. The plugin's job fetches the file by URL, so imports is stored on R2 with a public address. This is accepted, and the 30-day sweep limits the exposure.
  7. The duplicate rule's scope. It is deliberately global and covers updates, but its key ignores one-off dates, monthly day, interval and online URL.

🤖 Generated with Claude Code

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 Adversarial review

Reviewed against the comment that supersedes the body. The approach is right, and not close: 9,677 lines out for 2,967, the status machine, the proposal engine and two jobs with them. Item 1 holds — concurrency with exclusive: true is Payload's own, enforced through the indexed payload_jobs.concurrency_key that enableConcurrencyControl adds, so a second import stays queued rather than sharing a req. Item 2 holds too: IMPORT_FINISH pins status back to pending on any unmarked write, so the plugin's own is swallowed.

The one piece I would hold is refuseDuplicateClass, and it is not the importer's. #907 asked for a CSV import, and beforeImport's findDuplicateClass is what that needs. Beside it the diff adds a collection-wide gate on Events that also refuses update — new behaviour, no ticket, an uncounted cost. How many twin pairs are in production today? Each is a class that cannot be expired, take a registration or record feedback until someone reconciles it: all three go through updateEventBookkeeping, the one write a collection beforeValidate cannot be scoped off. #835 and #842 a third time.

Findings

  • blocker — refuseDuplicateClass.ts:31: refuses update, so a twin pair breaks expiry, fullness and visitor writes.
  • should-fix — refuseDuplicateClass.ts:85: the key drops a one-off's date and a monthly's day: distinct classes collide.
  • consider — eventImport/index.ts:66: the run is never cleared off req.context.

What was checked

Read whole: index.ts, run.ts, finish.ts, results.ts, importCollection.ts, refuseDuplicateClass.ts, updateEventWithoutValidation.ts. Verified concurrency against [email protected]'s types, concurrency_key against the new snapshot, and every updateEventBookkeeping caller. Not examined: items 4-6, the previews.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread src/plugins/eventImport/index.ts Resolved
claude and others added 3 commits October 20, 2026 00:53
`classKey` compared type, region, weekdays, local start time and street, so
two one-off classes at one address on different days read as one class and
the second was refused. The same held for two monthly classes on different
days of the month, two weekly ones at different intervals, and two online
ones behind different join links — the last because the key carried no
place at all for an online class.

The key now carries the one-off's local date, the repeat's cadence, and the
join link where the street stands for an offline class. Every component is
additive, so a pair the old key refused is still refused. Checked by
restoring the old key: six of the nine new cases go red.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HDhu7x5t6ZZoQJ8ZQxi6qS
Payload hands every job in a run the same `req`. The import wrapper put the
run on its context and never took it off, so a later job's Events write took
`refreshFromEvent`'s early return and skipped the status refresh it owes.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HDhu7x5t6ZZoQJ8ZQxi6qS
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Three critic threads: two adopted, one declined.

Adopted

  • The duplicate key — 106cb19. classKey takes the one-off's local date, the repeat's cadence, and the join link your item 7 names. Additive, so nothing the old key refused is now let through. 9 unit cases; the old key reddens 6.
  • The run on req.context — 1bf1739. Cleared in the finally.

Declined

  • The duplicate rule refusing update — the breakage is real and it is your stated call. One req.context flag on updateEventBookkeeping narrows it to editor writes. Say the word.

Base — merged ea0b8ef (#988), no conflicts.

Gate — lint, both typechecks, 2797 unit cases, plus event-verification (36) and event-imports (26).

⚠ The body above still describes the pre-rebuild design. Your comment is the current account.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Ardnived and others added 8 commits October 20, 2026 08:09
…er result table

- Imports are read and deleted by admins and the managers of the target
  region's subtree, not by the uploader alone. An import with no target is
  admin-only.
- The Regions Events tab heading carries an "Import classes" link that opens
  a new import with `?targetRegion=<id>`, which the field's defaultValue reads.
  Hidden on venues and for managers who cannot create imports.
- The result table builds the skipped-rows CSV on the server, shares one
  confirmation modal between Publish and Clean Up, and drops the region
  drawer's open-effect. The skipped-rows CSV moves into csv/template.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…unts-only email

- Schedule columns take the Events names and values: recurrenceType (DAILY,
  WEEKLY, MONTHLY, blank for one-off) and inactive (TRUE) replace
  scheduleType. Dates are YYYY-MM-DD, times 24-hour HH:MM. One Zod schema
  checks the cells and the rules across them; csv/weekdays.ts goes, and the
  weekday and recurrence options come from scheduleFields.
- Each built class runs through Payload's own field validation
  (beforeChangeTraverseFields), since a draft create skips it. That replaces
  the per-column delegation, the URL fix-up and its warnings channel, the
  email hints and the language check. Pinned by an integration case.
- The column spec names the Events field each column writes, and reads the
  eventType, recurrence and weekday values from the collection.
- targetRegion's validator is Payload's relationship validator, composed on
  create only, with Payload's wording.
- The summary email counts what was created, duplicated and refused, and
  links only to the import.
- The duplicate rule selects only the stored columns it compares. Selecting
  the whole schedule group computed its virtual fields for every class in the
  region on every save, so a 500-row import took over ten minutes; it now
  takes about a minute, covered by a 500-row integration case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…page

Selecting the whole schedule group computed its virtual icalRule and
upcomingDates for every row; a 500-row result page spent most of its render
there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The plugin gave us its upload collection, a job and a create loop, and
cost a task wrapper carrying the run on the shared request, one import at
a time, a parse to undo, error details reduced to one line, created ids
matched to rows by order, a status write to hold back, fields to strip,
and an unused `exports` collection.

- `imports` is our own collection. The CSV is parsed at upload into a
  hidden `rows` field, which the job clears when it finishes, and the file
  is stored nowhere: no local storage, and no longer on R2.
- `importEvents` prepares the rows as before, then creates each class as
  the uploader (with their per-locale roles), each in its own transaction.
  It keeps the exact id of each class and Payload's full refusal for each
  failed row.
- Events gains an "Import classes" list menu item in place of the plugin's.
- Classes are imported active only: the `inactive` column is gone, and
  `date` and `startTime` are required columns.
- Migration drops the plugin's columns and `exports` tables, adds `rows`,
  and swaps the job slugs, deleting jobs queued under the old ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…oints at the import page

Co-Authored-By: Claude Opus 5.5 <[email protected]>
main's 20261017_093546 lesson localization sits behind this branch's
newer migrations, so the newest snapshot lacked it and migrate:create
re-emitted its DDL. Every statement already ships in that migration, so
this one keeps only the merged snapshot. A probe migrate:create now writes
nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/emails/EventImportSummaryEmail.tsx Resolved
Comment thread src/plugins/eventImport/csv/schedule.ts Resolved
Comment thread src/plugins/eventImport/csv/template.ts Resolved
Comment thread src/plugins/eventImport/targetRegion.ts Resolved
Three conflicts, all where #995 and #1000 edited lines this branch had
also touched:

- `src/jobs/queues.ts` — keep this branch's `default` queue entry and
  main's `queueTranscription` rename. The transcription comment's
  clearance list named a queue `imports` that this branch no longer
  declares; it is `default`.
- `tests/unit/job-stage-view.spec.ts` — keep the generalised
  `fieldNamed` helper. It still reads `defaultValue`, which the imports
  status field has and the now-virtual transcripts one does not.
- `docs/architecture.md` — keep the CSV import bullet and take main's
  rewritten `TranscribeMeditation` paragraph.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01H6zmb4FdfrMUxYahrrPDrD
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Merged main (d5ac8b3). Three conflicts, all in lines #995 and #1000 also edited.

  • src/jobs/queues.ts — kept this branch's default queue entry and main's queueTranscription rename. The transcription comment's clearance list still named a queue imports; this branch declares default, so I corrected it.
  • tests/unit/job-stage-view.spec.ts — kept the generalised fieldNamed helper over main's narrower statusField. Main dropped defaultValue from the type because the transcripts status field is virtual now; the imports status field still has one, and only that spec case reads it.
  • docs/architecture.md — kept the CSV import bullet, took main's rewritten TranscribeMeditation paragraph whole.

Lean gate green: lint, both typechecks, 2,772 unit tests.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Main's #1007 trimmed the agent guides; this branch extends two of the files
it trimmed. Three hunks, resolved toward both sides:

- `docs/rules/access.md`: took #1007's removal of the manager-role table, a
  config copy it cut deliberately. The dropped `atlas-manager` row carried
  one thing the config does not show — that `imports: create` is also what
  keeps the collection's admin pages visible — so that moved onto the
  `imports` paragraph, which already owns the collection's access block.
- `docs/rules/admin-ui.md`: took #1007's trim of the `@payloadcms/ui` table
  and of the custom-field paragraph. `ProgressBar` is exported, so the
  warning below the table no longer had a curated list to be absent from;
  it now names what the component actually is.
- `docs/rules/admin-ui.md`: kept the `WorkflowButtons` section. It documents
  `src/components/admin/WorkflowButtons/`, which only this branch carries,
  so #1007 never saw it.

`tests/PERF.md` needed a count, not a resolution. #994 recorded 204 unit
specs and #990's spec pins that figure to the tree, so the merged tree's 215
files and 2783 tests reddened it with neither side wrong. Re-recorded the two
counts, and the three consumer docs that restate them. Timings are untouched:
PERF.md keeps each one with the session that measured it.

Lean gate green: lint, typecheck, typecheck:tests, 215 unit files / 2783
tests, in 83 s.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012KhBAi8xKwJspy75uAvmDV
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Merged main and pushed 6c9aae2. Three doc hunks, all from #1007's guide trim.

tests/PERF.md reddened with neither side wrong. #994 recorded 204 unit specs and #990's spec pins that count to the tree. The merged tree has 215 files and 2783 tests, so I re-recorded both counts and the three consumer docs that restate them. Timings untouched.

Lean gate green in 83 s: lint, typecheck, typecheck:tests, 215 unit files.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

#1007 cut the maxLength trap that this section called "above", and kept
only the general "supplying validate replaces the default" rule. The
section is now a single warning on that rule, pointing to targetRegion.ts,
whose docblock already carries the detail. This puts src/collections/AGENTS.md
back under 32k characters (33,124 to 31,993).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

feat(events): CSV class import as a Payload collection driven by jobs

3 participants