diff --git a/docs/Yimaru_Backend_Developer_Documentation.docx b/docs/Yimaru_Backend_Developer_Documentation.docx new file mode 100644 index 00000000..99a3555c Binary files /dev/null and b/docs/Yimaru_Backend_Developer_Documentation.docx differ diff --git a/docs/generate_backend_developer_docx.py b/docs/generate_backend_developer_docx.py new file mode 100644 index 00000000..ca2c3c81 --- /dev/null +++ b/docs/generate_backend_developer_docx.py @@ -0,0 +1,754 @@ +#!/usr/bin/env python3 +"""Generate Yimaru Backend Developer Documentation (.docx).""" + +from datetime import date +from pathlib import Path + +from docx import Document +from docx.enum.style import WD_STYLE_TYPE +from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING +from docx.oxml.ns import qn +from docx.shared import Inches, Pt, RGBColor + +OUT = Path(__file__).resolve().parent / "Yimaru_Backend_Developer_Documentation.docx" + + +def set_run_font(run, name="Calibri", size=11, bold=False, italic=False, color=None): + run.font.name = name + run._element.rPr.rFonts.set(qn("w:eastAsia"), name) + run.font.size = Pt(size) + run.bold = bold + run.italic = italic + if color is not None: + run.font.color.rgb = color + + +def add_para(doc, text, *, style=None, size=11, bold=False, italic=False, space_after=8, space_before=0, align=None): + p = doc.add_paragraph(style=style) if style else doc.add_paragraph() + if align is not None: + p.alignment = align + pf = p.paragraph_format + pf.space_after = Pt(space_after) + pf.space_before = Pt(space_before) + pf.line_spacing_rule = WD_LINE_SPACING.SINGLE + run = p.add_run(text) + set_run_font(run, size=size, bold=bold, italic=italic) + return p + + +def add_heading_custom(doc, text, level=1): + # Use built-in heading styles for TOC-friendly structure + h = doc.add_heading(text, level=level) + for run in h.runs: + set_run_font(run, name="Calibri", size={1: 18, 2: 14, 3: 12}.get(level, 11), bold=True) + if level == 1: + run.font.color.rgb = RGBColor(0x5E, 0x1F, 0x70) + elif level == 2: + run.font.color.rgb = RGBColor(0x9E, 0x28, 0x91) + return h + + +def add_bullets(doc, items, size=11): + for item in items: + p = doc.add_paragraph(style="List Bullet") + p.paragraph_format.space_after = Pt(3) + run = p.add_run(item) + set_run_font(run, size=size) + + +def add_numbered(doc, items, size=11): + for item in items: + p = doc.add_paragraph(style="List Number") + p.paragraph_format.space_after = Pt(3) + run = p.add_run(item) + set_run_font(run, size=size) + + +def add_code_block(doc, text): + for line in text.strip("\n").splitlines(): + p = doc.add_paragraph() + p.paragraph_format.space_after = Pt(0) + p.paragraph_format.space_before = Pt(0) + p.paragraph_format.left_indent = Inches(0.15) + run = p.add_run(line if line else " ") + set_run_font(run, name="Consolas", size=9, color=RGBColor(0x33, 0x33, 0x33)) + doc.add_paragraph().paragraph_format.space_after = Pt(8) + + +def add_table(doc, headers, rows): + table = doc.add_table(rows=1 + len(rows), cols=len(headers)) + table.style = "Table Grid" + hdr = table.rows[0].cells + for i, h in enumerate(headers): + hdr[i].text = "" + p = hdr[i].paragraphs[0] + run = p.add_run(h) + set_run_font(run, size=10, bold=True, color=RGBColor(0x5E, 0x1F, 0x70)) + for r_i, row in enumerate(rows): + cells = table.rows[r_i + 1].cells + for c_i, val in enumerate(row): + cells[c_i].text = "" + p = cells[c_i].paragraphs[0] + run = p.add_run(str(val)) + set_run_font(run, size=9) + doc.add_paragraph().paragraph_format.space_after = Pt(10) + + +def configure_styles(doc): + styles = doc.styles + normal = styles["Normal"] + normal.font.name = "Calibri" + normal.font.size = Pt(11) + normal._element.rPr.rFonts.set(qn("w:eastAsia"), "Calibri") + + +def build(): + doc = Document() + configure_styles(doc) + + section = doc.sections[0] + section.top_margin = Inches(0.9) + section.bottom_margin = Inches(0.9) + section.left_margin = Inches(1.0) + section.right_margin = Inches(1.0) + + # ----- Title page ----- + for _ in range(3): + doc.add_paragraph() + add_para( + doc, + "Yimaru Backend", + size=28, + bold=True, + align=WD_ALIGN_PARAGRAPH.CENTER, + space_after=6, + ) + add_para( + doc, + "Developer Documentation", + size=20, + bold=True, + align=WD_ALIGN_PARAGRAPH.CENTER, + space_after=18, + ) + add_para( + doc, + "A practical guide for engineers working on the Yimaru Academy API", + size=12, + italic=True, + align=WD_ALIGN_PARAGRAPH.CENTER, + space_after=28, + ) + add_para( + doc, + f"Version aligned with repository module Yimaru-Backend (Go 1.25)\n" + f"Document generated {date.today().isoformat()}\n" + f"Audience: Backend developers & maintainers\n" + f"Source: https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd.git", + size=10, + align=WD_ALIGN_PARAGRAPH.CENTER, + space_after=12, + ) + add_para( + doc, + "Internal / proprietary — Yaltopia Tech · Yimaru Academy", + size=9, + italic=True, + align=WD_ALIGN_PARAGRAPH.CENTER, + ) + doc.add_page_break() + + # ----- Intro ----- + add_heading_custom(doc, "1. Introduction", 1) + add_para( + doc, + "If you are opening this document because you just joined the Yimaru backend team " + "(or you are returning after a few months away), welcome. The codebase is larger than " + "it looks at first glance: one Fiber HTTP server, two content trees (Learn English LMS " + "and exam-prep / Duolingo–IELTS), a full subscription and payments stack, team RBAC for " + "the admin panel, analytics that the product team actually looks at every week, and a " + "fair amount of glue to MinIO, Vimeo, Resend, SMS, and payment gateways.", + ) + add_para( + doc, + "This guide is written the way we wish someone had written it for us—less “list of " + "folders,” more “how we actually ship changes without breaking learners at 9pm.” It " + "assumes you are comfortable with Go, SQL, and HTTP APIs. It does not assume you already " + "know our sqlc conventions, permission keys, or why team_role and users.role are not the " + "same thing.", + ) + add_para( + doc, + "Companion surfaces you will touch constantly:", + space_after=4, + ) + add_bullets( + doc, + [ + "Admin panel: https://gitea.yaltopia.com/Yimaru/Yimaru-Admin.git (consumes /api/v1)", + "Swagger UI on a running server: /swagger/index.html", + "Feature contracts for admin: docs/*-admin-panel-integration.md in this repo", + "README.md at the repo root (quick start & env tables)", + ], + ) + + add_heading_custom(doc, "1.1 What this service is responsible for", 2) + add_para( + doc, + "Yimaru-Backend is the system of record for learner accounts, learning content, " + "practice assessments, subscription entitlements, payment attempts, team (staff) " + "accounts, RBAC permissions, operational notifications, support issues, FAQs, ratings, " + "and the analytics dashboard used by admins. Mobile apps and the admin SPA are clients; " + "business rules live here, not in the UI.", + ) + + add_heading_custom(doc, "1.2 Branches and release posture", 2) + add_para( + doc, + "We deploy from the production branch. main exists and is useful for long-lived work, " + "but if you are fixing something that needs to go live, land it on production (or merge " + "into production) and treat that as the source of truth for the live API. Always run " + "migrations with the same care you would on a bank ledger—because for subscriptions and " + "payments, it almost is.", + ) + + # ----- Architecture ----- + add_heading_custom(doc, "2. Architecture overview", 1) + add_para( + doc, + "We use a pragmatic ports-and-adapters layout. Handlers should stay thin. Services own " + "orchestration and invariants. Repositories talk to Postgres through sqlc-generated " + "code. Domain types and domain errors live in internal/domain so that HTTP mapping stays " + "consistent.", + ) + add_code_block( + doc, + """ +cmd/main.go + └─ config.NewConfig() + └─ wire repositories, services, Fiber App + └─ httpserver.App.Run() + +Request path (typical protected route): + Fiber → CORS / recover → authMiddleware → RequirePermission("…") + → optional subscription / content-access middleware + → handler → service → repository (ports) → gen/db (sqlc) → PostgreSQL +""", + ) + add_table( + doc, + ["Layer", "Package", "You put here…"], + [ + ["Entry / DI", "cmd/main.go", "Construction only; avoid business logic"], + ["HTTP", "internal/web_server", "Routes, middleware, handlers, validators, workers"], + ["Domain", "internal/domain", "Structs, enums, Err*, request DTOs"], + ["Ports", "internal/ports", "Store interfaces the services depend on"], + ["Services", "internal/services/*", "Use-cases, external HTTP clients"], + ["Repository", "internal/repository", "Implement ports using sqlc Queries"], + ["SQL", "db/query, db/migrations", "Source of truth; regenerate gen/db"], + ["Generated", "gen/db", "Never hand-edit"], + ["Config", "internal/config", "Env loading & validation"], + ["Logs", "internal/logger", "slog + optional Mongo app logs"], + ], + ) + add_para( + doc, + "HTTP framework: Fiber v2 with Sonic JSON. Auth: JWT Bearer tokens. Primary database: " + "PostgreSQL 16. Application logs may also land in MongoDB. Object storage: MinIO when " + "enabled. Live reload in local dev: Air (.air.toml).", + space_before=6, + ) + + add_heading_custom(doc, "2.1 Mental model for content", 2) + add_para( + doc, + "There are two parallel hierarchies. Mixing them in your head is the fastest way to " + "open the wrong handler file.", + space_after=6, + ) + add_para(doc, "Learn English (LMS)", bold=True, space_after=2) + add_code_block( + doc, + """ +Programs + └── Courses + └── Modules + └── Lessons (+ video engagement) + └── Practices → Questions / stimulus blocks +""", + ) + add_para(doc, "Exam prep / Duolingo–IELTS", bold=True, space_after=2) + add_code_block( + doc, + """ +Catalog courses + └── Units + └── Unit modules + └── Lessons + └── Lesson practices +""", + ) + add_para( + doc, + "Practices can attach to multiple parents (course / module / lesson, or exam-prep " + "equivalents). Unlink and multi-parent update endpoints exist—read the practice " + "integration docs before changing parent semantics.", + ) + + # ----- Local setup ----- + add_heading_custom(doc, "3. Local development setup", 1) + add_para( + doc, + "You will want Docker for Postgres (and usually Mongo + MinIO). Running the API itself " + "with Air on the host is the pleasant path for day-to-day coding.", + ) + add_heading_custom(doc, "3.1 Tooling checklist", 2) + add_bullets( + doc, + [ + "Go matching go.mod (currently 1.25.x)", + "Docker Desktop / Compose", + "Air (live reload)", + "sqlc CLI", + "golang-migrate CLI", + "swag (Swagger codegen)", + "Optional: psql, Mongo shell tools", + ], + ) + add_heading_custom(doc, "3.2 First-time bootstrap", 2) + add_numbered( + doc, + [ + "Clone https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd.git and check out production (or the branch your team uses).", + "Copy or create .env. Ask a teammate for a working local template—never invent payment webhook secrets.", + "make db-up — brings up Postgres, runs migrations container, starts Mongo.", + "Optionally make seed_data and/or make seed_dev_data.", + "make air — or go run ./cmd/main.go", + "Open Swagger and hit a health/simple route to confirm boot.", + ], + ) + add_para( + doc, + "Compose defaults (see docker-compose.yml): Postgres user root, password secret, " + "database gh. Host port mapping can look unusual (check docker compose ps—do not assume " + "5432). In-network DSN used by the migrate service is " + "postgresql://root:secret@postgres:5432/gh?sslmode=disable. pgAdmin is exposed around " + "port 5030; MinIO API/console 9000/9001; Mongo mapped near 27021.", + space_before=6, + ) + + add_heading_custom(doc, "3.3 Day-to-day commands you will actually use", 2) + add_table( + doc, + ["Command", "When"], + [ + ["make air", "Iterating on Go code"], + ["make sqlc-gen", "After editing db/query/*.sql or migrations that change schema used by queries"], + ["make migrations/new name=…", "New schema change"], + ["make migrations/up", "Apply migrations via Compose migrate service"], + ["make swagger", "After changing swag annotations on handlers"], + ["make test / go test ./internal/…", "Before pushing risky changes"], + ["make backup", "Before destructive local experiments"], + ], + ) + + # ----- Config ----- + add_heading_custom(doc, "4. Configuration and secrets", 1) + add_para( + doc, + "Configuration is loaded in internal/config via godotenv and validated at startup. If " + "the process dies immediately, read the config error—half the “it won’t start” tickets " + "are a missing JWT_KEY, bad DB_URL, or ENV not set.", + ) + add_heading_custom(doc, "4.1 Core process settings", 2) + add_table( + doc, + ["Variable", "Role"], + [ + ["ENV", "Environment name (development / production / …)"], + ["PORT", "HTTP listen port"], + ["APP_VERSION", "Version string exposed to clients where applicable"], + ["DB_URL", "PostgreSQL DSN"], + ["MONGODB_URL", "Mongo connection for app logs"], + ["JWT_KEY", "HMAC secret for access tokens"], + ["ACCESS_EXPIRY", "Access token TTL (seconds)"], + ["REFRESH_EXPIRY", "Refresh token TTL (seconds)"], + ["LOG_LEVEL", "slog level"], + ], + ) + add_heading_custom(doc, "4.2 Team / admin panel URLs", 2) + add_para( + doc, + "TEAM_INVITE_BASE_URL and TEAM_PASSWORD_RESET_BASE_URL must point at the admin front-end " + "origins used in email links. If invites “send” but the link 404s, these are wrong—not " + "the mail provider.", + ) + add_heading_custom(doc, "4.3 Integrations (high level)", 2) + add_bullets( + doc, + [ + "Email: RESEND_API_KEY, RESEND_SENDER_EMAIL", + "SMS: AFRO_SMS_* family", + "Google OAuth: GOOGLE_OAUTH_CLIENT_ID / SECRET / REDIRECT_URL", + "Apple Sign-In: APPLE_SIGN_IN_CLIENT_IDS (comma-separated aud values)", + "FCM: FCM_SERVICE_ACCOUNT_KEY", + "MinIO: MINIO_ENABLED and endpoint/credentials/bucket/SSL", + "Vimeo: VIMEO_ENABLED, VIMEO_ACCESS_TOKEN", + "CloudConvert: CLOUDCONVERT_ENABLED, CLOUDCONVERT_API_KEY", + "Chapa: CHAPA_SECRET_KEY, public key, webhook secret, base/callback/return URLs", + "Arifpay: ARIFPAY_* notify/success/cancel URLs, bank account, API key", + "Account deletion purge: ACCOUNT_DELETION_PURGE_* knobs", + ], + ) + add_para( + doc, + "Treat .env like production credentials even on your laptop. It is gitignored for a reason.", + space_before=4, + italic=True, + ) + + # ----- HTTP layer ----- + add_heading_custom(doc, "5. HTTP layer, middleware, and permissions", 1) + add_para( + doc, + "Routes live in internal/web_server/routes.go and are mounted under /api/v1. When you " + "add an endpoint, wire it there, implement the handler, annotate it for Swagger, and " + "pick a permission key that already exists in RBAC seed data—or add the permission " + "properly via migration/seed and admin UI.", + ) + add_heading_custom(doc, "5.1 Authentication middleware", 2) + add_para( + doc, + "authMiddleware validates the Bearer JWT and places claims into Fiber locals " + "(user id, role, etc.). Team members and platform users share the JWT machinery but " + "represent different tables. Deactivated / suspended learners are blocked on auth " + "paths—do not “helpfully” bypass that when debugging; you will reintroduce a production " + "incident.", + ) + add_heading_custom(doc, "5.2 RequirePermission", 2) + add_para( + doc, + "Almost every admin and many learner routes use a.RequirePermission(\"resource.action\"). " + "Examples you will see everywhere: programs.create, practices.update, " + "exam_prep.catalog_courses.reorder, team.members.invite, rbac.roles.list, " + "analytics.* (as applicable). Permission checks are the contract with the admin panel. " + "Hard-coding if role == ADMIN in new code is a regression unless there is a very strong " + "reason (SuperAdminOnly still exists for a few break-glass paths).", + ) + add_heading_custom(doc, "5.3 Content access gates", 2) + add_para( + doc, + "Learners do not get paid content just because they are authenticated. Middleware such " + "as RequireLMSSubscriptionUnlessFree, RequireExamPrepSubscription, " + "RequireActiveSubscription, and related content-access helpers resolve effective access " + "tiers from subscriptions and content flags. Free/unlocked nodes short-circuit; " + "everything else requires a matching active entitlement. When a mobile client reports " + "“I pay but cannot open the lesson,” start here—not in the lesson repository.", + ) + add_heading_custom(doc, "5.4 Background workers", 2) + add_para( + doc, + "The Fiber App also starts long-running workers (see app.go): account deletion purge, " + "payment expiry, subscription expiry reminders. Know that they run in-process with the " + "API. Scaling to multiple replicas means thinking about duplicate job execution unless " + "you add locking later—today, be deliberate about how many API processes you run in an " + "environment.", + ) + + # ----- Data ----- + add_heading_custom(doc, "6. Database workflow (migrations + sqlc)", 1) + add_para( + doc, + "This is the part of the stack where shortcuts hurt the most. We have on the order of " + "100+ up migrations and dozens of query files. Treat SQL as first-class code review " + "material.", + ) + add_heading_custom(doc, "6.1 Migrations", 2) + add_numbered( + doc, + [ + "make migrations/new name=short_snake_description — creates numbered up/down SQL under db/migrations.", + "Write forward-compatible ups when possible; downs should be honest (or clearly noted if irreversible).", + "Apply with make migrations/up (Compose) or migrate CLI against your DB_URL.", + "Never edit an already-applied migration on a shared environment—add a new one.", + ], + ) + add_heading_custom(doc, "6.2 sqlc", 2) + add_para( + doc, + "sqlc.yaml points schema at ./db/migrations/ and queries at ./db/query/, engine " + "PostgreSQL, output package dbgen in ./gen/db using pgx/v5. After changing queries:", + ) + add_code_block(doc, "make sqlc-gen") + add_para( + doc, + "Commit the regenerated Go. Reviewers should see both the .sql and gen/db diff. If " + "sqlc fails, fix the SQL—do not bypass with raw Query in a service unless you are " + "prototyping and will replace it immediately.", + ) + add_heading_custom(doc, "6.3 Seeds", 2) + add_para( + doc, + "db/data holds baseline seed SQL (roles, templates, etc.). db/dev_data is for local " + "convenience. make seed_dev_data also runs a sequence desync fix—useful after manual " + "inserts that fight serial sequences.", + ) + + # ----- Auth domain ----- + add_heading_custom(doc, "7. Identity: learners vs team members", 1) + add_para( + doc, + "Two populations share the product but not the same tables.", + ) + add_heading_custom(doc, "7.1 Platform users (learners)", 2) + add_para( + doc, + "Stored in users (and related profile fields). Auth flows include OTP, Google, Apple. " + "Roles include STUDENT, OPEN_LEARNER (catalog without sequential locking), INSTRUCTOR, " + "SUPPORT, ADMIN, SUPER_ADMIN, and others as defined in domain. OPEN_LEARNER is " + "intentionally not a staff role—keep it out of team invites.", + ) + add_heading_custom(doc, "7.2 Team members (admin staff)", 2) + add_para( + doc, + "Stored in team_members. Login: POST /api/v1/team/login (plus Google / refresh). " + "Invites create a pending member and email a token; accept flow sets password and " + "activates. Refresh tokens are first-class—see docs/team-member-refresh-token-admin-panel-integration.md.", + ) + add_para( + doc, + "team_role may be a built-in key (SUPER_ADMIN, ADMIN, CONTENT_MANAGER, …) or a custom " + "RBAC role name (migration 000097 dropped the rigid CHECK). Invite validation accepts " + "built-in keys, RBAC names, numeric role ids, and display-style labels for built-ins " + "(e.g. “Super Admin” → SUPER_ADMIN). Prefer sending canonical keys from clients.", + ) + add_heading_custom(doc, "7.3 RBAC", 2) + add_para( + doc, + "Roles and permissions are managed under /api/v1/rbac/*. JWT Role for custom team roles " + "uses the stored RBAC name; built-ins map through PlatformRole()/RBACRoleForJWT(). Bulk " + "deactivate/reactivate by role affects both platform users and team members with " + "documented SUPER_ADMIN guardrails—read the admin handler comments before changing that " + "behavior.", + ) + + # ----- Domains ----- + add_heading_custom(doc, "8. Major product domains (where to look)", 1) + + add_heading_custom(doc, "8.1 LMS & exam-prep content", 2) + add_para( + doc, + "Services: programs, courses, modules, lessons, examprep, practices, practicecontent, " + "questions, assessment, videoengagement, vimeo, minio, cloudconvert. Handlers mirror " + "those names under internal/web_server/handlers. Reorder endpoints take ordered_ids and " + "are used heavily by the admin Reorder Content page.", + ) + + add_heading_custom(doc, "8.2 Progress", 2) + add_para( + doc, + "lmsprogress tracks learner progress; exam-prep has its own helpers. Completing lessons " + "and practices goes through dedicated routes. Sequential locking vs OPEN_LEARNER " + "behavior is a product rule—confirm with product before “simplifying” gates.", + ) + + add_heading_custom(doc, "8.3 Subscriptions & payments", 2) + add_para( + doc, + "subscriptions and checkoutsubscription services, plus chapa and arifpay clients, " + "transaction tracking, and admin grant/extend/cancel handlers. Plans can be term-based " + "or one-time lifetime (IELTS/Duolingo plans historically special-cased; lifetime is " + "also a per-plan option). Webhooks must be idempotent in spirit—duplicate gateway " + "callbacks happen in the wild.", + ) + + add_heading_custom(doc, "8.4 Analytics", 2) + add_para( + doc, + "GET analytics dashboard aggregates users, subscriptions (including renewal/churn " + "series and snapshots), payments, courses, content, notifications, issues, team, and " + "video drop-off. Field normalization maps free-text demographics onto field_options " + "(Unknown → Other style cleanup). Date filters: all_time, year, year_month, custom " + "range—see analytics_params.go.", + ) + + add_heading_custom(doc, "8.5 Messaging & ops", 2) + add_para( + doc, + "notification + learnernotifications + messenger + emailtemplates cover in-app, email, " + "and SMS. Bulk/scheduled notification docs are under docs/bulk-scheduled-notifications-integration.md. " + "issue_reporting, faqs, ratings, activity_log, appversions round out ops tooling. CSV " + "exports for admin live in admin_export handlers.", + ) + + # ----- Adding a feature ----- + add_heading_custom(doc, "9. How we prefer to ship a feature", 1) + add_para( + doc, + "A healthy change usually looks like this:", + ) + add_numbered( + doc, + [ + "Agree on the API shape (and permission key) with whoever owns the admin or mobile client.", + "Add or extend migrations if the schema must change; keep them reviewable and named clearly.", + "Write sqlc queries; regenerate; wrap in repository methods matching ports.", + "Implement service methods with domain errors (ErrNotFound, ErrInvalid…, or feature-specific).", + "Add handler + route + middleware chain; add swag comments; make swagger.", + "If the admin panel needs a contract, add or update a docs/*-admin-panel-integration.md file—future you will thank present you.", + "Add focused tests where logic is branching (role resolution, money, access gates).", + "Manual smoke via Swagger or Postman collections in postman/.", + "Commit with a message that says why; push the branch your team deploys from.", + ], + ) + add_para( + doc, + "Code style expectations in practice: match neighboring files; do not rename half the " + "package “for consistency” in the same PR as a bugfix; keep handlers boring; put the " + "clever bits in services with comments only where the business rule is non-obvious.", + space_before=6, + ) + + # ----- Testing ----- + add_heading_custom(doc, "10. Testing and quality", 1) + add_para( + doc, + "make test runs go test ./... inside the Compose test service. For faster loops, " + "go test ./internal/domain/ ./internal/services/team/ -count=1 is a common pattern. " + "Some packages need a live DB; others are pure. Prefer table-driven tests for " + "normalization and role mapping (see team_roles_test.go and analytics field normalize " + "tests as examples of the tone we like).", + ) + add_para( + doc, + "Coverage: make coverage writes under coverage/. Use it when you touch payment or " + "permission-sensitive code—not as a vanity metric.", + ) + + # ----- Observability ----- + add_heading_custom(doc, "11. Logging, activity, and exports", 1) + add_para( + doc, + "Application logging uses slog (and zap in places). Mongo can store app logs; " + "make export_logs helps pull them. Activity logs record admin/team actions " + "(invites, role changes, etc.)—wire RecordAction when you add sensitive mutations so " + "support can answer “who did what.” Admin CSV export endpoints are permission-gated; " + "filters live in export_filters.go.", + ) + + # ----- Integrations deep dive ----- + add_heading_custom(doc, "12. Third-party integrations (developer notes)", 1) + add_table( + doc, + ["System", "Package", "Failure mode to watch"], + [ + ["Resend", "messenger / emailtemplates", "Invite/OTP fails silently if key/sender wrong"], + ["Afro SMS", "config + messenger", "OTP delivery in Ethiopia; wrong sender IDs"], + ["Chapa", "services/chapa", "Webhook signature + duplicate events"], + ["Arifpay", "services/arifpay", "Notify URL mismatch with deployed API"], + ["MinIO", "services/minio", "SSL/endpoint mismatch; bucket ACL"], + ["Vimeo", "services/vimeo", "Upload token scope; progress polling"], + ["CloudConvert", "services/cloudconvert", "Disabled in many envs—feature-flagged"], + ["Firebase FCM", "notification", "Invalid service account JSON"], + ["Google/Apple", "authentication", "Redirect URI / aud mismatches"], + ], + ) + add_para( + doc, + "When an integration is optional, respect the Enabled flag. Do not call external APIs " + "in tests without fakes or build tags.", + space_before=6, + ) + + # ----- Troubleshooting ----- + add_heading_custom(doc, "13. Troubleshooting field guide", 1) + add_table( + doc, + ["Symptom", "Likely place to look"], + [ + ["Process exits on boot", "internal/config validation; .env"], + ["sqlc / compile errors after SQL edit", "make sqlc-gen; query vs schema mismatch"], + ["migrate dirty state", "schema_migrations; restore backup; fix forward"], + ["403 on admin route", "JWT role permissions; RequirePermission key typo"], + ["401 loops in admin", "Team refresh token path; clock skew; JWT_KEY rotated"], + ["Invite invalid team role", "roles.go resolution; client sending UI labels only"], + ["Paid user blocked from content", "content_access_middleware; subscription snapshot"], + ["Payment succeeded, no entitlement", "Webhook handler; transaction idempotency"], + ["Analytics demographics “Other”", "analytics_field_normalize vs field_options"], + ["Email invite not received", "RESEND_*; TEAM_INVITE_BASE_URL; spam"], + ], + ) + + # ----- Glossary ----- + add_heading_custom(doc, "14. Glossary", 1) + add_table( + doc, + ["Term", "Meaning here"], + [ + ["LMS", "Learn English program → course → module → lesson tree"], + ["Exam prep", "Duolingo/IELTS catalog course → unit → module → lesson tree"], + ["Practice", "Assessment container holding questions / stimulus"], + ["Team member", "Staff row in team_members (admin users)"], + ["Platform user", "Learner (or platform role) in users"], + ["Permission key", "String like practices.update checked by middleware"], + ["Lifetime plan", "One-time purchase; no normal expiry"], + ["OPEN_LEARNER", "Learner role without sequential prerequisite locking"], + ["sqlc", "Compile-time type-safe SQL → Go codegen"], + ], + ) + + # ----- Doc index ----- + add_heading_custom(doc, "15. Related documentation in the repo", 1) + add_para( + doc, + "Prefer these over tribal knowledge when integrating the admin panel:", + ) + add_bullets( + doc, + [ + "docs/team-member-invitation-admin-panel-integration.md", + "docs/team-member-refresh-token-admin-panel-integration.md", + "docs/team-password-reset-admin-panel-integration.md", + "docs/csv-export-admin-panel-integration.md", + "docs/bulk-scheduled-notifications-integration.md", + "docs/file-upload-admin-panel-integration.md", + "docs/vimeo-video-upload-progress-admin-panel-integration.md", + "docs/admin-subscription-grant-extend-cancel-admin-panel-integration.md", + "docs/faq-admin-panel-integration.md / ratings / activity-logs / personas", + "docs/practice-*-admin-panel-integration.md and question-type-* guides", + "docs/chapa-direct-charge-client-app-integration.md", + "postman/*.json collections for exploratory testing", + "Root README.md for env tables and Makefile reference", + ], + ) + + # ----- Closing ----- + add_heading_custom(doc, "16. Closing notes", 1) + add_para( + doc, + "Yimaru’s backend is not a toy CRUD service. Learners depend on entitlements being " + "correct; teachers and content managers depend on reorder and publish semantics staying " + "stable; finance depends on payment webhooks being trustworthy. When in doubt, add a " + "test, write the integration note, and ask in review before merging something that " + "touches money, auth, or access gates.", + ) + add_para( + doc, + "If this document drifts from the code, trust the code—and then update this file. " + "Documentation that lies is worse than no documentation.", + italic=True, + ) + add_para( + doc, + "— Yaltopia engineering, for Yimaru Academy backend developers", + space_before=16, + italic=True, + ) + + OUT.parent.mkdir(parents=True, exist_ok=True) + doc.save(OUT) + print(f"Wrote {OUT}") + + +if __name__ == "__main__": + build()