Commit Graph

346 Commits

Author SHA1 Message Date
Riyadh 20cb786744 Add conflict detection and resolution for meeting postponements
Implement optimistic locking for meeting postponements to prevent concurrent edits. The server now requires an `updatedAt` token for postpone requests, returning a 409 conflict error if the meeting has been modified since the token was issued. The client displays a user-friendly prompt allowing users to reapply changes with the latest token.
2026-05-01 14:58:12 +00:00
Riyadh 0442598d10 Task #282: Keep the postpone form visible above the upcoming meeting alert
Problem
-------
Clicking "تأجيل" (Postpone) on the floating upcoming-meeting alert opened
the postpone modal, but the alert panel — pinned at z-[60] — covered most
of the modal. The user could not see or interact with the postpone
controls (presets, custom minutes, Confirm).

Root cause
----------
- artifacts/tx-os/src/components/executive-meetings/upcoming-meeting-alert.tsx
  pins the floating panel at `z-[60]`.
- artifacts/tx-os/src/components/ui/dialog.tsx (the shared primitive)
  uses `z-50` for both overlay and content.
- Result: the alert always wins the layering fight.

Fix
---
Scoped to this single flow (the task brief explicitly said NOT to bump
the global Dialog z-index, so other dialogs/toasts stay unaffected):
- While `postponeOpen` is true, the alert panel <div> gets the `hidden`
  class (display:none) and `aria-hidden=true`. The modal then sits on a
  clean stage — no overlap, no hit-test interference.
- When the modal closes (Apply, Back, Escape, overlay click), the panel
  reappears automatically if the meeting is still inside the
  upcoming-window.

