diff --git a/cmd/main.go b/cmd/main.go index 2f71341a..f1f74b4f 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -144,6 +144,7 @@ func main() { cfg, messengerSvc, userSvc, + repository.NewTeamStore(store), emailTemplateSvc, ) diff --git a/docs/bulk-scheduled-notifications-integration.md b/docs/bulk-scheduled-notifications-integration.md index 73be1ad0..82f1b672 100644 --- a/docs/bulk-scheduled-notifications-integration.md +++ b/docs/bulk-scheduled-notifications-integration.md @@ -346,13 +346,15 @@ Permission: notifications.bulk_email | `subject` | string | Cond. | Email subject. **Required** when no `email_template_slug`, or when slug is `custom_message`. | | `message` | string | Cond. | Plain-text body. **Required** (with `subject`) for free-form sends, or for `custom_message`. | | `html` | string | No | HTML body (free-form only; ignored when a non-`custom_message` template supplies HTML). | -| `user_ids` | string | No* | JSON array string, e.g. `[1,2,3]` | +| `user_ids` | string | No* | JSON array string, e.g. `[1,2,3]` (platform users) | | `role` | string | No* | Platform role filter | +| `team_member_ids` | string | No* | JSON array string, e.g. `[1,2,3]` (team members) | +| `team_role` | string | No* | `team_members.team_role` filter (e.g. `ADMIN`, `CONTENT_MANAGER`) | | `emails` | string | No* | JSON array string, e.g. `["a@b.com"]` | | `scheduled_at` | string | No | RFC3339 | | `file` | file | No | Attachment (immediate send only) | -\* At least one of `user_ids`, `role`, or `emails` is required. +\* At least one of `user_ids`, `role`, `team_member_ids`, `team_role`, or `emails` is required. ### Content modes @@ -386,6 +388,17 @@ curl -X POST "https://api.example.com/api/v1/notifications/bulk-email" \ -F "role=STUDENT" ``` +### Example — email to staff by team role + +```bash +curl -X POST "https://api.example.com/api/v1/notifications/bulk-email" \ + -H "Authorization: Bearer " \ + -F "email_template_slug=custom_message" \ + -F "subject=Admin handbook update" \ + -F "message=The internal handbook has been revised." \ + -F "team_role=ADMIN" +``` + ### Example — scheduled with template ```bash @@ -650,13 +663,15 @@ Permission: notifications.bulk_in_app |-------|------|----------|-------------| | `title` | string | **Yes** | Headline (`payload.headline`) | | `message` | string | **Yes** | Body (`payload.message`) | -| `user_ids` | int64[] | No* | Target user IDs | +| `user_ids` | int64[] | No* | Target platform user IDs | | `role` | string | No* | All users with platform role | +| `team_member_ids` | int64[] | No* | Target team member IDs | +| `team_role` | string | No* | All team members with `team_members.team_role` | | `scheduled_at` | string | No | RFC3339 | | `type` | string | No | Notification type (default `system_alert`) | | `level` | string | No | `info`, `warning`, `error`, `success` (default `info`) | -\* At least one of `user_ids` or `role` is required. +\* At least one of `user_ids`, `role`, `team_member_ids`, or `team_role` is required. ### Notification `type` values (common) @@ -667,7 +682,7 @@ Permission: notifications.bulk_in_app | `course_completed` | Learning milestones | | `payment_verified` | Payment events | -### Example — immediate +### Example — immediate (learners) ```json { @@ -677,6 +692,27 @@ Permission: notifications.bulk_in_app } ``` +### Example — immediate (staff) + +```json +{ + "title": "Admin policy update", + "message": "Please review the updated content guidelines in the admin panel.", + "team_role": "CONTENT_MANAGER" +} +``` + +### Example — mixed audience + +```json +{ + "title": "Platform notice", + "message": "Scheduled maintenance this weekend.", + "role": "INSTRUCTOR", + "team_member_ids": [1, 2, 5] +} +``` + ### Example — scheduled ```json @@ -864,7 +900,9 @@ Permission: notifications.count_unread ## Recipient targeting rules -### Platform roles (`role` field) +Recipients can be **platform users** (`users` table), **team members** (`team_members` table), or both in the same request. All targeting fields are unioned (deduplicated). + +### Platform users (`user_ids` / `role`) Valid platform `users.role` values: @@ -879,16 +917,41 @@ Valid platform `users.role` values: When `role` is set without `user_ids`, the API loads **all users** matching that role (up to 100k). Role values are matched case-insensitively (`STUDENT`, `student`, etc.). +### Team members (`team_member_ids` / `team_role`) + +Valid `team_members.team_role` values: + +| Team role | Value | +|-----------|-------| +| Super admin | `SUPER_ADMIN` | +| Admin | `ADMIN` | +| Content manager | `CONTENT_MANAGER` | +| Support agent | `SUPPORT_AGENT` | +| Instructor | `INSTRUCTOR` | +| Finance | `FINANCE` | +| HR | `HR` | +| Analyst | `ANALYST` | + +When `team_role` is set without `team_member_ids`, the API loads **all team members** with that `team_role` (up to 100k). + +**In-app:** notifications are stored with `receiver_type: "team_member"` and delivered over WebSocket to the team member ID. + +**Email:** team member email addresses are resolved from `team_members.email`. + +`role` (platform users) and `team_role` (staff) are **different fields** — do not confuse them. + ### Combining targets -| Channel | `user_ids` | `role` | Direct (`phones` / `emails`) | -|---------|------------|--------|------------------------------| -| SMS | ✓ | ✓ | `phone_numbers` | -| Email | ✓ | ✓ | `emails` (form field) | -| Push | ✓ | ✓ | — | -| In-app | ✓ | ✓ | — | +| Channel | `user_ids` | `role` | `team_member_ids` | `team_role` | Direct (`phones` / `emails`) | +|---------|------------|--------|-------------------|-------------|------------------------------| +| SMS | ✓ | ✓ | — | — | `phone_numbers` | +| Email | ✓ | ✓ | ✓ | ✓ | `emails` (form field) | +| Push | ✓ | ✓ | — | — | — | +| In-app | ✓ | ✓ | ✓ | ✓ | — | -For immediate SMS/email, all sources are **unioned** (deduplicated). Scheduled jobs store the targeting fields as-is and resolve at dispatch time. +For immediate SMS/email, all sources are **unioned** (deduplicated). Scheduled jobs store user/team targeting in `target_user_ids`, `target_role`, and `target_raw` (`team_member_ids`, `team_role`, `emails`) and resolve at dispatch time. + +Scheduled notification API responses include `target_team_member_ids` and `target_team_role` when present (parsed from `target_raw`). --- diff --git a/docs/select-missing-words-sequence-order-admin-panel-integration.md b/docs/select-missing-words-sequence-order-admin-panel-integration.md new file mode 100644 index 00000000..a71bfcd7 --- /dev/null +++ b/docs/select-missing-words-sequence-order-admin-panel-integration.md @@ -0,0 +1,968 @@ +# Select Missing Words & Sequence Order — Admin Panel Integration Guide + +This guide explains how to **render, edit, validate, and serialize** the dynamic question builder components **`SELECT_MISSING_WORDS`** and **`SEQUENCE_ORDER`** in the Yimaru admin panel. + +It is written to match the **existing admin UI patterns** already used for: + +- **Fill in the blank** → stimulus `SELECT_MISSING_WORDS` (segment builder + word bank) +- **Matching** → stimulus `MATCHING_INPUTS` (paired row list) + +> **Scope:** Admin question authoring for `DYNAMIC` questions (`dynamic_payload.stimulus` / `dynamic_payload.response`). +> **Backend source of truth for kinds:** `internal/domain/question_type_builder.go` +> **Related:** `docs/question-type-definition-groups-admin-panel-integration.md`, Postman collection `postman/Dynamic-Question-Type-Builder.postman_collection.json` + +--- + +## Table of contents + +1. [Summary](#summary) +2. [How schema-driven rendering works](#how-schema-driven-rendering-works) +3. [Shared UI shell (STIMULUS / RESPONSE sections)](#shared-ui-shell-stimulus--response-sections) +4. [SELECT_MISSING_WORDS](#select_missing_words) +5. [SEQUENCE_ORDER](#sequence_order) +6. [TypeScript types](#typescript-types) +7. [Serialization helpers](#serialization-helpers) +8. [Client-side validation](#client-side-validation) +9. [React component patterns](#react-component-patterns) +10. [Full API examples](#full-api-examples) +11. [Comparison with Matching & Fill in the blank](#comparison-with-matching--fill-in-the-blank) +12. [Error handling](#error-handling) +13. [Integration checklist](#integration-checklist) +14. [Quick reference](#quick-reference) + +--- + +## Summary + +| Component kind | Typical section | Admin UI pattern | Stored in `value` | +|----------------|-----------------|------------------|-------------------| +| `SELECT_MISSING_WORDS` | **Stimulus** | Alternating **Text** / **Blank** blocks + **Word bank** rows | `segments`, `word_bank`, `allow_reuse` | +| `SELECT_MISSING_WORDS` | **Response** | Per-blank correct answer picker (dropdown from bank) | `blanks[]` with `blank_id`, `text`, `word_id` | +| `SEQUENCE_ORDER` | **Response only** | Ordered **item rows** with drag-reorder (like Matching rows, single column) | `items[]`, `correct_order[]` | + +### Backend validation today + +The API validates: + +- Element `id` + `kind` presence +- Kinds allowed by the selected **question type definition** +- Required schema element ids present + +The API **does not** currently validate the inner shape of `value` objects for these kinds. The admin panel should enforce the conventions below so learner apps and future server validators stay consistent. + +### Runtime mapping + +| Response kind | Legacy `question_type` used internally | API `question_type` on question row | +|---------------|----------------------------------------|-------------------------------------| +| `SELECT_MISSING_WORDS` | `SHORT_ANSWER` | `DYNAMIC` | +| `SEQUENCE_ORDER` | `DYNAMIC` (auxiliary / builder-native) | `DYNAMIC` | + +**Do not** send top-level `options`, `short_answers`, or `question_text` for these dynamic questions. Content lives entirely in `dynamic_payload`. + +--- + +## How schema-driven rendering works + +Each question is authored against a **question type definition**: + +```http +GET /api/v1/questions/type-definitions/:id +``` + +The definition provides: + +| Field | Use in admin UI | +|-------|-----------------| +| `stimulus_schema[]` | Ordered list of stimulus slots to render under **STIMULUS** | +| `response_schema[]` | Ordered list of response slots to render under **RESPONSE** | +| `*.id` | Must match `dynamic_payload.*[].id` when saving | +| `*.kind` | Chooses which React renderer to mount | +| `*.label` | Section heading (e.g. `"Passage with blanks"`) | +| `*.required` | Show `*` and block save when empty | +| `*.config` | Min/max limits for lists (blanks, words, items) | + +```mermaid +flowchart TD + A[Load question type definition] --> B[Render stimulus_schema slots] + A --> C[Render response_schema slots] + B --> D{kind?} + D -->|SELECT_MISSING_WORDS| E[Segment + word bank editor] + D -->|INSTRUCTION / TEXT_PASSAGE| F[Text area] + D -->|MATCHING_INPUTS| G[Left/right row editor] + C --> H{kind?} + H -->|SELECT_MISSING_WORDS| I[Blank answer key editor] + H -->|SEQUENCE_ORDER| J[Sequence item + order editor] + E --> K[Build dynamic_payload JSON] + I --> K + J --> K + K --> L[POST or PUT /api/v1/questions] +``` + +When **editing** an existing question, hydrate local form state from `question.dynamic_payload` by matching `element.id` to schema slot `id`. + +--- + +## Shared UI shell (STIMULUS / RESPONSE sections) + +Match the layout used for Matching and Fill in the blank: + +``` +┌─ STIMULUS ─────────────────────────────────────────────────────┐ +│ [purple micro-label] STIMULUS │ +│ ┌─ Instruction banner (optional) ───────────────────────────┐ │ +│ │ Image, audio, and PDF use upload or URL. Table uses the │ │ +│ │ visual table builder. Timer and prep-time slots use seconds.│ │ +│ │ Other slots use text or structured JSON where noted. │ │ +│ └────────────────────────────────────────────────────────────┘ │ +│ … one card per stimulus_schema element … │ +└──────────────────────────────────────────────────────────────────┘ + +┌─ RESPONSE ─────────────────────────────────────────────────────┐ +│ [purple micro-label] RESPONSE │ +│ … one card per response_schema element … │ +└──────────────────────────────────────────────────────────────────┘ +``` + +### Card anatomy (same as Matching rows) + +| UI element | Spec | +|------------|------| +| Section label | `STIMULUS` / `RESPONSE` — small caps, purple (`#7C3AED` or your design token) | +| Card title | `schema.label` + red `*` when `required` | +| Primary action | Outlined purple button top-right (`+ Add row`, `+ Add word`, `+ Add item`) | +| Row container | White card, `1px` light border, `8–12px` radius, padding `12–16px` | +| Field micro-labels | Gray uppercase (`LEFT L1`, `BLANK B1`, `ITEM S1`) | +| Delete | Trash icon button, right edge of row | +| Helper text | Gray `12–13px` under the card | + +--- + +## SELECT_MISSING_WORDS + +Used for **cloze / gap-fill / word-bank** tasks. The system definition `fill_in_the_blank` allows this kind on **both** stimulus and response. + +### Stimulus UI — passage builder + word bank + +This is the UI shown in your **Fill in the blank** screenshot: alternating **Blank** chips and **Text** areas, plus a **WORD BANK** list. + +#### Visual layout + +``` +┌─ Passage with blanks * ─────────────────────────── [+ Add text] [+ Add blank] ─┐ +│ │ +│ ┌ Blank b1 ─────────────────────────────────────────────────────── [🗑] ─┐ │ +│ │ (purple/lavender pill — not editable, only identifies the slot) │ │ +│ └─────────────────────────────────────────────────────────────────────────┘ │ +│ │ +│ ┌ TEXT ─────────────────────────────────────────────────────────── [🗑] ─┐ │ +│ │ [ multiline: "Text before or after a blank" ] │ │ +│ └─────────────────────────────────────────────────────────────────────────┘ │ +│ │ +│ ┌ Blank b2 ─────────────────────────────────────────────────────── [🗑] ─┐ │ +│ └─────────────────────────────────────────────────────────────────────────┘ │ +│ │ +│ ┌ TEXT ─────────────────────────────────────────────────────────── [🗑] ─┐ │ +│ │ [ multiline textarea ] │ │ +│ └─────────────────────────────────────────────────────────────────────────┘ │ +│ │ +│ Helper: Passage must contain at least one blank. Text before/after blanks │ +│ is preserved exactly (including spaces). │ +└───────────────────────────────────────────────────────────────────────────────┘ + +┌─ WORD BANK ─────────────────────────────────────────────── [+ Add word] ─┐ +│ w1 [ Word 1________________________ ] [🗑] │ +│ w2 [ Word 2________________________ ] [🗑] │ +│ Helper: Add decoy words; not every word must be used in the answer. │ +└─────────────────────────────────────────────────────────────────────────────┘ + +┌─ Options ─────────────────────────────────────────────────────────────────┐ +│ [ ] Allow reusing the same word for multiple blanks (allow_reuse) │ +└─────────────────────────────────────────────────────────────────────────────┘ +``` + +#### Block types + +| Block | Admin control | Maps to `segments[]` | +|-------|---------------|----------------------| +| **Text** | Multiline textarea | `{ "type": "text", "value": "" }` | +| **Blank** | Non-editable pill showing `b1`, `b2`, … | `{ "type": "blank", "id": "b1" }` | + +#### ID generation rules + +| Entity | Pattern | Example | +|--------|---------|---------| +| Blank ids | `b` + monotonic number | `b1`, `b2`, `b3` | +| Word bank ids | `w` + monotonic number | `w1`, `w2`, `w3` | + +- Generate ids **once** when a row/block is created; **never** renumber on delete (keeps response answers stable). +- Display labels (`Blank b1`, `w1`) are derived from ids for the admin UI only. + +#### Recommended block toolbar actions + +| Button | Behavior | +|--------|----------| +| `+ Add text` | Appends a text segment block at end | +| `+ Add blank` | Appends a blank segment; auto-suggest next `bN` id | +| Drag handle (optional) | Reorder blocks in `segments` array | +| 🗑 on block | Remove segment; if blank removed, also remove linked response answer | + +#### `value` JSON shape (stimulus) + +```json +{ + "segments": [ + { "type": "text", "value": "Yesterday I " }, + { "type": "blank", "id": "b1" }, + { "type": "text", "value": " to school and " }, + { "type": "blank", "id": "b2" }, + { "type": "text", "value": " my homework." } + ], + "word_bank": [ + { "id": "w1", "text": "went" }, + { "id": "w2", "text": "did" }, + { "id": "w3", "text": "go" }, + { "id": "w4", "text": "do" } + ], + "allow_reuse": false +} +``` + +| Field | Type | Required | Notes | +|-------|------|----------|-------| +| `segments` | array | Yes | Alternating text + blank; order = display order | +| `segments[].type` | `"text"` \| `"blank"` | Yes | | +| `segments[].value` | string | When `type=text` | Preserve whitespace | +| `segments[].id` | string | When `type=blank` | Unique within this question | +| `word_bank` | array | Yes (for bank-style UI) | Min 1 word recommended | +| `word_bank[].id` | string | Yes | Stable id | +| `word_bank[].text` | string | Yes | Trim for display; preserve internal spaces if entered | +| `allow_reuse` | boolean | No | Default `false` | + +#### Schema `config` hints (definition authoring) + +```json +{ + "id": "cloze", + "kind": "SELECT_MISSING_WORDS", + "label": "Passage with blanks", + "required": true, + "config": { + "min_blanks": 1, + "max_blanks": 10, + "min_word_bank": 2, + "max_word_bank": 20 + } +} +``` + +Enforce `min_*` / `max_*` in the admin UI before save. + +--- + +### Response UI — correct answers per blank + +Render **one row per blank** discovered from the **stimulus** `segments` (do not let admins invent blank ids only in response). + +``` +┌─ Correct selections * ──────────────────────────────────────────────────────┐ +│ BLANK B1 [ dropdown: went ▼ ] or [ text: went________ ] │ +│ BLANK B2 [ dropdown: did ▼ ] or [ text: did_________ ] │ +│ Helper: Each blank must have an answer. Duplicates disallowed unless reuse on.│ +└───────────────────────────────────────────────────────────────────────────────┘ +``` + +#### Interaction rules + +| Rule | Behavior | +|------|----------| +| Dropdown source | Stimulus `word_bank` entries (`id` + `text`) | +| On stimulus blank deleted | Remove corresponding response row | +| On stimulus blank added | Add empty response row for that `blank_id` | +| `word_id` | Set when picked from bank; omit if admin types free text | +| `text` | Always store the canonical answer string (from bank or typed) | + +#### `value` JSON shape (response) + +```json +{ + "blanks": [ + { "blank_id": "b1", "text": "went", "word_id": "w1" }, + { "blank_id": "b2", "text": "did", "word_id": "w2" } + ] +} +``` + +| Field | Type | Required | Notes | +|-------|------|----------|-------| +| `blanks` | array | Yes | One entry per stimulus blank | +| `blanks[].blank_id` | string | Yes | Matches stimulus blank `id` | +| `blanks[].text` | string | Yes | Grading string | +| `blanks[].word_id` | string | No | Links to `word_bank[].id` when selected from bank | + +--- + +### Stimulus + response on the same question + +For `fill_in_the_blank` and custom cloze types you often have: + +| Slot | Kind | Role | +|------|------|------| +| Stimulus `passage_intro` | `TEXT_PASSAGE` or `INSTRUCTION` | Top-level task text | +| Stimulus `cloze` | `SELECT_MISSING_WORDS` | Segment builder + word bank | +| Response `cloze_answer` | `SELECT_MISSING_WORDS` | Answer key | + +The segment/word-bank UI mounts only on the stimulus `SELECT_MISSING_WORDS` slot. The response slot mounts the per-blank answer editor. + +**Important:** If the definition includes only `SELECT_MISSING_WORDS` in stimulus with **no** `QUESTION_TEXT`, `INSTRUCTION`, or `TEXT_PASSAGE`, the stored search/activity `question_text` may be empty. Prefer definitions that include at least one text stimulus kind for discoverability. + +--- + +## SEQUENCE_ORDER + +`SEQUENCE_ORDER` is a **response-side** kind (ordering / sequencing tasks). There is **no** dedicated stimulus kind for items — items and correct order are authored together in the response slot. + +### Typical type definition + +```json +{ + "key": "sequence_ordering", + "display_name": "Sequence Order", + "description": "Learner arranges items in the correct order.", + "stimulus_component_kinds": ["INSTRUCTION"], + "response_component_kinds": ["SEQUENCE_ORDER"], + "stimulus_schema": [ + { + "id": "instruction", + "kind": "INSTRUCTION", + "label": "Instructions", + "required": true + } + ], + "response_schema": [ + { + "id": "ordering", + "kind": "SEQUENCE_ORDER", + "label": "Sequence items", + "required": true, + "config": { + "min_items": 2, + "max_items": 12 + } + } + ], + "status": "ACTIVE" +} +``` + +### Response UI — sequence item list (admin canonical order) + +Mirror the **Matching inputs** row pattern, but with a **single column** and **drag-to-reorder** handles. The **vertical order in the admin list is the correct order** learners must produce. + +``` +┌─ Sequence items * ─────────────────────────────────────── [+ Add item] ─┐ +│ Helper: Minimum 2 items. Drag to set the correct order. Whitespace │ +│ in text is preserved. Learners see items shuffled at runtime. │ +│ │ +│ ≡ ITEM S1 [ First step_______________________________ ] [🗑] │ +│ ≡ ITEM S2 [ Second step______________________________ ] [🗑] │ +│ ≡ ITEM S3 [ Third step_______________________________ ] [🗑] │ +│ ≡ ITEM S4 [ Fourth step______________________________ ] [🗑] │ +└──────────────────────────────────────────────────────────────────────────┘ +``` + +#### UI elements + +| Element | Spec | +|---------|------| +| `≡` drag handle | Reorders rows; updates `correct_order` | +| Micro-label | `ITEM S1`, `ITEM S2`, … from item `id` | +| Text input | Single-line; placeholder `Item 1`, `Item 2`, … | +| `+ Add item` | Appends row with next `sN` id | +| 🗑 | Removes item; also remove id from `correct_order` | + +#### ID generation + +| Entity | Pattern | Example | +|--------|---------|---------| +| Sequence item ids | `s` + monotonic number | `s1`, `s2`, `s3` | + +Same rule as blanks: **stable ids** across edits; do not renumber on delete. + +#### `value` JSON shape (response) + +```json +{ + "items": [ + { "id": "s1", "text": "Preheat the oven" }, + { "id": "s2", "text": "Mix the ingredients" }, + { "id": "s3", "text": "Pour into a pan" }, + { "id": "s4", "text": "Bake for 25 minutes" } + ], + "correct_order": ["s1", "s2", "s3", "s4"] +} +``` + +| Field | Type | Required | Notes | +|-------|------|----------|-------| +| `items` | array | Yes | Pool of sequence steps | +| `items[].id` | string | Yes | Stable identifier | +| `items[].text` | string | Yes | Display text | +| `correct_order` | string[] | Yes | Permutation of `items[].id`; admin list top-to-bottom | + +#### Serialization rule + +On every drag or row edit: + +```text +correct_order = items.map(item => item.id) // after visual reorder +``` + +On load from API: + +```text +items = order items by index of id in correct_order +// if correct_order missing or invalid, fall back to items array order +``` + +#### Schema `config` + +| Config key | Default | Admin enforcement | +|------------|---------|-------------------| +| `min_items` | `2` | Block save below minimum | +| `max_items` | `12` | Disable `+ Add item` at max | + +Postman example uses `max_items: 8`; treat schema config as authoritative per definition. + +### Learner preview (admin optional) + +| Mode | Behavior | +|------|----------| +| Authoring | Show ordered list (canonical answer) | +| Preview | Shuffle a copy of `items` for display; learner drags to match `correct_order` | + +Shuffle for preview only — never mutate stored `correct_order`. + +### Combining with other response kinds + +Definitions may pair `SEQUENCE_ORDER` with `ANSWER_TIMER` or `OPTION` (see Postman). Render each response schema slot as its own card; only the `SEQUENCE_ORDER` slot uses the sequence editor. + +--- + +## TypeScript types + +```typescript +/** Matches dynamic_payload root */ +export interface DynamicQuestionPayload { + stimulus: DynamicElementInstance[]; + response: DynamicElementInstance[]; +} + +export interface DynamicElementInstance { + id: string; + kind: string; + value?: unknown; + meta?: Record; +} + +/** SELECT_MISSING_WORDS — stimulus */ +export type ClozeSegment = + | { type: "text"; value: string } + | { type: "blank"; id: string }; + +export interface ClozeStimulusValue { + segments: ClozeSegment[]; + word_bank: Array<{ id: string; text: string }>; + allow_reuse?: boolean; +} + +/** SELECT_MISSING_WORDS — response */ +export interface ClozeResponseValue { + blanks: Array<{ + blank_id: string; + text: string; + word_id?: string; + }>; +} + +/** SEQUENCE_ORDER — response */ +export interface SequenceOrderValue { + items: Array<{ id: string; text: string }>; + correct_order: string[]; +} + +/** Local admin form state (stimulus cloze) */ +export interface ClozeStimulusFormState { + blocks: Array< + | { kind: "text"; clientKey: string; value: string } + | { kind: "blank"; clientKey: string; id: string } + >; + wordBank: Array<{ id: string; text: string; clientKey: string }>; + allowReuse: boolean; +} + +/** Local admin form state (sequence) */ +export interface SequenceOrderFormState { + items: Array<{ id: string; text: string; clientKey: string }>; +} +``` + +--- + +## Serialization helpers + +### Cloze: form → API (stimulus) + +```typescript +export function clozeStimulusToValue(state: ClozeStimulusFormState): ClozeStimulusValue { + return { + segments: state.blocks.map((block) => + block.kind === "text" + ? { type: "text", value: block.value } + : { type: "blank", id: block.id } + ), + word_bank: state.wordBank.map((w) => ({ id: w.id, text: w.text })), + allow_reuse: state.allowReuse, + }; +} +``` + +### Cloze: API → form (stimulus) + +```typescript +export function clozeStimulusFromValue(value: ClozeStimulusValue): ClozeStimulusFormState { + return { + blocks: value.segments.map((seg, i) => + seg.type === "text" + ? { kind: "text", clientKey: `t-${i}`, value: seg.value } + : { kind: "blank", clientKey: `b-${seg.id}`, id: seg.id } + ), + wordBank: value.word_bank.map((w) => ({ + id: w.id, + text: w.text, + clientKey: `w-${w.id}`, + })), + allowReuse: value.allow_reuse ?? false, + }; +} +``` + +### Cloze: blank ids from stimulus (for response editor) + +```typescript +export function listBlankIds(stimulus: ClozeStimulusValue): string[] { + return stimulus.segments + .filter((s): s is { type: "blank"; id: string } => s.type === "blank") + .map((s) => s.id); +} +``` + +### Sequence: form → API + +```typescript +export function sequenceOrderToValue(state: SequenceOrderFormState): SequenceOrderValue { + const items = state.items.map((i) => ({ id: i.id, text: i.text })); + return { + items, + correct_order: items.map((i) => i.id), + }; +} +``` + +### Sequence: API → form + +```typescript +export function sequenceOrderFromValue(value: SequenceOrderValue): SequenceOrderFormState { + const byId = new Map(value.items.map((i) => [i.id, i])); + const ordered = + value.correct_order?.length > 0 + ? value.correct_order.map((id) => byId.get(id)).filter(Boolean) + : value.items; + + return { + items: ordered.map((i) => ({ + id: i!.id, + text: i!.text, + clientKey: `s-${i!.id}`, + })), + }; +} +``` + +### Building `dynamic_payload` for save + +```typescript +function upsertElement( + list: DynamicElementInstance[], + slot: { id: string; kind: string }, + value: unknown +): DynamicElementInstance[] { + const idx = list.findIndex((e) => e.id === slot.id); + const el: DynamicElementInstance = { id: slot.id, kind: slot.kind, value }; + if (idx === -1) return [...list, el]; + const next = [...list]; + next[idx] = el; + return next; +} +``` + +--- + +## Client-side validation + +Validate before `POST /api/v1/questions` or `PUT /api/v1/questions/:id`. + +### SELECT_MISSING_WORDS (stimulus) + +| Check | Error message | +|-------|---------------| +| ≥ 1 blank segment | `Add at least one blank` | +| ≤ `max_blanks` | `Too many blanks (max N)` | +| Each text segment not only whitespace | `Text segments cannot be empty` | +| Blank ids unique | `Duplicate blank id` | +| ≥ `min_word_bank` words | `Add at least N words to the bank` | +| Word texts non-empty | `Word bank entries cannot be empty` | +| Word ids unique | `Duplicate word id` | + +### SELECT_MISSING_WORDS (response) + +| Check | Error message | +|-------|---------------| +| Every stimulus blank has an answer | `Missing answer for blank b2` | +| Answer `text` non-empty | `Answer for b1 cannot be empty` | +| If `!allow_reuse` | Same `word_id` cannot appear twice | +| `blank_id` set matches stimulus | `Unknown blank_id in response` | + +### SEQUENCE_ORDER (response) + +| Check | Error message | +|-------|---------------| +| ≥ `min_items` (default 2) | `Add at least 2 sequence items` | +| ≤ `max_items` | `Too many items (max N)` | +| Item texts non-empty | `Sequence item cannot be empty` | +| Item ids unique | `Duplicate item id` | +| `correct_order` length = `items.length` | `Correct order must include every item` | +| `correct_order` ids ⊆ `items` ids | `Invalid id in correct_order` | + +--- + +## React component patterns + +### Registry map (extend your existing dynamic renderer) + +```typescript +const STIMULUS_RENDERERS: Record> = { + SELECT_MISSING_WORDS: ClozeStimulusEditor, + MATCHING_INPUTS: MatchingInputsEditor, + INSTRUCTION: InstructionTextarea, + TEXT_PASSAGE: TextPassageTextarea, + // … +}; + +const RESPONSE_RENDERERS: Record> = { + SELECT_MISSING_WORDS: ClozeResponseEditor, + SEQUENCE_ORDER: SequenceOrderEditor, + MATCHING_ANSWER: MatchingAnswerEditor, + // … +}; + +interface SlotRendererProps { + schema: DynamicElementDefinition; + value: unknown; + onChange: (value: unknown) => void; + /** Stimulus cloze answers need stimulus cloze value */ + stimulusContext?: DynamicQuestionPayload["stimulus"]; +} +``` + +### `ClozeStimulusEditor` responsibilities + +1. Render block list (blank pills + text areas). +2. Render word bank section (`WORD BANK` header + `+ Add word`). +3. Optional `allow_reuse` checkbox. +4. Emit `ClozeStimulusValue` on change. + +### `ClozeResponseEditor` responsibilities + +1. Find sibling stimulus element with `kind === "SELECT_MISSING_WORDS"`. +2. Parse blank ids from that stimulus value. +3. Render one answer control per blank. +4. Emit `ClozeResponseValue`. + +### `SequenceOrderEditor` responsibilities + +1. Render ordered rows with drag-and-drop (`@dnd-kit` or similar). +2. `+ Add item` / delete row. +3. Keep `correct_order` in sync with visual order on every reorder. + +### Suggested component tree + +``` + + + {stimulusSchema.map(slot => ( + + {renderStimulus(slot)} + + ))} + + + {responseSchema.map(slot => ( + + {renderResponse(slot)} + + ))} + + +``` + +--- + +## Full API examples + +### Example A — Word-bank cloze (custom definition) + +**Create definition** (once): + +```http +POST /api/v1/questions/type-definitions +Authorization: Bearer +Content-Type: application/json +``` + +```json +{ + "key": "word_bank_cloze", + "display_name": "Word Bank Cloze", + "stimulus_component_kinds": ["INSTRUCTION", "SELECT_MISSING_WORDS"], + "response_component_kinds": ["SELECT_MISSING_WORDS"], + "stimulus_schema": [ + { "id": "instruction", "kind": "INSTRUCTION", "label": "Instructions", "required": true }, + { + "id": "cloze", + "kind": "SELECT_MISSING_WORDS", + "label": "Passage with blanks", + "required": true, + "config": { "min_blanks": 1, "max_blanks": 10, "min_word_bank": 2 } + } + ], + "response_schema": [ + { + "id": "cloze_answer", + "kind": "SELECT_MISSING_WORDS", + "label": "Correct selections", + "required": true + } + ], + "status": "ACTIVE" +} +``` + +**Create question:** + +```http +POST /api/v1/questions +``` + +```json +{ + "question_type": "DYNAMIC", + "question_type_definition_id": 8, + "difficulty_level": "MEDIUM", + "points": 2, + "status": "DRAFT", + "dynamic_payload": { + "stimulus": [ + { + "id": "instruction", + "kind": "INSTRUCTION", + "value": "Select the correct word from the bank for each blank." + }, + { + "id": "cloze", + "kind": "SELECT_MISSING_WORDS", + "value": { + "segments": [ + { "type": "text", "value": "Yesterday I " }, + { "type": "blank", "id": "b1" }, + { "type": "text", "value": " to school and " }, + { "type": "blank", "id": "b2" }, + { "type": "text", "value": " my homework." } + ], + "word_bank": [ + { "id": "w1", "text": "went" }, + { "id": "w2", "text": "did" }, + { "id": "w3", "text": "go" }, + { "id": "w4", "text": "do" } + ], + "allow_reuse": false + } + } + ], + "response": [ + { + "id": "cloze_answer", + "kind": "SELECT_MISSING_WORDS", + "value": { + "blanks": [ + { "blank_id": "b1", "text": "went", "word_id": "w1" }, + { "blank_id": "b2", "text": "did", "word_id": "w2" } + ] + } + } + ] + } +} +``` + +### Example B — System `fill_in_the_blank` (id often `3`) + +Uses `TEXT_PASSAGE` instead of `INSTRUCTION` for intro text; same cloze UI for the `SELECT_MISSING_WORDS` stimulus slot. + +### Example C — Sequence order + +```json +{ + "question_type": "DYNAMIC", + "question_type_definition_id": 12, + "difficulty_level": "EASY", + "points": 1, + "status": "DRAFT", + "dynamic_payload": { + "stimulus": [ + { + "id": "instruction", + "kind": "INSTRUCTION", + "value": "Put the steps of making tea in the correct order." + } + ], + "response": [ + { + "id": "ordering", + "kind": "SEQUENCE_ORDER", + "value": { + "items": [ + { "id": "s1", "text": "Boil water" }, + { "id": "s2", "text": "Put tea bag in cup" }, + { "id": "s3", "text": "Pour hot water" }, + { "id": "s4", "text": "Steep for 3 minutes" } + ], + "correct_order": ["s1", "s2", "s3", "s4"] + } + } + ] + } +} +``` + +--- + +## Comparison with Matching & Fill in the blank + +| Aspect | Matching (`MATCHING_INPUTS`) | Fill in blank (`SELECT_MISSING_WORDS` stimulus) | Sequence (`SEQUENCE_ORDER`) | +|--------|------------------------------|-----------------------------------------------|-----------------------------| +| Section | Stimulus | Stimulus (+ optional text slot) | Response only | +| Row layout | Two columns (LEFT / RIGHT) | Text blocks + blank pills | Single column + drag handle | +| List action | `+ Add row` | `+ Add text`, `+ Add blank`, `+ Add word` | `+ Add item` | +| Stable ids | `l1`, `r1` | `b1`, `w1` | `s1` | +| Answer side | `MATCHING_ANSWER` pairs | `SELECT_MISSING_WORDS` blanks[] | `correct_order[]` | +| Whitespace | Preserved in item text | Preserved in text segments | Preserved in item text | +| Min count | 2 pairs | 1 blank, 2+ bank words | 2 items | + +--- + +## Error handling + +| API error | Typical cause | Admin action | +|-----------|---------------|--------------| +| `400 Invalid dynamic_payload` | Missing required schema slot id | Ensure every `required` schema id exists in payload | +| `400 dynamic_payload is required` | Missing payload on create | Build payload before save | +| `400 question_text is not used for DYNAMIC` | Sent top-level `question_text` | Remove; use stimulus text kinds | +| `400 kind X is not allowed` | Kind not in definition | Reload definition; remount correct renderer | + +Show server `error` string in a toast; map known client validation errors inline on the relevant card. + +--- + +## Integration checklist + +### SELECT_MISSING_WORDS + +- [ ] Stimulus renderer: alternating text + blank blocks matching Fill in the blank screenshot +- [ ] Word bank section with `WORD BANK` label and `+ Add word` +- [ ] Stable `bN` / `wN` ids (no renumber on delete) +- [ ] `allow_reuse` toggle when definition allows bank reuse +- [ ] Response renderer: one answer row per stimulus blank +- [ ] Dropdown answers sourced from stimulus `word_bank` +- [ ] Serialize / deserialize `segments`, `word_bank`, `blanks` +- [ ] Client validation before save +- [ ] Cross-slot sync when blanks added/removed in stimulus + +### SEQUENCE_ORDER + +- [ ] Response-only card under **RESPONSE** section +- [ ] Row UI aligned with Matching (bordered rows, micro-labels, trash, `+ Add item`) +- [ ] Drag-and-drop reorder updates `correct_order` +- [ ] Stable `sN` item ids +- [ ] Enforce `min_items` / `max_items` from schema `config` +- [ ] Optional learner preview with shuffled items +- [ ] Serialize / deserialize `items` + `correct_order` + +### Shared + +- [ ] Registry maps `kind` → editor component for stimulus/response +- [ ] Load definition schema before rendering question form +- [ ] `upsertElement` by schema slot `id` on save +- [ ] Do not send `question_text` for `DYNAMIC` questions +- [ ] Practice full-update flows pass `dynamic_payload` unchanged in shape + +--- + +## Quick reference + +### Component kinds + +``` +Stimulus: SELECT_MISSING_WORDS +Response: SELECT_MISSING_WORDS | SEQUENCE_ORDER +``` + +### Minimal valid values + +```json +// Stimulus SELECT_MISSING_WORDS +{ + "segments": [ + { "type": "text", "value": "Hello " }, + { "type": "blank", "id": "b1" }, + { "type": "text", "value": " world" } + ], + "word_bank": [{ "id": "w1", "text": "big" }], + "allow_reuse": false +} + +// Response SELECT_MISSING_WORDS +{ "blanks": [{ "blank_id": "b1", "text": "big", "word_id": "w1" }] } + +// Response SEQUENCE_ORDER +{ + "items": [ + { "id": "s1", "text": "Step A" }, + { "id": "s2", "text": "Step B" } + ], + "correct_order": ["s1", "s2"] +} +``` + +### APIs + +| Action | Endpoint | +|--------|----------| +| Component catalog | `GET /api/v1/questions/component-catalog` | +| Load definition | `GET /api/v1/questions/type-definitions/:id` | +| Create question | `POST /api/v1/questions` | +| Update question | `PUT /api/v1/questions/:id` | +| List questions in practice | `GET /api/v1/question-sets/:setId/questions` | + +--- + +*Document version: 2026-06-18 — aligns with backend `production` branch component catalog and dynamic payload conventions.* diff --git a/docs/team-member-refresh-token-admin-panel-integration.md b/docs/team-member-refresh-token-admin-panel-integration.md new file mode 100644 index 00000000..5727da64 --- /dev/null +++ b/docs/team-member-refresh-token-admin-panel-integration.md @@ -0,0 +1,673 @@ +# Team Member Refresh Token — Admin Panel Integration Guide + +This guide documents how to integrate **team member login** and **refresh token rotation** into the Yimaru admin panel. It covers the login/refresh APIs, token lifecycle, storage, HTTP client interceptors, TypeScript types, error handling, and security notes. + +**Use this guide when:** staff sign in with `POST /api/v1/team/login` and the admin panel must keep sessions alive without forcing re-login when the short-lived access JWT expires. + +--- + +## Table of contents + +1. [Feature overview](#feature-overview) +2. [Team auth vs learner auth](#team-auth-vs-learner-auth) +3. [Architecture & token lifecycle](#architecture--token-lifecycle) +4. [Token types & expiry](#token-types--expiry) +5. [Response envelopes](#response-envelopes) +6. [API reference](#api-reference) +7. [Login flow (admin panel)](#login-flow-admin-panel) +8. [Refresh flow (admin panel)](#refresh-flow-admin-panel) +9. [HTTP client integration](#http-client-integration) +10. [Session storage recommendations](#session-storage-recommendations) +11. [Logout & session invalidation](#logout--session-invalidation) +12. [JWT claims & RBAC](#jwt-claims--rbac) +13. [TypeScript types & API client](#typescript-types--api-client) +14. [Error handling](#error-handling) +15. [Security notes](#security-notes) +16. [Integration checklist](#integration-checklist) +17. [Limitations & future work](#limitations--future-work) +18. [Quick reference](#quick-reference) + +--- + +## Feature overview + +Team members (internal staff) authenticate against the **`team_members`** table. The admin panel should use the **team** auth endpoints exclusively — not learner `auth/login` or `auth/admin-login` unless you intentionally support legacy platform-admin users. + +| Capability | Endpoint | Auth required | +|------------|----------|---------------| +| Sign in | `POST /api/v1/team/login` | No | +| Refresh session | `POST /api/v1/team/refresh` | No | +| Call protected admin APIs | Any RBAC-protected route | Yes — `Authorization: Bearer ` | + +On successful **login** or **refresh**, the API returns: + +- **`access_token`** — short-lived JWT sent on every protected request +- **`refresh_token`** — long-lived opaque token used only to obtain new tokens +- **`member_id`** — team member primary key (also embedded in JWT as `UserId`) +- **`team_role`** — RBAC role string from `team_members.team_role` (e.g. `ADMIN`, `CONTENT_MANAGER`) + +--- + +## Team auth vs learner auth + +Do **not** mix token families. Each refresh endpoint only accepts tokens it issued. + +| Aspect | Team member (admin panel) | Platform user / learner | +|--------|---------------------------|-------------------------| +| Login | `POST /api/v1/team/login` | `POST /api/v1/auth/login`, OTP flows, etc. | +| Refresh | `POST /api/v1/team/refresh` | `POST /api/v1/auth/refresh` | +| Identity table | `team_members` | `users` | +| Refresh token store | `team_refresh_tokens` | `refresh_tokens` | +| Refresh rotation | **Yes** — old token revoked, new token returned | **Yes** — old token revoked server-side | +| Logout API | **Not implemented** for team | `POST /api/v1/auth/logout` | + +If the admin panel stores a team `refresh_token`, all refresh calls must go to **`/api/v1/team/refresh`**. + +--- + +## Architecture & token lifecycle + +```mermaid +sequenceDiagram + participant UI as Admin panel + participant API as Yimaru API + participant DB as PostgreSQL + + UI->>API: POST /team/login (email, password) + API->>DB: Validate member, revoke old refresh tokens + API->>DB: Insert new team_refresh_tokens row + API-->>UI: access_token + refresh_token + + loop Protected requests + UI->>API: Bearer access_token + API-->>UI: 200 or 401 (expired) + end + + UI->>API: POST /team/refresh (refresh_token) + API->>DB: Validate, revoke used token, insert new token + API-->>UI: new access_token + new refresh_token + + Note over UI: Must persist NEW refresh_token immediately +``` + +**Source of truth (backend):** + +- Handler: `internal/web_server/handlers/team_handler.go` — `TeamMemberLogin`, `TeamMemberRefresh` +- Service: `internal/services/team/tokens.go` — `IssueRefreshTokenOnLogin`, `RefreshSession` +- Migration: `000039_team_refresh_tokens` — `team_refresh_tokens` table +- Routes: `internal/web_server/routes.go` — `/team/login`, `/team/refresh` (no auth middleware) + +### Rotation rules (critical) + +1. **Single-use refresh tokens** — each `refresh_token` can be exchanged **once**. The server revokes it before issuing a new one. +2. **Always save the new refresh token** — after every successful refresh response, replace the stored `refresh_token` with `data.refresh_token` from the response. Reusing an old refresh token returns `401`. +3. **Login invalidates prior sessions** — `IssueRefreshTokenOnLogin` revokes all active refresh tokens for that member. A new login on another device/browser ends refresh capability for older sessions. +4. **Account status checked on refresh** — if the member is suspended/inactive, refresh returns `403` even with a previously valid token. + +--- + +## Token types & expiry + +| Token | Format | Config (server) | Purpose | +|-------|--------|-----------------|---------| +| Access token | JWT (HS256) | `ACCESS_EXPIRY` env (seconds) | `Authorization: Bearer` header | +| Refresh token | Opaque base32 string (~52 chars) | `REFRESH_EXPIRY` env (seconds) | Body of `POST /team/refresh` only | + +JWT claims (`internal/web_server/jwt/jwt.go`): + +```json +{ + "UserId": 42, + "Role": "ADMIN", + "iss": "yimaru.com", + "aud": ["api.yimaru.com"], + "exp": 1719244800 +} +``` + +`Role` in the JWT is the **platform role** mapped from `team_role` (see [JWT claims & RBAC](#jwt-claims--rbac)). `UserId` is the **team member ID**, not a row in `users`. + +**Admin panel tip:** decode the JWT client-side only to read `exp` for proactive refresh timing. Never trust client-side role checks for security — the API enforces RBAC on every request. + +--- + +## Response envelopes + +### Success (`200`) + +All team login/refresh success responses use `domain.Response`: + +```json +{ + "message": "Login successful", + "data": { + "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", + "refresh_token": "MFRGGZDFMZTWQ2LKONSW44DJNZ2GKY3FONUXEY3FON2GK5BA", + "member_id": 42, + "team_role": "ADMIN" + }, + "success": true, + "status_code": 200, + "metadata": null +} +``` + +Refresh success uses `"message": "Token refreshed successfully"` but **`data` has the same shape** as login. + +### Error (`4xx` / `5xx`) + +Errors use `domain.ErrorResponse`: + +```json +{ + "message": "Refresh failed", + "error": "Invalid or expired refresh token" +} +``` + +Protected routes that receive an expired access token return Fiber errors (often plain text body), e.g. `"Access token expired"` with HTTP `401`. + +--- + +## API reference + +Base URL: `{API_BASE}/api/v1` (e.g. `https://api.yimaru.com/api/v1`). + +### `POST /team/login` + +Authenticate a team member with email and password. + +**Request** + +```http +POST /api/v1/team/login +Content-Type: application/json + +{ + "email": "staff@yimaru.com", + "password": "your-password" +} +``` + +| Field | Type | Required | Validation | +|-------|------|----------|------------| +| `email` | string | Yes | Valid email | +| `password` | string | Yes | Non-empty | + +**Success `200`** — `data` is [team member session payload](#success-200). + +**Errors** + +| HTTP | `error` (typical) | Meaning | +|------|-------------------|---------| +| `400` | Validation message | Missing/invalid fields | +| `401` | `Invalid credentials` | Wrong email/password | +| `401` | `Account is not active` | Member suspended/inactive/terminated | +| `401` | `Please accept your invitation email...` | `email_verified` is false | +| `500` | Server message | Unexpected failure | + +--- + +### `POST /team/refresh` + +Exchange a valid team refresh token for a new access JWT and a **new** refresh token. + +**Request** + +```http +POST /api/v1/team/refresh +Content-Type: application/json + +{ + "refresh_token": "" +} +``` + +| Field | Type | Required | +|-------|------|----------| +| `refresh_token` | string | Yes | + +**No `Authorization` header** — this endpoint is public (the refresh token in the body is the credential). + +**Success `200`** — same `data` shape as login. **Replace both tokens in storage.** + +**Errors** + +| HTTP | `error` (typical) | Admin UI behavior | +|------|-------------------|-------------------| +| `400` | Validation / parse error | Fix client payload | +| `401` | `Invalid or expired refresh token` | Clear session, redirect to login | +| `403` | `Account is not active` | Clear session, show account disabled message | +| `500` | Server message | Retry once; then force login | + +--- + +## Login flow (admin panel) + +```mermaid +flowchart TD + A[Login form] --> B[POST /team/login] + B -->|200| C[Persist access_token + refresh_token] + C --> D[Store member_id + team_role] + D --> E[Redirect to dashboard] + B -->|401| F[Show error toast] + B -->|400| G[Show field errors] +``` + +**Recommended steps** + +1. Submit email/password to `POST /api/v1/team/login`. +2. On success, persist `access_token`, `refresh_token`, `member_id`, and `team_role`. +3. Optionally call `GET /api/v1/team/me` to load profile (requires Bearer token + `team.profile.get_mine`). +4. Navigate to the authenticated area. + +**Example (fetch)** + +```typescript +async function teamLogin(email: string, password: string): Promise { + const res = await fetch(`${API_BASE}/api/v1/team/login`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email, password }), + }); + + const body: ApiResponse = await res.json(); + + if (!res.ok) { + throw new TeamAuthError(body.message, body.error, res.status); + } + + return body.data; +} +``` + +--- + +## Refresh flow (admin panel) + +Use refresh when: + +- A protected API returns `401` with `"Access token expired"`, or +- Proactively, shortly before JWT `exp` (recommended for smoother UX) + +```mermaid +flowchart TD + A[API request with Bearer token] --> B{401 expired?} + B -->|No| C[Return response] + B -->|Yes| D{Refresh in flight?} + D -->|Yes| E[Queue request, wait for refresh] + D -->|No| F[POST /team/refresh] + F -->|200| G[Save NEW tokens] + G --> H[Retry original request] + F -->|401/403| I[Clear session → login page] +``` + +### Rules for implementers + +1. **Serialize refresh** — only one refresh request at a time. Concurrent 401s should share the same in-flight refresh promise (mutex / queue). +2. **Update storage atomically** — write both `access_token` and `refresh_token` together after refresh succeeds. +3. **Do not refresh with `/auth/refresh`** — team tokens are stored in a different table. +4. **Retry the failed request once** with the new access token after refresh. +5. **On refresh failure** — clear all auth state and redirect to login. Do not retry refresh in a loop. + +**Example** + +```typescript +async function teamRefresh(refreshToken: string): Promise { + const res = await fetch(`${API_BASE}/api/v1/team/refresh`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ refresh_token: refreshToken }), + }); + + const body: ApiResponse = await res.json(); + + if (!res.ok) { + throw new TeamAuthError(body.message, body.error, res.status); + } + + // IMPORTANT: body.data.refresh_token is NEW — old one is revoked + return body.data; +} +``` + +--- + +## HTTP client integration + +### Axios interceptor sketch + +```typescript +import axios, { AxiosError, InternalAxiosRequestConfig } from "axios"; +import { authStore } from "./auth-store"; // your persistence layer + +const api = axios.create({ baseURL: `${API_BASE}/api/v1` }); + +api.interceptors.request.use((config) => { + const token = authStore.getAccessToken(); + if (token) { + config.headers.Authorization = `Bearer ${token}`; + } + return config; +}); + +let refreshPromise: Promise | null = null; + +api.interceptors.response.use( + (response) => response, + async (error: AxiosError) => { + const original = error.config as InternalAxiosRequestConfig & { _retry?: boolean }; + + if ( + error.response?.status !== 401 || + original._retry || + original.url?.includes("/team/login") || + original.url?.includes("/team/refresh") + ) { + return Promise.reject(error); + } + + const msg = String(error.response?.data ?? ""); + if (!msg.includes("Access token expired") && !msg.includes("Invalid access token")) { + return Promise.reject(error); + } + + original._retry = true; + + if (!refreshPromise) { + const rt = authStore.getRefreshToken(); + if (!rt) { + authStore.clear(); + return Promise.reject(error); + } + refreshPromise = teamRefresh(rt) + .then((session) => { + authStore.setSession(session); + return session; + }) + .finally(() => { + refreshPromise = null; + }); + } + + try { + const session = await refreshPromise; + original.headers.Authorization = `Bearer ${session.access_token}`; + return api(original); + } catch { + authStore.clear(); + window.location.href = "/login"; + return Promise.reject(error); + } + } +); + +export { api }; +``` + +### Proactive refresh (optional) + +Decode JWT `exp` and schedule refresh ~60 seconds before expiry: + +```typescript +function scheduleProactiveRefresh(accessToken: string, refreshToken: string) { + const payload = JSON.parse(atob(accessToken.split(".")[1])); + const expiresAtMs = payload.exp * 1000; + const refreshAtMs = expiresAtMs - 60_000; + const delay = Math.max(0, refreshAtMs - Date.now()); + + setTimeout(async () => { + try { + const session = await teamRefresh(refreshToken); + authStore.setSession(session); + scheduleProactiveRefresh(session.access_token, session.refresh_token); + } catch { + authStore.clear(); + } + }, delay); +} +``` + +Use proactive refresh **in addition to** the 401 interceptor, not instead of it. + +--- + +## Session storage recommendations + +| Storage | Access token | Refresh token | Notes | +|---------|--------------|---------------|-------| +| `sessionStorage` | OK | OK | Cleared on tab close; simpler SPA setup | +| `localStorage` | OK | OK | Survives browser restart; slightly higher XSS risk | +| Memory only + httpOnly cookie | Best if BFF exists | Best if BFF exists | Requires a backend-for-frontend to set cookies | + +**Minimum to persist after login/refresh:** + +```typescript +interface TeamMemberSession { + access_token: string; + refresh_token: string; + member_id: number; + team_role: string; +} +``` + +Also store nothing sensitive in URL query params. Never send `refresh_token` as a query parameter or log it. + +--- + +## Logout & session invalidation + +There is **no** `POST /api/v1/team/logout` endpoint today. + +**Client-side logout** + +1. Clear `access_token`, `refresh_token`, and session metadata from storage. +2. Redirect to the login page. + +**Server-side invalidation (without logout API)** + +| Event | Effect on existing refresh tokens | +|-------|-----------------------------------| +| User logs in again (same or other device) | All prior refresh tokens for that member revoked | +| Refresh succeeds | Previous refresh token revoked; only the new one works | +| Admin changes member status to non-active | Next refresh returns `403` | +| Token expires (`REFRESH_EXPIRY`) | Refresh returns `401` | + +For “log out everywhere”, the member must sign in again (which revokes old tokens) or an admin must deactivate the account. + +--- + +## JWT claims & RBAC + +`team_role` from the API maps to JWT `Role` via `TeamRole.PlatformRole()`: + +| `team_role` (API) | JWT `Role` | RBAC behavior | +|-------------------|------------|---------------| +| `SUPER_ADMIN` | `SUPER_ADMIN` | Full bypass | +| `ADMIN`, `CONTENT_MANAGER`, `FINANCE`, `HR`, `ANALYST` | `ADMIN` | Permission checks via RBAC | +| `INSTRUCTOR` | `INSTRUCTOR` | Limited permissions | +| `SUPPORT_AGENT` | `SUPPORT` | Support-scoped permissions | + +Protected admin routes use `authMiddleware` + `RequirePermission(...)`. A valid access token alone is not enough — the role must have the required permission key. + +After refresh, `team_role` in the response reflects the current DB value. Update any UI role badges if you cache `team_role` separately from the JWT. + +--- + +## TypeScript types & API client + +```typescript +export interface ApiResponse { + message: string; + data: T; + success: boolean; + status_code: number; + metadata?: unknown; +} + +export interface ApiErrorResponse { + message: string; + error?: string; +} + +export interface TeamMemberSession { + access_token: string; + refresh_token: string; + member_id: number; + team_role: string; +} + +export interface TeamMemberLoginRequest { + email: string; + password: string; +} + +export interface TeamMemberRefreshRequest { + refresh_token: string; +} + +export class TeamAuthError extends Error { + constructor( + message: string, + public readonly detail: string | undefined, + public readonly status: number + ) { + super(message); + this.name = "TeamAuthError"; + } +} +``` + +### React Query / auth context sketch + +```typescript +import { createContext, useContext, useMemo, useState } from "react"; + +type AuthContextValue = { + session: TeamMemberSession | null; + login: (email: string, password: string) => Promise; + logout: () => void; + getAccessToken: () => string | null; +}; + +const AuthContext = createContext(null); + +export function AuthProvider({ children }: { children: React.ReactNode }) { + const [session, setSession] = useState(() => + loadSessionFromStorage() + ); + + const value = useMemo( + () => ({ + session, + async login(email, password) { + const next = await teamLogin(email, password); + saveSessionToStorage(next); + setSession(next); + }, + logout() { + clearSessionStorage(); + setSession(null); + }, + getAccessToken: () => session?.access_token ?? null, + }), + [session] + ); + + return {children}; +} + +export function useAuth() { + const ctx = useContext(AuthContext); + if (!ctx) throw new Error("useAuth must be used within AuthProvider"); + return ctx; +} +``` + +Wire the [Axios interceptor](#axios-interceptor-sketch) to `authStore` / `AuthProvider` so all admin API modules share the same refresh logic. + +--- + +## Error handling + +| Scenario | HTTP | Action | +|----------|------|--------| +| Wrong password | `401` on login | Show `error` message; keep form | +| Pending invitation | `401` on login | Link to invitation accept flow | +| Access token expired | `401` on API | Trigger refresh once, then retry | +| Refresh token expired/revoked | `401` on refresh | Clear session → login | +| Account deactivated | `403` on refresh | Clear session → show support message | +| Missing permission | `403` on API | Show “no access” (do not refresh) | +| Network error | — | Toast + retry; do not clear session | + +**Distinguish 401 causes on protected routes** + +- `"Access token expired"` / `"Invalid access token"` → try refresh +- `"Authorization header missing"` → user not logged in → login page +- Refresh endpoint `401` → session dead → login page + +--- + +## Security notes + +1. **HTTPS only** in production for login and refresh. +2. **Never expose refresh tokens** in logs, analytics, or error reports. +3. **Rotate on every refresh** — treat `refresh_token` like a password; store the latest value only. +4. **XSS** — if using `localStorage`, keep dependencies patched; CSP helps. Prefer httpOnly cookies if you add a BFF later. +5. **CSRF** — not applicable to bearer-token JSON APIs from a SPA origin; relevant only if you move tokens to cookies. +6. **Tab sync** — if multiple tabs share `localStorage`, listen to `storage` events so one tab’s refresh updates others. + +--- + +## Integration checklist + +- [ ] Login form calls `POST /api/v1/team/login` (not `auth/admin-login` unless supporting legacy users) +- [ ] Persist `access_token`, `refresh_token`, `member_id`, `team_role` on login success +- [ ] All admin API calls send `Authorization: Bearer ` +- [ ] HTTP client intercepts `401` access-token failures and calls `POST /api/v1/team/refresh` +- [ ] After refresh, **replace** stored `refresh_token` with the new value from `data` +- [ ] Serialize concurrent refresh attempts (single in-flight refresh) +- [ ] On refresh `401`/`403`, clear storage and redirect to login +- [ ] Logout clears tokens locally (no team logout API yet) +- [ ] Optional: proactive refresh before JWT `exp` +- [ ] RBAC: gate UI with permissions; do not rely on `team_role` alone +- [ ] Test: login → wait for access expiry → API call succeeds via refresh +- [ ] Test: reuse old refresh token → expect `401` +- [ ] Test: login on second browser → first browser refresh fails → login prompt + +--- + +## Limitations & future work + +| Item | Status | +|------|--------| +| Team logout endpoint (revoke refresh token) | Not implemented — client clears storage only | +| Refresh token in httpOnly cookie | Not implemented — body JSON only | +| `Refresh-Token` header on API calls | Read in middleware but **not required** for team flow | +| Activity log on refresh | `AUTH_TOKEN_REFRESHED` recorded server-side | + +--- + +## Quick reference + +```http +# Login +POST /api/v1/team/login +Content-Type: application/json +{ "email": "...", "password": "..." } + +# Refresh (no Authorization header) +POST /api/v1/team/refresh +Content-Type: application/json +{ "refresh_token": "..." } + +# Protected admin call +GET /api/v1/team/me +Authorization: Bearer +``` + +**Success `data` fields:** `access_token`, `refresh_token`, `member_id`, `team_role` + +**Backend files:** `team_handler.go`, `tokens.go`, `routes.go` (`/team/login`, `/team/refresh`) + +**Swagger:** `docs/swagger.yaml` — tags `team`, paths `/api/v1/team/login` and `/api/v1/team/refresh` diff --git a/internal/domain/scheduled_notification.go b/internal/domain/scheduled_notification.go index c6d337a9..7112e497 100644 --- a/internal/domain/scheduled_notification.go +++ b/internal/domain/scheduled_notification.go @@ -16,13 +16,38 @@ const ( ) type ScheduledNotificationTargetRaw struct { - Phones []string `json:"phones,omitempty"` - Emails []string `json:"emails,omitempty"` + Phones []string `json:"phones,omitempty"` + Emails []string `json:"emails,omitempty"` + TeamMemberIDs []int64 `json:"team_member_ids,omitempty"` + TeamRole string `json:"team_role,omitempty"` // In-app scheduled notifications may store optional metadata here. Level string `json:"level,omitempty"` Type string `json:"type,omitempty"` } +// ParseScheduledTargetRaw decodes team/extra targeting stored in scheduled_notifications.target_raw. +func ParseScheduledTargetRaw(data json.RawMessage) ScheduledNotificationTargetRaw { + var raw ScheduledNotificationTargetRaw + if len(data) > 0 { + _ = json.Unmarshal(data, &raw) + } + return raw +} + +// EnrichScheduledTargets copies team targeting from target_raw onto the scheduled notification for API responses. +func EnrichScheduledTargets(sn *ScheduledNotification) { + if sn == nil { + return + } + raw := ParseScheduledTargetRaw(sn.TargetRaw) + if len(raw.TeamMemberIDs) > 0 { + sn.TargetTeamMemberIDs = raw.TeamMemberIDs + } + if raw.TeamRole != "" { + sn.TargetTeamRole = raw.TeamRole + } +} + type ScheduledNotification struct { ID int64 `json:"id"` Channel DeliveryChannel `json:"channel"` @@ -36,9 +61,11 @@ type ScheduledNotification struct { ScheduledAt time.Time `json:"scheduled_at"` Status ScheduledNotificationStatus `json:"status"` - TargetUserIDs []int64 `json:"target_user_ids,omitempty"` - TargetRole string `json:"target_role,omitempty"` - TargetRaw json.RawMessage `json:"target_raw,omitempty"` + TargetUserIDs []int64 `json:"target_user_ids,omitempty"` + TargetRole string `json:"target_role,omitempty"` + TargetTeamMemberIDs []int64 `json:"target_team_member_ids,omitempty"` + TargetTeamRole string `json:"target_team_role,omitempty"` + TargetRaw json.RawMessage `json:"target_raw,omitempty"` AttemptCount int32 `json:"attempt_count"` LastError string `json:"last_error,omitempty"` diff --git a/internal/repository/scheduled_notification.go b/internal/repository/scheduled_notification.go index 042a0d44..b5e174a0 100644 --- a/internal/repository/scheduled_notification.go +++ b/internal/repository/scheduled_notification.go @@ -206,5 +206,7 @@ func mapScheduledDBToDomain(db *dbgen.ScheduledNotification) *domain.ScheduledNo sn.CancelledAt = &t } + domain.EnrichScheduledTargets(sn) + return sn } diff --git a/internal/services/notification/recipients.go b/internal/services/notification/recipients.go new file mode 100644 index 00000000..3d3b066c --- /dev/null +++ b/internal/services/notification/recipients.go @@ -0,0 +1,115 @@ +package notificationservice + +import ( + "context" + + "Yimaru-Backend/internal/domain" +) + +const bulkRecipientLimit int32 = 100_000 + +func dedupeInt64(ids []int64) []int64 { + if len(ids) == 0 { + return nil + } + seen := make(map[int64]struct{}, len(ids)) + out := make([]int64, 0, len(ids)) + for _, id := range ids { + if id <= 0 { + continue + } + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + out = append(out, id) + } + return out +} + +func (s *Service) ResolveUserIDsForBulk(ctx context.Context, userIDs []int64, role string) ([]int64, error) { + ids := dedupeInt64(userIDs) + if len(ids) > 0 || role == "" { + return ids, nil + } + users, _, err := s.userSvc.GetAllUsers(ctx, domain.UserFilter{Role: role}) + if err != nil { + return nil, err + } + for _, u := range users { + ids = append(ids, u.ID) + } + return dedupeInt64(ids), nil +} + +func (s *Service) ResolveTeamMemberIDsForBulk(ctx context.Context, teamMemberIDs []int64, teamRole string) ([]int64, error) { + ids := dedupeInt64(teamMemberIDs) + if len(ids) > 0 || teamRole == "" { + return ids, nil + } + if s.teamStore == nil { + return ids, nil + } + role := teamRole + members, _, err := s.teamStore.GetAllTeamMembers(ctx, &role, nil, nil, bulkRecipientLimit, 0) + if err != nil { + return nil, err + } + for _, m := range members { + ids = append(ids, m.ID) + } + return dedupeInt64(ids), nil +} + +func (s *Service) ResolveBulkEmailAddresses( + ctx context.Context, + userIDs []int64, + role string, + teamMemberIDs []int64, + teamRole string, + directEmails []string, +) (emails []string, resolvedUserIDs []int64, resolvedTeamMemberIDs []int64, err error) { + emailSet := make(map[string]struct{}) + + for _, e := range directEmails { + if e != "" { + emailSet[e] = struct{}{} + } + } + + resolvedUserIDs, err = s.ResolveUserIDsForBulk(ctx, userIDs, role) + if err != nil { + return nil, nil, nil, err + } + for _, uid := range resolvedUserIDs { + user, err := s.userSvc.GetUserByID(ctx, uid) + if err != nil { + continue + } + if user.Email != "" { + emailSet[user.Email] = struct{}{} + } + } + + resolvedTeamMemberIDs, err = s.ResolveTeamMemberIDsForBulk(ctx, teamMemberIDs, teamRole) + if err != nil { + return nil, nil, nil, err + } + if s.teamStore != nil { + for _, mid := range resolvedTeamMemberIDs { + member, err := s.teamStore.GetTeamMemberByID(ctx, mid) + if err != nil { + continue + } + if member.Email != "" { + emailSet[member.Email] = struct{}{} + } + } + } + + emails = make([]string, 0, len(emailSet)) + for e := range emailSet { + emails = append(emails, e) + } + return emails, resolvedUserIDs, resolvedTeamMemberIDs, nil +} diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go index e44cc906..95c5a5f7 100644 --- a/internal/services/notification/service.go +++ b/internal/services/notification/service.go @@ -43,6 +43,7 @@ type Service struct { stopCh chan struct{} config *config.Config userSvc *user.Service + teamStore ports.TeamStore messengerSvc *messenger.Service emailTemplateSvc *emailtemplates.Service mongoLogger *zap.Logger @@ -58,6 +59,7 @@ func New( cfg *config.Config, messengerSvc *messenger.Service, userSvc *user.Service, + teamStore ports.TeamStore, emailTemplateSvc *emailtemplates.Service, ) *Service { hub := ws.NewNotificationHub() @@ -72,6 +74,7 @@ func New( stopCh: make(chan struct{}), messengerSvc: messengerSvc, userSvc: userSvc, + teamStore: teamStore, emailTemplateSvc: emailTemplateSvc, config: cfg, } @@ -254,31 +257,6 @@ func (s *Service) GetFilteredNotifications(ctx context.Context, filter domain.No return s.store.GetFilteredNotifications(ctx, filter) } -// RecordNotification saves a notification to the database for history/audit without dispatching to the worker. -func (s *Service) RecordNotification(ctx context.Context, recipientID int64, notifType domain.NotificationType, channel domain.DeliveryChannel, level domain.NotificationLevel, headline, message string) { - notification := &domain.Notification{ - ID: helpers.GenerateID(), - RecipientID: recipientID, - Type: notifType, - Level: level, - DeliveryChannel: channel, - DeliveryStatus: domain.DeliveryStatusSent, - Payload: domain.NotificationPayload{ - Headline: headline, - Message: message, - }, - Timestamp: time.Now(), - } - - if _, err := s.store.CreateNotification(ctx, notification); err != nil { - s.mongoLogger.Error("[NotificationSvc.RecordNotification] Failed to record notification", - zap.Int64("recipientID", recipientID), - zap.String("channel", string(channel)), - zap.Error(err), - ) - } -} - func (s *Service) SendNotification(ctx context.Context, notification *domain.Notification) error { notification.ID = helpers.GenerateID() @@ -830,7 +808,7 @@ func (s *Service) SendBulkSMS(ctx context.Context, recipients []string, message return sent, failed } -// SendBulkInAppNotification creates in-app notifications for each user (DB + WebSocket). +// SendBulkInAppNotification creates in-app notifications for each platform user (DB + WebSocket). func (s *Service) SendBulkInAppNotification( ctx context.Context, userIDs []int64, @@ -880,6 +858,95 @@ func (s *Service) SendBulkInAppNotification( return sent, failed } +// SendBulkInAppToTeamMembers creates in-app notifications for each team member (DB + WebSocket). +func (s *Service) SendBulkInAppToTeamMembers( + ctx context.Context, + memberIDs []int64, + title, message string, + notifType domain.NotificationType, + level domain.NotificationLevel, +) (sent int, failed int) { + for _, mid := range memberIDs { + notification := &domain.Notification{ + RecipientID: mid, + ReceiverType: domain.ReceiverTypeTeamMember, + Type: notifType, + Level: level, + ErrorSeverity: domain.NotificationErrorSeverityMedium, + Reciever: domain.NotificationRecieverSideTeamMember, + DeliveryChannel: domain.DeliveryChannelInApp, + Payload: domain.NotificationPayload{ + Headline: title, + Message: message, + }, + } + + if err := s.SendNotification(ctx, notification); err != nil { + s.mongoLogger.Error("[NotificationSvc.SendBulkInAppToTeamMembers] Failed to send", + zap.Int64("teamMemberID", mid), + zap.Error(err), + ) + failed++ + continue + } + sent++ + } + + s.mongoLogger.Info("[NotificationSvc.SendBulkInAppToTeamMembers] Bulk in-app completed", + zap.Int("totalRecipients", len(memberIDs)), + zap.Int("sent", sent), + zap.Int("failed", failed), + ) + + return sent, failed +} + +// RecordNotification saves a notification to the database for history/audit without dispatching to the worker. +func (s *Service) RecordNotification(ctx context.Context, recipientID int64, notifType domain.NotificationType, channel domain.DeliveryChannel, level domain.NotificationLevel, headline, message string) { + s.recordNotification(ctx, recipientID, domain.ReceiverTypeUser, domain.NotificationRecieverSideCustomer, notifType, channel, level, headline, message) +} + +// RecordTeamMemberNotification saves an email/in-app history row for a team member recipient. +func (s *Service) RecordTeamMemberNotification(ctx context.Context, memberID int64, notifType domain.NotificationType, channel domain.DeliveryChannel, level domain.NotificationLevel, headline, message string) { + s.recordNotification(ctx, memberID, domain.ReceiverTypeTeamMember, domain.NotificationRecieverSideTeamMember, notifType, channel, level, headline, message) +} + +func (s *Service) recordNotification( + ctx context.Context, + recipientID int64, + receiverType domain.ReceiverType, + reciever domain.NotificationRecieverSide, + notifType domain.NotificationType, + channel domain.DeliveryChannel, + level domain.NotificationLevel, + headline, message string, +) { + notification := &domain.Notification{ + ID: helpers.GenerateID(), + RecipientID: recipientID, + ReceiverType: receiverType, + Reciever: reciever, + Type: notifType, + Level: level, + DeliveryChannel: channel, + DeliveryStatus: domain.DeliveryStatusSent, + Payload: domain.NotificationPayload{ + Headline: headline, + Message: message, + }, + Timestamp: time.Now(), + } + + if _, err := s.store.CreateNotification(ctx, notification); err != nil { + s.mongoLogger.Error("[NotificationSvc.RecordNotification] Failed to record notification", + zap.Int64("recipientID", recipientID), + zap.String("receiver_type", string(receiverType)), + zap.String("channel", string(channel)), + zap.Error(err), + ) + } +} + // SendBulkEmail sends an email to multiple recipients using the messenger service. // It sends sequentially and returns the count of successful and failed deliveries. func (s *Service) SendBulkEmail(ctx context.Context, recipients []string, content domain.OutboundEmailContent, attachments []*resend.Attachment) (sent int, failed int) { @@ -1256,37 +1323,17 @@ func (s *Service) resolvePhoneNumbers(ctx context.Context, sn *domain.ScheduledN } func (s *Service) resolveEmails(ctx context.Context, sn *domain.ScheduledNotification) []string { - emailSet := make(map[string]struct{}) - - userIDs := sn.TargetUserIDs - if len(userIDs) == 0 && sn.TargetRole != "" { - users, _, err := s.userSvc.GetAllUsers(ctx, domain.UserFilter{Role: sn.TargetRole}) - if err == nil { - for _, u := range users { - userIDs = append(userIDs, u.ID) - } - } - } - - for _, uid := range userIDs { - user, err := s.userSvc.GetUserByID(ctx, uid) - if err == nil && user.Email != "" { - emailSet[user.Email] = struct{}{} - } - } - - if len(sn.TargetRaw) > 0 { - var raw domain.ScheduledNotificationTargetRaw - if err := json.Unmarshal(sn.TargetRaw, &raw); err == nil { - for _, e := range raw.Emails { - emailSet[e] = struct{}{} - } - } - } - - emails := make([]string, 0, len(emailSet)) - for e := range emailSet { - emails = append(emails, e) + raw := domain.ParseScheduledTargetRaw(sn.TargetRaw) + emails, _, _, err := s.ResolveBulkEmailAddresses( + ctx, + sn.TargetUserIDs, + sn.TargetRole, + raw.TeamMemberIDs, + raw.TeamRole, + raw.Emails, + ) + if err != nil { + return nil } return emails } @@ -1400,13 +1447,25 @@ func scheduledInAppMeta(sn *domain.ScheduledNotification) (domain.NotificationTy } func (s *Service) dispatchScheduledInApp(ctx context.Context, sn *domain.ScheduledNotification) error { - userIDs := s.resolveUserIDs(ctx, sn) - if len(userIDs) == 0 { + raw := domain.ParseScheduledTargetRaw(sn.TargetRaw) + + userIDs, err := s.ResolveUserIDsForBulk(ctx, sn.TargetUserIDs, sn.TargetRole) + if err != nil { + return err + } + teamMemberIDs, err := s.ResolveTeamMemberIDsForBulk(ctx, raw.TeamMemberIDs, raw.TeamRole) + if err != nil { + return err + } + if len(userIDs) == 0 && len(teamMemberIDs) == 0 { return fmt.Errorf("no in-app recipients resolved") } notifType, level := scheduledInAppMeta(sn) - sent, failed := s.SendBulkInAppNotification(ctx, userIDs, sn.Title, sn.Message, notifType, level) + userSent, userFailed := s.SendBulkInAppNotification(ctx, userIDs, sn.Title, sn.Message, notifType, level) + teamSent, teamFailed := s.SendBulkInAppToTeamMembers(ctx, teamMemberIDs, sn.Title, sn.Message, notifType, level) + sent := userSent + teamSent + failed := userFailed + teamFailed if sent == 0 && failed > 0 { return fmt.Errorf("all %d in-app deliveries failed", failed) } diff --git a/internal/web_server/handlers/notification_handler.go b/internal/web_server/handlers/notification_handler.go index 3cbbd05a..c4da8515 100644 --- a/internal/web_server/handlers/notification_handler.go +++ b/internal/web_server/handlers/notification_handler.go @@ -1438,24 +1438,26 @@ func (h *Handler) SendBulkSMS(c *fiber.Ctx) error { // SendBulkInAppNotification godoc // @Summary Send bulk in-app notification -// @Description Creates in-app notifications for specified user IDs or all users matching a role. Optionally schedule for later with scheduled_at (RFC3339). +// @Description Creates in-app notifications for specified platform user IDs, users matching a platform role, team member IDs, or team members matching a team_role. Optionally schedule for later with scheduled_at (RFC3339). // @Tags notifications // @Accept json // @Produce json -// @Param body body object{title=string,message=string,user_ids=[]int64,role=string,scheduled_at=string,type=string,level=string} true "Bulk in-app content" +// @Param body body object{title=string,message=string,user_ids=[]int64,role=string,team_member_ids=[]int64,team_role=string,scheduled_at=string,type=string,level=string} true "Bulk in-app content" // @Success 200 {object} domain.Response // @Failure 400 {object} domain.ErrorResponse // @Failure 500 {object} domain.ErrorResponse // @Router /api/v1/notifications/bulk-in-app [post] func (h *Handler) SendBulkInAppNotification(c *fiber.Ctx) error { type Request struct { - Title string `json:"title" validate:"required"` - Message string `json:"message" validate:"required"` - UserIDs []int64 `json:"user_ids"` - Role string `json:"role"` - ScheduledAt string `json:"scheduled_at"` - Type string `json:"type"` - Level string `json:"level"` + Title string `json:"title" validate:"required"` + Message string `json:"message" validate:"required"` + UserIDs []int64 `json:"user_ids"` + Role string `json:"role"` + TeamMemberIDs []int64 `json:"team_member_ids"` + TeamRole string `json:"team_role"` + ScheduledAt string `json:"scheduled_at"` + Type string `json:"type"` + Level string `json:"level"` } var req Request @@ -1472,10 +1474,10 @@ func (h *Handler) SendBulkInAppNotification(c *fiber.Ctx) error { }) } - if len(req.UserIDs) == 0 && req.Role == "" { + if len(req.UserIDs) == 0 && req.Role == "" && len(req.TeamMemberIDs) == 0 && req.TeamRole == "" { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "No recipients specified", - Error: "Provide user_ids or role", + Error: "Provide user_ids, role, team_member_ids, or team_role", }) } @@ -1504,8 +1506,10 @@ func (h *Handler) SendBulkInAppNotification(c *fiber.Ctx) error { creatorID, _ := c.Locals("user_id").(int64) targetRaw, _ := json.Marshal(domain.ScheduledNotificationTargetRaw{ - Type: string(notifType), - Level: string(level), + Type: string(notifType), + Level: string(level), + TeamMemberIDs: req.TeamMemberIDs, + TeamRole: req.TeamRole, }) sn := &domain.ScheduledNotification{ @@ -1529,10 +1533,12 @@ func (h *Handler) SendBulkInAppNotification(c *fiber.Ctx) error { scheduledID := created.ID scheduleMeta, _ := json.Marshal(map[string]interface{}{ - "channel": "in_app", - "target_users": len(req.UserIDs), - "target_role": req.Role, - "scheduled_at": req.ScheduledAt, + "channel": "in_app", + "target_users": len(req.UserIDs), + "target_role": req.Role, + "target_team_members": len(req.TeamMemberIDs), + "target_team_role": req.TeamRole, + "scheduled_at": req.ScheduledAt, }) h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, &scheduledID, fmt.Sprintf("Scheduled in-app notification ID: %d", scheduledID), scheduleMeta) @@ -1544,51 +1550,61 @@ func (h *Handler) SendBulkInAppNotification(c *fiber.Ctx) error { }) } - userIDs := req.UserIDs - if len(userIDs) == 0 && req.Role != "" { - users, _, err := h.userSvc.GetAllUsers(context.Background(), domain.UserFilter{Role: req.Role}) - if err != nil { - return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ - Message: "Failed to fetch users for role", - Error: err.Error(), - }) - } - for _, u := range users { - userIDs = append(userIDs, u.ID) - } - } - - if len(userIDs) == 0 { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "No target users found", + userIDs, err := h.notificationSvc.ResolveUserIDsForBulk(c.Context(), req.UserIDs, req.Role) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to fetch users for role", + Error: err.Error(), }) } - sent, failed := h.notificationSvc.SendBulkInAppNotification(c.Context(), userIDs, req.Title, req.Message, notifType, level) + teamMemberIDs, err := h.notificationSvc.ResolveTeamMemberIDsForBulk(c.Context(), req.TeamMemberIDs, req.TeamRole) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to fetch team members for team_role", + Error: err.Error(), + }) + } + + if len(userIDs) == 0 && len(teamMemberIDs) == 0 { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "No target recipients found", + }) + } + + userSent, userFailed := h.notificationSvc.SendBulkInAppNotification(c.Context(), userIDs, req.Title, req.Message, notifType, level) + teamSent, teamFailed := h.notificationSvc.SendBulkInAppToTeamMembers(c.Context(), teamMemberIDs, req.Title, req.Message, notifType, level) + sent := userSent + teamSent + failed := userFailed + teamFailed + totalRecipients := len(userIDs) + len(teamMemberIDs) h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkInAppNotification] Bulk in-app sent", - zap.Int("totalRecipients", len(userIDs)), + zap.Int("totalRecipients", totalRecipients), zap.Int("sent", sent), zap.Int("failed", failed), zap.Time("timestamp", time.Now()), ) bulkInAppMeta, _ := json.Marshal(map[string]interface{}{ - "channel": "in_app", - "total_recipients": len(userIDs), - "sent": sent, - "failed": failed, + "channel": "in_app", + "total_recipients": totalRecipients, + "user_recipients": len(userIDs), + "team_member_recipients": len(teamMemberIDs), + "sent": sent, + "failed": failed, }) - h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk in-app notification sent to %d users", len(userIDs)), bulkInAppMeta) + h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk in-app notification sent to %d recipients", totalRecipients), bulkInAppMeta) return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Bulk in-app notification sent", Success: true, StatusCode: fiber.StatusOK, Data: map[string]interface{}{ - "total_recipients": len(userIDs), - "sent": sent, - "failed": failed, + "total_recipients": totalRecipients, + "user_recipients": len(userIDs), + "team_member_recipients": len(teamMemberIDs), + "sent": sent, + "failed": failed, }, }) } @@ -1820,9 +1836,9 @@ func (h *Handler) SendSingleEmail(c *fiber.Ctx) error { }) } -// SendBulkEmail sends an email to multiple users by user IDs, role, or direct email addresses. +// SendBulkEmail sends an email to multiple users by user IDs, role, team member IDs, team role, or direct email addresses. // @Summary Send bulk email -// @Description Sends an email to specified user IDs, all users of a role, or direct email addresses with optional image attachment. Optionally schedule for later with scheduled_at (RFC3339). +// @Description Sends an email to specified user IDs, users of a platform role, team member IDs, team members of a team_role, or direct email addresses with optional image attachment. Optionally schedule for later with scheduled_at (RFC3339). // @Tags notifications // @Accept multipart/form-data // @Produce json @@ -1833,6 +1849,8 @@ func (h *Handler) SendSingleEmail(c *fiber.Ctx) error { func (h *Handler) SendBulkEmail(c *fiber.Ctx) error { role := c.FormValue("role") userIDsRaw := c.FormValue("user_ids") + teamMemberIDsRaw := c.FormValue("team_member_ids") + teamRole := c.FormValue("team_role") emailsRaw := c.FormValue("emails") scheduledAtRaw := c.FormValue("scheduled_at") @@ -1869,10 +1887,20 @@ func (h *Handler) SendBulkEmail(c *fiber.Ctx) error { } } - if len(userIDs) == 0 && role == "" && len(directEmails) == 0 { + var teamMemberIDs []int64 + if teamMemberIDsRaw != "" { + if err := json.Unmarshal([]byte(teamMemberIDsRaw), &teamMemberIDs); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "Invalid team_member_ids format", + Error: "team_member_ids must be a JSON array of integers", + }) + } + } + + if len(userIDs) == 0 && role == "" && len(teamMemberIDs) == 0 && teamRole == "" && len(directEmails) == 0 { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "No recipients specified", - Error: "Provide user_ids, role, or emails", + Error: "Provide user_ids, role, team_member_ids, team_role, or emails", }) } @@ -1893,11 +1921,11 @@ func (h *Handler) SendBulkEmail(c *fiber.Ctx) error { creatorID, _ := c.Locals("user_id").(int64) - var targetRaw json.RawMessage - if len(directEmails) > 0 { - raw := domain.ScheduledNotificationTargetRaw{Emails: directEmails} - targetRaw, _ = json.Marshal(raw) - } + targetRaw, _ := json.Marshal(domain.ScheduledNotificationTargetRaw{ + Emails: directEmails, + TeamMemberIDs: teamMemberIDs, + TeamRole: teamRole, + }) sn := &domain.ScheduledNotification{ Channel: domain.DeliveryChannelEmail, @@ -1923,10 +1951,12 @@ func (h *Handler) SendBulkEmail(c *fiber.Ctx) error { scheduledID := created.ID scheduleMeta, _ := json.Marshal(map[string]interface{}{ - "channel": "email", - "target_users": len(userIDs), - "target_role": role, - "scheduled_at": scheduledAtRaw, + "channel": "email", + "target_users": len(userIDs), + "target_role": role, + "target_team_members": len(teamMemberIDs), + "target_team_role": teamRole, + "scheduled_at": scheduledAtRaw, }) h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, &scheduledID, fmt.Sprintf("Scheduled email notification ID: %d", scheduledID), scheduleMeta) @@ -1939,58 +1969,38 @@ func (h *Handler) SendBulkEmail(c *fiber.Ctx) error { } // Immediate send: collect emails from all sources - emailSet := make(map[string]struct{}) - for _, e := range directEmails { - emailSet[e] = struct{}{} - } - - if len(userIDs) == 0 && role != "" { - users, _, err := h.userSvc.GetAllUsers(context.Background(), domain.UserFilter{Role: role}) - if err != nil { - return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ - Message: "Failed to fetch users for role", - Error: err.Error(), - }) - } - for _, u := range users { - userIDs = append(userIDs, u.ID) - } - } - - for _, uid := range userIDs { - user, err := h.userSvc.GetUserByID(context.Background(), uid) - if err != nil { - h.mongoLoggerSvc.Warn("[NotificationHandler.SendBulkEmail] Failed to get user", - zap.Int64("userID", uid), - zap.Error(err), - ) - continue - } - if user.Email != "" { - emailSet[user.Email] = struct{}{} - } - } - - if len(emailSet) == 0 { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "No recipients found", - Error: "Provide user_ids, role, or emails", + recipients, resolvedUserIDs, resolvedTeamMemberIDs, err := h.notificationSvc.ResolveBulkEmailAddresses( + c.Context(), + userIDs, + role, + teamMemberIDs, + teamRole, + directEmails, + ) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to resolve email recipients", + Error: err.Error(), }) } - recipients := make([]string, 0, len(emailSet)) - for e := range emailSet { - recipients = append(recipients, e) + if len(recipients) == 0 { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "No recipients found", + Error: "Provide user_ids, role, team_member_ids, team_role, or emails", + }) } attachments := h.parseEmailAttachment(c) sent, failed := h.notificationSvc.SendBulkEmail(c.Context(), recipients, content, attachments) - // Record in DB for history (only for known users) - for _, uid := range userIDs { + for _, uid := range resolvedUserIDs { h.notificationSvc.RecordNotification(c.Context(), uid, domain.NOTIFICATION_TYPE_SYSTEM_ALERT, domain.DeliveryChannelEmail, domain.NotificationLevelInfo, content.Subject, content.Message) } + for _, mid := range resolvedTeamMemberIDs { + h.notificationSvc.RecordTeamMemberNotification(c.Context(), mid, domain.NOTIFICATION_TYPE_SYSTEM_ALERT, domain.DeliveryChannelEmail, domain.NotificationLevelInfo, content.Subject, content.Message) + } h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkEmail] Bulk email sent", zap.Int("totalRecipients", len(recipients)), @@ -2000,10 +2010,12 @@ func (h *Handler) SendBulkEmail(c *fiber.Ctx) error { ) bulkEmailMeta, _ := json.Marshal(map[string]interface{}{ - "channel": "email", - "total_recipients": len(recipients), - "sent": sent, - "failed": failed, + "channel": "email", + "total_recipients": len(recipients), + "user_recipients": len(resolvedUserIDs), + "team_member_recipients": len(resolvedTeamMemberIDs), + "sent": sent, + "failed": failed, }) h.recordActivity(c, domain.ActionNotificationBulkSent, domain.ResourceNotification, nil, fmt.Sprintf("Bulk email sent to %d recipients", len(recipients)), bulkEmailMeta) @@ -2012,9 +2024,11 @@ func (h *Handler) SendBulkEmail(c *fiber.Ctx) error { Success: true, StatusCode: fiber.StatusOK, Data: map[string]interface{}{ - "total_recipients": len(recipients), - "sent": sent, - "failed": failed, + "total_recipients": len(recipients), + "user_recipients": len(resolvedUserIDs), + "team_member_recipients": len(resolvedTeamMemberIDs), + "sent": sent, + "failed": failed, }, }) }