From 703f2b00416f7d9d03a02194c1f2735602e5ff9a Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Thu, 30 Jul 2026 01:14:51 -0700 Subject: [PATCH] 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 --- README.md | 727 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 458 insertions(+), 269 deletions(-) diff --git a/README.md b/README.md index a1cd102e..e3a7e94f 100644 --- a/README.md +++ b/README.md @@ -1,281 +1,470 @@ # 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) -- [Environment Configuration](#environment-configuration) -- [Running the Application](#running-the-application) -- [Database Management](#database-management) -- [Testing and Code Quality](#testing-and-code-quality) -- [API Documentation](#api-documentation) -- [Project Structure](#project-structure) -- [Core Services Overview](#core-services-overview) -- [Roles and Access Control](#roles-and-access-control) -- [Code Organization Guidelines](#code-organization-guidelines) -- [Further Details](#further-details) +| | | +|---|---| +| **Module** | `Yimaru-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/Yimaru/Yimaru-BackEnd.git` | +| **Branches** | `main`, `production` (deploy from `production`) | --- -## Installation -Before running the application, ensure you have the following installed: +## Table of contents -- [Go](https://golang.org/doc/install) (1.20+ recommended) -- [Docker](https://www.docker.com/) -- [Air](https://github.com/cosmtrek/air) — for live reloading during development -- [SQLC](https://sqlc.dev) -- [Migrate](https://github.com/golang-migrate/migrate) -- [Swag](https://github.com/swaggo/swag) +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) -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 -git clone https://github.com/your-org/Yimaru-backend.git -cd Yimaru-backend +git clone https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd.git +cd Yimaru-BackEnd -├── cmd/ -│ └── main.go # Application entry point -├── internal/ -│ ├── config/ # Configuration and environment loading -│ │ └── config.go -│ ├── domain/ # Domain models, constants, and roles -│ │ ├── course.go # Course and lesson structures -│ │ └── roles.go # Role definitions (e.g., RoleAdmin, RoleInstructor) -│ ├── repository/ # Database interaction layer -│ │ ├── course.go # Course-related queries -│ │ ├── lesson.go # Lesson-related database functions -│ │ ├── user.go # User repository methods -│ │ └── ... # Other repository files -│ ├── services/ # Business logic and core services -│ │ ├── course/ -│ │ │ └── service.go # Course management logic -│ │ └── quiz/ -│ │ ├── service.go # Quiz management and evaluation logic -│ │ └── eval.go # Evaluation logic for student progress -│ └── web_server/ # HTTP handlers, routes, middleware, and cron jobs -│ ├── cron.go # Scheduled background tasks -│ └── handlers/ -│ ├── course_handler.go # Course-related API endpoints -│ ├── user_handler.go # User-related endpoints -│ └── ... # Additional handlers +# 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. Seed (optional, after migrations) +make seed_data # db/data/*.sql +# make seed_dev_data # db/dev_data/*.sql (dev only) + +# 4. Run API with live reload +make air +# or: go run ./cmd/main.go +``` + +Health check: open Swagger at `http://localhost:/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:/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:/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 ` (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/ -│ └── migrations/ # SQL migration files -├── docs/ -│ ├── swagger/ # Swagger/OpenAPI documentation files -│ └── docs.go # Swaggo-generated docs -├── gen/ -│ └── db/ # SQLC-generated Go code for database access -├── makefile # Development and operations commands -├── .env # Environment configuration file -└── README.md # Project documentation - - -1. Course Category (Top-Level Classification) - -Table: course_categories - -Purpose: -Logical grouping of courses (e.g., Learning English, Other Courses). - -Key Fields: - -id – Primary identifier - -name – Category name - -is_active – Soft enable/disable - -created_at – Audit timestamp - -Relationships: - -One Course Category → Many Course Sub-categories - -Course Category -└── Course Sub-categories[] - -2. Course Sub-category - -Table: course_sub_categories - -Purpose: -A grouping within a category (e.g., Speaking, Listening under Learning English). - -Key Fields: - -category_id – FK → course_categories.id - -title, description - -is_active - -Relationships: - -Belongs to one Course Category - -Has many Courses - -Course Category -└── Course Sub-category - └── Courses[] - -3. Course - -Table: courses - -Purpose: -A learning unit within a sub-category representing different skill levels -(e.g., Beginner, Intermediate, Advanced). - -Key Fields: - -sub_category_id – FK → course_sub_categories.id - -title, description - -thumbnail - -display_order - -level – BEGINNER | INTERMEDIATE | ADVANCED - -is_active - -Relationships: - -Belongs to one Course Sub-category - -Has many Course Videos - -Has many Practices - -Course Sub-category -└── Course - ├── Course Videos[] - └── Practices[] - -4. Course Video - -Table: course_videos - -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 \ No newline at end of file +│ ├── 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 / Yimaru Academy. Internal use only unless otherwise licensed.