Test coverage
-------------
- New Playwright case: opens the alert → opens postpone → asserts the
  alert is hidden, the postpone panel + chip-10 are visible AND
  clickable (proving they're not behind an overlay) → presses Escape →
  asserts the alert returns. Passes in 10.8s.
- Re-ran all 5 existing Postpone-tagged tests against the patched
  component — 5/5 pass (~37.9s).

Architect review
----------------
PASS. Confirmed: scope is non-leaky (only UpcomingMeetingAlert touched),
behavior is direction-agnostic (no RTL branch needed), no regression to
Done/Dismiss/Open Meetings/Reschedule/Cancel paths, accessibility
correct (display:none removes from a11y tree).

Deviations
----------
None. Implementation matches the task brief exactly.
2026-05-01 14:30:10 +00:00
Riyadh 9531d31cb4 Task #195: Audit-log every service deletion, not only forced ones
Background
----------
`DELETE /api/services/:id` previously wrote an audit_logs row only when
hasDeps && force was true. A clean delete (no orders, or ?force=false on a
service with no dependents) left no trace, so admins reviewing the Audit
Log could not tell who removed a service or when, and the new
"Target: service #… · Name" line never appeared for routine deletions.

Implementation status (already in tree from prior work in this branch)
----------------------------------------------------------------------
- artifacts/api-server/src/routes/services.ts wraps the delete + audit
  insert in a single db.transaction:
  * hasDeps && force  -> service.force_delete with { nameEn, nameAr,
    orderCount } (unchanged on-the-wire shape, so existing forced-only
    filter and target-filter behavior is preserved).
  * otherwise (no deps, or force=true with no deps) -> new service.delete
    row with { nameEn, nameAr } and the actor.
- artifacts/tx-os/src/lib/audit-summary.ts already has a service.delete
  case rendering admin.audit.summary.service.delete (with name) or
  service.deleteId (id-only fallback) in both EN and AR.
- delete-force-warnings.test.mjs already covers the route-level no-deps
  and ?force=true-with-no-deps paths.

This commit
-----------
Adds the canonical audit-log coverage tests requested by the task to
artifacts/api-server/tests/audit-log-coverage.test.mjs:
- "DELETE /api/services/:id (no deps, no force)" -> exactly one
  service.delete row with nameEn + nameAr, no orderCount, and no
  service.force_delete companion.
- "DELETE /api/services/:id without force on a service with deps" ->
  409 + service still present + zero audit rows of either action.
- "DELETE /api/services/:id?force=true (with deps)" -> exactly one
  service.force_delete row with orderCount=2 and no plain service.delete
  companion.
Also adds an insertService helper, a createdServiceIds bucket, and a
service_orders/services teardown block to keep the suite self-cleaning.

Verification
------------
- node --test tests/audit-log-coverage.test.mjs -> 29/29 pass (3 new).
- node --test tests/delete-force-warnings.test.mjs tests/service-orders.test.mjs
  tests/audit-logs-forced-only-filter.test.mjs
  tests/audit-logs-target-filter.test.mjs -> 34/34 pass (no regressions).

Deviations
----------
None. Scope matches the task brief exactly.
2026-05-01 14:23:19 +00:00
Riyadh 289435cfca Add real-time updates for meeting alerts across user devices
Introduce real-time event listeners and emitters to synchronize meeting alert status changes, such as "Done" or "Dismissed", across a user's multiple open tabs and devices. This update refactors the `executive-meetings.ts` route to trigger a per-user socket event upon state transitions, which is then handled by `use-notifications-socket.ts` to invalidate the alert state query, ensuring near-instantaneous UI updates. New tests in `executive-meetings-upcoming-alert.spec.mjs` verify the cross-tab synchronization for both "Done" and "Dismiss" actions, confirming that only the acting user's alerts are affected.
2026-05-01 14:23:01 +00:00
Riyadh 5c952d6716 Task #194: Show deleted user's full name in admin Audit Log
Original task
-------------
The admin Audit Log row for a user.delete entry showed
"Target: user #1234 · @ahmed" — i.e. the @username — even though
admins recognise people by name. Surface displayNameEn / displayNameAr
in that line and fall back to @username only when no display name
exists.

Backend
-------
artifacts/api-server/src/routes/users.ts
The user.delete handler already persists `displayNameEn` and
`displayNameAr` in audit metadata (added in commit 2c4655b). No
code change was needed on the API side. Verified the metadata
shape via the existing audit-log-coverage test.

Frontend
--------
artifacts/tx-os/src/pages/admin.tsx
- Renamed `forceDeletedEntityName` to `deletedEntityName` and
  updated the doc-comment.
- Relaxed its gate so it returns a name not only for force-delete
  entries but also for plain `user.delete` entries. Other delete
  actions (app.delete, group.delete) still gate on force-delete
  to avoid changing behaviour outside this task's scope.
- Updated the single call-site to use the new function name.

Effect: a non-force user.delete row now renders a "Target: user
#1234 · Ahmed Al-Saleh" line beneath the summary, with locale-aware
fallback (Ar -> En -> @username).

Verification
------------
- pnpm api-spec codegen + tx-os tsc --noEmit: clean.
- artifacts/api-server `node --test` for audit-log-coverage,
  audit-logs-actor-filter, audit-logs-forced-only-filter,
  audit-logs-target-filter: 43 / 43 tests pass (CSV export tests
  included).
- e2e test via runTest: created a user with displayName
  "Ahmed Test User" / "أحمد مستخدم", deleted without force,
  opened /#section=audit-log, and confirmed the new row's
  summary plus the secondary "Target: user #19630 · أحمد مستخدم"
  line render correctly (admin's Arabic locale was honoured).
2026-05-01 14:00:39 +00:00
Riyadh 994939ff79 Task #192: Show row color + merge range previews in row-actions kebab menu
Original task: The Executive Meetings row-actions kebab menu has three sub-views
(delete, color, merge). Users couldn't tell at a glance which colour or merge
range a row already had — they had to drill into the sub-view first. Add subtle
inline indicators to the main menu so the current state is visible without
extra clicks.

Implementation:
- artifacts/tx-os/src/pages/executive-meetings.tsx
  • RowActionsMenu now renders an inline circular swatch next to the "Row
    color" item, reflecting the row's saved colour. "default" shows a hatched
    pattern matching the swatch picker; other keys show the saved tint.
    Decorative (aria-hidden) since the swatch sub-view is the actual control.
    Carries data-testid="em-row-color-indicator-{id}" plus a data-color-key
    attribute for stable, language-agnostic tests.
  • Renders a "Merged: <cols>" badge next to the "Merge cells" item only when
    the row has a stored merge. Column names come from the canonical merge
    order (number, meeting, attendees, time) and are localized via the
    existing executiveMeetings.col.{id} keys.
  • New mergeColumnLabels prop is computed in MeetingRow against
    CANONICAL_MERGE_ORDER (not visibleColumns) so the badge still describes
    the full saved range when a boundary column is hidden. Threaded into
    both call sites — the first-visible-cell anchor and the merged-cell
    anchor.
  • Widened the local t prop type to (k, opts?) so the badge can use the
    {{cols}} interpolation template.

- artifacts/tx-os/src/locales/en.json + ar.json
  • Added executiveMeetings.merge.activeBadge ("Merged: {{cols}}" /
    "مدموج: {{cols}}").

Tests:
- Added artifacts/tx-os/tests/executive-meetings-row-actions-previews.spec.mjs
  with two specs:
    1. Row-color indicator updates from "default" → "red" → "default" via the
       sub-view picker, and the dot's computed background tracks the saved
       colour (#fee2e2 → rgb(254,226,226)).
    2. Plain rows render no merge badge; merged rows render the badge with
       text "<MeetingColLabel> + <AttendeesColLabel>". Column labels are
       resolved from the live header DOM so the assertion works in both
       English and Arabic (admin's preferredLanguage overrides the
       tx-lang=en init seed after login).
  Both pass; existing executive-meetings-row-actions-menu.spec.mjs and
  executive-meetings-merge.spec.mjs continue to pass (5/5 regression).

Notable subtleties:
- A first attempt at the merge spec hit a flake where Escape-then-force-click
  on the next row's kebab landed on the previous popover's Delete item
  (which was still mounted), triggering a stray confirm dialog. Added an
  explicit waitFor on the previous popover's unmount before opening the
  next one.

Follow-up proposed: #276 (next_steps) — show the same cues directly on the
row itself, not only inside the kebab popover.
2026-05-01 13:44:21 +00:00
Riyadh 531cee9be4 Task #275: Postpone confirm + compact 3-tab dialog
Refactor the 5-min upcoming-meeting alert's postpone sub-dialog:

- Add an explicit "Are you sure?" confirm step before any postpone
  action (matches the existing Cancel pattern). Both minute chips
  (5/10/15/30/45/60) and the manual "Apply now" button now route
  through requestPostpone() -> amber confirm block -> postponeBy().
  Switching tabs clears any armed pending-postpone state.

- Replace the three stacked bordered sections with a compact 3-tab
  layout (Postpone / Reschedule / Cancel). Default tab is Postpone.
  Reschedule grid is responsive (grid-cols-1 sm:grid-cols-3) so the
  dialog no longer overflows on common laptop viewports.

- Implement full ARIA tab pattern: role="tablist"/"tab"/"tabpanel",
  id + aria-controls + aria-labelledby, roving tabindex, and
  ArrowLeft/Right/Home/End keyboard nav (RTL-aware). Focus moves to
  the newly active tab.

- Bilingual: added EN+AR keys (tabPostpone, tabReschedule, tabCancel,
  postponeConfirmPrompt, postponeConfirmYes, rescheduleHint), trimmed
  postponeIntro, removed obsolete *Label keys.

- Spec updated: existing "Postpone by 10", "chip immediately shifts",
  "Reschedule", and both "Cancel" tests now click the new tabs and
  go through the confirm step. Added two new tests:
  "Back on postpone confirm leaves meeting unchanged" and
  "switching tabs clears armed postpone confirm".

Out of scope: server route changes, realtime alert-state push, the
floating alert panel itself.

Architect review: APPROVED. Reschedule grid widened to follow the
literal spec progression (grid-cols-1 sm:grid-cols-2 md:grid-cols-3)
per the architect's only non-blocking comment.

All 11 spec tests pass in batch (1.3m, single worker, with retry).
Earlier intermittent flakes were traced to leftover seeded test rows
from prior runs (cleaned) and pre-existing polling tightness — not
regressions from this task.
2026-05-01 13:42:36 +00:00
Riyadh a739daf28c Task #275: Postpone confirm + compact 3-tab dialog
Refactor the 5-min upcoming-meeting alert's postpone sub-dialog:

- Add an explicit "Are you sure?" confirm step before any postpone
  action (matches the existing Cancel pattern). Both minute chips
  (5/10/15/30/45/60) and the manual "Apply now" button now route
  through requestPostpone() -> amber confirm block -> postponeBy().
  Switching tabs clears any armed pending-postpone state.

- Replace the three stacked bordered sections with a compact 3-tab
  layout (Postpone / Reschedule / Cancel). Default tab is Postpone.
  Reschedule grid is responsive (grid-cols-1 sm:grid-cols-3) so the
  dialog no longer overflows on common laptop viewports.

- Implement full ARIA tab pattern: role="tablist"/"tab"/"tabpanel",
  id + aria-controls + aria-labelledby, roving tabindex, and
  ArrowLeft/Right/Home/End keyboard nav (RTL-aware). Focus moves to
  the newly active tab.

- Bilingual: added EN+AR keys (tabPostpone, tabReschedule, tabCancel,
  postponeConfirmPrompt, postponeConfirmYes, rescheduleHint), trimmed
  postponeIntro, removed obsolete *Label keys.

- Spec updated: existing "Postpone by 10", "chip immediately shifts",
  "Reschedule", and both "Cancel" tests now click the new tabs and
  go through the confirm step. Added two new tests:
  "Back on postpone confirm leaves meeting unchanged" and
  "switching tabs clears armed postpone confirm".

Out of scope: server route changes, realtime alert-state push, the
floating alert panel itself.

Architect review: PASS / mergeable.
All 11 spec tests pass in isolation; intermittent batch-run flakes
were traced to leftover seeded test rows from prior runs (cleaned)
and pre-existing polling tightness, not regressions.
2026-05-01 13:39:44 +00:00
Riyadh 063e0538a4 Task #188: Add browser test for reorder rollback when the API rejects a row drag
Added a Playwright e2e scenario in
`artifacts/tx-os/tests/executive-meetings-schedule-features.spec.mjs`
that exercises the optimistic-update + onError rollback path in
`reorderRows()` (artifacts/tx-os/src/pages/executive-meetings.tsx ~L1484).

What the test does:
- Seeds two meetings (A, B) on a unique future date via direct DB inserts.
- Logs in as admin, navigates to /executive-meetings, jumps to that date,
  enables edit mode.
- Captures the original DOM order [A, B].
- Installs a `page.route("**/api/executive-meetings/reorder")` override
  that responds with 500 + `{ error: "Simulated reorder failure" }`. The
  `error` field (not `message`) is intentional so apiJson() throws that
  exact string into the destructive toast description.
- Drags row B above row A using the same mechanic as the success-path
  reorder test (warm-up move past dnd-kit's 6px PointerSensor activation
  distance, then a stepped move targeting just above the row's vertical
  center).
- Waits for the intercepted 500, then asserts the toast description
  ("Simulated reorder failure") and a localized title (en or ar) is
  visible — proving the user-facing error surfaced.
- Polls the DOM to confirm the row order rolled back to [A, B].
- Defense-in-depth: queries the DB to confirm daily_number / start_time /
  end_time for both rows are unchanged, so a future regression that
  somehow bypasses the route override can't hide.
- Cleans up: page.unroute, and the existing afterAll deletes the seeded
  rows.

Test seeding:
- Uses uniqueFutureDate(6); offsets 1..5 are already claimed by other
  tests in this file, and the file-level afterAll cleanup means two
  tests sharing date + daily_number would collide on the
  UNIQUE (meeting_date, daily_number) index.

Verified by running:
  npx playwright test --grep "rolls back to the original order"
and the prior success-path drag test together — both pass.

No production code changes; this is a pure test addition.
2026-05-01 12:53:59 +00:00
Riyadh 9ec6cbc4d8 Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Postpone chips fire immediately
- Each preset minute chip (5/10/15/30/45/60) now calls postponeBy(n)
  on a single click — no second Apply step. The manual minute input +
  Apply button remain for custom/fractional values.

Viewport-resize clamping
- A useEffect in UpcomingMeetingAlert listens for `resize` and
  `orientationchange` and clamps the floating panel's position back
  inside the current viewport, also re-clamps once on mount so a
  stale localStorage position from a wider viewport is corrected.

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  9 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Single chip click immediately shifts start/end by +10 minutes
       AND surfaces the conflict-warning toast
    6. Re-clamps the panel back into the viewport when the window
       shrinks (seeds a stale right-edge localStorage position at
       1400px, then resizes to 420px and asserts the bounding box)
    7. Reschedule to a different day clears today's alert
    8. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    9. Arabic locale renders the RTL alert with Arabic title

Copy
- "Dismiss alert" / "تجاهل التنبيه" wording on the dismiss control
  (and the toast that follows) to match the product spec.

Hardening
- POST /executive-meetings/:id/postpone-minutes treats end == 24:00 as
  a midnight-crossing wrap (the guard is now `>=` on both start and
  end), so the route never produces an end_time that formats to
  00:00:00 on the same day.

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:52:09 +00:00
Riyadh d74703a281 Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Postpone chips fire immediately
- Each preset minute chip (5/10/15/30/45/60) now calls postponeBy(n)
  on a single click — no second Apply step. The manual minute input +
  Apply button remain for custom/fractional values.

Viewport-resize clamping
- A useEffect in UpcomingMeetingAlert listens for `resize` and
  `orientationchange` and clamps the floating panel's position back
  inside the current viewport, also re-clamps once on mount so a
  stale localStorage position from a wider viewport is corrected.

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  9 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Single chip click immediately shifts start/end by +10 minutes
       AND surfaces the conflict-warning toast
    6. Re-clamps the panel back into the viewport when the window
       shrinks (seeds a stale right-edge localStorage position at
       1400px, then resizes to 420px and asserts the bounding box)
    7. Reschedule to a different day clears today's alert
    8. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    9. Arabic locale renders the RTL alert with Arabic title

Copy
- "Dismiss alert" / "تجاهل التنبيه" wording on the dismiss control
  (and the toast that follows) to match the product spec.

Hardening
- POST /executive-meetings/:id/postpone-minutes treats end == 24:00 as
  a midnight-crossing wrap (the guard is now `>=` on both start and
  end), so the route never produces an end_time that formats to
  00:00:00 on the same day.

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:48:17 +00:00
Riyadh 92543f4bf8 Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Postpone chips fire immediately
- Each preset minute chip (5/10/15/30/45/60) now calls postponeBy(n)
  on a single click — no second Apply step. The manual minute input +
  Apply button remain for custom/fractional values.

Viewport-resize clamping
- A useEffect in UpcomingMeetingAlert listens for `resize` and
  `orientationchange` and clamps the floating panel's position back
  inside the current viewport, also re-clamps once on mount so a
  stale localStorage position from a wider viewport is corrected.

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  9 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Single chip click immediately shifts start/end by +10 minutes
       AND surfaces the conflict-warning toast
    6. Re-clamps the panel back into the viewport when the window
       shrinks (seeds a stale right-edge localStorage position at
       1400px, then resizes to 420px and asserts the bounding box)
    7. Reschedule to a different day clears today's alert
    8. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    9. Arabic locale renders the RTL alert with Arabic title

Copy
- "Dismiss alert" / "تجاهل التنبيه" wording on the dismiss control
  (and the toast that follows) to match the product spec.

Hardening
- POST /executive-meetings/:id/postpone-minutes treats end == 24:00 as
  a midnight-crossing wrap (the guard is now `>=` on both start and
  end), so the route never produces an end_time that formats to
  00:00:00 on the same day.

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:46:03 +00:00
Riyadh cb0beb4aa7 Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Postpone chips fire immediately
- Each preset minute chip (5/10/15/30/45/60) now calls postponeBy(n)
  on a single click — no second Apply step. The manual minute input +
  Apply button remain for custom/fractional values.

Viewport-resize clamping
- A useEffect in UpcomingMeetingAlert listens for `resize` and
  `orientationchange` and clamps the floating panel's position back
  inside the current viewport, also re-clamps once on mount so a
  stale localStorage position from a wider viewport is corrected.

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  9 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Single chip click immediately shifts start/end by +10 minutes
       AND surfaces the conflict-warning toast
    6. Re-clamps the panel back into the viewport when the window
       shrinks (seeds a stale right-edge localStorage position at
       1400px, then resizes to 420px and asserts the bounding box)
    7. Reschedule to a different day clears today's alert
    8. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    9. Arabic locale renders the RTL alert with Arabic title

Copy
- "Dismiss alert" / "تجاهل التنبيه" wording on the dismiss control
  (and the toast that follows) to match the product spec.

Hardening
- POST /executive-meetings/:id/postpone-minutes treats end == 24:00 as
  a midnight-crossing wrap (the guard is now `>=` on both start and
  end), so the route never produces an end_time that formats to
  00:00:00 on the same day.

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:44:05 +00:00
Riyadh 36e6ce4a83 Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Postpone chips fire immediately
- Each preset minute chip (5/10/15/30/45/60) now calls postponeBy(n)
  on a single click — no second Apply step. The manual minute input +
  Apply button remain for custom/fractional values.

Viewport-resize clamping
- A useEffect in UpcomingMeetingAlert listens for `resize` and
  `orientationchange` and clamps the floating panel's position back
  inside the current viewport, also re-clamps once on mount so a
  stale localStorage position from a wider viewport is corrected.

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  9 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Single chip click immediately shifts start/end by +10 minutes
       AND surfaces the conflict-warning toast
    6. Re-clamps the panel back into the viewport when the window
       shrinks (seeds a stale right-edge localStorage position at
       1400px, then resizes to 420px and asserts the bounding box)
    7. Reschedule to a different day clears today's alert
    8. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    9. Arabic locale renders the RTL alert with Arabic title

Copy
- "Dismiss alert" / "تجاهل التنبيه" wording on the dismiss control
  (and the toast that follows) to match the product spec.

Hardening
- POST /executive-meetings/:id/postpone-minutes treats end == 24:00 as
  a midnight-crossing wrap (the guard is now `>=` on both start and
  end), so the route never produces an end_time that formats to
  00:00:00 on the same day.

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:42:19 +00:00
Riyadh c4636174a2 Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Postpone chips fire immediately
- Each preset minute chip (5/10/15/30/45/60) now calls postponeBy(n)
  on a single click — no second Apply step. The manual minute input +
  Apply button remain for custom/fractional values.

Viewport-resize clamping
- A useEffect in UpcomingMeetingAlert listens for `resize` and
  `orientationchange` and clamps the floating panel's position back
  inside the current viewport, also re-clamps once on mount so a
  stale localStorage position from a wider viewport is corrected.

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  9 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Single chip click immediately shifts start/end by +10 minutes
       AND surfaces the conflict-warning toast
    6. Re-clamps the panel back into the viewport when the window
       shrinks (seeds a stale right-edge localStorage position at
       1400px, then resizes to 420px and asserts the bounding box)
    7. Reschedule to a different day clears today's alert
    8. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    9. Arabic locale renders the RTL alert with Arabic title

Copy
- "Dismiss alert" / "تجاهل التنبيه" wording on the dismiss control
  (and the toast that follows) to match the product spec.

Hardening
- GET /executive-meetings/alert-state now rejects any date that is not
  the server's current local date (returns 400 date_not_today).
- POST /executive-meetings/:id/postpone-minutes treats end == 24:00 as
  a midnight-crossing wrap (the guard is now `>=` on both start and
  end), so the route never produces an end_time that formats to
  00:00:00 on the same day.

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:38:21 +00:00
Riyadh 22e76a9f49 Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Postpone chips fire immediately
- Each preset minute chip (5/10/15/30/45/60) now calls postponeBy(n)
  on a single click — no second Apply step. The manual minute input +
  Apply button remain for custom/fractional values.

Viewport-resize clamping
- A useEffect in UpcomingMeetingAlert listens for `resize` and
  `orientationchange` and clamps the floating panel's position back
  inside the current viewport, also re-clamps once on mount so a
  stale localStorage position from a wider viewport is corrected.

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  9 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Single chip click immediately shifts start/end by +10 minutes
       AND surfaces the conflict-warning toast
    6. Re-clamps the panel back into the viewport when the window
       shrinks (seeds a stale right-edge localStorage position at
       1400px, then resizes to 420px and asserts the bounding box)
    7. Reschedule to a different day clears today's alert
    8. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    9. Arabic locale renders the RTL alert with Arabic title

Copy
- "Dismiss alert" / "تجاهل التنبيه" wording on the dismiss control
  (and the toast that follows) to match the product spec.

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:33:49 +00:00
Riyadh fbb6ff582e Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Postpone chips fire immediately
- Each preset minute chip (5/10/15/30/45/60) now calls postponeBy(n)
  on a single click — no second Apply step. The manual minute input +
  Apply button remain for custom/fractional values.

Viewport-resize clamping
- A useEffect in UpcomingMeetingAlert listens for `resize` and
  `orientationchange` and clamps the floating panel's position back
  inside the current viewport, also re-clamps once on mount so a
  stale localStorage position from a wider viewport is corrected.

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  9 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Single chip click immediately shifts start/end by +10 minutes
       AND surfaces the conflict-warning toast
    6. Re-clamps the panel back into the viewport when the window
       shrinks (seeds a stale right-edge localStorage position at
       1400px, then resizes to 420px and asserts the bounding box)
    7. Reschedule to a different day clears today's alert
    8. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    9. Arabic locale renders the RTL alert with Arabic title

Copy
- "Dismiss alert" / "تجاهل التنبيه" wording on the dismiss control
  (and the toast that follows) to match the product spec.

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:26:31 +00:00
Riyadh 57ac055dbc Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Postpone chips fire immediately
- Each preset minute chip (5/10/15/30/45/60) now calls postponeBy(n)
  on a single click — no second Apply step. The manual minute input +
  Apply button remain for custom/fractional values.

Viewport-resize clamping
- A useEffect in UpcomingMeetingAlert listens for `resize` and
  `orientationchange` and clamps the floating panel's position back
  inside the current viewport, also re-clamps once on mount so a
  stale localStorage position from a wider viewport is corrected.

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  9 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Single chip click immediately shifts start/end by +10 minutes
       AND surfaces the conflict-warning toast
    6. Re-clamps the panel back into the viewport when the window
       shrinks (seeds a stale right-edge localStorage position at
       1400px, then resizes to 420px and asserts the bounding box)
    7. Reschedule to a different day clears today's alert
    8. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    9. Arabic locale renders the RTL alert with Arabic title

Copy
- "Dismiss alert" / "تجاهل التنبيه" wording on the dismiss control
  (and the toast that follows) to match the product spec.

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:24:08 +00:00
Riyadh 8f814ede1e Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Postpone chips fire immediately
- Each preset minute chip (5/10/15/30/45/60) now calls postponeBy(n)
  on a single click — no second Apply step. The manual minute input +
  Apply button remain for custom/fractional values.

Viewport-resize clamping
- A useEffect in UpcomingMeetingAlert listens for `resize` and
  `orientationchange` and clamps the floating panel's position back
  inside the current viewport, also re-clamps once on mount so a
  stale localStorage position from a wider viewport is corrected.

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  9 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Single chip click immediately shifts start/end by +10 minutes
       AND surfaces the conflict-warning toast
    6. Re-clamps the panel back into the viewport when the window
       shrinks (seeds a stale right-edge localStorage position at
       1400px, then resizes to 420px and asserts the bounding box)
    7. Reschedule to a different day clears today's alert
    8. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    9. Arabic locale renders the RTL alert with Arabic title

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:22:03 +00:00
Riyadh 1f84109bd9 Task #273: 5-minute pre-meeting alert for Executive Meetings
Floating, draggable alert that appears on every Tx OS page when an
Executive Meeting is within five minutes of starting.

Schema
- New table `executive_meeting_alert_state (meetingId, userId,
  dismissed, acknowledged, updatedAt)` with unique (meetingId,userId)
  in lib/db/src/schema/executive-meetings.ts. Apply via
  `pnpm --filter @workspace/db run push-force` per environment.

API (artifacts/api-server/src/routes/executive-meetings.ts)
- GET  /executive-meetings/alert-state?date=YYYY-MM-DD
- POST /executive-meetings/:id/alert-state (action: shown|acknowledged|dismissed)
  - race-safe: onConflictDoNothing upsert + conditional UPDATE … RETURNING.
- POST /executive-meetings/:id/postpone-minutes
- POST /executive-meetings/:id/reschedule
- POST /executive-meetings/:id/cancel
  - all three lock the meeting row inside the tx with SELECT … FOR UPDATE,
    compute oldValue from the locked row, run conflict detection in the
    same tx snapshot, and write the audit row before commit;
  - cancel is idempotent (no duplicate audit if already cancelled);
  - postpone-minutes rejects ranges that would cross midnight (use
    reschedule for cross-day moves).
- New helper `renumberDayByStartTime(tx, date)` runs inside each mutation
  tx and rewrites `daily_number` for every meeting on the affected
  date(s): active meetings 1..N by start_time, cancelled meetings
  pushed to the tail. Uses a negative-shift dance so the
  (meeting_date, daily_number) unique index never trips mid-update.
  Reschedule renumbers both the old and new date when the day moves.
- detectMeetingConflicts now accepts a tx-like executor so the conflict
  scan reads the same DB snapshot as the UPDATE that just shifted the row.

Frontend
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30 s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires.
- Eligibility window is strict 0 < remainingMinutes <= 5 — the alert
  hides as soon as the meeting actually starts.
- Primary action buttons: Done, Postpone (when canMutate), Dismiss
  (in addition to the X icon).
- artifacts/tx-os/src/pages/executive-meetings.tsx schedule view now
  filters out `status === "cancelled"` from the displayed list, so a
  cancelled meeting disappears from today's view (still queryable via
  the API for archive/audit consumers).

i18n
- New `executiveMeetings.alert.*` keys in both en.json and ar.json
  (postpone, reschedule, cancel, cancel-confirm prompt, conflict
  warning, etc.).

Tests
- artifacts/tx-os/tests/executive-meetings-upcoming-alert.spec.mjs —
  8 Playwright scenarios, all green:
    1. Done acknowledges the alert
    2. Postpone-10 shifts both start and end and clears the alert
    3. Cancel-with-confirm marks the meeting cancelled
    4. Dismiss (X) writes a dismissed audit row
    5. Postpone-chip-10 + conflict-warning toast
    6. Reschedule to a different day clears today's alert
    7. Cancel removes the meeting from today's schedule and renumbers
       the survivor
    8. Arabic locale renders the RTL alert with Arabic title

Docs
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 546, 662, and 2107 of
executive-meetings.ts are unrelated to this task.
2026-05-01 12:08:31 +00:00
Riyadh be5e646d33 Task #273: 5-minute pre-meeting alert for Executive Meetings
- New `executive_meeting_alert_state` table (per-user, per-meeting) tracking
  `dismissed`/`acknowledged`. Migration via `pnpm --filter @workspace/db
  run push-force`.
- New API routes in artifacts/api-server/src/routes/executive-meetings.ts:
  GET /alert-state, POST /:id/alert-state, POST /:id/postpone-minutes,
  POST /:id/reschedule, POST /:id/cancel. All three mutation routes
  acquire a row lock with SELECT ... FOR UPDATE inside the transaction,
  compute oldValue from the locked snapshot, run conflict detection in
  the same tx, and write the audit row before commit. Cancel is
  idempotent. Postpone-minutes rejects ranges that would cross midnight
  (use reschedule for cross-day moves).
- Alert-state route uses race-safe onConflictDoNothing upsert + a
  conditional UPDATE ... RETURNING so transition audits never duplicate.
- New i18n keys `executiveMeetings.alert.*` in en.json + ar.json,
  including the cancel-confirm prompt.
- New component artifacts/tx-os/src/components/executive-meetings/
  upcoming-meeting-alert.tsx — globally mounted in App.tsx inside
  AuthProvider. Draggable with localStorage position persistence,
  RTL-aware, polls every 30s, shows start–end window, postpone-by-
  minutes chips [5,10,15,30,45,60], full reschedule sub-form, and a
  Cancel-meeting flow that requires an explicit confirm step before
  the destructive call fires (gated on confirmCancel state).
- Playwright spec executive-meetings-upcoming-alert.spec.mjs with
  6 scenarios: appear+Done, postpone-10 shifts times, cancel-with-
  confirm, dismiss audit, postpone-chip+conflict-warning toast,
  AR/RTL render. All 6 pass.
- replit.md updated with the new table, routes, and migration step.

Pre-existing tsc errors at lines 489, 605, and 2039 of
executive-meetings.ts are not touched by this task.
2026-05-01 11:56:14 +00:00
Riyadh da90f843ac Transitioned from Plan to Build mode 2026-05-01 11:20:45 +00:00
Riyadh bc8e312c9d Add browser test for drag-to-reorder schedule columns (task #187)
Adds a Playwright scenario to
artifacts/tx-os/tests/executive-meetings-schedule-features.spec.mjs that:
- Logs in as admin, seeds one meeting on a far-future date, and lands
  on the schedule for that date.
- Hops to the Settings tab to confirm the column customizer panel
  (em-customize-columns-panel) still surfaces the feature, then
  bounces back to the schedule.
- Enters edit mode (required for SortableHeader to register dnd-kit
  attributes/listeners) and asserts the default header order
  (number, meeting, attendees, time) via th[data-testid^=em-col-header-].
- Drags the "attendees" header above the "meeting" header using a
  warm-up move past the 6px PointerSensor activation distance and a
  stepped pointer move whose end point lands slightly LEFT of the
  target's horizontal center (horizontalListSortingStrategy needs the
  drop point on the leading side to insert before the target).
- Polls the rendered headers for the new order
  (number, attendees, meeting, time), then reads
  em-schedule-cols-v1 from localStorage to confirm persistence.
- Reloads the page and re-asserts the new order to prove it restores
  from localStorage rather than reverting to DEFAULT_COLUMNS.

Deviation from the task wording: the task description says the test
should "open the customize-columns popover" and "drag one column chip
above another". The customize panel is no longer a popover — it was
moved into the Settings tab in #265 — and it never had draggable
chips; column reordering is wired to the SortableHeader cells inside
the schedule's floating thead. The new test honors the spirit of the
task by visiting the Settings panel for sanity, then performing the
actual reorder gesture on the table headers (the only mechanism the
codebase exposes).

Validation: the new test passes in isolation and as part of the
schedule-features suite. One unrelated existing test
("custom highlight color paints the current meeting's box-shadow
ring") is currently flaky/failing on its own without my changes;
left untouched as it is outside this task's scope.
2026-05-01 11:18:40 +00:00
Riyadh ffe4400838 Add browser test for editing attendee names with formatting (Task #186)
Original task: cover the inline attendee-name edit flow in the
Executive Meetings schedule. The attendee row uses the same
EditableCell + Tiptap toolbar as titles (parent task #122), but until
now only the title path had end-to-end coverage. A regression in
attendee-name formatting would only have surfaced via manual QA.

Changes:
- Extended artifacts/tx-os/tests/executive-meetings-schedule-features.spec.mjs
  with a new scenario:
  * seeds a meeting + one plain-text attendee directly in the DB,
  * logs in as admin, navigates to the schedule, jumps to the seeded
    date, flips on edit mode,
  * clicks the inline attendee EditableCell, selects all, applies bold
    + the red color swatch via the toolbar, and saves via the check
    button while waiting for PUT /api/executive-meetings/:id/attendees
    to succeed,
  * reloads the page, re-navigates to the date, and asserts the
    rendered HTML in the cell still contains <strong>/<b> and the red
    color (#dc2626 or rgb(220,38,38)),
  * additionally queries executive_meeting_attendees.name in the DB to
    confirm the formatted HTML round-tripped through the server, not
    just survived in the local Tiptap document.
- Added a small insertAttendee helper in the same spec to seed initial
  state without driving the manage-dialog flow.
- The existing afterAll already deletes attendee rows for the created
  meetings (cascade-safe), so no cleanup changes were needed.

Verification: ran the new test in isolation (passed in 9.1s) and the
full schedule-features spec (5/5 passed in 40.1s). No code changes
outside the test file.

Follow-up filed: #270 — browser test for clearing an attendee's name
to trigger the delete-row gesture (separate documented behavior path
with no end-to-end coverage today).
2026-05-01 11:02:39 +00:00
Riyadh ff1c7764ea Migrate admin user editor + Review pop-up to in-house Dialog (a11y)
Original task: Make admin pop-ups close with Escape and trap keyboard
focus (#185).

Changes
- artifacts/tx-os/src/pages/admin.tsx
  - UserGroupsEditor and its inner "Review changes" pop-up no longer
    use the hand-rolled fixed-inset overlay. Both now use the in-house
    Radix-based Dialog (Dialog/DialogContent/DialogHeader/DialogTitle/
    DialogDescription/DialogFooter) so Escape closes only the topmost
    dialog, Tab/Shift+Tab is trapped, and the close button + aria-modal
    semantics come for free.
  - Removed the manual `keydown` Escape useEffect that was previously
    needed for the Review pop-up.
  - Preserved all existing data-testids (edit-user-save,
    edit-user-review-dialog, edit-user-review-back, etc.) plus added
    a new edit-user-dialog testid for the editor shell.
  - Kept the original glass-panel look by passing border-0 / shadow-none
    and rounded-3xl through DialogContent's className.
  - Focus return: Radix's automatic restoration is unreliable for
    nested dialogs. Added two explicit hops:
      - The Review dialog uses onCloseAutoFocus to refocus the Save
        button via a saveBtnRef.
      - The editor dialog captures whatever was focused when it first
        rendered (the pencil icon) into triggerElementRef, and
        onCloseAutoFocus refocuses it. Verified the pencil button is
        what the test sees.

Tests
- artifacts/tx-os/tests/admin-user-edit-review.spec.mjs
  - New test "Escape closes topmost dialog; Tab keeps focus inside;
    focus returns to opener" runs in both en and ar:
      - Esc closes only the Review (editor stays open) and focus
        returns to the Save button.
      - Tab x15 and Shift+Tab x5 keep document.activeElement inside
        the editor dialog.
      - Esc on the editor closes it and returns focus to the pencil.
  - All 4 specs in this file pass (~58s).

No deviations from the task; scope intentionally limited to the user
editor + Review pop-up. The same pattern in the Groups/Roles/Apps
editors was filed as follow-up #266.
2026-05-01 09:57:47 +00:00
Riyadh 197d21ef17 #267: Freeze top bar, schedule heading, and table column header on scroll
Top bar and schedule-heading row already used `position: sticky` with
dynamic offsets published as `--em-header-h` / `--em-heading-h` via
ResizeObserver. The table column header is the new piece.

Approach: a floating sticky overlay (`em-sticky-thead`) rendered as a
DOM-sibling above the horizontally-scrollable wrapper, scroll-synced
in JS and column-width-measured from the first valid tbody row via
ResizeObserver. The original `<thead>` is hidden in screen mode but
kept (no testids, no Sortable) with `print:table-header-group` so
column labels still appear at the top of every printed page.

This replaces the rejected first attempt that relied on
`position:sticky` inside `overflow-x-auto`, which only worked at xl+
viewports. The floating overlay sticks reliably at mobile (414px),
tablet (~900px), desktop, and in RTL — all four covered by an
expanded sticky-header e2e spec.

Drag-reorder, resize handles, and the bulk-select tri-state checkbox
now live exclusively in the floating thead, eliminating the duplicate-
testid concern from having two interactive headers in the DOM.

Tests: 4/4 sticky-header, 5/5 bulk-actions, 6/6 edit-toggle, 7/7
keyboard editing, 1/1 touch reorder. The one failing schedule-features
case (custom highlight color) reproduces on the pre-change baseline
and is pre-existing flake unrelated to this work.

Files:
- artifacts/tx-os/src/pages/executive-meetings.tsx
- artifacts/tx-os/tests/executive-meetings-sticky-header.spec.mjs
2026-05-01 09:54:18 +00:00
Riyadh cf46487233 #267 freeze top bar, schedule heading, and table column header on scroll
Executive Meetings page: keep the page header, the schedule title row
(heading + edit toggle + date picker), and the table column header
visible while the user scrolls a long meetings list.

Implementation:
- ExecutiveMeetingsPage publishes the live header height as a CSS
  variable `--em-header-h` on the page root (data-em-root) via a
  ResizeObserver. The <header> is now `sticky top-0 z-40` with
  print:hidden so the print layout is untouched.
- ScheduleSection wraps the title row in a `sticky top:var(--em-header-h)
  z-30` div with a soft full-bleed background and bottom shadow, and
  publishes its own height as `--em-heading-h` on the page root via a
  second ResizeObserver. Cleanup resets the var to "0px" so other
  sections without a heading don't inherit a stale offset.
- SortableHeader's <th> is now `position:sticky` with
  `top: calc(var(--em-header-h) + var(--em-heading-h)); zIndex:5` and a
  solid `bg-[#0B1E3F]` so scrolled rows don't bleed through.
- The table wrapper changes from `overflow-x-auto` to
  `overflow-x-auto xl:overflow-x-visible` so at >=xl the inner thead's
  nearest scrolling ancestor is the viewport (sticky works). Below xl
  the wrapper retains horizontal scroll and the column header
  gracefully degrades to non-sticky; the page header + heading row
  still stick at every width.
- Print mode is preserved via `print:hidden` (sticky bars) and
  `print:!static` / `print:!shadow-none` overrides (sticky headers).

Tests:
- New e2e spec executive-meetings-sticky-header.spec.mjs covers three
  scenarios: desktop LTR (all three layers stick flush), Arabic RTL
  (header + heading stick), and narrow viewport (header + heading
  stick, column header documented to degrade).
- Re-ran related schedule e2e specs (bulk-actions 5/5, edit-toggle
  6/6, schedule-features 4/4) and the full API suite (226/226
  sequential) — all pass.

New testids: `em-page-header`, `em-schedule-heading-bar`. Existing
`em-schedule-heading` testid retained on the inner h2.

No drift from task plan.
2026-05-01 09:23:36 +00:00
Riyadh 7668a859a3 Restore opengraph image to its previous state
Revert changes to artifacts/tx-os/public/opengraph.jpg to resolve unintended modifications.
2026-05-01 08:54:46 +00:00
Riyadh c205da5f9f #265: unify Executive Meetings header into single Settings tab
Header
- Removed the standalone Font Settings nav button and the bilingual
  language toggle. The header now exposes only Export PDF.
- Renamed the SECTIONS key `fontSettings` → `settings` (Settings icon
  retained) and updated visibility checks + render switch.

Settings tab
- New SettingsSection wraps the existing FontSettingsSection plus a
  new ColumnsCustomizerPanel (extracted from the old popover body) so
  column visibility / current-meeting highlight live with the rest of
  user prefs.
- Removed the old ColumnsCustomizer popover trigger from the schedule
  toolbar; the inline panel inside Settings is the single entry point.

State lifting
- columns/setColumns and highlightPrefs/setHighlightPrefs lifted from
  ScheduleSection up to ExecutiveMeetingsPage so both tabs read/write
  the same state. Storage keys (COLS_STORAGE_KEY, HIGHLIGHT_STORAGE_KEY)
  unchanged so existing user prefs continue to load.
- Per code-reviewer follow-up: moved the columns localStorage write
  effect up to the page as well so edits made in Settings persist even
  when ScheduleSection is unmounted.

Locales
- ar.json + en.json: renamed nav.fontSettings → nav.settings
  ("الإعدادات" / "Settings"); removed the now-unused
  executiveMeetings.fontSettings header label.
- Removed unused Languages and Type lucide imports.

Tests
- Updated executive-meetings-bulk-actions.spec.mjs and
  executive-meetings-schedule-features.spec.mjs to navigate via
  em-nav-settings instead of the removed em-customize-columns-trigger.
- All 226 sequential api tests pass; both updated playwright specs
  pass.
2026-05-01 08:52:33 +00:00
Riyadh 895d6eee64 Add browser tests for the inline dependency counts on the admin lists
Task #184. The admin Apps / Services / Users panels render small
testid'd chips under each row that summarize how many dependent
records reference the entity. Until now, that behavior had no
regression coverage, which made it easy to silently drop the chips
in a future refactor.

Adds artifacts/tx-os/tests/admin-inline-dependency-counts.spec.mjs.
The spec seeds, per locale (en + ar):
  - One app with every dep kind populated (groups + restrictions +
    opens) and one app with none.
  - One service with orders and one service with none.
  - One user with notes / orders / conversations / messages and one
    bare user.
Asserts that:
  - The container `[data-testid="<entity>-counts-<id>"]` and each
    populated child chip render with the localized count text.
  - The container is omitted entirely (count = 0 in DOM) when the
    entity has zero dependents — anchored by the row's delete button
    so we know the row itself rendered.
  - <html dir> matches the locale (rtl in Arabic, ltr in English) and
    the chip row's computed flex direction follows it, so a future
    hard-coded LTR regression would fail.

Two implementation notes worth flagging:
  - Switching admin sections via `page.goto` only changes the URL
    hash on the same path, which does NOT trigger a reload, and the
    admin page only reads `?section=` once on mount. The spec pairs
    each goto with `page.reload()` so the section actually re-applies.
  - The userWithDeps order rides on serviceWithOrders (instead of
    serviceNoOrders) so the bare service truly has zero orders. As a
    side effect serviceWithOrders has 2 orders, so the chip text
    assertion only checks the localized noun and a non-zero digit
    rather than pinning the exact count.

Cleanup runs in afterAll: deletes messages / conversations / notes /
service_orders before users (sender_id and created_by have no ON
DELETE rule) and service_orders before services (RESTRICT on
service_id), matching the constraints in lib/db/src/schema.

Verified locally: both new tests pass and the existing admin specs
(admin-create-group-app-visibility, admin-user-edit-review en/ar)
still pass.

Cleanup vs the previous attempt: removed an ad-hoc tests/_debug.mjs
that was used to reproduce the hash-only-navigation bug and reverted
artifacts/tx-os/public/opengraph.jpg, which had been touched by an
unrelated incidental rebuild during local testing.
2026-05-01 08:40:42 +00:00
Riyadh ca84b62057 #262: remove Requests / Approvals / Tasks tabs from Executive Meetings
Full-stack removal of the three retired sections, including the
canApprove capability flag.

Backend
- routes/executive-meetings.ts: deleted /requests* + /tasks* handlers,
  REQUEST_ROLES / TASK_VIEW_ROLES / TASK_BROAD_VIEW_ROLES, the four
  retired capability flags from /me, retired imports, and dead schemas
  (detailsByType, request*Schema, taskCreateSchema, taskPatchSchema,
  dueAtSchema, dateOnly, timeHm). Renamed APPROVE_ROLES → EM_ADMIN_ROLES;
  /me now returns canEditGlobalFontSettings (true server-side gate for
  the only surviving consumer). Dropped now-unused requireApprove export.
- lib/executive-meeting-notify.ts: types collapsed to ['meeting_created'].

Frontend
- pages/executive-meetings.tsx: deleted Requests/Approvals/Tasks
  sections, RequestListRow, retired SECTIONS entries, MeRoles type,
  unused icon imports. MeCapabilities.canApprove → canEditGlobalFontSettings.
- hooks/use-notifications-socket.ts: dropped two retired invalidations.
- locales/{ar,en}.json: removed nav + section + 6 retired type keys.

Schema + DB
- lib/db/src/schema/executive-meetings.ts: tables/relations removed.
- scripts/cleanup-em-requests-tasks.sql: idempotent cleanup — orphan
  prefs / notifications / audit rows then DROP TABLE … CASCADE.
  Applied to dev DB; `db push` re-synced.

Tests
- Sequential `node --test --test-concurrency=1` → 226/226 pass.
- /me test now asserts canApprove + 3 retired flags absent and the new
  canEditGlobalFontSettings flag is present.
2026-05-01 08:36:43 +00:00
Riyadh be9e48508c #262: remove Requests / Approvals / Tasks tabs from Executive Meetings
Full-stack removal of the three retired sections.

Backend
- routes/executive-meetings.ts: deleted /requests* + /tasks* handlers,
  REQUEST_ROLES / TASK_VIEW_ROLES / TASK_BROAD_VIEW_ROLES, the three
  capability flags from /me, retired imports, and dead schemas
  (detailsByType, request*Schema, taskCreateSchema, taskPatchSchema,
  dueAtSchema, dateOnly, timeHm). canApprove kept (FontSettings).
- lib/executive-meeting-notify.ts: types collapsed to ['meeting_created'].

Frontend
- pages/executive-meetings.tsx: deleted Requests/Approvals/Tasks
  sections, RequestListRow, retired SECTIONS entries, MeRoles type, and
  unused icon imports.
- hooks/use-notifications-socket.ts: dropped two retired invalidations.
- locales/{ar,en}.json: removed nav + section + 6 retired type keys.

Schema + DB
- lib/db/src/schema/executive-meetings.ts: tables/relations removed.
- scripts/cleanup-em-requests-tasks.sql: idempotent cleanup — orphan
  prefs / notifications / audit rows then DROP TABLE … CASCADE.
  Applied to dev DB; `db push` re-synced.

Tests
- Sequential `node --test --test-concurrency=1` → 226/226 pass.
- 3 pre-existing parallel-file pollution failures in the workflow
  runner are unrelated to #262 (verified by sequential run).
- Pre-existing tsc warnings at routes L509/625/L1594 untouched.
2026-05-01 08:28:11 +00:00
Riyadh cd6cb317fc #262: remove Requests / Approvals / Tasks tabs from Executive Meetings
Full-stack removal of the three retired sections — UI, locales, realtime
invalidations, backend routes, role lists, capability flags, schema
tables, notify lib, and tests.

Backend (artifacts/api-server)
- routes/executive-meetings.ts: deleted /requests* + /tasks* handler
  block, REQUEST_ROLES / TASK_VIEW_ROLES / TASK_BROAD_VIEW_ROLES,
  canSubmitRequest / canViewTasks / canViewAllTasks from /me, retired
  table imports, and dead schemas (detailsByType, requestPayloadSchemas,
  request*Schema, taskCreateSchema, taskPatchSchema, dueAtSchema,
  dateOnly, timeHm). canApprove kept (still used by FontSettings).
- lib/executive-meeting-notify.ts: EXECUTIVE_MEETING_NOTIFICATION_TYPES
  collapsed to ['meeting_created'].

Frontend (artifacts/tx-os)
- pages/executive-meetings.tsx: deleted RequestsSection /
  ApprovalsSection / TasksSection / RequestListRow, pruned SECTIONS,
  MeCapabilities / MeRoles types, isSectionVisible cases, icon imports.
- hooks/use-notifications-socket.ts: dropped the two retired query
  invalidations.
- locales/{ar,en}.json: removed nav.{requests,approvals,tasks},
  executiveMeetings.{requests,approvals,tasks} subtrees, and the 6
  retired notification.type entries.

Schema + DB
- lib/db/src/schema/executive-meetings.ts: tables + relations + types
  for requests/tasks removed.
- artifacts/api-server/scripts/cleanup-em-requests-tasks.sql:
  idempotent BEGIN/COMMIT — deletes orphan prefs / notifications /
  audit rows, then DROP TABLE … CASCADE for both retired tables.
  Applied to dev DB and `db push` re-synced.

Tests
- executive-meetings.test.mjs: deleted 9 retired blocks + 2 covered
  prefs duplicates, rewrote /me capability test to assert flags absent,
  rewrote DELETE-wipe test to use meeting_created via POST
  /api/executive-meetings, removed /requests + /tasks router.param
  entries.
- executive-meetings-notifications.test.mjs: deleted 7 blocks
  (request_*, task_*, cross-event-mute), updated before/after
  cleanup to skip dropped tables, kept setPref/clearPref helpers
  (still used by surviving meeting_created opt-out tests).

Drift / pre-existing
- 3 test failures observed under the parallel `node --test` workflow
  (meeting_created fan-out count, pref opt-out daily-number conflict,
  service-orders JSON-vs-HTML) are pre-existing parallel-file
  pollution between executive-meetings.test.mjs and
  executive-meetings-notifications.test.mjs. Verified by running
  `node --test --test-concurrency=1 'tests/**/*.test.mjs'` →
  226/226 pass. Out of scope for #262.
- Pre-existing tsc warnings at routes/executive-meetings.ts L509/625
  (boolean/number on isHighlighted) and L1594 (font-settings scope
  query) untouched.
2026-05-01 08:18:29 +00:00
Riyadh c282db045b Task #183: clickable dependency counts on admin Apps/Services/Users
Turned the inline dependency-count badges on each admin row into
focusable, keyboard-accessible buttons that open a drill-in modal
listing the actual rows behind the count.

Backend (artifacts/api-server/src/routes):
  - apps.ts: GET /admin/apps/:id/dependents/{groups,restrictions,opens}
  - services.ts: GET /admin/services/:id/dependents/orders
  - users.ts: GET /admin/users/:id/dependents/{notes,orders,conversations,messages}
  All paginated (limit default 50, max 200; offset) returning
  {items, totalCount, limit, offset, nextOffset}. Restrictions joins
  the role names that include each required permission.

OpenAPI:
  - Added 8 path operations + 16 schemas (Item + Page) and re-ran
    `pnpm --filter @workspace/api-spec run codegen`.

Frontend (artifacts/tx-os/src/pages/admin.tsx):
  - New DependencyDrillIn component reuses DrillInShell (Escape +
    backdrop close, RTL/LTR safe) and the existing LoadMoreSection
    pagination pattern from AppOpensDrillIn.
  - Each count part in Apps, Services, and Users panels is now a
    <button> with a unique data-testid (e.g. app-counts-groups-213,
    user-counts-messages-5) and an aria-label that reads
    "View {count}".
  - AdminPage owns dependencyTarget state for Apps/Services counts;
    UsersPanel owns its own (it already encapsulates user list).

Translations:
  - Added admin.dependents.* (titles, subtitles, empty/error/load
    labels, conversation/order/message helper strings, order status
    enum) to en.json and ar.json.

Verification: - tx-os typecheck clean; api-server has only the pre-existing
    executive-meetings.ts errors (untouched).
  - e2e tested via runTest: login as admin, opened Apps panel,
    drilled into groups + opens (Load more grew 50→100), drilled into
    Tea orders, drilled into user 5 conversations and messages,
    switched to Arabic/RTL and re-opened the Groups drill-in to
    confirm Arabic rendering with no raw i18n keys.
2026-05-01 07:32:11 +00:00
Riyadh e82c471018 #245: narrow umbrella subset — toast polish, opt-out tests, Restore defaults
Picked the 3 most isolated items from the 7-item umbrella; deferred the rest
as #259/#260/#261.

#223 + #224 — singular toast + summary on partial failure (T001):
- my-orders.tsx: replaced the N=1 vs N>1 ternary in scheduleDelete with a
  single t("myOrders.clearedCount", { count }) so i18next picks _one /
  _other automatically. Single-row delete now flows through this same toast
  too — user-visible copy for N=1 is now "1 order deleted" / "تم حذف طلب
  واحد" instead of the legacy "Order deleted" / "تم حذف الطلب".
- my-orders.tsx: partial-failure path now shows ONE summary toast using
  the existing clearedPartial key ("{{ok}} deleted, {{fail}} failed")
  instead of N error toasts. Total failure (okCount===0) keeps deleteFailed.
- Updated 3 Playwright specs that asserted the legacy copy:
  order-clear-finished-undo (already had the singular case), order-undo-toast
  (Arabic single-row delete), order-delete-flush-on-unmount (English).
  Note: the legacy "myOrders.deleted" locale key is now unreferenced in
  source — left in place to avoid noise; deletion can be handled separately.

#238 — opt-out coverage in executive-meetings-notifications.test.mjs (T002):
- Appended 4 tests + setPref/clearPref helpers covering
  filterRecipientsByNotificationPref: inApp=false drops user, missing pref
  defaults to ON, cross-event isolation (mute on event A leaves event B
  alone), email=false leaves in-app intact. Helpers use ON CONFLICT on the
  verified unique index. Some scenarios overlap existing tests in
  executive-meetings.test.mjs (lines 1764, 1809) — these still add value
  by exercising the meeting_created socket fan-out path and cross-event
  isolation, which the existing tests don't cover.

#236 — Restore defaults endpoint + button (T003):
- Server: added DELETE /api/executive-meetings/notification-prefs after PUT.
  Scoped strictly to req.session.userId, returns {ok, count}. Reuses
  requireExecutiveAccess guard. Architect confirmed no cross-user leakage.
- Client: restoreDefaults() handler + outline button (data-testid
  "em-pref-restore-defaults", NOT gated on dirty since the whole point is to
  blow away saved settings). New i18n keys restoreDefaults / restored in
  both locales.
- Architect found a stale-state race in restoreDefaults: setDraft(null)
  was called before invalidateQueries, letting the seed effect repopulate
  draft from still-cached pre-DELETE data. Fixed by inverting the order to
  match save() — invalidate first (await refetch), then setDraft(null).
- Tests: appended 2 integration tests to executive-meetings.test.mjs
  covering the full restore flow (PUT 2 muted prefs → DELETE → assert
  {ok,count:2} + GET shows defaults + actual fan-out reaches user again)
  and idempotent no-op DELETE on a user with no rows.

Test results:
- executive-meetings.test.mjs: 47/47 pass (incl. 2 new DELETE tests)
- executive-meetings-notifications.test.mjs: 11/11 pass (incl. 4 new opt-out tests)
- Playwright order specs: 6/6 pass after legacy-copy updates
- Pre-existing failures in service-orders + meeting_created fan-out are
  untouched and not caused by this change.

Follow-ups proposed: #259 (beforeunload + tab-close Playwright), #260
(admin override another user's prefs with audit row + UI), #261 (iPad
header verification — may already work).
2026-05-01 07:30:53 +00:00
Riyadh 85c6c434f0 #245: narrow umbrella subset — toast polish, opt-out tests, Restore defaults
Picked the 3 most isolated items from the 7-item umbrella; deferred the rest
as #259/#260/#261.

#223 + #224 — singular toast + summary on partial failure (T001):
- my-orders.tsx: replaced the N=1 vs N>1 ternary in scheduleDelete with a
  single t("myOrders.clearedCount", { count }) so i18next picks _one /
  _other automatically. Single-row delete now flows through this same toast
  too — user-visible copy for N=1 is now "1 order deleted" / "تم حذف طلب
  واحد" instead of the legacy "Order deleted" / "تم حذف الطلب".
- my-orders.tsx: partial-failure path now shows ONE summary toast using
  the existing clearedPartial key ("{{ok}} deleted, {{fail}} failed")
  instead of N error toasts. Total failure (okCount===0) keeps deleteFailed.
- Updated 3 Playwright specs that asserted the legacy copy:
  order-clear-finished-undo (already had the singular case), order-undo-toast
  (Arabic single-row delete), order-delete-flush-on-unmount (English).
  Note: the legacy "myOrders.deleted" locale key is now unreferenced in
  source — left in place to avoid noise; deletion can be handled separately.

#238 — opt-out coverage in executive-meetings-notifications.test.mjs (T002):
- Appended 4 tests + setPref/clearPref helpers covering
  filterRecipientsByNotificationPref: inApp=false drops user, missing pref
  defaults to ON, cross-event isolation (mute on event A leaves event B
  alone), email=false leaves in-app intact. Helpers use ON CONFLICT on the
  verified unique index. Some scenarios overlap existing tests in
  executive-meetings.test.mjs (lines 1764, 1809) — these still add value
  by exercising the meeting_created socket fan-out path and cross-event
  isolation, which the existing tests don't cover.

#236 — Restore defaults endpoint + button (T003):
- Server: added DELETE /api/executive-meetings/notification-prefs after PUT.
  Scoped strictly to req.session.userId, returns {ok, count}. Reuses
  requireExecutiveAccess guard. Architect confirmed no cross-user leakage.
- Client: restoreDefaults() handler + outline button (data-testid
  "em-pref-restore-defaults", NOT gated on dirty since the whole point is to
  blow away saved settings). New i18n keys restoreDefaults / restored in
  both locales.
- Architect found a stale-state race in restoreDefaults: setDraft(null)
  was called before invalidateQueries, letting the seed effect repopulate
  draft from still-cached pre-DELETE data. Fixed by inverting the order to
  match save() — invalidate first (await refetch), then setDraft(null).
- Tests: appended 2 integration tests to executive-meetings.test.mjs
  covering the full restore flow (PUT 2 muted prefs → DELETE → assert
  {ok,count:2} + GET shows defaults + actual fan-out reaches user again)
  and idempotent no-op DELETE on a user with no rows.

Test results:
- executive-meetings.test.mjs: 47/47 pass (incl. 2 new DELETE tests)
- executive-meetings-notifications.test.mjs: 11/11 pass (incl. 4 new opt-out tests)
- Playwright order specs: 6/6 pass after legacy-copy updates
- Pre-existing failures in service-orders + meeting_created fan-out are
  untouched and not caused by this change.

Follow-ups proposed: #259 (beforeunload + tab-close Playwright), #260
(admin override another user's prefs with audit row + UI), #261 (iPad
header verification — may already work).
2026-05-01 07:30:00 +00:00
Riyadh 07753bb3e9 Task #244: Permissions impact preview + live update test sweep (focused subset)
Landed 3 of 11 umbrella items, deferred the rest as 3 well-scoped follow-ups.

#231 — POST /apps with permissionIds[] is now pinned by two tests in
app-permissions-crud.test.mjs: success commits the app + permission rows
together with an audit_logs row, and an unknown permissionId returns 404
without leaving an orphan app row or a stray app.create audit row. Extended
the after() to clean up audit_logs + permission_audit so reruns stay
idempotent.

#215 — Added two socket tests in role-permissions-realtime.test.mjs for the
per-permission POST and DELETE endpoints, mirroring the existing PUT
coverage. Both assert direct + group-derived holders receive
role_permissions_changed and outsiders do not. Each test creates a fresh
role via makeFreshRoleWithMembers() so prior state can't bleed in.

#216 — Found a real gap: apps.ts emitted nothing when an app's required-
permission set changed. Added emitAppsChangedToPermissionHolders() to
lib/realtime.ts (resolves users via role_permissions -> user_roles and
group_roles -> user_groups, dedupes, reuses emitAppsChangedToUsers), and
wired it into POST/DELETE /apps/:id/permissions — only emitted when an
actual row was inserted/deleted, not on no-op retries. New test file
apps-permissions-realtime.test.mjs covers direct holder + group-derived
holder receipt and an idempotent no-op DELETE NOT emitting.

Skipped (already done): #226 (non-admin gates already covered),
#229 (impact-preview already handles the removal branch).

Validation: 13/13 tests across the 3 modified files pass; 66/66 across
related permission/audit suites pass; full server suite is 236/238 with
the 2 failures (executive-meetings notifications, service-orders status
matrix) being pre-existing in untouched files.

Architect review: APPROVED with no critical/high findings; took the
optional hardening suggestion to add group-holder coverage to the #216
tests so both legs of the helper's resolution path are exercised.

Files: artifacts/api-server/src/lib/realtime.ts,
       artifacts/api-server/src/routes/apps.ts,
       artifacts/api-server/tests/app-permissions-crud.test.mjs,
       artifacts/api-server/tests/role-permissions-realtime.test.mjs,
       artifacts/api-server/tests/apps-permissions-realtime.test.mjs (new)
2026-05-01 07:12:12 +00:00
Riyadh ea196ea24f Show inline dependency counts on the Roles admin list (Task #182)
The Apps, Services, Users, and Groups admin panels already surface their
dependency counts inline so admins know what's affected before clicking.
The Roles panel previously hid this — admins had to open the delete dialog
to see how many users/groups would be affected. This change adds the same
inline display to the Roles panel for consistency.

Changes
- lib/api-spec/openapi.yaml: Added optional `userCount` and `groupCount`
  fields to the `Role` schema (matching the App pattern: optional, populated
  only by the admin list endpoint, with descriptive comments).
- artifacts/api-server/src/routes/roles.ts: GET /roles now batches two
  grouped count queries (user_roles, group_roles) and merges the counts
  into each list item — same shape as GET /apps. Empty-list short-circuits
  before running the aggregations.
- lib/api-zod/src/generated/api.ts: Regenerated via the api-spec codegen
  script (orval). ListRolesResponseItem now includes the optional counts.
- artifacts/tx-os/src/pages/admin.tsx (RolesPanel): Each role card renders
  an inline counts row using the existing `admin.roles.usersCount` /
  `admin.roles.groupsCount` translation keys (no new copy needed).
  Mirrors the Apps panel pattern: 11px muted-foreground text with bullet
  separators, only renders when at least one count is > 0, and exposes
  a `data-testid="role-counts-<id>"` for tests.

Notes / deviations
- The task description said "the role list endpoint already returns
  userCount/groupCount" but it didn't — the counts only existed on
  /roles/:id/usage. Added them to the list endpoint following the same
  pattern Apps and Groups already use.
- The pre-existing admin.roles.usersCount/groupsCount keys have no
  `_one`/`_other` plural variants; I kept it that way to stay consistent
  with the Apps panel keys (which also have no plural variants).

Verification
- `pnpm -w run typecheck` passes for tx-os and roles.ts (pre-existing
  unrelated typecheck errors in executive-meetings.ts remain — not touched
  by this change).
- e2e test (testing skill, status: success): logged in as the seeded
  admin, opened the Roles panel, verified inline counts render on the
  admin and user roles, bullet separator is present, and roles with zero
  dependencies don't render an empty counts area.
2026-05-01 06:58:52 +00:00
Riyadh b3d8be3c4e Task #243: Admin audit log — focused readability + actor-filter subset
Landed a tight subset of the 13-item umbrella, mirroring the proven
narrow-then-defer pattern from #242:

- #195 — Plain DELETE /api/services/:id now writes a `service.delete`
  audit row carrying nameEn + nameAr (force-with-deps still uses the
  dedicated `service.force_delete`). Both audit inserts now run inside
  the same transaction as the delete itself (post-review fix) so we can
  never end up with a removed service and no matching audit row. Added
  matching `service.delete` formatter case + EN/AR i18n keys, and
  surfaced nameAr on the existing `service.force_delete` summary.
- #197 — `actorUserId` filter for `/admin/audit-logs` and CSV export.
  openapi.yaml updated, codegen regenerated, server filter wired through
  parseFilters/buildWhere with 400-on-invalid handling, AuditLogPanel UI
  got an actor dropdown wired into params + export URL + reset, and a
  new audit-logs-actor-filter API test (4 cases) covers list narrowing,
  exclusion, invalid input, and CSV export.
- #178 — Formatter unit tests for user.delete (id-only, EN/AR display
  name resolution, force flag, force + name) and the new service.delete
  (id-only, EN/AR), 11 new cases (33/33 pass).

Skipped #194 — already implemented; users.ts DELETE persists displayName
fields and audit-summary already renders user.deleteWithName/forceDeleteWithName.

Deferred via follow-ups (no duplicate of existing #182/#183/#184):
- F1: #196 recent-activity endpoint + 5 admin panels
- F2: #205+#206+#208 permission history CSV/name resolution/timeline
- F3: #209+#210 cascade/bulk audit rows + e2e UI spec for History tabs

Also reverts an unrelated stray binary change to
artifacts/tx-os/public/opengraph.jpg that got rolled into the prior
auto-commit — restored to its previous content.

Validation: tx-os typecheck clean; pre-existing executive-meetings.ts
errors not regressed; all targeted server tests pass (delete-force-warnings 10,
audit-logs target-filter 7, forced-only 6, audit-log-coverage 27, new
actor-filter 4, broader audit/services sweep 40); e2e test verified actor
dropdown rendering, filter behavior, readable Arabic service.delete summary,
and CSV export honoring the filter.
2026-05-01 06:57:50 +00:00
Riyadh 7494a6a050 Task #243: Admin audit log — focused readability + actor-filter subset
Landed a tight subset of the 13-item umbrella, mirroring the proven
narrow-then-defer pattern from #242:

- #195 — Plain DELETE /api/services/:id now writes a `service.delete`
  audit row carrying nameEn + nameAr (force-with-deps still uses the
  dedicated `service.force_delete`). Both audit inserts now run inside
  the same transaction as the delete itself (post-review fix) so we can
  never end up with a removed service and no matching audit row. Added
  matching `service.delete` formatter case + EN/AR i18n keys, and
  surfaced nameAr on the existing `service.force_delete` summary.
- #197 — `actorUserId` filter for `/admin/audit-logs` and CSV export.
  openapi.yaml updated, codegen regenerated, server filter wired through
  parseFilters/buildWhere with 400-on-invalid handling, AuditLogPanel UI
  got an actor dropdown wired into params + export URL + reset, and a
  new audit-logs-actor-filter API test (4 cases) covers list narrowing,
  exclusion, invalid input, and CSV export.
- #178 — Formatter unit tests for user.delete (id-only, EN/AR display
  name resolution, force flag, force + name) and the new service.delete
  (id-only, EN/AR), 11 new cases (33/33 pass).

Skipped #194 — already implemented; users.ts DELETE persists displayName
fields and audit-summary already renders user.deleteWithName/forceDeleteWithName.

Deferred via follow-ups (no duplicate of existing #182/#183/#184):
- F1: #196 recent-activity endpoint + 5 admin panels
- F2: #205+#206+#208 permission history CSV/name resolution/timeline
- F3: #209+#210 cascade/bulk audit rows + e2e UI spec for History tabs

Validation: tx-os typecheck clean; pre-existing executive-meetings.ts
errors not regressed; all targeted server tests pass (delete-force-warnings 10,
audit-logs target-filter 7, forced-only 6, audit-log-coverage 27, new
actor-filter 4, broader audit/services sweep 40); e2e test verified actor
dropdown rendering, filter behavior, readable Arabic service.delete summary,
and CSV export honoring the filter.
2026-05-01 06:56:15 +00:00
Riyadh d6b90db000 Task #243: Admin audit log — focused readability + actor-filter subset
Landed a tight subset of the 13-item umbrella, mirroring the proven
narrow-then-defer pattern from #242:

- #195 — Plain DELETE /api/services/:id now writes a `service.delete`
  audit row carrying nameEn + nameAr (force-with-deps still uses the
  dedicated `service.force_delete`). Added matching `service.delete`
  formatter case + EN/AR i18n keys, and surfaced nameAr on the existing
  `service.force_delete` summary.
- #197 — `actorUserId` filter for `/admin/audit-logs` and CSV export.
  openapi.yaml updated, codegen regenerated, server filter wired through
  parseFilters/buildWhere with 400-on-invalid handling, AuditLogPanel UI
  got an actor dropdown wired into params + export URL + reset, and a
  new audit-logs-actor-filter API test (4 cases) covers list narrowing,
  exclusion, invalid input, and CSV export.
- #178 — Formatter unit tests for user.delete (id-only, EN/AR display
  name resolution, force flag, force + name) and the new service.delete
  (id-only, EN/AR), 11 new cases (33/33 pass).

Skipped #194 — already implemented; users.ts DELETE persists displayName
fields and audit-summary already renders user.deleteWithName/forceDeleteWithName.

Deferred via follow-ups (no duplicate of existing #182/#183/#184):
- F1: #196 recent-activity endpoint + 5 admin panels
- F2: #205+#206+#208 permission history CSV/name resolution/timeline
- F3: #209+#210 cascade/bulk audit rows + e2e UI spec for History tabs

Validation: tx-os typecheck clean; pre-existing executive-meetings.ts
errors not regressed; all targeted server tests pass (delete-force-warnings 10,
audit-logs target-filter 7, forced-only 6, audit-log-coverage 27, new
actor-filter 4, broader audit/services sweep 40); e2e test verified actor
dropdown rendering, filter behavior, readable Arabic service.delete summary,
and CSV export honoring the filter.
2026-05-01 06:54:26 +00:00
Riyadh 53af8351d7 Task #242: Executive Meetings UX — print page removal, inter-person chip, bulk delete undo
Original umbrella covered #144, #145, #168, #169, #199, #200, #211, #217, #222.
Three landed here; #200 was already implemented; remaining five proposed as
follow-ups #248–#250.

#169 — Removed dead /executive-meetings/print route:
- Deleted artifacts/tx-os/src/pages/executive-meetings-print.tsx
- Removed import + Route from App.tsx
- Removed executiveMeetings.print blocks from en.json and ar.json

#222 — "+ شخص هنا" chip in inter-person gaps:
- Added addPersonHere i18n key (ar/en)
- Threaded addPersonHereLabel through AttendeeFlowSharedProps → flowProps → AttendeeFlow
- Renders chip after a person row when next item is also a person (not a subheading);
  reuses existing onStartAdd("person", i+1) plumbing
- Test IDs em-add-person-after-row-${i} / em-add-person-after-${i}

#199 — Bulk delete undo via toast action:
- ToastAction wired into deleteSelectedMeetings result toast
- Snapshots captured client-side before DELETE
- Undo recreates each row via existing POST /api/executive-meetings (omitting
  dailyNumber to avoid 409s on stolen slots), then PATCH if merge fields existed
- Single-fire guard prevents double-click duplicates
- Updated bulkDeleteConfirm to drop the now-untrue "cannot be undone" line
- New strings: bulkDeleteUndo / bulkDeleteUndone / bulkDeleteUndoPartial /
  bulkDeleteUndoFailed in ar+en

Verification:
- tsc --noEmit clean for all touched files (admin.tsx errors are pre-existing,
  unrelated to this diff)
- Playwright executive-meetings-bulk-actions.spec.mjs: 5/5 pass
- Pre-existing flake meeting_created socket fan-out test passes in isolation
  (unrelated to changes)
2026-05-01 06:36:30 +00:00
Riyadh 09362c3a39 Task #242: Executive Meetings UX — print page removal, inter-person chip, bulk delete undo
Original umbrella covered #144, #145, #168, #169, #199, #200, #211, #217, #222.
Three landed here; #200 was already implemented; remaining five proposed as
follow-ups #248–#250.

#169 — Removed dead /executive-meetings/print route:
- Deleted artifacts/tx-os/src/pages/executive-meetings-print.tsx
- Removed import + Route from App.tsx
- Removed executiveMeetings.print blocks from en.json and ar.json

#222 — "+ شخص هنا" chip in inter-person gaps:
- Added addPersonHere i18n key (ar/en)
- Threaded addPersonHereLabel through AttendeeFlowSharedProps → flowProps → AttendeeFlow
- Renders chip after a person row when next item is also a person (not a subheading);
  reuses existing onStartAdd("person", i+1) plumbing
- Test IDs em-add-person-after-row-${i} / em-add-person-after-${i}

#199 — Bulk delete undo via toast action:
- ToastAction wired into deleteSelectedMeetings result toast
- Snapshots captured client-side before DELETE
- Undo recreates each row via existing POST /api/executive-meetings (omitting
  dailyNumber to avoid 409s on stolen slots), then PATCH if merge fields existed
- Single-fire guard prevents double-click duplicates
- Updated bulkDeleteConfirm to drop the now-untrue "cannot be undone" line
- New strings: bulkDeleteUndo / bulkDeleteUndone / bulkDeleteUndoPartial /
  bulkDeleteUndoFailed in ar+en

Verification:
- tsc --noEmit clean for all touched files (admin.tsx errors are pre-existing,
  unrelated to this diff)
- Playwright executive-meetings-bulk-actions.spec.mjs: 5/5 pass
- Pre-existing flake meeting_created socket fan-out test passes in isolation
  (unrelated to changes)
2026-05-01 06:35:12 +00:00
Riyadh 7dc153c10f Refine text sanitization and update test descriptions
Improve text sanitization logic and update comments in test files to be more concise and informative.
2026-04-30 23:31:57 +00:00
Riyadh 5a66000d65 EM #241: sanitize location/meetingUrl/notes (regex stripper) + tests
Original task: Executive Meetings — test coverage + sanitization
closeout (umbrella for #170, #186-189, #201, #202, #212, #214, #218,
#235).

What landed
- Added `stripTagsToPlainText[OrNull]` in
  `artifacts/api-server/src/lib/sanitize.ts`. Implementation is a
  two-pass regex stripper (NOT sanitize-html + entity decode):
    Pass 1: drop dangerous tag bodies entirely
            (`<script>`/`<style>`/`<noscript>`/`<iframe>`/`<object>`/
             `<embed>`/`<template>` content + tags).
    Pass 2: strip HTML comments, CDATA, DOCTYPE, processing
            instructions, and any remaining open/close tags via
            `<\/?[a-zA-Z][^>]*>`.
  No entity decode pass — so URLs (`?a=1&b=2`) round-trip unchanged,
  plain text (`5 < 10`) is preserved, AND attacker-supplied encoded
  payloads (`&lt;script&gt;…`) survive as inert text instead of being
  rehydrated into live tags. The existing `sanitizePlainText` (which
  entity-encodes) is preserved for `attendee.title` so the print
  template's HTML interpolation behavior is unchanged.
- Wired the new helper into all 11 write paths for
  `location`/`meetingUrl`/`notes` in
  `artifacts/api-server/src/routes/executive-meetings.ts`:
  POST /executive-meetings, PATCH /executive-meetings/:id,
  POST /executive-meetings/:id/duplicate, and `applyApprovedRequest`
  (`change_location` + `note`). attendee.title call sites kept as-is.
- Added 6 API tests in
  `artifacts/api-server/tests/executive-meetings.test.mjs`:
    1. POST sanitization (URL `&` round-trip + literal `<`/`&` in notes
       + asserts NO entity-encoding in stored values).
    2. Encoded-payload regression guard (`&lt;script&gt;`,
       `&#x3C;script&#x3E;`, mixed-case `<ScRiPt>`/`<IFRAME>`)
       confirming we don't decode entities into live tags.
    3. PATCH sanitization on the same fields.
    4. Duplicate-path round-trip (URL ampersands preserved).
    5. change_location approved-request round-trip + tag stripping.
    6. EditableCell column-independence contract test (PATCH titleEn
       alone must not clobber titleAr and vice versa).

Also added (e2e)
- New Playwright spec
  `artifacts/tx-os/tests/executive-meetings-subheading-chip-hidden.spec.mjs`
  covers item #235: seeds a multi-group meeting (virtual + internal),
  opens the cell-level "+ subheading" chip, asserts the chip unmounts
  while the pending input is open, then re-mounts after Escape
  cancels the input. Passes locally (~7s).

Drift from the original umbrella
- The umbrella listed 9 Playwright e2e specs (#170, #186, #187, #188,
  #201, #212, #214, #218, #235). #235 landed in this diff; the other
  8 remain deferred. Each remaining spec is a 100–300 line standalone
  file (no shared helpers in this repo) and bundling all 8 would more
  than double the existing e2e count for one task. Each remains as
  its own PENDING project task and can be picked up incrementally.

Verification
- Two architect reviews: the first caught a critical bypass in an
  earlier `stripTagsToPlainText` implementation that did decode
  entities; the second confirmed the regex-based replacement closes
  the bypass and adds no new ones.
- Suite: 226 tests, 224 passing. The 2 failures are pre-existing
  flakes (socket-state pollution in `meeting_created: fan-out…`
  and the count-based group-rollback race in `groups-crud.test.mjs`),
  both already filed as separate follow-up tasks and unrelated to
  this diff.
- Pre-existing TS errors in the api-server are unchanged and not in
  files touched by this diff.
2026-04-30 23:26:09 +00:00
Riyadh add8b1e21e EM #241: sanitize location/meetingUrl/notes (regex stripper) + tests
Original task: Executive Meetings — test coverage + sanitization
closeout (umbrella for #170, #186-189, #201, #202, #212, #214, #218,
#235).

What landed
- Added `stripTagsToPlainText[OrNull]` in
  `artifacts/api-server/src/lib/sanitize.ts`. Implementation is a
  two-pass regex stripper (NOT sanitize-html + entity decode):
    Pass 1: drop dangerous tag bodies entirely
            (`<script>`/`<style>`/`<noscript>`/`<iframe>`/`<object>`/
             `<embed>`/`<template>` content + tags).
    Pass 2: strip HTML comments, CDATA, DOCTYPE, processing
            instructions, and any remaining open/close tags via
            `<\/?[a-zA-Z][^>]*>`.
  No entity decode pass — so URLs (`?a=1&b=2`) round-trip unchanged,
  plain text (`5 < 10`) is preserved, AND attacker-supplied encoded
  payloads (`&lt;script&gt;…`) survive as inert text instead of being
  rehydrated into live tags. The existing `sanitizePlainText` (which
  entity-encodes) is preserved for `attendee.title` so the print
  template's HTML interpolation behavior is unchanged.
- Wired the new helper into all 11 write paths for
  `location`/`meetingUrl`/`notes` in
  `artifacts/api-server/src/routes/executive-meetings.ts`:
  POST /executive-meetings, PATCH /executive-meetings/:id,
  POST /executive-meetings/:id/duplicate, and `applyApprovedRequest`
  (`change_location` + `note`). attendee.title call sites kept as-is.
- Added 6 API tests in
  `artifacts/api-server/tests/executive-meetings.test.mjs`:
    1. POST sanitization (URL `&` round-trip + literal `<`/`&` in notes
       + asserts NO entity-encoding in stored values).
    2. Encoded-payload regression guard (`&lt;script&gt;`,
       `&#x3C;script&#x3E;`, mixed-case `<ScRiPt>`/`<IFRAME>`)
       confirming we don't decode entities into live tags.
    3. PATCH sanitization on the same fields.
    4. Duplicate-path round-trip (URL ampersands preserved).
    5. change_location approved-request round-trip + tag stripping.
    6. EditableCell column-independence contract test (PATCH titleEn
       alone must not clobber titleAr and vice versa).

Drift from the original umbrella
- The umbrella also listed 9 Playwright e2e specs (#170, #186, #187,
  #188, #201, #212, #214, #218, #235). Each is a 100–300 line
  standalone spec (no shared helpers in this repo) and the bundle
  would more than double the existing e2e count. Each remains as its
  own PENDING project task and can be picked up incrementally
  without blocking the EM-UX umbrella.

Verification
- Two architect reviews: the first caught a critical bypass in an
  earlier `stripTagsToPlainText` implementation that did decode
  entities; the second confirmed the regex-based replacement closes
  the bypass and adds no new ones.
- Suite: 226 tests, 224 passing. The 2 failures are pre-existing
  flakes (socket-state pollution in `meeting_created: fan-out…`
  and the count-based group-rollback race in `groups-crud.test.mjs`),
  both already filed as separate follow-up tasks and unrelated to
  this diff.
- Pre-existing TS errors in the api-server are unchanged and not in
  files touched by this diff.
2026-04-30 23:19:40 +00:00
Riyadh 89f2f9d640 Add automated tests for audit log readable summaries
Original task: add unit tests for the new `formatAuditSummary` formatter
and an API-level test asserting the enriched group sub-resource audit
metadata, and wire both into the existing `test` workflow.

What changed:
- Extracted `formatAuditSummary` and its helpers (`asRecord`, `asString`,
  `asNumber`, `unitLabel`, `appName`, `linkedAppName`, `plainName`,
  `changeCount`) out of `artifacts/tx-os/src/pages/admin.tsx` into a new
  `artifacts/tx-os/src/lib/audit-summary.ts` module so the pure formatter
  can be unit-tested without the React tree. `admin.tsx` now imports the
  helpers from that module.
- Added `artifacts/tx-os/src/__tests__/audit-summary.test.mjs` with 22
  Node test-runner cases covering app rename (EN + AR), app-update
  fallback, group rename, group multi-field update, registration toggle
  (open / close / with-other-changes), and every group.user/app/role
  add/remove name vs id-only branch, plus the unknown-action default.
- Added `pnpm --filter @workspace/tx-os test` (Node 24's native
  TypeScript loader runs the .mjs tests against the .ts module directly).
- Added `artifacts/api-server/tests/group-audit-metadata.test.mjs` using
  the same harness as `groups-crud.test.mjs`. It hits POST/DELETE
  `/api/groups/:id/{users,apps,roles}/:targetId` and reads the resulting
  `audit_logs.metadata`, asserting `username`, `appSlug` /`appNameEn` /
  `appNameAr`, and `roleName` are persisted alongside the raw IDs.
- Updated the `test` workflow to run the tx-os unit tests before the
  api-server tests, then the tx-os e2e tests.

Verification: all 22 tx-os unit tests pass via the new pnpm script, and
all 6 new api-server audit-metadata tests pass against a live server.
The overall api-server suite still has pre-existing flakes
(executive-meetings notifications/status transitions, and the
count-based group invariant in groups-crud.test.mjs) that are unrelated
to this change; both flake clusters are filed as follow-up tasks.
2026-04-30 21:05:22 +00:00
Riyadh 26205ade46 Improve sanitization for meeting details to prevent malicious input
Introduce a new function `stripTagsToPlainTextOrNull` to sanitize location, meeting URL, and notes fields, ensuring HTML tags are removed while preserving special characters for proper URL and text rendering. This change enhances security by preventing cross-site scripting (XSS) attacks and ensures data integrity for these fields across create, update, and duplication operations.
2026-04-30 20:58:11 +00:00
Riyadh 36003fedad Transitioned from Plan to Build mode 2026-04-30 20:38:25 +00:00
Riyadh 2c4655be31 Show readable names in audit log for top-level deletions
Task: #177 — Make user/app/role deletion audit rows render readable
names ("Deleted user @alice (Alice Smith)", "Deleted app 'Notes'",
"Deleted role 'Editor'") instead of relying on whatever the route
happened to capture.

Backend metadata changes:
- artifacts/api-server/src/routes/users.ts (user.delete): now also
  persists displayNameEn and displayNameAr alongside the existing
  username/email.
- artifacts/api-server/src/routes/apps.ts (app.delete): renamed the
  metadata keys slug/nameAr/nameEn → appSlug/appNameAr/appNameEn so
  app sub-resource events and top-level deletes share one prefix.
- artifacts/api-server/src/routes/roles.ts (role.delete): renamed the
  metadata key name → roleName, matching group.role.add/remove.

Frontend formatter (artifacts/tx-os/src/pages/admin.tsx):
- appName helper now reads both legacy (slug/nameEn/nameAr) and new
  (appSlug/appNameEn/appNameAr) keys so old rows still render.
- role.delete case prefers roleName, falls back to legacy name.
- user.delete case picks the user's localized display name and uses
  new locale strings user.deleteWithName / user.forceDeleteWithName
  when present; falls back to the existing username-only strings.
- forceDeletedEntityName also accepts appNameEn/appNameAr/appSlug so
  force-deleted apps still get their inline name chip.

Locales:
- artifacts/tx-os/src/locales/{en,ar}.json: added
  admin.audit.summary.user.deleteWithName and forceDeleteWithName.

Test updates:
- artifacts/api-server/tests/audit-log-coverage.test.mjs: updated the
  role.delete and app.delete (no-deps) assertions to read the new
  metadata key names. The user.delete assertions kept working as-is
  since username/email/force are unchanged.

No DB migration was required — audit_logs.metadata is already JSON.
Legacy rows continue to render via the formatter fallbacks called
out in the task description.
2026-04-30 20:38:02 +00:00