RezinaLMS-BackEnd/docs/overview.md

317 lines
12 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Rezina Backend — Technical Overview
Technical briefing for engineers, architects, or integrators evaluating or working on the **Rezina Backend API**.
> **Setup & ops:** [README](../README.md)
> **OpenAPI:** `/swagger/index.html` when the server is running
> **Production base:** `https://api.rezinaacademy.com/api/v1`
---
## What this repo is
A single **Go monolith** exposing REST JSON at `/api/v1`. It is the system of record for:
| Consumer | Auth | Primary use |
|----------|------|-------------|
| iOS / Android learner apps | Learner JWT | Content delivery, progress, checkout |
| [Rezina Admin](https://gitea.yaltopia.com/Rezina/Rezina-Admin) | Team JWT + RBAC | CRUD, analytics, bulk notify, exports |
| Web checkout (Vite SPA) | Learner JWT | Hosted Chapa subscribe flow |
There is **no separate BFF**. Clients talk directly to this API.
---
## System context
```mermaid
flowchart LR
subgraph clients [Clients]
Mobile[iOS / Android]
Admin[Admin React SPA]
Web[Web checkout]
end
API[Rezina API<br/>Fiber /api/v1]
subgraph persistence [Persistence]
PG[(PostgreSQL)]
Mongo[(MongoDB logs)]
MinIO[(MinIO)]
end
subgraph external [External APIs]
Pay[Chapa / Arifpay]
Mail[Resend]
Push[FCM]
Vid[Vimeo]
end
Mobile --> API
Admin --> API
Web --> API
API --> PG
API --> Mongo
API --> MinIO
API --> Pay
API --> Mail
API --> Push
API --> Vid
```
---
## Stack
| Component | Choice | Notes |
|-----------|--------|-------|
| Runtime | Go 1.25+ | See `go.mod` |
| HTTP | Fiber v2 | `internal/web_server` |
| SQL access | sqlc → `gen/db` | Queries in `db/query/` — do not edit generated code |
| Migrations | golang-migrate | `db/migrations/` (one consolidated baseline pair) |
| Validation | go-playground/validator | Handler DTOs in `internal/domain` |
| Auth | JWT HMAC | Access + refresh; separate learner vs team claims |
| Docs | swag | `make swagger` regenerates `docs/` |
| Local dev | Air + Docker Compose | Postgres, Mongo, MinIO, migrate sidecar |
Entry point: `cmd/main.go` wires ~40 services, repositories, cron, and the Fiber app.
---
## Architecture
Ports-and-adapters layout:
```
Request
→ Fiber middleware (CORS, logging, resolveFileURLs)
→ authMiddleware (JWT parse → Locals: user_id / team_member_id, role, permissions)
→ RequirePermission("key") // admin write paths
→ RequireLMSSubscriptionUnlessFree() // learner course reads
→ Handler (thin: bind, validate, call service, map domain errors → HTTP)
→ Service (business rules, orchestration)
→ Repository (sqlc queries)
→ PostgreSQL
```
| Package | Responsibility |
|---------|----------------|
| `internal/domain` | Entities, enums, request/response structs, domain errors |
| `internal/ports` | Store interfaces (testability) |
| `internal/repository` | Postgres implementations |
| `internal/services/*` | One package per bounded context (subscriptions, examprep, practices, …) |
| `internal/web_server/handlers` | HTTP adapters |
| `internal/web_server/routes.go` | Route registration — **start here to understand the API surface** |
Cron (same process): scheduled notification dispatch, account-deletion purge, subscription reminders, etc. (see `internal/web_server` cron setup in `main.go`).
---
## Learning content
The active learning hierarchy is organized for academic programs and subject-focused remedial instruction.
```
programs
└── courses
└── modules ← top-level modules (no units)
└── lessons
└── practices → questions
```
- Reorder: `PUT /programs/reorder`, `/programs/:id/courses/reorder`, `/courses/:id/modules/reorder`, `/modules/:id/lessons/reorder`.
- Learner routes use `RequireLMSSubscriptionUnlessFree()` — `FREE` access tier content bypasses subscription.
---
## Auth model
Two JWT audiences, same signing key:
| Actor | Login | Claims | Middleware |
|-------|-------|--------|------------|
| **Learner** | `/auth/login`, OTP, Google, Apple | `user_id`, platform role | `authMiddleware` |
| **Team member** | `/team/login`, Google, refresh | `team_member_id`, RBAC permissions[] | `authMiddleware` |
Authorization for admin operations is **permission-key based**, not role-string based in handlers:
```go
groupV1.Post("/programs", a.authMiddleware, a.RequirePermission("programs.create"), h.CreateProgram)
```
Custom RBAC roles stored in DB; built-in keys like `SUPER_ADMIN` still exist for team members. Clients should send permission keys from the JWT, not assume role names.
Refresh: separate endpoints for learners and team (`/auth/refresh`, `/team/refresh`).
---
## Subscription & entitlements
Plans (`subscription_plans.category`):
Subscription plan categories are stored in the database and control access to paid learning content. Historic category rows may remain during migration; course content itself is organized by the LMS hierarchy.
Active row: `user_subscriptions` joined to plan. Content entities carry:
- `publish_status` — `DRAFT` hidden from learners
- `access_tier` — `FREE` vs `PREMIUM`
Gating logic lives in middleware + `domain.SubscriptionGrantsContentAccess`.
**Payments:** Chapa hosted checkout (`POST /subscriptions/checkout`), webhooks update payment + subscription state. Arifpay as alternate. Admin list/export under `/admin/payments`.
**iOS note:** mobile app sends checkout link via `POST /subscriptions/request-checkout-link`; user completes payment on web SPA (see `web-checkout-client-integration.md`).
---
## API surface (by route group)
Registered in `internal/web_server/routes.go`. Representative groups:
| Prefix / group | Examples | Auth |
|----------------|----------|------|
| `/auth/*` | register, login, OTP, Google, Apple, refresh | Public / JWT |
| `/team/*` | login, invite, accept-invite, members CRUD | Team JWT |
| `/programs`, `/courses`, `/modules`, `/lessons` | LMS CRUD + learner GET | JWT + permissions / subscription |
| `/practices`, `/questions` | LMS practice engine | JWT + permissions |
| `/progress/*`, `/lms/progress*` | lesson complete, practice complete | Learner JWT + LMS sub |
| `/subscriptions/*` | plans, checkout, me, request-checkout-link | Mixed |
| `/admin/payments`, `/admin/subscriptions/*` | list, grant, extend, cancel | Team JWT + permissions |
| `/admin/analytics/*` | dashboard aggregates | Team JWT |
| `/notifications/*` | in-app, bulk, scheduled | Team / learner |
| `/files/*` | upload, presign, refresh-url | JWT |
| `/devices/register` | FCM token + platform | Learner JWT |
| `/app/version/check` | force-update gate | Public |
Full list: Swagger or `GET /routes` (dev).
---
## Request / response conventions
- Envelope: `{ message, data, success, status_code, metadata }` (see `domain.Response`).
- Errors: `{ message, error }` with appropriate HTTP status.
- Pagination: offset/limit on list endpoints (`total_count` in `data`).
- File URLs in responses may be presigned; `resolveFileURLsMiddleware` rewrites for clients.
- Validation errors: `"Validation failed: …"` from centralized validator.
---
## Data layer workflow
```bash
# 1. Change SQL
vim db/query/programs.sql
make migrations/new name=add_something
# 2. Regenerate
make sqlc-gen
# 3. Implement repository + service + handler
# 4. Annotate handler for Swagger
make swagger
```
Seeds: `db/data/` (baseline), `db/dev_data/` (local only).
Backup: `make backup` / `make restore`.
---
## Key services (wiring map)
`cmd/main.go` constructs stores and services. Notable packages:
| Service | Package | Role |
|---------|---------|------|
| Auth | `services/authentication` | Login, OAuth, OTP |
| Team | `services/team` | Invites, team CRUD |
| RBAC | `services/rbac` | Custom roles / permissions |
| Programs / courses | `services/programs`, `courses`, `modules`, `lessons` | LMS tree |
| Practices | `services/practices`, `practicecontent`, `questions` | Content + assessment |
| Assessment | `services/assessment` | Scoring / evaluation |
| Subscriptions | `services/subscriptions` | Plans, checkout, entitlements |
| Chapa / Arifpay | `services/chapa`, `arifpay` | Payment providers |
| Notifications | `services/notification`, `learnernotifications`, `messenger` | Push, email, SMS, scheduled jobs |
| MinIO / Vimeo | `services/minio`, `vimeo` | Media pipeline |
| LMS progress | `services/lmsprogress` | Completion state |
---
## Security (implementation-level)
| Topic | Where |
|-------|--------|
| JWT secret | `JWT_KEY`, expiry in seconds |
| OAuth | Google client IDs (multi-client for web + mobile), Apple `aud` allowlist |
| Webhooks | Chapa/Arifpay signature verification in payment handlers |
| Uploads | Presigned PUT to MinIO; `CompletePresignedUpload` records metadata |
| RBAC | Permission checked per route; missing permission → 403 |
| SQL injection | sqlc parameterized queries only in repositories |
| Secrets | `godotenv` / env; `.env` gitignored |
---
## Deployment
- **Branch:** `production` → Docker image → server pull + restart.
- **Migrate before/up with deploy:** `migrate` container or CI step against production `DB_URL`.
- **Binary:** multi-stage `Dockerfile`, non-root runner, single process (HTTP + cron).
- **Observability:** structured slog; optional Mongo log sink; Postgres for domain data.
Local parity: `make db-up` then `make air`.
---
## Technical demo script (~20 min)
For a peer engineer — use Swagger + one code walk:
| # | Show | Point |
|---|------|-------|
| 1 | `routes.go` lines 86–180 | Learning content routes + middleware chain |
| 2 | Swagger → `GET /programs` | LMS list; note permission + subscription middleware |
| 5 | `POST /subscriptions/checkout` | Server creates Chapa session; no client-side secret |
| 6 | `GET /subscriptions/me` | Entitlement source of truth for apps |
| 7 | `db/query/` + `gen/db` | sqlc workflow |
| 8 | Admin panel side-by-side | Same API the SPA calls |
Optional deep dive: open `CompletePractice` handler → progress service → migration `000109` (parent-scoped progress).
---
## Integration docs (for client implementers)
| Doc | Client |
|-----|--------|
| [web-checkout-client-integration.md](./web-checkout-client-integration.md) | Web checkout / iOS link flow |
| [admin-subscription-grant-extend-cancel-admin-panel-integration.md](./admin-subscription-grant-extend-cancel-admin-panel-integration.md) | Admin subscription ops |
| [practice-multi-parent-admin-panel-integration.md](./practice-multi-parent-admin-panel-integration.md) | Practice linking |
| [question-type-definition-groups-admin-panel-integration.md](./question-type-definition-groups-admin-panel-integration.md) | Dynamic question types |
| [bulk-scheduled-notifications-integration.md](./bulk-scheduled-notifications-integration.md) | Scheduled notify |
| `postman/` | Importable collections |
---
## Suggested slide deck (technical audience)
1. **Scope** — monolith API, three client types, one Postgres DB
2. **Context diagram** — clients, API, stores, externals
3. **Layered architecture** — handler → service → repository → sqlc
4. **Dual content model** — LMS vs `exam_prep` (diagram + why separate)
5. **Auth** — dual JWT, RBAC permission keys
6. **Entitlements** — plan categories, middleware gates, free tier
7. **Practice engine** — shared questions, multi-parent, assessment
8. **Payments** — checkout flow, webhooks, admin export
9. **Media** — MinIO presign, Vimeo, URL refresh middleware
10. **Dev workflow** — migrate, sqlc, swagger, compose, air
11. **Demo** — routes.go + Swagger + one vertical slice
12. **Q&A**
---
## License
Proprietary — Yaltopia / Rezina. Internal use only unless otherwise licensed.