Expand the backend README with setup, architecture, and operations.

Document env vars, makefile targets, domain model, integrations, and admin integration guides.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-30 01:14:51 -07:00
parent d276e3060f
commit 703f2b0041

727
README.md
View File

@ -1,281 +1,470 @@
# Yimaru Backend API # Yimaru Backend API
Yimaru Backend is the server-side application that powers the Yimaru online learning system. It manages courses, lessons, quizzes, student progress, instructor content, and administrative operations for institutions and users on the platform. Go API for **Yimaru Academy**, an LMS and exam-prep platform. It serves the mobile learner apps and the [Yimaru Admin](https://gitea.yaltopia.com/Yimaru/Yimaru-Admin) panel: authentication, content (Learn English + Duolingo/IELTS), practices/questions, subscriptions & payments, team RBAC, analytics, notifications, and more.
## Table of Content | | |
|---|---|
- [Installation](#installation) | **Module** | `Yimaru-Backend` |
- [Environment Configuration](#environment-configuration) | **Language** | Go `1.25` (see `go.mod`) |
- [Running the Application](#running-the-application) | **HTTP** | [Fiber](https://gofiber.io/) |
- [Database Management](#database-management) | **DB** | PostgreSQL 16 (primary) + MongoDB (app logs) |
- [Testing and Code Quality](#testing-and-code-quality) | **SQL** | [sqlc](https://sqlc.dev) + [golang-migrate](https://github.com/golang-migrate/migrate) |
- [API Documentation](#api-documentation) | **API docs** | Swagger / OpenAPI (`docs/`, `/swagger/*`) |
- [Project Structure](#project-structure) | **Remote** | `https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd.git` |
- [Core Services Overview](#core-services-overview) | **Branches** | `main`, `production` (deploy from `production`) |
- [Roles and Access Control](#roles-and-access-control)
- [Code Organization Guidelines](#code-organization-guidelines)
- [Further Details](#further-details)
--- ---
## Installation ## Table of contents
Before running the application, ensure you have the following installed:
- [Go](https://golang.org/doc/install) (1.20+ recommended) 1. [Features](#features)
- [Docker](https://www.docker.com/) 2. [Architecture](#architecture)
- [Air](https://github.com/cosmtrek/air) — for live reloading during development 3. [Prerequisites](#prerequisites)
- [SQLC](https://sqlc.dev) 4. [Quick start](#quick-start)
- [Migrate](https://github.com/golang-migrate/migrate) 5. [Environment configuration](#environment-configuration)
- [Swag](https://github.com/swaggo/swag) 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)
Clone the repository: ---
## Features
- **Learners**: registration/login (email OTP, Google, Apple), profiles, field options, progress
- **Learn English LMS**: programs → courses → modules → lessons; practices & questions; video engagement
- **Exam prep (Duolingo / IELTS)**: catalog courses → units → modules → lessons; reorder APIs; shared stimulus blocks
- **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)
---
## 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 base path: **`/api/v1`** (see Swagger `@BasePath` and route groups).
---
## 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 ```bash
git clone https://github.com/your-org/Yimaru-backend.git git clone https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd.git
cd Yimaru-backend cd Yimaru-BackEnd
├── cmd/ # 1. Environment
│ └── main.go # Application entry point cp .env .env.local # or create .env from the table below
├── internal/ # Edit DB_URL, JWT_KEY, PORT, RESEND_*, etc.
│ ├── config/ # Configuration and environment loading
│ │ └── config.go # 2. Infrastructure
│ ├── domain/ # Domain models, constants, and roles make db-up # Postgres + migrate + Mongo (detached)
│ │ ├── course.go # Course and lesson structures
│ │ └── roles.go # Role definitions (e.g., RoleAdmin, RoleInstructor) # 3. Seed (optional, after migrations)
│ ├── repository/ # Database interaction layer make seed_data # db/data/*.sql
│ │ ├── course.go # Course-related queries # make seed_dev_data # db/dev_data/*.sql (dev only)
│ │ ├── lesson.go # Lesson-related database functions
│ │ ├── user.go # User repository methods # 4. Run API with live reload
│ │ └── ... # Other repository files make air
│ ├── services/ # Business logic and core services # or: go run ./cmd/main.go
│ │ ├── course/ ```
│ │ │ └── service.go # Course management logic
│ │ └── quiz/ Health check: open Swagger at `http://localhost:<PORT>/swagger/index.html`.
│ │ ├── service.go # Quiz management and evaluation logic
│ │ └── eval.go # Evaluation logic for student progress Default Compose Postgres (from `docker-compose.yml`):
│ └── web_server/ # HTTP handlers, routes, middleware, and cron jobs
│ ├── cron.go # Scheduled background tasks | Setting | Value |
│ └── handlers/ |---------|--------|
│ ├── course_handler.go # Course-related API endpoints | User / password / DB | `root` / `secret` / `gh` |
│ ├── user_handler.go # User-related endpoints | Host port mapping | `5592` → container (see compose file; confirm with `docker compose ps`) |
│ └── ... # Additional handlers | 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/`
- Create: `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_data` | `db/data/*.sql` |
| `make seed_dev_data` | `db/dev_data/*.sql` (+ sequence fix script) |
### 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
### Learn English content
```
Learning programs
└── Courses
└── Modules (top-level)
└── Lessons (+ video)
└── Practices → Questions
```
Reorder: program / course / module / lesson ordered-id endpoints (admin).
### Exam prep (Duolingo / IELTS)
```
Catalog courses
└── Units
└── Unit modules
└── Lessons
└── Lesson practices
```
Reorder APIs mirror the LMS hierarchy for catalog courses, units, modules, and lessons.
### 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
```
Yimaru-BackEnd/
├── cmd/main.go # Entry + DI wiring
├── db/ ├── db/
│ └── migrations/ # SQL migration files │ ├── migrations/ # golang-migrate SQL
├── docs/ │ ├── query/ # sqlc query files
│ ├── swagger/ # Swagger/OpenAPI documentation files │ ├── data/ # Production-ish seeds
│ └── docs.go # Swaggo-generated docs │ ├── dev_data/ # Dev-only seeds
├── gen/ │ └── scripts/ # Utility SQL
│ └── db/ # SQLC-generated Go code for database access ├── gen/db/ # sqlc output (generated)
├── makefile # Development and operations commands ├── docs/ # Swagger + integration MD guides
├── .env # Environment configuration file ├── postman/ # API collections
└── README.md # Project documentation ├── internal/
│ ├── config/ # Env loading & validation
│ ├── domain/ # Models & errors
1. Course Category (Top-Level Classification) │ ├── ports/ # Interfaces
│ ├── repository/ # DB adapters
Table: course_categories │ ├── services/ # Business + third-party
│ ├── web_server/ # Fiber app, routes, handlers, JWT, cron
Purpose: │ ├── infrastructure/ # Shared infra helpers
Logical grouping of courses (e.g., Learning English, Other Courses). │ ├── logger/ # slog + Mongo logging
│ ├── mocks/ # Test mocks
Key Fields: │ └── pkgs/ # Shared packages (e.g. MinIO client)
├── docker-compose.yml
id – Primary identifier ├── Dockerfile
├── makefile
name – Category name ├── sqlc.yaml
├── .air.toml
is_active – Soft enable/disable └── README.md
```
created_at – Audit timestamp
Key route registration: `internal/web_server/routes.go`.
Relationships:
---
One Course Category → Many Course Sub-categories
## Testing & code quality
Course Category
└── Course Sub-categories[] ```bash
make test # full module tests in Docker
2. Course Sub-category go test ./internal/... # local (requires reachable DB for some packages)
make coverage # func coverage report under coverage/
Table: course_sub_categories ```
Purpose: Guidelines:
A grouping within a category (e.g., Speaking, Listening under Learning English).
- Prefer domain errors (`internal/domain`) surfaced as consistent HTTP error payloads
Key Fields: - Keep handlers thin; put rules in services
- Add/adjust sqlc queries rather than raw SQL in services when possible
category_id – FK → course_categories.id - Update Swagger comments on public handlers
title, description ---
is_active ## Admin panel integration docs
Relationships: Detailed contracts for the admin UI live under `docs/`:
Belongs to one Course Category | Doc | Topic |
|-----|--------|
Has many Courses | `team-member-invitation-admin-panel-integration.md` | Invite / accept / roles |
| `team-member-refresh-token-admin-panel-integration.md` | Refresh session |
Course Category | `team-password-reset-admin-panel-integration.md` | Team password reset |
└── Course Sub-category | `csv-export-admin-panel-integration.md` | CSV exports |
└── Courses[] | `bulk-scheduled-notifications-integration.md` | Bulk / scheduled notify |
| `file-upload-admin-panel-integration.md` | Uploads |
3. Course | `vimeo-video-upload-progress-admin-panel-integration.md` | Vimeo progress |
| `faq-admin-panel-integration.md` | FAQs |
Table: courses | `ratings-admin-panel-integration.md` | App ratings |
| `activity-logs-admin-panel-integration.md` | Activity logs |
Purpose: | `personas-admin-panel-integration.md` | Personas |
A learning unit within a sub-category representing different skill levels | `admin-subscription-grant-extend-cancel-admin-panel-integration.md` | Admin sub lifecycle |
(e.g., Beginner, Intermediate, Advanced). | `practice-*-admin-panel-integration.md` | Practice parents, stimulus, associations |
| `question-type-*-admin-panel-integration.md` | Dynamic question types |
Key Fields: | `chapa-direct-charge-client-app-integration.md` | Mobile Chapa direct charge |
sub_category_id – FK → course_sub_categories.id ---
title, description ## Deployment notes
thumbnail - Primary deploy branch: **`production`**
- Build: multi-stage `Dockerfile` (`builder` / `runner`); binary served as `/app/bin/web`
display_order - 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
level – BEGINNER | INTERMEDIATE | ADVANCED - Never expose MinIO/pgAdmin ports publicly without auth hardening
is_active ---
Relationships: ## Troubleshooting
Belongs to one Course Sub-category | Issue | What to check |
|-------|----------------|
Has many Course Videos | 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` |
Has many Practices | Migrations fail | Postgres healthy? Correct `DB_URL`? Dirty schema_migrations? |
| Invite email fails | `RESEND_*`, `TEAM_INVITE_BASE_URL` |
Course Sub-category | `invalid team role` | Send `SUPER_ADMIN` / RBAC name / id — not only a UI label (backend also accepts display-style built-ins) |
└── Course | 403 on admin APIs | Team JWT missing permission key; check RBAC role permissions |
├── Course Videos[] | Payment webhooks | Public callback URLs + gateway secrets match env |
└── Practices[]
---
4. Course Video
## License
Table: course_videos
Proprietary — Yaltopia / Yimaru Academy. Internal use only unless otherwise licensed.
Purpose:
Video learning content attached to a course.
Key Fields:
course_id – FK → courses.id
title, description
video_url
duration, resolution
Publishing controls:
is_published
publish_date
visibility
instructor_id
thumbnail
display_order
is_active
Relationships:
Belongs to one Course
Course
└── Course Video
5. Practice
Table: practices
Purpose:
Exercises or assessments that belong to a course.
Key Fields:
course_id – FK → courses.id
title, description
banner_image
persona
is_active
Relationships:
Belongs to one Course
One Practice → Many Practice Questions
Course
└── Practice
└── Practice Questions[]
6. Practice Question
Table: practice_questions
Purpose:
Individual questions within a practice session.
Key Fields:
practice_id – FK → practices.id
question
Voice support:
question_voice_prompt
sample_answer_voice_prompt
sample_answer
tips
type – MCQ | TRUE_FALSE | SHORT
Relationships:
Belongs to one Practice
Practice
└── Practice Question
Complete Hierarchical Flow (Compact View)
Course Category
└── Course Sub-category
└── Course (with levels: BEGINNER, INTERMEDIATE, ADVANCED)
├── Course Video
└── Practice
└── Practice Question
Architectural Observations
Simple three-level hierarchy: Category → Sub-category → Course
Level is now a property of Course, not a separate entity
Cascade deletes ensure referential integrity
Schema is well-suited for:
LMS platforms
Progressive learning apps
Video + assessment-based education systems