484 lines
18 KiB
Markdown
484 lines
18 KiB
Markdown
# Rezina Backend API
|
|
|
|
Golang API for **Rezina**, a remedial and makeup education LMS. It serves the learner apps and the [Rezina Admin](https://gitea.yaltopia.com/Rezina/Rezina-Admin) panel: authentication, academic programs and courses, practices and assessments, subscriptions and payments, team RBAC, analytics, notifications, and more.
|
|
|
|
| | |
|
|
|---|---|
|
|
| **Module** | `Rezina-Backend` |
|
|
| **Language** | Go `1.25` (see `go.mod`) |
|
|
| **HTTP** | [Fiber](https://gofiber.io/) |
|
|
| **DB** | PostgreSQL 16 (primary) + MongoDB (app logs) |
|
|
| **SQL** | [sqlc](https://sqlc.dev) + [golang-migrate](https://github.com/golang-migrate/migrate) |
|
|
| **API docs** | Swagger / OpenAPI (`docs/`, `/swagger/*`) |
|
|
| **Remote** | `https://gitea.yaltopia.com/Rezina/Rezina-BackEnd.git` |
|
|
| **Branches** | `main`, `production` (deploy from `production`) |
|
|
|
|
---
|
|
|
|
## Table of contents
|
|
|
|
0. [Technical overview (presentations)](docs/overview.md)
|
|
1. [Features](#features)
|
|
2. [Architecture](#architecture)
|
|
3. [Prerequisites](#prerequisites)
|
|
4. [Quick start](#quick-start)
|
|
5. [Environment configuration](#environment-configuration)
|
|
6. [Running the application](#running-the-application)
|
|
7. [Database](#database)
|
|
8. [Makefile reference](#makefile-reference)
|
|
9. [API documentation](#api-documentation)
|
|
10. [Auth, roles & permissions](#auth-roles--permissions)
|
|
11. [Domain overview](#domain-overview)
|
|
12. [Integrations](#integrations)
|
|
13. [Project structure](#project-structure)
|
|
14. [Testing & code quality](#testing--code-quality)
|
|
15. [Admin panel integration docs](#admin-panel-integration-docs)
|
|
16. [Deployment notes](#deployment-notes)
|
|
17. [Troubleshooting](#troubleshooting)
|
|
|
|
---
|
|
|
|
## Features
|
|
|
|
- **Learners**: registration/login (email OTP, Google, Apple), profiles, field options, progress
|
|
- **Learning content**: programs → courses → modules → lessons; practices, subject-focused assessments, and video engagement
|
|
- **Dynamic question types**: type definitions, groups, multi-slot answers, select-missing-words, etc.
|
|
- **Subscriptions & payments**: plans (including one-time lifetime), Chapa / Arifpay / related gateways, admin grant/extend/cancel
|
|
- **Team admin**: invite by email, accept-invite flow, refresh tokens, password reset, custom RBAC roles
|
|
- **Analytics**: dashboard metrics (users, subscriptions, revenue, content, video drop-off, renewal/churn)
|
|
- **Ops**: notifications (in-app, email, SMS), FAQs, issues, ratings, activity logs, CSV export, app version checks
|
|
- **Media**: MinIO object storage, Vimeo uploads, CloudConvert (optional)
|
|
|
|
---
|
|
|
|
Referral codes, admin-configured commissions, wallet APIs, and rollout instructions are documented in [Referral system](docs/referral-system.md).
|
|
|
|
## Subscription access
|
|
|
|
Learning content under `/api/v1/exam-prep` uses the EDUCATION subscription.
|
|
Student requests for lessons, practices, assessment collections, practice questions,
|
|
completion, and video engagement require an active subscription whose start date has
|
|
arrived and whose expiry date is in the future. Missing access returns HTTP 403.
|
|
Individual free lessons and practices remain accessible, provided all their ancestors
|
|
are free. Content collections require a subscription because they can contain premium
|
|
descendants. Catalog course, unit, and module browsing remains available for discovery.
|
|
Existing staff and OPEN_LEARNER exemptions are preserved.
|
|
|
|
Checkout uses `/api/v1/payments/subscribe`; clients can inspect access through
|
|
`/api/v1/subscriptions/status` and `/api/v1/subscriptions/me`. These changes enforce
|
|
existing plans and payments; they do not add automatic recurring gateway charges.
|
|
|
|
## Architecture
|
|
|
|
Layered layout (ports & adapters style):
|
|
|
|
```
|
|
cmd/main.go
|
|
→ config + wiring
|
|
→ Fiber HTTP server (internal/web_server)
|
|
→ handlers + JWT / permission middleware
|
|
→ services (internal/services/*)
|
|
→ repositories (internal/repository) via ports
|
|
→ gen/db (sqlc) + pgx → PostgreSQL
|
|
→ Mongo logger (optional)
|
|
```
|
|
|
|
| Layer | Responsibility |
|
|
|--------|----------------|
|
|
| `internal/domain` | Entities, enums, request/response DTOs, domain errors |
|
|
| `internal/ports` | Store / service interfaces |
|
|
| `internal/repository` | PostgreSQL implementations over sqlc |
|
|
| `internal/services` | Business rules, external API clients |
|
|
| `internal/web_server` | Routes, middleware, validators, cron |
|
|
| `db/query` + `db/migrations` | SQL source of truth; `sqlc generate` → `gen/db` |
|
|
|
|
API bases: **`/api/v1/admin`** for staff and **`/api/v1`** for customer web/mobile apps. See [API separation and migration](docs/api-audiences.md).
|
|
|
|
---
|
|
|
|
## Prerequisites
|
|
|
|
Install locally:
|
|
|
|
- [Go](https://go.dev/dl/) matching `go.mod` (1.25+)
|
|
- [Docker](https://www.docker.com/) + Docker Compose
|
|
- [Air](https://github.com/air-verse/air) — live reload (`make air`)
|
|
- [sqlc](https://docs.sqlc.dev/en/latest/overview/install.html)
|
|
- [migrate](https://github.com/golang-migrate/migrate/tree/master/cmd/migrate) CLI
|
|
- [swag](https://github.com/swaggo/swag) — regenerate OpenAPI (`make swagger`)
|
|
|
|
Optional: `psql`, MongoDB tools for log export.
|
|
|
|
---
|
|
|
|
## Quick start
|
|
|
|
```bash
|
|
git clone https://gitea.yaltopia.com/Rezina/Rezina-BackEnd.git
|
|
cd Rezina-BackEnd
|
|
|
|
# 1. Environment
|
|
cp .env .env.local # or create .env from the table below
|
|
# Edit DB_URL, JWT_KEY, PORT, RESEND_*, etc.
|
|
|
|
# 2. Infrastructure
|
|
make db-up # Postgres + migrate + Mongo (detached)
|
|
|
|
# 3. Demo seed (optional, non-production only, after all migrations)
|
|
go run ./cmd/demo-seed -environment development
|
|
# See docs/demo-and-public-catalog.md for role credentials and fixture details.
|
|
|
|
# 4. Run API with live reload
|
|
make air
|
|
# or: go run ./cmd/main.go
|
|
```
|
|
|
|
Health check: open Swagger at `http://localhost:<PORT>/swagger/index.html`.
|
|
|
|
Default Compose Postgres (from `docker-compose.yml`):
|
|
|
|
| Setting | Value |
|
|
|---------|--------|
|
|
| User / password / DB | `root` / `secret` / `gh` |
|
|
| Host port mapping | `5592` → container (see compose file; confirm with `docker compose ps`) |
|
|
| Connection URL (host) | `postgresql://root:secret@localhost:<host_port>/gh?sslmode=disable` |
|
|
| In-network URL | `postgresql://root:secret@postgres:5432/gh?sslmode=disable` |
|
|
|
|
Also started by compose: **pgAdmin** (`5030`), **Mongo** (`27021`), **MinIO** (`9000` / console `9001`).
|
|
|
|
---
|
|
|
|
## Environment configuration
|
|
|
|
Loaded via `godotenv` in `internal/config`. Keep secrets in `.env` (gitignored). Do not commit real keys.
|
|
|
|
### Core
|
|
|
|
| Variable | Purpose |
|
|
|----------|---------|
|
|
| `ENV` | `development` / `production` / etc. |
|
|
| `PORT` | HTTP listen port |
|
|
| `APP_VERSION` | Reported app version |
|
|
| `DB_URL` | PostgreSQL connection string |
|
|
| `MONGODB_URL` | Mongo URI for application logs |
|
|
| `JWT_KEY` | HMAC secret for access tokens |
|
|
| `ACCESS_EXPIRY` | Access token TTL (seconds) |
|
|
| `REFRESH_EXPIRY` | Refresh token TTL (seconds) |
|
|
| `LOG_LEVEL` | e.g. `debug`, `info`, `warn`, `error` |
|
|
|
|
### Team / admin panel
|
|
|
|
| Variable | Purpose |
|
|
|----------|---------|
|
|
| `TEAM_INVITE_BASE_URL` | Front-end accept-invite URL base |
|
|
| `TEAM_PASSWORD_RESET_BASE_URL` | Front-end password-reset URL base |
|
|
|
|
### Email / SMS
|
|
|
|
| Variable | Purpose |
|
|
|----------|---------|
|
|
| `RESEND_API_KEY` | Resend transactional email |
|
|
| `RESEND_SENDER_EMAIL` | From address |
|
|
| `AFRO_SMS_*` | AfroMessage SMS (API key, sender, base URL, …) |
|
|
|
|
### Auth providers
|
|
|
|
| Variable | Purpose |
|
|
|----------|---------|
|
|
| `GOOGLE_OAUTH_CLIENT_ID` / `SECRET` / `REDIRECT_URL` | Google OAuth |
|
|
| `APPLE_SIGN_IN_CLIENT_IDS` | Comma-separated allowed Apple `aud` values |
|
|
| `FCM_SERVICE_ACCOUNT_KEY` | Firebase Cloud Messaging (JSON path or payload) |
|
|
|
|
### Media & files
|
|
|
|
| Variable | Purpose |
|
|
|----------|---------|
|
|
| `MINIO_ENABLED` / `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_BUCKET` / `MINIO_USE_SSL` | Object storage |
|
|
| `VIMEO_ENABLED` / `VIMEO_ACCESS_TOKEN` | Vimeo uploads |
|
|
| `CLOUDCONVERT_ENABLED` / `CLOUDCONVERT_API_KEY` | Format conversion |
|
|
|
|
### Payments
|
|
|
|
| Variable | Purpose |
|
|
|----------|---------|
|
|
| `CHAPA_*` | Chapa secret/public key, webhook, callback/return URLs |
|
|
| `ARIFPAY_*` | Arifpay API key, notify/success/cancel URLs, bank account, … |
|
|
|
|
### Jobs
|
|
|
|
| Variable | Purpose |
|
|
|----------|---------|
|
|
| `ACCOUNT_DELETION_PURGE_ENABLED` | Enable scheduled purge of deleted accounts |
|
|
| `ACCOUNT_DELETION_PURGE_INTERVAL` | Cron / interval setting |
|
|
| `ACCOUNT_DELETION_PURGE_BATCH_SIZE` | Batch size |
|
|
|
|
After changing SQL queries or migrations:
|
|
|
|
```bash
|
|
make sqlc-gen # regenerate gen/db
|
|
make swagger # regenerate docs from handler annotations
|
|
```
|
|
|
|
---
|
|
|
|
## Running the application
|
|
|
|
| Command | Description |
|
|
|---------|-------------|
|
|
| `make air` | Local Air hot-reload (`.air.toml`) |
|
|
| `go run ./cmd/main.go` | Run once without Air |
|
|
| `make run` | `docker compose up` (full stack including `app`) |
|
|
| `make build` | Build app image |
|
|
| `make stop` | `docker compose down` |
|
|
| `make db-up` | Start Postgres + migrate + Mongo only |
|
|
| `make db-down` | Tear down compose **and volumes** (`-v`) |
|
|
|
|
Entry point: `cmd/main.go` (wires config, stores, services, Fiber, cron).
|
|
|
|
---
|
|
|
|
## Database
|
|
|
|
### Migrations
|
|
|
|
- Path: `db/migrations/`
|
|
- Baseline: `000001_Rezina.up.sql` and `000001_Rezina.down.sql` contain the consolidated migration history.
|
|
- This baseline is for a fresh or rebuilt database. Existing databases with a previous `schema_migrations` version need a database reset or a dedicated upgrade migration before using it.
|
|
- Create future incremental migrations: `make migrations/new name=add_something`
|
|
- Apply (Compose migrate service): `make migrations/up`
|
|
|
|
### sqlc
|
|
|
|
- Config: `sqlc.yaml`
|
|
- Queries: `db/query/*.sql`
|
|
- Output: `gen/db/`
|
|
- Regenerate: `make sqlc-gen`
|
|
|
|
**Do not hand-edit `gen/db`.** Change SQL → regenerate.
|
|
|
|
### Seeds
|
|
|
|
| Target | Source |
|
|
|--------|--------|
|
|
| `make seed_demo` | Current course/chapter/lesson demo, chapter quizzes, and role test accounts (`cmd/demo-seed`) |
|
|
| `make seed_data` | `db/data/*.sql` |
|
|
| `make seed_dev_data` | `db/dev_data/*.sql` (+ sequence fix script) |
|
|
|
|
Use `seed_demo` for the current hierarchy. The older SQL seed collections target
|
|
historical schemas. [Public catalog and demo setup](docs/demo-and-public-catalog.md)
|
|
documents anonymous browsing, test credentials, and database setup.
|
|
|
|
### Backup / restore
|
|
|
|
```bash
|
|
make backup # gzip data-only dump under backup/
|
|
make restore # restore latest dump_*.sql.gz
|
|
make restore_file file=... # restore a specific file
|
|
make postgres # psql shell into Compose Postgres
|
|
```
|
|
|
|
---
|
|
|
|
## Makefile reference
|
|
|
|
| Target | Action |
|
|
|--------|--------|
|
|
| `test` | Run `go test ./...` inside Compose `test` service |
|
|
| `coverage` | Coverage for `./internal/...` |
|
|
| `sqlc-gen` | `sqlc generate` |
|
|
| `swagger` | `swag init -g cmd/main.go` |
|
|
| `migrations/new` | New migration pair (`name=...`) |
|
|
| `migrations/up` | Run migrate container |
|
|
| `seed_data` / `seed_dev_data` | Seed SQL |
|
|
| `backup` / `restore` / `restore_file` | Postgres dump helpers |
|
|
| `export_logs` | Export Mongo app logs |
|
|
| `postgres_log` | Tail Postgres container logs |
|
|
|
|
---
|
|
|
|
## API documentation
|
|
|
|
1. **Swagger UI** (when server is running):
|
|
`http://localhost:<PORT>/swagger/index.html`
|
|
2. **Generated artifacts**: `docs/swagger.json`, `docs/swagger.yaml`, `docs/docs.go`
|
|
3. **Postman collections**: `postman/` (FAQ, personas, mobile app versions, dynamic question types, …)
|
|
4. **Feature integration guides**: `docs/*-admin-panel-integration.md` (see [below](#admin-panel-integration-docs))
|
|
|
|
Regenerate after handler / annotation changes:
|
|
|
|
```bash
|
|
make swagger
|
|
```
|
|
|
|
Auth for protected routes: `Authorization: Bearer <access_token>` (JWT). Team members and platform users use role/permission claims checked by middleware (`RequirePermission(...)`).
|
|
|
|
---
|
|
|
|
## Auth, roles & permissions
|
|
|
|
### Platform users (learners / legacy roles)
|
|
|
|
Typical roles include `STUDENT`, `OPEN_LEARNER`, `INSTRUCTOR`, `SUPPORT`, `ADMIN`, `SUPER_ADMIN` (see `internal/domain`).
|
|
|
|
### Team members (admin panel)
|
|
|
|
- Login: `POST /api/v1/team/login` (also Google login / refresh)
|
|
- Invite: `POST /api/v1/team/members/invite` with `team_role` = built-in key (`SUPER_ADMIN`, `ADMIN`, …), custom RBAC **name**, or RBAC **numeric id**
|
|
- Display labels like `"Super Admin"` are normalized to `SUPER_ADMIN` where applicable
|
|
- Permissions: RBAC keys (e.g. `team.members.invite`, `rbac.roles.list`) — prefer permission checks over hard-coded role strings in clients
|
|
|
|
Custom roles live in RBAC tables; migration `000097` allows custom names on `team_members.team_role`.
|
|
|
|
---
|
|
|
|
## Domain overview
|
|
|
|
### Learning content
|
|
|
|
```
|
|
Learning programs
|
|
└── Courses
|
|
└── Modules (top-level)
|
|
└── Lessons (+ video)
|
|
└── Practices → Questions
|
|
```
|
|
|
|
Reorder: program / course / module / lesson ordered-id endpoints (admin).
|
|
|
|
|
|
### Practices & questions
|
|
|
|
- Practices can attach to course / module / lesson parents (multi-parent, unlink)
|
|
- Shared **stimulus blocks**, dynamic **question type definitions** & groups
|
|
- Assessment / evaluation services under `internal/services/assessment` and related packages
|
|
|
|
### Subscriptions
|
|
|
|
- Plans with duration or **one-time lifetime** flags
|
|
- Snapshot, renewal, churn, and revenue analytics on the dashboard endpoint
|
|
- Admin grant / extend / cancel documented in `docs/admin-subscription-grant-extend-cancel-admin-panel-integration.md`
|
|
|
|
---
|
|
|
|
## Integrations
|
|
|
|
| System | Package / area | Notes |
|
|
|--------|----------------|-------|
|
|
| Resend | messenger / email templates | Team invites, OTP, templates |
|
|
| Afro SMS | config `AFROSMS` | SMS OTP / alerts |
|
|
| Chapa | `services/chapa` | Cards / mobile money; webhooks |
|
|
| Arifpay | `services/arifpay` | Alternate checkout |
|
|
| MinIO | `services/minio` | Uploads (images, files) |
|
|
| Vimeo | `services/vimeo` | Video upload + progress |
|
|
| CloudConvert | `services/cloudconvert` | Optional conversion |
|
|
| Firebase / FCM | notifications | Push |
|
|
| Google / Apple | authentication | Social sign-in |
|
|
|
|
---
|
|
|
|
## Project structure
|
|
|
|
```
|
|
Rezina-BackEnd/
|
|
├── cmd/main.go # Entry + DI wiring
|
|
├── db/
|
|
│ ├── migrations/ # golang-migrate SQL
|
|
│ ├── query/ # sqlc query files
|
|
│ ├── data/ # Production-ish seeds
|
|
│ ├── dev_data/ # Dev-only seeds
|
|
│ └── scripts/ # Utility SQL
|
|
├── gen/db/ # sqlc output (generated)
|
|
├── docs/ # Swagger + integration MD guides
|
|
├── postman/ # API collections
|
|
├── internal/
|
|
│ ├── config/ # Env loading & validation
|
|
│ ├── domain/ # Models & errors
|
|
│ ├── ports/ # Interfaces
|
|
│ ├── repository/ # DB adapters
|
|
│ ├── services/ # Business + third-party
|
|
│ ├── web_server/ # Fiber app, routes, handlers, JWT, cron
|
|
│ ├── infrastructure/ # Shared infra helpers
|
|
│ ├── logger/ # slog + Mongo logging
|
|
│ ├── mocks/ # Test mocks
|
|
│ └── pkgs/ # Shared packages (e.g. MinIO client)
|
|
├── docker-compose.yml
|
|
├── Dockerfile
|
|
├── makefile
|
|
├── sqlc.yaml
|
|
├── .air.toml
|
|
└── README.md
|
|
```
|
|
|
|
Key route registration: `internal/web_server/routes.go`
|
|
|
|
---
|
|
|
|
## Testing & code quality
|
|
|
|
```bash
|
|
make test # full module tests in Docker
|
|
go test ./internal/... # local (requires reachable DB for some packages)
|
|
make coverage # func coverage report under coverage/
|
|
```
|
|
|
|
Guidelines:
|
|
|
|
- Prefer domain errors (`internal/domain`) surfaced as consistent HTTP error payloads
|
|
- Keep handlers thin; put rules in services
|
|
- Add/adjust sqlc queries rather than raw SQL in services when possible
|
|
- Update Swagger comments on public handlers
|
|
|
|
---
|
|
|
|
## Admin panel integration docs
|
|
|
|
Detailed contracts for the admin UI live under `docs/`:
|
|
|
|
| Doc | Topic |
|
|
|-----|--------|
|
|
| `team-member-invitation-admin-panel-integration.md` | Invite / accept / roles |
|
|
| `team-member-refresh-token-admin-panel-integration.md` | Refresh session |
|
|
| `team-password-reset-admin-panel-integration.md` | Team password reset |
|
|
| `csv-export-admin-panel-integration.md` | CSV exports |
|
|
| `bulk-scheduled-notifications-integration.md` | Bulk / scheduled notify |
|
|
| `file-upload-admin-panel-integration.md` | Uploads |
|
|
| `vimeo-video-upload-progress-admin-panel-integration.md` | Vimeo progress |
|
|
| `faq-admin-panel-integration.md` | FAQs |
|
|
| `ratings-admin-panel-integration.md` | App ratings |
|
|
| `activity-logs-admin-panel-integration.md` | Activity logs |
|
|
| `personas-admin-panel-integration.md` | Personas |
|
|
| `admin-subscription-grant-extend-cancel-admin-panel-integration.md` | Admin sub lifecycle |
|
|
| `practice-*-admin-panel-integration.md` | Practice parents, stimulus, associations |
|
|
| `question-type-*-admin-panel-integration.md` | Dynamic question types |
|
|
| `chapa-direct-charge-client-app-integration.md` | Mobile Chapa direct charge |
|
|
|
|
---
|
|
|
|
## Deployment notes
|
|
|
|
- Primary deploy branch: **`production`**
|
|
- Build: multi-stage `Dockerfile` (`builder` / `runner`); binary served as `/app/bin/web`
|
|
- Ensure migrations run before/with deploy (`migrate` service or CI step)
|
|
- Configure production `DB_URL`, JWT, payment webhooks, `TEAM_*_BASE_URL` to the live admin origin
|
|
- Never expose MinIO/pgAdmin ports publicly without auth hardening
|
|
|
|
---
|
|
|
|
## Troubleshooting
|
|
|
|
| Issue | What to check |
|
|
|-------|----------------|
|
|
| Config fails on boot | Required env vars in `internal/config` (JWT, DB, ENV, PORT, …) |
|
|
| sqlc / compile errors after SQL change | Run `make sqlc-gen`; commit `gen/db` |
|
|
| Migrations fail | Postgres healthy? Correct `DB_URL`? Dirty schema_migrations? |
|
|
| Invite email fails | `RESEND_*`, `TEAM_INVITE_BASE_URL` |
|
|
| `invalid team role` | Send `SUPER_ADMIN` / RBAC name / id — not only a UI label (backend also accepts display-style built-ins) |
|
|
| 403 on admin APIs | Team JWT missing permission key; check RBAC role permissions |
|
|
| Payment webhooks | Public callback URLs + gateway secrets match env |
|
|
|
|
---
|
|
|
|
## License
|
|
|
|
Proprietary — Yaltopia / Rezina. Internal use only unless otherwise licensed.
|