Skip to content

feat(wm-app-translations): rich-text leaf properties + schema delta + English seed import (closes #393) - #404

Merged
Ardnived merged 2 commits into
mainfrom
feat/wm-app-translations-richtext
May 25, 2026
Merged

Ardnived merged 2 commits into
mainfrom
feat/wm-app-translations-richtext

Conversation

@antontcymbal

@antontcymbal antontcymbal commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements all three phases of #393 — rich-text support in wm-app-translations, the schema rewrite that uses it, and the English seed import wired into the existing pnpm seed pipeline. Two commits, scoped to be reviewed independently if preferred.

  • Phase 1 — src/fields/translationsField.ts gains a new LeafPropertySchema = StringPropertySchema | RichTextPropertySchema union. buildTranslationTabs() treats leaves like this:
    • Pure-string leaf (current behaviour, 33 of 40 leaves) → single JSON field rendered by TranslationsTable. Field name and shape unchanged — no breaking change.
    • Mixed leaf (≥ 1 richText property, 7 leaves) → wrapper Payload group field named after the leaf, containing one strings JSON sub-field + one stock Payload richText sub-field per richText property, each using the existing basicRichTextEditor preset (Bold, Italic, Link, InlineToolbar).
  • Phase 2 — src/globals/wemeditate-app/translationsSchema.json is rewritten to collapse 22 *_prefix / *_link / *_suffix triples into 7 richText fields, and convert 3 plain-string paragraphs to richText so the bold spans live in the translation rather than hardcoded Flutter styling. Description of every collapse and conversion is in the issue.
  • Types regenerated via pnpm generate:types.
  • Tests in tests/int/translations-globals.int.spec.ts — updated the globalSlug test to inspect both shapes; added two new assertions: one for the mixed-leaf wrapper-group shape (onboarding_consent_modal) and one for pure-string leaves staying flat (onboarding_name).

Schema delta — concrete list

Leaf What changes
onboarding.welcome 4 string keys (legal_disclaimer_prefix/_and/_terms/_privacy_policy) → 1 richText (legal_disclaimer)
onboarding.user_type 3 string keys (title_prefix/_brand/_suffix) → 1 richText (title)
onboarding.carousel 2 string keys (page_true_self_prefix/_highlight) → 1 richText (page_true_self_title)
onboarding.consent_modal 3 string keys (body_intro_prefix/_link/_suffix) → 1 richText (body_intro); 2 plain-string paragraphs (body_never_share, body_never_sell) → richText
auth.create_account 4 string keys (consent_prefix/_terms/_and_acknowledge/_privacy) → 1 richText (consent_label)
meditation.footsoak 3 string keys (description_prefix/_emphasis/_suffix) → 1 richText (description)
profile.privacy_advertising 3 string keys (advertising_body_intro_prefix/_link/_suffix) → 1 richText (advertising_body_intro); 1 plain-string paragraph (advertising_body_never_share) → richText

Totals: 25 string keys consolidated into 10 richText fields. 458 plain-string keys remain unchanged. Schema goes from 483 → 468 total keys + 10 richText.

⚠ Migration required before merge

This PR does not include the D1 schema migration. Mixed leaves change from a single JSON column to one column per sub-field (one strings JSON column + N richText JSON columns per locale on wm-app-translations_locales).

Per .claude/rules/migrations.md, pnpm db:migrations:create must be run interactively — it hangs in agent shells. @Ardnived, please run:

pnpm db:migrations:create

and use a name like wm-app-translations-richtext. The resulting .ts + .json pair under src/migrations/ then commits on top of this branch. No --augment should be needed for this change — it's a clean column-additions migration.

Once the migration is in: pnpm payload migrate locally, eyeball the admin UI to confirm the 7 mixed-leaf tabs render the new richText editors below their strings table, then we're good to merge.

Phase 3 — English seed import (commit 524fa30)

Phase 3 is in this PR. New files under seeds/wm-app-translations/:

  • data.en.json (734 lines, 36 KB) — the full English seed: 455 keys mapped from sydevs/WeMeditateApp@main:assets/l10n/en.yaml, 28 keys for consent surfaces sourced from Figma (node-ids 11564-91404 + 11571-40337), 10 keys for the LEGAL / Learn more sections from the Profile-tab Figma. 1 explicit _todo marker for advertising_platforms_* (below the screenshot fold).
  • lexicalConverter.ts — pure-function converter from the human-readable paragraph/segment shape in the JSON to the Lexical JSON tree Payload's richText fields persist. Conventions match seeds/lib/lexicalConverter.ts (direction: null, link version: 3, fields: { linkType: 'custom', url, newTab: false }, text format bitmask for bold/italic). Exposed as a separate module for unit testing.
  • import.ts — WeMeditateAppTranslationsImporter extends BaseImporter. Loads the JSON via the dual-mode loader (filesystem in dev, raw.githubusercontent.com in Workers), runs the segment→Lexical conversion for the 7 mixed leaves, issues a single payload.updateGlobal() call. Surfaces every _todo marker as a warning for editor follow-up.

Wired into the existing seed pipeline so it's targeted exactly like the other scripts:

pnpm seed wm-app-translations --dry-run                    # local preview
pnpm seed wm-app-translations                              # commit to local
SAHAJCLOUD_URL=https://cloud.sydevelopers.com pnpm seed wm-app-translations

Two glue files updated:

  • seeds/lib/expectedCounts.ts — adds 'wm-app-translations' to the ScriptName union. Empty EXPECTED_COUNTS + empty COLLECTION_METADATA entries (the script targets a global, not collections — verifyCountsForScript correctly passes by default).
  • src/app/(payload)/api/seed/[script]/route.ts — adds the new script to VALID_SCRIPTS, a getImporter() switch case, and a no-op case in getDatabaseCounts() (the collection-counting path doesn't apply to a global).

Unit test coverage: tests/unit/wm-app-translations-lexical.spec.ts — 26 cases covering plain text, bold/italic format bitmask, link nodes, multi-paragraph trees, error paths (malformed link/text segments, empty paragraphs), leaf shaping (pure-string vs mixed), metadata-key stripping (_source / _todo), and TODO collection. Pure functions, no Payload bootstrap, ~7ms total.

What's NOT in this PR

  • D1 schema migration — see the ⚠ Migration required before merge section above.
  • Per-locale migration of existing translation data. Verified empty against prod via GET /api/globals/wm-app-translations — only markReviewed is currently set on the global. No live translation data to migrate.
  • WeMeditateApp Flutter changes. Out of scope here per the ticket framing — owned by a separate team.

Test Results

  • pnpm test:int → 724 / 724 passing (including 4 new tests added in commit c7bc889)
  • pnpm exec vitest run tests/unit/wm-app-translations-lexical.spec.ts → 26 / 26 passing (new converter unit tests, no Payload bootstrap, ~7ms total)
  • pnpm lint → no new warnings (the existing src/collections/content/Videos.ts import-order warning is unrelated to this change)
  • pnpm tsc --noEmit -p tsconfig.json → 0 errors in changed files
  • Dry-run against prod with the standalone temp-script variant of the importer (validated before the seed-pipeline integration was written) → auth succeeded with the clients API key, GET /api/globals/wm-app-translations returned 200, diff showed all 40 leaves would be created (current global is empty except for markReviewed). The pipeline-integrated pnpm seed wm-app-translations --dry-run is gated on the migration step before it can be exercised locally.

Test plan for reviewer

  • Pull this branch, run pnpm db:migrations:create interactively, name it something like wm-app-translations-richtext
  • Verify the generated .ts migration looks like clean column additions (no _rels rebuilds, no polymorphic FK renames)
  • pnpm payload migrate against local D1
  • pnpm test:int — confirm 724+ tests still pass
  • Open http://localhost:{PORT}/admin/globals/wm-app-translations and confirm:
    • The 7 affected tabs (Onboarding → Welcome / User Type / Carousel / Consent Modal, Auth → Create Account, Meditation → Footsoak, Profile → Privacy Advertising) each show the rich-text editor for the new richText fields below their strings table
    • The basicRichTextEditor toolbar shows only Bold / Italic / Link / InlineToolbar (no headings, lists, blocks)
    • Pure-string leaves (Daily, Path steps, Auth Login, etc.) render identically to before — single JSON table per tab
  • Confirm Review tab still works (this PR doesn't touch it)
  • Phase 3 sanity check: with the dev server running, pnpm seed wm-app-translations --dry-run reports 40 leaf groups planned + 1 TODO. Then pnpm seed wm-app-translations (without --dry-run) writes successfully and the admin UI shows the seeded English copy across all 7 mixed-leaf tabs.

Once the migration is in and these check out, the whole PR ships together.

🤖 Generated with Claude Code

…Phase 1+2 of #393)

Phase 1 — extend buildTranslationTabs() in src/fields/translationsField.ts to
support `type: "richText"` alongside `type: "string"` in leaf schema properties.
Pure-string leaves keep the existing single-JSON-field shape (backward
compatible — 33 of 40 leaves unchanged). Mixed leaves (at least one richText
property) wrap in a Payload `group` field containing `strings` JSON + one
stock Payload richText sibling per richText property, using the existing
basicRichTextEditor preset (Bold, Italic, Link, InlineToolbar).

Phase 2 — apply the schema delta to src/globals/wemeditate-app/translationsSchema.json:

  - Collapse 22 prefix/link/suffix strings into 7 richText fields:
    onboarding_welcome.legal_disclaimer,
    onboarding_user_type.title,
    onboarding_carousel.page_true_self_title,
    onboarding_consent_modal.body_intro,
    auth_create_account.consent_label,
    meditation_footsoak.description,
    profile_privacy_advertising.advertising_body_intro
  - Convert 3 plain-string paragraphs to richText so bold spans live in the
    translation rather than hardcoded Flutter styling:
    onboarding_consent_modal.body_never_share / body_never_sell,
    profile_privacy_advertising.advertising_body_never_share

Net: 483 → 468 string keys, +10 richText keys, 33 pure-string leaves, 7 mixed
leaves. Schema field-name shape is unchanged for pure-string leaves.

Tests — tests/int/translations-globals.int.spec.ts:
  - Update the existing `globalSlug` test to look for the JSON field at both
    depths (direct child or inside the wrapper group).
  - Add a new test asserting mixed-leaf wrapper-group shape (strings JSON +
    richText siblings) for onboarding_consent_modal.
  - Add a new test asserting pure-string leaves remain a direct JSON field
    (onboarding_name).

Migration: not included in this commit. A D1 schema migration is needed
because mixed leaves change from a single JSON column to one column per
sibling field (one `strings` JSON column + N richText JSON columns per
locale). pnpm db:migrations:create needs to be run interactively per
.claude/rules/migrations.md.

Phase 3 (English seed import) is deliberately not in this PR — see #393
for the seed data, import script, and rollout plan.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@antontcymbal
antontcymbal requested a review from Ardnived May 25, 2026 13:23
Adds a new seed script that imports the English source copy for the
wm-app-translations PayloadCMS global from a checked-in JSON data file.

Targeted via the existing seed pipeline:

  pnpm seed wm-app-translations --dry-run     # local preview
  pnpm seed wm-app-translations                # commit to local
  SAHAJCLOUD_URL=https://cloud.sydevelopers.com pnpm seed wm-app-translations

Idempotent — re-running overwrites the English-locale value for every
key in the seed. Other locales are untouched.

## New files

* seeds/wm-app-translations/data.en.json — 734 lines, 36 KB. Full seed
  for the post-Phase-1+2 schema (40 leaf groups: 33 pure-string, 7
  mixed-with-richText). 455 keys map from sydevs/WeMeditateApp's
  assets/l10n/en.yaml; 28 keys for consent surfaces sourced from Figma
  (node-ids 11564-91404 + 11571-40337); 10 keys for the LEGAL / Learn
  more sections added from the Profile-tab Figma. 1 explicit _todo
  marker (advertising_platforms_* values, below the screenshot fold).

* seeds/wm-app-translations/lexicalConverter.ts — pure-function converter
  from the human-readable paragraph/segment shape in the JSON to the
  Lexical JSON tree Payload's richText fields persist. Conventions match
  seeds/lib/lexicalConverter.ts (direction: null, link version: 3,
  fields: { linkType: 'custom', url, newTab: false }, text format
  bitmask for bold/italic). Exposed for unit testing.

* seeds/wm-app-translations/import.ts — WeMeditateAppTranslationsImporter
  extending BaseImporter. Loads the JSON via the dual-mode loader
  (filesystem in dev, raw.githubusercontent.com in Workers), runs the
  segment→Lexical conversion for the 7 mixed leaves, then issues a single
  payload.updateGlobal() call. Surfaces every _todo marker as a warning
  for editor follow-up after the import lands.

* tests/unit/wm-app-translations-lexical.spec.ts — 26 unit tests covering
  plain text, bold/italic format bitmask, link nodes (version: 3,
  newTab: false, direction: null), multi-paragraph trees, error paths
  (malformed link/text segments), leaf shaping (pure-string vs mixed),
  metadata-key stripping (_source / _todo), and TODO collection.

## Wired into the existing seed pipeline

* seeds/lib/expectedCounts.ts — adds 'wm-app-translations' to the
  ScriptName union. Empty EXPECTED_COUNTS + empty COLLECTION_METADATA
  entries reflect that this script targets a global, not collections —
  the runner's verifyCountsForScript correctly passes by default.

* src/app/(payload)/api/seed/[script]/route.ts — adds 'wm-app-translations'
  to VALID_SCRIPTS, a getImporter() switch case for dynamic import of
  the new importer class, and a no-op case in getDatabaseCounts() (the
  collection-counting path doesn't apply to a global).

## Gates passed

* pnpm exec vitest run tests/unit/wm-app-translations-lexical.spec.ts
  → 26 / 26 passing in ~7ms (no Payload bootstrap)
* pnpm test:int → 724 / 724 passing (no regressions)
* pnpm lint → no new warnings
* pnpm tsc --noEmit -p tsconfig.json → 0 errors in changed files

## End-to-end runs still gated on

* D1 schema migration for the Phase 1+2 schema changes (the wrapper
  group + per-richText-field columns). Per .claude/rules/migrations.md
  this must be created by pnpm db:migrations:create interactively and
  is the only remaining human-input step before pnpm seed wm-app-translations
  can run against local or prod.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@antontcymbal antontcymbal changed the title feat(wm-app-translations): rich-text leaf properties + schema delta (Phase 1+2 of #393) feat(wm-app-translations): rich-text leaf properties + schema delta + English seed import (closes #393) May 25, 2026
@Ardnived
Ardnived merged commit bd9de1b into main May 25, 2026
Ardnived pushed a commit that referenced this pull request May 25, 2026
…S validate (Workers-safe) (#407)

Writes to wm-app-translations JSON fields fail on prod (Cloudflare
Workers) with:

  ValidationError: The following field is invalid: Navigation > Navigation
  → "Code generation from strings disallowed for this context"
    at beforeChange (worker.js)

Root cause: the JSON-field `jsonSchema` option compiles to an Ajv
validator (`new Ajv() + ajv.validate`) in payload's beforeChange field
validation. Ajv uses `new Function()` for performance, which Cloudflare
Workers' V8 isolate blocks with the CSP-style error above. The bug has
existed since the global was first introduced (#188 / #190) but was
latent because nothing ever wrote to these JSON fields on prod — the
admin UI showed empty fields and translators hadn't yet started. The
#393 seed import is the first thing to hit it.

Fix: drop `jsonSchema` from `createStringsJsonField` and reimplement the
same validation contract (required keys, additionalProperties,
per-key string-type checks) as a pure-JS `validate` function. No more
Ajv compilation, no more dynamic code generation. The admin UX is
unaffected because these JSON fields are rendered by the custom
TranslationsTable component (key/value rows), not Monaco, so the loss
of Monaco's schema hints costs nothing.

Generated types: `pnpm generate:types` produces a more generic shape
for the JSON fields (no inner-key types) since Payload was deriving
those from the jsonSchema. TranslationsTable + the seed converter both
work on the runtime data shape, not the generated TS types, so this is
purely a type-permissiveness regression with no runtime impact.

Wire-up: also adds 'wm-app-translations' to seeds/run.ts's local CLI
registry (ScriptName, VALID_SCRIPTS, SCRIPT_RUN_ORDER, SCRIPT_DESCRIPTIONS,
usage text). This was missed in #404 — the API route already knew about
the seed but the CLI rejected it as Unknown script. Note that the CLI's
cookie-forwarding auth is known-fragile against prod's Workers runtime
(per .claude session-handoff notes); the JWT-header path via direct
fetch to the API endpoint is the verified production-safe import path.

Tests:
- tests/int/translations-field.int.spec.ts — replace the 5 jsonSchema-
  assertion tests with 8 pure-JS validate tests covering: null/undefined
  passes, non-object rejection, missing-required-key rejection,
  unknown-key rejection (when additionalProperties is not true),
  unknown-key acceptance (when additionalProperties is true),
  non-string-value rejection for declared keys, well-formed object
  acceptance.
- tests/int/translations-globals.int.spec.ts — replace the 2 jsonSchema-
  assertion tests with assertions that jsonSchema is undefined and
  validate is a function on every JSON field of all three translation
  globals (wm-web-translations, wm-app-translations, sy-atlas-translations).
- All 728 integration tests + 26 unit tests pass; lint clean; typecheck
  clean for changed files. The 33 "errors" reported by vitest are
  pre-existing unhandled rejections from a payload package-version
  mismatch (@payloadcms/[email protected] vs [email protected]),
  not caused by this change.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Ardnived added a commit that referenced this pull request Aug 3, 2026
…re import (#605)

* feat(atlas): groom legacy event listings before import

The 511 Atlas events were typed by ~200 volunteer managers over four years
with no validation, so the free-text fields carried information the listing
already renders structurally, copy-paste junk, spelling mistakes, and dates
now 2-4 years stale. 219 of 511 events needed at least one edit.

Grooming (events.json, managers' wording kept verbatim):

- Removed what `address` / `room` / `schedule` / `contactInfo` /
  `onlineUrl` / `registrationUrl` / `website` already render. Where prose
  and schedule disagreed the schedule won — its weekday always matches
  startDate's day-of-week, the prose did not (#128, #149, #235, #389, #443).
- Dropped stale dates (25 events named a year, 48 a specific date) and 18
  expired notices ("On Christmas break", "Sommerpause", "CLOSED during
  August 2024").
- Fixed capitalization (the Italian `SAHAJA YOGA -` prefix, the Australian
  `HORNSBY Thursdays 6.30pm` pattern, German title-case, missing accents)
  and ~25 confirmed spelling errors across 8 languages.
- Stripped 480 U+2800 braille blanks used as VK padding, 31 zero-width
  spaces, tabs, CRLF, `</br>`, and styled Mathematical-Alphanumeric letters.
- Rewrote titles that were a bare place name, a venue name, an address, or
  a day and time.

A weekday stays in a title where it is the only thing separating sibling
events at one venue, and in a description where `schedule` cannot express
the real cadence — both noted in AGENTS.md.

Supporting changes:

- Add `Events.contactEmail`. Atlas has no such column: 16 addresses came
  out of descriptions and 12 from the `contactInfo.email_address` the
  importer never read. Deliberately outside the contactPhone -> contactName
  required gate, since some events publish an email and no phone.
- Promote 10 `contactInfo.meetup`/`facebook` values to `website`, own
  domain beating the aggregator per the #584 rule.
- Derive a missing `schedule.weekday` from `startDate` in `parseSchedule`.
  49 rows use a YAML dialect with no `on` key; weekly ones were already
  covered by scheduleMapper's fallback, but `monthly_1st` was not — 2
  events recurred on "day 3 of the month" instead of "first Sunday".
- Emit optional event fields as `null`, not `undefined`. Payload omits
  `undefined` from an update, so the 36 descriptions this pass cleared
  survived the first `--update` reseed unchanged.
- Skip the leftover test records #494/#575, warning with the document id
  when an earlier import already created them (#575 landed published).
- Move recurrence parsing to `helpers/recurrence.ts` so it is unit-testable
  (extract.ts runs `main()` at module load).

tests/unit/atlas-events-data.spec.ts guards the grooming invariants so a
re-extraction — which drops every curated value — fails the unit lane
instead of quietly shipping. 13 of its 15 cases fail against the
pre-grooming file.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(events): time-of-day auto-titles, and prefer them over generic names

A blank event title is better than a hand-written generic one: the auto-fill
localizes, and improving one string improves every event, where 60 copies of
"Free Meditation Classes in <Place>" cannot be. This makes the auto-fill worth
preferring, then retires the generic names in favour of it.

Auto-title:

- Add `event.title` to the Atlas translations global — `morning` / `afternoon` /
  `evening` / `default`. Each is a complete sentence with a `%{place}`
  placeholder, not a shared prefix plus a time-of-day word: a locale that puts
  the time of day after the place, or inflects it with the preposition, cannot
  be served by concatenation.
- Pick the slot from the event's *local* start hour via `schedule.firstDate_tz`.
  19:00 in Auckland is 07:00 UTC, so reading the UTC hour would label it a
  morning class. `default` covers a 22:00-04:59 start and the 19 events with no
  schedule at all.
- Slots fall back to English individually — Payload's locale fallback is
  per-field, not per-key, so a partly translated locale would otherwise yield
  `undefined` for the slots a translator skipped.

The hook previously read `event.titlePrefix`, which was never declared in
`translationsSchema.json`: the lookup always missed and every title used the
hardcoded English. `event` holds nested groups and the builder cannot mix leaf
keys with groups at one level, which is likely why it was never added — hence a
`title` group rather than a bare key.

Titles (69 blanked, 11 kept or restored):

- Blanked the standardised "Free Meditation Classes in <Place>" names an earlier
  pass introduced, three indistinguishable "Online Meditation" listings, five
  casing/"Weekly" variants, eight that collided at one venue, and five carrying
  an English generic on a DE/FR event.
- Restored 10 titles that name the **venue** — the auto-fill only has the
  street, so `Regina Public Library, Glen Elm branch` carries what
  `1601 Dewdney Ave E` cannot. Kept #293/#294/#371, whose streets are `Zentrum`,
  `Innenstadt` and `B26`; fixed #294 `Tyrol` -> `Tirol`.
- The importer now sends `title: ''` for a blank `customName`. The hook keeps
  `originalDoc.title` for a nullish value, so clearing a title in events.json
  would otherwise never reach an already-imported row.

Because the auto-fill takes the first comma-segment of `street`, three venue
records were producing "Meditation at 9" / "at solihull" / "at old bar"; fixed
in venues.json, which improves the rendered address too.

The four Swiss `Introduction & Meditation Course` events are not a translation
gap — they are the `course` half of duplicate pairs (same venue, weekday,
language, and time in 5 of 7). Translating them would mint a duplicate title per
venue, so they are blanked and the pairs documented for a manager to reconcile.

Verified: lint, typecheck, 897 unit tests, and 60 integration tests across the
events/atlas/translations specs. The full integration lane is flaky on this
machine — the clean tree at 4f7ca64 fails 12 files / 13 tests the same way
(timeouts in media- and meditation-heavy suites), so this branch sits inside the
existing noise band rather than adding to it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(atlas): merge 12 confirmed duplicate events

Atlas let one real class be entered twice. 12 pairs were confirmed by sharing a
venue *and* an identical frequency/interval/weekday/weekNumber/startTime, then
differing only in title, description, lifecycle status or language. Atlas's own
`status` decided the survivor: 0 = verified/live, 6 = finished, so a 6/0 pair
means Atlas had already retired one side.

15 rows removed from events.json (511 -> 496):

- #195 -> #603   same Zoom room + slot, same manager and region; title blanked
- #752 -> #753   one bilingual Ixelles session listed twice, EN and FR
- #360 -> #684, #392 -> #698                     Helsinki, retired half dropped
- #458/#461/#464/#468/#469 -> #560/#565/#562/#570/#571
                 one Swiss manager's `course` rows, retired and re-entered as
                 `dropin` at the same venue/weekday/time/language
- #82 + #496, #497 + #534, #355 + #535           both sides already retired

A merge is not a delete: values the removed row held and the survivor lacked
were carried over first — #684 gained #360's meetup `website` and contact, #698
gained #392's contact.

- Add a curated `languageCodes` override. Atlas stored one code per row but
  Payload's `languages` is hasMany, so the merged bilingual #753 carries
  ['EN','FR']; `mapEventLanguages` prefers it over `languageCode`.
- Generalise the skip guard into `EXCLUDED_EVENT_LEGACY_IDS`, a reason-per-id
  map covering the 2 test records and all 15 removals, so a re-extraction (which
  rebuilds the file from `select * from events`) cannot undo the merge. It warns
  with the document id when an excluded row already exists from an earlier
  import — all 15 do.
- `expectedCounts.events` 509 -> 494. Removing rows also drops 3 venues from
  multi-use to single-use (132, 317, 562), so the import now creates 3 fewer
  region centers; regions still clear their expected minimum.

Deliberately not merged: #115/#116 (same Zoom link but different `areaId` — one
room advertised to two regions on purpose), five pairs owned by two *different*
managers, and #400/#404 + #435/#437, which only look co-located because a venue
record's coordinates disagree with its own stated address.

Verified with captured exit codes: lint, typecheck, 899 unit tests, and 33
integration tests across the atlas/events/translations specs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(atlas): blank 78 titles that only say "meditation"

A custom title has to earn its place: the auto-fill localizes and improves
centrally, so a generic name is strictly worse than none. 78 titles said nothing
the auto-title doesn't — often the identical string repeated verbatim across a
dozen cities, so they never distinguished anything either.

Blanked, among others:

  10x  Taller de meditación          (5 Spanish cities)
   7x  Viikoittainen meditaatio      (4 Finnish cities)
   6x  Corso di Meditazione          (6 Italian cities)
   5x  Meditatie Cursus              (5 Belgian towns)
   5x  Sahaja Yoga Präsentation und Meditationsübung
   3x  Méditation                    (#753/#754/#755)

plus one-offs — `Aula aberta`, `Meditation Course`, `Learn to meditate`,
`Meditate for inner peace`, `Медитация`, `Meditação Presencial` ("in person"
is `eventType`), `Weekly meditation`, `Daily online meditation`.

Kept, because they name something the auto-fill cannot:

- a venue      — Regina Public Library, University of Guelph, Button Factory
- an audience  — Kids' Meditations, Aula de Aprofundamento, Meditation für
                 Fortgeschrittene
- a language   — Viikoittainen meditaatio suomeksi, Meditationskurs auf Deutsch,
                 Sahaja Yoga in English
- a format     — Music and Meditation, Live Online WhatsApp Video Meditation,
                 Taller de musicoterapia
- a named event — Corso Leopold, Puja a Shri Ganesha, Vaasan Taiteiden Yö

Blanking can collide: two events at one venue in the same time-of-day slot
auto-fill to the same title. #463 and #569 were therefore left named, each
sharing a street with an already-blank sibling. The 7 remaining collisions are
all pre-existing pairs already on the unmerged-duplicates list — #263-#266 were
four identical `Taller de meditación` titles before this change, so they are no
less distinguishable than they were.

Two guards added to tests/unit/atlas-events-data.spec.ts: a regex rejecting bare
"meditation/class/course" titles in 9 languages, and a check that every blank
title can still produce one (online, or a venue with a street). The first was
mutation-checked by re-introducing `Méditation` on #753 — it fails.

221 custom titles remain, 273 events auto-fill.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(atlas): group events that meet at one address into a shared venue

A venue used by more than one event becomes a Regions node those events point
at; a single-use venue's address is inlined and the record dropped. That already
worked — but grouping keys on `venueId`, and Atlas holds the same place under
several venue rows, so two events at one address each looked single-use and
neither grouped.

Ten pairs added to VENUE_MERGES, each verified by hand. **36 -> 44 shared
venues**, 346 inlined.

Coordinates alone are not evidence in either direction: two Civitavecchia venues
sit 177 m apart but are different places, while Athens 386/432 are 230 m apart
yet share a name, street, city and postcode. Two candidates were rejected on
inspection — Móstoles 155/158 (404 km apart, different names; one row's `street`
is simply wrong) and Воронеж/Тольятти 483/511 (700 km apart). Both had surfaced
from a normaliser that stripped non-Latin text to an empty string, so every
Cyrillic and Greek address matched every other one.

The kept side is whichever holds better data, not the lower id — 191 -> 215
because 215 is named `Wensum Sports Centre`, which event #315's own description
names; 50 -> 514 because 50's postcode `1017ZP` is Amsterdam's on a Den Haag
venue. VENUE_FIELD_OVERRIDES repairs a field where the *deleted* row was better
(514 keeps its correct postcode but takes 50's real name, `Atelier`), in code so
a re-extraction reproduces it.

Two bugs this fixes:

- Venues 11 and 104 sit 1 m apart and were *both* shared, so the import created
  two nodes for one Amsterdam building.
- Merges apply in a single pass, so a chain strands events on a deleted row. The
  pre-existing `342 -> 104` had to become `342 -> 11` once 104 merged into 11.
  `venueMergeChains()` + a unit test now reject any chain.

Also: warn on orphaned nodes. The import only upserts, so a venue dropping below
the >1-event bar leaves a stale region behind with its public URL. It reports the
document id rather than deleting — a manager may have hung content off it.

Three postcode conflicts are left as they stand, flagged in AGENTS.md, because
the data cannot settle them: Eindhoven 5641EC/5641PC, Tampere 33541/33540,
Derby DE73 5SA/5UA.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(events): keep the venue name, and let the auto-title use it

`venueToEventAddress` discarded a venue's own name when folding a single-use
venue into an event's address, leaving nothing but a street — so a blank title
auto-filled to "Meditation at 9 St Peter's Park Rd" rather than naming the
meeting house a seeker is looking for.

- Add `address.venueName` (text, max 100) behind a `hasVenueName` option on the
  shared addressFields factory; only Events opts in. Distinct from `room`, which
  says where *inside* the building to go.
- `addressPlaceName` prefers it over the street, so `composeEventTitle` now takes
  the address rather than the street alone.
- The importer sets it for 232 offline events.

166 names are deliberately dropped, because they add nothing over the address:

- **the street rewritten** — Atlas names many venues after their own address with
  the house number on the other end ("22 Manenburgstraat" for "Manenburgstraat
  22"). Compared as a sorted token bag, so word order and punctuation don't
  matter.
- **the city** — venue 483 is named "Воронеж", in Воронеж. Using that as the
  place would be worse than the street, not better.

Trailing separators are stripped: "Browns Bay Community Centre," and
"Waimarie: Hamilton East Community House," both carried one, and would otherwise
have ended a title with a comma.

Resulting titles: "#4 Evening Meditation at Main Sahaja Centre in New Zealand",
"#11 Afternoon Meditation at Upper Riccarton Community and School Library".

The generated migration also picks up `event_title` on the translations locales
tables — that group was added in 023fc39 without one. Dev runs `push: true` so
it went unnoticed; production would have been missing the column.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(regions): rename the `center` level to `venue`

Most of these are public libraries and community halls that host more than one
class, not Sahaja Yoga centres — "SY Center" claimed more than the data supports.
The level is what it actually is: a venue shared by several events.

Renamed the stored enum value, not just the label, so the API says the same thing
the admin does: `level: 'center'` -> `'venue'`, "SY Center" -> "Venue", the
Centers tab -> Venues, `childrenCenters` -> `childrenVenues`, and the importer's
`center:<venueId>` map keys -> `venue:<venueId>`.

*** BREAKING FOR AtlasReact *** — the widget reads `level` off the region API and
must be updated in step. Nothing else consumes the value: it appears only in
Regions.ts, Events.ts's City/Venue filter, geocoder.ts's radius default, the
importer, and generated types.

`src/lib/atlasSidebar/sidebarModel.ts` declares its own `RegionLevel` union
(deliberately, to keep the client tree free of the server collection), so
typecheck could NOT catch it — the stale `center` key surfaced only when the unit
lane ran. Worth remembering the next time a level value changes.

*** THE MIGRATION NEEDS A HAND-EDIT BEFORE MERGE ***

`20260730_172342_rename_region_level_center_to_venue.ts` is committed exactly as
generated, and as generated it will FAIL on deploy: it casts the column to text,
drops and recreates the type, then casts back with
`USING "level"::"enum_regions_level"` — which throws on every existing row
holding 'center' (44 of them), aborting the in-process boot migration.

The hook blocks me from editing files under src/migrations. Replace both bodies
with an in-place rename, which carries the rows and needs no backfill:

  up:    ALTER TYPE "public"."enum_regions_level" RENAME VALUE 'center' TO 'venue';
  down:  ALTER TYPE "public"."enum_regions_level" RENAME VALUE 'venue' TO 'center';

Verified with captured exit codes: lint, typecheck, 919 unit tests, 29
integration tests across atlas-collections / regions / events / atlas-sidebar.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor: re-export RegionLevel instead of redeclaring it

`sidebarModel.ts` declared its own copy of the `RegionLevel` union, so the
`center` -> `venue` rename typechecked cleanly while leaving two stale `center`
keys behind — the failure surfaced only when the unit lane ran. A type-only
re-export from the canonical union makes tsc catch it.

Type-only, so it's erased at compile time: none of geocoder.ts's server-side
Mapbox code reaches the client bundle this module feeds ('use client' components
under src/components/admin/AtlasNav/).

Mutation-checked — renaming the canonical value now produces
`sidebarModel.ts(147,3): Type '"venue"' is not assignable to type
'RegionLevel | null'` where it previously compiled silently.

`REGION_LEVEL_LABEL` stays duplicated on purpose, now with the reason recorded:
`REGION_LEVEL_OPTIONS` is a runtime value inside a server collection config, so
importing it would drag that config, its hooks and `serverEnv` into the client
bundle.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(seeds): correct the expected Atlas region count to 518

`expectedCounts.atlas.regions` was 482 with a comment claiming "482 source geo
nodes (29 + 100 + 353)". Both halves were wrong: regions.json holds 474 rows
(29 country + 99 region + 346 area, post-dedupe), and the importer adds one
shared-venue node per venue used by more than one surviving event — 44 of them.
The real figure is 518.

This mattered because verification is `actual >= expected`, so an understated
constant is not a conservative choice — it degrades into no check at all. At 482
the import could have silently lost 36 regions and still reported a pass.

Adds a unit test deriving the number from the data (regions.json row count +
shared-venue count computed off events.json, excluding the two test records the
importer skips) and asserting EXPECTED_COUNTS matches. Mutation-checked: with
the constant back at 482 the case fails with "expected 482 to be 518".

Also corrects the `eventTitle` no-place comment, which claimed an empty title
would fall through to `useAsTitle`/the document id. It doesn't — `title` is
`required`, and field `beforeChange` hooks run *before* validation
(payload/dist/fields/hooks/beforeChange/promise.js:16-19), so the field is
refused rather than saved blank. The behaviour was already correct and already
covered by "leaves no event unable to produce a title at all"; only the comment
was misleading.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(atlas): sync the region-level rename and the groomed/region counts

The branch renamed the Regions `center` level to `venue` and moved several
counts; the docs still described the old shape.

- MIGRATION_PLAN.md: three "Regions `center`" references → `venue` node.
- atlas/AGENTS.md: the grooming pass covers 446 of the 511 extracted events, not
  219 (the figure predates the second and third passes); contactEmail is on 27
  events; the venue-topology note points at the test that now guards the count.
- seeds/AGENTS.md: atlas events 511 → 494, regions 482 → 518 in the collection
  metadata table, and the same 446 correction.
- Records why an understated `expectedCounts` value is not a safe default.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(migrations): rename the region level enum value in place

The generated migration cast `regions.level` to text, dropped the enum type,
recreated it without 'center', then cast back with
`USING "level"::"enum_regions_level"` — which throws
`22P02 invalid input value for enum enum_regions_level: "center"` on every
existing 'center' row. Prod has 44, and Railway PR previews boot against cloned
prod data, so as generated this aborted the in-process boot migration.

`ALTER TYPE ... RENAME VALUE` renames the label in place, so no row is rewritten.
Verified in a scratch schema seeded with center rows: the generated form fails
with 22P02, RENAME VALUE succeeds, the column default survives as
'country'::enum_regions_level, and `down` reverses cleanly.

Augmentation case 1 in .claude/rules/migrations.md — the migration fails without
the edit. The .json snapshot already records the post-rename values, so the
chain stays intact for the next migrate:create.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(tests): finish the center → venue rename in the access specs

`role-based-access.int.spec.ts` still created regions with `level: 'center'` in
four places, so the whole "recursive inheritance via breadcrumbs" block failed CI
with "Details > Type: This field has an invalid selection" (plus a cascading slug
collision as the fixture chain unwound).

The reason it reached CI: `tsconfig.json` excludes `tests`, so `pnpm typecheck`
never reads the int specs — the type-only RegionLevel re-export added earlier
guards `src/` but cannot guard here. Compounding it, both `createRegion` helpers
took `Record<string, unknown>`, so `level` was unconstrained even in-editor.

Narrows both helpers to a `RegionFixture` type keyed on the canonical
`RegionLevel`, and renames the leftover center/Center identifiers and test names
in both region specs to match the level they now create.

Including `tests` in the tsconfig program would be the real fix — it surfaces 189
pre-existing errors across ~20 spec files, so it needs its own ticket rather than
riding along here.

Verified: role-based-access + regions + atlas-collections int specs pass (79
tests), and the lean gate is green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants