Repository navigation
feat(events): CSV class import as a Payload collection driven by jobs - #912
Conversation
…, 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
|
🚅 Deployed to the SahajCloud-pr-912 environment in sahajcloud
1 service not affected by this PR
|
…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
…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
…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
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 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 slugfreeSlugmay 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
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
- 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]>
Rebuilt on
|
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 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: refusesupdate, 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 offreq.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
`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
|
Three critic threads: two adopted, one declined. Adopted
Declined
Base — merged Gate — lint, both typechecks, 2797 unit cases, plus ⚠ 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 |
…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]>
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]>
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
|
Merged
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
|
Merged
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]>
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.
@payloadcms/plugin-import-exportand replaced it, because we used a thin slice of the plugin and worked around it in several places. See "Why not the plugin" below.How it works
Starting an import
?targetRegion=<id>).relationshipvalidator enforces the same scope, composed on create only (targetRegion.ts).The upload (
csv/upload.ts)Refused in the form:
.csv;Then:
rowsfield, each with its spreadsheet line. The file is stored nowhere:disableLocalStorage, and no storage adapter.The job (
task.ts,prepare.ts),importEventson thedefaultqueuecsv/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.validate.ts, viabeforeChangeTraverseFields). 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.managerEmailmanager, so a skipped row opens no account.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:
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 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
eventsmoves an import between Review and Completed as its drafts are published or deleted, wherever that happens.Access
importsis inRESTRICTED_COLLECTIONS.atlas-managergainsimports: create, without which the access plugin hides the collection.The summary email
Counts of classes created, duplicates and errors, and one Review and publish button that opens the import.
The CSV format
recurrenceTypetakesDAILY,WEEKLYorMONTHLY, or blank for a one-off class.weekdaystakes codes fromMO,TU,WE,TH,FR,SA,SU.intervalanduntilDatework as their Events fields do.YYYY-MM-DDand times 24-hourHH:MM, so "9:30" and "7pm" are refused.inactivecolumn, anddateandstartTimeare required.csv/columns.ts).csv/template.ts).tests/unit/event-import-template.spec.tsholdspublic/event-import-template.csvto the generated version.Changes outside the importer
collections/Events/hooks/refuseDuplicateClass.ts). AbeforeValidatehook 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.icalRuleandupcomingDatesfor every class in the region on every save, which made a 500-row import take over ten minutes.ImportClassesLabel).scheduleFields.tsexportsWEEKDAY_OPTIONSandRECURRENCE_OPTIONS.resolveOwnedRegionIdsis 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:
10999into numbers.exportscollection.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
sendImportSummarybyscripts/preview-event-import-emails.ts. Mailpit keeps them for 7 days, andMAILPIT_UI_AUTHopens them.Contract impact
src/payload-types.tschanges, all additive for consumers:Event.importBatch, which isnumber | Import;Import,EventImportResultsandEventImportRowstypes;importEventsandsweepEventImportstask types.WeMeditateWebandSahajAtlasWebre-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.
20261010_013059_event_imports,20261010_025807_event_import_jobs,20261017_161838_event_import_analyze_slugevent_importscollection and job slugs20261019_182311_import_pluginevent_importswithimports, addsevents.import_batch_id, and swaps the job slugs20261020_002253_event_import_resultsresultsanderror, makes the target and uploader nullable, and sets the status values20261020_172522_event_import_own_jobexportstables, addsrows, and swaps the job slugs toimportEvents. It is hand-edited to delete jobs queued under the old slugs before the enum recast20261020_181806_merge_main_snapshotmain(below)Merged with
main, and the snapshot healed. Main's20261017_*lesson migrations sort between this branch's migrations, so the newest snapshot lacked their schema.20261020_181806_merge_main_snapshothas no DDL and only carries the merged snapshot. A probemigrate:createnow writes nothing.Both orders were checked on scratch databases:
transcribeMeditationandcleanupJobsjobs, then this branch's migrations. They applied cleanly and the jobs survived the enum recasts.Test results
pnpm lint,typecheck,typecheck:testspnpm test:unitmainevent-imports.int.spec.tsrole-based-access,collections-smoke,payload-system-access,event-verification,eventsevent-imports.int.spec.tscovers:beforeChangeTraverseFields;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
public/event-import-template.csvwith its example row edited into a real class, plus one row withstartTime7pmand 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.Closes #907
🤖 Generated with Claude Code