Go to file
2026-09-24 15:27:18 +03:00
.cursor subscription expiration six 2026-07-22 07:38:31 -07:00
.idea added inittal assessment feature 2025-12-29 07:59:24 -08:00
.vscode minimal registeration implementation 2026-01-09 06:35:22 -08:00
cmd Improve web checkout auth: phone normalization and Google web OAuth. 2026-08-24 16:48:53 +03:00
db Add archived subscription plan cleanup before unique index migration 2026-09-24 15:27:18 +03:00
docs Add archived subscription plan cleanup before unique index migration 2026-09-24 15:27:18 +03:00
gen/db Add free subscription plans and enforce unique billing periods. 2026-09-23 21:32:33 +03:00
internal Add free subscription plans and enforce unique billing periods. 2026-09-23 21:32:33 +03:00
postman feat: paginate question type definitions list API 2026-06-05 04:33:41 -07:00
.air.toml init 2025-03-26 23:50:19 +03:00
.DS_Store test logs 2026-01-12 09:47:41 +03:00
.gitignore removed build files 2026-02-27 01:15:38 -08:00
db.sql fix: transfer not showing online bet issue 2025-06-16 16:24:42 +03:00
docker-compose.yml Fix scheduled notification creator FK and default app timezone to EAT. 2026-08-16 18:52:09 +03:00
Dockerfile updated Dockerfile to use 1.25.5 Golang version 2026-01-22 06:24:11 -08:00
go.mod feat: expire stale pending payments with background worker 2026-06-09 04:10:17 -07:00
go.sum MinIO integration + speaking implementation adjustment 2026-03-12 07:06:16 -07:00
makefile removed all unnecessary data seed 2026-04-10 03:32:07 -07:00
new.env profile picture, birthday format and refresh token expiry fixes 2026-01-28 09:24:31 -08:00
README.md subscription plan creation pricing fix 2026-09-10 14:23:13 +03:00
sqlc.yaml fix: refactored the transactions into shop_transactions 2025-07-02 03:19:59 +03:00
test.html transaction maker-checker fixes 2025-07-11 15:48:59 +03:00

Yimaru Backend API

Golang API for Yimaru Academy, an LMS and exam-prep platform. It serves the mobile learner apps and the Yimaru Admin panel: authentication, content (Learn English + Duolingo/IELTS), practices/questions, subscriptions & payments, team RBAC, analytics, notifications, and more.

Module Yimaru-Backend
Language Go 1.25 (see go.mod)
HTTP Fiber
DB PostgreSQL 16 (primary) + MongoDB (app logs)
SQL sqlc + golang-migrate
API docs Swagger / OpenAPI (docs/, /swagger/*)
Remote https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd.git
Branches main, production (deploy from production)

Table of contents

  1. Technical overview (presentations)
  2. Features
  3. Architecture
  4. Prerequisites
  5. Quick start
  6. Environment configuration
  7. Running the application
  8. Database
  9. Makefile reference
  10. API documentation
  11. Auth, roles & permissions
  12. Domain overview
  13. Integrations
  14. Project structure
  15. Testing & code quality
  16. Admin panel integration docs
  17. Deployment notes
  18. Troubleshooting

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 matching go.mod (1.25+)
  • Docker + Docker Compose
  • Air — live reload (make air)
  • sqlc
  • migrate CLI
  • swag — regenerate OpenAPI (make swagger)

Optional: psql, MongoDB tools for log export.


Quick start

git clone https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd.git
cd Yimaru-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. 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:<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:

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

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)

Regenerate after handler / annotation changes:

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/
│   ├── 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

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.