From 10babe06f66087250275d4d26865d0b8ea53d9cf Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Sun, 14 Jun 2026 02:15:00 -0700 Subject: [PATCH] feat: add in-app notification delete APIs and fix FAQ RBAC access - Add DELETE /notifications/:id and POST /notifications/delete-in-app for owned in-app rows - Seed FAQ permissions for ADMIN/INSTRUCTOR, migration 000084, and improve RBAC sync - Document FAQ admin panel integration Co-authored-by: Cursor --- .../000084_faq_rbac_permissions.down.sql | 9 + .../000084_faq_rbac_permissions.up.sql | 20 + db/query/notification.sql | 12 + docs/faq-admin-panel-integration.md | 782 ++++++++++++++++++ gen/db/notification.sql.go | 40 + internal/ports/notification.go | 2 + internal/repository/notification.go | 21 + internal/services/notification/service.go | 31 + .../notification/service_delete_test.go | 66 ++ internal/services/rbac/seeds.go | 3 + internal/services/rbac/service.go | 2 + .../handlers/notification_handler.go | 120 +++ internal/web_server/handlers/rbac_handler.go | 12 + internal/web_server/handlers/team_handler.go | 2 +- internal/web_server/routes.go | 2 + 15 files changed, 1123 insertions(+), 1 deletion(-) create mode 100644 db/migrations/000084_faq_rbac_permissions.down.sql create mode 100644 db/migrations/000084_faq_rbac_permissions.up.sql create mode 100644 docs/faq-admin-panel-integration.md create mode 100644 internal/services/notification/service_delete_test.go diff --git a/db/migrations/000084_faq_rbac_permissions.down.sql b/db/migrations/000084_faq_rbac_permissions.down.sql new file mode 100644 index 00000000..d0b11389 --- /dev/null +++ b/db/migrations/000084_faq_rbac_permissions.down.sql @@ -0,0 +1,9 @@ +DELETE FROM role_permissions +WHERE permission_id IN ( + SELECT id FROM permissions WHERE key IN ( + 'faqs.create', 'faqs.list', 'faqs.get', 'faqs.update', 'faqs.delete' + ) +); + +DELETE FROM permissions +WHERE key IN ('faqs.create', 'faqs.list', 'faqs.get', 'faqs.update', 'faqs.delete'); diff --git a/db/migrations/000084_faq_rbac_permissions.up.sql b/db/migrations/000084_faq_rbac_permissions.up.sql new file mode 100644 index 00000000..77ea4ceb --- /dev/null +++ b/db/migrations/000084_faq_rbac_permissions.up.sql @@ -0,0 +1,20 @@ +-- Ensure FAQ admin permissions exist and are assigned to staff roles that manage content. + +INSERT INTO permissions (key, name, description, group_name) VALUES + ('faqs.create', 'Create FAQ', 'Create a FAQ item', 'FAQs'), + ('faqs.list', 'List FAQs (Admin)', 'List FAQs for admin management', 'FAQs'), + ('faqs.get', 'Get FAQ (Admin)', 'Get FAQ by ID for admin management', 'FAQs'), + ('faqs.update', 'Update FAQ', 'Update a FAQ item', 'FAQs'), + ('faqs.delete', 'Delete FAQ', 'Delete a FAQ item', 'FAQs') +ON CONFLICT (key) DO UPDATE SET + name = EXCLUDED.name, + description = EXCLUDED.description, + group_name = EXCLUDED.group_name; + +INSERT INTO role_permissions (role_id, permission_id) +SELECT r.id, p.id +FROM roles r +CROSS JOIN permissions p +WHERE r.name IN ('ADMIN', 'INSTRUCTOR') + AND p.key IN ('faqs.create', 'faqs.list', 'faqs.get', 'faqs.update', 'faqs.delete') +ON CONFLICT DO NOTHING; diff --git a/db/query/notification.sql b/db/query/notification.sql index a7dd4701..c4f70394 100644 --- a/db/query/notification.sql +++ b/db/query/notification.sql @@ -87,6 +87,18 @@ WHERE user_id = $1 DELETE FROM notifications WHERE user_id = $1; +-- name: DeleteUserInAppNotification :execrows +DELETE FROM notifications +WHERE id = $1 + AND user_id = $2 + AND channel = 'in_app'; + +-- name: DeleteUserInAppNotificationsByIDs :execrows +DELETE FROM notifications +WHERE user_id = $1 + AND channel = 'in_app' + AND id = ANY($2::BIGINT[]); + -- name: GetFilteredNotifications :many SELECT * FROM notifications diff --git a/docs/faq-admin-panel-integration.md b/docs/faq-admin-panel-integration.md new file mode 100644 index 00000000..9affcc29 --- /dev/null +++ b/docs/faq-admin-panel-integration.md @@ -0,0 +1,782 @@ +# FAQ Admin Panel — Integration Guide + +This guide documents how to integrate the **FAQ management** feature into the Yimaru admin panel. It covers authentication, RBAC permissions, admin CRUD APIs, response shapes, validation, UI recommendations, and how admin content relates to the public help center. + +--- + +## Table of contents + +1. [Feature overview](#feature-overview) +2. [Architecture](#architecture) +3. [Authentication & permissions](#authentication--permissions) +4. [Data model](#data-model) +5. [Response envelopes](#response-envelopes) +6. [Admin API reference](#admin-api-reference) +7. [Public API reference (preview only)](#public-api-reference-preview-only) +8. [Publish workflow (ACTIVE / INACTIVE)](#publish-workflow-active--inactive) +9. [Categories & display order](#categories--display-order) +10. [Recommended admin UI screens](#recommended-admin-ui-screens) +11. [TypeScript types & API client](#typescript-types--api-client) +12. [Error handling](#error-handling) +13. [Integration checklist](#integration-checklist) +14. [Limitations & future work](#limitations--future-work) +15. [Quick reference](#quick-reference) + +--- + +## Feature overview + +The FAQ system is a simple **question / answer** help center: + +| Capability | Admin panel | Mobile / web app | +|------------|-------------|------------------| +| List FAQs | All statuses (`ACTIVE`, `INACTIVE`) | `ACTIVE` only | +| Create / edit / delete | Yes | No | +| Filter by category | Yes | Yes (public) | +| Sort order | `display_order` field | Same order | +| Rich HTML answers | No (plain text) | Plain text | + +**Admin panel uses only `/api/v1/admin/faqs*` routes** (authenticated + RBAC). + +Public routes (`/api/v1/faqs`) are for learners and can be used in admin **preview** mode without auth. + +--- + +## Architecture + +```mermaid +flowchart LR + subgraph AdminPanel["Admin panel"] + ListPage[List / filter] + FormPage[Create / edit form] + Preview[Preview public view] + end + + subgraph API["Yimaru API"] + AdminRoutes["/admin/faqs CRUD"] + PublicRoutes["/faqs read-only"] + end + + subgraph DB["PostgreSQL"] + FAQsTable["faqs table"] + end + + ListPage --> AdminRoutes + FormPage --> AdminRoutes + Preview --> PublicRoutes + AdminRoutes --> FAQsTable + PublicRoutes --> FAQsTable +``` + +- **Migration:** `000059_faqs` +- **Postman collection:** `postman/FAQ-Management.postman_collection.json` + +--- + +## Authentication & permissions + +All admin FAQ endpoints require: + +```http +Authorization: Bearer +Content-Type: application/json +``` + +### RBAC permission keys + +| Action | Permission | HTTP | +|--------|------------|------| +| List FAQs (admin) | `faqs.list` | `GET /admin/faqs` | +| Get one FAQ (admin) | `faqs.get` | `GET /admin/faqs/:id` | +| Create FAQ | `faqs.create` | `POST /admin/faqs` | +| Update FAQ | `faqs.update` | `PUT /admin/faqs/:id` | +| Delete FAQ | `faqs.delete` | `DELETE /admin/faqs/:id` | + +These permissions are included in the default **ADMIN** role bundle after RBAC seeding. + +### UI gating + +Hide or disable FAQ menu items / buttons when the logged-in team member lacks the corresponding permission. A `403` from the API means missing permission. + +--- + +## Data model + +### FAQ object (`data` in responses) + +```json +{ + "id": 1, + "question": "How do I reset my password?", + "answer": "Go to login and click 'Forgot Password'.", + "category": "Account", + "display_order": 1, + "status": "ACTIVE", + "created_at": "2026-04-30 08:45:15.961307 +0000 UTC", + "updated_at": "2026-04-30 09:10:00.123456 +0000 UTC" +} +``` + +| Field | Type | Description | +|-------|------|-------------| +| `id` | int64 | Primary key | +| `question` | string | FAQ question (required on create) | +| `answer` | string | FAQ answer, plain text (required on create) | +| `category` | string \| omitted | Optional grouping label (free text, max 100 chars in DB) | +| `display_order` | int32 | Sort order (ascending). Default `0` on create | +| `status` | string | `ACTIVE` (published) or `INACTIVE` (hidden from public) | +| `created_at` | string | Timestamp string from server | +| `updated_at` | string \| omitted | Set after first update | + +### Status values + +| Value | Meaning | Visible on public `/faqs`? | +|-------|---------|----------------------------| +| `ACTIVE` | Published | Yes | +| `INACTIVE` | Draft / hidden | No | + +List order (admin and public): **`display_order ASC`, then `id ASC`**. + +--- + +## Response envelopes + +### Success (`domain.Response`) + +```json +{ + "message": "FAQs retrieved successfully", + "data": { }, + "success": true, + "status_code": 200, + "metadata": null +} +``` + +Note: `success` and `status_code` in the JSON body may be `0` / `false` on some older responses; rely on **HTTP status code** as the source of truth. + +### Error (`domain.ErrorResponse`) + +```json +{ + "message": "Validation failed", + "error": "question is required" +} +``` + +### List payload (`data`) + +```json +{ + "faqs": [ /* FAQ object[] */ ], + "total_count": 42 +} +``` + +--- + +## Admin API reference + +Base path: `{API_BASE_URL}/api/v1` + +### 1. List FAQs (admin) + +``` +GET /admin/faqs +Permission: faqs.list +``` + +#### Query parameters + +| Param | Type | Default | Description | +|-------|------|---------|-------------| +| `status` | string | — | `ACTIVE` or `INACTIVE` (case-insensitive) | +| `category` | string | — | Exact category match | +| `limit` | int | 20 | Page size (max 200 enforced server-side) | +| `offset` | int | 0 | Pagination offset | + +Omit `status` to return **all** FAQs (active + inactive). + +#### Example + +```http +GET /api/v1/admin/faqs?status=ACTIVE&category=Account&limit=20&offset=0 +Authorization: Bearer +``` + +#### Response `200` + +```json +{ + "message": "FAQs retrieved successfully", + "data": { + "faqs": [ + { + "id": 1, + "question": "How do I reset my password?", + "answer": "Go to login and click 'Forgot Password'.", + "category": "Account", + "display_order": 1, + "status": "ACTIVE", + "created_at": "2026-04-30 08:45:15.961307 +0000 UTC" + } + ], + "total_count": 1 + } +} +``` + +#### Pagination + +``` +page = 1-based page number +offset = (page - 1) * limit +total_pages = ceil(total_count / limit) +``` + +--- + +### 2. Get FAQ by ID (admin) + +``` +GET /admin/faqs/:id +Permission: faqs.get +``` + +Returns the FAQ **regardless of status** (unlike public GET). + +#### Example + +```http +GET /api/v1/admin/faqs/1 +Authorization: Bearer +``` + +#### Response `200` + +```json +{ + "message": "FAQ retrieved successfully", + "data": { + "id": 1, + "question": "How do I reset my password?", + "answer": "Go to login and click 'Forgot Password'.", + "category": "Account", + "display_order": 1, + "status": "INACTIVE", + "created_at": "2026-04-30 08:45:15.961307 +0000 UTC", + "updated_at": "2026-05-01 10:00:00 +0000 UTC" + } +} +``` + +#### Errors + +| HTTP | When | +|------|------| +| `400` | Invalid ID | +| `404` | FAQ not found | + +Use this endpoint to populate the **edit form**. + +--- + +### 3. Create FAQ + +``` +POST /admin/faqs +Permission: faqs.create +``` + +#### Request body + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `question` | string | **Yes** | Non-empty after trim | +| `answer` | string | **Yes** | Non-empty after trim | +| `category` | string | No | Optional label; empty string → stored as null | +| `display_order` | int32 | No | Default `0` | +| `status` | string | No | Default `ACTIVE`. Must be `ACTIVE` or `INACTIVE` | + +#### Example + +```http +POST /api/v1/admin/faqs +Authorization: Bearer +Content-Type: application/json + +{ + "question": "How do I reset my password?", + "answer": "Go to login and click 'Forgot Password'.", + "category": "Account", + "display_order": 1, + "status": "ACTIVE" +} +``` + +#### Response `201` + +```json +{ + "message": "FAQ created successfully", + "data": { + "id": 5, + "question": "How do I reset my password?", + "answer": "Go to login and click 'Forgot Password'.", + "category": "Account", + "display_order": 1, + "status": "ACTIVE", + "created_at": "2026-06-10 12:00:00 +0000 UTC" + } +} +``` + +#### Validation errors `400` + +| Error | Cause | +|-------|-------| +| `Validation failed` | Missing `question` or `answer` (validator) | +| `question is required` | Empty question after trim | +| `answer is required` | Empty answer after trim | +| `status must be one of ACTIVE, INACTIVE` | Invalid status | + +--- + +### 4. Update FAQ + +``` +PUT /admin/faqs/:id +Permission: faqs.update +``` + +Partial update — send only fields you want to change. + +#### Request body + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `question` | string | No | Must not be empty if sent | +| `answer` | string | No | Must not be empty if sent | +| `category` | string | No | Send `""` to clear category | +| `display_order` | int32 | No | New sort position | +| `status` | string | No | `ACTIVE` or `INACTIVE` | + +#### Example — publish draft + +```json +{ + "status": "ACTIVE" +} +``` + +#### Example — full edit + +```json +{ + "question": "How can I reset my password?", + "answer": "Tap Forgot Password on the login screen and follow the email link.", + "category": "Account", + "display_order": 2, + "status": "ACTIVE" +} +``` + +#### Response `200` + +```json +{ + "message": "FAQ updated successfully", + "data": { /* updated FAQ object */ } +} +``` + +#### Errors + +| HTTP | When | +|------|------| +| `400` | Validation / invalid status | +| `404` | FAQ not found | + +--- + +### 5. Delete FAQ + +``` +DELETE /admin/faqs/:id +Permission: faqs.delete +``` + +Hard delete — row is removed from the database (not soft delete). + +#### Example + +```http +DELETE /api/v1/admin/faqs/5 +Authorization: Bearer +``` + +#### Response `200` + +```json +{ + "message": "FAQ deleted successfully", + "data": { + "id": 5 + } +} +``` + +#### Errors + +| HTTP | When | +|------|------| +| `404` | FAQ not found | + +Show a confirmation dialog in the admin UI before calling delete. + +--- + +## Public API reference (preview only) + +Use these in admin **“Preview as learner”** or to verify published content. **No auth required.** + +| Method | Path | Behavior | +|--------|------|----------| +| `GET` | `/api/v1/faqs` | List **ACTIVE** FAQs only | +| `GET` | `/api/v1/faqs/:id` | Get one **ACTIVE** FAQ | + +Query params for list: `category`, `limit` (default 50), `offset` (default 0). + +If `GET /faqs/:id` returns `404` but admin GET returns the FAQ, it is likely **`INACTIVE`** (not published). + +--- + +## Publish workflow (ACTIVE / INACTIVE) + +There is no separate publish endpoint. Publishing is done via `status`: + +| Admin action | API call | +|--------------|----------| +| Save as draft | `POST` or `PUT` with `"status": "INACTIVE"` | +| Publish | `PUT` with `"status": "ACTIVE"` | +| Unpublish (hide) | `PUT` with `"status": "INACTIVE"` | + +**Recommended UI:** + +- Status toggle or dropdown: **Published** (`ACTIVE`) / **Draft** (`INACTIVE`) +- List filter tabs: All | Published | Draft +- Badge on list rows: green = Active, gray = Inactive + +--- + +## Categories & display order + +### Categories + +- **Free-text** string on each FAQ (e.g. `"Account"`, `"Billing"`, `"General"`). +- No backend API to list distinct categories. +- **Admin panel pattern:** load all FAQs (or a large page), derive unique categories client-side for filter dropdowns and create-form suggestions. + +```typescript +const categories = [...new Set(faqs.map(f => f.category).filter(Boolean))].sort(); +``` + +Category filter on list uses **exact match** (case-sensitive in DB). + +### Display order + +- Lower numbers appear first. +- Default `0` for new FAQs if omitted. +- **No bulk reorder API** — set `display_order` on create/update per item. + +**Admin panel patterns:** + +1. **Numeric input** on create/edit form. +2. **Drag-and-drop reorder UI** → on drop, `PUT` each affected FAQ with new `display_order` values (e.g. 1, 2, 3…). +3. When creating, suggest `max(display_order) + 1` from current list. + +--- + +## Recommended admin UI screens + +### 1. FAQ list page + +**Route example:** `/admin/help/faqs` + +| UI element | API | +|------------|-----| +| Table/cards of FAQs | `GET /admin/faqs?limit=&offset=` | +| Status filter | `?status=ACTIVE` / `INACTIVE` | +| Category filter | `?category=Account` | +| Search (client-side) | Filter loaded rows by question/answer text | +| “Add FAQ” button | Navigate to create form (`faqs.create`) | +| Edit row | `GET /admin/faqs/:id` → edit form | +| Delete row | `DELETE /admin/faqs/:id` with confirm | +| Publish toggle | `PUT` with `status` | + +**Columns:** Question, Category, Order, Status, Updated, Actions + +### 2. Create / edit form + +**Routes:** `/admin/help/faqs/new`, `/admin/help/faqs/:id/edit` + +| Field | Control | +|-------|---------| +| Question | Text input / textarea | +| Answer | Textarea (plain text; no HTML editor unless you add sanitization client-side only for display) | +| Category | Text input with datalist from known categories | +| Display order | Number input | +| Status | Select: Published / Draft | + +| Action | API | +|--------|-----| +| Save (create) | `POST /admin/faqs` | +| Save (update) | `PUT /admin/faqs/:id` | +| Cancel | Back to list | + +### 3. Preview (optional) + +- Open public URL or call `GET /api/v1/faqs` to show how learners see published FAQs. +- Preview single item: `GET /api/v1/faqs/:id` (only works when `ACTIVE`). + +--- + +## TypeScript types & API client + +### Types + +```typescript +export type FAQStatus = "ACTIVE" | "INACTIVE"; + +export interface FAQ { + id: number; + question: string; + answer: string; + category?: string | null; + display_order: number; + status: FAQStatus; + created_at: string; + updated_at?: string | null; +} + +export interface FAQListData { + faqs: FAQ[]; + total_count: number; +} + +export interface ApiResponse { + message: string; + data: T; + success?: boolean; + status_code?: number; + metadata?: unknown; +} + +export interface ApiError { + message: string; + error?: string; +} + +export interface CreateFAQInput { + question: string; + answer: string; + category?: string | null; + display_order?: number; + status?: FAQStatus; +} + +export interface UpdateFAQInput { + question?: string; + answer?: string; + category?: string | null; + display_order?: number; + status?: FAQStatus; +} +``` + +### Example client (fetch) + +```typescript +const API_BASE = import.meta.env.VITE_API_BASE_URL; // e.g. https://api.yimaru.com + +function authHeaders(token: string): HeadersInit { + return { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + }; +} + +export async function listFAQsAdmin( + token: string, + params: { status?: FAQStatus; category?: string; limit?: number; offset?: number } = {} +): Promise { + const qs = new URLSearchParams(); + if (params.status) qs.set("status", params.status); + if (params.category) qs.set("category", params.category); + qs.set("limit", String(params.limit ?? 20)); + qs.set("offset", String(params.offset ?? 0)); + + const res = await fetch(`${API_BASE}/api/v1/admin/faqs?${qs}`, { + headers: authHeaders(token), + }); + if (!res.ok) throw await res.json(); + const body: ApiResponse = await res.json(); + return body.data; +} + +export async function getFAQAdmin(token: string, id: number): Promise { + const res = await fetch(`${API_BASE}/api/v1/admin/faqs/${id}`, { + headers: authHeaders(token), + }); + if (!res.ok) throw await res.json(); + const body: ApiResponse = await res.json(); + return body.data; +} + +export async function createFAQ(token: string, input: CreateFAQInput): Promise { + const res = await fetch(`${API_BASE}/api/v1/admin/faqs`, { + method: "POST", + headers: authHeaders(token), + body: JSON.stringify(input), + }); + if (!res.ok) throw await res.json(); + const body: ApiResponse = await res.json(); + return body.data; +} + +export async function updateFAQ( + token: string, + id: number, + input: UpdateFAQInput +): Promise { + const res = await fetch(`${API_BASE}/api/v1/admin/faqs/${id}`, { + method: "PUT", + headers: authHeaders(token), + body: JSON.stringify(input), + }); + if (!res.ok) throw await res.json(); + const body: ApiResponse = await res.json(); + return body.data; +} + +export async function deleteFAQ(token: string, id: number): Promise { + const res = await fetch(`${API_BASE}/api/v1/admin/faqs/${id}`, { + method: "DELETE", + headers: authHeaders(token), + }); + if (!res.ok) throw await res.json(); +} +``` + +### React Query example (list + pagination) + +```typescript +const page = 1; +const limit = 20; + +const { data, isLoading, error } = useQuery({ + queryKey: ["admin-faqs", statusFilter, categoryFilter, page], + queryFn: () => + listFAQsAdmin(token, { + status: statusFilter, + category: categoryFilter, + limit, + offset: (page - 1) * limit, + }), +}); +``` + +--- + +## Error handling + +| HTTP | Typical `message` | Admin UI action | +|------|-------------------|-----------------| +| `400` | Validation failed / Failed to create FAQ | Show field errors from `error` | +| `401` | Unauthorized | Redirect to login | +| `403` | Forbidden | Show “No permission” | +| `404` | FAQ not found | Toast + redirect to list | +| `500` | Failed to list/get FAQ | Generic error + retry | + +Always parse `error` field when present for detail. + +--- + +## Integration checklist + +### Backend / access + +- [ ] Migration `000059_faqs` applied +- [ ] RBAC seeded; admin role has `faqs.*` permissions +- [ ] Team member can obtain Bearer token for admin API + +### Admin panel — navigation + +- [ ] Add “FAQs” or “Help center” menu item (gate on `faqs.list`) + +### List page + +- [ ] `GET /admin/faqs` with pagination +- [ ] Filters: status, category (optional) +- [ ] Status badges (ACTIVE / INACTIVE) +- [ ] Actions: Edit, Delete, quick publish/unpublish + +### Create / edit + +- [ ] Form validation (question + answer required) +- [ ] `POST /admin/faqs` on create +- [ ] `GET /admin/faqs/:id` on edit load +- [ ] `PUT /admin/faqs/:id` on save + +### Delete + +- [ ] Confirmation modal +- [ ] `DELETE /admin/faqs/:id` +- [ ] Refresh list after delete + +### Optional enhancements + +- [ ] Client-side search on question/answer +- [ ] Category datalist from existing FAQs +- [ ] Drag-and-drop reorder → multiple `PUT`s with `display_order` +- [ ] Preview link using public `GET /faqs` + +### QA scenarios + +- [ ] Create ACTIVE FAQ → appears on public `GET /faqs` +- [ ] Create INACTIVE FAQ → hidden from public, visible in admin list +- [ ] Update status INACTIVE → ACTIVE → public visibility +- [ ] Delete FAQ → gone from admin and public +- [ ] Invalid status → 400 error shown in UI + +--- + +## Limitations & future work + +| Topic | Current behavior | +|-------|------------------| +| Reorder API | None — update `display_order` per FAQ | +| Category API | No list endpoint; derive client-side | +| Search | No server-side search | +| Rich text | Plain text answers only | +| i18n | Single language | +| Soft delete | Hard delete | +| Audit log | Not FAQ-specific | + +If product needs HTML answers, server-side search, or bulk reorder, those require backend changes. + +--- + +## Quick reference + +| Method | Path | Permission | Purpose | +|--------|------|------------|---------| +| `GET` | `/api/v1/admin/faqs` | `faqs.list` | List (all statuses) | +| `GET` | `/api/v1/admin/faqs/:id` | `faqs.get` | Get one for edit | +| `POST` | `/api/v1/admin/faqs` | `faqs.create` | Create | +| `PUT` | `/api/v1/admin/faqs/:id` | `faqs.update` | Update / publish | +| `DELETE` | `/api/v1/admin/faqs/:id` | `faqs.delete` | Delete | +| `GET` | `/api/v1/faqs` | — | Public list (preview) | +| `GET` | `/api/v1/faqs/:id` | — | Public detail (preview) | + +**Postman:** Import `postman/FAQ-Management.postman_collection.json` for executable examples and test scripts. diff --git a/gen/db/notification.sql.go b/gen/db/notification.sql.go index c21af0e8..54c7bc23 100644 --- a/gen/db/notification.sql.go +++ b/gen/db/notification.sql.go @@ -89,6 +89,46 @@ func (q *Queries) CreateNotification(ctx context.Context, arg CreateNotification return i, err } +const DeleteUserInAppNotification = `-- name: DeleteUserInAppNotification :execrows +DELETE FROM notifications +WHERE id = $1 + AND user_id = $2 + AND channel = 'in_app' +` + +type DeleteUserInAppNotificationParams struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` +} + +func (q *Queries) DeleteUserInAppNotification(ctx context.Context, arg DeleteUserInAppNotificationParams) (int64, error) { + result, err := q.db.Exec(ctx, DeleteUserInAppNotification, arg.ID, arg.UserID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const DeleteUserInAppNotificationsByIDs = `-- name: DeleteUserInAppNotificationsByIDs :execrows +DELETE FROM notifications +WHERE user_id = $1 + AND channel = 'in_app' + AND id = ANY($2::BIGINT[]) +` + +type DeleteUserInAppNotificationsByIDsParams struct { + UserID int64 `json:"user_id"` + Column2 []int64 `json:"column_2"` +} + +func (q *Queries) DeleteUserInAppNotificationsByIDs(ctx context.Context, arg DeleteUserInAppNotificationsByIDsParams) (int64, error) { + result, err := q.db.Exec(ctx, DeleteUserInAppNotificationsByIDs, arg.UserID, arg.Column2) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const DeleteUserNotifications = `-- name: DeleteUserNotifications :exec DELETE FROM notifications WHERE user_id = $1 diff --git a/internal/ports/notification.go b/internal/ports/notification.go index ef54f8d0..138254f9 100644 --- a/internal/ports/notification.go +++ b/internal/ports/notification.go @@ -19,6 +19,8 @@ type NotificationStore interface { MarkNotificationAsUnread(ctx context.Context, id int64) (*domain.Notification, error) MarkAllUserNotificationsAsUnread(ctx context.Context, userID int64) error DeleteUserNotifications(ctx context.Context, userID int64) error + DeleteUserInAppNotification(ctx context.Context, id, userID int64) (int64, error) + DeleteUserInAppNotificationsByIDs(ctx context.Context, userID int64, ids []int64) (int64, error) // Scheduled Notifications CreateScheduledNotification(ctx context.Context, sn *domain.ScheduledNotification) (*domain.ScheduledNotification, error) diff --git a/internal/repository/notification.go b/internal/repository/notification.go index 6ad39232..ad9ed9b3 100644 --- a/internal/repository/notification.go +++ b/internal/repository/notification.go @@ -237,6 +237,27 @@ func (r *Store) DeleteUserNotifications( return r.queries.DeleteUserNotifications(ctx, userID) } +func (r *Store) DeleteUserInAppNotification( + ctx context.Context, + id, userID int64, +) (int64, error) { + return r.queries.DeleteUserInAppNotification(ctx, dbgen.DeleteUserInAppNotificationParams{ + ID: id, + UserID: userID, + }) +} + +func (r *Store) DeleteUserInAppNotificationsByIDs( + ctx context.Context, + userID int64, + ids []int64, +) (int64, error) { + return r.queries.DeleteUserInAppNotificationsByIDs(ctx, dbgen.DeleteUserInAppNotificationsByIDsParams{ + UserID: userID, + Column2: ids, + }) +} + /* ========================= Mapping ========================= */ diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go index d6335676..715a2380 100644 --- a/internal/services/notification/service.go +++ b/internal/services/notification/service.go @@ -1012,6 +1012,37 @@ func (s *Service) DeleteUserNotifications(ctx context.Context, userID int64) err return nil } +func (s *Service) DeleteUserInAppNotification(ctx context.Context, id, userID int64) error { + rows, err := s.store.DeleteUserInAppNotification(ctx, id, userID) + if err != nil { + s.mongoLogger.Error("[NotificationSvc.DeleteUserInAppNotification] Failed to delete in-app notification", + zap.Int64("notificationID", id), + zap.Int64("userID", userID), + zap.Error(err), + zap.Time("timestamp", time.Now()), + ) + return err + } + if rows == 0 { + return ErrNotificationNotFound + } + return nil +} + +func (s *Service) DeleteUserInAppNotifications(ctx context.Context, userID int64, ids []int64) (int64, error) { + rows, err := s.store.DeleteUserInAppNotificationsByIDs(ctx, userID, ids) + if err != nil { + s.mongoLogger.Error("[NotificationSvc.DeleteUserInAppNotifications] Failed to delete in-app notifications", + zap.Int64("userID", userID), + zap.Int("idCount", len(ids)), + zap.Error(err), + zap.Time("timestamp", time.Now()), + ) + return 0, err + } + return rows, nil +} + // Scheduled Notification Methods func (s *Service) CreateScheduledNotification(ctx context.Context, sn *domain.ScheduledNotification) (*domain.ScheduledNotification, error) { diff --git a/internal/services/notification/service_delete_test.go b/internal/services/notification/service_delete_test.go new file mode 100644 index 00000000..acfed8bd --- /dev/null +++ b/internal/services/notification/service_delete_test.go @@ -0,0 +1,66 @@ +package notificationservice + +import ( + "context" + "errors" + "testing" + + "Yimaru-Backend/internal/ports" +) + +type deleteInAppStoreStub struct { + ports.NotificationStore + singleRows int64 + singleErr error + bulkRows int64 + bulkErr error +} + +func (s *deleteInAppStoreStub) DeleteUserInAppNotification(_ context.Context, _, _ int64) (int64, error) { + if s.singleErr != nil { + return 0, s.singleErr + } + return s.singleRows, nil +} + +func (s *deleteInAppStoreStub) DeleteUserInAppNotificationsByIDs(_ context.Context, _ int64, _ []int64) (int64, error) { + if s.bulkErr != nil { + return 0, s.bulkErr + } + return s.bulkRows, nil +} + +func TestDeleteUserInAppNotification_success(t *testing.T) { + svc := &Service{ + store: &deleteInAppStoreStub{singleRows: 1}, + } + + if err := svc.DeleteUserInAppNotification(context.Background(), 10, 42); err != nil { + t.Fatalf("expected nil error, got %v", err) + } +} + +func TestDeleteUserInAppNotification_notFound(t *testing.T) { + svc := &Service{ + store: &deleteInAppStoreStub{singleRows: 0}, + } + + err := svc.DeleteUserInAppNotification(context.Background(), 10, 42) + if !errors.Is(err, ErrNotificationNotFound) { + t.Fatalf("expected ErrNotificationNotFound, got %v", err) + } +} + +func TestDeleteUserInAppNotifications_success(t *testing.T) { + svc := &Service{ + store: &deleteInAppStoreStub{bulkRows: 2}, + } + + got, err := svc.DeleteUserInAppNotifications(context.Background(), 42, []int64{1, 2, 3}) + if err != nil { + t.Fatalf("expected nil error, got %v", err) + } + if got != 2 { + t.Fatalf("expected deleted count 2, got %d", got) + } +} diff --git a/internal/services/rbac/seeds.go b/internal/services/rbac/seeds.go index 28085992..54ffb1c3 100644 --- a/internal/services/rbac/seeds.go +++ b/internal/services/rbac/seeds.go @@ -551,6 +551,9 @@ var DefaultRolePermissions = map[string][]string{ "question_set_items.add", "question_set_items.list", "question_set_items.remove", "question_set_items.update_order", "question_set_personas.list", "question_set_personas.add", "question_set_personas.remove", + // FAQs + "faqs.create", "faqs.list", "faqs.get", "faqs.update", "faqs.delete", + // Subscriptions & Payments (own) "subscriptions.checkout", "subscriptions.get_mine", "subscriptions.history", "subscriptions.status", "subscriptions.cancel", "subscriptions.set_auto_renew", diff --git a/internal/services/rbac/service.go b/internal/services/rbac/service.go index fa573b2c..f36aaa6e 100644 --- a/internal/services/rbac/service.go +++ b/internal/services/rbac/service.go @@ -6,6 +6,7 @@ import ( "context" "fmt" "log/slog" + "strings" "sync/atomic" ) @@ -33,6 +34,7 @@ func NewService(store ports.RBACStore, logger *slog.Logger) *Service { // SUPER_ADMIN and ADMIN always return true to keep admin panel // access resilient even when RBAC seed data is partially missing. func (s *Service) HasPermission(roleName, permKey string) bool { + roleName = strings.ToUpper(strings.TrimSpace(roleName)) if roleName == string(domain.RoleSuperAdmin) || roleName == string(domain.RoleAdmin) { return true } diff --git a/internal/web_server/handlers/notification_handler.go b/internal/web_server/handlers/notification_handler.go index c5369760..4383ca9e 100644 --- a/internal/web_server/handlers/notification_handler.go +++ b/internal/web_server/handlers/notification_handler.go @@ -340,6 +340,126 @@ func (h *Handler) DeleteUserNotifications(c *fiber.Ctx) error { }) } +// DeleteInAppNotification godoc +// @Summary Delete a single in-app notification +// @Description Deletes one in-app notification owned by the authenticated user. +// @Tags notifications +// @Produce json +// @Param id path int true "Notification ID" +// @Success 200 {object} domain.Response +// @Failure 400 {object} domain.ErrorResponse +// @Failure 404 {object} domain.ErrorResponse +// @Failure 500 {object} domain.ErrorResponse +// @Router /api/v1/notifications/{id} [delete] +func (h *Handler) DeleteInAppNotification(c *fiber.Ctx) error { + idStr := c.Params("id") + id, err := strconv.ParseInt(idStr, 10, 64) + if err != nil || id <= 0 { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "Invalid notification ID", + Error: err.Error(), + }) + } + + userID, ok := c.Locals("user_id").(int64) + if !ok || userID == 0 { + return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{ + Message: "Invalid user identification", + Error: "User ID not found in context", + }) + } + + if err := h.notificationSvc.DeleteUserInAppNotification(c.Context(), id, userID); err != nil { + switch { + case errors.Is(err, notificationservice.ErrNotificationNotFound): + return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ + Message: "In-app notification not found", + Error: err.Error(), + }) + default: + h.mongoLoggerSvc.Error("[NotificationHandler.DeleteInAppNotification] Failed to delete in-app notification", + zap.Int64("notificationID", id), + zap.Int64("userID", userID), + zap.Error(err), + zap.Time("timestamp", time.Now()), + ) + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to delete in-app notification", + Error: err.Error(), + }) + } + } + + return c.Status(fiber.StatusOK).JSON(domain.Response{ + Message: "In-app notification deleted successfully", + Success: true, + StatusCode: fiber.StatusOK, + }) +} + +// DeleteInAppNotifications godoc +// @Summary Delete multiple in-app notifications +// @Description Deletes in-app notifications by ID for the authenticated user. Non-matching IDs are ignored. +// @Tags notifications +// @Accept json +// @Produce json +// @Param body body object true "Notification IDs" example({"ids":[1,2,3]}) +// @Success 200 {object} domain.Response +// @Failure 400 {object} domain.ErrorResponse +// @Failure 500 {object} domain.ErrorResponse +// @Router /api/v1/notifications/delete-in-app [post] +func (h *Handler) DeleteInAppNotifications(c *fiber.Ctx) error { + type request struct { + IDs []int64 `json:"ids"` + } + + userID, ok := c.Locals("user_id").(int64) + if !ok || userID == 0 { + return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{ + Message: "Invalid user identification", + Error: "User ID not found in context", + }) + } + + var req request + if err := c.BodyParser(&req); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "Invalid request body", + Error: err.Error(), + }) + } + if len(req.IDs) == 0 { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "At least one notification ID is required", + Error: "ids must contain at least one item", + }) + } + + deletedCount, err := h.notificationSvc.DeleteUserInAppNotifications(c.Context(), userID, req.IDs) + if err != nil { + h.mongoLoggerSvc.Error("[NotificationHandler.DeleteInAppNotifications] Failed to delete in-app notifications", + zap.Int64("userID", userID), + zap.Int("idCount", len(req.IDs)), + zap.Error(err), + zap.Time("timestamp", time.Now()), + ) + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to delete in-app notifications", + Error: err.Error(), + }) + } + + return c.Status(fiber.StatusOK).JSON(domain.Response{ + Message: "In-app notifications deleted successfully", + Success: true, + StatusCode: fiber.StatusOK, + Data: fiber.Map{ + "deleted_count": deletedCount, + "requested_ids": len(req.IDs), + }, + }) +} + func (h *Handler) CreateAndSendNotification(c *fiber.Ctx) error { type Request struct { RecipientID int64 `json:"recipient_id" validate:"required_if=DeliveryScheme single"` diff --git a/internal/web_server/handlers/rbac_handler.go b/internal/web_server/handlers/rbac_handler.go index b3eff868..500f4aac 100644 --- a/internal/web_server/handlers/rbac_handler.go +++ b/internal/web_server/handlers/rbac_handler.go @@ -540,6 +540,18 @@ func (h *Handler) SyncPermissions(c *fiber.Ctx) error { }) } + if err := h.rbacSvc.SeedDefaultRolePermissions(c.Context()); err != nil { + h.mongoLoggerSvc.Error("Failed to seed default role permissions", + zap.Int("status_code", fiber.StatusInternalServerError), + zap.Error(err), + zap.Time("timestamp", time.Now()), + ) + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to sync role permissions", + Error: err.Error(), + }) + } + if err := h.rbacSvc.Reload(c.Context()); err != nil { h.mongoLoggerSvc.Error("Failed to reload RBAC cache", zap.Int("status_code", fiber.StatusInternalServerError), diff --git a/internal/web_server/handlers/team_handler.go b/internal/web_server/handlers/team_handler.go index 413d2074..39e77502 100644 --- a/internal/web_server/handlers/team_handler.go +++ b/internal/web_server/handlers/team_handler.go @@ -36,7 +36,7 @@ func mapTeamRoleToRole(teamRole domain.TeamRole) domain.Role { switch teamRole { case domain.TeamRoleSuperAdmin: return domain.RoleSuperAdmin - case domain.TeamRoleAdmin: + case domain.TeamRoleAdmin, domain.TeamRoleContentManager: return domain.RoleAdmin case domain.TeamRoleInstructor: return domain.RoleInstructor diff --git a/internal/web_server/routes.go b/internal/web_server/routes.go index a2e2a2b2..4f128ac2 100644 --- a/internal/web_server/routes.go +++ b/internal/web_server/routes.go @@ -382,6 +382,7 @@ func (a *App) initAppRoutes() { groupV1.Patch("/notifications/:id/unread", a.authMiddleware, a.RequirePermission("notifications.mark_unread"), h.MarkNotificationAsUnread) groupV1.Post("/notifications/mark-all-unread", a.authMiddleware, a.RequirePermission("notifications.mark_all_unread"), h.MarkAllNotificationsAsUnread) groupV1.Delete("/notifications", a.authMiddleware, a.RequirePermission("notifications.delete_mine"), h.DeleteUserNotifications) + groupV1.Post("/notifications/delete-in-app", a.authMiddleware, a.RequirePermission("notifications.delete_mine"), h.DeleteInAppNotifications) groupV1.Get("/notifications/unread", a.authMiddleware, a.RequirePermission("notifications.count_unread"), h.CountUnreadNotifications) groupV1.Post("/notifications/create", a.authMiddleware, a.RequirePermission("notifications.create"), h.CreateAndSendNotification) groupV1.Post("/notifications/test-push", a.authMiddleware, a.RequirePermission("notifications.test_push"), h.SendTestPushNotification) @@ -397,6 +398,7 @@ func (a *App) initAppRoutes() { groupV1.Get("/notifications/scheduled", a.authMiddleware, a.RequirePermission("notifications_scheduled.list"), h.ListScheduledNotifications) groupV1.Get("/notifications/scheduled/:id", a.authMiddleware, a.RequirePermission("notifications_scheduled.get"), h.GetScheduledNotification) groupV1.Post("/notifications/scheduled/:id/cancel", a.authMiddleware, a.RequirePermission("notifications_scheduled.cancel"), h.CancelScheduledNotification) + groupV1.Delete("/notifications/:id", a.authMiddleware, a.RequirePermission("notifications.delete_mine"), h.DeleteInAppNotification) groupV1.Get("/notifications/:id", a.authMiddleware, a.RequirePermission("notifications.list_mine"), h.GetNotificationByID) // Issues