diff --git a/docs/team-member-invitation-admin-panel-integration.md b/docs/team-member-invitation-admin-panel-integration.md new file mode 100644 index 00000000..0f6cfc3f --- /dev/null +++ b/docs/team-member-invitation-admin-panel-integration.md @@ -0,0 +1,977 @@ +# Team Member Invitation — Admin Panel Integration Guide + +This guide documents how to implement the **team member email invitation** flow in the Yimaru admin panel: sending invites, managing pending invitations, building the public **accept-invitation** page, and signing in after activation. + +**Use this guide when:** admins invite staff by email, invitees complete profile setup via a link, and the admin panel lists/resends/revokes invitations. + +**Related:** [Team Member Refresh Token — Admin Panel Integration](./team-member-refresh-token-admin-panel-integration.md) (login/session after accept). + +--- + +## Table of contents + +1. [Feature overview](#feature-overview) +2. [Architecture & end-to-end flow](#architecture--end-to-end-flow) +3. [Backend prerequisites](#backend-prerequisites) +4. [Authentication & RBAC permissions](#authentication--rbac-permissions) +5. [Team roles (built-in + custom RBAC)](#team-roles-built-in--custom-rbac) +6. [Data model](#data-model) +7. [Response envelopes](#response-envelopes) +8. [Admin API reference](#admin-api-reference) +9. [Public accept-invite API reference](#public-accept-invite-api-reference) +10. [Invitation email](#invitation-email) +11. [Recommended admin UI screens](#recommended-admin-ui-screens) +12. [Accept-invite page (public route)](#accept-invite-page-public-route) +13. [Post-accept login](#post-accept-login) +14. [TypeScript types & API client](#typescript-types--api-client) +15. [Error handling](#error-handling) +16. [Activity logs](#activity-logs) +17. [Integration checklist](#integration-checklist) +18. [Testing checklist](#testing-checklist) +19. [Quick reference](#quick-reference) + +--- + +## Feature overview + +Team invitations let admins onboard staff **without creating a password in the admin UI**. The flow is: + +| Step | Who | What happens | +|------|-----|----------------| +| 1 | Admin | Sends invite with **email + role** only | +| 2 | Backend | Creates pending `team_members` row + `team_invitations` row; sends email | +| 3 | Invitee | Opens link, verifies token, fills profile + password | +| 4 | Backend | Activates account (`status=active`, `email_verified=true`) | +| 5 | Invitee | Signs in via `POST /api/v1/team/login` | + +| Capability | Endpoint | Auth | +|------------|----------|------| +| Send invite | `POST /api/v1/team/members/invite` | Bearer + `team.members.invite` | +| List invitations | `GET /api/v1/team/invitations` | Bearer + `team.invitations.list` | +| Resend invite | `POST /api/v1/team/members/:id/resend-invite` | Bearer + `team.invitations.resend` | +| Revoke invite | `POST /api/v1/team/invitations/:id/revoke` | Bearer + `team.invitations.revoke` | +| Verify token (accept page) | `GET /api/v1/team/invitations/verify` | **Public** | +| Accept invitation | `POST /api/v1/team/invitations/accept` | **Public** | +| Staff login | `POST /api/v1/team/login` | **Public** | + +> **Not learner registration.** Team invites use `team_members` + `invitation` email template. Learner OTP/welcome flows use the `users` table. + +--- + +## Architecture & end-to-end flow + +```mermaid +sequenceDiagram + participant Admin as Admin panel + participant API as Yimaru API + participant Mail as Email (Resend) + participant Invitee as Invitee browser + + Admin->>API: POST /team/members/invite { email, team_role } + API->>API: Create team_members (inactive, placeholder name) + API->>API: Create team_invitations (pending token) + API->>Mail: Send invitation template with InviteLink + API-->>Admin: 201 { invitation_id, team_member_id, expires_at } + + Invitee->>Invitee: Open email link (?token=...) + Invitee->>API: GET /team/invitations/verify?token=... + API-->>Invitee: { valid, email, team_role, needs_profile_setup } + + Invitee->>API: POST /team/invitations/accept { token, password, profile... } + API->>API: Update profile, set password, status=active, email_verified=true + API-->>Invitee: 200 Team account activated + + Invitee->>API: POST /team/login { email, password } + API-->>Invitee: access_token + refresh_token +``` + +### Invite link format + +The backend builds links from `TEAM_INVITE_BASE_URL`: + +``` +{TEAM_INVITE_BASE_URL}?token={opaque_token} +``` + +Example admin panel accept route: + +``` +https://admin.yimaruacademy.com/accept-invite?token=abc123... +``` + +The **frontend route** is your choice; only the `token` query param is required for the API. + +--- + +## Backend prerequisites + +### Environment variables + +| Variable | Required | Default | Purpose | +|----------|----------|---------|---------| +| `TEAM_INVITE_BASE_URL` | **Yes** (for invite to succeed) | — | Base URL for accept-invite page (token appended as query) | +| `TEAM_INVITE_EXPIRY_HOURS` | No | `168` (7 days) | Hours until pending invitation expires | +| `RESEND_API_KEY` | Yes (for email) | — | Transactional email delivery | +| `RESEND_SENDER_EMAIL` | Yes (for email) | — | From address | + +If `TEAM_INVITE_BASE_URL` is empty, invite returns **500** with `TEAM_INVITE_BASE_URL is not configured`. + +### Database migrations + +| Migration | Purpose | +|-----------|---------| +| `000011` | `team_members` table | +| `000068` | `team_invitations` table | +| `000097` | Allow **custom RBAC role names** on `team_members.team_role` (drops fixed 8-role CHECK) | + +### Email template + +System template slug: **`invitation`** + +Variables: `FirstName`, `InviterName`, `InviteLink` + +Managed in admin via email templates APIs; seeded by migration `000067`. + +--- + +## Authentication & RBAC permissions + +Admin invitation endpoints require **team member** (or platform admin) auth: + +```http +Authorization: Bearer +``` + +Use `POST /api/v1/team/login` for staff — not learner `auth/customer-login`. + +### Permission keys + +| Permission | Endpoint | +|------------|----------| +| `team.members.invite` | `POST /team/members/invite` | +| `team.invitations.list` | `GET /team/invitations` | +| `team.invitations.resend` | `POST /team/members/:id/resend-invite` | +| `team.invitations.revoke` | `POST /team/invitations/:id/revoke` | +| `team.members.list` | `GET /team/members` (see pending members) | +| `rbac.roles.list` | `GET /rbac/roles` (populate role picker) | +| `rbac.roles.create` | `POST /rbac/roles` (create custom roles) | +| `rbac.roles.set_permissions` | `PUT /rbac/roles/:id/permissions` | + +Default **ADMIN** role includes invite permissions after RBAC seed. + +### Public endpoints (no Bearer) + +- `GET /api/v1/team/invitations/verify` +- `POST /api/v1/team/invitations/accept` + +Host the accept-invite page on a route that does **not** require admin login. + +--- + +## Team roles (built-in + custom RBAC) + +`team_role` on invite identifies the staff role stored on `team_members.team_role`. + +### Built-in team roles + +| `team_role` value | Typical use | +|-------------------|-------------| +| `SUPER_ADMIN` | Full access | +| `ADMIN` | General administration | +| `CONTENT_MANAGER` | Courses, content | +| `SUPPORT_AGENT` | Support | +| `INSTRUCTOR` | Instructional content | +| `FINANCE` | Payments, subscriptions | +| `HR` | Team management | +| `ANALYST` | Reports | + +### Custom RBAC roles + +You may invite with a **custom role** created via RBAC: + +1. `POST /api/v1/rbac/roles` → e.g. `{ "name": "CONTENT_MANAGER_NEW", "description": "..." }` +2. `PUT /api/v1/rbac/roles/:id/permissions` → assign permission keys +3. Invite with `"team_role": "CONTENT_MANAGER_NEW"` **or** `"team_role": "12"` (numeric `roles.id`) + +Custom role names are normalized to **UPPERCASE_WITH_UNDERSCORES** on RBAC create/update. + +**Excluded from team assignment:** `STUDENT`, `OPEN_LEARNER` (learner platform roles). + +### Role picker (admin UI) + +Recommended approach: + +```http +GET /api/v1/rbac/roles?limit=100 +Authorization: Bearer +``` + +Filter out `STUDENT` and `OPEN_LEARNER`. Display `name` + `description`. Submit `name` or `id` as `team_role`. + +> **Permission gating in UI:** use RBAC permission keys from `GET /rbac/roles/:id/permissions`, not hardcoded `team_role === "ADMIN"`. Custom roles use their RBAC name in JWT after login. + +--- + +## Data model + +### `team_members` (after invite, before accept) + +| Field | Value | +|-------|-------| +| `first_name` | `"Pending"` (placeholder) | +| `last_name` | `"Invite"` (placeholder) | +| `email` | Invited email (lowercased) | +| `status` | `inactive` | +| `email_verified` | `false` | +| `team_role` | Assigned role (built-in or custom) | + +After accept: real name, `status=active`, `email_verified=true`. + +### `team_invitations` + +| Field | Description | +|-------|-------------| +| `id` | Invitation ID (used for **revoke**) | +| `team_member_id` | Linked member (used for **resend**) | +| `token` | Opaque token in email URL | +| `status` | `pending` \| `accepted` \| `expired` \| `revoked` | +| `expires_at` | Expiry timestamp | +| `invited_by` | Team member ID of inviter (optional) | + +### Invitation status lifecycle + +```mermaid +stateDiagram-v2 + [*] --> pending: Invite sent + pending --> accepted: POST /invitations/accept + pending --> expired: expires_at passed + pending --> revoked: Admin revoke + expired --> pending: Resend (new token) + revoked --> pending: Resend (new token) +``` + +--- + +## Response envelopes + +### Success + +```json +{ + "message": "Team invitation sent successfully", + "data": { }, + "success": true, + "status_code": 201, + "metadata": null +} +``` + +### Error + +```json +{ + "message": "Failed to send team invitation", + "error": "invalid team role: \"FOO\" (use a built-in team role or an existing RBAC role name/id)" +} +``` + +--- + +## Admin API reference + +Base URL: `{API_BASE}/api/v1` + +### `POST /team/members/invite` + +Creates a pending team member and sends the invitation email. + +**Permission:** `team.members.invite` + +**Request** + +```http +POST /api/v1/team/members/invite +Authorization: Bearer +Content-Type: application/json + +{ + "email": "staff@example.com", + "team_role": "CONTENT_MANAGER_NEW" +} +``` + +| Field | Type | Required | Notes | +|-------|------|----------|-------| +| `email` | string | Yes | Valid email; stored lowercased | +| `team_role` | string | Yes | Built-in role name, custom RBAC role name, or RBAC `roles.id` | + +**Success `201` — `data`** + +```json +{ + "invitation_id": 15, + "team_member_id": 42, + "email": "staff@example.com", + "expires_at": "2026-07-10T12:00:00Z" +} +``` + +**Common errors** + +| HTTP | `error` | Cause | +|------|---------|-------| +| `400` | `Email already exists` | Email already on a team member | +| `400` | `invalid team role: ...` | Unknown role / RBAC role missing | +| `400` | Validation failed | Invalid email or missing fields | +| `500` | `TEAM_INVITE_BASE_URL is not configured` | Server env not set | +| `403` | Permission denied | Missing `team.members.invite` | + +--- + +### `GET /team/invitations` + +Paginated list of invitations. + +**Permission:** `team.invitations.list` + +**Query** + +| Param | Type | Description | +|-------|------|-------------| +| `status` | string | Optional: `pending`, `accepted`, `expired`, `revoked` | +| `limit` | int | Default `20`, max `200` | +| `offset` | int | Default `0` | + +**Example** + +```http +GET /api/v1/team/invitations?status=pending&limit=20&offset=0 +Authorization: Bearer +``` + +**Success `200` — `data`** + +```json +{ + "invitations": [ + { + "id": 15, + "team_member_id": 42, + "email": "staff@example.com", + "first_name": "", + "last_name": "", + "team_role": "CONTENT_MANAGER_NEW", + "status": "pending", + "expires_at": "2026-07-10T12:00:00Z", + "created_at": "2026-07-03T12:00:00Z" + } + ], + "total_count": 1 +} +``` + +> Placeholder names (`Pending` / `Invite`) are returned as empty strings in the list. + +--- + +### `POST /team/members/:id/resend-invite` + +Revokes the current pending token, creates a new one, and sends a fresh email. + +**Permission:** `team.invitations.resend` + +**Path:** `:id` = **`team_member_id`** (not invitation id) + +```http +POST /api/v1/team/members/42/resend-invite +Authorization: Bearer +``` + +**Success `200` — `data`:** same shape as invite response (`invitation_id`, `team_member_id`, `email`, `expires_at`). + +**Errors:** member not awaiting acceptance, email already verified, etc. + +--- + +### `POST /team/invitations/:id/revoke` + +Revokes a **pending** invitation. If the member is still inactive and unverified, the **team member row is deleted**. + +**Permission:** `team.invitations.revoke` + +**Path:** `:id` = **`invitation_id`** + +```http +POST /api/v1/team/invitations/15/revoke +Authorization: Bearer +``` + +**Success `200` — `data`** + +```json +{ "id": 15 } +``` + +--- + +### `GET /team/members` (pending invite visibility) + +Pending invitees appear as team members with: + +- `status`: `"inactive"` +- `email_verified`: `false` +- `first_name` / `last_name`: `"Pending"` / `"Invite"` until accepted + +```http +GET /api/v1/team/members?status=inactive&page=1&page_size=20 +Authorization: Bearer +``` + +**Permission:** `team.members.list` + +Use alongside `GET /team/invitations?status=pending` for a complete invitations admin view. + +--- + +## Public accept-invite API reference + +No `Authorization` header. CORS must allow your admin frontend origin. + +### `GET /team/invitations/verify` + +Call when the accept-invite page loads. + +```http +GET /api/v1/team/invitations/verify?token= +``` + +**Success `200` — `data` (valid token)** + +```json +{ + "valid": true, + "email": "staff@example.com", + "team_role": "CONTENT_MANAGER_NEW", + "needs_profile_setup": true, + "expires_at": "2026-07-10T12:00:00Z", + "status": "pending" +} +``` + +**Success `200` — `data` (invalid/expired token)** + +```json +{ + "valid": false, + "status": "expired" +} +``` + +> **Important:** Invalid tokens return HTTP **200** with `valid: false`, not 404. Branch UI on `data.valid`. + +**Missing token → `400`** + +```json +{ + "message": "Invitation token is required" +} +``` + +--- + +### `POST /team/invitations/accept` + +Completes account setup. + +```http +POST /api/v1/team/invitations/accept +Content-Type: application/json + +{ + "token": "", + "password": "SecurePass123", + "first_name": "Yared", + "last_name": "Yemane", + "phone_number": "251911223344", + "department": "Engineering", + "job_title": "Content Editor", + "employment_type": "full_time", + "hire_date": "2026-07-03", + "profile_picture_url": "", + "bio": "", + "work_phone": "", + "emergency_contact": "" +} +``` + +| Field | Required | Validation | +|-------|----------|------------| +| `token` | Yes | From invite URL | +| `password` | Yes | Min 8 characters | +| `first_name` | Yes | Non-empty | +| `last_name` | Yes | Non-empty | +| `phone_number` | No | | +| `department`, `job_title`, `bio`, etc. | No | | +| `employment_type` | No | `full_time`, `part_time`, `contract`, `intern` | +| `hire_date` | No | `YYYY-MM-DD` | + +**Success `200` — `data`:** full `TeamMemberResponse` object. + +```json +{ + "message": "Team account activated successfully. You can now sign in.", + "data": { + "id": 42, + "first_name": "Yared", + "last_name": "Yemane", + "email": "staff@example.com", + "team_role": "CONTENT_MANAGER_NEW", + "status": "active", + "email_verified": true, + "created_at": "2026-07-03T12:00:00Z" + }, + "success": true +} +``` + +--- + +## Invitation email + +- **Template slug:** `invitation` (system — do not delete) +- **Subject:** branded default (“You’re invited to Yimaru Academy”) +- **CTA:** `{{.InviteLink}}` → `TEAM_INVITE_BASE_URL?token=...` +- **Variables:** `FirstName` (empty for new invites), `InviterName`, `InviteLink` + +Invite fails at send time if email/messenger services are misconfigured (500). + +--- + +## Recommended admin UI screens + +### 1. Invite team member (modal or page) + +- **Fields:** Email (required), Role (required dropdown) +- **Role dropdown:** load from `GET /rbac/roles`; show built-in + custom; exclude `STUDENT`, `OPEN_LEARNER` +- **Submit:** `POST /team/members/invite` +- **On success:** toast + redirect to invitations list or members list +- **On `Email already exists`:** suggest resend if member is pending + +### 2. Invitations list + +- **Table columns:** Email, Role, Status, Expires, Created, Actions +- **Data:** `GET /team/invitations?status=pending` (tabs for accepted/expired/revoked) +- **Actions:** + - **Resend** → `POST /team/members/{team_member_id}/resend-invite` + - **Revoke** → `POST /team/invitations/{invitation_id}/revoke` (confirm dialog) + +### 3. Team members list (optional badge) + +- Show **“Pending invite”** when `status === "inactive" && !email_verified` +- Quick actions: Resend / Revoke (resolve invitation id from list endpoint) + +### 4. Custom roles management (settings) + +- Create role → assign permissions → available in invite dropdown +- See [FAQ admin guide](./faq-admin-panel-integration.md#rbac-setup--troubleshooting-403) for RBAC 403 troubleshooting patterns + +--- + +## Accept-invite page (public route) + +Suggested route: `/accept-invite` (must match `TEAM_INVITE_BASE_URL` path on server). + +### Page flow + +```mermaid +flowchart TD + A[Load /accept-invite?token=...] --> B{token in URL?} + B -->|No| C[Show invalid link message] + B -->|Yes| D[GET /invitations/verify?token=...] + D --> E{data.valid?} + E -->|No| F[Show expired / revoked / used message] + E -->|Yes| G[Show form: name, password, optional profile] + G --> H[POST /invitations/accept] + H --> I{Success?} + I -->|Yes| J[Redirect to /login with success message] + I -->|No| K[Show field errors] +``` + +### Form UX + +- Pre-fill **email** from verify response (read-only) +- Show **role** as read-only label +- Password + confirm password (client-side match) +- Required: first name, last name, password +- Optional: phone, department, job title, employment type, hire date + +### Route guard + +- Do **not** mount behind admin auth layout +- No Bearer token on verify/accept calls + +--- + +## Post-accept login + +After successful accept, redirect to staff login: + +```http +POST /api/v1/team/login +Content-Type: application/json + +{ + "email": "staff@example.com", + "password": "SecurePass123" +} +``` + +If login returns: + +```json +{ + "error": "Please accept your invitation email and set your password before signing in" +} +``` + +the accept step did not complete (`email_verified` still false). + +Full session handling: [team-member-refresh-token-admin-panel-integration.md](./team-member-refresh-token-admin-panel-integration.md). + +### JWT role after custom `team_role` + +| `team_role` type | JWT `Role` used for API permission checks | +|------------------|-------------------------------------------| +| Built-in (e.g. `CONTENT_MANAGER`) | Mapped platform role (`ADMIN`, `INSTRUCTOR`, …) | +| Custom (e.g. `CONTENT_MANAGER_NEW`) | Same string as RBAC role name | + +--- + +## TypeScript types & API client + +```typescript +const API_BASE = import.meta.env.VITE_API_BASE_URL; // e.g. https://api.yimaru.com/api/v1 + +export interface ApiResponse { + message: string; + data: T; + success: boolean; + status_code?: number; + metadata?: unknown; +} + +export interface ApiErrorResponse { + message: string; + error?: string; +} + +// --- Invite (admin) --- + +export interface InviteTeamMemberRequest { + email: string; + team_role: string; // RBAC name or roles.id string +} + +export interface InviteTeamMemberResult { + invitation_id: number; + team_member_id: number; + email: string; + expires_at: string; // RFC3339 +} + +export async function inviteTeamMember( + accessToken: string, + body: InviteTeamMemberRequest +): Promise { + const res = await fetch(`${API_BASE}/team/members/invite`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${accessToken}`, + }, + body: JSON.stringify(body), + }); + const json = (await res.json()) as ApiResponse | ApiErrorResponse; + if (!res.ok) throw new Error("error" in json ? json.error ?? json.message : "Invite failed"); + return (json as ApiResponse).data; +} + +// --- Invitations list (admin) --- + +export type TeamInvitationStatus = "pending" | "accepted" | "expired" | "revoked"; + +export interface TeamInvitationListItem { + id: number; + team_member_id: number; + email: string; + first_name: string; + last_name: string; + team_role: string; + status: TeamInvitationStatus; + expires_at: string; + created_at: string; +} + +export interface ListTeamInvitationsResult { + invitations: TeamInvitationListItem[]; + total_count: number; +} + +export async function listTeamInvitations( + accessToken: string, + params?: { status?: TeamInvitationStatus; limit?: number; offset?: number } +): Promise { + const q = new URLSearchParams(); + if (params?.status) q.set("status", params.status); + if (params?.limit != null) q.set("limit", String(params.limit)); + if (params?.offset != null) q.set("offset", String(params.offset)); + const res = await fetch(`${API_BASE}/team/invitations?${q}`, { + headers: { Authorization: `Bearer ${accessToken}` }, + }); + const json = (await res.json()) as ApiResponse; + if (!res.ok) throw new Error("Failed to list invitations"); + return json.data; +} + +export async function resendTeamInvitation( + accessToken: string, + teamMemberId: number +): Promise { + const res = await fetch(`${API_BASE}/team/members/${teamMemberId}/resend-invite`, { + method: "POST", + headers: { Authorization: `Bearer ${accessToken}` }, + }); + const json = (await res.json()) as ApiResponse | ApiErrorResponse; + if (!res.ok) throw new Error("error" in json ? json.error ?? json.message : "Resend failed"); + return (json as ApiResponse).data; +} + +export async function revokeTeamInvitation( + accessToken: string, + invitationId: number +): Promise { + const res = await fetch(`${API_BASE}/team/invitations/${invitationId}/revoke`, { + method: "POST", + headers: { Authorization: `Bearer ${accessToken}` }, + }); + if (!res.ok) { + const json = (await res.json()) as ApiErrorResponse; + throw new Error(json.error ?? json.message); + } +} + +// --- Public accept flow --- + +export interface VerifyTeamInvitationResult { + valid: boolean; + email?: string; + team_role?: string; + needs_profile_setup?: boolean; + expires_at?: string; + status?: TeamInvitationStatus | "expired"; +} + +export async function verifyTeamInvitation( + token: string +): Promise { + const res = await fetch( + `${API_BASE}/team/invitations/verify?token=${encodeURIComponent(token)}` + ); + const json = (await res.json()) as ApiResponse; + if (!res.ok) throw new Error("Verify failed"); + return json.data; +} + +export interface AcceptTeamInvitationRequest { + token: string; + password: string; + first_name: string; + last_name: string; + phone_number?: string; + department?: string; + job_title?: string; + employment_type?: "full_time" | "part_time" | "contract" | "intern"; + hire_date?: string; // YYYY-MM-DD + profile_picture_url?: string; + bio?: string; + work_phone?: string; + emergency_contact?: string; +} + +export interface TeamMember { + id: number; + first_name: string; + last_name: string; + email: string; + team_role: string; + status: string; + email_verified: boolean; + phone_number?: string; + department?: string; + job_title?: string; + employment_type?: string; + hire_date?: string; + created_at: string; + updated_at?: string; +} + +export async function acceptTeamInvitation( + body: AcceptTeamInvitationRequest +): Promise { + const res = await fetch(`${API_BASE}/team/invitations/accept`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + const json = (await res.json()) as ApiResponse | ApiErrorResponse; + if (!res.ok) throw new Error("error" in json ? json.error ?? json.message : "Accept failed"); + return (json as ApiResponse).data; +} + +// --- RBAC roles for picker --- + +export interface RoleRecord { + id: number; + name: string; + description: string; + is_system: boolean; +} + +const LEARNER_ROLES = new Set(["STUDENT", "OPEN_LEARNER"]); + +export async function listAssignableTeamRoles( + accessToken: string +): Promise { + const res = await fetch(`${API_BASE}/rbac/roles?limit=100`, { + headers: { Authorization: `Bearer ${accessToken}` }, + }); + const json = (await res.json()) as ApiResponse; + if (!res.ok) throw new Error("Failed to load roles"); + return json.data.filter((r) => !LEARNER_ROLES.has(r.name.toUpperCase())); +} +``` + +--- + +## Error handling + +### Invite (`POST /team/members/invite`) + +| HTTP | `error` (typical) | UI action | +|------|-------------------|-----------| +| `400` | `Email already exists` | Show conflict; offer resend if pending | +| `400` | `invalid team role: "..."` | Refresh role list; ensure RBAC role exists | +| `400` | Validation failed | Highlight email field | +| `403` | Permission denied | Hide invite action | +| `500` | `TEAM_INVITE_BASE_URL is not configured` | Show ops/config message | + +### Verify (`GET /invitations/verify`) + +| Condition | UI | +|-----------|-----| +| `data.valid === false` | “Invitation expired or invalid” + contact admin | +| `400` missing token | “Invalid link” | + +### Accept (`POST /invitations/accept`) + +| HTTP | `error` | UI | +|------|---------|-----| +| `400` | `Invitation has expired` | Link to request resend | +| `400` | `Invitation has already been accepted` | Link to login | +| `400` | `Invitation has been revoked` | Contact admin | +| `404` | `Invitation not found` | Invalid link | +| `400` | `invalid employment type` | Fix employment dropdown | +| `400` | Validation failed | Field-level errors | + +### Login before accept + +| HTTP | `error` | UI | +|------|---------|-----| +| `401` | `Please accept your invitation email...` | Redirect to accept-invite or show resend instructions | + +--- + +## Activity logs + +| Action | `action` constant | +|--------|-------------------| +| Invite sent | `TEAM_MEMBER_INVITED` | +| Resend | `TEAM_INVITATION_RESENT` | +| Revoke | `TEAM_INVITATION_REVOKED` | +| Accept (self) | `TEAM_MEMBER_UPDATED` | + +Metadata example for invite: `{ "email": "...", "team_member_id": 42 }` + +See [activity-logs-admin-panel-integration.md](./activity-logs-admin-panel-integration.md). + +--- + +## Integration checklist + +### Backend / DevOps + +- [ ] `TEAM_INVITE_BASE_URL` points to admin accept-invite route +- [ ] `TEAM_INVITE_EXPIRY_HOURS` set appropriately +- [ ] Resend email configured +- [ ] Migration `000097` applied (custom team roles) +- [ ] `invitation` email template active + +### Admin panel — invite management + +- [ ] Role picker loads from `GET /rbac/roles` (excludes learner roles) +- [ ] Invite form posts `POST /team/members/invite` +- [ ] Invitations list with status filter +- [ ] Resend uses **team_member_id** +- [ ] Revoke uses **invitation_id** +- [ ] Pending badge on members list (`inactive` + `!email_verified`) + +### Admin panel — accept page (public) + +- [ ] Route `/accept-invite?token=` (matches `TEAM_INVITE_BASE_URL`) +- [ ] Verify on mount; handle `valid: false` without treating as HTTP error +- [ ] Accept form with required fields +- [ ] Redirect to login on success + +### Auth + +- [ ] Staff login via `POST /team/login` only +- [ ] Menu gating uses RBAC permissions, not role name alone + +--- + +## Testing checklist + +- [ ] Invite with built-in role (`ADMIN`) → email received → accept → login +- [ ] Invite with custom RBAC role → permissions match role after login +- [ ] Invite with `team_role` as numeric `roles.id` +- [ ] Duplicate email → `400 Email already exists` +- [ ] Unknown role → `400 invalid team role` +- [ ] Expired token → verify `valid: false`; accept returns expired error +- [ ] Resend invalidates old link; new link works +- [ ] Revoke removes pending member; old link fails +- [ ] Login before accept → `401` with invitation message + +--- + +## Quick reference + +| Task | Method | Path | Auth | +|------|--------|------|------| +| Send invite | `POST` | `/team/members/invite` | Bearer | +| List invitations | `GET` | `/team/invitations` | Bearer | +| Resend | `POST` | `/team/members/:team_member_id/resend-invite` | Bearer | +| Revoke | `POST` | `/team/invitations/:invitation_id/revoke` | Bearer | +| Verify token | `GET` | `/team/invitations/verify?token=` | Public | +| Accept | `POST` | `/team/invitations/accept` | Public | +| Staff login | `POST` | `/team/login` | Public | +| List RBAC roles | `GET` | `/rbac/roles` | Bearer | + +**Invite body:** `{ "email": string, "team_role": string }` + +**Accept body (minimum):** `{ "token", "password", "first_name", "last_name" }` + +**Employment types:** `full_time` | `part_time` | `contract` | `intern` + +**Member statuses:** `active` | `inactive` | `suspended` | `terminated` + +**Invitation statuses:** `pending` | `accepted` | `expired` | `revoked`