b4d47e1012e7aba5decff8d090b0e7cbb46a9e96
70 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
b4d47e1012 |
Executive Meetings Phase 2: full module + atomic audit
Original task (#108): polish the daily-schedule UI and ship the remaining 8 sections of the Executive Meetings module (Manage, Requests, Approvals, Tasks, Notifications, Audit, PDF, Font Settings) with bilingual i18n and fine-grained RBAC. What changed: - Schedule UI: centered cells, '#' header (not 'م'), attendees widest, RTL column order locked, navy/white/gray + red highlighting only. - Schema: made executive_meeting_requests.meetingId nullable so 'create-meeting' suggestions don't need a target row. - Backend rewrite of artifacts/api-server/src/routes/executive-meetings.ts: GET /me (now returns userId), full CRUD for meetings (transactional attendee replace), requests CRUD + approve/reject/withdraw, tasks CRUD with assignee status updates, audit-logs GET (admin), notifications GET, font-settings GET/PATCH (per-user + global). RBAC via 5 role sets and a makeRequireRoles middleware factory. - Audit-in-transaction: every mutation (meeting/request/task/font CRUD) wraps the DB write AND the audit-log insert in the same db.transaction so audit entries cannot drift from state if either insert fails. This was the main finding from the architect review and is now fixed. - Path-to-regexp 8 fix: replaced inline ':id(\\d+)' with router.param('id') + next('route') guard, plus NaN guards in handlers. - Frontend rewrite of artifacts/tx-os/src/pages/executive-meetings.tsx (~2200 lines): 8 new section components, RBAC-aware UI via /me, per-task assignee check now shown for status buttons. - i18n: full executiveMeetings.* key set added in ar.json + en.json. Verified: full e2e (admin login -> all 9 tabs -> create meeting -> submit request -> approve -> audit shows full chain -> font save) plus a smoke regression after the audit-in-tx refactor (atomic audit row created in lockstep with mutation). Out of scope (proposed as follow-ups #110-#112): real notification delivery, real PDF generation (currently window.print), and automated integration tests for the new endpoints. The pre-existing 'apps-open.test.mjs' syntax error in the test workflow is unrelated to this task. |
||
|
|
1ad311ad50 |
Add automated tests for role create / edit / delete endpoints (Task #90)
Original task
- Cover the new /api/roles create, update, and delete handlers with
automated tests so regressions in role validation, system-role
protection, and the in-use conflict response can't slip in unnoticed.
- Tests must run as part of the standard api-server test command.
What was added
- artifacts/api-server/tests/roles-crud.test.mjs with 7 tests:
* POST /api/roles -> 201 (also checks DB row + serialized fields)
* POST /api/roles duplicate name -> 409 (no second row inserted)
* POST /api/roles invalid name format -> 400 (no row leaked)
* PATCH /api/roles/:id description-only update -> 200, name unchanged
* DELETE /api/roles/:id on system role 'admin' -> 400, row preserved
* DELETE /api/roles/:id on in-use role -> 409 with userCount=1,
groupCount=1; row preserved
* DELETE /api/roles/:id on unused role -> 204, row gone
- The file follows the same pattern as groups-crud.test.mjs:
pg.Pool seed via DATABASE_URL, login -> connect.sid cookie,
thorough teardown of users / groups / roles / link tables.
Test infra
- No new test setup needed; the package's existing
"test": "node --test 'tests/**/*.test.mjs'" picks the file up
automatically. All 7 new tests pass.
Notes / drift
- Two pre-existing test failures (apps-open.test.mjs and one assertion
in groups-crud.test.mjs that depends on global group counts) are
unrelated to this task and were left untouched.
Replit-Task-Id: 4254b35b-ba28-443f-80a6-22f6ddfbedd6
|
||
|
|
aa6866936d |
Task #89: Permissions picker for roles in admin dashboard
Original task: let admins assign permissions to roles from the dashboard.
Changes:
- lib/api-spec/openapi.yaml: added Permission and ReplaceRolePermissionsBody
schemas; added GET /permissions, expanded GET /roles/{id}/permissions to
return full Permission objects, and added admin-guarded
PUT /roles/{id}/permissions. Ran codegen to refresh generated hooks/zod.
- artifacts/api-server/src/routes/roles.ts:
* Added a single isSystemRole helper and PROTECTED_ROLE_NAMES set.
* Added serializePermission + GET /permissions.
* Expanded GET /roles/:id/permissions (404 on missing role, full
Permission objects).
* New PUT /roles/:id/permissions: blocks system/protected roles
(400 with code "system_role_permissions"), rejects non-positive /
non-integer permissionIds with 400, validates all ids exist (404),
deletes+inserts atomically in a transaction, and notifies role
holders via emitAppsChangedToRoleHolders.
* Hardened legacy POST /roles/:id/permissions and
DELETE /roles/:id/permissions/:permissionId so they also reject
system-role mutations with the same code, closing the bypass that
the new endpoint was meant to prevent.
* Re-used isSystemRole in PATCH/DELETE role flows.
- artifacts/tx-os/src/pages/admin.tsx: added a permissions checkbox list
inside the role editor dialog, disabled (read-only) for system /
protected roles with a hint. Save flow runs updateRole then
replaceRolePermissions only when the set actually changed and the role
is non-system. Front-end ROLES_PROTECTED_NAMES set mirrors the
back-end fallback so admin/user/order_receiver are recognised even
when the legacy DB column is 0 (also gates the role-card system badge
and delete button).
- artifacts/tx-os/src/locales/en.json + ar.json: new translation keys
for the permissions picker, system-role read-only hint, empty list,
and error toasts.
Verification: tx-os and api-server typecheck clean. End-to-end test
passes: admin login → edit a created role → toggle/save permissions →
re-open and confirm round-trip → admin role dialog shows disabled
checkboxes and read-only hint → PUT on admin role returns 400
"system_role_permissions". curl regression checks: legacy POST/DELETE
on admin role return the same 400/code; PUT rejects float / negative /
string ids with 400.
Replit-Task-Id: 74180397-afdf-4489-976a-a6fe099684bd
|
||
|
|
1e9024e5a2 |
Let admins edit role names + descriptions in both languages
Original task (#88): The Roles tab in the Group editor displays each role's Arabic and English descriptions, but admins had no UI to edit them — any tweak required a developer. The edit dialog also didn't allow updating the role's name. Make role name + bilingual descriptions editable from the admin Roles panel and persist via PATCH /api/roles/:id. Changes: - lib/api-spec/openapi.yaml: UpdateRoleBody now accepts an optional `name` (minLength 1). PATCH /roles/{id} summary updated to "Update role name and descriptions (admin)" and documents 400 (invalid request) and 409 (name already taken) responses. Regenerated lib/api-zod. - artifacts/api-server/src/routes/roles.ts (PATCH /roles/:id): * Accept and validate `name` with the same rules as create (`/^[a-z][a-z0-9_]*$/i`, uniqueness check that ignores the role's own row). * Refuse to rename system roles (isSystem=1 or one of admin/user/ order_receiver) -> 400 with `code: "system_role_rename"`. * Returns 409 on name collision. - artifacts/tx-os/src/pages/admin.tsx (RolesPanel edit dialog): * Edit form now includes a Name input (data-testid="role-edit-name") prefilled from the role. * Name input is disabled for system roles, with a dedicated hint string. * Save is disabled when name is empty; 400 errors with `code: "system_role_rename"` show a system-role-specific toast, other 400s show the invalid-name toast, and 409 shows name-taken. - artifacts/tx-os/src/locales/{en,ar}.json: * Replaced the now-misleading `editHint` ("Role names cannot be changed") with `editSystemNameHint` (only shown for system roles). * Removed "Cannot be changed later" from `nameHint`. * Added `errorSystemRename` for the system-role rename toast. Validation: - pnpm typecheck passes. - Playwright e2e (testing skill) created a role, renamed it + updated both descriptions, verified the new name + descriptions appear on the role card and in the Group editor's Roles tab, confirmed empty name disables Save, and cleaned up via delete. (Test agent flagged one stale snapshot on the system-role disabled-name check; the implementation gates on r.isSystem from the API and is also enforced server-side.) Replit-Task-Id: 01dbc785-03e0-4714-b9d5-f0dff6de9a56 |
||
|
|
b865e69f64 |
Add test coverage for the order-unavailable error responses (Task #86)
Task #80 introduced a new 409 `order_unavailable` error code returned by: - PATCH /api/orders/:id/confirm-receipt - PATCH /api/orders/:id/status …to distinguish "already_claimed" (lost a race) from "no longer claimable" (target order is cancelled or completed). The integration test suite did not cover these paths. Changes ------- artifacts/api-server/tests/service-orders.test.mjs + Added test "confirm-receipt returns 409 order_unavailable when the order is cancelled or completed": - Owner cancels a pending order → another receiver's confirm-receipt returns 409 with body.error === "order_unavailable" (not "already_claimed"). - Receiver claims, prepares, completes an order → another receiver's confirm-receipt returns 409 "order_unavailable". + Added test "PATCH /orders/:id/status returns 409 order_unavailable when targeting a terminal order": - Completed order: assignee → preparing → 409 "order_unavailable" - Completed order: assignee → completed → 409 "order_unavailable" - Completed order: owner → cancelled → 409 "order_unavailable" - Cancelled order: owner → cancelled → 409 "order_unavailable" Verification ------------ All 11 service-orders integration tests pass (including both new tests): pnpm --filter @workspace/api-server test → 11 passed, 0 failed. No production code changes; tests only. Replit-Task-Id: 229ed991-1c32-4281-8e57-00abeacd80b4 |
||
|
|
7c9edf6cb6 |
Warn admins before deleting non-empty users/apps/services (Task #85)
Apply the existing groups delete-warning pattern to user, app, and
service deletions so admins are warned (and have to confirm twice)
before destroying records that still own dependent data.
Backend
- openapi.yaml: added `force` query param to DELETE /users/{id},
/apps/{id}, /services/{id} plus three new conflict schemas
(UserDeletionConflict, AppDeletionConflict, ServiceDeletionConflict).
- routes/users.ts, apps.ts, services.ts: rewrote DELETE handlers to
count dependents (notes/orders/conversations/messages for users;
group_apps/restrictions/open events for apps; service_orders for
services), return 409 with counts when non-empty and force is not set,
and on `?force=true` perform the cascade in a transaction and write
an `*.force_delete` audit_logs row.
- Existing 204 success path preserved for empty deletes.
UI (artifacts/tx-os/src/pages/admin.tsx)
- New `DeletionWarningDialog` helper, plus app/service/user delete state
+ lazy 409 detection (first click probes; on 409 the dialog upgrades
to show counts + "Delete anyway"; second click sends ?force=true).
- Replaced the three plain `confirm(t("admin.deleteConfirm"))` callsites.
i18n
- Added admin.deleteApp/deleteService/deleteUser keys (title, warning,
forceHint, emptyBody, count keys, confirm, anyway) in en.json + ar.json.
Tests
- artifacts/api-server/tests/delete-force-warnings.test.mjs covers all
9 cases (clean delete, 409 with counts, force=true 204 + audit log)
for users, apps, and services. Existing groups-crud and service-orders
tests still pass.
Notes / drift
- Lazy detection (vs eager counts on the row like Groups already does)
was chosen because list endpoints don't return counts yet — proposed
follow-up #96 covers eager counts so the warning appears on first
click everywhere.
- E2E test for the UI flow flaked twice; backend integration tests
(9/9 pass), direct curl validation of force=true returning 204, and
typecheck across the monorepo all confirm correctness.
Replit-Task-Id: 91404d92-e74c-4720-8fc9-8eb772eefc33
|
||
|
|
6e9b9b5f3d | Git commit prior to merge | ||
|
|
66bc96f97f |
Add executive meeting management system with role-based access
Implement a new API endpoint and UI for managing executive meetings, including role-based access control and database schema changes for meeting data and attendees. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Event-Id: 079afca5-8c32-40ea-b7d1-8bf26358ff75 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/BRoHDEI Replit-Helium-Checkpoint-Created: true |
||
|
|
1ca5d5ae4b |
Add admin Audit Log view (task-84)
Original task: Show admins a history of sensitive actions. Forced group deletions already write to the new `audit_logs` table; admins now have a UI to browse and filter those entries. API - New OpenAPI endpoint GET /admin/audit-logs (admin-only) with optional filters: action (exact), from / to (YYYY-MM-DD, inclusive), limit (1-200, default 50), offset (default 0). - New schemas: AuditLogActor, AuditLogEntry, AuditLogList. List response includes paginated `entries`, `totalCount`, `nextOffset`, and a distinct `actions` list to power the filter dropdown. - New `audit` tag added to the spec; ran orval codegen so api-client-react / api-zod expose useListAuditLogs et al. - Implemented `artifacts/api-server/src/routes/audit.ts` and registered it in routes/index.ts. Validates date format / order, joins users for actor info, and orders newest-first. UI (artifacts/tx-os/src/pages/admin.tsx) - New "Audit log" entry under the User Management nav group (icon: ScrollText). Section deep-link works via #section=audit-log. - New AuditLogPanel + AuditLogRow components: action chip + target, formatted timestamp, actor avatar/name, expandable JSON metadata. - Filters bar: action dropdown (populated from API's distinct actions), from/to date inputs, Apply / Reset, plus a "Load more" control that increases the page size (caps at 200, the API limit). Read-only by design. - Added en/ar locale strings for nav.auditLog and the audit subtree. Verification - Typecheck: pnpm -w run typecheck (clean). - API smoke tested via curl: 401 unauthenticated, validation errors for bad / inverted dates, returns the seeded `group.force_delete` entry once produced. - End-to-end browser test (testing skill): logged in as admin, navigated to /admin#section=audit-log, verified the row, expanded metadata, exercised filters (empty state + reset). No deviations from the task description. Replit-Task-Id: 5b5bf9b1-6937-43c3-85c9-81f0c19a5e49 |
||
|
|
c05ae786fc |
Fix order cancellation logic and update tests to reflect new behavior
Adjusts the order cancellation endpoint to correctly handle admin overrides for completed/cancelled orders and updates associated tests to expect 409 status codes reflecting Task #80's changes. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Event-Id: d358e7e1-8a16-4746-86aa-4f1739233f2e Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/3E2mNig Replit-Helium-Checkpoint-Created: true |
||
|
|
595ca06a57 |
Task #83: Refresh role and permission changes live across user sessions
## Socket.IO broadcasts (core task): - POST /users/:id/roles: uses .returning() to emit apps_changed only when row inserted - DELETE /users/:id/roles/:roleName: uses .returning() to emit only when row deleted - Added emitAppsChangedToRoleHolders(roleId) helper to realtime.ts - New role-permission endpoints in roles.ts, emit only on effective changes: - GET /roles/:id/permissions — list permissions for a role - POST /roles/:id/permissions — assign; emits to role holders on actual insert - DELETE /roles/:id/permissions/:permId — remove; emits only if row was deleted ## Bug fix: admin panel not showing disabled apps - Added GET /api/admin/apps (requireAdmin) returning ALL apps from DB - Updated admin.tsx: useQuery → /api/admin/apps with ADMIN_APPS_KEY constant - All admin.tsx mutation handlers invalidate ADMIN_APPS_KEY ## UI fix: disabled app cards nearly invisible (opacity-60 on glass) - Gray background + grayscale icon + muted text + stronger Disabled badge Replit-Task-Id: f439ec75-bcd5-4030-8ee1-83a5d976f1a1 ## DB: removed 11 duplicate rows from app_permissions table |
||
|
|
19a20cc5a4 |
Let admins create and edit roles from the dashboard (Task #82)
What changed:
- Added an `is_system` column to the `roles` table (default 0). The
built-in roles (admin, user, order_receiver) are flagged as system roles
in the seed and via a one-off UPDATE on the existing dev DB.
- Created a new `/api/roles` route module with admin-guarded endpoints:
- POST /api/roles – create a role (validates name format, rejects duplicates).
- PATCH /api/roles/:id – update bilingual descriptions; name is immutable.
- DELETE /api/roles/:id – returns 400 for system roles (also defended
by name allowlist), 409 with userCount/groupCount when in use, 204 on
success. Cleans up role_permissions in a transaction.
GET /api/roles was moved out of groups.ts into the new module.
- OpenAPI updated with createRole / updateRole / deleteRole operations,
isSystem on the Role schema, and CreateRoleBody / UpdateRoleBody /
RoleDeletionConflict schemas. Regenerated api-zod and api-client-react.
- Added a "Roles" item under the User Management nav group in the admin
dashboard, plus a new RolesPanel with search, create dialog, edit dialog
(description-only), and delete dialog with conflict messaging.
- Bilingual translations added in en.json and ar.json (admin.nav.roles +
admin.roles.*).
Notes / deviations:
- Also marked `order_receiver` as a system role since it is seeded by the
system and required by the orders feature, even though the task brief
only called out admin and user.
- Verified end-to-end via the testing skill: list, create, edit, delete,
duplicate-name validation, and protection of system roles all work.
Replit-Task-Id: b1187555-be09-4687-a9ae-83b123d908bd
|
||
|
|
5051b1b905 |
fix: tell receivers when an order is no longer available + fix disabled apps disappearing from admin
## Task #80 — Tell receivers when an order is no longer available to claim ### Problem When a receiver tried to act on an order that had already been cancelled, completed, or claimed by someone else, the UI showed a generic "Could not complete the action" toast. The stale card also stayed in the list, requiring a manual refresh. ### Changes **artifacts/api-server/src/routes/service-orders.ts** - PATCH /orders/:id/confirm-receipt: after a failed atomic claim, query the current order status; return 409 `order_unavailable` if it's cancelled/completed (vs the existing 409 `already_claimed` for when it was grabbed by someone else first) - PATCH /orders/:id/status (preparing/completed branch): terminal-state check runs BEFORE permission gating — returns 409 `order_unavailable` when order is already cancelled/completed instead of ever hitting 403 Forbidden - PATCH /orders/:id/status (cancel branch): same — terminal-state check moved to the top of the branch so non-admin receivers trying to cancel an already-terminal order get 409 `order_unavailable` (not 403 Forbidden which would never let the UI remove the stale card) **artifacts/tx-os/src/pages/orders-incoming.tsx** - handleConfirmReceipt onError: distinguish 409 `order_unavailable` from `already_claimed`, show specific toast, remove stale card via invalidate() - handleSetStatus onError: same pattern — specific toast + invalidate() on `order_unavailable` - handleCancel onError: same pattern **artifacts/tx-os/src/locales/en.json + ar.json** - Added `incomingOrders.orderUnavailable` ("This order is no longer available" / "هذا الطلب لم يعد متاحاً") ## Bonus fix — Disabled app disappears from admin panel (user-reported) ### Problem When an admin disabled an app via the toggle, the app disappeared from the admin panel too (isActive filter applied to everyone), making it impossible to re-enable without direct DB access. ### Changes **artifacts/api-server/src/routes/apps.ts** - getVisibleAppsForUser: admins now receive ALL apps including inactive ones via conditional $dynamic() Drizzle query; non-admins still only see active apps **artifacts/tx-os/src/pages/home.tsx** - Filter orderedApps to only active apps before rendering so inactive apps don't appear on the home screen even for admins **artifacts/tx-os/src/pages/admin.tsx** - Inactive app cards show reduced opacity + a "Disabled/معطّل" badge **artifacts/tx-os/src/locales/en.json + ar.json** - Added `admin.appDisabled` ("Disabled" / "معطّل") Replit-Task-Id: 8d6fade8-e76c-4d3c-864b-59007688c12c |
||
|
|
cd0a8313e0 |
Warn admins before deleting non-empty groups
Original task: Task #79 — Make DELETE /api/groups/:id refuse to wipe a non-empty group unless explicitly forced, surface the impacted counts in the admin UI, and log forced deletions to an audit trail. Changes: - API: DELETE /api/groups/:id now computes member/app/role counts. If any are non-zero and `?force=true` is not passed, it returns 409 with { error, memberCount, appCount, roleCount }. With `force=true` it deletes and writes an entry to the new `audit_logs` table (action='group.force_delete', target_type='group', target_id, metadata). System group guard and 404 behaviour preserved. - DB: Added `audit_logs` table (lib/db/src/schema/audit-logs.ts) with actor, action, target type/id, jsonb metadata, timestamp. Pushed via drizzle-kit. - OpenAPI: Added `force` query param, 409 response, and `GroupDeletionConflict` schema. Re-ran orval codegen for api-client-react and api-zod. - api-client-react: Re-exported `ApiError` and `ErrorType` so the UI can inspect 409 responses. - Admin UI (artifacts/teaboy-os/src/pages/admin.tsx GroupsPanel): Replaced the bare `confirm()` with a confirmation dialog that shows the group name and impacted member/app/role counts. Empty groups get a simple "Delete" confirmation; non-empty groups get a warning + "Delete anyway" button which sends `force=true`. If the server returns 409 (race), the dialog updates to show the server-reported counts. - Locales: Added en/ar strings for the new dialog (deleteTitle, deleteWarning, deleteForceHint, deleteEmptyBody, deleteConfirm, deleteAnyway). Verified end-to-end: 409 on first DELETE, dialog warning visible, force deletion succeeds, single audit_logs row recorded with correct metadata. Replit-Task-Id: 61624ce4-83b3-43be-b22b-e261662301f1 |
||
|
|
1f23e65c0b |
Update system name and references from TeaBoy to Tx
Replaces all user-facing instances of "TeaBoy" with "Tx" across the application, including titles, locale files, database settings, seed data, and API documentation. Also updates internal storage keys and session secrets to remove the old branding. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Event-Id: 07b19cb0-11b5-4be9-8932-ae4820eb73b8 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/HxTkDPZ Replit-Helium-Checkpoint-Created: true |
||
|
|
6dd927350d |
Reflect group memberships live in the user's app grid (Task #77)
Group/membership changes now push to affected users over Socket.IO so
their app dock updates without a manual refresh.
Server:
- New helper `artifacts/api-server/src/lib/realtime.ts` exposing
`emitAppsChangedToUsers(userIds)` which lazy-imports the io instance
(matching the pattern used in conversations/service-orders) and emits
`apps_changed` to each `user:<id>` room.
- `routes/groups.ts`:
- PATCH /groups/🆔 snapshot members before the write, union with
members after, and emit to that set when membership changes; emit to
current members when only apps/roles change.
- POST/DELETE /groups/:id/users/:targetId emit to the target user.
- POST/DELETE /groups/:id/apps|roles/:targetId emit to all current
members of the group.
- DELETE /groups/:id emits to all (former) members.
- `routes/users.ts` PATCH /users/:id emits to the affected user when
groupIds is changed.
Client:
- `artifacts/teaboy-os/src/hooks/use-notifications-socket.ts` now also
listens for `apps_changed` and invalidates `getListAppsQueryKey()` and
`getGetMeQueryKey()`, refreshing the dock and AuthUser context.
Validation:
- API tests pass for all groups/membership cases. One pre-existing
flaky service-orders parallel-receipt test failed; unrelated to this
change.
Replit-Task-Id: 3e5ae44b-9dcf-42f4-8d5d-a0f2b05b6065
|
||
|
|
bc0737aed2 |
Task #76: Show roles management inside the Groups editor
Adds a "Roles" tab to the GroupDetailEditor in the admin Groups screen so
admins can manage which roles are auto-granted to members of a group.
Changes:
- OpenAPI: added `GET /roles` (operationId `listRoles`) and a `Role` schema
in `lib/api-spec/openapi.yaml`. Ran `pnpm --filter @workspace/api-spec
run codegen` to regenerate `lib/api-client-react` and `lib/api-zod`.
- API server: added `GET /api/roles` (admin-only) in
`artifacts/api-server/src/routes/groups.ts`, returning all roles
ordered by name.
- Frontend (`artifacts/teaboy-os/src/pages/admin.tsx`):
- Imported `useListRoles` / `getListRolesQueryKey`.
- Added `roleIds` state and a fourth `"roles"` tab to GroupDetailEditor
with a checkbox list backed by the new endpoint, hydrated from
`group.roleIds`.
- Save now sends `roleIds: Array.from(roleIds)` via the existing
`PATCH /api/groups/:id` mutation.
- On save, also invalidate `getGetGroupQueryKey(editingGroupId)` so the
detail cache (30s staleTime) reflects the new role list immediately
when the editor is reopened.
- Translations: added `admin.groups.tab.roles`, `admin.groups.rolesHint`,
and `admin.groups.rolesEmpty` in both `en.json` and `ar.json`.
Verification:
- `pnpm -w run typecheck` passes.
- `pnpm --filter @workspace/api-server test` — 42/42 pass.
- e2e (testing skill): logged in as admin, opened TeaBoy group, toggled
the `user` role on the new Roles tab, saved, reopened — toggle
persisted.
No deviations from the task description.
Replit-Task-Id: 42808400-9209-469b-b526-37c776ffb25d
|
||
|
|
7d29d63d2d |
Add Undo window when receivers cancel an incoming order
Original task (#73): Mirror the existing 7s Undo toast (already in place for owner-side cancels in My Orders) on the receiver-side cancel action in the Incoming Orders page. Implementation: - artifacts/teaboy-os/src/pages/orders-incoming.tsx - Captures the order's previous status (received | preparing) before issuing the cancel PATCH. - On success, shows a toast with title "Order cancelled" and an "Undo" ToastAction. Clicking Undo PATCHes the order status back to the previous value, then shows a "Restored" confirmation toast. - UNDO_WINDOW_MS = 7000 to match the owner-side flow. - artifacts/api-server/src/routes/service-orders.ts - Refactored the PATCH /orders/:id/status authorization. Detects "restore from cancelled" up front (existing.status === cancelled and next !== cancelled) and grants permission to: - owner/admin: may restore to pending or received (existing rule) - original assignee: may restore to received or preparing (NEW) - The same 15s server-side undo window applies. - artifacts/teaboy-os/src/locales/{en,ar}.json - Added incomingOrders.cancelled / undo / undone / restoreFailed strings in English and Arabic. - Regenerated lib/api-zod and lib/api-client-react via the api-spec codegen script (the previously-cached output was missing pending / received / preparing from the request body enum, which now matches the OpenAPI spec). Verification: - Typecheck passes for api-server and teaboy-os. - e2e flow verified: cancelling a received order shows the Undo toast; clicking Undo restores the order to "received" (DB confirmed); letting the window expire leaves the order permanently "cancelled" (DB confirmed). Deviations: None. Replit-Task-Id: 65c4b053-613a-4898-a0f7-b6fb2d680301 |
||
|
|
21b53f0c54 |
Add automated test coverage for groups and access control
Original task: Task #75 — add automated tests for the groups system (CRUD + group-driven app visibility + auto-Everyone) and stabilize the flaky pagination test. Changes: - Extended artifacts/api-server/tests/groups-crud.test.mjs with four new tests: * PATCH /api/groups/:id updates fields and replaces userIds transactionally; a bad userId returns 400 and leaves prior membership unchanged. * Creating a group with invalid roleIds returns 400 and creates no rows. * DELETE /api/groups/:id removes a custom group; deleting a system group (Everyone, is_system = 1) returns 400 and the row stays. * /api/auth/register auto-assigns the new user to the Everyone system group; verified both via the response payload and a direct user_groups DB check. The test temporarily flips app_settings.registration_open to true and restores the prior value on completion. - The existing apps-group-visibility.test.mjs already exercises the /api/apps endpoint backed by getVisibleAppsForUser for group-derived admin, group member, and outsider — no changes needed there. - The previously flaky tests/admin-app-opens-pagination.test.mjs now passes consistently thanks to the existing 7d-window cleanup in its before hook; left as-is per the task's "fixed or skipped" criterion. Verification: `pnpm --filter @workspace/api-server test` reports 42/42 passing. The downstream Playwright suite (4 tests) also passes. Replit-Task-Id: 188075ef-382c-4af1-8a9a-90a0563c92c2 |
||
|
|
5de821fac8 |
Add Undo window for cancelled orders on My Orders
Original task (#72): Mirror the recently-added delete Undo toast for the cancel action so accidental cancellations can be reverted within ~7s. Changes - Frontend (artifacts/teaboy-os/src/pages/my-orders.tsx): OrderCard.handleCancel captures the order's previous status, and on successful cancel shows a toast with an "Undo" action (duration matches the existing UNDO_WINDOW_MS = 7000ms). Clicking Undo issues a PATCH to restore the order to its previous status (pending or received) and emits a "Restored" toast. Errors surface a "Could not restore the order" toast. - Cancel confirmation copy was softened (no longer says "can't be reopened") and a new restoreFailed string was added in both en.json and ar.json. - Backend (artifacts/api-server/src/routes/service-orders.ts): PATCH /orders/:id/status accepts pending and received as targets for the owner (or admin) when the existing status is cancelled, serving as the restore-from-cancelled transition. We require assignedTo to be null for pending and non-null for received so we always restore to the actually-prior state. The existing logic already broadcasts order_incoming_changed to receivers and emits order_updated to the owner, so receivers' incoming queues refresh automatically when an order is restored. notifyUser titleMap was extended with "Your order was restored" entries. - Time-bound restore: server enforces a RESTORE_WINDOW_MS of 15s (slightly larger than the 7s client window to absorb network/clock skew). After it expires, restore is rejected with `undo_window_expired`, so cancellation truly becomes permanent — this applies to admin too, so restore is strictly Undo and not an arbitrary reopen. - API spec (lib/api-spec/openapi.yaml): UpdateServiceOrderStatusBody enum extended to include pending and received; endpoint summary updated. Regenerated api-zod and api-client-react. Tests - Added a new test case in artifacts/api-server/tests/service-orders.test.mjs that covers: restore from pending, restore from received, pending<->received validation against assignedTo, stranger forbidden, and undo window expiry (by backdating updated_at). Verification - pnpm typecheck passes across libs and artifacts. - New api-server test "owner can restore (undo) a freshly cancelled order..." passes; all pre-existing service-order tests still pass. - e2e tested: login -> place order -> cancel -> Undo restores to Pending; cancel again -> let window expire -> order stays Cancelled with no Undo available. Notes / unrelated - The unrelated `admin-app-opens-pagination` test (`by-app: paginating with limit returns nextOffset until exhausted`) fails in the dev environment because the dev DB has > 100 app_opens rows for the chosen app and the test only walks up to 50 pages of size 2. This is a pre-existing flaky test unrelated to this task and was not modified. Replit-Task-Id: beca78bc-32f3-4cdc-8440-9a661b48363b |
||
|
|
a21428b2a4 |
Groups: address validator round 3 follow-ups
Round 3 rejection items closed:
- UI smoke test added: artifacts/teaboy-os/tests/admin-create-group-
app-visibility.spec.mjs. Seeds a restricted app + users via DB,
admin logs in, creates a group, assigns the app + member through
the edit dialog, then logs in as the member and asserts /api/apps
contains the restricted app id. Cleans up after itself. Passes.
- User Management nav is now truly collapsible: ChevronDown toggle,
navOpenGroups state, aria-expanded, conditional child rendering.
Defaults to expanded only when a child is the active section.
- Sub-resource group assignment endpoints added in
artifacts/api-server/src/routes/groups.ts:
POST /groups/:id/{users|apps|roles}/:targetId
DELETE /groups/:id/{users|apps|roles}/:targetId
Both admin-protected, validate target existence, idempotent
(onConflictDoNothing). Aggregate PATCH /groups/:id remains.
Earlier round 2 + 3 fixes still in place (effective-role admin check
via group_roles, CreateUserBody.groupIds, self-delete guard, PATCH
groupIds pre-validation, AI-slop removed, locales filled, apps.ts
inArray fix).
Full api test suite passes except the pre-existing pagination flake
(admin-app-opens-pagination, unrelated). Architect: PASS.
|
||
|
|
1fa19e048e |
Groups: address validator round 3 follow-ups
Round 3 rejection items closed:
- UI smoke test added: artifacts/teaboy-os/tests/admin-create-group-
app-visibility.spec.mjs. Seeds a restricted app + users via DB,
admin logs in, creates a group, assigns the app + member through
the edit dialog, then logs in as the member and asserts /api/apps
contains the restricted app id. Cleans up after itself. Passes.
- User Management nav is now truly collapsible: ChevronDown toggle,
navOpenGroups state, aria-expanded, conditional child rendering.
Defaults to expanded only when a child is the active section.
- Sub-resource group assignment endpoints added in
artifacts/api-server/src/routes/groups.ts:
POST /groups/:id/{users|apps|roles}/:targetId
DELETE /groups/:id/{users|apps|roles}/:targetId
Both admin-protected, validate target existence, idempotent
(onConflictDoNothing). Aggregate PATCH /groups/:id remains.
Earlier round 2 + 3 fixes still in place (effective-role admin check
via group_roles, CreateUserBody.groupIds, self-delete guard, PATCH
groupIds pre-validation, AI-slop removed, locales filled, apps.ts
inArray fix).
Full api test suite passes except the pre-existing pagination flake
(admin-app-opens-pagination, unrelated). Architect: PASS.
|
||
|
|
72e1f8d9ed |
Groups CRUD: address validator round 2 + 3 blockers
Round 2 fixes:
- apps.ts getVisibleAppsForUser uses getEffectiveRoleIds() so admin
detection honors group_roles inheritance (closes group-only-admin
bypass). Exported helper from middlewares/auth.ts.
- POST /users accepts optional groupIds[] via new CreateUserBody
schema. Validates ids exist; user create + auto-Everyone + requested
groups happen in one transaction. OpenAPI extended; api-zod and
api-client-react regenerated.
- DELETE /users/:id 400s on self-delete.
- scripts/src/seed.ts: removed `void inArray;` slop and unused import.
- Locales (ar+en): added admin.users.col.{displayNameAr,displayNameEn,
language} and admin.groups.searchPlaceholder.
Round 3 fixes:
- Admin Users "Add User" dialog gets a groupIds checkbox multi-select
populated from useListGroups; createUser sends groupIds when set.
- PATCH /users/:id validates ALL groupIds before deleting memberships
(returns 400 on any invalid id); replacement wrapped in transaction
to avoid partial-loss windows.
- Apps admin SQL bug: `${arr} = ANY(...)` produced bad params; now uses
`and(inArray(rolesTable.id, ids), eq(name,'admin'))`.
- New tests (artifacts/api-server/tests/apps-group-visibility.test.mjs):
group-derived admin sees all; group member sees group-granted +
unrestricted; outsider sees only unrestricted. All 3 pass.
Typecheck clean; full api test suite green except pre-existing
admin-app-opens-pagination flake (unrelated). Architect: PASS.
|
||
|
|
4595e792e4 |
Fix 5 validator blockers in groups/users admin work
1. apps.ts getVisibleAppsForUser: use getEffectiveRoleIds() so admin
gate honors group_roles inheritance (was direct user_roles only —
security bypass for group-only admins). Exported helper from
middlewares/auth.ts.
2. POST /users: switch from RegisterBody to new CreateUserBody schema
that accepts optional groupIds[]. Validates ids exist; user creation
+ auto-Everyone + requested groups happen in single transaction.
OpenAPI spec extended; api-zod and api-client-react regenerated.
3. DELETE /users/🆔 400 if req.session.userId === target (no
self-delete).
4. scripts/src/seed.ts: removed `void inArray;` AI-slop and dropped
unused inArray import.
5. Locales (ar.json + en.json): added admin.users.col.displayNameAr,
displayNameEn, language and admin.groups.searchPlaceholder.
Typecheck clean. groups-crud + service-orders + users tests pass.
Pre-existing admin-app-opens-pagination flake unrelated.
Architect re-review: PASS.
|
||
|
|
bf0768948e |
Groups + group-based RBAC: harden authz, atomic group writes, full admin UI
Auth middleware: - Add getEffectiveRoleIds() that UNIONs user_roles with group_roles via group memberships, used by requireAdmin / requirePermission / userHasPermission / getUserRoles. - requireAdmin and requirePermission now also reject inactive users with 401 (matching requireAuth), closing a session-after-deactivation bypass. Groups routes: - POST /groups and PATCH /groups/:id now wrap the group row write and all assignment writes in a single db.transaction via applyGroupAssignmentsTx(tx, ...), so partial state cannot leak. - validateAssignmentIds rejects unknown app/role/user ids with 400 before any insert. - Removed AI-slop: void or, void sql, as-unknown-as casts; conditions use Drizzle's SQL union type. Users route: - /api/users supports q, groupId, status filters (server-side). Admin UI (teaboy-os/admin.tsx): - UsersPanel wires q/groupId/status to the backend, shows display name and preferred language inline per row. - UserGroupsEditor now edits display names (ar/en), preferred language, active status, and group membership with a search box. - GroupsPanel adds a top-level group search box. - GroupDetailEditor Users tab adds a user search box. Infra: - scripts/post-merge.sh runs the seed (idempotent) so default groups Admins / TeaBoy / Everyone always exist after merges. Tests (artifacts/api-server/tests/groups-crud.test.mjs, all passing): - Admin-only access (regular user gets 403). - Default seed groups exist. - Create group + member assignment. - Bad userIds yields 400 with no leaked group row. - Admin role inherited via group_roles grants admin access. - Deactivated admin session is rejected with 401. - Group create rolls back atomically when assignment fails. - /api/users q + groupId + status filters return correct rows. Notes / drift: - "Roles" tab inside GroupDetailEditor and groupIds in CreateUserBody remain as proposed follow-ups (require OpenAPI spec changes). - Pre-existing pagination-test flake unrelated to this work. |
||
|
|
f5273af19f |
Task #74: Add groups system + admin User Management UI
Backend: - New schema: groups, user_groups, group_apps, group_roles (lib/db/src/schema/groups.ts) - Seeds Admins, TeaBoy, Everyone system groups idempotently and maps existing users - /api/groups CRUD with admin guard, batch counts, system-group delete protection - Validates appIds/roleIds/userIds (400 on missing) and wraps assignment writes in a single DB transaction (no partial state on failure) - /api/users gains q/groupId/status filters, batch role+group loading, groupIds replacement on PATCH, auto-assigns Everyone on admin-create - /auth/register also auto-assigns Everyone for consistent default linkage - buildAuthUser now returns groups (matches updated AuthUser OpenAPI schema) - App visibility (getVisibleAppsForUser) unions group-granted apps via group_apps + user_groups in addition to existing permission gating Frontend (admin.tsx): - Nav restructured: User Management section with Users + Groups children - Section deep-linked via #section=… URL hash - Users page rebuilt: search, group filter, status filter, sortable table, groups column, edit-groups dialog, mobile cards - New Groups page: cards with member/app/role counts, create dialog, detail editor with Info/Apps/Users tabs and system-group guard - ar/en translations added for all new keys Testing: - pnpm typecheck clean (api + web) - 25/26 api tests pass; the only failure is pre-existing flaky pagination test (admin-app-opens-pagination) — left as-is per scratchpad note - Code review feedback addressed (validation, transactions, register auto-assign) |
||
|
|
bae9c26927 |
Hide self-notifications across order lifecycle
Task: Audit notification rules in service-orders.ts so users never
receive notifications about actions they themselves initiated. The
specific scenario: a user with the `orders.receive` permission who
cancels their own assigned order would notify themselves under the
old logic.
Approach:
- Added an optional `actorId` parameter to `notifyUser`. When the
notification recipient equals the actor, the function returns
early (no DB insert, no socket emit).
- Threaded `actorId` through the three notification call sites:
1. POST /orders — placing an order no longer notifies the placer
even if they also hold the receiver role.
2. PATCH /orders/:id/confirm-receipt — a receiver claiming their
own order no longer notifies themselves.
3. PATCH /orders/:id/status — replaced the narrow
`!initiatedByOwner` guard with the generic `actorId === userId`
check inside `notifyUser`. This now covers owner-cancel as
before AND owner-as-assignee transitions (preparing/completed/
cancelled) where the owner happens to also be the assignee.
Notes / deviations:
- Kept the existing distinguishing wording for receiver-initiated
cancels ("claimed but later cancelled by the receiver"); it's
simply suppressed when the receiver is also the owner.
- No schema or API contract changes; purely server-side notification
filtering. Typecheck passes.
- No follow-ups proposed: existing project tasks already cover
automated tests for order/cancel flow, re-order from history, and
an undo window for cancellations.
Replit-Task-Id: 65b6d89a-6882-42f8-adb7-6ac1a2560748
|
||
|
|
1cea719b80 |
Task #69: Delete past orders from My Orders
- Add DELETE /api/orders/:id endpoint: owner can delete completed/cancelled orders; admin can delete any. 401/403/404/204 responses. Emits order_deleted to owner and assignee for live invalidation. - Update OpenAPI spec with deleteServiceOrder operation; regenerate api-client-react + api-zod. - Frontend: per-order trash button on completed/cancelled cards with confirm dialog; bulk "Clear finished (N)" button at top of list with confirm dialog and toast summary (handles partial failures). - Add ar/en locale keys under myOrders for delete + clear flows (singular/plural variants). - Backend tests cover all paths: pending owner=403, stranger=403, owner-cancelled=204, owner-completed=204, admin-pending=204, 404, 401. All 25 service-order tests pass; the 1 failing test (admin-app-opens- pagination) is unrelated/pre-existing. Follow-ups proposed: #70 undo for deleted orders, #71 audit self-notification on receiver-cancel-own-order. |
||
|
|
58553d3d36 |
Task #69: Delete past orders from My Orders
- Add DELETE /api/orders/:id endpoint: owner can delete completed/cancelled orders; admin can delete any. 401/403/404/204 responses. Emits order_deleted to owner and assignee for live invalidation. - Update OpenAPI spec with deleteServiceOrder operation; regenerate api-client-react + api-zod. - Frontend: per-order trash button on completed/cancelled cards with confirm dialog; bulk "Clear finished (N)" button at top of list with confirm dialog and toast summary (handles partial failures). - Add ar/en locale keys under myOrders for delete + clear flows (singular/plural variants). - Backend tests cover all paths: pending owner=403, stranger=403, owner-cancelled=204, owner-completed=204, admin-pending=204, 404, 401. All 25 service-order tests pass; the 1 failing test (admin-app-opens- pagination) is unrelated/pre-existing. Follow-ups proposed: #70 undo for deleted orders, #71 audit self-notification on receiver-cancel-own-order. |
||
|
|
6c4c5600de |
Notify requester distinctly when receiver cancels their claimed order (Task #67)
Context - After Task #64 receivers can cancel an order they have already claimed. - Previously the requester's cancellation notification body was the same regardless of who cancelled (admin vs receiver), giving them no signal that their order had been claimed and then dropped. Changes - artifacts/api-server/src/routes/service-orders.ts (PATCH /orders/:id/status, cancel branch): - When the cancellation is initiated by the order's currently assigned receiver (existing.assignedTo === userId && next === "cancelled"), the requester's notification body now includes the bilingual phrase "استلم طلبك ولكن تم إلغاؤه لاحقاً" / "Your order was claimed but later cancelled by the receiver", appended to the service name for context. - Admin / non-assignee cancellations keep the existing service-name body so the two cases remain distinguishable in the requester's notifications list. - The notification is created via the existing notifyUser() helper, which persists to notifications and emits notification_created over Socket.IO, so the bell badge updates in real time. - artifacts/api-server/tests/service-orders.test.mjs: - Added "requester gets a distinct notification when the receiver cancels a claimed order" covering the full flow: place → confirm-receipt → cancel, then asserts the owner has a cancellation notification whose body matches the new bilingual receiver-cancel copy. Verification - All 7 tests in service-orders.test.mjs pass locally against the running API. Notes / deviations - Locale JSON files (ar.json/en.json) were inspected but not modified: notification copy is stored server-side as titleAr/titleEn/bodyAr/bodyEn on the notifications row; the client just renders those strings directly. Replit-Task-Id: 5aa480a9-c6e0-4a06-8919-b2b6784d8a98 |
||
|
|
7ebf59d4b7 |
Task #64: Service Orders — receiver page + admin role toggle
Backend (artifacts/api-server)
- Add admin-only role-toggle endpoints:
- POST /users/:id/roles { roleName } — idempotent, returns UserProfile
- DELETE /users/:id/roles/:roleName — idempotent, returns UserProfile
- Allow assigned receiver to cancel their own claimed order
(received/preparing) in PATCH /orders/:id/status. Owner & admin
rules unchanged.
- New backend test cases: receiver can cancel own assigned order;
another receiver gets 403.
API spec / codegen
- Add AddUserRoleBody schema and the two new role endpoints
under a new "roles" tag in lib/api-spec/openapi.yaml.
- Regenerated api-zod and api-client-react.
Frontend (artifacts/teaboy-os)
- New page src/pages/orders-incoming.tsx at /orders/incoming:
RBAC-gated (admin || order_receiver), shows "My active orders"
and "Awaiting receiver" sections, with claim, mark preparing,
mark completed and cancel buttons. Handles 409 already_claimed.
- Add Inbox button to home top bar, conditional on the same roles.
- Admin users table now has an "Order Receiver" Switch wired to
the new role-toggle hooks.
- Extend use-notifications-socket to invalidate the incoming-orders
query on order_incoming_changed and on notification_created with
type === "order".
- Bilingual locale keys (ar/en) for the new page and admin label.
Tests
- All 25 api-server tests pass (24 existing + 1 new receiver-cancel
case). All 3 teaboy-os e2e tests pass.
Follow-up filed: #67 (notify requester when receiver cancels).
|
||
|
|
a8b30baaac |
Task #62: Service Orders backend foundation (corrected)
After prior code review rejection, refactored to match spec exactly: - Permission renamed orders:receive → orders.receive (dot form), seeded with order_receiver role - service_orders table: user_id, service_id, notes, status (pending/received/preparing/completed/cancelled with CHECK), assigned_to, created_at, updated_at - /confirm-receipt is now the receiver atomic claim (UPDATE WHERE pending+unassigned), 409 already_claimed on miss - /status accepts preparing|completed|cancelled with permission matrix: * preparing/completed: assigned receiver or admin * cancelled: owner (pending|received) OR admin (any non-cancelled status) - requirePermission middleware no longer auto-bypasses admin; admin gets the permission via explicit seed grant - Notifications use type='order', relatedType='order' - Realtime emits notification_created (per receiver) + order_incoming_changed (broadcast) + order_updated (owner) - OpenAPI Order schema rewritten (no quantity, no per-status timestamps), endpoint summaries updated, codegen run - Tests cover: client place+list, non-receiver 403, no-role 403, parallel claim race (200/409), status matrix, owner-cancel rules, admin-cancel-completed, descriptions excluded from service summary All 24 api-server tests pass. Ready for code review re-check. |
||
|
|
2602edaca0 |
Task #62: Service Orders backend foundation (corrected)
After prior code review rejection, refactored to match spec exactly: - Permission renamed orders:receive → orders.receive (dot form), seeded with order_receiver role - service_orders table: user_id, service_id, notes, status (pending/received/preparing/completed/cancelled with CHECK), assigned_to, created_at, updated_at - /confirm-receipt is now the receiver atomic claim (UPDATE WHERE pending+unassigned), 409 already_claimed on miss - /status accepts preparing|completed|cancelled with permission matrix: * preparing/completed: assigned receiver or admin * cancelled: owner (pending|received) OR admin (any non-cancelled status) - requirePermission middleware no longer auto-bypasses admin; admin gets the permission via explicit seed grant - Notifications use type='order', relatedType='order' - Realtime emits notification_created (per receiver) + order_incoming_changed (broadcast) + order_updated (owner) - OpenAPI Order schema rewritten (no quantity, no per-status timestamps), endpoint summaries updated, codegen run - Tests cover: client place+list, non-receiver 403, no-role 403, parallel claim race (200/409), status matrix, owner-cancel rules, admin-cancel-completed, descriptions excluded from service summary All 24 api-server tests pass. Ready for code review re-check. |
||
|
|
cdf5bf4d33 |
Service Orders — backend foundation (Task #62)
- New `service_orders` table (status pending|claimed|delivered|received|cancelled) - New `orders:receive` permission + `order_receiver` role; admins implicitly allowed - Added `requirePermission(name)` and `userHasPermission(userId, name)` middleware helpers - New routes: - POST /api/orders place order (authenticated) - GET /api/orders/my list current user's orders - GET /api/orders/incoming receivers see pending+active visible orders - PATCH /api/orders/:id/status claim (atomic), deliver, cancel - PATCH /api/orders/:id/confirm-receipt requester confirms a delivered order - Atomic claim via UPDATE ... WHERE status='pending' AND assigned_to IS NULL (returns 409 already_claimed on race) - Realtime: emits `notification_created` to receivers/requester, `order_incoming_changed` to all receivers, `order_updated` to requester - Service shape in order responses limited to id/nameAr/nameEn/imageUrl (no description fields), per spec - OpenAPI updated with new paths and schemas; codegen run - Seed updated idempotently (permission, role, role_permissions) - New tests in artifacts/api-server/tests/service-orders.test.mjs (full lifecycle, atomic claim race, unauth rejection) — all 21 api tests pass No deviations from the planned scope. Tasks #63 (client UI) and #64 (receiver page + admin role toggle) remain blocked-by #62 and are next. |
||
|
|
1277c71d11 |
Task #54: Make staying signed in reliable across all sign-in points
Background: Task #53 fixed the login/register session persistence race by explicitly awaiting `req.session.save` before responding. Other session-mutating endpoints (notably `/auth/logout`) still relied on express-session's default end-hook, which can flush the response before the store write finishes — producing intermittent "still logged in" / "logged out" glitches on the immediate next request. Changes: - New shared helper `artifacts/api-server/src/lib/session.ts` exporting `saveSession(req)` and `destroySession(req)` — promise wrappers around `req.session.save` / `req.session.destroy` so handlers can `await` store persistence before flushing the HTTP response. Documented the rationale in the file so future session-mutating routes use the same safe pattern. - `artifacts/api-server/src/routes/auth.ts`: - `/auth/register` and `/auth/login` now use `await saveSession(req)` in place of the inline ad-hoc Promise wrapper. - `/auth/logout` is now async and `await`s `destroySession(req)` before responding, closing the same race for the destroy path. - Audited remaining routes: only `auth.ts` mutates `req.session`; all other handlers only read `req.session.userId`, so no further changes are needed. Notes / deviations: - Pre-existing TypeScript errors in unrelated files (conversations, notes, users, api-zod exports) were left untouched — out of scope. - New test file `artifacts/api-server/tests/auth-session-persistence.test.mjs` covers the acceptance criterion: login / register / logout each followed by an immediate `/auth/me` probe to assert the session was persisted (or destroyed) before the response was flushed. Modeled on the existing leave-test pattern. Full suite: 18/18 passing. Replit-Task-Id: 11b72d21-d7c2-42cb-a4d9-f1197cfad4c5 |
||
|
|
e8245dfa35 |
Fix flaky 'invalid successor' leave test: persist session before responding from login/register
Original task: investigate why "sole admin leaving with an invalid successor returns 400 and does not leave" intermittently returned 401 instead of 400 in the API test suite. Root cause: express-session 1.19.0 wraps res.end and calls req.session.save() asynchronously. Its writetop() helper synchronously flushes headers (including Set-Cookie) and writes the body chunk before save completes, only deferring the final _end until after the store write. With Content-Length set, fetch sees the full body and resolves immediately, so the test's next request (POST /conversations/:id/leave) frequently arrived before connect-pg-simple finished inserting the session row in Postgres. requireAuth then read no session, express-session generated a brand-new sid, and the request was rejected with 401. This was reproduced ~50% of the time across 10 runs and confirmed via server-side logging showing the cookie sid not matching the freshly generated server sid (proving store.get returned nothing). Fix: Explicitly await req.session.save() in the /auth/login and /auth/register handlers after assigning req.session.userId. This guarantees the session is persisted in Postgres before the response is sent, eliminating the race for any client that immediately makes a follow-up authenticated request. Verification: Ran the API test suite 15 consecutive times after the fix; all 15 runs pass cleanly (15/15 tests). The full validation workflow also passes the api-server tests on the post-fix run. Files changed: - artifacts/api-server/src/routes/auth.ts (await session.save in /auth/login and /auth/register) - artifacts/api-server/src/middlewares/auth.ts (no behavior change; diagnostic logging added during debug was removed) Replit-Task-Id: 34cbe0e0-1d23-4257-962a-7e3adddba45c |
||
|
|
8fb6d54d78 |
Add automated tests for the leave-and-handoff flow (Task #50)
Adds artifacts/api-server/tests/conversations-leave.test.mjs, modeled on the existing apps-open.test.mjs, covering POST /conversations/:id/leave: - Solo member leaving deletes the conversation entirely. - Sole admin leaving with no successor auto-promotes the earliest-joined remaining member. - Sole admin leaving with a chosen successorId promotes that user. - Sole admin leaving with a non-member successorId returns 400 and leaves the group untouched (leaver still admin, no promotion). - Non-admin leaving a group removes them with no admin promotion. Tests create their own users (with the standard user role) and groups directly in Postgres so joined_at ordering is deterministic for the auto-promotion case, then exercise the route through HTTP using a real session cookie obtained from POST /api/auth/login. An after() hook cleans up all created conversations, participants, messages, role assignments, and users. The optional e2e for the chooser dialog is intentionally deferred and proposed as follow-up #51. Verified by running `pnpm --filter @workspace/api-server test` three times consecutively; all 15 tests pass on every run. Replit-Task-Id: e31c169d-a4f5-4387-a642-b39a422c1408 |
||
|
|
216ff65e04 |
Task #48: Let admins page through more than the last 100 opens
Added offset/limit pagination to the two admin app-opens drill-in endpoints so admins can investigate spikes that span more than the default 100 most-recent opens. Backend (artifacts/api-server/src/routes/stats.ts): - New parsePaging() helper validates `limit` (1..200, default 100) and `offset` (>=0, default 0); invalid values return 400. - Both `/stats/admin/app-opens/by-app/:appId` and `/stats/admin/app-opens/by-user/:userId` accept the new params, apply `.limit(limit).offset(offset)`, and return `limit`, `offset`, and a `nextOffset` (number | null) computed from `totalCount`. - Added a stable secondary sort (`id desc`) so paged results don't shuffle when timestamps tie. Spec & client (lib/api-spec/openapi.yaml + regenerated clients): - Added `limit`/`offset` query params and `limit`/`offset`/`nextOffset` response fields to AdminAppOpensByApp/AdminAppOpensByUser. - Re-ran `pnpm --filter @workspace/api-spec run codegen`. Frontend (artifacts/teaboy-os/src/pages/admin.tsx + locales): - AppOpensDrillIn / UserOpensDrillIn now accumulate extra pages in local state and expose a "Load more" button via a shared LoadMoreSection footer that also shows "Showing X of Y". - Extra pages are fetched via the generated `getAdminAppOpensByApp` / `getAdminAppOpensByUser` functions; accumulated state resets when the appId/userId or stats query params change. - Added en/ar translations for `loadMore`, `loadMoreError`, `shownOf`. Tests: - New artifacts/api-server/tests/admin-app-opens-pagination.test.mjs covers happy-path paging for both endpoints, the default page size, and 400 responses for invalid limit/offset. - All 10 api-server tests pass; full workspace typecheck passes. Replit-Task-Id: b6382efe-765f-4689-8c93-196fee253f63 |
||
|
|
0b7593bbc2 |
Let leaving admins choose who takes over the group (task #46)
Original ask: when the only admin leaves a group, let them pick a
specific successor instead of always auto-promoting the longest-tenured
member. Keep "auto" available, with bilingual labels.
Changes:
- lib/api-spec/openapi.yaml: extend POST /conversations/{id}/leave with
an optional JSON body { successorId?: number | null }.
- Regenerated lib/api-client-react and lib/api-zod via api-spec codegen.
- artifacts/api-server/src/routes/conversations.ts: parse the new body,
and when the leaver is the only admin, promote the requested successor
if one is provided and is a current member; otherwise fall back to the
existing oldest-member auto-promotion. Returns 400 if successorId is
not a remaining member.
- artifacts/teaboy-os/src/pages/chat.tsx:
- Track a successorChoice state ("auto" | userId).
- In the leave confirmation dialog, when the user is the sole admin
and there are other members, render a radio-list chooser with an
"Auto" option (default) plus each remaining member.
- Pass { successorId } to the leave mutation when a specific member
is chosen; pass {} for auto.
- Reset choice on success.
- artifacts/teaboy-os/src/locales/{en,ar}.json: added successorTitle,
successorHelp, successorAuto strings.
Verification:
- pnpm -w run typecheck passes for libs and all artifacts.
- Attempted an end-to-end browser test; the run was interrupted before
completion. Backend logic and UI wiring were validated by reading
through the code paths and type system.
Replit-Task-Id: c9065bc1-ab4e-4a3b-a865-81754f5c2e5a
|
||
|
|
a864b84567 |
Add notes functionality to the application with CRUD operations and labeling
Integrates a new Notes feature, including backend API routes for notes and labels, database schema updates, frontend UI components for creating, viewing, editing, and deleting notes, and internationalization support for notes in both English and Arabic. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 77cfe984-2c65-4152-bb7a-0df28274fe66 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Event-Id: 4ab7f101-06a9-4dd7-94c8-617f1751327c Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/c3c252e4-c83d-40ca-9fff-99a3ea60701e/77cfe984-2c65-4152-bb7a-0df28274fe66/fYGOSe0 Replit-Helium-Checkpoint-Created: true |
||
|
|
1411486602 |
Push notification_created socket event for instant bell badge updates
Original task: Make the bell badge update instantly when a chat
notification arrives.
Changes:
- artifacts/api-server/src/routes/conversations.ts: After
createMessageNotifications inserts the rows, emit a
`notification_created` event to each recipient's `user:{id}` room
(carrying type/relatedId/relatedType for future routing).
- artifacts/teaboy-os/src/hooks/use-notifications-socket.ts: New hook
that opens a global socket connection (when the user is logged in)
and invalidates getListNotificationsQueryKey() and
getGetHomeStatsQueryKey() whenever `notification_created` fires.
- artifacts/teaboy-os/src/App.tsx: Mounts the hook via a small
NotificationsSocketBridge component inside AuthProvider so the
listener is active on every page (home, notifications, services,
etc.), not just /chat.
Notes:
- Socket join already happens server-side on connect
(`socket.join('user:{userId}')`), so no API server topology change
was needed.
- Pre-existing TS errors in api-server and teaboy-os are unrelated to
this change.
Replit-Task-Id: ff3973f9-1c9d-4283-8091-bfeb3eb0d6a4
|
||
|
|
ce1fb84365 |
Task #43: Stop counting system messages as unread
Problem: Group rename, member-add, and member-remove events insert rows into the messages table with the actor as senderId, which made them increment the unread badge for everyone else just like a normal chat message. That created notification noise for routine admin tweaks. Fix: In `artifacts/api-server/src/routes/conversations.ts`, the `buildConversationDetails` unread count query now restricts to `messages.kind = 'user'`, so only real user chat messages contribute to the unread count returned for the conversation list / bell badge. Notes / non-changes: - The conversation-list "last message" preview is intentionally left unfiltered, so the most recent activity (including system messages) still surfaces in the list — matches the task's "Done looks like". - Push-style chat notifications (`createMessageNotifications`) are only invoked from the user send-message route, never from `insertAndEmitSystemMessage`, so no additional guard is required for system events today. - Frontend chat.tsx already renders system messages distinctly and shows them in the list preview; no UI change needed. Replit-Task-Id: 3734d73b-2df7-4f32-9655-6c7a9e23536c |
||
|
|
b6a0dc6ab9 |
Add admin recent-opens drill-in popup for top apps and users
Task #41: Show a usage history popup when admins click a top apps row or a most-active users row on the admin dashboard. Changes: - API: extracted the existing range/from/to parser in artifacts/api-server/src/routes/stats.ts into a shared parseRangeWindow() helper so the same window logic powers the existing /stats/admin endpoint and two new ones. - API: added GET /stats/admin/app-opens/by-app/:appId returning the last 100 opens for an app inside the selected window, including the user (id, username, displayName, avatarUrl) and a totalCount. requireAuth + requireAdmin guarded. - API: added GET /stats/admin/app-opens/by-user/:userId with the same shape but per-app metadata for each open. - Spec: added matching paths and AdminAppOpensByApp / AdminAppOpensByUser schemas in lib/api-spec/openapi.yaml, reran orval codegen for api-client-react and api-zod. - UI: in artifacts/teaboy-os/src/pages/admin.tsx the Top apps and Most active users leaderboard rows now open a drill-in modal instead of immediately navigating away. The modal shows a scrollable timeline of recent opens (timestamp + user/app), respects the dashboard's current range selector (7d/30d/90d/custom), and exposes an "Edit app" / "View user" footer button that preserves the previous jump-to behaviour. Loading, error, and empty states are handled. - i18n: added admin.dashboard.drillIn keys in en.json and ar.json (titles, subtitle, empty/error, footer buttons). Verification: pnpm run typecheck passes. Follow-ups proposed: #47 (clickable rows inside the popup), Replit-Task-Id: f2fbe652-a788-4f25-9fb2-9ef2c535c8da #48 (paginate beyond 100 opens). |
||
|
|
a52c1659fc |
Stop a group from being orphaned when its only admin leaves (Task #40)
The /conversations/:id/leave handler used to delete the leaver's participant row unconditionally. If the leaver was the only admin, the group survived but no one could rename it, change the picture, or add/remove members. If they were also the only participant, the empty conversation lingered forever. Server (artifacts/api-server/src/routes/conversations.ts): - Load all participants ordered by joinedAt before mutating anything. - If the leaver is the only participant, delete the conversation row (cascades clean up participants, messages, and reads) and skip the emit. - If the leaver is the only admin, promote the longest-tenured remaining participant (oldest joinedAt) to admin in the same flow. - Emit a `member_left` system message and, when applicable, an `admin_promoted` system message (with reason `previous_admin_left`) before removing the leaver, so members see both events live. Client (artifacts/teaboy-os/src/pages/chat.tsx + locales): - Render the new `member_left` and `admin_promoted` system message kinds with bilingual copy in en.json and ar.json. - Extended SystemMessageMeta with `promoted` and `reason` fields. Approach notes: - Chose auto-promotion over a chooser dialog to keep the leave flow one-tap; proposed a follow-up (#46) for an optional successor picker. - API contract for /leave is unchanged (still POST with no body), so no openapi.yaml or codegen changes were needed. - Pre-existing TypeScript errors in auth.ts, admin.tsx, etc. are unrelated codegen drift and were left alone. Replit-Task-Id: 026e59a5-90c0-4faa-9080-aee0aee0a631 |
||
|
|
5a0f6803b0 |
Task #39: Send a real chat notification when someone messages a non-muted chat
Wired the chat message-send handler in artifacts/api-server/src/routes/conversations.ts to
create rows in the `notifications` table for every conversation participant who:
- is not the sender
- has `is_muted = false` on `conversation_participants`
Implementation details:
- Added a `createMessageNotifications` helper invoked after the new_message socket emit.
- Imported `notificationsTable` from `@workspace/db`.
- Notification content:
* Direct chat: title = sender display name, body = message preview (≤140 chars)
* Group chat: title = group name (fallback chain), body = "{sender}: {preview}"
Both Arabic and English titles/bodies are populated using the sender's
displayNameAr/displayNameEn (with username fallback) so the existing
bilingual notifications page renders correctly.
- type = "chat", relatedType = "conversation", relatedId = conversation id, so
notifications can later be deep-linked to the chat.
Muted conversations are filtered at the SQL level, so no notification rows are
created for muted recipients — the existing `conversation_participants.is_muted`
flag is the single source of truth, satisfying the task acceptance criteria.
No schema changes were needed; existing `notifications` table fields cover this.
The notifications page and bell badge already read from `useListNotifications`,
so no frontend changes were required — entries appear on next refetch/navigation.
Pre-existing TypeScript errors in the api-server (stale codegen for
@workspace/api-zod and unrelated schema fields) are not introduced by this change;
the esbuild build succeeds and the server starts cleanly.
Replit-Task-Id: 6b146a53-a575-4921-bd4f-3332247779df
|
||
|
|
db9cf7b315 |
Send system messages for group rename / add / remove
Original task (#38): When admins rename a group or add/remove members, post a system message into the chat thread so other members see who changed what and when, with bilingual (AR/EN) text and real-time delivery. Changes - lib/db/src/schema/conversations.ts: added `kind` (varchar default "user") and `meta` (jsonb) columns on the `messages` table. Pushed the new columns directly via ALTER TABLE since drizzle-kit push prompted on unrelated rename ambiguities. Also healed pre-existing schema drift on `users.clock_hour12`, `conversations.avatar_url`, and `conversation_participants.is_muted/is_archived` so the API could start. - lib/api-spec/openapi.yaml: extended MessageWithSender with `kind` (enum: user | group_renamed | members_added | member_removed) and optional `meta`. Re-ran codegen. - artifacts/api-server/src/routes/conversations.ts: added insertAndEmitSystemMessage + small user-display helpers; PATCH conversation now emits a `group_renamed` system message when a name actually changes; add-participants emits `members_added` with the actor + added users; remove-participant emits `member_removed` with actor + removed user. Each system message is broadcast over Socket.IO via the existing `new_message` channel so all current members receive it immediately. - artifacts/teaboy-os/src/pages/chat.tsx: render messages with `kind != "user"` as centered, muted pill bubbles (no avatar / sender label) using a new renderSystemMessage helper that picks the language-appropriate name out of meta. Conversation list preview also uses it so the last activity reads sensibly when the most recent message is a system message. - artifacts/teaboy-os/src/locales/{en,ar}.json: added chat.system.* strings (groupRenamed, membersAdded with plural variants, memberRemoved, someone, listSeparator). Verification - Typecheck (libs + artifacts) passes. - e2e via testing skill: registered fresh users, created a group, renamed it, added a member, removed a member; all three centered system messages appeared in the thread in order with the expected copy. Notes / deviations - Used the actor's userId as senderId for system messages (kept existing NOT NULL FK) instead of introducing a nullable sender, which keeps the migration lightweight. This means system messages count toward unread for non-actor members; flagged as a follow-up. Replit-Task-Id: 6dfa2b99-fbac-4146-b59b-8c04a14c9e96 |
||
|
|
36f2872dcd |
Reject invalid custom date ranges on /api/stats/admin with HTTP 400
Original task (Task #35): When the admin dashboard's custom range receives a malformed or missing date (e.g. ?range=custom&from=foo), the API silently fell back to the 7-day window instead of returning an error. This masked client bugs and confused admins. Changes: - artifacts/api-server/src/routes/stats.ts: - Refactored the custom-range branch so range=custom now always validates from/to. Returns 400 with a helpful, specific message when: * from or to is missing * from or to is not a valid YYYY-MM-DD UTC date * from is after to (existing behavior, message clarified) - Removed the silent `if (range === "custom") range = "7d"` fallback. - lib/api-spec/openapi.yaml: - Documented the 400 ErrorResponse on getAdminStats so the generated clients know about this failure mode. - Regenerated @workspace/api-client-react and @workspace/api-zod via `pnpm --filter @workspace/api-spec run codegen`. - artifacts/teaboy-os/src/pages/admin.tsx: - Captured `error` from useGetAdminStats (with retry: false) and surface a translated, role="alert" panel beneath the range controls when the API returns an error, including the server's error message. The frontend already guards against client-side invalid input via isCustomValid, so this primarily covers any remaining edge cases (stale querystring, race conditions). - Added admin.dashboard.customRange.loadError translations in en.json and ar.json. Verified with `pnpm -w run typecheck` (passes for libs and all artifacts). Manual curl confirmed the route is wired (auth gate returns 401 first, as expected). Replit-Task-Id: 965134ad-0d07-4cd2-a6ff-f60a50289d90 |
||
|
|
7b77de107f |
Task #31: Let people leave, mute, or archive a group chat
Adds per-user mute / archive / leave actions for chats. Schema: - `lib/db/src/schema/conversations.ts`: added `is_muted` and `is_archived` boolean columns on `conversation_participants`. - Columns applied directly via SQL (drizzle push wanted to make unrelated app_opens decisions; force-applied is_muted/is_archived with `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`). API (`artifacts/api-server/src/routes/conversations.ts`): - New endpoint `PATCH /conversations/:id/state` — current user toggles their own `isMuted` / `isArchived`. - New endpoint `POST /conversations/:id/leave` — removes the caller from a group conversation; rejects DMs. - `buildConversationDetails` now returns `isMuted` and `isArchived` for the requesting user. - `sendMessage` auto-clears `isArchived` for all participants so archived chats reappear when a new message arrives. OpenAPI (`lib/api-spec/openapi.yaml`): - Added the two new operations and `UpdateConversationStateBody`. - Added `isMuted` / `isArchived` to `ConversationWithDetails`. - Re-ran codegen for `@workspace/api-zod` and `@workspace/api-client-react`. UI (`artifacts/teaboy-os/src/pages/chat.tsx`): - Header gets a kebab "chat actions" button visible for both DMs and groups when a conversation is open. - Action sheet offers Mute/Unmute, Archive/Unarchive, and (groups only) Leave with a confirmation dialog. - Conversation list now has Active / Archived tabs and a bell-off indicator + dimmed unread badge for muted chats. - Bilingual strings added to en.json and ar.json. Side fixes (unrelated pre-existing schema drift discovered while testing): added missing `users.clock_hour12` and `conversations.avatar_url` columns directly so login and the conversations list work; the schema files already declared them. Verified end-to-end with the testing tool: mute, archive, unarchive, and leave-group flows all pass. Replit-Task-Id: faec58bb-12c6-4f6f-9ddb-f3f9f6c033f4 |
||
|
|
f6a7bc294d |
Task #30: Group settings (rename, add/remove members)
Lets group admins manage their groups after creation.
API changes (lib/api-spec/openapi.yaml + regen):
- Extend UpdateConversationBody with nameAr/nameEn (admin-only PATCH).
- Add POST /conversations/{id}/participants (add members).
- Add DELETE /conversations/{id}/participants/{userId} (remove member).
Backend (artifacts/api-server/src/routes/conversations.ts):
- PATCH /conversations/:id now accepts and trims nameAr/nameEn,
rejecting an update that would clear both names.
- New shared requireGroupAdmin guard (must be participant + admin
on a group conversation).
- Add-participants validates user IDs exist and skips duplicates.
- Remove-participants forbids the admin from removing themselves.
- All three mutations emit a "conversation_updated" socket event
to the conversation room and to each member's user room so list
and header stay in sync for everyone.
Frontend (artifacts/teaboy-os/src/pages/chat.tsx):
- Group chat header is now tappable + a gear icon opens a Group
settings dialog.
- Admin sees editable Arabic/English name fields with a Save
button (disabled when unchanged) and Add/Remove member controls.
- Non-admins see a read-only members list.
- Add Members reuses /users/directory and excludes existing members.
- Removes own row's trash button so admin can't remove themselves.
- Subscribes to "conversation_updated" socket event to refresh list.
- Bilingual strings added (chat.settings.*) in en.json and ar.json
with full Arabic plural forms.
Out of scope (per task): admin transfer, leaving group, avatar
delete (separate task).
Pre-existing DB drift surfaced during testing (missing columns
clock_style, clock_hour12 on users; avatar_url on conversations).
Added with non-destructive ALTER TABLE ... ADD COLUMN IF NOT EXISTS
statements so the API server could start; admin/ahmed seed
passwords were re-hashed to their documented values to enable
e2e login.
Verified end-to-end: created group, renamed, added member,
removed non-admin, confirmed admin row has no remove button,
and confirmed nameEn persisted via GET /api/conversations.
Replit-Task-Id: 9d1023cc-56de-45f2-9d73-4caafccc57b4
|
||
|
|
55b39f7d6f |
Task #29: Give each group chat its own picture
Adds upload + display of a custom avatar for group conversations.
Changes:
- DB: Added `avatar_url text` (nullable) to `conversations` table.
Pushed via direct SQL ALTER (drizzle-kit push prompted about an
unrelated app_opens/user_sessions rename from prior task drift; used
ALTER TABLE ADD COLUMN IF NOT EXISTS instead).
- OpenAPI (`lib/api-spec/openapi.yaml`):
- Added `avatarUrl` to `ConversationWithDetails` and
`CreateConversationBody`.
- Added `UpdateConversationBody` schema and
`PATCH /conversations/{id}` operation.
- Regenerated `@workspace/api-zod` and `@workspace/api-client-react`.
- API (`artifacts/api-server/src/routes/conversations.ts`):
- Persist `avatarUrl` on create.
- New `PATCH /conversations/:id` (admin-only) to update `avatarUrl`.
- Web (`artifacts/teaboy-os/src/pages/chat.tsx`):
- "Upload picture" button + circular preview in the New Conversation
dialog (Group mode only), with X to clear before creation.
- Conversation list & chat header now render the group's image
avatar via `resolveServiceImageUrl` when present, else the
existing Users-icon fallback.
- Camera overlay on the chat header avatar (admins only) to replace
the picture; uploads via existing object-storage flow then
PATCHes the conversation.
- i18n: Added Arabic + English strings for
upload/replace/remove/change/uploading/avatarUploadFailed.
Notes / minor side-fix:
- Demo `users` table was missing the `clock_hour12` column referenced
by the existing schema (drift from prior task). Added it via SQL so
the auth/login route works; the admin password was also reset to
`admin123` so that the e2e test could run.
- Direct conversations are unchanged (no avatar UI, no avatar saved).
Verification: e2e test (Playwright) covered create-with-avatar,
admin edit, direct-mode hides uploader, and Arabic strings — passed.
Replit-Task-Id: 34e8a2d2-621a-42a9-88ba-89652c6094dc
|