Skip to content

feat(audiences): split into progress/condition types with contextual targeting - #348

Merged
Ardnived merged 10 commits into
mainfrom
feat/345-audiences-progress-condition
May 5, 2026
Merged

Ardnived merged 10 commits into
mainfrom
feat/345-audiences-progress-condition

Conversation

@Ardnived

@Ardnived Ardnived commented May 5, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Replaces JSON rulesField on Audiences with native Payload group fields (pathProgress, meditationsPerWeek, totalMeditationsViewed, totalLecturesViewed) — each with optional min/max bounds, a max > min validator, and proper admin UI (range sliders out, native number inputs in).
  • Adds type discriminator (progress | condition) with collapsible field groups in the admin UI (progress rules only shown for progress type; country/eventTime/schedule only shown for condition type).
  • Condition-type fields: country (hasMany ISO 3166-1 alpha-2 select via i18n-iso-countries), eventTime (time-only date + timezone — passes if event falls in user's 08:00–22:00 local window), schedule (recurring/one-off gate via scheduleField).
  • Rewrites /api/audiences/for-user: progress audiences matched via a single SQL WHERE query; condition audiences fetched-all + JS-filtered by country/schedule/daytime. New context params: country (optional ISO alpha-2) and timezone (optional IANA — required for condition audiences that use schedule or eventTime).
  • Adds conditions relationship on AppCards (AND semantics: all condition audience IDs must be in the caller's resolved list, vs OR for audiences). appCardsForAudience endpoint post-filters accordingly.
  • Deletes: rulesField.ts, RulesEditor component (3 files), definitions.ts, evaluateAudiencesForUser.ts, rules-field.spec.ts.
  • New pure functions: isEventInUserDaytime (Temporal-based), isScheduleActiveNow (rrule-temporal occurrence window check).
  • OpenAPI: replaces dynamic AUDIENCE_DEFINITIONS generation with hand-written parameters.

⚠️ Destructive migration: drops audiences.rules JSON column. Existing audience rows lose their configured rules and must be re-entered using the new native fields after migration. Document this for operators before deploying.

Test Results

  • Unit tests: 208 passed (includes 28 new — daytime-match.spec.ts, schedule-match.spec.ts)
  • Integration tests: 433 passed (rewrote audiences-for-user.int.spec.ts, updated app-cards-for-audience.int.spec.ts with AND-conditions gate tests)
  • Build: ✓ Success
  • Lint: ✓ No errors

Closes #345

🤖 Generated with Claude Code

Ardnived and others added 10 commits May 4, 2026 18:59
…ase CRUD endpoints (#341)

- Gate fullLectureId in shapeLecture: clips only expose parent ID when
  the parent lecture's audiences overlap the requesting audiences list.
  Adds optional eligibleAudienceIds param (null = no gating, backward
  compat with existing callers).
- Add denyApiClientReads access helper; apply to Lectures and AppCards
  so API-key clients cannot use the base CRUD endpoints.
- Add overrideAccess: true to lecturesForAudience, meditationLectures,
  and appCardsForAudience so custom endpoints still work for clients.
- Add CUSTOM_ENDPOINTS_ONLY_COLLECTIONS to specFilter; mark base CRUD
  paths for lectures and app-cards as x-internal in the OpenAPI spec
  while keeping /for-audience and /related-lectures visible.
- Update and extend integration tests in lectures-for-audience,
  meditation-lectures, role-based-access, and api-explorer to cover all
  three gaps.

Closes #341

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…targeting (#345)

- Replace JSON rulesField with native Payload group fields (SQL-queryable,
  better admin UI): pathProgress, meditationsPerWeek, totalMeditationsViewed,
  totalLecturesViewed — each with optional min/max bounds and max>min validator.
- Add `type` discriminator ('progress' | 'condition') with collapsible field
  groups in the admin UI.
- Add condition-type fields: country (hasMany ISO 3166-1 select),
  eventTime (time-only date picker with timezone), schedule (via scheduleField).
- Rewrite /api/audiences/for-user: progress audiences via SQL WHERE (single
  query), condition audiences via JS filter (country/schedule/daytime gates).
  Optional country + timezone context params; missing timezone excludes
  schedule/eventTime audiences but not progress ones.
- Add `conditions` relationship on AppCards (AND semantics vs OR for audiences).
  Endpoint post-filters: all condition IDs must be in the caller's resolved list.
- Export buildRRuleTemporal from scheduleHooks.ts; extract ScheduleSubFields
  and ExclusionRange interfaces to src/types/schedule.ts (two consumers).
- New pure functions: isEventInUserDaytime (Temporal-based, daytime window
  08:00–22:00 in user's timezone), isScheduleActiveNow (occurrence window check
  via rrule-temporal).
- Add i18n-iso-countries for COUNTRY_OPTIONS select field.
- OpenAPI: replace dynamic AUDIENCE_DEFINITIONS generation with hand-written
  parameters (4 progress + country + timezone).
- Delete: rulesField.ts, RulesEditor component, definitions.ts,
  evaluateAudiencesForUser.ts, rules-field.spec.ts.
- 28 new unit tests (daytime-match, schedule-match); rewrote
  audiences-for-user.int.spec.ts with new field shapes + condition audience
  cases; updated app-cards-for-audience.int.spec.ts with AND-conditions gate
  tests; updated api-explorer, app-cards, audiences integration tests.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ion split (#345)

Drops audiences.rules JSON column; adds type discriminator, native
progress range columns (pathProgress, meditationsPerWeek, etc.), and
condition columns (country join table, eventTime, eventTime_tz,
schedule subfields). Adds conditions relationship on app-cards.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… docs (#348)

scheduleMatch.ts was calling Temporal.Instant.from() on the endTime field,
which scheduleField stores as HH:MM text. The try/catch silently fell back
to 1-hour windows for any schedule with a custom end time. Fix parses the
HH:MM parts directly and updates unit tests to use matching HH:MM format.

Also removes a redundant admin.condition on the scheduleField inside
Audiences (the outer collapsible already guards it), updates the OpenAPI
description for appCardsForAudience to mention the conditions AND-gate,
and corrects stale references to deleted files in .claude/rules/openapi.md.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@Ardnived
Ardnived merged commit 835423d into main May 5, 2026
Ardnived added a commit that referenced this pull request Nov 5, 2026
… docs (#348)

scheduleMatch.ts was calling Temporal.Instant.from() on the endTime field,
which scheduleField stores as HH:MM text. The try/catch silently fell back
to 1-hour windows for any schedule with a custom end time. Fix parses the
HH:MM parts directly and updates unit tests to use matching HH:MM format.

Also removes a redundant admin.condition on the scheduleField inside
Audiences (the outer collapsible already guards it), updates the OpenAPI
description for appCardsForAudience to mention the conditions AND-gate,
and corrects stale references to deleted files in .claude/rules/openapi.md.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Ardnived added a commit that referenced this pull request Nov 5, 2026
Ardnived added a commit that referenced this pull request Nov 12, 2026
* test(perf): stop pinning lane counts to the tree and the docs

Every PR that added a spec had to bump the file and test counts in
tests/PERF.md and three or four consumer docs: all 28 commits touching
PERF.md since 2026-10-20 did. The docs now point at PERF.md for counts,
and perf-figures-pinned keeps only the two tier-target checks (#990).

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

* test(unit): derive counts and lists from the source instead of restating them

- atlas-translations-schema: the key and leaf-group counts become floors; 7
  of the case's 10 edits only bumped the exact numbers.
- locales, filterAvailableLocales: compare against LOCALES rather than a
  hand-written 19-code array and length.
- json-field-schemas: validate buildDefaultNotificationPreferences() rather
  than a copy of it.
- admin-locale-urls: drop the call-site count from the header comment.

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

* test(email): assert email structure, and copy only where the wording is the point

- One local renderHtml() per email spec, so a renderEmail return-shape
  change costs one line instead of ~40 call sites (fd18755).
- Sign-in and verify URLs passed in as fixtures are neutral
  (https://cloud.test/x?t=1), not real routes; manager-auth-urls pins the
  real shape. Those literals changed twice (4f0b06a, 8971cc1).
- Copy assertions are kept only where the wording is the contract;
  elsewhere the specs check the href, the locale, or the value present.
- Registration question labels come from EVENT_REGISTRATION_QUESTIONS and
  the key fallback from toWords, not restated strings.

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

* test(openapi): check the custom-endpoint document's structure, not its prose

openapi-custom-endpoints had 24 edits since it was written, and all 11 that
changed existing lines came from renames, copy edits or deleted endpoints,
not from anything it imports. It drops 28 per-endpoint path, parameter and
description assertions (51 cases to 18) and gains structural checks:

- every documented method and path is one the sanitized config registers;
- every $ref resolves to a declared schema or a generated collection one;
- documented root endpoints stay visible in each project spec, and are
  hidden when not declared as root paths, read from the config.

The config-reading cases sit in sanitized-config-rules, which already pays
the ~6.5 s config import, so no new spec loads @/payload.config. Visibility
filtering, the calendar feed's security: [], the transcript hiding, and the
enums sourced from constants keep their cases.

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

* test(int): drop cases that test Payload built-ins or repeat a unit matrix

- audiences, user-choices, pages, meditations: 17 cases asserting plain
  CRUD, required, field defaults or draft status on fields with no hook or
  validate of ours (tests/AGENTS.md: do not test Payload internals).
- meditation-lectures, lectures-for-audience, app-cards-for-audience: the
  empty / non-numeric / normalisation cases for ?audiences, which every
  handler parses with audiencesQueryParamSchema and
  unit/audiences-query-param covers. "missing -> 400" stays in each as the
  wiring proof.
- retention-jobs, event-imports, screen-submissions: one case each that
  repeats a pure unit case with no wiring added.

event-feedback's mixed-verdict case and user-submissions-create's
rich-text scan stay: each is the only int proof of its wiring.

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

* refactor(audiences): delete the unused daytime and schedule matchers

isEventInUserDaytime and isScheduleActiveNow (#348) have no consumer in
src, scripts or seeds; only their own specs imported them, and those specs
still cost edits in type sweeps (cf5e09e). The code and its 28 cases go
together.

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

* test(unit): give firstAddressSegment, composeEventTitle and redeemUrl one home each

- event-title-cache: drop its three helper cases; event-title.spec holds
  the same inputs and outputs, and both were edited together twice.
- manager-signin-urls: its "one redeem route" case was already in
  reminder-button-url; the escaping case moves there and the file goes.

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

* test(transcripts): stop re-running the pure read-along and stall matrices in the mounted tab

activeSegmentIndex's whole-second and pause cases live in
meditation-transcript-model.spec, and the stall bound in
transcript-phase.spec. The jsdom tab keeps one case per wiring: the mark
follows the playhead, sits on the focusable phrase, and the stall notice
appears while mounted (now also asserting the copy names no duration).

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

* test: move three pure int specs to the unit lane

storage-utils (57 cases), cloudflare-stream-webhook (25) and
translations-field (26) never call createTestEnvironment() and need no
.env; each paid the int lane's setup and a fork for pure functions.
tests/AGENTS.md already cited the first two as unit-lane examples.

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

* docs(tests): add rules for keeping specs cheap to change

Five rules aimed at the causes of most spec edits that changed no
behaviour: restated counts and lists, docs quoting lane counts, copy
pinned in many places, the same matrix in several specs, and a call
shape repeated across dozens of sites.

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

* fix(perf): hold the four docs to PERF.md's lane figure

The perf commit dropped the doc-to-PERF.md timing agreement along with the
count pins, but PERF.md still declares itself the single writer of every
timing the three-tier contract states. Nothing then held the four docs' 78 s
to the 77.9 s recorded here, which is the drift #990 was filed for — and
unlike the count pins, this case only reddens on a re-measurement, so it
costs no edit on a PR that adds a spec.

The count pins stay gone.

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

* fix(email): assert the absent event link by structure

`baseProps` carries no `eventUrl`, so `not.toContain(EVENT_URL)` could not
fail however the template behaved — dropping the `eventUrl ?` guard left it
green. The secondary button's own fill and border is the fingerprint instead:
no label is restated, and the variant is only ever this one button.

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

* fix(openapi): check registered endpoints are documented

The structural check held documented ⊆ registered only. The failure the
deleted per-path cases named is the other direction — an endpoint missing
from the hand-written shim is invisible in /api/docs with nothing going red —
and nothing covered it: renaming the geojson path left the lane green.

The rule is derived from the raw collection barrel, so adding an endpoint
needs no new case. Six manager-only endpoints are exempt by name, each
authenticating a manager and accepting no client API key; a second case reds
when an exemption outlives its endpoint.

It is its own file because `buildConfig` mutates those raw configs in place,
appending Payload's 440-odd REST routes, so this must not share a module
graph with `@/payload.config`.

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

---------

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

None yet

Development

Successfully merging this pull request may close these issues.

feat(audiences): split into progress / condition types and add contextual targeting

1 participant