diff --git a/db/query/device.sql b/db/query/device.sql index adb515a6..dd5b2882 100644 --- a/db/query/device.sql +++ b/db/query/device.sql @@ -10,7 +10,8 @@ VALUES ( ON CONFLICT (user_id, device_token) DO UPDATE SET is_active = true, - last_seen = CURRENT_TIMESTAMP + last_seen = CURRENT_TIMESTAMP, + platform = EXCLUDED.platform RETURNING *; -- name: GetUserDevices :many @@ -36,7 +37,7 @@ WHERE user_id = $1; -- name: GetActiveDeviceTokens :many SELECT device_token FROM devices -WHERE user_id = $1 AND is_active = true AND platform IN ('android', 'ios'); +WHERE user_id = $1 AND is_active = true; -- name: DeactivateDeviceByToken :exec UPDATE devices diff --git a/docs/bulk-scheduled-notifications-integration.md b/docs/bulk-scheduled-notifications-integration.md index 1628d663..5fa1b627 100644 --- a/docs/bulk-scheduled-notifications-integration.md +++ b/docs/bulk-scheduled-notifications-integration.md @@ -5,12 +5,15 @@ This guide documents how admin clients integrate with the Yimaru backend to send | Channel | Value | Endpoint | |---------|-------|----------| | SMS | `sms` | `POST /api/v1/notifications/bulk-sms` | -| Email | `email` | `POST /api/v1/notifications/bulk-email` | +| Email (bulk) | `email` | `POST /api/v1/notifications/bulk-email` | +| Email (single) | `email` | `POST /api/v1/notifications/send-email` | | Push (FCM) | `push` | `POST /api/v1/notifications/bulk-push` | | In-app | `in_app` | `POST /api/v1/notifications/bulk-in-app` | Scheduled jobs are created by the same bulk endpoints when `scheduled_at` is provided. Management APIs list, inspect, and cancel pending jobs. +Bulk and single **email** sends support optional **email template** selection (`email_template_slug`). When a template is used, subject/body are rendered server-side from the template store (with code defaults as fallback). + --- ## Table of contents @@ -22,14 +25,16 @@ Scheduled jobs are created by the same bulk endpoints when `scheduled_at` is pro 5. [Scheduled notification object](#scheduled-notification-object) 6. [Bulk SMS](#bulk-sms) 7. [Bulk email](#bulk-email) -8. [Bulk push](#bulk-push) -9. [Bulk in-app](#bulk-in-app) -10. [Scheduled job management](#scheduled-job-management) -11. [In-app real-time delivery (WebSocket)](#in-app-real-time-delivery-websocket) -12. [Recipient targeting rules](#recipient-targeting-rules) -13. [Error handling](#error-handling) -14. [Operational notes & limitations](#operational-notes--limitations) -15. [Admin UI integration checklist](#admin-ui-integration-checklist) +8. [Single email](#single-email) +9. [Email templates for outbound mail](#email-templates-for-outbound-mail) +10. [Bulk push](#bulk-push) +11. [Bulk in-app](#bulk-in-app) +12. [Scheduled job management](#scheduled-job-management) +13. [In-app real-time delivery (WebSocket)](#in-app-real-time-delivery-websocket) +14. [Recipient targeting rules](#recipient-targeting-rules) +15. [Error handling](#error-handling) +16. [Operational notes & limitations](#operational-notes--limitations) +17. [Admin UI integration checklist](#admin-ui-integration-checklist) --- @@ -82,13 +87,16 @@ Content-Type: application/json |--------|----------------| | Bulk SMS | `notifications.bulk_sms` | | Bulk email | `notifications.bulk_email` | +| Single email | `notifications.send_email` | | Bulk push | `notifications.bulk_push` | | Bulk in-app | `notifications.bulk_in_app` | | List scheduled jobs | `notifications_scheduled.list` | | Get scheduled job | `notifications_scheduled.get` | | Cancel scheduled job | `notifications_scheduled.cancel` | +| List email templates (compose UI) | `email_templates.list` | +| Preview email template | `email_templates.preview` | -Team members with the **ADMIN** role bundle receive these permissions after RBAC seeding. Ensure migration `000083` has been applied for `in_app` scheduled channel support. +Team members with the **ADMIN** role bundle receive these permissions after RBAC seeding. Ensure migrations **`000083`** (in-app scheduled channel) and **`000087`** (email template fields on scheduled email jobs) have been applied. --- @@ -143,6 +151,7 @@ Team members with the **ADMIN** role bundle receive these permissions after RBAC ```json { "target_users": 150, + "devices_targeted": 200, "sent": 200, "failed": 5, "image": "https://api.example.com/files/notification_images/abc.jpg" @@ -151,6 +160,8 @@ Team members with the **ADMIN** role bundle receive these permissions after RBAC > Push `sent`/`failed` count **device tokens**, not users. One user may have multiple devices. +> If `devices_targeted` is **0** while `target_users` > 0, targeted user(s) have no active FCM tokens. They must register via `POST /api/v1/devices/register` from the learner app or web client while logged in. + --- ## Scheduled notification object @@ -164,6 +175,8 @@ Returned when scheduling (`201`) and from management GET endpoints. "title": "Optional subject / headline", "message": "Body text", "html": "Optional HTML (email only)", + "email_template_slug": "custom_message", + "email_template_variables": { "Subject": "...", "Message": "..." }, "scheduled_at": "2026-06-15T09:00:00.000Z", "status": "pending", "target_user_ids": [1, 2, 3], @@ -218,6 +231,15 @@ Used when recipients cannot be expressed only via `target_user_ids` / `target_ro | `emails` | Scheduled email with direct addresses | | `type`, `level` | Scheduled in-app metadata (defaults: `system_alert`, `info`) | +### Email-only fields (`channel: "email"`) + +| Field | Type | Description | +|-------|------|-------------| +| `email_template_slug` | string | Template slug used when the job was created (e.g. `custom_message`). Omitted for free-form emails. | +| `email_template_variables` | object | JSON variables passed at schedule time. Merged with `title` / `message` / `html` when the job runs. | + +When dispatching a scheduled email, the worker renders the template if `email_template_slug` is set; otherwise it sends `title` + `message` / `html` as-is. + --- ## Bulk SMS @@ -319,9 +341,11 @@ Permission: notifications.bulk_email | Field | Type | Required | Description | |-------|------|----------|-------------| -| `subject` | string | **Yes** | Email subject (stored as `title` when scheduled) | -| `message` | string | No** | Plain-text body | -| `html` | string | No** | HTML body | +| `email_template_slug` | string | No | Template slug (e.g. `custom_message`). When set, subject/body are rendered from the template store. | +| `template_variables` | string | No | JSON object string for template placeholders, e.g. `{"Subject":"Hello","Message":"..."}`. | +| `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]` | | `role` | string | No* | Platform role filter | | `emails` | string | No* | JSON array string, e.g. `["a@b.com"]` | @@ -330,9 +354,17 @@ Permission: notifications.bulk_email \* At least one of `user_ids`, `role`, or `emails` is required. -\** At least one of `message` or `html` is required. +### Content modes -### Example — immediate (cURL) +| Mode | Fields | Behavior | +|------|--------|----------| +| **Free-form** (legacy) | `subject` + (`message` and/or `html`) | Sent as provided; no template wrapper. | +| **`custom_message`** | `subject` + `message` (+ optional `template_variables`) | Renders the branded `custom_message` template; `subject`/`message` map to `Subject`/`Message` variables. | +| **Other template slugs** | `email_template_slug` + `template_variables` | Subject and HTML/text come from the template. Use admin preview APIs to discover required variables. | + +> **System templates** (`otp`, `invitation`, `password_reset`, `welcome`) are reserved for automated learner flows. Admins should use **`custom_message`** or free-form content for outbound campaigns. + +### Example — immediate free-form (cURL) ```bash curl -X POST "https://api.example.com/api/v1/notifications/bulk-email" \ @@ -343,11 +375,23 @@ curl -X POST "https://api.example.com/api/v1/notifications/bulk-email" \ -F "file=@banner.png" ``` -### Example — scheduled (cURL) +### Example — immediate with `custom_message` template ```bash curl -X POST "https://api.example.com/api/v1/notifications/bulk-email" \ -H "Authorization: Bearer " \ + -F "email_template_slug=custom_message" \ + -F "subject=Weekly digest" \ + -F "message=Here is your weekly summary." \ + -F "role=STUDENT" +``` + +### Example — scheduled with template + +```bash +curl -X POST "https://api.example.com/api/v1/notifications/bulk-email" \ + -H "Authorization: Bearer " \ + -F "email_template_slug=custom_message" \ -F "subject=Weekly digest" \ -F "message=Here is your weekly summary." \ -F "emails=[\"admin@example.com\",\"user@example.com\"]" \ @@ -386,6 +430,8 @@ curl -X POST "https://api.example.com/api/v1/notifications/bulk-email" \ "title": "Weekly digest", "message": "Here is your weekly summary.", "html": "", + "email_template_slug": "custom_message", + "email_template_variables": { "Subject": "Weekly digest", "Message": "Here is your weekly summary." }, "scheduled_at": "2026-06-15T09:00:00.000Z", "status": "pending", "target_raw": { "emails": ["admin@example.com", "user@example.com"] }, @@ -396,6 +442,116 @@ curl -X POST "https://api.example.com/api/v1/notifications/bulk-email" \ --- +## Single email + +Send one email immediately to a single address. Supports the same template fields as bulk email. + +### Endpoint + +``` +POST /api/v1/notifications/send-email +Content-Type: multipart/form-data +Permission: notifications.send_email +``` + +### Form fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `recipient` | string | **Yes** | Destination email address | +| `email_template_slug` | string | No | Same as bulk email | +| `template_variables` | string | No | JSON object string | +| `subject` | string | Cond. | Same rules as bulk email | +| `message` | string | Cond. | Same rules as bulk email | +| `html` | string | No | Optional HTML (free-form) | +| `file` | file | No | Optional attachment | + +### Example — free-form + +```bash +curl -X POST "https://api.example.com/api/v1/notifications/send-email" \ + -H "Authorization: Bearer " \ + -F "recipient=user@example.com" \ + -F "subject=Quick note" \ + -F "message=Thanks for reaching out." +``` + +### Example — `custom_message` template + +```bash +curl -X POST "https://api.example.com/api/v1/notifications/send-email" \ + -H "Authorization: Bearer " \ + -F "recipient=user@example.com" \ + -F "email_template_slug=custom_message" \ + -F "subject=Account update" \ + -F "message=Your request has been processed." +``` + +### Success response (`200`) + +```json +{ + "message": "Email sent successfully", + "success": true, + "status_code": 200 +} +``` + +--- + +## Email templates for outbound mail + +Admin clients can list and preview templates before composing outbound email. + +### List templates + +``` +GET /api/v1/admin/email-templates?status=ACTIVE&limit=20&offset=0 +Permission: email_templates.list +``` + +Optional query: `query` (search slug, name, or subject). + +### Get by slug + +``` +GET /api/v1/admin/email-templates/slug/:slug +Permission: email_templates.get +``` + +### Preview (no send) + +``` +POST /api/v1/admin/email-templates/slug/:slug/preview +Content-Type: application/json +Permission: email_templates.preview +``` + +```json +{ + "variables": { + "Subject": "Preview subject", + "Message": "Preview body text" + } +} +``` + +Response `data` includes rendered `subject`, `text`, and `html` for UI preview. + +### Built-in slugs + +| Slug | Admin outbound | Automated use | +|------|----------------|---------------| +| `custom_message` | **Yes** — branded wrapper for admin subject/body | — | +| `otp` | No | Login / verification OTP | +| `invitation` | No | Team invitations | +| `password_reset` | No | Learner password-reset link email | +| `welcome` | No | Learner welcome after email registration | + +Templates are stored in the database with code defaults as fallback. Admins can edit `custom_message` (and other templates) via `PUT /api/v1/admin/email-templates/:id`. + +--- + ## Bulk push ### Endpoint @@ -749,6 +905,12 @@ For immediate SMS/email, all sources are **unioned** (deduplicated). Scheduled j | `Invalid scheduled_at format` | Not RFC3339 | | `scheduled_at must be in the future` | Past timestamp | | `Invalid user_ids format` | Push/email: not a JSON array string | +| `subject is required when no email_template_slug is provided` | Free-form email missing subject | +| `message or html is required when no email_template_slug is provided` | Free-form email missing body | +| `template_variables must be valid JSON` | Malformed `template_variables` form field | +| `subject is required for custom_message template` | `custom_message` without subject | +| `message is required for custom_message template` | `custom_message` without message | +| `Recipient is required` | Single email: empty `recipient` | ### Common `401` / `403` @@ -787,7 +949,9 @@ For scheduled jobs, if **at least one** recipient succeeds, status becomes `sent | Email provider | Resend (messenger service) | | Push provider | Firebase Cloud Messaging | | History records | Immediate SMS/email/push call `RecordNotification` for known `user_ids`; scheduled SMS/email/push do **not** write per-user history rows. In-app always creates notification rows (immediate and scheduled). | -| Migration | `000083` required for `in_app` scheduled channel | +| Migrations | `000083` — `in_app` scheduled channel; `000087` — `email_template_slug` / `email_template_variables` on scheduled email jobs | +| Learner welcome email | Sent automatically after **email** OTP registration verification (`welcome` template). Not sent for phone registration or team invites. | +| Password reset email | Learner email reset uses `password_reset` template with link (`LEARNER_APP_BASE_URL` / `PASSWORD_RESET_BASE_URL`). SMS reset still uses OTP text. | --- @@ -796,6 +960,9 @@ For scheduled jobs, if **at least one** recipient succeeds, status becomes `sent ### Compose screen (per channel) - [ ] Title/subject + message fields (channel-specific) +- [ ] **Email only:** optional template picker (`email_template_slug`); load options from `GET /admin/email-templates` +- [ ] **Email only:** when `custom_message` or another template is selected, show variable editor → serialize as `template_variables` JSON; preview via `POST /admin/email-templates/slug/:slug/preview` +- [ ] **Email only:** when no template selected, require subject + message/html (legacy free-form) - [ ] Recipient picker: user multi-select, role dropdown, and/or direct phones/emails - [ ] Toggle: **Send now** vs **Schedule** - [ ] Date/time picker → serialize as RFC3339 UTC (`scheduled_at`) @@ -805,7 +972,7 @@ For scheduled jobs, if **at least one** recipient succeeds, status becomes `sent ### After submit - [ ] Immediate: show `sent` / `failed` / `total_recipients` from `data` -- [ ] Scheduled: show returned `id`, `scheduled_at`, `status` — link to job detail view +- [ ] Scheduled: show returned `id`, `scheduled_at`, `status`, and email `email_template_slug` when present — link to job detail view ### Scheduled jobs list @@ -828,8 +995,11 @@ For scheduled jobs, if **at least one** recipient succeeds, status becomes `sent |--------|------|---------| | `POST` | `/api/v1/notifications/bulk-sms` | Bulk / schedule SMS | | `POST` | `/api/v1/notifications/bulk-email` | Bulk / schedule email | +| `POST` | `/api/v1/notifications/send-email` | Single immediate email | | `POST` | `/api/v1/notifications/bulk-push` | Bulk / schedule push | | `POST` | `/api/v1/notifications/bulk-in-app` | Bulk / schedule in-app | +| `GET` | `/api/v1/admin/email-templates` | List email templates (admin) | +| `POST` | `/api/v1/admin/email-templates/slug/:slug/preview` | Preview template HTML | | `GET` | `/api/v1/notifications/scheduled` | List scheduled jobs | | `GET` | `/api/v1/notifications/scheduled/:id` | Get scheduled job | | `POST` | `/api/v1/notifications/scheduled/:id/cancel` | Cancel scheduled job | diff --git a/gen/db/device.sql.go b/gen/db/device.sql.go index fc3a2915..c73d554f 100644 --- a/gen/db/device.sql.go +++ b/gen/db/device.sql.go @@ -23,7 +23,8 @@ VALUES ( ON CONFLICT (user_id, device_token) DO UPDATE SET is_active = true, - last_seen = CURRENT_TIMESTAMP + last_seen = CURRENT_TIMESTAMP, + platform = EXCLUDED.platform RETURNING id, user_id, device_token, platform, is_active, last_seen, created_at ` @@ -89,7 +90,7 @@ func (q *Queries) DeactivateUserDevices(ctx context.Context, userID int64) error const GetActiveDeviceTokens = `-- name: GetActiveDeviceTokens :many SELECT device_token FROM devices -WHERE user_id = $1 AND is_active = true AND platform IN ('android', 'ios') +WHERE user_id = $1 AND is_active = true ` func (q *Queries) GetActiveDeviceTokens(ctx context.Context, userID int64) ([]string, error) { diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go index 746f0e04..a74e30bc 100644 --- a/internal/services/notification/service.go +++ b/internal/services/notification/service.go @@ -680,9 +680,9 @@ func (s *Service) MessengerSvc() *messenger.Service { return s.messengerSvc } -func (s *Service) SendBulkPushNotification(ctx context.Context, userIDs []int64, notification *domain.Notification) (sent int, failed int, err error) { +func (s *Service) SendBulkPushNotification(ctx context.Context, userIDs []int64, notification *domain.Notification) (sent int, failed int, devicesTargeted int, err error) { if err := s.ensureFCMClient(); err != nil { - return 0, 0, err + return 0, 0, 0, err } // Collect all device tokens for the given users @@ -703,11 +703,12 @@ func (s *Service) SendBulkPushNotification(ctx context.Context, userIDs []int64, allTokens = append(allTokens, tokens...) } - if len(allTokens) == 0 { + devicesTargeted = len(allTokens) + if devicesTargeted == 0 { s.mongoLogger.Info("[NotificationSvc.SendBulkPushNotification] No device tokens found for any user", zap.Int("userCount", len(userIDs)), ) - return 0, 0, nil + return 0, 0, 0, nil } fcmNotification := &messaging.Notification{ @@ -765,7 +766,7 @@ func (s *Service) SendBulkPushNotification(ctx context.Context, userIDs []int64, zap.Int("failed", failed), ) - return sent, failed, nil + return sent, failed, devicesTargeted, nil } // SendBulkSMS sends an SMS to multiple phone numbers using AfroMessage. @@ -1326,10 +1327,13 @@ func (s *Service) dispatchScheduledPush(ctx context.Context, sn *domain.Schedule }, } - sent, failed, err := s.SendBulkPushNotification(ctx, userIDs, notification) + sent, failed, devicesTargeted, err := s.SendBulkPushNotification(ctx, userIDs, notification) if err != nil { return err } + if devicesTargeted == 0 { + return fmt.Errorf("no registered device tokens for %d target user(s)", len(userIDs)) + } if sent == 0 && failed > 0 { return fmt.Errorf("all %d push deliveries failed", failed) } diff --git a/internal/web_server/handlers/notification_handler.go b/internal/web_server/handlers/notification_handler.go index 8605a87a..08c5ad55 100644 --- a/internal/web_server/handlers/notification_handler.go +++ b/internal/web_server/handlers/notification_handler.go @@ -1137,7 +1137,7 @@ func (h *Handler) SendBulkPushNotification(c *fiber.Ctx) error { }, } - sent, failed, err := h.notificationSvc.SendBulkPushNotification(c.Context(), userIDs, notification) + sent, failed, devicesTargeted, err := h.notificationSvc.SendBulkPushNotification(c.Context(), userIDs, notification) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to send bulk push notification", @@ -1152,20 +1152,27 @@ func (h *Handler) SendBulkPushNotification(c *fiber.Ctx) error { h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkPushNotification] Bulk push sent", zap.Int("targetUsers", len(userIDs)), + zap.Int("devicesTargeted", devicesTargeted), zap.Int("sent", sent), zap.Int("failed", failed), zap.Time("timestamp", time.Now()), ) + responseMessage := "Bulk push notification sent" + if devicesTargeted == 0 { + responseMessage = "No registered device tokens for target users" + } + return c.Status(fiber.StatusOK).JSON(domain.Response{ - Message: "Bulk push notification sent", + Message: responseMessage, Success: true, StatusCode: fiber.StatusOK, Data: map[string]interface{}{ - "target_users": len(userIDs), - "sent": sent, - "failed": failed, - "image": imageURL, + "target_users": len(userIDs), + "devices_targeted": devicesTargeted, + "sent": sent, + "failed": failed, + "image": imageURL, }, }) }