diff --git a/cmd/main.go b/cmd/main.go index 0cdb8fc6..2f71341a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -144,6 +144,7 @@ func main() { cfg, messengerSvc, userSvc, + emailTemplateSvc, ) recommendationRepo := repository.NewRecommendationRepository(store) diff --git a/db/migrations/000087_scheduled_email_templates.down.sql b/db/migrations/000087_scheduled_email_templates.down.sql new file mode 100644 index 00000000..3dfc5ae2 --- /dev/null +++ b/db/migrations/000087_scheduled_email_templates.down.sql @@ -0,0 +1,3 @@ +ALTER TABLE scheduled_notifications + DROP COLUMN IF EXISTS email_template_variables, + DROP COLUMN IF EXISTS email_template_slug; diff --git a/db/migrations/000087_scheduled_email_templates.up.sql b/db/migrations/000087_scheduled_email_templates.up.sql new file mode 100644 index 00000000..63dd045d --- /dev/null +++ b/db/migrations/000087_scheduled_email_templates.up.sql @@ -0,0 +1,3 @@ +ALTER TABLE scheduled_notifications + ADD COLUMN IF NOT EXISTS email_template_slug VARCHAR(100), + ADD COLUMN IF NOT EXISTS email_template_variables JSONB; diff --git a/db/query/scheduled_notification.sql b/db/query/scheduled_notification.sql index cb73189a..1abd39c1 100644 --- a/db/query/scheduled_notification.sql +++ b/db/query/scheduled_notification.sql @@ -1,14 +1,16 @@ -- name: CreateScheduledNotification :one INSERT INTO scheduled_notifications ( channel, title, message, html, + email_template_slug, email_template_variables, scheduled_at, target_user_ids, target_role, target_raw, created_by ) VALUES ( $1, $2, $3, $4, - $5, - $6, $7, $8, - $9 + $5, $6, + $7, + $8, $9, $10, + $11 ) RETURNING *; diff --git a/docs/file-upload-admin-panel-integration.md b/docs/file-upload-admin-panel-integration.md new file mode 100644 index 00000000..b5c1a917 --- /dev/null +++ b/docs/file-upload-admin-panel-integration.md @@ -0,0 +1,1224 @@ +# File Upload — Admin Panel Integration Guide + +This guide documents how the Yimaru admin panel should upload **images, audio, PDFs, and videos** using **direct-to-storage uploads** with accurate client-side progress tracking. + +**Use this guide instead of `POST /api/v1/files/upload`.** That legacy endpoint accepts `multipart/form-data` and streams the entire file through the API server. The browser cannot report true upload progress for that path in a meaningful way, and large files (especially video) add load and timeout risk on the backend. + +| Media type | Recommended flow | Progress tracked on | +|------------|------------------|---------------------| +| `image` | MinIO presigned PUT | Browser → MinIO | +| `audio` | MinIO presigned PUT | Browser → MinIO | +| `pdf` | MinIO presigned PUT | Browser → MinIO | +| `video` | Vimeo TUS resumable upload | Browser → Vimeo | + +--- + +## Table of contents + +1. [Feature overview](#feature-overview) +2. [Why not `/files/upload`](#why-not-filesupload) +3. [Architecture](#architecture) +4. [Authentication & permissions](#authentication--permissions) +5. [Media routing decision tree](#media-routing-decision-tree) +6. [Progress model (admin UI)](#progress-model-admin-ui) +7. [Response envelopes](#response-envelopes) +8. [MinIO presigned upload (image / audio / pdf)](#minio-presigned-upload-image--audio--pdf) +9. [Vimeo TUS upload (video)](#vimeo-tus-upload-video) +10. [Storing upload results in content](#storing-upload-results-in-content) +11. [Download & URL refresh (MinIO)](#download--url-refresh-minio) +12. [Recommended admin UI patterns](#recommended-admin-ui-patterns) +13. [TypeScript types & upload service](#typescript-types--upload-service) +14. [React upload hook example](#react-upload-hook-example) +15. [Error handling](#error-handling) +16. [Infrastructure & CORS](#infrastructure--cors) +17. [Integration checklist](#integration-checklist) +18. [Limitations & legacy endpoints](#limitations--legacy-endpoints) +19. [Quick reference](#quick-reference) + +--- + +## Feature overview + +The admin panel uploads files when creating or editing content: lesson media, persona avatars, PDF handouts, audio prompts, video lessons, etc. + +The backend exposes two **progress-friendly** upload paths: + +1. **MinIO presigned upload** — three-step flow for static files stored in the Yimaru MinIO bucket. +2. **Vimeo TUS upload** — two-step flow (create slot + client TUS upload) for video hosted on Vimeo. + +Both flows upload **directly from the browser to the storage provider**. The Yimaru API only: + +- Authenticates the admin user +- Issues upload credentials (presigned URL or TUS upload link) +- Verifies completion (MinIO `complete-upload`) or exposes post-upload metadata (Vimeo video info / transcode status) + +### Supported formats & size limits + +| `media_type` | Max size | Allowed content types | Storage | +|--------------|----------|------------------------|---------| +| `image` | 10 MB | `image/jpeg`, `image/png`, `image/webp` | MinIO | +| `audio` | 50 MB | mp3, wav, ogg, m4a, aac, webm, flac (see validation below) | MinIO | +| `pdf` | 25 MB | `application/pdf` | MinIO | +| `video` | Vimeo account quota | Any `video/*` detected by browser / file | Vimeo | + +Object keys for MinIO uploads follow `{media_type}/{uuid}{extension}`, e.g. `image/3fa85f64-5717-4562-b3fc-2c963f66afa6.jpg`. + +Presigned PUT URLs expire in **15 minutes** (`expires_in: 900`). + +--- + +## Why not `/files/upload` + +`POST /api/v1/files/upload` still exists for backward compatibility but should **not** be used in new admin panel code. + +| Topic | `/files/upload` (legacy) | Presigned MinIO + Vimeo TUS (recommended) | +|-------|--------------------------|---------------------------------------------| +| Request shape | `multipart/form-data` with file body | JSON to API; binary goes to MinIO/Vimeo | +| Upload path | Browser → API → MinIO/Vimeo | Browser → MinIO/Vimeo directly | +| Progress | Not reliable (single HTTP request to API) | `xhr.upload.onprogress` (MinIO) or TUS `onProgress` (Vimeo) | +| Large video | Buffered through API (500 MB cap in handler) | Resumable TUS to Vimeo | +| Timeouts | API server limits | Storage provider handles long uploads | + +If the admin panel sends a video to `POST /files/presign-upload`, the API returns **400** with guidance to use Vimeo TUS instead. + +--- + +## Architecture + +```mermaid +flowchart TB + subgraph AdminPanel["Admin panel"] + Picker[File picker] + Progress[Progress bar] + Form[Content form save] + end + + subgraph API["Yimaru API (authenticated)"] + Presign["POST /files/presign-upload"] + Complete["POST /files/complete-upload"] + TusCreate["POST /vimeo/uploads/tus"] + Transcode["GET /vimeo/videos/:id/status"] + Refresh["POST /files/refresh-url"] + end + + subgraph Storage["External storage"] + MinIO[(MinIO bucket)] + Vimeo[(Vimeo TUS endpoint)] + end + + Picker -->|"image/audio/pdf"| Presign + Presign -->|"upload_url + object_key"| Picker + Picker -->|"HTTP PUT + onprogress"| MinIO + Picker --> Complete + Complete --> Form + + Picker -->|"video"| TusCreate + TusCreate -->|"upload_link + vimeo_id"| Picker + Picker -->|"TUS PATCH + onProgress"| Vimeo + Picker --> Transcode + Transcode --> Form + + Form --> Refresh +``` + +**Commit reference:** MinIO presigned endpoints were added in commit `b57b306` on branch `production`. + +--- + +## Authentication & permissions + +### Obtaining a token + +Use a **team member** token for the admin panel (recommended): + +```http +POST /api/v1/team/login +Content-Type: application/json +``` + +Use the `access_token` from the response on all upload-related API calls: + +```http +Authorization: Bearer +Content-Type: application/json +``` + +Platform admin login (`POST /api/v1/auth/admin-login`) also works where applicable. + +### Permission requirements + +| Endpoint group | Auth | RBAC permission | +|----------------|------|-----------------| +| `POST /files/presign-upload` | Required | None (any authenticated user) | +| `POST /files/complete-upload` | Required | None | +| `GET /files/url` | Required | None | +| `POST /files/refresh-url` | Required | None | +| `POST /vimeo/uploads/tus` | Required | **`vimeo.uploads.tus`** | +| `GET /vimeo/videos/:video_id/status` | Required | **`vimeo.videos.status`** | +| `GET /vimeo/videos/:video_id` | Required | **`vimeo.videos.get`** | +| `GET /vimeo/videos/:video_id/embed` | Required | **`vimeo.videos.embed`** | + +Default roles **`ADMIN`**, **`SUPER_ADMIN`**, and **`INSTRUCTOR`** receive all `vimeo.*` permissions after RBAC seeding. Custom roles must be assigned `vimeo.uploads.tus` (and related keys) explicitly. + +### Troubleshooting 403 on video upload + +If `POST /vimeo/uploads/tus` returns **403 Forbidden**: + +1. Confirm the token is from a team/admin account, not a learner token. +2. In RBAC admin UI, verify the role includes **`vimeo.uploads.tus`**. +3. Re-run RBAC sync / restart API if permissions were recently added. +4. `ADMIN` / `SUPER_ADMIN` bypass permission checks in middleware. + +MinIO file routes only require authentication — a 403 there usually means an invalid or expired token. + +--- + +## Media routing decision tree + +``` +User selects file + │ + ├─ MIME starts with video/ OR extension is common video (.mp4, .mov, .webm, …) + │ └─► Vimeo TUS flow (POST /vimeo/uploads/tus → TUS upload → poll transcode) + │ + ├─ MIME image/jpeg|png|webp + │ └─► MinIO presign (media_type: "image") + │ + ├─ MIME audio/* or known audio extension + │ └─► MinIO presign (media_type: "audio") + │ + ├─ MIME application/pdf OR .pdf extension + │ └─► MinIO presign (media_type: "pdf") + │ + └─ else + └─► Show validation error before calling API +``` + +Always pass the **actual file size** and **content type** to the presign/TUS create step. The backend validates both before issuing upload credentials. + +--- + +## Progress model (admin UI) + +Split progress into named phases so users see meaningful feedback: + +### MinIO (image / audio / pdf) + +| Phase | Weight | Source | +|-------|--------|--------| +| `presigning` | 0–5% | Waiting for `POST /files/presign-upload` | +| `uploading` | 5–92% | `xhr.upload.onprogress` on PUT to `upload_url` | +| `completing` | 92–100% | `POST /files/complete-upload` | + +Formula during upload phase: + +```text +overall = 5 + (loaded / total) * 87 +``` + +### Vimeo (video) + +| Phase | Weight | Source | +|-------|--------|--------| +| `creating` | 0–5% | Waiting for `POST /vimeo/uploads/tus` | +| `uploading` | 5–80% | TUS client `onProgress(bytesUploaded, bytesTotal)` | +| `processing` | 80–100% | Poll `GET /vimeo/videos/:video_id/status` until transcode complete | + +During transcode polling, map Vimeo status to UI: + +| `status` (transcode) | UI label | +|----------------------|----------| +| `in_progress` | "Processing video…" (animate 80–95%) | +| `complete` | Done (100%) | +| `error` | Failed — show retry | + +Poll every **3–5 seconds** after TUS upload succeeds. Stop after ~30 minutes or show a "still processing" message with manual refresh. + +--- + +## Response envelopes + +Successful API responses use the standard envelope: + +```json +{ + "message": "Human-readable message", + "data": { }, + "success": true, + "status_code": 200, + "metadata": null +} +``` + +Errors: + +```json +{ + "message": "Short error title", + "error": "Detailed reason" +} +``` + +--- + +## MinIO presigned upload (image / audio / pdf) + +Three steps: **presign → PUT → complete**. + +### Step 1 — Create presigned upload slot + +```http +POST /api/v1/files/presign-upload +Authorization: Bearer +Content-Type: application/json +``` + +**Request body:** + +```json +{ + "media_type": "image", + "filename": "lesson-cover.png", + "content_type": "image/png", + "file_size": 245760 +} +``` + +| Field | Required | Description | +|-------|----------|-------------| +| `media_type` | Yes | `image`, `audio`, or `pdf` (not `video`) | +| `filename` | Yes | Original filename (used for extension) | +| `content_type` | Yes | MIME type; must pass backend validation | +| `file_size` | Yes | File size in bytes; must be > 0 and within limit | + +**Success — `201 Created`:** + +```json +{ + "message": "Presigned upload URL created successfully", + "data": { + "object_key": "image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png", + "upload_url": "https://minio.example.com/bucket/image/3fa85f64-....png?X-Amz-...", + "reference": "minio://image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png", + "content_type": "image/png", + "media_type": "image", + "provider": "MINIO", + "expires_in": 900 + }, + "success": true, + "status_code": 201 +} +``` + +**Important:** Save `object_key`, `upload_url`, and `content_type` for the next steps. The presigned URL is bound to the exact `Content-Type` sent here. + +### Step 2 — Upload file directly to MinIO (progress tracked here) + +Send the raw file bytes with **HTTP PUT** to `upload_url`. + +**Required headers on PUT:** + +```http +Content-Type: image/png +``` + +Use the **same** `content_type` as step 1. Do **not** send `Authorization` — credentials are in the presigned query string. + +**Do not** use `multipart/form-data` on this request. + +**Success:** MinIO returns `200 OK` (empty or minimal body). + +**Client example with progress (XHR):** + +```typescript +function putFileWithProgress( + uploadUrl: string, + file: File, + contentType: string, + onProgress: (loaded: number, total: number) => void +): Promise { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open("PUT", uploadUrl); + xhr.setRequestHeader("Content-Type", contentType); + + xhr.upload.onprogress = (e) => { + if (e.lengthComputable) onProgress(e.loaded, e.total); + }; + + xhr.onload = () => { + if (xhr.status >= 200 && xhr.status < 300) resolve(); + else reject(new Error(`MinIO PUT failed: ${xhr.status} ${xhr.responseText}`)); + }; + + xhr.onerror = () => reject(new Error("Network error during MinIO upload")); + xhr.send(file); + }); +} +``` + +`fetch()` does not expose upload progress — use `XMLHttpRequest` or a library that wraps it. + +### Step 3 — Complete and verify upload + +Call the API after PUT succeeds so the backend confirms the object exists in MinIO and returns the canonical file metadata (same shape as legacy `/files/upload` for MinIO files). + +```http +POST /api/v1/files/complete-upload +Authorization: Bearer +Content-Type: application/json +``` + +**Request body:** + +```json +{ + "object_key": "image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png", + "media_type": "image", + "file_size": 245760 +} +``` + +| Field | Required | Description | +|-------|----------|-------------| +| `object_key` | Yes | From presign response | +| `media_type` | Yes | Must match presign `media_type` and object key prefix | +| `file_size` | No | If provided, must match actual uploaded size | + +**Success — `200 OK`:** + +```json +{ + "message": "File uploaded successfully", + "data": { + "object_key": "image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png", + "url": "https://minio.example.com/bucket/image/....png?X-Amz-...", + "content_type": "image/png", + "media_type": "image", + "provider": "MINIO" + }, + "success": true, + "status_code": 200 +} +``` + +**Store `reference` as `minio://{object_key}`** in database fields (persona `profile_picture`, lesson image URLs, etc.). The `url` field is a **short-lived presigned GET** (~1 hour) for immediate preview only. + +### MinIO error cases + +| HTTP | When | Admin UI action | +|------|------|-----------------| +| 400 | Invalid media type, size, or content type | Show validation message before retry | +| 400 | `media_type: video` | Route user to Vimeo flow | +| 404 | `complete-upload` before PUT finished | Retry complete after PUT succeeds | +| 400 | Size mismatch on complete | Re-upload or omit `file_size` | +| 503 | MinIO not configured | Disable upload; show ops message | +| PUT fails / CORS | Browser blocked cross-origin PUT | Fix MinIO CORS (see [Infrastructure](#infrastructure--cors)) | + +If presign expires (15 min) before PUT completes, call `presign-upload` again with a **new** slot (new `object_key`). + +--- + +## Vimeo TUS upload (video) + +Two main steps from the admin panel: **create TUS slot → upload via TUS client**. Optionally poll transcode status before enabling "Save" on the form. + +### Step 1 — Create TUS upload slot + +```http +POST /api/v1/vimeo/uploads/tus +Authorization: Bearer +Content-Type: application/json +``` + +**Request body:** + +```json +{ + "name": "Unit 3 — Listening Introduction", + "description": "Lesson intro video for admin-created content", + "file_size": 52428800 +} +``` + +| Field | Required | Validation | +|-------|----------|------------| +| `name` | Yes | Video title shown in Vimeo | +| `description` | No | Optional description | +| `file_size` | Yes | Must be > 0 (bytes) | + +**Success — `201 Created`:** + +```json +{ + "message": "Vimeo TUS upload created successfully", + "data": { + "vimeo_id": "123456789", + "uri": "/videos/123456789", + "link": "https://vimeo.com/123456789", + "upload_link": "https://global.upload.vimeo.com/tus/uploads/...", + "status": "in_progress" + }, + "success": true, + "status_code": 201 +} +``` + +Save **`vimeo_id`** and **`upload_link`** immediately. The upload link is single-use for this upload session. + +### Step 2 — Upload file with TUS (progress tracked here) + +Upload **directly to `upload_link`** using a TUS 1.0.0 client. Do not send the video bytes to the Yimaru API. + +**Recommended library:** [`tus-js-client`](https://github.com/tus/tus-js-client) (browser). + +**Install:** + +```bash +npm install tus-js-client +``` + +**Example:** + +```typescript +import * as tus from "tus-js-client"; + +export function uploadVideoToVimeo( + file: File, + uploadLink: string, + onProgress: (loaded: number, total: number) => void +): Promise { + return new Promise((resolve, reject) => { + const upload = new tus.Upload(file, { + uploadUrl: uploadLink, + retryDelays: [0, 3000, 5000, 10000, 20000], + chunkSize: 5 * 1024 * 1024, + metadata: { + filename: file.name, + filetype: file.type || "video/mp4", + }, + onError: (error) => reject(error), + onProgress: (bytesUploaded, bytesTotal) => onProgress(bytesUploaded, bytesTotal), + onSuccess: () => resolve(), + }); + + upload.start(); + }); +} +``` + +The backend server-side TUS implementation uses: + +```http +PATCH +Tus-Resumable: 1.0.0 +Upload-Offset: 0 +Content-Type: application/offset+octet-stream +``` + +The TUS client handles offsets, retries, and resumption automatically — prefer the library over hand-rolled PATCH. + +### Step 3 — Poll transcode status (optional but recommended) + +After TUS `onSuccess`, the file is on Vimeo but may still be transcoding. + +```http +GET /api/v1/vimeo/videos/123456789/status +Authorization: Bearer +``` + +**Success — `200 OK`:** + +```json +{ + "message": "Transcode status retrieved successfully", + "data": { + "video_id": "123456789", + "status": "in_progress" + }, + "success": true, + "status_code": 200 +} +``` + +Poll until `status` is `complete`. On `error`, allow retry (create a new TUS slot and re-upload). + +**Embed URL for storage:** + +```text +https://player.vimeo.com/video/{vimeo_id} +``` + +**Optional — fetch embed HTML for preview:** + +```http +GET /api/v1/vimeo/videos/123456789/embed?width=640&height=360 +Authorization: Bearer +``` + +Requires permission `vimeo.videos.embed`. + +### Vimeo pull upload (alternative, usually not for admin file picker) + +If the video is already hosted at a **public HTTPS URL**, staff with `vimeo.uploads.pull` can use: + +```http +POST /api/v1/vimeo/uploads/pull +``` + +Body: `{ "name", "description", "source_url", "file_size" }`. Vimeo fetches the file server-side — **no browser progress** for the fetch phase. Prefer TUS for local file picker uploads. + +--- + +## Storing upload results in content + +After a successful upload, persist stable identifiers — not expiring presigned GET URLs. + +### MinIO files + +| Field to store | Example | Notes | +|----------------|---------|-------| +| **Preferred** | `minio://image/uuid.png` | Matches API `reference`; refresh URLs on display | +| Alternative | `image/uuid.png` | Raw `object_key`; pass to `GET /files/url?key=` or `refresh-url` | + +Example persona avatar (from personas guide): set `profile_picture` to `minio://image/...` or a refreshed presigned URL when saving the form. + +### Vimeo videos + +| Field to store | Example | +|----------------|---------| +| Video ID | `123456789` | +| Player embed URL | `https://player.vimeo.com/video/123456789` | +| Canonical link | `https://vimeo.com/123456789` | + +Many content models accept a video URL string — use **`embed_url`** / player URL for in-app players. + +### Unified upload result type (admin state) + +```typescript +type UploadResult = + | { + provider: "MINIO"; + mediaType: "image" | "audio" | "pdf"; + objectKey: string; + reference: string; // minio://... + contentType: string; + previewUrl: string; // short-lived; refresh before display if stale + } + | { + provider: "VIMEO"; + mediaType: "video"; + vimeoId: string; + link: string; + embedUrl: string; + transcodeStatus: string; + }; +``` + +--- + +## Download & URL refresh (MinIO) + +Presigned GET URLs expire (~1 hour). For admin previews and learner delivery, refresh when needed. + +### By object key + +```http +GET /api/v1/files/url?key=image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png +Authorization: Bearer +``` + +**Response `data`:** + +```json +{ "url": "https://minio.example.com/..." } +``` + +### By reference (supports `minio://`, object key, or stale URL) + +```http +POST /api/v1/files/refresh-url +Authorization: Bearer +Content-Type: application/json +``` + +```json +{ + "reference": "minio://image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png" +} +``` + +**Response `data`:** + +```json +{ + "object_key": "image/3fa85f64-5717-4562-b3fc-2c963f66afa6.png", + "url": "https://minio.example.com/...", + "expires_in": 3600 +} +``` + +Use this in image components when a preview fails to load (expired URL). + +--- + +## Recommended admin UI patterns + +### Shared upload widget + +Build one **`MediaUploadField`** component used across forms (personas, lessons, modules, FAQs with attachments, etc.): + +| UI element | Behavior | +|------------|----------| +| Drop zone / file input | Accept filter by expected media types | +| Progress bar | Phase label + percentage (see [Progress model](#progress-model-admin-ui)) | +| Cancel | Abort XHR / `tus.Upload.abort()` | +| Preview | MinIO: `` / `