Compare commits
10 Commits
3a959cd563
...
d54a2b11d4
| Author | SHA1 | Date | |
|---|---|---|---|
| d54a2b11d4 | |||
| a1f012774e | |||
| 2134b953ab | |||
| 38e9f81372 | |||
| 1eb03b7e03 | |||
| e68814c2c5 | |||
| 7571ee4f1c | |||
| 18c875e89c | |||
| a3bf8ba5a2 | |||
| 77de56d801 |
33
README.md
33
README.md
|
|
@ -1,22 +1,23 @@
|
|||
# Yimaru Backend API
|
||||
# Rezina Backend API
|
||||
|
||||
Golang 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.
|
||||
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** | `Yimaru-Backend` |
|
||||
| **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/Yimaru/Yimaru-BackEnd.git` |
|
||||
| **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)
|
||||
|
|
@ -40,8 +41,7 @@ Golang API for **Yimaru Academy**, an LMS and exam-prep platform. It serves the
|
|||
## 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
|
||||
- **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
|
||||
|
|
@ -97,8 +97,8 @@ Optional: `psql`, MongoDB tools for log export.
|
|||
## Quick start
|
||||
|
||||
```bash
|
||||
git clone https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd.git
|
||||
cd Yimaru-BackEnd
|
||||
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
|
||||
|
|
@ -309,7 +309,7 @@ Custom roles live in RBAC tables; migration `000097` allows custom names on `tea
|
|||
|
||||
## Domain overview
|
||||
|
||||
### Learn English content
|
||||
### Learning content
|
||||
|
||||
```
|
||||
Learning programs
|
||||
|
|
@ -321,17 +321,6 @@ Learning programs
|
|||
|
||||
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
|
||||
|
||||
|
|
@ -366,7 +355,7 @@ Reorder APIs mirror the LMS hierarchy for catalog courses, units, modules, and l
|
|||
## Project structure
|
||||
|
||||
```
|
||||
Yimaru-BackEnd/
|
||||
Rezina-BackEnd/
|
||||
├── cmd/main.go # Entry + DI wiring
|
||||
├── db/
|
||||
│ ├── migrations/ # golang-migrate SQL
|
||||
|
|
@ -467,4 +456,4 @@ Detailed contracts for the admin UI live under `docs/`:
|
|||
|
||||
## License
|
||||
|
||||
Proprietary — Yaltopia / Yimaru Academy. Internal use only unless otherwise licensed.
|
||||
Proprietary — Yaltopia / Rezina. Internal use only unless otherwise licensed.
|
||||
|
|
|
|||
105
cmd/main.go
105
cmd/main.go
|
|
@ -1,55 +1,54 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
_ "Yimaru-Backend/docs"
|
||||
dbgen "Yimaru-Backend/gen/db"
|
||||
"Yimaru-Backend/internal/config"
|
||||
"Yimaru-Backend/internal/domain"
|
||||
customlogger "Yimaru-Backend/internal/logger"
|
||||
"Yimaru-Backend/internal/logger/mongoLogger"
|
||||
minioclient "Yimaru-Backend/internal/pkgs/minio"
|
||||
"Yimaru-Backend/internal/repository"
|
||||
activitylogservice "Yimaru-Backend/internal/services/activity_log"
|
||||
"Yimaru-Backend/internal/services/arifpay"
|
||||
"Yimaru-Backend/internal/services/appversions"
|
||||
"Yimaru-Backend/internal/services/chapa"
|
||||
"Yimaru-Backend/internal/services/assessment"
|
||||
"Yimaru-Backend/internal/services/authentication"
|
||||
cloudconvertservice "Yimaru-Backend/internal/services/cloudconvert"
|
||||
coursesservice "Yimaru-Backend/internal/services/courses"
|
||||
"Yimaru-Backend/internal/services/emailtemplates"
|
||||
"Yimaru-Backend/internal/services/examprep"
|
||||
"Yimaru-Backend/internal/services/faqs"
|
||||
issuereporting "Yimaru-Backend/internal/services/issue_reporting"
|
||||
lessonsservice "Yimaru-Backend/internal/services/lessons"
|
||||
learnernotificationsservice "Yimaru-Backend/internal/services/learnernotifications"
|
||||
"Yimaru-Backend/internal/services/lmsprogress"
|
||||
"Yimaru-Backend/internal/services/messenger"
|
||||
minioservice "Yimaru-Backend/internal/services/minio"
|
||||
moduleservice "Yimaru-Backend/internal/services/modules"
|
||||
notificationservice "Yimaru-Backend/internal/services/notification"
|
||||
personasservice "Yimaru-Backend/internal/services/personas"
|
||||
practicecontentservice "Yimaru-Backend/internal/services/practicecontent"
|
||||
practicesservice "Yimaru-Backend/internal/services/practices"
|
||||
profilefieldoptions "Yimaru-Backend/internal/services/profilefieldoptions"
|
||||
programsservice "Yimaru-Backend/internal/services/programs"
|
||||
"Yimaru-Backend/internal/services/questions"
|
||||
ratingsservice "Yimaru-Backend/internal/services/ratings"
|
||||
rbacservice "Yimaru-Backend/internal/services/rbac"
|
||||
"Yimaru-Backend/internal/services/recommendation"
|
||||
"Yimaru-Backend/internal/services/settings"
|
||||
"Yimaru-Backend/internal/services/subscriptions"
|
||||
"Yimaru-Backend/internal/services/team"
|
||||
vimeoservice "Yimaru-Backend/internal/services/vimeo"
|
||||
_ "Rezina-Backend/docs"
|
||||
dbgen "Rezina-Backend/gen/db"
|
||||
"Rezina-Backend/internal/config"
|
||||
"Rezina-Backend/internal/domain"
|
||||
customlogger "Rezina-Backend/internal/logger"
|
||||
"Rezina-Backend/internal/logger/mongoLogger"
|
||||
minioclient "Rezina-Backend/internal/pkgs/minio"
|
||||
"Rezina-Backend/internal/repository"
|
||||
activitylogservice "Rezina-Backend/internal/services/activity_log"
|
||||
"Rezina-Backend/internal/services/appversions"
|
||||
"Rezina-Backend/internal/services/arifpay"
|
||||
"Rezina-Backend/internal/services/authentication"
|
||||
"Rezina-Backend/internal/services/chapa"
|
||||
cloudconvertservice "Rezina-Backend/internal/services/cloudconvert"
|
||||
coursesservice "Rezina-Backend/internal/services/courses"
|
||||
"Rezina-Backend/internal/services/emailtemplates"
|
||||
"Rezina-Backend/internal/services/examprep"
|
||||
"Rezina-Backend/internal/services/faqs"
|
||||
issuereporting "Rezina-Backend/internal/services/issue_reporting"
|
||||
learnernotificationsservice "Rezina-Backend/internal/services/learnernotifications"
|
||||
lessonsservice "Rezina-Backend/internal/services/lessons"
|
||||
"Rezina-Backend/internal/services/lmsprogress"
|
||||
"Rezina-Backend/internal/services/messenger"
|
||||
minioservice "Rezina-Backend/internal/services/minio"
|
||||
moduleservice "Rezina-Backend/internal/services/modules"
|
||||
notificationservice "Rezina-Backend/internal/services/notification"
|
||||
personasservice "Rezina-Backend/internal/services/personas"
|
||||
practicecontentservice "Rezina-Backend/internal/services/practicecontent"
|
||||
practicesservice "Rezina-Backend/internal/services/practices"
|
||||
profilefieldoptions "Rezina-Backend/internal/services/profilefieldoptions"
|
||||
programsservice "Rezina-Backend/internal/services/programs"
|
||||
"Rezina-Backend/internal/services/questions"
|
||||
ratingsservice "Rezina-Backend/internal/services/ratings"
|
||||
rbacservice "Rezina-Backend/internal/services/rbac"
|
||||
"Rezina-Backend/internal/services/recommendation"
|
||||
"Rezina-Backend/internal/services/settings"
|
||||
"Rezina-Backend/internal/services/subscriptions"
|
||||
"Rezina-Backend/internal/services/team"
|
||||
vimeoservice "Rezina-Backend/internal/services/vimeo"
|
||||
"context"
|
||||
|
||||
// referralservice "Yimaru-Backend/internal/services/referal"
|
||||
"Yimaru-Backend/internal/services/transaction"
|
||||
"Yimaru-Backend/internal/services/user"
|
||||
videoengagementservice "Yimaru-Backend/internal/services/videoengagement"
|
||||
httpserver "Yimaru-Backend/internal/web_server"
|
||||
jwtutil "Yimaru-Backend/internal/web_server/jwt"
|
||||
customvalidator "Yimaru-Backend/internal/web_server/validator"
|
||||
// referralservice "Rezina-Backend/internal/services/referal"
|
||||
"Rezina-Backend/internal/services/transaction"
|
||||
"Rezina-Backend/internal/services/user"
|
||||
videoengagementservice "Rezina-Backend/internal/services/videoengagement"
|
||||
httpserver "Rezina-Backend/internal/web_server"
|
||||
jwtutil "Rezina-Backend/internal/web_server/jwt"
|
||||
customvalidator "Rezina-Backend/internal/web_server/validator"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
|
|
@ -61,9 +60,9 @@ import (
|
|||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// @title Yimaru API
|
||||
// @title Rezina API
|
||||
// @version 1.0.1
|
||||
// @description This is server for Yimaru.
|
||||
// @description This is server for Rezina.
|
||||
// @termsOfService http://swagger.io/terms/
|
||||
// @contact.name API Support
|
||||
// @contact.url http://www.swagger.io/support
|
||||
|
|
@ -244,13 +243,6 @@ func main() {
|
|||
// transferStore := repository.NewTransferStore(store)
|
||||
// walletStore := wallet.WalletStore(store)
|
||||
|
||||
assessmentSvc := assessment.NewService(
|
||||
repository.NewUserStore(store),
|
||||
store, // Use store directly as it implements QuestionStore
|
||||
notificationSvc,
|
||||
cfg,
|
||||
)
|
||||
|
||||
// Vimeo service for video hosting
|
||||
var vimeoSvc *vimeoservice.Service
|
||||
if cfg.Vimeo.Enabled && cfg.Vimeo.AccessToken != "" {
|
||||
|
|
@ -370,7 +362,6 @@ func main() {
|
|||
|
||||
// Initialize and start HTTP server
|
||||
app := httpserver.NewApp(
|
||||
assessmentSvc,
|
||||
questionsSvc,
|
||||
faqSvc,
|
||||
appVersionSvc,
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|||
-- ======================================================
|
||||
-- Customer/Learner Users (login via /api/v1/auth/customer-login)
|
||||
-- Credentials: email + password@123
|
||||
-- OPEN_LEARNER demo user (openlearner@yimaru.com) is seeded by migration 000061_open_learner_role.
|
||||
-- Additional OPEN_LEARNER users are seeded below.
|
||||
-- OPEN_LEARNER demo user (openlearner@rezina.com) is seeded by migration 000061_open_learner_role.
|
||||
-- Optional sample STUDENT / OPEN_LEARNER rows below (no demo student@rezina.com account).
|
||||
-- ======================================================
|
||||
INSERT INTO users (
|
||||
id,
|
||||
|
|
@ -40,45 +40,13 @@ INSERT INTO users (
|
|||
updated_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
10,
|
||||
'Demo',
|
||||
'Student',
|
||||
'Male',
|
||||
'2000-01-01',
|
||||
'student@yimaru.com',
|
||||
NULL,
|
||||
'STUDENT',
|
||||
crypt('password@123', gen_salt('bf'))::bytea,
|
||||
'25_34',
|
||||
'Bachelor',
|
||||
'Ethiopia',
|
||||
'Addis Ababa',
|
||||
'BEGINNER',
|
||||
'Demo',
|
||||
'Student',
|
||||
'Learn programming',
|
||||
'English',
|
||||
'Grammar',
|
||||
'Technology',
|
||||
FALSE,
|
||||
TRUE,
|
||||
FALSE,
|
||||
'ACTIVE',
|
||||
NULL,
|
||||
FALSE,
|
||||
NULL,
|
||||
'en',
|
||||
CURRENT_TIMESTAMP,
|
||||
NULL
|
||||
),
|
||||
(
|
||||
11,
|
||||
'Abebe',
|
||||
'Kebede',
|
||||
'Male',
|
||||
'1995-01-01',
|
||||
'abebe@yimaru.com',
|
||||
'abebe@rezina.com',
|
||||
'0911001100',
|
||||
'STUDENT',
|
||||
crypt('password@123', gen_salt('bf'))::bytea,
|
||||
|
|
@ -110,7 +78,7 @@ VALUES
|
|||
'Tadesse',
|
||||
'Female',
|
||||
'1998-01-01',
|
||||
'sara@yimaru.com',
|
||||
'sara@rezina.com',
|
||||
'0911223344',
|
||||
'STUDENT',
|
||||
crypt('password@123', gen_salt('bf'))::bytea,
|
||||
|
|
@ -138,6 +106,9 @@ VALUES
|
|||
)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
DELETE FROM users
|
||||
WHERE LOWER(TRIM(email)) = 'student@rezina.com';
|
||||
|
||||
-- OPEN_LEARNER learners (login via /api/v1/auth/customer-login)
|
||||
-- Credentials: email + password@123
|
||||
INSERT INTO users (
|
||||
|
|
@ -233,87 +204,9 @@ WHERE LOWER(TRIM(email)) = 'tsegaye.negera@reachforchange.org'
|
|||
-- Team Members / Admin Panel Users (login via /api/v1/team/login)
|
||||
-- Credentials: email + password@123
|
||||
-- Allowed team_role values (migration 000103): SUPER_ADMIN, ADMIN, CONTENT_MANAGER
|
||||
-- Super Admin: superadmin@yimaru.com / password@123
|
||||
-- Admin: admin@yimaru.com / password@123
|
||||
-- Content: content@yimaru.com / password@123
|
||||
-- Super Admin: superadmin@rezina.com / password@123
|
||||
-- ======================================================
|
||||
|
||||
INSERT INTO team_members (
|
||||
id,
|
||||
first_name,
|
||||
last_name,
|
||||
email,
|
||||
phone_number,
|
||||
password,
|
||||
team_role,
|
||||
department,
|
||||
job_title,
|
||||
employment_type,
|
||||
hire_date,
|
||||
bio,
|
||||
status,
|
||||
email_verified,
|
||||
permissions,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
1,
|
||||
'Super',
|
||||
'Admin',
|
||||
'superadmin@yimaru.com',
|
||||
'0911001100',
|
||||
crypt('password@123', gen_salt('bf'))::bytea,
|
||||
'SUPER_ADMIN',
|
||||
'Executive',
|
||||
'System Super Administrator',
|
||||
'full_time',
|
||||
'2024-01-01',
|
||||
'Platform super administrator with full system access including team invitations.',
|
||||
'active',
|
||||
TRUE,
|
||||
'["*"]'::jsonb,
|
||||
CURRENT_TIMESTAMP
|
||||
),
|
||||
(
|
||||
2,
|
||||
'Admin',
|
||||
'User',
|
||||
'admin@yimaru.com',
|
||||
'0922001100',
|
||||
crypt('password@123', gen_salt('bf'))::bytea,
|
||||
'ADMIN',
|
||||
'Operations',
|
||||
'Operations Manager',
|
||||
'full_time',
|
||||
'2024-02-01',
|
||||
'Administrative staff managing day-to-day operations.',
|
||||
'active',
|
||||
TRUE,
|
||||
'["*"]'::jsonb,
|
||||
CURRENT_TIMESTAMP
|
||||
),
|
||||
(
|
||||
3,
|
||||
'Content',
|
||||
'MANAGER',
|
||||
'content@yimaru.com',
|
||||
'0933001100',
|
||||
crypt('password@123', gen_salt('bf'))::bytea,
|
||||
'CONTENT_MANAGER',
|
||||
'Content',
|
||||
'Content Lead',
|
||||
'full_time',
|
||||
'2024-03-01',
|
||||
'Manages all course content and curriculum.',
|
||||
'active',
|
||||
TRUE,
|
||||
'["courses.manage", "courses.publish", "content.manage"]'::jsonb,
|
||||
CURRENT_TIMESTAMP
|
||||
)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- Ensure staff logins exist even if ids were already taken by other rows.
|
||||
INSERT INTO team_members (
|
||||
first_name,
|
||||
last_name,
|
||||
|
|
@ -335,7 +228,7 @@ VALUES
|
|||
(
|
||||
'Super',
|
||||
'Admin',
|
||||
'superadmin@yimaru.com',
|
||||
'superadmin@rezina.com',
|
||||
'0911001100',
|
||||
crypt('password@123', gen_salt('bf'))::bytea,
|
||||
'SUPER_ADMIN',
|
||||
|
|
@ -350,113 +243,33 @@ VALUES
|
|||
CURRENT_TIMESTAMP
|
||||
)
|
||||
ON CONFLICT (email) DO UPDATE SET
|
||||
first_name = EXCLUDED.first_name,
|
||||
last_name = EXCLUDED.last_name,
|
||||
phone_number = EXCLUDED.phone_number,
|
||||
password = EXCLUDED.password,
|
||||
team_role = 'SUPER_ADMIN',
|
||||
department = EXCLUDED.department,
|
||||
job_title = EXCLUDED.job_title,
|
||||
employment_type = EXCLUDED.employment_type,
|
||||
hire_date = EXCLUDED.hire_date,
|
||||
bio = EXCLUDED.bio,
|
||||
status = 'active',
|
||||
email_verified = TRUE,
|
||||
permissions = '["*"]'::jsonb,
|
||||
updated_at = CURRENT_TIMESTAMP;
|
||||
|
||||
INSERT INTO team_members (
|
||||
first_name,
|
||||
last_name,
|
||||
email,
|
||||
phone_number,
|
||||
password,
|
||||
team_role,
|
||||
department,
|
||||
job_title,
|
||||
employment_type,
|
||||
hire_date,
|
||||
bio,
|
||||
status,
|
||||
email_verified,
|
||||
permissions,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'Admin',
|
||||
'User',
|
||||
'admin@yimaru.com',
|
||||
'0922001100',
|
||||
crypt('password@123', gen_salt('bf'))::bytea,
|
||||
'ADMIN',
|
||||
'Operations',
|
||||
'Operations Manager',
|
||||
'full_time',
|
||||
'2024-02-01',
|
||||
'Administrative staff managing day-to-day operations.',
|
||||
'active',
|
||||
TRUE,
|
||||
'["*"]'::jsonb,
|
||||
CURRENT_TIMESTAMP
|
||||
)
|
||||
ON CONFLICT (email) DO UPDATE SET
|
||||
password = EXCLUDED.password,
|
||||
team_role = 'ADMIN',
|
||||
status = 'active',
|
||||
email_verified = TRUE,
|
||||
permissions = '["*"]'::jsonb,
|
||||
updated_at = CURRENT_TIMESTAMP;
|
||||
-- Remove legacy demo staff seeds (admin/content); keep super admin only.
|
||||
UPDATE scheduled_notifications sn
|
||||
SET created_by = tm_super.id
|
||||
FROM team_members tm_super
|
||||
WHERE LOWER(TRIM(tm_super.email)) = 'superadmin@rezina.com'
|
||||
AND sn.created_by IN (
|
||||
SELECT id FROM team_members
|
||||
WHERE LOWER(TRIM(email)) IN ('admin@rezina.com', 'content@rezina.com')
|
||||
);
|
||||
|
||||
INSERT INTO team_members (
|
||||
first_name,
|
||||
last_name,
|
||||
email,
|
||||
phone_number,
|
||||
password,
|
||||
team_role,
|
||||
department,
|
||||
job_title,
|
||||
employment_type,
|
||||
hire_date,
|
||||
bio,
|
||||
status,
|
||||
email_verified,
|
||||
permissions,
|
||||
created_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
'Content',
|
||||
'MANAGER',
|
||||
'content@yimaru.com',
|
||||
'0933001100',
|
||||
crypt('password@123', gen_salt('bf'))::bytea,
|
||||
'CONTENT_MANAGER',
|
||||
'Content',
|
||||
'Content Lead',
|
||||
'full_time',
|
||||
'2024-03-01',
|
||||
'Manages all course content and curriculum.',
|
||||
'active',
|
||||
TRUE,
|
||||
'["courses.manage", "courses.publish", "content.manage"]'::jsonb,
|
||||
CURRENT_TIMESTAMP
|
||||
)
|
||||
ON CONFLICT (email) DO UPDATE SET
|
||||
password = EXCLUDED.password,
|
||||
team_role = 'CONTENT_MANAGER',
|
||||
status = 'active',
|
||||
email_verified = TRUE,
|
||||
updated_at = CURRENT_TIMESTAMP;
|
||||
|
||||
-- Legacy team_members rows may pre-exist; align admin permissions with seed expectations.
|
||||
UPDATE team_members
|
||||
SET permissions = '["*"]'::jsonb,
|
||||
team_role = 'SUPER_ADMIN',
|
||||
status = 'active',
|
||||
email_verified = TRUE,
|
||||
password = crypt('password@123', gen_salt('bf'))::bytea,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = 1 OR email = 'superadmin@yimaru.com';
|
||||
|
||||
UPDATE team_members
|
||||
SET permissions = '["*"]'::jsonb,
|
||||
password = crypt('password@123', gen_salt('bf'))::bytea,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = 2 OR email = 'admin@yimaru.com';
|
||||
DELETE FROM team_members
|
||||
WHERE LOWER(TRIM(email)) IN ('admin@rezina.com', 'content@rezina.com');
|
||||
|
||||
-- ======================================================
|
||||
-- RBAC safety seed: ensure ADMIN / SUPER_ADMIN have permission grants
|
||||
|
|
|
|||
|
|
@ -0,0 +1,86 @@
|
|||
-- Run separately BEFORE migration 000110, against the intended database.
|
||||
-- Review docs/subscription-plan-cleanup.md first. No automatic winner selection.
|
||||
BEGIN;
|
||||
SET LOCAL lock_timeout = '10s';
|
||||
SET LOCAL statement_timeout = '60s';
|
||||
SET LOCAL search_path = public, pg_catalog;
|
||||
|
||||
-- Prevent concurrent plan/reference changes between archival and consolidation.
|
||||
LOCK TABLE subscription_plans, user_subscriptions, payments IN EXCLUSIVE MODE;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF current_setting('rezina.approve_plan_consolidation', true) IS DISTINCT FROM 'yes' THEN
|
||||
RAISE EXCEPTION 'Review the historical-plan change, then explicitly SET rezina.approve_plan_consolidation = ''yes'' in this session';
|
||||
END IF;
|
||||
IF (SELECT count(*) FROM subscription_plans
|
||||
WHERE id IN (2, 9, 14) AND category = 'LEARN_ENGLISH'
|
||||
AND NOT is_lifetime AND duration_value = 1 AND duration_unit = 'MONTH'
|
||||
AND currency = 'ETB'
|
||||
AND ((id = 2 AND price = 300 AND is_active)
|
||||
OR (id = 9 AND price = 1 AND NOT is_active)
|
||||
OR (id = 14 AND price = 0 AND NOT is_active))) <> 3 THEN
|
||||
RAISE EXCEPTION 'Plans differ from the reviewed backup; stop and review current data';
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM payments WHERE plan_id IN (9, 14)
|
||||
AND status IN ('PENDING', 'PROCESSING')) THEN
|
||||
RAISE EXCEPTION 'Duplicate plans have in-flight payments; resolve them before consolidation';
|
||||
END IF;
|
||||
-- Unknown references must be reviewed, even if their FK would silently SET NULL/CASCADE.
|
||||
IF EXISTS (SELECT 1 FROM pg_constraint
|
||||
WHERE contype = 'f' AND confrelid = 'public.subscription_plans'::regclass
|
||||
AND NOT (conrelid IN ('public.payments'::regclass, 'public.user_subscriptions'::regclass)
|
||||
AND conkey = ARRAY[(SELECT attnum FROM pg_attribute
|
||||
WHERE attrelid = conrelid AND attname = 'plan_id')]::smallint[]
|
||||
AND confkey = ARRAY[(SELECT attnum FROM pg_attribute
|
||||
WHERE attrelid = confrelid AND attname = 'id')]::smallint[])) THEN
|
||||
RAISE EXCEPTION 'Unexpected foreign key references subscription_plans; review before consolidation';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Deliberately fail on a repeated run; never overwrite the original archive.
|
||||
CREATE SCHEMA plan_cleanup_000110;
|
||||
REVOKE ALL ON SCHEMA plan_cleanup_000110 FROM PUBLIC;
|
||||
CREATE TABLE plan_cleanup_000110.mapping (
|
||||
old_plan_id bigint PRIMARY KEY,
|
||||
canonical_plan_id bigint NOT NULL,
|
||||
archived_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
INSERT INTO plan_cleanup_000110.mapping (old_plan_id, canonical_plan_id)
|
||||
VALUES (9, 2), (14, 2);
|
||||
CREATE TABLE plan_cleanup_000110.subscription_plans AS
|
||||
SELECT * FROM public.subscription_plans WHERE id IN (2, 9, 14);
|
||||
CREATE TABLE plan_cleanup_000110.user_subscriptions AS
|
||||
SELECT * FROM public.user_subscriptions WHERE plan_id IN (9, 14);
|
||||
CREATE TABLE plan_cleanup_000110.payments AS
|
||||
SELECT * FROM public.payments WHERE plan_id IN (9, 14);
|
||||
REVOKE ALL ON ALL TABLES IN SCHEMA plan_cleanup_000110 FROM PUBLIC;
|
||||
|
||||
UPDATE public.user_subscriptions AS s SET plan_id = m.canonical_plan_id
|
||||
FROM plan_cleanup_000110.mapping AS m WHERE s.plan_id = m.old_plan_id;
|
||||
UPDATE public.payments AS p SET plan_id = m.canonical_plan_id
|
||||
FROM plan_cleanup_000110.mapping AS m WHERE p.plan_id = m.old_plan_id;
|
||||
DELETE FROM public.subscription_plans WHERE id IN (9, 14);
|
||||
|
||||
-- Ensure the full catalog satisfies the intended rule before committing anything.
|
||||
-- Migration 000110 subsequently sees this exact index and leaves it in place.
|
||||
CREATE UNIQUE INDEX idx_subscription_plans_category_period
|
||||
ON public.subscription_plans (category, is_lifetime, duration_value, duration_unit);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM plan_cleanup_000110.payments a
|
||||
LEFT JOIN public.payments p USING (id)
|
||||
WHERE p.id IS NULL OR p.plan_id <> 2
|
||||
OR (to_jsonb(p) - 'plan_id') IS DISTINCT FROM (to_jsonb(a) - 'plan_id')
|
||||
) OR EXISTS (
|
||||
SELECT 1 FROM plan_cleanup_000110.user_subscriptions a
|
||||
LEFT JOIN public.user_subscriptions s USING (id)
|
||||
WHERE s.id IS NULL OR s.plan_id <> 2
|
||||
OR (to_jsonb(s) - 'plan_id') IS DISTINCT FROM (to_jsonb(a) - 'plan_id')
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Reference consolidation changed fields other than plan_id';
|
||||
END IF;
|
||||
END $$;
|
||||
COMMIT;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
DELETE FROM users WHERE id = 13 AND email = 'openlearner@yimaru.com';
|
||||
DELETE FROM users WHERE id = 13 AND email = 'openlearner@rezina.com';
|
||||
|
||||
DELETE FROM role_permissions WHERE role_id = (SELECT id FROM roles WHERE name = 'OPEN_LEARNER');
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ INSERT INTO roles (name, description, is_system) VALUES
|
|||
)
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
-- Demo OPEN_LEARNER (customer-login): openlearner@yimaru.com / password@123
|
||||
-- Demo OPEN_LEARNER (customer-login): openlearner@rezina.com / password@123
|
||||
INSERT INTO users (
|
||||
id,
|
||||
first_name,
|
||||
|
|
@ -50,7 +50,7 @@ VALUES
|
|||
'OpenLearner',
|
||||
'Female',
|
||||
'1999-06-01',
|
||||
'openlearner@yimaru.com',
|
||||
'openlearner@rezina.com',
|
||||
NULL,
|
||||
'OPEN_LEARNER',
|
||||
crypt('password@123', gen_salt('bf'))::bytea,
|
||||
|
|
|
|||
|
|
@ -20,8 +20,8 @@ VALUES
|
|||
(
|
||||
'otp',
|
||||
'One-Time Password',
|
||||
'Yimaru Academy — Your verification code',
|
||||
'Yimaru Academy{{if .FirstName}}, {{.FirstName}}{{end}}
|
||||
'Rezina — Your verification code',
|
||||
'Rezina{{if .FirstName}}, {{.FirstName}}{{end}}
|
||||
|
||||
Your verification code is {{.OTP}}.
|
||||
It expires in {{.ExpiresMinutes}} minutes.
|
||||
|
|
@ -29,18 +29,18 @@ It expires in {{.ExpiresMinutes}} minutes.
|
|||
Please do not share this code with anyone.',
|
||||
$otp_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;letter-spacing:0.3px;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;letter-spacing:0.3px;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;line-height:1.3;">Your verification code</h1>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}use the code below to continue signing in to Yimaru Academy.</p>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}use the code below to continue signing in to Rezina.</p>
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0"><tr><td style="background-color:#eef4ff;border-radius:8px;padding:20px;border:1px solid #e0e8f5;text-align:center;">
|
||||
<p style="margin:0 0 6px;color:#9d2a83;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;">One-time password</p>
|
||||
<p style="margin:0;color:#333333;font-size:34px;font-weight:700;letter-spacing:8px;font-family:Consolas,Monaco,monospace;">{{.OTP}}</p>
|
||||
|
|
@ -49,7 +49,7 @@ Please do not share this code with anyone.',
|
|||
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">If you did not request this code, you can safely ignore this email.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;line-height:1.5;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;line-height:1.5;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$otp_html$,
|
||||
'["OTP", "FirstName", "ExpiresMinutes"]'::jsonb,
|
||||
|
|
@ -59,31 +59,31 @@ Please do not share this code with anyone.',
|
|||
(
|
||||
'invitation',
|
||||
'User Invitation',
|
||||
'You are invited to Yimaru Academy',
|
||||
'You are invited to Rezina',
|
||||
'Hi{{if .FirstName}} {{.FirstName}}{{end}},
|
||||
|
||||
You have been invited{{if .InviterName}} by {{.InviterName}}{{end}} to join Yimaru Academy.
|
||||
You have been invited{{if .InviterName}} by {{.InviterName}}{{end}} to join Rezina.
|
||||
|
||||
Accept your invitation: {{.InviteLink}}',
|
||||
$invite_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">You’re invited</h1>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}you have been invited{{if .InviterName}} by <strong style="color:#9d2a83;">{{.InviterName}}</strong>{{end}} to join Yimaru Academy.</p>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}you have been invited{{if .InviterName}} by <strong style="color:#9d2a83;">{{.InviterName}}</strong>{{end}} to join Rezina.</p>
|
||||
<p style="margin:0 0 24px;text-align:center;"><a href="{{.InviteLink}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Accept invitation</a></p>
|
||||
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">Or copy this link: <a href="{{.InviteLink}}" style="color:#9d2a83;">{{.InviteLink}}</a></p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$invite_html$,
|
||||
'["FirstName", "InviterName", "InviteLink"]'::jsonb,
|
||||
|
|
@ -93,7 +93,7 @@ Accept your invitation: {{.InviteLink}}',
|
|||
(
|
||||
'password_reset',
|
||||
'Password Reset',
|
||||
'Reset your Yimaru Academy password',
|
||||
'Reset your Rezina password',
|
||||
'Hi{{if .FirstName}} {{.FirstName}}{{end}},
|
||||
|
||||
Reset your password: {{.ResetLink}}
|
||||
|
|
@ -101,23 +101,23 @@ Reset your password: {{.ResetLink}}
|
|||
This link expires in {{.ExpiresMinutes}} minutes.',
|
||||
$reset_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Reset your password</h1>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}we received a request to reset your Yimaru Academy password. The link below expires in {{.ExpiresMinutes}} minutes.</p>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}we received a request to reset your Rezina password. The link below expires in {{.ExpiresMinutes}} minutes.</p>
|
||||
<p style="margin:0 0 24px;text-align:center;"><a href="{{.ResetLink}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Reset password</a></p>
|
||||
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">If you did not request a reset, ignore this email.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$reset_html$,
|
||||
'["FirstName", "ResetLink", "ExpiresMinutes"]'::jsonb,
|
||||
|
|
@ -127,28 +127,28 @@ This link expires in {{.ExpiresMinutes}} minutes.',
|
|||
(
|
||||
'welcome',
|
||||
'Welcome Email',
|
||||
'Welcome to Yimaru Academy',
|
||||
'Welcome to Rezina',
|
||||
'Hi{{if .FirstName}} {{.FirstName}}{{end}},
|
||||
|
||||
Welcome to Yimaru Academy! Sign in to get started: {{.LoginURL}}',
|
||||
Welcome to Rezina! Sign in to get started: {{.LoginURL}}',
|
||||
$welcome_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Welcome aboard</h1>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}your Yimaru Academy account is ready. Start learning at your own pace.</p>
|
||||
<p style="margin:0 0 24px;text-align:center;"><a href="{{.LoginURL}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Sign in to Yimaru Academy</a></p>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}your Rezina account is ready. Start learning at your own pace.</p>
|
||||
<p style="margin:0 0 24px;text-align:center;"><a href="{{.LoginURL}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Sign in to Rezina</a></p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$welcome_html$,
|
||||
'["FirstName", "LoginURL"]'::jsonb,
|
||||
|
|
@ -162,13 +162,13 @@ Welcome to Yimaru Academy! Sign in to get started: {{.LoginURL}}',
|
|||
'{{.Message}}',
|
||||
$custom_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
|
|
@ -176,7 +176,7 @@ Welcome to Yimaru Academy! Sign in to get started: {{.LoginURL}}',
|
|||
<div style="margin:0;color:#666666;font-size:15px;line-height:1.6;">{{.Message}}</div>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$custom_html$,
|
||||
'["Subject", "Message"]'::jsonb,
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
-- Refresh system email templates with Yimaru Academy branded HTML (admin portal colors).
|
||||
-- Refresh system email templates with Rezina branded HTML (admin portal colors).
|
||||
-- Safe to run after 000066 when seeds used the original plain layout.
|
||||
|
||||
UPDATE email_templates SET
|
||||
name = 'One-Time Password',
|
||||
subject = 'Yimaru Academy — Your verification code',
|
||||
body_text = 'Yimaru Academy{{if .FirstName}}, {{.FirstName}}{{end}}
|
||||
subject = 'Rezina — Your verification code',
|
||||
body_text = 'Rezina{{if .FirstName}}, {{.FirstName}}{{end}}
|
||||
|
||||
Your verification code is {{.OTP}}.
|
||||
It expires in {{.ExpiresMinutes}} minutes.
|
||||
|
|
@ -12,18 +12,18 @@ It expires in {{.ExpiresMinutes}} minutes.
|
|||
Please do not share this code with anyone.',
|
||||
body_html = $otp_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;letter-spacing:0.3px;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;letter-spacing:0.3px;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;line-height:1.3;">Your verification code</h1>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}use the code below to continue signing in to Yimaru Academy.</p>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}use the code below to continue signing in to Rezina.</p>
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0"><tr><td style="background-color:#eef4ff;border-radius:8px;padding:20px;border:1px solid #e0e8f5;text-align:center;">
|
||||
<p style="margin:0 0 6px;color:#9d2a83;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;">One-time password</p>
|
||||
<p style="margin:0;color:#333333;font-size:34px;font-weight:700;letter-spacing:8px;font-family:Consolas,Monaco,monospace;">{{.OTP}}</p>
|
||||
|
|
@ -32,7 +32,7 @@ Please do not share this code with anyone.',
|
|||
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">If you did not request this code, you can safely ignore this email.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;line-height:1.5;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;line-height:1.5;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$otp_html$,
|
||||
updated_at = NOW()
|
||||
|
|
@ -40,31 +40,31 @@ WHERE slug = 'otp';
|
|||
|
||||
UPDATE email_templates SET
|
||||
name = 'User Invitation',
|
||||
subject = 'You are invited to Yimaru Academy',
|
||||
subject = 'You are invited to Rezina',
|
||||
body_text = 'Hi{{if .FirstName}} {{.FirstName}}{{end}},
|
||||
|
||||
You have been invited{{if .InviterName}} by {{.InviterName}}{{end}} to join Yimaru Academy.
|
||||
You have been invited{{if .InviterName}} by {{.InviterName}}{{end}} to join Rezina.
|
||||
|
||||
Accept your invitation: {{.InviteLink}}',
|
||||
body_html = $invite_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">You’re invited</h1>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}you have been invited{{if .InviterName}} by <strong style="color:#9d2a83;">{{.InviterName}}</strong>{{end}} to join Yimaru Academy.</p>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}you have been invited{{if .InviterName}} by <strong style="color:#9d2a83;">{{.InviterName}}</strong>{{end}} to join Rezina.</p>
|
||||
<p style="margin:0 0 24px;text-align:center;"><a href="{{.InviteLink}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Accept invitation</a></p>
|
||||
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">Or copy this link: <a href="{{.InviteLink}}" style="color:#9d2a83;">{{.InviteLink}}</a></p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$invite_html$,
|
||||
updated_at = NOW()
|
||||
|
|
@ -72,7 +72,7 @@ WHERE slug = 'invitation';
|
|||
|
||||
UPDATE email_templates SET
|
||||
name = 'Password Reset',
|
||||
subject = 'Reset your Yimaru Academy password',
|
||||
subject = 'Reset your Rezina password',
|
||||
body_text = 'Hi{{if .FirstName}} {{.FirstName}}{{end}},
|
||||
|
||||
Reset your password: {{.ResetLink}}
|
||||
|
|
@ -80,23 +80,23 @@ Reset your password: {{.ResetLink}}
|
|||
This link expires in {{.ExpiresMinutes}} minutes.',
|
||||
body_html = $reset_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Reset your password</h1>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}we received a request to reset your Yimaru Academy password. The link below expires in {{.ExpiresMinutes}} minutes.</p>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}we received a request to reset your Rezina password. The link below expires in {{.ExpiresMinutes}} minutes.</p>
|
||||
<p style="margin:0 0 24px;text-align:center;"><a href="{{.ResetLink}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Reset password</a></p>
|
||||
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">If you did not request a reset, ignore this email.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$reset_html$,
|
||||
updated_at = NOW()
|
||||
|
|
@ -104,28 +104,28 @@ WHERE slug = 'password_reset';
|
|||
|
||||
UPDATE email_templates SET
|
||||
name = 'Welcome Email',
|
||||
subject = 'Welcome to Yimaru Academy',
|
||||
subject = 'Welcome to Rezina',
|
||||
body_text = 'Hi{{if .FirstName}} {{.FirstName}}{{end}},
|
||||
|
||||
Welcome to Yimaru Academy! Sign in to get started: {{.LoginURL}}',
|
||||
Welcome to Rezina! Sign in to get started: {{.LoginURL}}',
|
||||
body_html = $welcome_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Welcome aboard</h1>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}your Yimaru Academy account is ready. Start learning at your own pace.</p>
|
||||
<p style="margin:0 0 24px;text-align:center;"><a href="{{.LoginURL}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Sign in to Yimaru Academy</a></p>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}your Rezina account is ready. Start learning at your own pace.</p>
|
||||
<p style="margin:0 0 24px;text-align:center;"><a href="{{.LoginURL}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Sign in to Rezina</a></p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$welcome_html$,
|
||||
updated_at = NOW()
|
||||
|
|
@ -135,13 +135,13 @@ UPDATE email_templates SET
|
|||
name = 'Custom Message',
|
||||
body_html = $custom_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
|
|
@ -149,7 +149,7 @@ UPDATE email_templates SET
|
|||
<div style="margin:0;color:#666666;font-size:15px;line-height:1.6;">{{.Message}}</div>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$custom_html$,
|
||||
updated_at = NOW()
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ WITH email_ranked AS (
|
|||
)
|
||||
UPDATE users u
|
||||
SET
|
||||
email = 'dedup-' || u.id || '@invalid.yimaru.local',
|
||||
email = 'dedup-' || u.id || '@invalid.rezina.local',
|
||||
status = CASE WHEN u.status = 'ACTIVE' THEN 'DEACTIVATED' ELSE u.status END,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
FROM email_ranked r
|
||||
|
|
@ -120,7 +120,7 @@ SET
|
|||
phone_number = NULL,
|
||||
email = COALESCE(
|
||||
NULLIF(TRIM(u.email), ''),
|
||||
'dedup-' || u.id || '@invalid.yimaru.local'
|
||||
'dedup-' || u.id || '@invalid.rezina.local'
|
||||
),
|
||||
status = CASE WHEN u.status = 'ACTIVE' THEN 'DEACTIVATED' ELSE u.status END,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ INSERT INTO email_templates (slug, name, subject, body_text, body_html, variable
|
|||
VALUES (
|
||||
'subscription_activated',
|
||||
'Subscription Activated',
|
||||
'Your Yimaru Academy subscription is active',
|
||||
'Your Rezina subscription is active',
|
||||
'Hi{{if .FirstName}} {{.FirstName}}{{end}},
|
||||
|
||||
Your "{{.PlanName}}" {{.PackageLabel}} subscription is now active{{if .ExpiresLabel}} until {{.ExpiresLabel}}{{else if .IsLifetime}} with lifetime access{{end}}.
|
||||
|
|
@ -10,23 +10,23 @@ Your "{{.PlanName}}" {{.PackageLabel}} subscription is now active{{if .ExpiresLa
|
|||
Sign in to start learning: {{.LoginURL}}',
|
||||
$subscription_html$<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Yimaru Academy</title></head>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
|
||||
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
|
||||
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
|
||||
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Yimaru Academy</p>
|
||||
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
|
||||
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px;">
|
||||
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Subscription active</h1>
|
||||
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}your <strong style="color:#9d2a83;">{{.PlanName}}</strong> {{.PackageLabel}} package is now active.{{if .IsLifetime}} You have lifetime access.{{else if .ExpiresLabel}} It is valid until <strong style="color:#333333;">{{.ExpiresLabel}}</strong>.{{end}}</p>
|
||||
<p style="margin:0 0 24px;text-align:center;"><a href="{{.LoginURL}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Start learning</a></p>
|
||||
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">Thank you for subscribing to Yimaru Academy.</p>
|
||||
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">Thank you for subscribing to Rezina.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Yimaru Academy · All rights reserved</p>
|
||||
<p style="margin:0;color:#999999;font-size:12px;">© 2026 Rezina · All rights reserved</p>
|
||||
</td></tr>
|
||||
</table></td></tr></table></body></html>$subscription_html$,
|
||||
'["FirstName", "PlanName", "PackageLabel", "LoginURL", "ExpiresLabel", "IsLifetime"]'::jsonb,
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
DROP INDEX IF EXISTS idx_subscription_plans_category_period;
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
-- One catalog row per category + billing period (free vs paid is not part of the key).
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_subscription_plans_category_period
|
||||
ON subscription_plans (category, is_lifetime, duration_value, duration_unit);
|
||||
5
db/migrations/000111_subscription_plan_is_free.down.sql
Normal file
5
db/migrations/000111_subscription_plan_is_free.down.sql
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
ALTER TABLE subscription_plans
|
||||
DROP CONSTRAINT IF EXISTS chk_subscription_plans_free_price;
|
||||
|
||||
ALTER TABLE subscription_plans
|
||||
DROP COLUMN IF EXISTS is_free;
|
||||
15
db/migrations/000111_subscription_plan_is_free.up.sql
Normal file
15
db/migrations/000111_subscription_plan_is_free.up.sql
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
ALTER TABLE subscription_plans
|
||||
ADD COLUMN IF NOT EXISTS is_free BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
-- Legacy zero-price rows become explicitly free before the price constraint is enforced.
|
||||
UPDATE subscription_plans
|
||||
SET is_free = TRUE
|
||||
WHERE price = 0
|
||||
AND is_free = FALSE;
|
||||
|
||||
ALTER TABLE subscription_plans
|
||||
ADD CONSTRAINT chk_subscription_plans_free_price
|
||||
CHECK (
|
||||
(is_free = TRUE AND price = 0)
|
||||
OR (is_free = FALSE AND price > 0)
|
||||
);
|
||||
8
db/migrations/000112_rezina_email_brand.down.sql
Normal file
8
db/migrations/000112_rezina_email_brand.down.sql
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
-- Restore the previous email branding if this migration is rolled back.
|
||||
UPDATE email_templates
|
||||
SET name = REPLACE(name, 'Rezina', 'Yimaru Academy'),
|
||||
subject = REPLACE(subject, 'Rezina', 'Yimaru Academy'),
|
||||
body_text = REPLACE(body_text, 'Rezina', 'Yimaru Academy'),
|
||||
body_html = REPLACE(body_html, 'Rezina', 'Yimaru Academy'),
|
||||
updated_at = NOW()
|
||||
WHERE slug IN ('otp', 'invitation', 'password_reset', 'welcome', 'custom_message', 'subscription_activated');
|
||||
11
db/migrations/000112_rezina_email_brand.up.sql
Normal file
11
db/migrations/000112_rezina_email_brand.up.sql
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
-- Update system email templates to the Rezina brand for existing installations.
|
||||
UPDATE email_templates
|
||||
SET name = REPLACE(name, 'Yimaru Academy', 'Rezina'),
|
||||
subject = REPLACE(subject, 'Yimaru Academy', 'Rezina'),
|
||||
body_text = REPLACE(body_text, 'Yimaru Academy', 'Rezina'),
|
||||
body_html = REPLACE(body_html, 'Yimaru Academy', 'Rezina'),
|
||||
updated_at = NOW()
|
||||
WHERE name ILIKE '%Yimaru Academy%'
|
||||
OR subject ILIKE '%Yimaru Academy%'
|
||||
OR body_text ILIKE '%Yimaru Academy%'
|
||||
OR body_html ILIKE '%Yimaru Academy%';
|
||||
38
db/migrations/000113_generic_assessment_levels.down.sql
Normal file
38
db/migrations/000113_generic_assessment_levels.down.sql
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
DROP INDEX IF EXISTS idx_initial_assessment_one_published_per_level;
|
||||
|
||||
UPDATE question_sets
|
||||
SET description = CASE UPPER(TRIM(description))
|
||||
WHEN 'FOUNDATION' THEN 'A1' WHEN 'DEVELOPING' THEN 'A2' WHEN 'SECURE' THEN 'B1'
|
||||
WHEN 'EXTENSION' THEN 'B2' WHEN 'ADVANCED' THEN 'C1' WHEN 'MASTERY' THEN 'C2'
|
||||
ELSE description END,
|
||||
updated_at = NOW()
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND UPPER(TRIM(description)) IN ('FOUNDATION', 'DEVELOPING', 'SECURE', 'EXTENSION', 'ADVANCED', 'MASTERY');
|
||||
|
||||
UPDATE user_initial_assessment_progress
|
||||
SET next_level = CASE UPPER(TRIM(next_level))
|
||||
WHEN 'FOUNDATION' THEN 'A1' WHEN 'DEVELOPING' THEN 'A2' WHEN 'SECURE' THEN 'B1'
|
||||
WHEN 'EXTENSION' THEN 'B2' WHEN 'ADVANCED' THEN 'C1' WHEN 'MASTERY' THEN 'C2'
|
||||
ELSE UPPER(TRIM(next_level)) END,
|
||||
highest_passed_level = CASE UPPER(TRIM(highest_passed_level))
|
||||
WHEN 'FOUNDATION' THEN 'A1' WHEN 'DEVELOPING' THEN 'A2' WHEN 'SECURE' THEN 'B1'
|
||||
WHEN 'EXTENSION' THEN 'B2' WHEN 'ADVANCED' THEN 'C1' WHEN 'MASTERY' THEN 'C2'
|
||||
ELSE UPPER(TRIM(highest_passed_level)) END;
|
||||
|
||||
UPDATE initial_assessment_level_thresholds
|
||||
SET level = CASE UPPER(TRIM(level))
|
||||
WHEN 'FOUNDATION' THEN 'A1' WHEN 'DEVELOPING' THEN 'A2' WHEN 'SECURE' THEN 'B1'
|
||||
WHEN 'EXTENSION' THEN 'B2' WHEN 'ADVANCED' THEN 'C1' WHEN 'MASTERY' THEN 'C2'
|
||||
ELSE UPPER(TRIM(level)) END;
|
||||
|
||||
ALTER TABLE user_initial_assessment_progress
|
||||
ADD CONSTRAINT user_initial_assessment_progress_next_level_check
|
||||
CHECK (UPPER(TRIM(next_level)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')),
|
||||
ADD CONSTRAINT user_initial_assessment_progress_highest_passed_check
|
||||
CHECK (highest_passed_level IS NULL OR UPPER(TRIM(highest_passed_level)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2'));
|
||||
|
||||
CREATE UNIQUE INDEX idx_initial_assessment_one_published_per_level
|
||||
ON question_sets ((UPPER(TRIM(description))))
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND UPPER(TRIM(status)) = 'PUBLISHED'
|
||||
AND UPPER(TRIM(description)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2');
|
||||
42
db/migrations/000113_generic_assessment_levels.up.sql
Normal file
42
db/migrations/000113_generic_assessment_levels.up.sql
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
-- Replace CEFR defaults with curriculum-defined remediation bands while retaining
|
||||
-- existing assessment data and allowing longer administrator-defined labels.
|
||||
ALTER TABLE initial_assessment_level_thresholds ALTER COLUMN level TYPE VARCHAR(64);
|
||||
UPDATE initial_assessment_level_thresholds
|
||||
SET level = CASE UPPER(TRIM(level))
|
||||
WHEN 'A1' THEN 'FOUNDATION'
|
||||
WHEN 'A2' THEN 'DEVELOPING'
|
||||
WHEN 'B1' THEN 'SECURE'
|
||||
WHEN 'B2' THEN 'EXTENSION'
|
||||
WHEN 'C1' THEN 'ADVANCED'
|
||||
WHEN 'C2' THEN 'MASTERY'
|
||||
ELSE UPPER(TRIM(level)) END;
|
||||
|
||||
ALTER TABLE user_initial_assessment_progress ALTER COLUMN next_level TYPE VARCHAR(64);
|
||||
ALTER TABLE user_initial_assessment_progress ALTER COLUMN highest_passed_level TYPE VARCHAR(64);
|
||||
ALTER TABLE user_initial_assessment_progress DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_next_level_check;
|
||||
ALTER TABLE user_initial_assessment_progress DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_highest_passed_check;
|
||||
UPDATE user_initial_assessment_progress
|
||||
SET next_level = CASE UPPER(TRIM(next_level))
|
||||
WHEN 'A1' THEN 'FOUNDATION' WHEN 'A2' THEN 'DEVELOPING' WHEN 'B1' THEN 'SECURE'
|
||||
WHEN 'B2' THEN 'EXTENSION' WHEN 'C1' THEN 'ADVANCED' WHEN 'C2' THEN 'MASTERY'
|
||||
ELSE UPPER(TRIM(next_level)) END,
|
||||
highest_passed_level = CASE UPPER(TRIM(highest_passed_level))
|
||||
WHEN 'A1' THEN 'FOUNDATION' WHEN 'A2' THEN 'DEVELOPING' WHEN 'B1' THEN 'SECURE'
|
||||
WHEN 'B2' THEN 'EXTENSION' WHEN 'C1' THEN 'ADVANCED' WHEN 'C2' THEN 'MASTERY'
|
||||
ELSE UPPER(TRIM(highest_passed_level)) END;
|
||||
|
||||
UPDATE question_sets
|
||||
SET description = CASE UPPER(TRIM(description))
|
||||
WHEN 'A1' THEN 'FOUNDATION' WHEN 'A2' THEN 'DEVELOPING' WHEN 'B1' THEN 'SECURE'
|
||||
WHEN 'B2' THEN 'EXTENSION' WHEN 'C1' THEN 'ADVANCED' WHEN 'C2' THEN 'MASTERY'
|
||||
ELSE description END,
|
||||
updated_at = NOW()
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND UPPER(TRIM(description)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2');
|
||||
|
||||
DROP INDEX IF EXISTS idx_initial_assessment_one_published_per_level;
|
||||
CREATE UNIQUE INDEX idx_initial_assessment_one_published_per_level
|
||||
ON question_sets ((UPPER(TRIM(description))), (COALESCE(UPPER(TRIM(owner_type)), 'STANDALONE')), (COALESCE(owner_id, 0)))
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND UPPER(TRIM(status)) = 'PUBLISHED'
|
||||
AND NULLIF(TRIM(description), '') IS NOT NULL;
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
ALTER TABLE user_initial_assessment_progress
|
||||
DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_pkey;
|
||||
|
||||
ALTER TABLE user_initial_assessment_progress
|
||||
ADD CONSTRAINT user_initial_assessment_progress_pkey PRIMARY KEY (user_id);
|
||||
|
||||
ALTER TABLE user_initial_assessment_progress DROP COLUMN IF EXISTS subject_id;
|
||||
9
db/migrations/000114_subject_assessment_progress.up.sql
Normal file
9
db/migrations/000114_subject_assessment_progress.up.sql
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
-- Persist placement independently for each subject (subject_id is the subject/course identifier).
|
||||
ALTER TABLE user_initial_assessment_progress
|
||||
ADD COLUMN subject_id BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
ALTER TABLE user_initial_assessment_progress
|
||||
DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_pkey;
|
||||
|
||||
ALTER TABLE user_initial_assessment_progress
|
||||
ADD CONSTRAINT user_initial_assessment_progress_pkey PRIMARY KEY (user_id, subject_id);
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
ALTER TABLE programs DROP CONSTRAINT IF EXISTS chk_programs_category;
|
||||
UPDATE programs SET category = 'LEARN_ENGLISH', updated_at = NOW();
|
||||
ALTER TABLE programs
|
||||
ADD CONSTRAINT chk_programs_category CHECK (category = 'LEARN_ENGLISH');
|
||||
|
||||
UPDATE subscription_plans
|
||||
SET category = 'LEARN_ENGLISH', updated_at = NOW()
|
||||
WHERE category = 'EDUCATION';
|
||||
|
||||
ALTER TABLE subscription_plans DROP CONSTRAINT IF EXISTS chk_subscription_plans_category;
|
||||
ALTER TABLE subscription_plans
|
||||
ADD CONSTRAINT chk_subscription_plans_category
|
||||
CHECK (category IN ('LEARN_ENGLISH', 'IELTS', 'DUOLINGO'));
|
||||
19
db/migrations/000115_education_subscription_category.up.sql
Normal file
19
db/migrations/000115_education_subscription_category.up.sql
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
-- Generalize the active LMS subscription product. Keep inactive legacy plan rows
|
||||
-- available for historical billing and reporting records.
|
||||
ALTER TABLE subscription_plans DROP CONSTRAINT IF EXISTS chk_subscription_plans_category;
|
||||
ALTER TABLE subscription_plans
|
||||
ADD CONSTRAINT chk_subscription_plans_category
|
||||
CHECK (category IN ('EDUCATION', 'LEARN_ENGLISH', 'IELTS', 'DUOLINGO'));
|
||||
|
||||
UPDATE subscription_plans
|
||||
SET category = 'EDUCATION', updated_at = NOW()
|
||||
WHERE category = 'LEARN_ENGLISH';
|
||||
|
||||
UPDATE subscription_plans
|
||||
SET is_active = FALSE, updated_at = NOW()
|
||||
WHERE category IN ('IELTS', 'DUOLINGO');
|
||||
|
||||
ALTER TABLE programs DROP CONSTRAINT IF EXISTS chk_programs_category;
|
||||
UPDATE programs SET category = 'EDUCATION', updated_at = NOW();
|
||||
ALTER TABLE programs
|
||||
ADD CONSTRAINT chk_programs_category CHECK (category = 'EDUCATION');
|
||||
20
db/migrations/000116_remove_initial_assessment.down.sql
Normal file
20
db/migrations/000116_remove_initial_assessment.down.sql
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
ALTER TABLE question_sets DROP CONSTRAINT IF EXISTS question_sets_set_type_check;
|
||||
ALTER TABLE question_sets ADD CONSTRAINT question_sets_set_type_check
|
||||
CHECK (set_type IN ('PRACTICE', 'INITIAL_ASSESSMENT', 'QUIZ', 'EXAM', 'SURVEY', 'CAPSTONE'));
|
||||
|
||||
UPDATE question_sets qs
|
||||
SET set_type = retired.set_type
|
||||
FROM retired_initial_assessment_question_sets retired
|
||||
WHERE retired.question_set_id = qs.id;
|
||||
|
||||
ALTER TABLE retired_user_initial_assessment_progress RENAME TO user_initial_assessment_progress;
|
||||
ALTER TABLE retired_initial_assessment_level_thresholds RENAME TO initial_assessment_level_thresholds;
|
||||
|
||||
ALTER TABLE users ADD COLUMN initial_assessment_completed BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
UPDATE users u
|
||||
SET initial_assessment_completed = archive.completed
|
||||
FROM retired_initial_assessment_completion archive
|
||||
WHERE archive.user_id = u.id;
|
||||
|
||||
DROP TABLE retired_initial_assessment_completion;
|
||||
DROP TABLE retired_initial_assessment_question_sets;
|
||||
28
db/migrations/000116_remove_initial_assessment.up.sql
Normal file
28
db/migrations/000116_remove_initial_assessment.up.sql
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
-- Preserve existing assessment questions as ordinary practice and archive learner/configuration
|
||||
-- metadata so a rollback can restore the previous feature without losing its records.
|
||||
CREATE TABLE retired_initial_assessment_question_sets (
|
||||
question_set_id BIGINT PRIMARY KEY,
|
||||
set_type VARCHAR(30) NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO retired_initial_assessment_question_sets (question_set_id, set_type)
|
||||
SELECT id, set_type FROM question_sets WHERE set_type = 'INITIAL_ASSESSMENT';
|
||||
|
||||
UPDATE question_sets SET set_type = 'PRACTICE' WHERE set_type = 'INITIAL_ASSESSMENT';
|
||||
|
||||
ALTER TABLE question_sets DROP CONSTRAINT IF EXISTS question_sets_set_type_check;
|
||||
ALTER TABLE question_sets ADD CONSTRAINT question_sets_set_type_check
|
||||
CHECK (set_type IN ('PRACTICE', 'QUIZ', 'EXAM', 'SURVEY', 'CAPSTONE'));
|
||||
|
||||
ALTER TABLE initial_assessment_level_thresholds RENAME TO retired_initial_assessment_level_thresholds;
|
||||
ALTER TABLE user_initial_assessment_progress RENAME TO retired_user_initial_assessment_progress;
|
||||
|
||||
CREATE TABLE retired_initial_assessment_completion (
|
||||
user_id BIGINT PRIMARY KEY,
|
||||
completed BOOLEAN NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO retired_initial_assessment_completion (user_id, completed)
|
||||
SELECT id, initial_assessment_completed FROM users;
|
||||
|
||||
ALTER TABLE users DROP COLUMN initial_assessment_completed;
|
||||
|
|
@ -72,37 +72,6 @@ WHERE id = $1;
|
|||
DELETE FROM question_sets
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: GetInitialAssessmentSet :one
|
||||
SELECT *
|
||||
FROM question_sets
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND status = 'PUBLISHED'
|
||||
AND UPPER(TRIM(COALESCE(description, ''))) = 'A1'
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- name: GetInitialAssessmentSetByLevel :one
|
||||
SELECT *
|
||||
FROM question_sets
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND status = 'PUBLISHED'
|
||||
AND UPPER(TRIM(COALESCE(description, ''))) = sqlc.arg('level')::text
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN owner_type IS NULL OR UPPER(TRIM(owner_type)) = 'STANDALONE' THEN 0
|
||||
ELSE 1
|
||||
END,
|
||||
created_at DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- name: ListPublishedInitialAssessmentLevels :many
|
||||
SELECT DISTINCT UPPER(TRIM(description))::text AS level
|
||||
FROM question_sets
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND status = 'PUBLISHED'
|
||||
AND UPPER(TRIM(COALESCE(description, ''))) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')
|
||||
ORDER BY level;
|
||||
|
||||
-- name: AddUserPersonaToQuestionSet :one
|
||||
INSERT INTO question_set_personas (
|
||||
question_set_id,
|
||||
|
|
|
|||
|
|
@ -4,14 +4,28 @@
|
|||
|
||||
-- name: CreateSubscriptionPlan :one
|
||||
INSERT INTO subscription_plans (
|
||||
name, description, category, duration_value, duration_unit, price, currency, is_lifetime, is_active
|
||||
name, description, category, duration_value, duration_unit, price, currency, is_lifetime, is_free, is_active
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, false), COALESCE($9, true))
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, false), COALESCE($9, false), COALESCE($10, true))
|
||||
RETURNING *;
|
||||
|
||||
-- name: GetSubscriptionPlanByID :one
|
||||
SELECT * FROM subscription_plans WHERE id = $1;
|
||||
|
||||
-- name: SubscriptionPlanExistsWithCategoryPeriod :one
|
||||
SELECT EXISTS(
|
||||
SELECT 1
|
||||
FROM subscription_plans
|
||||
WHERE category = $1
|
||||
AND is_lifetime = $2
|
||||
AND duration_value = $3
|
||||
AND duration_unit = $4
|
||||
AND (
|
||||
sqlc.narg('exclude_plan_id')::bigint IS NULL
|
||||
OR id <> sqlc.narg('exclude_plan_id')::bigint
|
||||
)
|
||||
);
|
||||
|
||||
-- name: ListSubscriptionPlans :many
|
||||
SELECT * FROM subscription_plans
|
||||
WHERE (
|
||||
|
|
@ -41,6 +55,7 @@ SET
|
|||
price = COALESCE(sqlc.narg('price')::numeric, price),
|
||||
currency = COALESCE(sqlc.narg('currency')::varchar, currency),
|
||||
is_lifetime = COALESCE(sqlc.narg('is_lifetime')::boolean, is_lifetime),
|
||||
is_free = COALESCE(sqlc.narg('is_free')::boolean, is_free),
|
||||
is_active = COALESCE(sqlc.narg('is_active')::boolean, is_active),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = sqlc.arg('id');
|
||||
|
|
|
|||
|
|
@ -94,7 +94,6 @@ INSERT INTO users (
|
|||
language_challange,
|
||||
favourite_topic,
|
||||
|
||||
initial_assessment_completed,
|
||||
email_verified,
|
||||
phone_verified,
|
||||
status,
|
||||
|
|
@ -130,7 +129,6 @@ VALUES (
|
|||
$22,
|
||||
$23,
|
||||
$24,
|
||||
$25,
|
||||
CURRENT_TIMESTAMP
|
||||
)
|
||||
RETURNING
|
||||
|
|
@ -154,7 +152,6 @@ RETURNING
|
|||
language_challange,
|
||||
favourite_topic,
|
||||
|
||||
initial_assessment_completed,
|
||||
email_verified,
|
||||
phone_verified,
|
||||
status,
|
||||
|
|
@ -213,7 +210,6 @@ SELECT
|
|||
language_goal,
|
||||
language_challange,
|
||||
favourite_topic,
|
||||
initial_assessment_completed,
|
||||
email_verified,
|
||||
phone_verified,
|
||||
status,
|
||||
|
|
@ -256,7 +252,6 @@ WHERE
|
|||
AND (sqlc.narg('learning_goal')::TEXT IS NULL OR LOWER(TRIM(COALESCE(learning_goal, ''))) = LOWER(TRIM(sqlc.narg('learning_goal')::TEXT)))
|
||||
AND (sqlc.narg('knowledge_level')::TEXT IS NULL OR LOWER(TRIM(COALESCE(knowledge_level, ''))) = LOWER(TRIM(sqlc.narg('knowledge_level')::TEXT)))
|
||||
AND (sqlc.narg('profile_completed')::BOOLEAN IS NULL OR profile_completed = sqlc.narg('profile_completed')::BOOLEAN)
|
||||
AND (sqlc.narg('initial_assessment_completed')::BOOLEAN IS NULL OR initial_assessment_completed = sqlc.narg('initial_assessment_completed')::BOOLEAN)
|
||||
AND (
|
||||
sqlc.narg('min_profile_completion_pct')::INT IS NULL
|
||||
OR profile_completion_percentage >= sqlc.narg('min_profile_completion_pct')::INT
|
||||
|
|
@ -471,7 +466,6 @@ SELECT
|
|||
language_challange,
|
||||
favourite_topic,
|
||||
|
||||
initial_assessment_completed,
|
||||
profile_picture_url,
|
||||
preferred_language,
|
||||
email_verified,
|
||||
|
|
@ -511,13 +505,12 @@ SET
|
|||
language_goal = COALESCE($11, language_goal),
|
||||
language_challange = COALESCE($12, language_challange),
|
||||
favourite_topic = COALESCE($13, favourite_topic),
|
||||
initial_assessment_completed = COALESCE($14, initial_assessment_completed),
|
||||
profile_picture_url = COALESCE($15, profile_picture_url),
|
||||
preferred_language = COALESCE($16, preferred_language),
|
||||
gender = COALESCE($17, gender),
|
||||
birth_day = COALESCE($18, birth_day),
|
||||
profile_picture_url = COALESCE($14, profile_picture_url),
|
||||
preferred_language = COALESCE($15, preferred_language),
|
||||
gender = COALESCE($16, gender),
|
||||
birth_day = COALESCE($17, birth_day),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $19;
|
||||
WHERE id = $18;
|
||||
|
||||
-- name: DeleteUser :exec
|
||||
DELETE FROM users
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ version: "3.8"
|
|||
|
||||
services:
|
||||
postgres:
|
||||
container_name: yimaru-backend-postgres-1
|
||||
container_name: rezina-backend-postgres-1
|
||||
image: postgres:16-alpine
|
||||
ports:
|
||||
- "5592:5422"
|
||||
|
|
@ -22,7 +22,7 @@ services:
|
|||
- ./exports:/exports
|
||||
|
||||
pgadmin:
|
||||
container_name: yimaru-pgadmin
|
||||
container_name: rezina-pgadmin
|
||||
image: dpage/pgadmin4:latest
|
||||
restart: always
|
||||
ports:
|
||||
|
|
@ -39,7 +39,7 @@ services:
|
|||
- pgadmin_data:/var/lib/pgadmin
|
||||
|
||||
mongo:
|
||||
container_name: yimaru-mongo
|
||||
container_name: rezina-mongo
|
||||
image: mongo:7.0.11
|
||||
restart: always
|
||||
ports:
|
||||
|
|
@ -58,7 +58,7 @@ services:
|
|||
retries: 5
|
||||
|
||||
minio:
|
||||
container_name: yimaru-minio
|
||||
container_name: rezina-minio
|
||||
image: minio/minio:latest
|
||||
restart: always
|
||||
ports:
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -1,6 +1,6 @@
|
|||
# Activity Logs — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate the **platform activity log (audit trail)** into the Yimaru admin panel. It covers authentication, RBAC permissions, read-only APIs, filtering, pagination, action/resource catalogs, actor resolution, recommended UI patterns, TypeScript types, and how activity logs relate to other “activity” endpoints on user profiles.
|
||||
This guide documents how to integrate the **platform activity log (audit trail)** into the Rezina admin panel. It covers authentication, RBAC permissions, read-only APIs, filtering, pagination, action/resource catalogs, actor resolution, recommended UI patterns, TypeScript types, and how activity logs relate to other “activity” endpoints on user profiles.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -71,7 +71,7 @@ flowchart LR
|
|||
UserAudit["User audit filter (actor_id)"]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API"]
|
||||
subgraph API["Rezina API"]
|
||||
ListRoute["GET /activity-logs"]
|
||||
GetRoute["GET /activity-logs/:id"]
|
||||
end
|
||||
|
|
@ -310,7 +310,7 @@ Authorization: Bearer eyJhbG...
|
|||
"actor_id": 7,
|
||||
"actor_role": "ADMIN",
|
||||
"actor_name": "Jane Admin",
|
||||
"actor_email": "jane@yimaru.com",
|
||||
"actor_email": "jane@rezina.com",
|
||||
"actor_kind": "team_member",
|
||||
"action": "FAQ_UPDATED",
|
||||
"resource_type": "FAQ",
|
||||
|
|
@ -362,7 +362,7 @@ Authorization: Bearer <token>
|
|||
"actor_id": 7,
|
||||
"actor_role": "ADMIN",
|
||||
"actor_name": "Jane Admin",
|
||||
"actor_email": "jane@yimaru.com",
|
||||
"actor_email": "jane@rezina.com",
|
||||
"actor_kind": "team_member",
|
||||
"action": "NOTIFICATION_BULK_SENT",
|
||||
"resource_type": "NOTIFICATION",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Admin Subscription Grant / Extend / Cancel — Admin Panel Integration Guide
|
||||
# Admin Subscription Grant / Extend / Cancel — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate **admin-managed learner subscriptions** into the Yimaru admin panel: a **unified grant-or-extend** action (pick a plan), and **cancel**.
|
||||
This guide documents how to integrate **admin-managed learner subscriptions** into the Rezina admin panel: a **unified grant-or-extend** action (pick a plan), and **cancel**.
|
||||
|
||||
**Use this guide when:** building or updating the learner profile "Subscriptions / Billing" section.
|
||||
|
||||
|
|
@ -68,7 +68,7 @@ Admins manage learner access without Chapa/ArifPay checkout via **one** apply en
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Admin as Admin panel
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
participant DB as Postgres
|
||||
participant Notif as Learner notifications
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Bulk & Scheduled Notifications — Integration Guide
|
||||
|
||||
This guide documents how admin clients integrate with the Yimaru backend to send **immediate** or **scheduled** bulk notifications across four channels:
|
||||
This guide documents how admin clients integrate with the Rezina backend to send **immediate** or **scheduled** bulk notifications across four channels:
|
||||
|
||||
| Channel | Value | Endpoint |
|
||||
|---------|-------|----------|
|
||||
|
|
@ -43,7 +43,7 @@ Bulk and single **email** sends support optional **email template** selection (`
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Admin as Admin client
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
participant DB as PostgreSQL
|
||||
participant Worker as Scheduler worker
|
||||
participant Channel as SMS / Email / FCM / WS
|
||||
|
|
@ -291,7 +291,7 @@ Content-Type: application/json
|
|||
|
||||
```json
|
||||
{
|
||||
"message": "Welcome to Yimaru!",
|
||||
"message": "Welcome to Rezina!",
|
||||
"phone_numbers": ["+251911000000"],
|
||||
"scheduled_at": "2026-06-15T09:00:00Z"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Chapa Direct Charge (USSD) — Client App Integration Guide
|
||||
|
||||
This guide documents how to integrate **Chapa Direct Charge** subscription payments into the Yimaru **learner client app** (mobile or web). Direct charge lets users pay with Ethiopian mobile wallets **inside your app** — no browser redirect to Chapa’s hosted checkout page. For Telebirr and similar wallets, the user receives a **USSD push** on their phone and approves the payment there.
|
||||
This guide documents how to integrate **Chapa Direct Charge** subscription payments into the Rezina **learner client app** (mobile or web). Direct charge lets users pay with Ethiopian mobile wallets **inside your app** — no browser redirect to Chapa’s hosted checkout page. For Telebirr and similar wallets, the user receives a **USSD push** on their phone and approves the payment there.
|
||||
|
||||
> **Scope:** Subscription checkout only. Uses `POST /api/v1/payments/chapa/direct` and related endpoints. **Hosted Chapa checkout** (`POST /api/v1/payments/subscribe` with `provider: "CHAPA"`) remains available and unchanged — use it when you want a full payment page with cards and all wallets.
|
||||
|
||||
|
|
@ -72,7 +72,7 @@ This guide covers **Chapa Direct Charge** only.
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant App as Client app
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
participant Chapa as Chapa API
|
||||
participant Wallet as User wallet (Telebirr)
|
||||
|
||||
|
|
@ -96,7 +96,7 @@ sequenceDiagram
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant App as Client app
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
participant Chapa as Chapa API
|
||||
|
||||
App->>API: POST /payments/chapa/direct
|
||||
|
|
@ -132,7 +132,7 @@ Replace `{API_BASE}` with your environment:
|
|||
|
||||
| Environment | Example |
|
||||
|-------------|---------|
|
||||
| Production | `https://api.yimaru.com` |
|
||||
| Production | `https://api.rezina.com` |
|
||||
| Staging | Your staging API host |
|
||||
|
||||
All paths below are prefixed with `/api/v1`.
|
||||
|
|
@ -572,7 +572,7 @@ Invalid or empty phone → `400` with `"phone is required for direct charge"`.
|
|||
## TypeScript types & API client
|
||||
|
||||
```typescript
|
||||
const API_BASE = "https://api.yimaru.com";
|
||||
const API_BASE = "https://api.rezina.com";
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
message: string;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# CSV Export — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate **server-side CSV export** into the Yimaru admin panel. Exports mirror each resource’s **list filters** (same query parameters as the JSON list APIs) and return a downloadable file instead of paginated JSON.
|
||||
This guide documents how to integrate **server-side CSV export** into the Rezina admin panel. Exports mirror each resource’s **list filters** (same query parameters as the JSON list APIs) and return a downloadable file instead of paginated JSON.
|
||||
|
||||
> **Scope:** Tier 1 admin exports — payments, users, subscriptions, activity logs, and team members.
|
||||
> **Related:** List API guides for each resource (e.g. [activity-logs-admin-panel-integration.md](./activity-logs-admin-panel-integration.md)).
|
||||
|
|
@ -71,7 +71,7 @@ flowchart LR
|
|||
BlobDL["Blob download"]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API"]
|
||||
subgraph API["Rezina API"]
|
||||
ExportRoute["GET .../export"]
|
||||
StreamCSV["StreamCSV helper"]
|
||||
ListSvc["List service + DB"]
|
||||
|
|
|
|||
4236
docs/docs.go
4236
docs/docs.go
File diff suppressed because it is too large
Load Diff
|
|
@ -1,6 +1,6 @@
|
|||
# FAQ Admin Panel — Integration Guide
|
||||
|
||||
This guide documents how to integrate the **FAQ management** feature into the Yimaru admin panel. It covers authentication, RBAC permissions, admin CRUD APIs, response shapes, validation, UI recommendations, and how admin content relates to the public help center.
|
||||
This guide documents how to integrate the **FAQ management** feature into the Rezina admin panel. It covers authentication, RBAC permissions, admin CRUD APIs, response shapes, validation, UI recommendations, and how admin content relates to the public help center.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -53,7 +53,7 @@ flowchart LR
|
|||
Preview[Preview public view]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API"]
|
||||
subgraph API["Rezina API"]
|
||||
AdminRoutes["/admin/faqs CRUD"]
|
||||
PublicRoutes["/faqs read-only"]
|
||||
end
|
||||
|
|
@ -711,7 +711,7 @@ export interface UpdateFAQInput {
|
|||
### Example client (fetch)
|
||||
|
||||
```typescript
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL; // e.g. https://api.yimaru.com
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL; // e.g. https://api.rezina.com
|
||||
|
||||
function authHeaders(token: string): HeadersInit {
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# File Upload — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how the Yimaru admin panel should upload **images, audio, PDFs, and videos** using **direct-to-storage uploads** with accurate client-side progress tracking.
|
||||
This guide documents how the Rezina admin panel should upload **images, audio, PDFs, and videos** using **direct-to-storage uploads** with accurate client-side progress tracking.
|
||||
|
||||
**Use this guide instead of `POST /api/v1/files/upload`.** That legacy endpoint accepts `multipart/form-data` and streams the entire file through the API server. The browser cannot report true upload progress for that path in a meaningful way, and large files (especially video) add load and timeout risk on the backend.
|
||||
|
||||
|
|
@ -43,10 +43,10 @@ The admin panel uploads files when creating or editing content: lesson media, pe
|
|||
|
||||
The backend exposes two **progress-friendly** upload paths:
|
||||
|
||||
1. **MinIO presigned upload** — three-step flow for static files stored in the Yimaru MinIO bucket.
|
||||
1. **MinIO presigned upload** — three-step flow for static files stored in the Rezina MinIO bucket.
|
||||
2. **Vimeo TUS upload** — two-step flow (create slot + client TUS upload) for video hosted on Vimeo.
|
||||
|
||||
Both flows upload **directly from the browser to the storage provider**. The Yimaru API only:
|
||||
Both flows upload **directly from the browser to the storage provider**. The Rezina API only:
|
||||
|
||||
- Authenticates the admin user
|
||||
- Issues upload credentials (presigned URL or TUS upload link)
|
||||
|
|
@ -93,7 +93,7 @@ flowchart TB
|
|||
Form[Content form save]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API (authenticated)"]
|
||||
subgraph API["Rezina API (authenticated)"]
|
||||
Presign["POST /files/presign-upload"]
|
||||
Complete["POST /files/complete-upload"]
|
||||
TusCreate["POST /vimeo/uploads/tus"]
|
||||
|
|
@ -470,7 +470,7 @@ Save **`vimeo_id`** and **`upload_link`** immediately. The upload link is single
|
|||
|
||||
### Step 2 — Upload file with TUS (progress tracked here)
|
||||
|
||||
Upload **directly to `upload_link`** using a TUS 1.0.0 client. Do not send the video bytes to the Yimaru API.
|
||||
Upload **directly to `upload_link`** using a TUS 1.0.0 client. Do not send the video bytes to the Rezina API.
|
||||
|
||||
**Recommended library:** [`tus-js-client`](https://github.com/tus/tus-js-client) (browser).
|
||||
|
||||
|
|
@ -1104,14 +1104,14 @@ Always surface both `message` and `error` from API JSON when present.
|
|||
|
||||
### MinIO CORS (required for browser PUT)
|
||||
|
||||
The admin panel origin (e.g. `https://admin.yimaru.com`) must be allowed to **`PUT`** to the MinIO endpoint host embedded in `upload_url`.
|
||||
The admin panel origin (e.g. `https://admin.rezina.com`) must be allowed to **`PUT`** to the MinIO endpoint host embedded in `upload_url`.
|
||||
|
||||
Example MinIO CORS rule (adjust origins):
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"AllowedOrigin": ["https://admin.yimaru.com", "http://localhost:5173"],
|
||||
"AllowedOrigin": ["https://admin.rezina.com", "http://localhost:5173"],
|
||||
"AllowedMethod": ["GET", "PUT", "HEAD"],
|
||||
"AllowedHeader": ["*"],
|
||||
"ExposeHeader": ["ETag"],
|
||||
|
|
@ -1124,7 +1124,7 @@ Without this, step 2 fails in the browser with a CORS error even though presign
|
|||
|
||||
### Vimeo TUS
|
||||
|
||||
Vimeo upload endpoints accept browser TUS from public origins; no Yimaru MinIO CORS applies. Ensure outbound HTTPS to `*.upload.vimeo.com` is not blocked by corporate firewalls.
|
||||
Vimeo upload endpoints accept browser TUS from public origins; no Rezina MinIO CORS applies. Ensure outbound HTTPS to `*.upload.vimeo.com` is not blocked by corporate firewalls.
|
||||
|
||||
### Environment variables (backend ops)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Generate Yimaru Backend Developer Documentation (.docx)."""
|
||||
"""Generate Rezina Backend Developer Documentation (.docx)."""
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
|
@ -10,7 +10,7 @@ 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"
|
||||
OUT = Path(__file__).resolve().parent / "Rezina_Backend_Developer_Documentation.docx"
|
||||
|
||||
|
||||
def set_run_font(run, name="Calibri", size=11, bold=False, italic=False, color=None):
|
||||
|
|
@ -117,7 +117,7 @@ def build():
|
|||
doc.add_paragraph()
|
||||
add_para(
|
||||
doc,
|
||||
"Yimaru Backend",
|
||||
"Rezina Backend",
|
||||
size=28,
|
||||
bold=True,
|
||||
align=WD_ALIGN_PARAGRAPH.CENTER,
|
||||
|
|
@ -133,7 +133,7 @@ def build():
|
|||
)
|
||||
add_para(
|
||||
doc,
|
||||
"A practical guide for engineers working on the Yimaru Academy API",
|
||||
"A practical guide for engineers working on the Rezina API",
|
||||
size=12,
|
||||
italic=True,
|
||||
align=WD_ALIGN_PARAGRAPH.CENTER,
|
||||
|
|
@ -141,17 +141,17 @@ def build():
|
|||
)
|
||||
add_para(
|
||||
doc,
|
||||
f"Version aligned with repository module Yimaru-Backend (Go 1.25)\n"
|
||||
f"Version aligned with repository module Rezina-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",
|
||||
f"Source: https://gitea.yaltopia.com/Rezina/Rezina-BackEnd.git",
|
||||
size=10,
|
||||
align=WD_ALIGN_PARAGRAPH.CENTER,
|
||||
space_after=12,
|
||||
)
|
||||
add_para(
|
||||
doc,
|
||||
"Internal / proprietary — Yaltopia Tech · Yimaru Academy",
|
||||
"Internal / proprietary — Yaltopia Tech · Rezina",
|
||||
size=9,
|
||||
italic=True,
|
||||
align=WD_ALIGN_PARAGRAPH.CENTER,
|
||||
|
|
@ -162,7 +162,7 @@ def build():
|
|||
add_heading_custom(doc, "1. Introduction", 1)
|
||||
add_para(
|
||||
doc,
|
||||
"If you are opening this document because you just joined the Yimaru backend team "
|
||||
"If you are opening this document because you just joined the Rezina 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 "
|
||||
|
|
@ -185,7 +185,7 @@ def build():
|
|||
add_bullets(
|
||||
doc,
|
||||
[
|
||||
"Admin panel: https://gitea.yaltopia.com/Yimaru/Yimaru-Admin.git (consumes /api/v1)",
|
||||
"Admin panel: https://gitea.yaltopia.com/Rezina/Rezina-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)",
|
||||
|
|
@ -195,7 +195,7 @@ def build():
|
|||
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, "
|
||||
"Rezina-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; "
|
||||
|
|
@ -319,7 +319,7 @@ Catalog courses
|
|||
add_numbered(
|
||||
doc,
|
||||
[
|
||||
"Clone https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd.git and check out production (or the branch your team uses).",
|
||||
"Clone https://gitea.yaltopia.com/Rezina/Rezina-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.",
|
||||
|
|
@ -726,7 +726,7 @@ Catalog courses
|
|||
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 "
|
||||
"Rezina’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 "
|
||||
|
|
@ -740,7 +740,7 @@ Catalog courses
|
|||
)
|
||||
add_para(
|
||||
doc,
|
||||
"— Yaltopia engineering, for Yimaru Academy backend developers",
|
||||
"— Yaltopia engineering, for Rezina backend developers",
|
||||
space_before=16,
|
||||
italic=True,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,813 +0,0 @@
|
|||
# Initial Placement Assessment — Client App Integration Guide
|
||||
|
||||
This guide documents how to integrate the **initial placement assessment** into the Yimaru **learner mobile app** (iOS / Android / React Native / Flutter). The feature runs a **progressive, one-set-per-CEFR-level** flow: the learner starts at **A1**, answers that level’s published set, and advances to the next level only when they meet that level’s **pass score**. Failing a level (or running out of published higher sets) finalizes `knowledge_level` as the highest level already passed (A1 if none).
|
||||
|
||||
> **Scope:** Learner-facing placement flow only. Admin configuration (per-level sets, questions, pass thresholds) is managed in **Yimaru Admin** under **Content → Initial assessment** and is out of scope for the mobile client.
|
||||
|
||||
---
|
||||
|
||||
## Table of contents
|
||||
|
||||
1. [Feature overview](#feature-overview)
|
||||
2. [How placement content is selected](#how-placement-content-is-selected)
|
||||
3. [Prerequisites (ops / admin)](#prerequisites-ops--admin)
|
||||
4. [Architecture](#architecture)
|
||||
5. [Authentication](#authentication)
|
||||
6. [Response envelopes](#response-envelopes)
|
||||
7. [User profile flags](#user-profile-flags)
|
||||
8. [Recommended UX flow](#recommended-ux-flow)
|
||||
9. [API reference](#api-reference)
|
||||
10. [Question payload shapes](#question-payload-shapes)
|
||||
11. [Building answer payloads](#building-answer-payloads)
|
||||
12. [Scoring & CEFR mapping](#scoring--cefr-mapping)
|
||||
13. [Legacy knowledge-level endpoint](#legacy-knowledge-level-endpoint)
|
||||
14. [TypeScript types](#typescript-types)
|
||||
15. [Example API client](#example-api-client)
|
||||
16. [React Native integration patterns](#react-native-integration-patterns)
|
||||
17. [Error handling](#error-handling)
|
||||
18. [Edge cases & product rules](#edge-cases--product-rules)
|
||||
19. [Integration checklist](#integration-checklist)
|
||||
20. [Quick reference](#quick-reference)
|
||||
|
||||
---
|
||||
|
||||
## Feature overview
|
||||
|
||||
| Capability | Client app | Backend |
|
||||
|------------|------------|---------|
|
||||
| Decide whether to show placement | Read `initial_assessment_completed` / `knowledge_level` from profile | Stored on `users` |
|
||||
| Load session / next level | `GET /api/v1/assessment/session` (**auth**) | Progressive progress + published levels |
|
||||
| Load placement questions | `GET /api/v1/assessment/questions?level=A1` | Published `INITIAL_ASSESSMENT` set for that CEFR level |
|
||||
| Load one question | `GET /api/v1/assessment/questions/{id}` | Same scrubbing as list (no correct answers) |
|
||||
| Submit & grade one level | `POST /api/v1/assessment/submit` (**auth**) `{ level, answers }` | Grades that level set vs pass threshold; advances or finalizes |
|
||||
| Persist final result | When submit returns `completed: true` | Sets `knowledge_level` + `initial_assessment_completed = true` |
|
||||
|
||||
### What the learner gets
|
||||
|
||||
1. **One question set per CEFR level** (A1–C2), authored and published independently in admin.
|
||||
2. Progressive testing: start at A1 → pass → next level → … until fail or C2 pass.
|
||||
3. Questions authored as **Multiple choice** or **True / False** (recommended for auto-scoring).
|
||||
4. Final profile `knowledge_level` = highest level **passed** (or `A1` if they fail A1).
|
||||
|
||||
### What the client must **not** do
|
||||
|
||||
- Do **not** grade answers locally for the official result — always call `POST /assessment/submit`.
|
||||
- Do **not** skip levels or submit a level other than `session.next_level`.
|
||||
- Do **not** trust or display `is_correct` from list/get responses (backend forces them to `false` / strips them).
|
||||
- Do **not** call admin threshold APIs from the mobile app (`/admin/assessment/level-thresholds`).
|
||||
- Do **not** rely on `PUT /user/knowledge-level` as the primary placement completion path (see [Legacy knowledge-level endpoint](#legacy-knowledge-level-endpoint)).
|
||||
|
||||
---
|
||||
|
||||
## How placement content is selected
|
||||
|
||||
1. **Level set:** published `question_sets` row with `set_type = 'INITIAL_ASSESSMENT'` and `description` = CEFR level (`A1`…`C2`). At most one published set per level.
|
||||
2. **Questions:** only items in that set whose question `status = 'PUBLISHED'`.
|
||||
3. **Progress:** server tracks `next_level` / `highest_passed_level` per user. Submit must use the current `next_level`.
|
||||
4. **Pass mark:** `initial_assessment_level_thresholds.min_percent` for that level (default 70%).
|
||||
|
||||
If a level’s set is draft, empty, or has no published questions, list/submit for that level fails.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites (ops / admin)
|
||||
|
||||
Before the app can run a successful placement flow:
|
||||
|
||||
1. Run migrations through `000102_initial_assessment_per_level` (thresholds + progress + unique published-per-level).
|
||||
2. In Admin → **Initial assessment**:
|
||||
- For **each** CEFR level you want live, publish its set (“Live for learners”) with published MCQ / True-False questions.
|
||||
- At minimum publish **A1** (learners always start there).
|
||||
- Configure **Pass thresholds** (default 70% per level).
|
||||
3. Optionally configure pass scores differently per level under the Pass thresholds tab.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant App as Mobile app
|
||||
participant API as Yimaru API
|
||||
participant DB as Postgres
|
||||
|
||||
App->>API: GET /user/user-profile (auth)
|
||||
API-->>App: initial_assessment_completed, profile fields
|
||||
|
||||
alt not completed
|
||||
App->>API: GET /assessment/session (auth)
|
||||
API-->>App: next_level, published_levels
|
||||
|
||||
loop until completed
|
||||
App->>API: GET /assessment/questions?level={next_level}
|
||||
API->>DB: published INITIAL_ASSESSMENT set for that CEFR level
|
||||
API-->>App: questions (correct answers scrubbed)
|
||||
App->>App: Collect answers (option IDs)
|
||||
App->>API: POST /assessment/submit { level, answers } (auth)
|
||||
API->>DB: grade vs pass threshold; advance or finalize
|
||||
API-->>App: passed, next_level?, completed, knowledge_level?
|
||||
end
|
||||
|
||||
App->>App: Show result screen; route into app
|
||||
else already completed
|
||||
App->>App: Skip placement (or show “retake” only if product allows)
|
||||
end
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Authentication
|
||||
|
||||
| Endpoint | Auth |
|
||||
|----------|------|
|
||||
| `GET /api/v1/assessment/session` | **Required** — learner JWT |
|
||||
| `GET /api/v1/assessment/questions?level=` | **Public** (prefer after login) |
|
||||
| `GET /api/v1/assessment/questions/:id` | **Public** |
|
||||
| `POST /api/v1/assessment/submit` | **Required** — learner JWT |
|
||||
| `GET /api/v1/user/user-profile` | **Required** |
|
||||
| `PUT /api/v1/user/knowledge-level` | **Required** (learner JWT + `users.update_self`) — legacy / manual |
|
||||
|
||||
**Recommendation:** Drive the flow from `GET /assessment/session` after login. Submit without a valid session returns `401`.
|
||||
|
||||
Base URL pattern:
|
||||
|
||||
```http
|
||||
{API_BASE_URL}/api/v1/...
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```http
|
||||
Authorization: Bearer eyJhbGciOi...
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Response envelopes
|
||||
|
||||
Successful responses typically look like:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Questions fetched successfully",
|
||||
"data": [ /* payload */ ],
|
||||
"success": true,
|
||||
"status_code": 200,
|
||||
"metadata": null
|
||||
}
|
||||
```
|
||||
|
||||
Errors:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Human-readable summary",
|
||||
"error": "Detail string"
|
||||
}
|
||||
```
|
||||
|
||||
Always read the business payload from `data`.
|
||||
|
||||
---
|
||||
|
||||
## User profile flags
|
||||
|
||||
After login / on app launch, load the learner profile:
|
||||
|
||||
```http
|
||||
GET /api/v1/user/user-profile
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
Relevant fields:
|
||||
|
||||
| Field | Type | Meaning |
|
||||
|-------|------|---------|
|
||||
| `initial_assessment_completed` | `boolean` | `true` after a successful `POST /assessment/submit` |
|
||||
| `knowledge_level` | `string` (when present on profile / user objects) | After placement: CEFR code `A1`…`C2` |
|
||||
|
||||
> **Note:** Some profile DTOs historically emphasized `initial_assessment_completed` more than `knowledge_level`. After submit, trust the **submit response** (`knowledge_level` / `level`) and refresh the profile. If your profile mapper omits `knowledge_level`, use the submit result and any user-detail endpoint your app already uses that includes it.
|
||||
|
||||
### Gating recommendation
|
||||
|
||||
```text
|
||||
IF !user.initial_assessment_completed
|
||||
→ show Placement Assessment flow (blocking or soft gate)
|
||||
ELSE
|
||||
→ continue normal onboarding / home
|
||||
```
|
||||
|
||||
Product choices:
|
||||
|
||||
- **Hard gate:** cannot enter main content until completed.
|
||||
- **Soft gate:** can dismiss and take later (still call submit when finished).
|
||||
|
||||
Retakes: submit can be called again; it **overwrites** `knowledge_level` and keeps `initial_assessment_completed = true`. Decide in the app whether retakes are allowed.
|
||||
|
||||
---
|
||||
|
||||
## Recommended UX flow
|
||||
|
||||
1. **Gate** — After auth, if `initial_assessment_completed === false`, open Placement.
|
||||
2. **Intro** — Explain that answers determine starting level (A1–C2); optional time limit if you surface set metadata later.
|
||||
3. **Load questions** — `GET /assessment/questions`; show loading / empty / error states.
|
||||
4. **Quiz UI** — One question per screen or a scrollable list; support MCQ and True/False.
|
||||
5. **Local draft answers** — Keep `{ question_id, selected_option_ids[] }` in memory (and optionally secure storage if process death is a concern).
|
||||
6. **Submit** — Disable UI, call `POST /assessment/submit`.
|
||||
7. **Result** — Show `score_percent`, `level` (e.g. “You’re at **B1**”), optional breakdown from `questions[]`.
|
||||
8. **Continue** — Persist flags in app state; navigate home / curriculum.
|
||||
|
||||
Shuffle: if the published set has `shuffle_questions = true`, the list API currently returns set order from DB; client may shuffle locally for UX **only if** product wants it — grading does not depend on order.
|
||||
|
||||
---
|
||||
|
||||
## API reference
|
||||
|
||||
### 1. Placement session
|
||||
|
||||
```http
|
||||
GET /api/v1/assessment/session
|
||||
Authorization: Bearer <access_token>
|
||||
```
|
||||
|
||||
**Success `data`:**
|
||||
|
||||
```json
|
||||
{
|
||||
"next_level": "A1",
|
||||
"highest_passed_level": null,
|
||||
"completed": false,
|
||||
"initial_assessment_completed": false,
|
||||
"published_levels": ["A1", "A2", "B1"]
|
||||
}
|
||||
```
|
||||
|
||||
When `completed` is true, `knowledge_level` is set and the app should skip the flow (unless product allows a retake via support/admin reset).
|
||||
|
||||
### 2. List placement questions for a level
|
||||
|
||||
```http
|
||||
GET /api/v1/assessment/questions?level=A1
|
||||
```
|
||||
|
||||
**Auth:** optional (public). **`level`** defaults to `A1` when omitted; prefer the `next_level` from session.
|
||||
|
||||
**Success `data`:** array of question objects (see [Question payload shapes](#question-payload-shapes)).
|
||||
|
||||
**Important scrubbing (anti-cheat):**
|
||||
|
||||
- Flat `options[].is_correct` is forced to `false`.
|
||||
- `short_answers` removed.
|
||||
- `audio_correct_answer_text` removed.
|
||||
- Dynamic payload option `is_correct` keys stripped.
|
||||
|
||||
**404:** no published set for that level.
|
||||
|
||||
---
|
||||
|
||||
### 3. Get one placement question
|
||||
|
||||
```http
|
||||
GET /api/v1/assessment/questions/{id}
|
||||
```
|
||||
|
||||
**Auth:** optional (public).
|
||||
|
||||
Same scrubbing as list. Useful for deep links; most apps only need the list endpoint.
|
||||
|
||||
---
|
||||
|
||||
### 4. Submit one CEFR level (primary)
|
||||
|
||||
```http
|
||||
POST /api/v1/assessment/submit
|
||||
Authorization: Bearer <access_token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Body:**
|
||||
|
||||
```json
|
||||
{
|
||||
"level": "A1",
|
||||
"answers": [
|
||||
{
|
||||
"question_id": 303,
|
||||
"selected_option_ids": [1201]
|
||||
},
|
||||
{
|
||||
"question_id": 304,
|
||||
"selected_option_ids": [1210]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `level` | yes | Must equal `session.next_level` |
|
||||
| `answers` | yes (can be `[]`) | One entry per answered question |
|
||||
| `answers[].question_id` | yes | Question ID from list |
|
||||
| `answers[].selected_option_ids` | for MCQ / True-False | Numeric option primary keys from `options[].id` |
|
||||
| `answers[].text_answer` | for short-answer (if ever present) | string |
|
||||
| `answers[].dynamic_answers` | for DYNAMIC MC slots | see below |
|
||||
|
||||
**Success `data` example (continue):**
|
||||
|
||||
```json
|
||||
{
|
||||
"question_set_id": 42,
|
||||
"level_attempted": "A1",
|
||||
"score_percent": 80,
|
||||
"passed": true,
|
||||
"pass_percent": 70,
|
||||
"next_level": "A2",
|
||||
"completed": false,
|
||||
"level": "A1",
|
||||
"points_earned": 8,
|
||||
"points_max": 10,
|
||||
"gradable_questions": 10,
|
||||
"correct_questions": 8,
|
||||
"skipped_ungradable_questions": 0,
|
||||
"questions": [],
|
||||
"initial_assessment_completed": false
|
||||
}
|
||||
```
|
||||
|
||||
**Success `data` example (finalized):**
|
||||
|
||||
```json
|
||||
{
|
||||
"question_set_id": 43,
|
||||
"level_attempted": "A2",
|
||||
"score_percent": 40,
|
||||
"passed": false,
|
||||
"pass_percent": 70,
|
||||
"completed": true,
|
||||
"level": "A1",
|
||||
"knowledge_level": "A1",
|
||||
"initial_assessment_completed": true,
|
||||
"points_earned": 4,
|
||||
"points_max": 10,
|
||||
"gradable_questions": 10,
|
||||
"correct_questions": 4,
|
||||
"skipped_ungradable_questions": 0,
|
||||
"questions": []
|
||||
}
|
||||
```
|
||||
|
||||
On finalize the API also updates:
|
||||
|
||||
- `users.knowledge_level` ← final CEFR (`A1`…`C2`)
|
||||
- `users.initial_assessment_completed` ← `true`
|
||||
|
||||
**HTTP errors:**
|
||||
|
||||
| Status | When |
|
||||
|--------|------|
|
||||
| `401` | Missing / invalid auth |
|
||||
| `404` | No published placement set |
|
||||
| `400` | No gradable questions / validation failure |
|
||||
| `500` | Unexpected server error |
|
||||
|
||||
---
|
||||
|
||||
## Question payload shapes
|
||||
|
||||
List/get items follow the shared `questionRes` shape. Fields you typically need:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 303,
|
||||
"question_text": "Choose the correct greeting.",
|
||||
"question_type": "MCQ",
|
||||
"difficulty_level": "EASY",
|
||||
"points": 1,
|
||||
"tips": null,
|
||||
"explanation": null,
|
||||
"status": "PUBLISHED",
|
||||
"options": [
|
||||
{ "id": 1201, "option_text": "Hello", "option_order": 1, "is_correct": false },
|
||||
{ "id": 1202, "option_text": "Goodbye", "option_order": 2, "is_correct": false }
|
||||
],
|
||||
"dynamic_payload": null
|
||||
}
|
||||
```
|
||||
|
||||
### Types the mobile app should support first
|
||||
|
||||
| `question_type` | UI | Answer field |
|
||||
|-----------------|----|--------------|
|
||||
| `MCQ` | Radio / single select among `options` | `selected_option_ids: [option.id]` |
|
||||
| `TRUE_FALSE` | True / False (usually two options) | `selected_option_ids: [option.id]` |
|
||||
|
||||
Admin product guidance is **MCQ + True/False only**. Still tolerate missing `question_text` when content lives in `dynamic_payload` (see below).
|
||||
|
||||
### Dynamic / outbound shape (important)
|
||||
|
||||
For some deployments the API **normalizes** legacy MCQ/True-False into `dynamic_payload` and may **omit** top-level `question_text` / `options`. Mobile should resolve display content as:
|
||||
|
||||
1. Prefer flat `question_text` if non-empty.
|
||||
2. Else read stimulus text from `dynamic_payload.stimulus` where `kind` is one of `QUESTION_TEXT`, `INSTRUCTION`, `TEXT_PASSAGE`, `TEXT`.
|
||||
3. Prefer flat `options` if present and non-empty.
|
||||
4. Else read `dynamic_payload.response[]` entries with `kind` `MULTIPLE_CHOICE` or `OPTION`, and parse `value.options` (or a bare options array).
|
||||
|
||||
Example dynamic fragment:
|
||||
|
||||
```json
|
||||
{
|
||||
"question_type": "MCQ",
|
||||
"question_text": null,
|
||||
"options": null,
|
||||
"dynamic_payload": {
|
||||
"stimulus": [
|
||||
{ "id": "question_text_1", "kind": "QUESTION_TEXT", "value": "Pick the correct article." }
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"id": "multiple_choice_1",
|
||||
"kind": "MULTIPLE_CHOICE",
|
||||
"value": {
|
||||
"options": [
|
||||
{ "id": "a", "text": "a", "option_text": "a" },
|
||||
{ "id": "b", "text": "an", "option_text": "an" }
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Answering rules when options are only dynamic:**
|
||||
|
||||
- Prefer submitting classic `selected_option_ids` **when flat numeric `options[].id` exist**.
|
||||
- If only string option IDs exist in the dynamic slot, submit:
|
||||
|
||||
```json
|
||||
{
|
||||
"question_id": 303,
|
||||
"dynamic_answers": [
|
||||
{
|
||||
"element_id": "multiple_choice_1",
|
||||
"selected_option_ids": ["a"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Building answer payloads
|
||||
|
||||
### Single-select MCQ / True-False (flat options)
|
||||
|
||||
```ts
|
||||
function answerMcq(questionId: number, optionId: number) {
|
||||
return {
|
||||
question_id: questionId,
|
||||
selected_option_ids: [optionId],
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- Send **exactly** the set of correct option IDs expected by the server for multi-correct items (rare for placement; usually one).
|
||||
- Omitting a question from `answers` counts as incorrect / skipped for scoring (0 points), but still counts in the denominator if the question is gradable.
|
||||
|
||||
### Do not send
|
||||
|
||||
- Correctness flags
|
||||
- Explanations
|
||||
- Threshold configuration
|
||||
|
||||
---
|
||||
|
||||
## Scoring & CEFR mapping
|
||||
|
||||
Progressive placement (authoritative on server):
|
||||
|
||||
1. Only **auto-gradable** questions count: `MCQ`, `TRUE_FALSE`, `SHORT_ANSWER`, and DYNAMIC multiple-choice/option slots.
|
||||
2. `AUDIO` / other dynamic kinds are **skipped** and do not affect the percentage denominator.
|
||||
3. For the attempted level: `score_percent = points_earned / points_max * 100`.
|
||||
4. **Pass** if `score_percent >= pass_percent` for that level (`min_percent` in admin thresholds; default **70%**).
|
||||
5. On **pass**: if a next CEFR level has a published set → `next_level` returned and assessment continues; if C2 passed or next set missing → finalize.
|
||||
6. On **fail**: finalize. `knowledge_level` = highest level already passed, or **A1** if none.
|
||||
|
||||
The mobile app should display `passed`, `next_level`, and final `knowledge_level` from the submit response — do not recompute locally.
|
||||
|
||||
---
|
||||
|
||||
## Legacy knowledge-level endpoint
|
||||
|
||||
```http
|
||||
PUT /api/v1/user/knowledge-level
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{ "knowledge_level": "B1" }
|
||||
```
|
||||
|
||||
Requires a valid learner JWT. Without auth middleware the handler cannot resolve the caller (this used to be a routing bug — the route must include `authMiddleware`).
|
||||
|
||||
This updates `knowledge_level` **without** going through grading and historically expected values like beginner/intermediate/advanced. Prefer **`POST /assessment/submit`** for placement.
|
||||
|
||||
Use the legacy endpoint only if product still has a “pick your level manually” escape hatch — and then set `initial_assessment_completed` via submit or confirm whether your backend path marks completion (submit is the path that sets both fields).
|
||||
|
||||
---
|
||||
|
||||
## TypeScript types
|
||||
|
||||
```ts
|
||||
export type CefrLevel = "A1" | "A2" | "B1" | "B2" | "C1" | "C2";
|
||||
|
||||
export interface PlacementOption {
|
||||
id: number;
|
||||
option_text: string;
|
||||
option_order: number;
|
||||
is_correct?: boolean; // always false/untrusted on learner APIs
|
||||
}
|
||||
|
||||
export interface DynamicElement {
|
||||
id: string;
|
||||
kind: string;
|
||||
value?: unknown;
|
||||
}
|
||||
|
||||
export interface DynamicQuestionPayload {
|
||||
stimulus: DynamicElement[];
|
||||
response: DynamicElement[];
|
||||
}
|
||||
|
||||
export interface PlacementQuestion {
|
||||
id: number;
|
||||
question_text?: string | null;
|
||||
question_type: string;
|
||||
difficulty_level?: string | null;
|
||||
points?: number;
|
||||
tips?: string | null;
|
||||
explanation?: string | null;
|
||||
status?: string;
|
||||
options?: PlacementOption[] | null;
|
||||
dynamic_payload?: DynamicQuestionPayload | null;
|
||||
}
|
||||
|
||||
export interface PlacementAnswer {
|
||||
question_id: number;
|
||||
selected_option_ids?: number[];
|
||||
text_answer?: string;
|
||||
dynamic_answers?: Array<{
|
||||
element_id: string;
|
||||
selected_option_ids?: string[];
|
||||
text_answer?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface PlacementQuestionResult {
|
||||
question_id: number;
|
||||
question_type: string;
|
||||
gradable: boolean;
|
||||
correct: boolean;
|
||||
points_earned: number;
|
||||
points_max: number;
|
||||
skipped: boolean;
|
||||
}
|
||||
|
||||
export interface PlacementSubmitResult {
|
||||
question_set_id: number;
|
||||
score_percent: number;
|
||||
level: CefrLevel | string;
|
||||
points_earned: number;
|
||||
points_max: number;
|
||||
gradable_questions: number;
|
||||
correct_questions: number;
|
||||
skipped_ungradable_questions: number;
|
||||
questions: PlacementQuestionResult[];
|
||||
knowledge_level: CefrLevel | string;
|
||||
initial_assessment_completed: boolean;
|
||||
}
|
||||
|
||||
export interface ApiEnvelope<T> {
|
||||
message: string;
|
||||
data: T;
|
||||
success: boolean;
|
||||
status_code?: number;
|
||||
metadata?: unknown;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Example API client
|
||||
|
||||
```ts
|
||||
const API_BASE = process.env.EXPO_PUBLIC_API_BASE_URL; // e.g. https://api.example.com/api/v1
|
||||
|
||||
async function api<T>(
|
||||
path: string,
|
||||
opts: RequestInit & { token?: string } = {},
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/json",
|
||||
...(opts.body ? { "Content-Type": "application/json" } : {}),
|
||||
...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}),
|
||||
};
|
||||
const res = await fetch(`${API_BASE}${path}`, { ...opts, headers });
|
||||
const body = await res.json();
|
||||
if (!res.ok) {
|
||||
throw new Error(body?.error || body?.message || `HTTP ${res.status}`);
|
||||
}
|
||||
return body.data as T;
|
||||
}
|
||||
|
||||
export function listPlacementQuestions() {
|
||||
return api<PlacementQuestion[]>("/assessment/questions");
|
||||
}
|
||||
|
||||
export function submitPlacement(token: string, answers: PlacementAnswer[]) {
|
||||
return api<PlacementSubmitResult>("/assessment/submit", {
|
||||
method: "POST",
|
||||
token,
|
||||
body: JSON.stringify({ answers }),
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Resolving prompt + choices for UI
|
||||
|
||||
```ts
|
||||
function stimulusText(q: PlacementQuestion): string {
|
||||
const flat = (q.question_text ?? "").trim();
|
||||
if (flat) return flat;
|
||||
const kinds = ["QUESTION_TEXT", "INSTRUCTION", "TEXT_PASSAGE", "TEXT"];
|
||||
for (const kind of kinds) {
|
||||
for (const el of q.dynamic_payload?.stimulus ?? []) {
|
||||
if (String(el.kind).toUpperCase() !== kind) continue;
|
||||
if (typeof el.value === "string" && el.value.trim()) return el.value.trim();
|
||||
}
|
||||
}
|
||||
return `Question #${q.id}`;
|
||||
}
|
||||
|
||||
type UiOption = { key: string; label: string; numericId?: number };
|
||||
|
||||
function uiOptions(q: PlacementQuestion): UiOption[] {
|
||||
if (q.options?.length) {
|
||||
return [...q.options]
|
||||
.sort((a, b) => a.option_order - b.option_order)
|
||||
.map((o) => ({
|
||||
key: String(o.id),
|
||||
label: o.option_text,
|
||||
numericId: o.id,
|
||||
}));
|
||||
}
|
||||
for (const el of q.dynamic_payload?.response ?? []) {
|
||||
const kind = String(el.kind).toUpperCase();
|
||||
if (kind !== "MULTIPLE_CHOICE" && kind !== "OPTION") continue;
|
||||
const value = el.value as any;
|
||||
const raw = Array.isArray(value) ? value : value?.options;
|
||||
if (!Array.isArray(raw)) continue;
|
||||
return raw.map((o: any, i: number) => ({
|
||||
key: String(o.id ?? i),
|
||||
label: String(o.option_text ?? o.text ?? ""),
|
||||
}));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## React Native integration patterns
|
||||
|
||||
### Screen state machine
|
||||
|
||||
```text
|
||||
idle → loadingQuestions → inProgress → submitting → result
|
||||
↘ error
|
||||
```
|
||||
|
||||
### Minimal hook sketch
|
||||
|
||||
```ts
|
||||
function usePlacementAssessment(token: string) {
|
||||
const [questions, setQuestions] = useState<PlacementQuestion[]>([]);
|
||||
const [answers, setAnswers] = useState<Record<number, number>>({}); // questionId → optionId
|
||||
const [result, setResult] = useState<PlacementSubmitResult | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
listPlacementQuestions()
|
||||
.then(setQuestions)
|
||||
.catch((e) => setError(String(e.message || e)));
|
||||
}, []);
|
||||
|
||||
async function submit() {
|
||||
const payload: PlacementAnswer[] = Object.entries(answers).map(
|
||||
([questionId, optionId]) => ({
|
||||
question_id: Number(questionId),
|
||||
selected_option_ids: [optionId],
|
||||
}),
|
||||
);
|
||||
const graded = await submitPlacement(token, payload);
|
||||
setResult(graded);
|
||||
return graded;
|
||||
}
|
||||
|
||||
return { questions, answers, setAnswers, submit, result, error };
|
||||
}
|
||||
```
|
||||
|
||||
### Offline / background
|
||||
|
||||
- Prefer completing submit while online.
|
||||
- If you cache questions offline, still require online submit for official CEFR write.
|
||||
- Do not store correct answers client-side (they are not returned).
|
||||
|
||||
---
|
||||
|
||||
## Error handling
|
||||
|
||||
| Situation | UX |
|
||||
|-----------|----|
|
||||
| Empty question list | “Placement test is not available yet.” Retry / support |
|
||||
| Network failure on list | Retry button |
|
||||
| `401` on submit | Refresh token / re-login, then retry with same answers |
|
||||
| `404` on submit | Set unpublished — show ops message |
|
||||
| `400` no gradable questions | Same as empty / misconfigured content |
|
||||
| Partial answers | Allowed; score will be lower — optionally warn “Unanswered questions count as incorrect” |
|
||||
|
||||
Idempotency: submitting twice overwrites the stored level; show a confirm dialog on retake.
|
||||
|
||||
---
|
||||
|
||||
## Edge cases & product rules
|
||||
|
||||
1. **Draft questions** never appear — admins must publish each question.
|
||||
2. **Draft placement set** — learners get no set (`404` on submit / empty list).
|
||||
3. **Multiple published sets** — learners always get the newest preferred standalone set; clients never pass a set ID.
|
||||
4. **Points** — use `points` for progress UI if desired; server score uses the same.
|
||||
5. **Explanations / tips** — may be present on the question object; safe to show **after** submit using local copy, or hide until result screen (they are not authoritative grading data).
|
||||
6. **Create assessment question** `POST /assessment/questions` exists for legacy tooling — **do not** use it from the learner app.
|
||||
7. **Thresholds** are admin-only; do not hardcode bands except for offline demos.
|
||||
|
||||
---
|
||||
|
||||
## Integration checklist
|
||||
|
||||
- [ ] After login, read `initial_assessment_completed` and gate UX.
|
||||
- [ ] Implement `GET /assessment/questions` loader + empty/error states.
|
||||
- [ ] Render MCQ and True/False (flat `options` and dynamic fallback).
|
||||
- [ ] Track selected option IDs per question.
|
||||
- [ ] Call `POST /assessment/submit` with bearer token.
|
||||
- [ ] Show `score_percent` + `level` / `knowledge_level` on result screen.
|
||||
- [ ] Refresh local user session/profile after success.
|
||||
- [ ] Handle `401` / `404` / `400` with actionable copy.
|
||||
- [ ] Confirm staging has a **published** set and **published** questions before QA.
|
||||
- [ ] QA score bands against admin thresholds (change a threshold in admin and verify mapping).
|
||||
- [ ] Decide product policy for retakes and unanswered questions.
|
||||
|
||||
---
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Action | Method & path | Auth |
|
||||
|--------|---------------|------|
|
||||
| List questions | `GET /api/v1/assessment/questions` | Public |
|
||||
| Get question | `GET /api/v1/assessment/questions/{id}` | Public |
|
||||
| Submit & grade | `POST /api/v1/assessment/submit` | Learner JWT |
|
||||
| Profile gate | `GET /api/v1/user/user-profile` | Learner JWT |
|
||||
| Manual level (legacy) | `PUT /api/v1/user/knowledge-level` | Learner JWT |
|
||||
|
||||
**Submit body (typical):**
|
||||
|
||||
```json
|
||||
{ "answers": [{ "question_id": 1, "selected_option_ids": [10] }] }
|
||||
```
|
||||
|
||||
**Success highlights:**
|
||||
|
||||
```json
|
||||
{
|
||||
"score_percent": 70,
|
||||
"level": "B1",
|
||||
"knowledge_level": "B1",
|
||||
"initial_assessment_completed": true
|
||||
}
|
||||
```
|
||||
|
||||
**CEFR levels:** `A1`, `A2`, `B1`, `B2`, `C1`, `C2`.
|
||||
|
||||
---
|
||||
|
||||
## Related admin surface
|
||||
|
||||
For content authors / QA:
|
||||
|
||||
- Admin route: `/new-content/initial-assessment`
|
||||
- Tabs: Placement set · Questions · Score thresholds
|
||||
- Questions must be **Published** to reach the mobile list/submit pipeline
|
||||
|
||||
This completes the learner-app integration path for the graded initial placement assessment.
|
||||
316
docs/overview.md
Normal file
316
docs/overview.md
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
# Rezina Backend — Technical Overview
|
||||
|
||||
Technical briefing for engineers, architects, or integrators evaluating or working on the **Rezina Backend API**.
|
||||
|
||||
> **Setup & ops:** [README](../README.md)
|
||||
> **OpenAPI:** `/swagger/index.html` when the server is running
|
||||
> **Production base:** `https://api.rezinaacademy.com/api/v1`
|
||||
|
||||
---
|
||||
|
||||
## What this repo is
|
||||
|
||||
A single **Go monolith** exposing REST JSON at `/api/v1`. It is the system of record for:
|
||||
|
||||
| Consumer | Auth | Primary use |
|
||||
|----------|------|-------------|
|
||||
| iOS / Android learner apps | Learner JWT | Content delivery, progress, checkout |
|
||||
| [Rezina Admin](https://gitea.yaltopia.com/Rezina/Rezina-Admin) | Team JWT + RBAC | CRUD, analytics, bulk notify, exports |
|
||||
| Web checkout (Vite SPA) | Learner JWT | Hosted Chapa subscribe flow |
|
||||
|
||||
There is **no separate BFF**. Clients talk directly to this API.
|
||||
|
||||
---
|
||||
|
||||
## System context
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph clients [Clients]
|
||||
Mobile[iOS / Android]
|
||||
Admin[Admin React SPA]
|
||||
Web[Web checkout]
|
||||
end
|
||||
|
||||
API[Rezina API<br/>Fiber /api/v1]
|
||||
|
||||
subgraph persistence [Persistence]
|
||||
PG[(PostgreSQL)]
|
||||
Mongo[(MongoDB logs)]
|
||||
MinIO[(MinIO)]
|
||||
end
|
||||
|
||||
subgraph external [External APIs]
|
||||
Pay[Chapa / Arifpay]
|
||||
Mail[Resend]
|
||||
Push[FCM]
|
||||
Vid[Vimeo]
|
||||
end
|
||||
|
||||
Mobile --> API
|
||||
Admin --> API
|
||||
Web --> API
|
||||
API --> PG
|
||||
API --> Mongo
|
||||
API --> MinIO
|
||||
API --> Pay
|
||||
API --> Mail
|
||||
API --> Push
|
||||
API --> Vid
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Stack
|
||||
|
||||
| Component | Choice | Notes |
|
||||
|-----------|--------|-------|
|
||||
| Runtime | Go 1.25+ | See `go.mod` |
|
||||
| HTTP | Fiber v2 | `internal/web_server` |
|
||||
| SQL access | sqlc → `gen/db` | Queries in `db/query/` — do not edit generated code |
|
||||
| Migrations | golang-migrate | `db/migrations/` (~109 migrations) |
|
||||
| Validation | go-playground/validator | Handler DTOs in `internal/domain` |
|
||||
| Auth | JWT HMAC | Access + refresh; separate learner vs team claims |
|
||||
| Docs | swag | `make swagger` regenerates `docs/` |
|
||||
| Local dev | Air + Docker Compose | Postgres, Mongo, MinIO, migrate sidecar |
|
||||
|
||||
Entry point: `cmd/main.go` wires ~40 services, repositories, cron, and the Fiber app.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
Ports-and-adapters layout:
|
||||
|
||||
```
|
||||
Request
|
||||
→ Fiber middleware (CORS, logging, resolveFileURLs)
|
||||
→ authMiddleware (JWT parse → Locals: user_id / team_member_id, role, permissions)
|
||||
→ RequirePermission("key") // admin write paths
|
||||
→ RequireLMSSubscriptionUnlessFree() // learner course reads
|
||||
→ Handler (thin: bind, validate, call service, map domain errors → HTTP)
|
||||
→ Service (business rules, orchestration)
|
||||
→ Repository (sqlc queries)
|
||||
→ PostgreSQL
|
||||
```
|
||||
|
||||
| Package | Responsibility |
|
||||
|---------|----------------|
|
||||
| `internal/domain` | Entities, enums, request/response structs, domain errors |
|
||||
| `internal/ports` | Store interfaces (testability) |
|
||||
| `internal/repository` | Postgres implementations |
|
||||
| `internal/services/*` | One package per bounded context (subscriptions, examprep, practices, …) |
|
||||
| `internal/web_server/handlers` | HTTP adapters |
|
||||
| `internal/web_server/routes.go` | Route registration — **start here to understand the API surface** |
|
||||
|
||||
Cron (same process): scheduled notification dispatch, account-deletion purge, subscription reminders, etc. (see `internal/web_server` cron setup in `main.go`).
|
||||
|
||||
---
|
||||
|
||||
## Learning content
|
||||
|
||||
The active learning hierarchy is organized for academic programs and subject-focused remedial instruction.
|
||||
|
||||
```
|
||||
programs
|
||||
└── courses
|
||||
└── modules ← top-level modules (no units)
|
||||
└── lessons
|
||||
└── practices → questions
|
||||
```
|
||||
|
||||
- Reorder: `PUT /programs/reorder`, `/programs/:id/courses/reorder`, `/courses/:id/modules/reorder`, `/modules/:id/lessons/reorder`.
|
||||
- Learner routes use `RequireLMSSubscriptionUnlessFree()` — `FREE` access tier content bypasses subscription.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Auth model
|
||||
|
||||
Two JWT audiences, same signing key:
|
||||
|
||||
| Actor | Login | Claims | Middleware |
|
||||
|-------|-------|--------|------------|
|
||||
| **Learner** | `/auth/login`, OTP, Google, Apple | `user_id`, platform role | `authMiddleware` |
|
||||
| **Team member** | `/team/login`, Google, refresh | `team_member_id`, RBAC permissions[] | `authMiddleware` |
|
||||
|
||||
Authorization for admin operations is **permission-key based**, not role-string based in handlers:
|
||||
|
||||
```go
|
||||
groupV1.Post("/programs", a.authMiddleware, a.RequirePermission("programs.create"), h.CreateProgram)
|
||||
```
|
||||
|
||||
Custom RBAC roles stored in DB; built-in keys like `SUPER_ADMIN` still exist for team members. Clients should send permission keys from the JWT, not assume role names.
|
||||
|
||||
Refresh: separate endpoints for learners and team (`/auth/refresh`, `/team/refresh`).
|
||||
|
||||
---
|
||||
|
||||
## Subscription & entitlements
|
||||
|
||||
Plans (`subscription_plans.category`):
|
||||
|
||||
Subscription plan categories are stored in the database and control access to paid learning content. Historic category rows may remain during migration; course content itself is organized by the LMS hierarchy.
|
||||
|
||||
Active row: `user_subscriptions` joined to plan. Content entities carry:
|
||||
|
||||
- `publish_status` — `DRAFT` hidden from learners
|
||||
- `access_tier` — `FREE` vs `PREMIUM`
|
||||
|
||||
Gating logic lives in middleware + `domain.SubscriptionGrantsContentAccess`.
|
||||
|
||||
**Payments:** Chapa hosted checkout (`POST /subscriptions/checkout`), webhooks update payment + subscription state. Arifpay as alternate. Admin list/export under `/admin/payments`.
|
||||
|
||||
**iOS note:** mobile app sends checkout link via `POST /subscriptions/request-checkout-link`; user completes payment on web SPA (see `web-checkout-client-integration.md`).
|
||||
|
||||
---
|
||||
|
||||
## API surface (by route group)
|
||||
|
||||
Registered in `internal/web_server/routes.go`. Representative groups:
|
||||
|
||||
| Prefix / group | Examples | Auth |
|
||||
|----------------|----------|------|
|
||||
| `/auth/*` | register, login, OTP, Google, Apple, refresh | Public / JWT |
|
||||
| `/team/*` | login, invite, accept-invite, members CRUD | Team JWT |
|
||||
| `/programs`, `/courses`, `/modules`, `/lessons` | LMS CRUD + learner GET | JWT + permissions / subscription |
|
||||
| `/practices`, `/questions` | LMS practice engine | JWT + permissions |
|
||||
| `/progress/*`, `/lms/progress*` | lesson complete, practice complete | Learner JWT + LMS sub |
|
||||
| `/subscriptions/*` | plans, checkout, me, request-checkout-link | Mixed |
|
||||
| `/admin/payments`, `/admin/subscriptions/*` | list, grant, extend, cancel | Team JWT + permissions |
|
||||
| `/admin/analytics/*` | dashboard aggregates | Team JWT |
|
||||
| `/notifications/*` | in-app, bulk, scheduled | Team / learner |
|
||||
| `/files/*` | upload, presign, refresh-url | JWT |
|
||||
| `/devices/register` | FCM token + platform | Learner JWT |
|
||||
| `/app/version/check` | force-update gate | Public |
|
||||
|
||||
Full list: Swagger or `GET /routes` (dev).
|
||||
|
||||
---
|
||||
|
||||
## Request / response conventions
|
||||
|
||||
- Envelope: `{ message, data, success, status_code, metadata }` (see `domain.Response`).
|
||||
- Errors: `{ message, error }` with appropriate HTTP status.
|
||||
- Pagination: offset/limit on list endpoints (`total_count` in `data`).
|
||||
- File URLs in responses may be presigned; `resolveFileURLsMiddleware` rewrites for clients.
|
||||
- Validation errors: `"Validation failed: …"` from centralized validator.
|
||||
|
||||
---
|
||||
|
||||
## Data layer workflow
|
||||
|
||||
```bash
|
||||
# 1. Change SQL
|
||||
vim db/query/programs.sql
|
||||
vim db/migrations/000110_....up.sql
|
||||
|
||||
# 2. Regenerate
|
||||
make sqlc-gen
|
||||
|
||||
# 3. Implement repository + service + handler
|
||||
|
||||
# 4. Annotate handler for Swagger
|
||||
make swagger
|
||||
```
|
||||
|
||||
Seeds: `db/data/` (baseline), `db/dev_data/` (local only).
|
||||
Backup: `make backup` / `make restore`.
|
||||
|
||||
---
|
||||
|
||||
## Key services (wiring map)
|
||||
|
||||
`cmd/main.go` constructs stores and services. Notable packages:
|
||||
|
||||
| Service | Package | Role |
|
||||
|---------|---------|------|
|
||||
| Auth | `services/authentication` | Login, OAuth, OTP |
|
||||
| Team | `services/team` | Invites, team CRUD |
|
||||
| RBAC | `services/rbac` | Custom roles / permissions |
|
||||
| Programs / courses | `services/programs`, `courses`, `modules`, `lessons` | LMS tree |
|
||||
| Practices | `services/practices`, `practicecontent`, `questions` | Content + assessment |
|
||||
| Assessment | `services/assessment` | Scoring / evaluation |
|
||||
| Subscriptions | `services/subscriptions` | Plans, checkout, entitlements |
|
||||
| Chapa / Arifpay | `services/chapa`, `arifpay` | Payment providers |
|
||||
| Notifications | `services/notification`, `learnernotifications`, `messenger` | Push, email, SMS, scheduled jobs |
|
||||
| MinIO / Vimeo | `services/minio`, `vimeo` | Media pipeline |
|
||||
| LMS progress | `services/lmsprogress` | Completion state |
|
||||
|
||||
---
|
||||
|
||||
## Security (implementation-level)
|
||||
|
||||
| Topic | Where |
|
||||
|-------|--------|
|
||||
| JWT secret | `JWT_KEY`, expiry in seconds |
|
||||
| OAuth | Google client IDs (multi-client for web + mobile), Apple `aud` allowlist |
|
||||
| Webhooks | Chapa/Arifpay signature verification in payment handlers |
|
||||
| Uploads | Presigned PUT to MinIO; `CompletePresignedUpload` records metadata |
|
||||
| RBAC | Permission checked per route; missing permission → 403 |
|
||||
| SQL injection | sqlc parameterized queries only in repositories |
|
||||
| Secrets | `godotenv` / env; `.env` gitignored |
|
||||
|
||||
---
|
||||
|
||||
## Deployment
|
||||
|
||||
- **Branch:** `production` → Docker image → server pull + restart.
|
||||
- **Migrate before/up with deploy:** `migrate` container or CI step against production `DB_URL`.
|
||||
- **Binary:** multi-stage `Dockerfile`, non-root runner, single process (HTTP + cron).
|
||||
- **Observability:** structured slog; optional Mongo log sink; Postgres for domain data.
|
||||
|
||||
Local parity: `make db-up` then `make air`.
|
||||
|
||||
---
|
||||
|
||||
## Technical demo script (~20 min)
|
||||
|
||||
For a peer engineer — use Swagger + one code walk:
|
||||
|
||||
| # | Show | Point |
|
||||
|---|------|-------|
|
||||
| 1 | `routes.go` lines 86–180 | Learning content routes + middleware chain |
|
||||
| 2 | Swagger → `GET /programs` | LMS list; note permission + subscription middleware |
|
||||
| 5 | `POST /subscriptions/checkout` | Server creates Chapa session; no client-side secret |
|
||||
| 6 | `GET /subscriptions/me` | Entitlement source of truth for apps |
|
||||
| 7 | `db/query/` + `gen/db` | sqlc workflow |
|
||||
| 8 | Admin panel side-by-side | Same API the SPA calls |
|
||||
|
||||
Optional deep dive: open `CompletePractice` handler → progress service → migration `000109` (parent-scoped progress).
|
||||
|
||||
---
|
||||
|
||||
## Integration docs (for client implementers)
|
||||
|
||||
| Doc | Client |
|
||||
|-----|--------|
|
||||
| [web-checkout-client-integration.md](./web-checkout-client-integration.md) | Web checkout / iOS link flow |
|
||||
| [admin-subscription-grant-extend-cancel-admin-panel-integration.md](./admin-subscription-grant-extend-cancel-admin-panel-integration.md) | Admin subscription ops |
|
||||
| [practice-multi-parent-admin-panel-integration.md](./practice-multi-parent-admin-panel-integration.md) | Practice linking |
|
||||
| [question-type-definition-groups-admin-panel-integration.md](./question-type-definition-groups-admin-panel-integration.md) | Dynamic question types |
|
||||
| [bulk-scheduled-notifications-integration.md](./bulk-scheduled-notifications-integration.md) | Scheduled notify |
|
||||
| `postman/` | Importable collections |
|
||||
|
||||
---
|
||||
|
||||
## Suggested slide deck (technical audience)
|
||||
|
||||
1. **Scope** — monolith API, three client types, one Postgres DB
|
||||
2. **Context diagram** — clients, API, stores, externals
|
||||
3. **Layered architecture** — handler → service → repository → sqlc
|
||||
4. **Dual content model** — LMS vs `exam_prep` (diagram + why separate)
|
||||
5. **Auth** — dual JWT, RBAC permission keys
|
||||
6. **Entitlements** — plan categories, middleware gates, free tier
|
||||
7. **Practice engine** — shared questions, multi-parent, assessment
|
||||
8. **Payments** — checkout flow, webhooks, admin export
|
||||
9. **Media** — MinIO presign, Vimeo, URL refresh middleware
|
||||
10. **Dev workflow** — migrate, sqlc, swagger, compose, air
|
||||
11. **Demo** — routes.go + Swagger + one vertical slice
|
||||
12. **Q&A**
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Proprietary — Yaltopia / Rezina. Internal use only unless otherwise licensed.
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# LMS Personas — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate the **LMS persona catalog** into the Yimaru admin panel. Personas are coach/character profiles (name, description, avatar, gender) stored centrally and linked to **practice shells** in Learn English (LMS) and exam-prep via `persona_id`.
|
||||
This guide documents how to integrate the **LMS persona catalog** into the Rezina admin panel. Personas are coach/character profiles (name, description, avatar, gender) stored centrally and linked to **practice shells** in Learn English (LMS) and exam-prep via `persona_id`.
|
||||
|
||||
> **Naming note:** This feature is **`/api/v1/personas`** (catalog rows in `lms_personas`). It is **not** the same as **question-set user personas** (`/question-sets/:id/personas`), which assign real users to a question set for role-play scenarios. Both are covered below; the admin **Personas** menu usually means the catalog.
|
||||
|
||||
|
|
@ -60,7 +60,7 @@ flowchart LR
|
|||
PracticeEditor[Practice editor persona picker]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API"]
|
||||
subgraph API["Rezina API"]
|
||||
PersonaRoutes["/api/v1/personas CRUD"]
|
||||
LmsPractice["/api/v1/practices*"]
|
||||
EpPractice["/api/v1/exam-prep/practices*"]
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ An unlinked practice (`parents: null`) is valid for admins but **will not appear
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Admin panel
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
|
||||
Note over UI,API: Optional — create question set first
|
||||
UI->>API: POST /question-sets
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Practice Multi-Parent Links — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to update the Yimaru **admin panel practice creation and editing** flow for **multi-parent LMS practices**. A single practice can now be linked to **multiple** courses, modules, lessons, or any combination of those hierarchy nodes.
|
||||
This guide documents how to update the Rezina **admin panel practice creation and editing** flow for **multi-parent LMS practices**. A single practice can now be linked to **multiple** courses, modules, lessons, or any combination of those hierarchy nodes.
|
||||
|
||||
> **Scope:** LMS (`/api/v1/practices`) only. **Exam-prep** practices are unchanged — they still attach to exactly one `unit_module_lesson_id`.
|
||||
>
|
||||
|
|
@ -151,7 +151,7 @@ flowchart TB
|
|||
QuestionEditor[Question editor]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API"]
|
||||
subgraph API["Rezina API"]
|
||||
PostPractice["POST /practices"]
|
||||
PutParents["PUT /practices/:id/parents"]
|
||||
GetFull["GET /practices/:id/full"]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Practice Per-Parent Unlink — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate the **per-parent unlink** API into the Yimaru **admin panel**. Content editors can remove a single course, module, lesson, unit, or catalog-course link from a practice **without** sending the full replacement `parents` array and **without** deleting the practice shell or its questions.
|
||||
This guide documents how to integrate the **per-parent unlink** API into the Rezina **admin panel**. Content editors can remove a single course, module, lesson, unit, or catalog-course link from a practice **without** sending the full replacement `parents` array and **without** deleting the practice shell or its questions.
|
||||
|
||||
> **Scope:** Both **LMS** (`/api/v1/practices`) and **exam-prep** (`/api/v1/exam-prep/practices`).
|
||||
>
|
||||
|
|
@ -86,7 +86,7 @@ flowchart LR
|
|||
Confirm["Confirm dialog"]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API"]
|
||||
subgraph API["Rezina API"]
|
||||
DelLMS["DELETE /practices/:id/parents/:kind/:parentId"]
|
||||
DelEP["DELETE /exam-prep/practices/:id/parents/:kind/:parentId"]
|
||||
Put["PUT .../parents"]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Practice Question Associations — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate **question associations** into the Yimaru admin panel practice authoring flow. Associations let content authors group questions into **sequential sections** within a practice. Learners must complete earlier sections (in `display_order`) before later ones unlock.
|
||||
This guide documents how to integrate **question associations** into the Rezina admin panel practice authoring flow. Associations let content authors group questions into **sequential sections** within a practice. Learners must complete earlier sections (in `display_order`) before later ones unlock.
|
||||
|
||||
> **Scope:** This feature adds `associated_question_id` on question set membership (`question_set_items`). It works alongside existing `display_order`. There is **no server-side per-question progress table** — the API returns `prerequisite_question_ids` so the **learner app** (or admin preview) can gate access client-side.
|
||||
|
||||
|
|
@ -115,7 +115,7 @@ flowchart TB
|
|||
SaveBtn[Save practice]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API"]
|
||||
subgraph API["Rezina API"]
|
||||
GetFull["GET /practices/:id/full"]
|
||||
PutFull["PUT /practices/:id/full"]
|
||||
GetEpFull["GET /exam-prep/practices/:id/full"]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Practice Stimulus Blocks — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate **practice-level shared stimulus blocks** into the Yimaru admin panel practice authoring flow. Stimulus blocks let authors define **one shared passage, audio clip, or instruction set** that multiple dynamic questions in the same practice can reference — the primary use case is **IELTS-style listening/reading sections** where several questions share a single stimulus.
|
||||
This guide documents how to integrate **practice-level shared stimulus blocks** into the Rezina admin panel practice authoring flow. Stimulus blocks let authors define **one shared passage, audio clip, or instruction set** that multiple dynamic questions in the same practice can reference — the primary use case is **IELTS-style listening/reading sections** where several questions share a single stimulus.
|
||||
|
||||
> **Scope (Phase 1):** Blocks live on the **practice** (`practice_stimulus_blocks`), not on global question-type definition groups. Questions link via `stimulus_block_key` on set membership (`question_set_items`). The API returns both the **stored** per-question `dynamic_payload` and a computed **`effective_dynamic_payload`** (block stimulus + question stimulus merged). Use `authoring_profile` on the practice shell to switch admin UI modes (`STANDALONE` vs `IELTS_SHARED_STIMULUS`).
|
||||
|
||||
|
|
@ -162,7 +162,7 @@ flowchart TB
|
|||
SaveBtn[Save practice]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API"]
|
||||
subgraph API["Rezina API"]
|
||||
GetFull["GET /practices/:id/full"]
|
||||
PutFull["PUT /practices/:id/full"]
|
||||
GetEpFull["GET /exam-prep/practices/:id/full"]
|
||||
|
|
|
|||
|
|
@ -106,7 +106,7 @@ erDiagram
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Admin panel
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
|
||||
UI->>API: POST /questions/type-definition-groups { name }
|
||||
API-->>UI: 201 { id: 1, name, ... }
|
||||
|
|
@ -123,7 +123,7 @@ sequenceDiagram
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Admin panel
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
|
||||
UI->>API: GET /questions/type-definitions/42
|
||||
API-->>UI: 200 { ID: 42, group_ids: [1], ... }
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Question Type Definition — Practices List Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate **`GET /api/v1/questions/type-definitions/:id/practices`** into the Yimaru **admin panel**. Use it for the **“Practices using this definition”** modal on the Question types page: list every LMS and exam-prep practice whose question set contains at least one non-archived question of that type, show where each practice is attached in the hierarchy, and link editors into the correct practice shell.
|
||||
This guide documents how to integrate **`GET /api/v1/questions/type-definitions/:id/practices`** into the Rezina **admin panel**. Use it for the **“Practices using this definition”** modal on the Question types page: list every LMS and exam-prep practice whose question set contains at least one non-archived question of that type, show where each practice is attached in the hierarchy, and link editors into the correct practice shell.
|
||||
|
||||
> **Scope:** Admin read-only listing from question type definitions. Practice create/edit, parent attach/detach, and question authoring are covered in related guides.
|
||||
>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Ratings & App Reviews — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate **ratings and app reviews** into the Yimaru admin panel. Learners submit star ratings and optional text reviews from the mobile/web app; the admin panel **monitors and analyzes** that feedback.
|
||||
This guide documents how to integrate **ratings and app reviews** into the Rezina admin panel. Learners submit star ratings and optional text reviews from the mobile/web app; the admin panel **monitors and analyzes** that feedback.
|
||||
|
||||
> **Important:** There are **no** dedicated `/api/v1/admin/ratings*` routes today. Admin features use the shared authenticated **`/api/v1/ratings*`** endpoints with staff RBAC permissions. Submission and deletion are **learner-scoped** (own rating only).
|
||||
|
||||
|
|
@ -68,7 +68,7 @@ flowchart LR
|
|||
UserLink[User profile lookup]
|
||||
end
|
||||
|
||||
subgraph API["Yimaru API"]
|
||||
subgraph API["Rezina API"]
|
||||
RatingsRoutes["/api/v1/ratings*"]
|
||||
UserRoutes["/api/v1/user/single/:id"]
|
||||
end
|
||||
|
|
|
|||
216
docs/recommended-question-types-for-remedial-education.md
Normal file
216
docs/recommended-question-types-for-remedial-education.md
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
# Writing Questions for Rezina LMS
|
||||
|
||||
## A practical guide for lessons, practice, and review
|
||||
|
||||
Rezina is being shaped for remedial and makeup education. Questions should help a teacher see what a learner understands, where a step went wrong, and what to practise next. A question can be simple and still do that well. More elaborate formats are useful when the learner needs to work with a diagram, sort steps, or connect related ideas, but they should earn their place by making the task clearer.
|
||||
|
||||
This guide covers the question formats available through the backend question builder, how to use them across subjects, and what to consider when building image-based activities. It is written for the day-to-day work of teaching: introducing an idea, giving learners practice, checking understanding, and deciding what to revisit.
|
||||
|
||||
## Start with the learning evidence
|
||||
|
||||
Before choosing a format, write down what a correct response would show. For example:
|
||||
|
||||
- The learner can identify the numerator and denominator in a fraction.
|
||||
- The learner can put the stages of a process in order.
|
||||
- The learner can find the part of a plant shown in a diagram.
|
||||
- The learner can explain why a particular operation is needed.
|
||||
|
||||
Then choose the response format that lets the learner show that evidence with the least distraction. Avoid turning a question into a puzzle about the interface. If reading is not the skill being assessed, keep the instructions short and familiar.
|
||||
|
||||
## Recommended question formats
|
||||
|
||||
The builder separates question content (the **stimulus**) from the learner's response. A stimulus can combine text, an image, a passage, a table, audio, or an attachment with one or more response components. The names in parentheses are the backend component names and may appear in the admin interface.
|
||||
|
||||
### 1. Single-answer and multiple-answer choice
|
||||
|
||||
**Backend components:** `MULTIPLE_CHOICE`, `OPTION`; legacy question types also include `MCQ` and `TRUE_FALSE`.
|
||||
|
||||
Use a choice question when the aim is to check recognition, understanding of a concept, or a common misconception. It works well for a quick lesson check, a short practice round, or revision where the learner can get immediate feedback.
|
||||
|
||||
**Good fits**
|
||||
|
||||
- Select the equivalent fraction from four options.
|
||||
- Choose the force that would make an object slow down.
|
||||
- Identify the main idea of a short paragraph.
|
||||
- Select all statements that describe a mammal, when selecting every correct statement is part of the learning objective.
|
||||
|
||||
**Writing notes**
|
||||
|
||||
- Ask one clear question. Keep the options similar in length and grammatical form.
|
||||
- Use plausible distractors based on mistakes learners actually make. Avoid silly options that make the answer obvious.
|
||||
- State whether the learner should choose one answer or every correct answer.
|
||||
- Keep option sets to a manageable size. Three or four strong options are usually better than a long list of weak ones.
|
||||
- Avoid “all of the above” and “none of the above”; they make reasoning less visible.
|
||||
- When an item allows more than one correct answer, make sure the scoring and learner instructions match that intent.
|
||||
|
||||
### 2. True or false
|
||||
|
||||
**Backend components:** a `TRUE_FALSE` question, or a builder definition configured for the same response.
|
||||
|
||||
Use this sparingly to check a single, precise statement. It is fast to answer, but the learner has a high chance of guessing correctly, and the format rarely shows how they reached the answer.
|
||||
|
||||
**Example:** “A rectangle always has four right angles.”
|
||||
|
||||
Avoid statements that hinge on a hidden exception, a vague word such as “usually,” or two claims joined together. For important concepts, ask the learner to choose a reason or correct a false statement in a follow-up practice item.
|
||||
|
||||
### 3. Short answer
|
||||
|
||||
**Backend component:** `SHORT_ANSWER` (with `TEXT_INPUT` available as a response component).
|
||||
|
||||
Use a short answer when the learner should recall a term, number, or brief phrase without seeing a list of options. It is useful for vocabulary, labels, basic facts, and short calculations.
|
||||
|
||||
**Examples**
|
||||
|
||||
- “What is 7 × 8?”
|
||||
- “Name the gas that plants take in during photosynthesis.”
|
||||
- “Write the fraction shown in the diagram.”
|
||||
|
||||
Automatic checking can compare configured acceptable answers using exact, case-insensitive, or contains matching. It does not understand equivalent wording or mathematical equivalence on its own. Add acceptable variants deliberately (for example, `0.5` and `1/2` if both should count), and do not use “contains” matching where an accidental partial match could be marked correct. Questions that need working, reasoning, units, or nuanced wording should be reviewed by a teacher or assessed with a separate structured item.
|
||||
|
||||
### 4. Matching
|
||||
|
||||
**Backend components:** `MATCHING_INPUTS` in the stimulus and `MATCHING_ANSWER` in the response.
|
||||
|
||||
Use matching to connect two related sets: word and definition, symbol and meaning, cause and effect, or object and label. Keep the sets short enough that learners can compare them without losing track.
|
||||
|
||||
**Examples**
|
||||
|
||||
- Match each fraction to its picture.
|
||||
- Match a scientific instrument to what it measures.
|
||||
- Match a historical event to its period.
|
||||
|
||||
Do not rely on color alone to distinguish pairs. If answers can be reused, say so; otherwise, make the one-to-one relationship clear. Check that the learner app supports the matching interaction and that its scoring behavior is suitable for the lesson. If not, a teacher can review the result or the same content can be presented as a choice question.
|
||||
|
||||
### 5. Put in order
|
||||
|
||||
**Backend component:** `SEQUENCE_ORDER`.
|
||||
|
||||
Use sequencing when the order itself matters: steps in a calculation, stages in a life cycle, events in a timeline, or instructions for a practical task.
|
||||
|
||||
**Examples**
|
||||
|
||||
- Put the steps for finding a common denominator in order.
|
||||
- Arrange the stages of seed germination.
|
||||
- Place events on a short timeline.
|
||||
|
||||
Keep the sequence focused on one process and avoid steps that could reasonably happen in either order. Give enough context to make the start and end clear. The backend exposes this as a builder response type; confirm the learner app supports the intended interaction and scoring before publishing it.
|
||||
|
||||
### 6. Select missing words
|
||||
|
||||
**Backend components:** `SELECT_MISSING_WORDS` in the stimulus and/or response.
|
||||
|
||||
Use a gap-fill passage to check understanding in context, especially for key vocabulary, grammar within a subject explanation, or a short procedure. Keep the passage short and make each blank test an important idea rather than a minor word.
|
||||
|
||||
**Examples**
|
||||
|
||||
- A short science explanation with a missing term such as “evaporation.”
|
||||
- A worked method with the name of a missing step.
|
||||
- A sentence about a number pattern with the missing value.
|
||||
|
||||
Do not remove so many words that the passage becomes a guessing game. Make sure the surrounding clues do not make the answer trivial. The format exists in the builder; check how the learner app displays it and handles submitted answers.
|
||||
|
||||
### 7. Label an image or select a location
|
||||
|
||||
**Backend components:** `IMAGE` as stimulus and `LABEL_SELECTION` as a response component.
|
||||
|
||||
Image-based questions can make a concept concrete. A learner might select a part of a diagram, match labels to a figure, identify a feature on a map, or choose a point on a number line. The backend catalog provides image stimulus and label-selection response components, which are the building blocks for this kind of activity.
|
||||
|
||||
**Useful applications**
|
||||
|
||||
- Label the numerator and denominator in a fraction model.
|
||||
- Select the heart chamber named in the prompt.
|
||||
- Identify a landform on a map.
|
||||
- Mark the point that represents a value on a number line.
|
||||
- Choose the angle being discussed in a geometry figure.
|
||||
|
||||
Keep the image legible on a phone-sized screen. Use a concise prompt and make target areas large enough to tap. Provide a text equivalent or accessible labels where possible, and never make color the only clue. Crop out irrelevant details and use consistent orientation. If the learner must place several labels, keep the number small and group related labels.
|
||||
|
||||
**Implementation note:** `IMAGE` and `LABEL_SELECTION` are available component kinds, but their presence alone does not guarantee that every deployed learner app renders clickable hotspots or scores them. Confirm the client payload, answer submission, and scoring behavior before building a lesson around an interactive image. If that path is not available, keep the image as a visual prompt and ask a conventional multiple-choice or short-answer question about it.
|
||||
|
||||
### 8. Tables and data interpretation
|
||||
|
||||
**Backend component:** `TABLE` as stimulus; pair it with a suitable response such as multiple choice or short answer.
|
||||
|
||||
Tables are a useful way to present measurements, schedules, survey results, or number patterns without embedding the data in a long paragraph. Ask one thing at a time: find a value, compare two entries, or infer a simple relationship.
|
||||
|
||||
Check that headings include units and that the table remains readable on narrow screens. For younger learners or those still building reading fluency, avoid dense tables with unnecessary rows and columns.
|
||||
|
||||
### 9. Reading passage with a question
|
||||
|
||||
**Backend component:** `TEXT_PASSAGE` as stimulus; use a response that tests the intended reading or subject skill.
|
||||
|
||||
A short passage can provide context for comprehension, science, social studies, or applied numeracy. Ask about information that the learner can locate or infer from the passage, and make clear whether outside knowledge is expected.
|
||||
|
||||
Keep passages short enough that learners can focus on the idea being taught. If the goal is science knowledge rather than reading endurance, use direct language and, where appropriate, a diagram or table alongside the text.
|
||||
|
||||
### 10. Audio prompt and spoken response
|
||||
|
||||
**Backend components:** `AUDIO_PROMPT` stimulus and `AUDIO_RESPONSE` response.
|
||||
|
||||
Audio can make sense when listening or oral explanation is part of the objective—for example, following spoken instructions or explaining a solution aloud. Consider device access, speech differences, and the time needed to review recordings before making audio response a routine part of a course.
|
||||
|
||||
Provide a written alternative when audio is not itself the skill being taught. Audio responses may need teacher review or a learner app that provides its own feedback.
|
||||
|
||||
### 11. File or PDF response
|
||||
|
||||
**Backend components:** `PDF_ATTACHMENT` stimulus and `PDF_UPLOAD` response.
|
||||
|
||||
Use a file upload when the learner needs to submit a page of working, a diagram, or a longer piece of written work. Give a clear file type and size expectation, and offer a way to complete the work if the learner has no scanner or camera.
|
||||
|
||||
## Use images with a teaching purpose
|
||||
|
||||
An interactive image should help the learner notice or manipulate something meaningful. A clickable picture added only for decoration adds loading time and visual clutter without improving the evidence the question provides.
|
||||
|
||||
When planning an image activity, write down:
|
||||
|
||||
1. **What the learner does:** select one region, place a label, connect labels, or mark a point.
|
||||
2. **What counts as correct:** identify the accepted target or targets, including any reasonable alternatives.
|
||||
3. **How it works without a mouse:** support touch and keyboard operation where the client allows it.
|
||||
4. **What happens when it is unavailable:** provide a clear text-based alternative if the image or interaction cannot be used.
|
||||
5. **How it is scored:** decide whether the response can be checked automatically or needs teacher review, then verify that the deployed client and backend support that route.
|
||||
|
||||
For diagrams, use a clear source image, meaningful alt text, and labels that do not overlap important details. For maps, include a scale or orientation if the task depends on it. For number lines and charts, make tick marks, axes, units, and legends easy to read. Avoid putting essential question wording only inside the image.
|
||||
|
||||
## Keep practice sets balanced
|
||||
|
||||
A useful set samples several important skills without overloading any one of them. For each subject and lesson, consider whether it includes:
|
||||
|
||||
- Core knowledge or vocabulary.
|
||||
- Applying a method or concept to a new example.
|
||||
- Reading a diagram, table, or passage when that is part of the subject.
|
||||
- At least one item that can reveal a likely misconception.
|
||||
|
||||
Avoid making every item a simple recall question. At the same time, do not make every item long or complex: the assessment should leave enough time for learners to think, not spend the session deciphering instructions.
|
||||
|
||||
## A short review checklist for authors
|
||||
|
||||
Before publishing a question, check:
|
||||
|
||||
- Does it measure one clear learning objective?
|
||||
- Is the expected answer unambiguous and the marking key correct?
|
||||
- Are the distractors plausible and free of accidental clues?
|
||||
- Is the wording appropriate for the learner's reading level?
|
||||
- Does the chosen response type work on the learner's expected devices?
|
||||
- If an image or audio clip is used, does it contribute directly to the task?
|
||||
- Is there an accessible alternative where one is needed?
|
||||
- If a response needs automatic grading, have you confirmed that the learner app and backend support it?
|
||||
|
||||
## Backend component reference
|
||||
|
||||
| Purpose | Builder components |
|
||||
| --- | --- |
|
||||
| Prompt and directions | `QUESTION_TEXT`, `INSTRUCTION` |
|
||||
| Preparation or answer time | `PREP_TIME`, `ANSWER_TIMER` |
|
||||
| Reading content | `TEXT_PASSAGE` |
|
||||
| Image stimulus | `IMAGE` |
|
||||
| Matching content and response | `MATCHING_INPUTS`, `MATCHING_ANSWER` |
|
||||
| Missing-word activity | `SELECT_MISSING_WORDS` |
|
||||
| Table or data | `TABLE` |
|
||||
| PDF resource or learner submission | `PDF_ATTACHMENT`, `PDF_UPLOAD` |
|
||||
| Audio stimulus and recording | `AUDIO_PROMPT`, `AUDIO_RESPONSE` |
|
||||
| Text response | `TEXT_INPUT`, `SHORT_ANSWER` |
|
||||
| Choice response | `MULTIPLE_CHOICE`, `OPTION` |
|
||||
| Image label or target selection | `LABEL_SELECTION` |
|
||||
| Ordering activity | `SEQUENCE_ORDER` |
|
||||
|
||||
The builder catalog describes the components available to compose question types. A component being listed does not by itself guarantee that a particular learner app or scoring flow implements it end to end. Validate the full path in the client that learners will use.
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# Select Missing Words & Sequence Order — Admin Panel Integration Guide
|
||||
|
||||
This guide explains how to **render, edit, validate, and serialize** the dynamic question builder components **`SELECT_MISSING_WORDS`** and **`SEQUENCE_ORDER`** in the Yimaru admin panel.
|
||||
This guide explains how to **render, edit, validate, and serialize** the dynamic question builder components **`SELECT_MISSING_WORDS`** and **`SEQUENCE_ORDER`** in the Rezina admin panel.
|
||||
|
||||
It is written to match the **existing admin UI patterns** already used for:
|
||||
|
||||
|
|
|
|||
49
docs/subscription-plan-cleanup.md
Normal file
49
docs/subscription-plan-cleanup.md
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
# Subscription plan cleanup before migration 000110
|
||||
|
||||
This is a separate, one-time data repair, not an automatic migration. The reviewed
|
||||
backup contains duplicate LEARN_ENGLISH / non-lifetime / 1 MONTH plans: active
|
||||
plan 2 (ETB 300), inactive plan 9 (ETB 1), and inactive plan 14 (ETB 0).
|
||||
The repair keeps plan 2 and consolidates plans 9 and 14 into it.
|
||||
|
||||
The backup has 86 affected payments and 85 affected subscriptions, including three
|
||||
subscriptions marked ACTIVE on plan 9. Payment amounts, currency, status,
|
||||
subscription dates, and all other reference-row fields are preserved. Screens
|
||||
joining to the current plan will show plan 2's name and ETB 300 price. This is a
|
||||
product/history change that must be accepted before execution. Old plan IDs in
|
||||
external links will no longer resolve. The full original rows and mapping remain
|
||||
in the restricted `plan_cleanup_000110` schema.
|
||||
|
||||
## Execution
|
||||
|
||||
1. Take a fresh database backup and test this repair on an isolated restore.
|
||||
2. Pause application writes and migration startup. Use a database owner session
|
||||
against the intended database at migration 109, before applying 110 or 111.
|
||||
3. Execute with psql, stopping on any error:
|
||||
|
||||
```powershell
|
||||
psql "$env:DB_URL" -X -v ON_ERROR_STOP=1 -c "SET rezina.approve_plan_consolidation = 'yes'" -f db/maintenance/consolidate_subscription_plans_before_000110.sql
|
||||
```
|
||||
|
||||
4. Apply migrations 110 and 111 through the normal migration runner. The repair
|
||||
already creates the exact unique index, preventing new duplicates in the gap.
|
||||
5. Check subscription and payment displays before resuming application traffic.
|
||||
|
||||
The transaction locks all three affected tables, archives full original rows,
|
||||
updates only `plan_id`, removes duplicate plan rows, and validates uniqueness and
|
||||
unchanged historical fields before commit. Unknown foreign keys, changed plan
|
||||
attributes, in-flight payments, remaining duplicates, or an existing archive/index
|
||||
abort the transaction. Do not bypass these checks without reviewing the new data.
|
||||
Do not force migration versions if a prior migration failed without inspecting
|
||||
the schema and migration state first.
|
||||
|
||||
## Recovery
|
||||
|
||||
The original dump remains unchanged. Prefer restoring the fresh backup into an
|
||||
isolated database to verify recovery. For an immediate reversal while writes are
|
||||
still paused: roll back migrations 111/110 if applied, remove the unique index
|
||||
if still present, reinsert archived plans 9 and 14 using explicit column lists,
|
||||
then restore only the archived reference rows' original `plan_id` values by ID,
|
||||
all in one transaction. Keep the archive until recovery is verified. Do not
|
||||
overwrite complete live payment/subscription rows from the archive: their status
|
||||
may have changed after cleanup. Recovery after traffic resumes requires a fresh
|
||||
comparison of live and archived rows and cannot safely be automated blindly.
|
||||
4236
docs/swagger.json
4236
docs/swagger.json
File diff suppressed because it is too large
Load Diff
2943
docs/swagger.yaml
2943
docs/swagger.yaml
File diff suppressed because it is too large
Load Diff
|
|
@ -1,6 +1,6 @@
|
|||
# Team Member Invitation — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to implement the **team member email invitation** flow in the Yimaru admin panel: sending invites, managing pending invitations, building the public **accept-invitation** page, and signing in after activation.
|
||||
This guide documents how to implement the **team member email invitation** flow in the Rezina admin panel: sending invites, managing pending invitations, building the public **accept-invitation** page, and signing in after activation.
|
||||
|
||||
**Use this guide when:** admins invite staff by email, invitees complete profile setup via a link, and the admin panel lists/resends/revokes invitations.
|
||||
|
||||
|
|
@ -63,7 +63,7 @@ Team invitations let admins onboard staff **without creating a password in the a
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Admin as Admin panel
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
participant Mail as Email (Resend)
|
||||
participant Invitee as Invitee browser
|
||||
|
||||
|
|
@ -96,7 +96,7 @@ The backend builds links from `TEAM_INVITE_BASE_URL`:
|
|||
Example admin panel accept route:
|
||||
|
||||
```
|
||||
https://admin.yimaruacademy.com/accept-invite?token=abc123...
|
||||
https://admin.rezinaacademy.com/accept-invite?token=abc123...
|
||||
```
|
||||
|
||||
The **frontend route** is your choice; only the `token` query param is required for the API.
|
||||
|
|
@ -539,7 +539,7 @@ Content-Type: application/json
|
|||
## Invitation email
|
||||
|
||||
- **Template slug:** `invitation` (system — do not delete)
|
||||
- **Subject:** branded default (“You’re invited to Yimaru Academy”)
|
||||
- **Subject:** branded default (“You’re invited to Rezina”)
|
||||
- **CTA:** `{{.InviteLink}}` → `TEAM_INVITE_BASE_URL?token=...`
|
||||
- **Variables:** `FirstName` (empty for new invites), `InviterName`, `InviteLink`
|
||||
|
||||
|
|
@ -650,7 +650,7 @@ Full session handling: [team-member-refresh-token-admin-panel-integration.md](./
|
|||
## TypeScript types & API client
|
||||
|
||||
```typescript
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL; // e.g. https://api.yimaru.com/api/v1
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL; // e.g. https://api.rezina.com/api/v1
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
message: string;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Team Member Refresh Token — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to integrate **team member login** and **refresh token rotation** into the Yimaru admin panel. It covers the login/refresh APIs, token lifecycle, storage, HTTP client interceptors, TypeScript types, error handling, and security notes.
|
||||
This guide documents how to integrate **team member login** and **refresh token rotation** into the Rezina admin panel. It covers the login/refresh APIs, token lifecycle, storage, HTTP client interceptors, TypeScript types, error handling, and security notes.
|
||||
|
||||
**Use this guide when:** staff sign in with `POST /api/v1/team/login` and the admin panel must keep sessions alive without forcing re-login when the short-lived access JWT expires.
|
||||
|
||||
|
|
@ -70,7 +70,7 @@ If the admin panel stores a team `refresh_token`, all refresh calls must go to *
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Admin panel
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
participant DB as PostgreSQL
|
||||
|
||||
UI->>API: POST /team/login (email, password)
|
||||
|
|
@ -119,8 +119,8 @@ JWT claims (`internal/web_server/jwt/jwt.go`):
|
|||
{
|
||||
"UserId": 42,
|
||||
"Role": "ADMIN",
|
||||
"iss": "yimaru.com",
|
||||
"aud": ["api.yimaru.com"],
|
||||
"iss": "rezina.com",
|
||||
"aud": ["api.rezina.com"],
|
||||
"exp": 1719244800
|
||||
}
|
||||
```
|
||||
|
|
@ -171,7 +171,7 @@ Protected routes that receive an expired access token return Fiber errors (often
|
|||
|
||||
## API reference
|
||||
|
||||
Base URL: `{API_BASE}/api/v1` (e.g. `https://api.yimaru.com/api/v1`).
|
||||
Base URL: `{API_BASE}/api/v1` (e.g. `https://api.rezina.com/api/v1`).
|
||||
|
||||
### `POST /team/login`
|
||||
|
||||
|
|
@ -184,7 +184,7 @@ POST /api/v1/team/login
|
|||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "staff@yimaru.com",
|
||||
"email": "staff@rezina.com",
|
||||
"password": "your-password"
|
||||
}
|
||||
```
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Team Password Reset — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to implement **forgot password / password reset** for **team members** (admin panel staff) in the Yimaru admin panel.
|
||||
This guide documents how to implement **forgot password / password reset** for **team members** (admin panel staff) in the Rezina admin panel.
|
||||
|
||||
**Use this guide when:** a staff member cannot sign in and needs to reset their password via email link, or you are wiring the public “Forgot password” and “Reset password” screens on the admin app.
|
||||
|
||||
|
|
@ -75,7 +75,7 @@ Pending invitees must use the **accept-invite** flow, not password reset.
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Staff as Admin panel (logged out)
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
participant Mail as Email (Resend)
|
||||
participant DB as Postgres
|
||||
|
||||
|
|
@ -109,7 +109,7 @@ The backend builds links from `TEAM_PASSWORD_RESET_BASE_URL` (preferred), or der
|
|||
Example:
|
||||
|
||||
```
|
||||
https://admin.yimaruacademy.com/reset-password?email=admin%40yimaruacademy.com&otp=482913
|
||||
https://admin.rezinaacademy.com/reset-password?email=admin%40rezinaacademy.com&otp=482913
|
||||
```
|
||||
|
||||
| Query param | Required | Notes |
|
||||
|
|
@ -135,9 +135,9 @@ The **frontend route path** is your choice, but it **must match** what the serve
|
|||
**Examples:**
|
||||
|
||||
```env
|
||||
TEAM_PASSWORD_RESET_BASE_URL=https://admin.yimaruacademy.com/reset-password
|
||||
TEAM_PASSWORD_RESET_BASE_URL=https://admin.rezinaacademy.com/reset-password
|
||||
# Optional fallback source if the above is omitted:
|
||||
TEAM_INVITE_BASE_URL=https://admin.yimaruacademy.com/accept-invite
|
||||
TEAM_INVITE_BASE_URL=https://admin.rezinaacademy.com/accept-invite
|
||||
```
|
||||
|
||||
If neither yields a usable base URL, `POST /team/sendResetCode` returns **500** with:
|
||||
|
|
@ -163,7 +163,7 @@ Uses system slug **`password_reset`** (same branded template as historical learn
|
|||
| `ResetLink` | Full URL with `email` + `otp` query params |
|
||||
| `ExpiresMinutes` | Always **5** for team reset |
|
||||
|
||||
Subject (default): `Reset your Yimaru Academy password`
|
||||
Subject (default): `Reset your Rezina password`
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -249,7 +249,7 @@ Content-Type: application/json
|
|||
|
||||
```json
|
||||
{
|
||||
"email": "admin@yimaruacademy.com"
|
||||
"email": "admin@rezinaacademy.com"
|
||||
}
|
||||
```
|
||||
|
||||
|
|
@ -294,7 +294,7 @@ Content-Type: application/json
|
|||
|
||||
```json
|
||||
{
|
||||
"email": "admin@yimaruacademy.com",
|
||||
"email": "admin@rezinaacademy.com",
|
||||
"otp": "482913",
|
||||
"password": "NewSecurePass1"
|
||||
}
|
||||
|
|
@ -337,7 +337,7 @@ Content-Type: application/json
|
|||
|
||||
```json
|
||||
{
|
||||
"email": "admin@yimaruacademy.com",
|
||||
"email": "admin@rezinaacademy.com",
|
||||
"password": "NewSecurePass1"
|
||||
}
|
||||
```
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Vimeo Video Upload Progress — Admin Panel Integration Guide
|
||||
|
||||
This guide documents how to implement **real-time video upload progress** in the Yimaru admin panel when uploading videos to Vimeo.
|
||||
This guide documents how to implement **real-time video upload progress** in the Rezina admin panel when uploading videos to Vimeo.
|
||||
|
||||
**Use this guide when:** admins pick a local video file (MP4, MOV, WebM, etc.) and need a live progress bar, cancel support, and post-upload transcode feedback before saving lesson or practice content.
|
||||
|
||||
|
|
@ -40,16 +40,16 @@ This guide documents how to implement **real-time video upload progress** in the
|
|||
|
||||
## Feature overview
|
||||
|
||||
Video lessons in Yimaru are hosted on **Vimeo**. The admin panel uploads videos using **TUS 1.0.0** (resumable upload) directly from the browser to Vimeo's upload endpoint.
|
||||
Video lessons in Rezina are hosted on **Vimeo**. The admin panel uploads videos using **TUS 1.0.0** (resumable upload) directly from the browser to Vimeo's upload endpoint.
|
||||
|
||||
| What | Where it happens |
|
||||
|------|------------------|
|
||||
| Create upload slot | Yimaru API (`POST /vimeo/uploads/tus`) |
|
||||
| Create upload slot | Rezina API (`POST /vimeo/uploads/tus`) |
|
||||
| **Byte-level upload progress** | Browser → Vimeo (`tus-js-client` `onProgress`) |
|
||||
| Transcode / processing status | Yimaru API polls Vimeo (`GET /vimeo/videos/:id/status`) |
|
||||
| Transcode / processing status | Rezina API polls Vimeo (`GET /vimeo/videos/:id/status`) |
|
||||
| Store in lesson/practice | Admin form saves `video_url` / `intro_video_url` |
|
||||
|
||||
The Yimaru API **never receives the video file bytes** during admin uploads. Real-time progress is therefore implemented **in the admin panel client**, not via WebSockets or server push from the backend.
|
||||
The Rezina API **never receives the video file bytes** during admin uploads. Real-time progress is therefore implemented **in the admin panel client**, not via WebSockets or server push from the backend.
|
||||
|
||||
### User-visible phases
|
||||
|
||||
|
|
@ -66,7 +66,7 @@ The Yimaru API **never receives the video file bytes** during admin uploads. Rea
|
|||
|
||||
```text
|
||||
┌─────────────────┐ POST /vimeo/uploads/tus ┌──────────────┐
|
||||
│ Admin panel │ ─────────────────────────────────► │ Yimaru API │
|
||||
│ Admin panel │ ─────────────────────────────────► │ Rezina API │
|
||||
│ (browser) │ ◄──── upload_link + vimeo_id ───── │ │
|
||||
└────────┬────────┘ └──────────────┘
|
||||
│
|
||||
|
|
@ -81,7 +81,7 @@ The Yimaru API **never receives the video file bytes** during admin uploads. Rea
|
|||
│ after onSuccess
|
||||
▼
|
||||
┌─────────────────┐ GET /vimeo/videos/:id/status ┌──────────────┐
|
||||
│ Admin panel │ ─────────────────────────────────► │ Yimaru API │
|
||||
│ Admin panel │ ─────────────────────────────────► │ Rezina API │
|
||||
│ (poll loop) │ ◄──── { status: in_progress } ──── │ → Vimeo API │
|
||||
└─────────────────┘ └──────────────┘
|
||||
```
|
||||
|
|
@ -95,7 +95,7 @@ The Yimaru API **never receives the video file bytes** during admin uploads. Rea
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Admin panel UI
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
participant Vimeo as Vimeo TUS + transcode
|
||||
|
||||
UI->>UI: User selects video file
|
||||
|
|
@ -323,11 +323,11 @@ Content-Type: application/json
|
|||
|
||||
---
|
||||
|
||||
### Step 2 — Upload file (browser → Vimeo, not Yimaru API)
|
||||
### Step 2 — Upload file (browser → Vimeo, not Rezina API)
|
||||
|
||||
Performed by `tus-js-client` against `upload_link`. See [TUS upload with progress](#tus-upload-with-progress).
|
||||
|
||||
No `Authorization` header to Yimaru API during this step. Vimeo authenticates via the upload URL.
|
||||
No `Authorization` header to Rezina API during this step. Vimeo authenticates via the upload URL.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -410,7 +410,7 @@ const tus = await import("tus-js-client");
|
|||
### Environment (admin panel)
|
||||
|
||||
```env
|
||||
VITE_API_BASE_URL=https://api.yimaru.com
|
||||
VITE_API_BASE_URL=https://api.rezina.com
|
||||
```
|
||||
|
||||
### Network / CORS
|
||||
|
|
@ -1238,7 +1238,7 @@ Chrome DevTools → Network → Throttling. Verify progress bar moves smoothly d
|
|||
| Step | Method | Path | Auth / permission |
|
||||
|------|--------|------|-------------------|
|
||||
| 1. Create slot | `POST` | `/api/v1/vimeo/uploads/tus` | Bearer + `vimeo.uploads.tus` |
|
||||
| 2. Upload bytes | TUS `PATCH` | `{upload_link}` from step 1 | Vimeo upload URL (no Yimaru token) |
|
||||
| 2. Upload bytes | TUS `PATCH` | `{upload_link}` from step 1 | Vimeo upload URL (no Rezina token) |
|
||||
| 3. Poll transcode | `GET` | `/api/v1/vimeo/videos/:video_id/status` | Bearer + `vimeo.videos.status` |
|
||||
| Preview embed | `GET` | `/api/v1/vimeo/videos/:video_id/embed` | Bearer + `vimeo.videos.embed` |
|
||||
| Delete orphan | `DELETE` | `/api/v1/vimeo/videos/:video_id` | Bearer + `vimeo.videos.delete` |
|
||||
|
|
@ -1261,4 +1261,4 @@ canonical page link = https://vimeo.com/{vimeo_id}
|
|||
|
||||
---
|
||||
|
||||
*Last updated for Yimaru API `production` branch — Vimeo TUS handlers in `internal/web_server/handlers/vimeo.go`.*
|
||||
*Last updated for Rezina API `production` branch — Vimeo TUS handlers in `internal/web_server/handlers/vimeo.go`.*
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ When the iOS app shows **Subscription required** (locked content), it should **n
|
|||
```mermaid
|
||||
sequenceDiagram
|
||||
participant iOS as iOS app
|
||||
participant API as Yimaru API
|
||||
participant API as Rezina API
|
||||
participant User as Email / SMS
|
||||
participant Web as Web checkout app
|
||||
|
||||
|
|
@ -116,7 +116,7 @@ One link per **15 minutes** per user (`429` if called too soon).
|
|||
|
||||
| Variable | Example |
|
||||
|----------|---------|
|
||||
| `LEARNER_WEB_CHECKOUT_BASE_URL` | `https://subscribe.yimaruacademy.com` |
|
||||
| `LEARNER_WEB_CHECKOUT_BASE_URL` | `https://subscribe.rezinaacademy.com` |
|
||||
|
||||
Links are built as:
|
||||
|
||||
|
|
@ -177,12 +177,12 @@ flowchart TD
|
|||
|
||||
| Variable | Example | Purpose |
|
||||
|----------|---------|---------|
|
||||
| `VITE_API_BASE_URL` | `https://api.yimaruacademy.com/api/v1` | Yimaru API |
|
||||
| `LEARNER_WEB_CHECKOUT_BASE_URL` (backend) | `https://subscribe.yimaruacademy.com` | Base URL embedded in email/SMS links |
|
||||
| `VITE_API_BASE_URL` | `https://api.rezinaacademy.com/api/v1` | Rezina API |
|
||||
| `LEARNER_WEB_CHECKOUT_BASE_URL` (backend) | `https://subscribe.rezinaacademy.com` | Base URL embedded in email/SMS links |
|
||||
| `VITE_APP_STORE_URL` | `https://apps.apple.com/...` | Optional iOS download link on success |
|
||||
| `VITE_PLAY_STORE_URL` | `https://play.google.com/...` | Optional Android link |
|
||||
|
||||
Production API base: `https://api.yimaruacademy.com/api/v1`
|
||||
Production API base: `https://api.rezinaacademy.com/api/v1`
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -276,7 +276,7 @@ POST /api/v1/auth/customer-login
|
|||
|
||||
#### Google / Apple sign-in
|
||||
|
||||
Same as the mobile app — exchange the provider identity token for Yimaru JWTs.
|
||||
Same as the mobile app — exchange the provider identity token for Rezina JWTs.
|
||||
|
||||
**Google (web ID token):**
|
||||
|
||||
|
|
@ -311,7 +311,7 @@ POST /api/v1/auth/apple
|
|||
|----------|---------------------|
|
||||
| `VITE_GOOGLE_CLIENT_ID` | `GOOGLE_OAUTH_WEB_CLIENT_ID` (or comma-separated in `GOOGLE_OAUTH_CLIENT_ID`) |
|
||||
| `VITE_APPLE_CLIENT_ID` | include Services ID in `APPLE_SIGN_IN_CLIENT_IDS` |
|
||||
| `VITE_APPLE_REDIRECT_URI` | must match Apple Developer redirect URL (e.g. `https://subscribe.yimaruacademy.com/subscribe/login`) |
|
||||
| `VITE_APPLE_REDIRECT_URI` | must match Apple Developer redirect URL (e.g. `https://subscribe.rezinaacademy.com/subscribe/login`) |
|
||||
|
||||
Buttons are hidden when the corresponding `VITE_*` values are unset.
|
||||
|
||||
|
|
@ -428,7 +428,7 @@ Authorization: Bearer <token>
|
|||
```json
|
||||
{
|
||||
"payment_id": 100,
|
||||
"session_id": "yimaru-tx-abc123",
|
||||
"session_id": "rezina-tx-abc123",
|
||||
"payment_url": "https://checkout.chapa.co/...",
|
||||
"amount": 499.0,
|
||||
"currency": "ETB",
|
||||
|
|
@ -483,11 +483,11 @@ Expect an `ACTIVE` subscription with matching `category`.
|
|||
**Success UI copy (suggested):**
|
||||
|
||||
> Your subscription is active.
|
||||
> Open **Yimaru Academy** on your iPhone and sign in with this account.
|
||||
> Open **Rezina** on your iPhone and sign in with this account.
|
||||
|
||||
Optional buttons:
|
||||
|
||||
- **Open app** — custom URL scheme / Universal Link (`yimaru://` or `https://app.yimaru.com/open`) if configured
|
||||
- **Open app** — custom URL scheme / Universal Link (`rezina://` or `https://app.rezina.com/open`) if configured
|
||||
- **Download on App Store** — marketing link only; not a payment link
|
||||
|
||||
---
|
||||
|
|
@ -630,4 +630,4 @@ curl -s "$API/api/v1/subscriptions/me" \
|
|||
|
||||
---
|
||||
|
||||
*Aligns with Yimaru API `production` branch — Chapa hosted checkout via `SubscribeWithPayment` / `InitiateSubscriptionPayment`.*
|
||||
*Aligns with Rezina API `production` branch — Chapa hosted checkout via `SubscribeWithPayment` / `InitiateSubscriptionPayment`.*
|
||||
|
|
|
|||
|
|
@ -164,13 +164,6 @@ type GlobalSetting struct {
|
|||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
}
|
||||
|
||||
type InitialAssessmentLevelThreshold struct {
|
||||
Level string `json:"level"`
|
||||
MinPercent int32 `json:"min_percent"`
|
||||
DisplayOrder int32 `json:"display_order"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
}
|
||||
|
||||
type Lesson struct {
|
||||
ID int64 `json:"id"`
|
||||
ModuleID int64 `json:"module_id"`
|
||||
|
|
@ -503,6 +496,32 @@ type ReportedIssue struct {
|
|||
UpdatedAt pgtype.Timestamp `json:"updated_at"`
|
||||
}
|
||||
|
||||
type RetiredInitialAssessmentCompletion struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
Completed bool `json:"completed"`
|
||||
}
|
||||
|
||||
type RetiredInitialAssessmentLevelThreshold struct {
|
||||
Level string `json:"level"`
|
||||
MinPercent int32 `json:"min_percent"`
|
||||
DisplayOrder int32 `json:"display_order"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
}
|
||||
|
||||
type RetiredInitialAssessmentQuestionSet struct {
|
||||
QuestionSetID int64 `json:"question_set_id"`
|
||||
SetType string `json:"set_type"`
|
||||
}
|
||||
|
||||
type RetiredUserInitialAssessmentProgress struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
NextLevel string `json:"next_level"`
|
||||
HighestPassedLevel pgtype.Text `json:"highest_passed_level"`
|
||||
Completed bool `json:"completed"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
SubjectID int64 `json:"subject_id"`
|
||||
}
|
||||
|
||||
type Role struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
|
|
@ -553,6 +572,7 @@ type SubscriptionPlan struct {
|
|||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
Category string `json:"category"`
|
||||
IsLifetime bool `json:"is_lifetime"`
|
||||
IsFree bool `json:"is_free"`
|
||||
}
|
||||
|
||||
type TeamInvitation struct {
|
||||
|
|
@ -635,7 +655,6 @@ type User struct {
|
|||
LanguageGoal pgtype.Text `json:"language_goal"`
|
||||
LanguageChallange pgtype.Text `json:"language_challange"`
|
||||
FavouriteTopic pgtype.Text `json:"favourite_topic"`
|
||||
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
PhoneVerified bool `json:"phone_verified"`
|
||||
Status string `json:"status"`
|
||||
|
|
@ -665,14 +684,6 @@ type UserAudioResponse struct {
|
|||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
}
|
||||
|
||||
type UserInitialAssessmentProgress struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
NextLevel string `json:"next_level"`
|
||||
HighestPassedLevel pgtype.Text `json:"highest_passed_level"`
|
||||
Completed bool `json:"completed"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
}
|
||||
|
||||
type UserPracticeProgress struct {
|
||||
ID int64 `json:"id"`
|
||||
UserID int64 `json:"user_id"`
|
||||
|
|
|
|||
|
|
@ -132,79 +132,6 @@ func (q *Queries) DeleteQuestionSet(ctx context.Context, id int64) error {
|
|||
return err
|
||||
}
|
||||
|
||||
const GetInitialAssessmentSet = `-- name: GetInitialAssessmentSet :one
|
||||
SELECT id, title, description, set_type, owner_type, owner_id, banner_image, persona, time_limit_minutes, passing_score, shuffle_questions, status, created_at, updated_at, display_order, intro_video_url
|
||||
FROM question_sets
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND status = 'PUBLISHED'
|
||||
AND UPPER(TRIM(COALESCE(description, ''))) = 'A1'
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
func (q *Queries) GetInitialAssessmentSet(ctx context.Context) (QuestionSet, error) {
|
||||
row := q.db.QueryRow(ctx, GetInitialAssessmentSet)
|
||||
var i QuestionSet
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.Description,
|
||||
&i.SetType,
|
||||
&i.OwnerType,
|
||||
&i.OwnerID,
|
||||
&i.BannerImage,
|
||||
&i.Persona,
|
||||
&i.TimeLimitMinutes,
|
||||
&i.PassingScore,
|
||||
&i.ShuffleQuestions,
|
||||
&i.Status,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.DisplayOrder,
|
||||
&i.IntroVideoUrl,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const GetInitialAssessmentSetByLevel = `-- name: GetInitialAssessmentSetByLevel :one
|
||||
SELECT id, title, description, set_type, owner_type, owner_id, banner_image, persona, time_limit_minutes, passing_score, shuffle_questions, status, created_at, updated_at, display_order, intro_video_url
|
||||
FROM question_sets
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND status = 'PUBLISHED'
|
||||
AND UPPER(TRIM(COALESCE(description, ''))) = $1::text
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN owner_type IS NULL OR UPPER(TRIM(owner_type)) = 'STANDALONE' THEN 0
|
||||
ELSE 1
|
||||
END,
|
||||
created_at DESC
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
func (q *Queries) GetInitialAssessmentSetByLevel(ctx context.Context, level string) (QuestionSet, error) {
|
||||
row := q.db.QueryRow(ctx, GetInitialAssessmentSetByLevel, level)
|
||||
var i QuestionSet
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.Description,
|
||||
&i.SetType,
|
||||
&i.OwnerType,
|
||||
&i.OwnerID,
|
||||
&i.BannerImage,
|
||||
&i.Persona,
|
||||
&i.TimeLimitMinutes,
|
||||
&i.PassingScore,
|
||||
&i.ShuffleQuestions,
|
||||
&i.Status,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.DisplayOrder,
|
||||
&i.IntroVideoUrl,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const GetPublishedQuestionSetsByOwner = `-- name: GetPublishedQuestionSetsByOwner :many
|
||||
SELECT id, title, description, set_type, owner_type, owner_id, banner_image, persona, time_limit_minutes, passing_score, shuffle_questions, status, created_at, updated_at, display_order, intro_video_url
|
||||
FROM question_sets
|
||||
|
|
@ -466,35 +393,6 @@ func (q *Queries) GetUserPersonasByQuestionSetID(ctx context.Context, questionSe
|
|||
return items, nil
|
||||
}
|
||||
|
||||
const ListPublishedInitialAssessmentLevels = `-- name: ListPublishedInitialAssessmentLevels :many
|
||||
SELECT DISTINCT UPPER(TRIM(description))::text AS level
|
||||
FROM question_sets
|
||||
WHERE set_type = 'INITIAL_ASSESSMENT'
|
||||
AND status = 'PUBLISHED'
|
||||
AND UPPER(TRIM(COALESCE(description, ''))) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')
|
||||
ORDER BY level
|
||||
`
|
||||
|
||||
func (q *Queries) ListPublishedInitialAssessmentLevels(ctx context.Context) ([]string, error) {
|
||||
rows, err := q.db.Query(ctx, ListPublishedInitialAssessmentLevels)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []string
|
||||
for rows.Next() {
|
||||
var level string
|
||||
if err := rows.Scan(&level); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, level)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const RemoveUserPersonaFromQuestionSet = `-- name: RemoveUserPersonaFromQuestionSet :exec
|
||||
DELETE FROM question_set_personas
|
||||
WHERE question_set_id = $1
|
||||
|
|
|
|||
|
|
@ -123,10 +123,10 @@ func (q *Queries) CountUserSubscriptionsByPlanID(ctx context.Context, planID int
|
|||
const CreateSubscriptionPlan = `-- name: CreateSubscriptionPlan :one
|
||||
|
||||
INSERT INTO subscription_plans (
|
||||
name, description, category, duration_value, duration_unit, price, currency, is_lifetime, is_active
|
||||
name, description, category, duration_value, duration_unit, price, currency, is_lifetime, is_free, is_active
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, false), COALESCE($9, true))
|
||||
RETURNING id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, false), COALESCE($9, false), COALESCE($10, true))
|
||||
RETURNING id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime, is_free
|
||||
`
|
||||
|
||||
type CreateSubscriptionPlanParams struct {
|
||||
|
|
@ -139,6 +139,7 @@ type CreateSubscriptionPlanParams struct {
|
|||
Currency string `json:"currency"`
|
||||
Column8 interface{} `json:"column_8"`
|
||||
Column9 interface{} `json:"column_9"`
|
||||
Column10 interface{} `json:"column_10"`
|
||||
}
|
||||
|
||||
// =====================
|
||||
|
|
@ -155,6 +156,7 @@ func (q *Queries) CreateSubscriptionPlan(ctx context.Context, arg CreateSubscrip
|
|||
arg.Currency,
|
||||
arg.Column8,
|
||||
arg.Column9,
|
||||
arg.Column10,
|
||||
)
|
||||
var i SubscriptionPlan
|
||||
err := row.Scan(
|
||||
|
|
@ -170,6 +172,7 @@ func (q *Queries) CreateSubscriptionPlan(ctx context.Context, arg CreateSubscrip
|
|||
&i.UpdatedAt,
|
||||
&i.Category,
|
||||
&i.IsLifetime,
|
||||
&i.IsFree,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
|
@ -484,7 +487,7 @@ func (q *Queries) GetSubscriptionDisplayStatusByUserID(ctx context.Context, user
|
|||
}
|
||||
|
||||
const GetSubscriptionPlanByID = `-- name: GetSubscriptionPlanByID :one
|
||||
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime FROM subscription_plans WHERE id = $1
|
||||
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime, is_free FROM subscription_plans WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetSubscriptionPlanByID(ctx context.Context, id int64) (SubscriptionPlan, error) {
|
||||
|
|
@ -503,6 +506,7 @@ func (q *Queries) GetSubscriptionPlanByID(ctx context.Context, id int64) (Subscr
|
|||
&i.UpdatedAt,
|
||||
&i.Category,
|
||||
&i.IsLifetime,
|
||||
&i.IsFree,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
|
@ -698,7 +702,7 @@ func (q *Queries) HasActiveSubscriptionByCategory(ctx context.Context, arg HasAc
|
|||
}
|
||||
|
||||
const ListActiveSubscriptionPlans = `-- name: ListActiveSubscriptionPlans :many
|
||||
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime FROM subscription_plans
|
||||
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime, is_free FROM subscription_plans
|
||||
WHERE is_active = true
|
||||
ORDER BY price ASC
|
||||
`
|
||||
|
|
@ -725,6 +729,7 @@ func (q *Queries) ListActiveSubscriptionPlans(ctx context.Context) ([]Subscripti
|
|||
&i.UpdatedAt,
|
||||
&i.Category,
|
||||
&i.IsLifetime,
|
||||
&i.IsFree,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -993,7 +998,7 @@ func (q *Queries) ListSubscriptionDisplayStatusesByUserIDs(ctx context.Context,
|
|||
}
|
||||
|
||||
const ListSubscriptionPlans = `-- name: ListSubscriptionPlans :many
|
||||
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime FROM subscription_plans
|
||||
SELECT id, name, description, duration_value, duration_unit, price, currency, is_active, created_at, updated_at, category, is_lifetime, is_free FROM subscription_plans
|
||||
WHERE (
|
||||
$1::boolean IS NULL
|
||||
OR $1::boolean = false
|
||||
|
|
@ -1033,6 +1038,7 @@ func (q *Queries) ListSubscriptionPlans(ctx context.Context, arg ListSubscriptio
|
|||
&i.UpdatedAt,
|
||||
&i.Category,
|
||||
&i.IsLifetime,
|
||||
&i.IsFree,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -1193,6 +1199,42 @@ func (q *Queries) SetLifetimeExpiresForActiveSubscriptionsByPlanID(ctx context.C
|
|||
return err
|
||||
}
|
||||
|
||||
const SubscriptionPlanExistsWithCategoryPeriod = `-- name: SubscriptionPlanExistsWithCategoryPeriod :one
|
||||
SELECT EXISTS(
|
||||
SELECT 1
|
||||
FROM subscription_plans
|
||||
WHERE category = $1
|
||||
AND is_lifetime = $2
|
||||
AND duration_value = $3
|
||||
AND duration_unit = $4
|
||||
AND (
|
||||
$5::bigint IS NULL
|
||||
OR id <> $5::bigint
|
||||
)
|
||||
)
|
||||
`
|
||||
|
||||
type SubscriptionPlanExistsWithCategoryPeriodParams struct {
|
||||
Category string `json:"category"`
|
||||
IsLifetime bool `json:"is_lifetime"`
|
||||
DurationValue int32 `json:"duration_value"`
|
||||
DurationUnit string `json:"duration_unit"`
|
||||
ExcludePlanID pgtype.Int8 `json:"exclude_plan_id"`
|
||||
}
|
||||
|
||||
func (q *Queries) SubscriptionPlanExistsWithCategoryPeriod(ctx context.Context, arg SubscriptionPlanExistsWithCategoryPeriodParams) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, SubscriptionPlanExistsWithCategoryPeriod,
|
||||
arg.Category,
|
||||
arg.IsLifetime,
|
||||
arg.DurationValue,
|
||||
arg.DurationUnit,
|
||||
arg.ExcludePlanID,
|
||||
)
|
||||
var exists bool
|
||||
err := row.Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const UpdateAutoRenew = `-- name: UpdateAutoRenew :exec
|
||||
UPDATE user_subscriptions
|
||||
SET
|
||||
|
|
@ -1222,9 +1264,10 @@ SET
|
|||
price = COALESCE($6::numeric, price),
|
||||
currency = COALESCE($7::varchar, currency),
|
||||
is_lifetime = COALESCE($8::boolean, is_lifetime),
|
||||
is_active = COALESCE($9::boolean, is_active),
|
||||
is_free = COALESCE($9::boolean, is_free),
|
||||
is_active = COALESCE($10::boolean, is_active),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $10
|
||||
WHERE id = $11
|
||||
`
|
||||
|
||||
type UpdateSubscriptionPlanParams struct {
|
||||
|
|
@ -1236,6 +1279,7 @@ type UpdateSubscriptionPlanParams struct {
|
|||
Price pgtype.Numeric `json:"price"`
|
||||
Currency pgtype.Text `json:"currency"`
|
||||
IsLifetime pgtype.Bool `json:"is_lifetime"`
|
||||
IsFree pgtype.Bool `json:"is_free"`
|
||||
IsActive pgtype.Bool `json:"is_active"`
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
|
|
@ -1250,6 +1294,7 @@ func (q *Queries) UpdateSubscriptionPlan(ctx context.Context, arg UpdateSubscrip
|
|||
arg.Price,
|
||||
arg.Currency,
|
||||
arg.IsLifetime,
|
||||
arg.IsFree,
|
||||
arg.IsActive,
|
||||
arg.ID,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -110,7 +110,7 @@ INSERT INTO users (
|
|||
VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8
|
||||
)
|
||||
RETURNING id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
RETURNING id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
`
|
||||
|
||||
type CreateAppleUserParams struct {
|
||||
|
|
@ -156,7 +156,6 @@ func (q *Queries) CreateAppleUser(ctx context.Context, arg CreateAppleUserParams
|
|||
&i.LanguageGoal,
|
||||
&i.LanguageChallange,
|
||||
&i.FavouriteTopic,
|
||||
&i.InitialAssessmentCompleted,
|
||||
&i.EmailVerified,
|
||||
&i.PhoneVerified,
|
||||
&i.Status,
|
||||
|
|
@ -194,7 +193,7 @@ INSERT INTO users (
|
|||
VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7, true, $8
|
||||
)
|
||||
RETURNING id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
RETURNING id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
`
|
||||
|
||||
type CreateGoogleUserParams struct {
|
||||
|
|
@ -240,7 +239,6 @@ func (q *Queries) CreateGoogleUser(ctx context.Context, arg CreateGoogleUserPara
|
|||
&i.LanguageGoal,
|
||||
&i.LanguageChallange,
|
||||
&i.FavouriteTopic,
|
||||
&i.InitialAssessmentCompleted,
|
||||
&i.EmailVerified,
|
||||
&i.PhoneVerified,
|
||||
&i.Status,
|
||||
|
|
@ -285,7 +283,6 @@ INSERT INTO users (
|
|||
language_challange,
|
||||
favourite_topic,
|
||||
|
||||
initial_assessment_completed,
|
||||
email_verified,
|
||||
phone_verified,
|
||||
status,
|
||||
|
|
@ -321,7 +318,6 @@ VALUES (
|
|||
$22,
|
||||
$23,
|
||||
$24,
|
||||
$25,
|
||||
CURRENT_TIMESTAMP
|
||||
)
|
||||
RETURNING
|
||||
|
|
@ -345,7 +341,6 @@ RETURNING
|
|||
language_challange,
|
||||
favourite_topic,
|
||||
|
||||
initial_assessment_completed,
|
||||
email_verified,
|
||||
phone_verified,
|
||||
status,
|
||||
|
|
@ -358,31 +353,30 @@ RETURNING
|
|||
`
|
||||
|
||||
type CreateUserParams struct {
|
||||
FirstName pgtype.Text `json:"first_name"`
|
||||
LastName pgtype.Text `json:"last_name"`
|
||||
Gender pgtype.Text `json:"gender"`
|
||||
BirthDay pgtype.Date `json:"birth_day"`
|
||||
Email pgtype.Text `json:"email"`
|
||||
PhoneNumber pgtype.Text `json:"phone_number"`
|
||||
Role string `json:"role"`
|
||||
Password []byte `json:"password"`
|
||||
AgeGroup pgtype.Text `json:"age_group"`
|
||||
EducationLevel pgtype.Text `json:"education_level"`
|
||||
Country pgtype.Text `json:"country"`
|
||||
Region pgtype.Text `json:"region"`
|
||||
NickName pgtype.Text `json:"nick_name"`
|
||||
Occupation pgtype.Text `json:"occupation"`
|
||||
LearningGoal pgtype.Text `json:"learning_goal"`
|
||||
LanguageGoal pgtype.Text `json:"language_goal"`
|
||||
LanguageChallange pgtype.Text `json:"language_challange"`
|
||||
FavouriteTopic pgtype.Text `json:"favourite_topic"`
|
||||
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
PhoneVerified bool `json:"phone_verified"`
|
||||
Status string `json:"status"`
|
||||
ProfileCompleted pgtype.Bool `json:"profile_completed"`
|
||||
ProfilePictureUrl pgtype.Text `json:"profile_picture_url"`
|
||||
PreferredLanguage pgtype.Text `json:"preferred_language"`
|
||||
FirstName pgtype.Text `json:"first_name"`
|
||||
LastName pgtype.Text `json:"last_name"`
|
||||
Gender pgtype.Text `json:"gender"`
|
||||
BirthDay pgtype.Date `json:"birth_day"`
|
||||
Email pgtype.Text `json:"email"`
|
||||
PhoneNumber pgtype.Text `json:"phone_number"`
|
||||
Role string `json:"role"`
|
||||
Password []byte `json:"password"`
|
||||
AgeGroup pgtype.Text `json:"age_group"`
|
||||
EducationLevel pgtype.Text `json:"education_level"`
|
||||
Country pgtype.Text `json:"country"`
|
||||
Region pgtype.Text `json:"region"`
|
||||
NickName pgtype.Text `json:"nick_name"`
|
||||
Occupation pgtype.Text `json:"occupation"`
|
||||
LearningGoal pgtype.Text `json:"learning_goal"`
|
||||
LanguageGoal pgtype.Text `json:"language_goal"`
|
||||
LanguageChallange pgtype.Text `json:"language_challange"`
|
||||
FavouriteTopic pgtype.Text `json:"favourite_topic"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
PhoneVerified bool `json:"phone_verified"`
|
||||
Status string `json:"status"`
|
||||
ProfileCompleted pgtype.Bool `json:"profile_completed"`
|
||||
ProfilePictureUrl pgtype.Text `json:"profile_picture_url"`
|
||||
PreferredLanguage pgtype.Text `json:"preferred_language"`
|
||||
}
|
||||
|
||||
type CreateUserRow struct {
|
||||
|
|
@ -404,7 +398,6 @@ type CreateUserRow struct {
|
|||
LanguageGoal pgtype.Text `json:"language_goal"`
|
||||
LanguageChallange pgtype.Text `json:"language_challange"`
|
||||
FavouriteTopic pgtype.Text `json:"favourite_topic"`
|
||||
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
PhoneVerified bool `json:"phone_verified"`
|
||||
Status string `json:"status"`
|
||||
|
|
@ -436,7 +429,6 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateU
|
|||
arg.LanguageGoal,
|
||||
arg.LanguageChallange,
|
||||
arg.FavouriteTopic,
|
||||
arg.InitialAssessmentCompleted,
|
||||
arg.EmailVerified,
|
||||
arg.PhoneVerified,
|
||||
arg.Status,
|
||||
|
|
@ -464,7 +456,6 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateU
|
|||
&i.LanguageGoal,
|
||||
&i.LanguageChallange,
|
||||
&i.FavouriteTopic,
|
||||
&i.InitialAssessmentCompleted,
|
||||
&i.EmailVerified,
|
||||
&i.PhoneVerified,
|
||||
&i.Status,
|
||||
|
|
@ -510,7 +501,6 @@ SELECT
|
|||
language_goal,
|
||||
language_challange,
|
||||
favourite_topic,
|
||||
initial_assessment_completed,
|
||||
email_verified,
|
||||
phone_verified,
|
||||
status,
|
||||
|
|
@ -553,54 +543,53 @@ WHERE
|
|||
AND ($13::TEXT IS NULL OR LOWER(TRIM(COALESCE(learning_goal, ''))) = LOWER(TRIM($13::TEXT)))
|
||||
AND ($14::TEXT IS NULL OR LOWER(TRIM(COALESCE(knowledge_level, ''))) = LOWER(TRIM($14::TEXT)))
|
||||
AND ($15::BOOLEAN IS NULL OR profile_completed = $15::BOOLEAN)
|
||||
AND ($16::BOOLEAN IS NULL OR initial_assessment_completed = $16::BOOLEAN)
|
||||
AND (
|
||||
$17::INT IS NULL
|
||||
OR profile_completion_percentage >= $17::INT
|
||||
$16::INT IS NULL
|
||||
OR profile_completion_percentage >= $16::INT
|
||||
)
|
||||
AND ($17::TIMESTAMPTZ IS NULL OR last_login >= $17::TIMESTAMPTZ)
|
||||
AND ($18::TIMESTAMPTZ IS NULL OR last_login <= $18::TIMESTAMPTZ)
|
||||
AND (
|
||||
$19::INT IS NULL
|
||||
OR (
|
||||
last_login IS NOT NULL
|
||||
AND last_login <= CURRENT_TIMESTAMP - ($19::INT || ' days')::INTERVAL
|
||||
)
|
||||
)
|
||||
AND ($18::TIMESTAMPTZ IS NULL OR last_login >= $18::TIMESTAMPTZ)
|
||||
AND ($19::TIMESTAMPTZ IS NULL OR last_login <= $19::TIMESTAMPTZ)
|
||||
AND (
|
||||
$20::INT IS NULL
|
||||
OR (
|
||||
last_login IS NOT NULL
|
||||
AND last_login <= CURRENT_TIMESTAMP - ($20::INT || ' days')::INTERVAL
|
||||
AND last_login >= CURRENT_TIMESTAMP - ($20::INT || ' days')::INTERVAL
|
||||
)
|
||||
)
|
||||
AND (
|
||||
$21::INT IS NULL
|
||||
OR (
|
||||
last_login IS NOT NULL
|
||||
AND last_login >= CURRENT_TIMESTAMP - ($21::INT || ' days')::INTERVAL
|
||||
)
|
||||
SELECT COUNT(*)::INT
|
||||
FROM lms_user_lesson_progress ulp
|
||||
WHERE ulp.user_id = users.id
|
||||
) >= $21::INT
|
||||
)
|
||||
AND (
|
||||
$22::INT IS NULL
|
||||
OR (
|
||||
SELECT COUNT(*)::INT
|
||||
FROM lms_user_lesson_progress ulp
|
||||
WHERE ulp.user_id = users.id
|
||||
FROM lms_user_module_progress ump
|
||||
WHERE ump.user_id = users.id
|
||||
) >= $22::INT
|
||||
)
|
||||
AND (
|
||||
$23::INT IS NULL
|
||||
$23::BOOLEAN IS NULL
|
||||
OR (
|
||||
SELECT COUNT(*)::INT
|
||||
FROM lms_user_module_progress ump
|
||||
WHERE ump.user_id = users.id
|
||||
) >= $23::INT
|
||||
)
|
||||
AND (
|
||||
$24::BOOLEAN IS NULL
|
||||
OR (
|
||||
$24::BOOLEAN = TRUE
|
||||
$23::BOOLEAN = TRUE
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM payments p
|
||||
WHERE p.user_id = users.id AND p.status = 'SUCCESS'
|
||||
)
|
||||
)
|
||||
OR (
|
||||
$24::BOOLEAN = FALSE
|
||||
$23::BOOLEAN = FALSE
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM payments p
|
||||
WHERE p.user_id = users.id AND p.status = 'SUCCESS'
|
||||
|
|
@ -608,27 +597,27 @@ WHERE
|
|||
)
|
||||
)
|
||||
AND (
|
||||
$25::BOOLEAN IS NULL
|
||||
$24::BOOLEAN IS NULL
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM user_subscriptions us
|
||||
WHERE us.user_id = users.id
|
||||
AND us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND us.auto_renew = $25::BOOLEAN
|
||||
AND us.auto_renew = $24::BOOLEAN
|
||||
)
|
||||
)
|
||||
AND (
|
||||
$26::BIGINT IS NULL
|
||||
$25::BIGINT IS NULL
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM user_subscriptions us
|
||||
WHERE us.user_id = users.id
|
||||
AND us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND us.plan_id = $26::BIGINT
|
||||
AND us.plan_id = $25::BIGINT
|
||||
)
|
||||
)
|
||||
AND (
|
||||
$27::TEXT IS NULL
|
||||
$26::TEXT IS NULL
|
||||
OR EXISTS (
|
||||
SELECT 1
|
||||
FROM user_subscriptions us
|
||||
|
|
@ -636,32 +625,32 @@ WHERE
|
|||
WHERE us.user_id = users.id
|
||||
AND us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND UPPER(TRIM(sp.category)) = UPPER(TRIM($27::TEXT))
|
||||
AND UPPER(TRIM(sp.category)) = UPPER(TRIM($26::TEXT))
|
||||
)
|
||||
)
|
||||
AND (
|
||||
$28::INT IS NULL
|
||||
$27::INT IS NULL
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM user_subscriptions us
|
||||
WHERE us.user_id = users.id
|
||||
AND us.status = 'ACTIVE'
|
||||
AND us.expires_at > CURRENT_TIMESTAMP
|
||||
AND us.expires_at <= CURRENT_TIMESTAMP + ($28::INT || ' days')::INTERVAL
|
||||
AND us.expires_at <= CURRENT_TIMESTAMP + ($27::INT || ' days')::INTERVAL
|
||||
)
|
||||
)
|
||||
AND (
|
||||
$29::TEXT IS NULL
|
||||
$28::TEXT IS NULL
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM devices d
|
||||
WHERE d.user_id = users.id
|
||||
AND d.is_active = TRUE
|
||||
AND LOWER(TRIM(COALESCE(d.platform, ''))) = LOWER(TRIM($29::TEXT))
|
||||
AND LOWER(TRIM(COALESCE(d.platform, ''))) = LOWER(TRIM($28::TEXT))
|
||||
)
|
||||
)
|
||||
AND (
|
||||
$30::BOOLEAN IS NULL
|
||||
$29::BOOLEAN IS NULL
|
||||
OR (
|
||||
$30::BOOLEAN = TRUE
|
||||
$29::BOOLEAN = TRUE
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM devices d
|
||||
WHERE d.user_id = users.id
|
||||
|
|
@ -670,7 +659,7 @@ WHERE
|
|||
)
|
||||
)
|
||||
OR (
|
||||
$30::BOOLEAN = FALSE
|
||||
$29::BOOLEAN = FALSE
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM devices d
|
||||
WHERE d.user_id = users.id
|
||||
|
|
@ -680,9 +669,9 @@ WHERE
|
|||
)
|
||||
)
|
||||
AND (
|
||||
$31::TEXT IS NULL
|
||||
$30::TEXT IS NULL
|
||||
OR (
|
||||
$31::TEXT = 'ACTIVE'
|
||||
$30::TEXT = 'ACTIVE'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM user_subscriptions us
|
||||
WHERE us.user_id = users.id
|
||||
|
|
@ -691,7 +680,7 @@ WHERE
|
|||
)
|
||||
)
|
||||
OR (
|
||||
$31::TEXT = 'PENDING'
|
||||
$30::TEXT = 'PENDING'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM user_subscriptions us
|
||||
WHERE us.user_id = users.id
|
||||
|
|
@ -704,7 +693,7 @@ WHERE
|
|||
)
|
||||
)
|
||||
OR (
|
||||
$31::TEXT = 'Unsubscribed'
|
||||
$30::TEXT = 'Unsubscribed'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM user_subscriptions us
|
||||
WHERE us.user_id = users.id
|
||||
|
|
@ -713,7 +702,7 @@ WHERE
|
|||
)
|
||||
)
|
||||
OR (
|
||||
$31::TEXT = 'EXPIRED'
|
||||
$30::TEXT = 'EXPIRED'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM user_subscriptions us
|
||||
WHERE us.user_id = users.id
|
||||
|
|
@ -736,44 +725,43 @@ WHERE
|
|||
)
|
||||
)
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $33::INT
|
||||
OFFSET $32::INT
|
||||
LIMIT $32::INT
|
||||
OFFSET $31::INT
|
||||
`
|
||||
|
||||
type GetAllUsersParams struct {
|
||||
Role pgtype.Text `json:"role"`
|
||||
Status pgtype.Text `json:"status"`
|
||||
Query pgtype.Text `json:"query"`
|
||||
CreatedAfter pgtype.Timestamptz `json:"created_after"`
|
||||
CreatedBefore pgtype.Timestamptz `json:"created_before"`
|
||||
Country pgtype.Text `json:"country"`
|
||||
Region pgtype.Text `json:"region"`
|
||||
EducationLevel pgtype.Text `json:"education_level"`
|
||||
Occupation pgtype.Text `json:"occupation"`
|
||||
AgeGroup pgtype.Text `json:"age_group"`
|
||||
FavouriteTopic pgtype.Text `json:"favourite_topic"`
|
||||
LanguageGoal pgtype.Text `json:"language_goal"`
|
||||
LearningGoal pgtype.Text `json:"learning_goal"`
|
||||
KnowledgeLevel pgtype.Text `json:"knowledge_level"`
|
||||
ProfileCompleted pgtype.Bool `json:"profile_completed"`
|
||||
InitialAssessmentCompleted pgtype.Bool `json:"initial_assessment_completed"`
|
||||
MinProfileCompletionPct pgtype.Int4 `json:"min_profile_completion_pct"`
|
||||
LastLoginAfter pgtype.Timestamptz `json:"last_login_after"`
|
||||
LastLoginBefore pgtype.Timestamptz `json:"last_login_before"`
|
||||
DaysSinceLastLoginMin pgtype.Int4 `json:"days_since_last_login_min"`
|
||||
DaysSinceLastLoginMax pgtype.Int4 `json:"days_since_last_login_max"`
|
||||
MinLessonsCompleted pgtype.Int4 `json:"min_lessons_completed"`
|
||||
MinModulesCompleted pgtype.Int4 `json:"min_modules_completed"`
|
||||
HasEverPaid pgtype.Bool `json:"has_ever_paid"`
|
||||
AutoRenew pgtype.Bool `json:"auto_renew"`
|
||||
PlanID pgtype.Int8 `json:"plan_id"`
|
||||
PlanCategory pgtype.Text `json:"plan_category"`
|
||||
ExpiresWithinDays pgtype.Int4 `json:"expires_within_days"`
|
||||
DevicePlatform pgtype.Text `json:"device_platform"`
|
||||
HasActiveDevice pgtype.Bool `json:"has_active_device"`
|
||||
SubscriptionStatus pgtype.Text `json:"subscription_status"`
|
||||
Offset pgtype.Int4 `json:"offset"`
|
||||
Limit pgtype.Int4 `json:"limit"`
|
||||
Role pgtype.Text `json:"role"`
|
||||
Status pgtype.Text `json:"status"`
|
||||
Query pgtype.Text `json:"query"`
|
||||
CreatedAfter pgtype.Timestamptz `json:"created_after"`
|
||||
CreatedBefore pgtype.Timestamptz `json:"created_before"`
|
||||
Country pgtype.Text `json:"country"`
|
||||
Region pgtype.Text `json:"region"`
|
||||
EducationLevel pgtype.Text `json:"education_level"`
|
||||
Occupation pgtype.Text `json:"occupation"`
|
||||
AgeGroup pgtype.Text `json:"age_group"`
|
||||
FavouriteTopic pgtype.Text `json:"favourite_topic"`
|
||||
LanguageGoal pgtype.Text `json:"language_goal"`
|
||||
LearningGoal pgtype.Text `json:"learning_goal"`
|
||||
KnowledgeLevel pgtype.Text `json:"knowledge_level"`
|
||||
ProfileCompleted pgtype.Bool `json:"profile_completed"`
|
||||
MinProfileCompletionPct pgtype.Int4 `json:"min_profile_completion_pct"`
|
||||
LastLoginAfter pgtype.Timestamptz `json:"last_login_after"`
|
||||
LastLoginBefore pgtype.Timestamptz `json:"last_login_before"`
|
||||
DaysSinceLastLoginMin pgtype.Int4 `json:"days_since_last_login_min"`
|
||||
DaysSinceLastLoginMax pgtype.Int4 `json:"days_since_last_login_max"`
|
||||
MinLessonsCompleted pgtype.Int4 `json:"min_lessons_completed"`
|
||||
MinModulesCompleted pgtype.Int4 `json:"min_modules_completed"`
|
||||
HasEverPaid pgtype.Bool `json:"has_ever_paid"`
|
||||
AutoRenew pgtype.Bool `json:"auto_renew"`
|
||||
PlanID pgtype.Int8 `json:"plan_id"`
|
||||
PlanCategory pgtype.Text `json:"plan_category"`
|
||||
ExpiresWithinDays pgtype.Int4 `json:"expires_within_days"`
|
||||
DevicePlatform pgtype.Text `json:"device_platform"`
|
||||
HasActiveDevice pgtype.Bool `json:"has_active_device"`
|
||||
SubscriptionStatus pgtype.Text `json:"subscription_status"`
|
||||
Offset pgtype.Int4 `json:"offset"`
|
||||
Limit pgtype.Int4 `json:"limit"`
|
||||
}
|
||||
|
||||
type GetAllUsersRow struct {
|
||||
|
|
@ -797,7 +785,6 @@ type GetAllUsersRow struct {
|
|||
LanguageGoal pgtype.Text `json:"language_goal"`
|
||||
LanguageChallange pgtype.Text `json:"language_challange"`
|
||||
FavouriteTopic pgtype.Text `json:"favourite_topic"`
|
||||
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
PhoneVerified bool `json:"phone_verified"`
|
||||
Status string `json:"status"`
|
||||
|
|
@ -827,7 +814,6 @@ func (q *Queries) GetAllUsers(ctx context.Context, arg GetAllUsersParams) ([]Get
|
|||
arg.LearningGoal,
|
||||
arg.KnowledgeLevel,
|
||||
arg.ProfileCompleted,
|
||||
arg.InitialAssessmentCompleted,
|
||||
arg.MinProfileCompletionPct,
|
||||
arg.LastLoginAfter,
|
||||
arg.LastLoginBefore,
|
||||
|
|
@ -874,7 +860,6 @@ func (q *Queries) GetAllUsers(ctx context.Context, arg GetAllUsersParams) ([]Get
|
|||
&i.LanguageGoal,
|
||||
&i.LanguageChallange,
|
||||
&i.FavouriteTopic,
|
||||
&i.InitialAssessmentCompleted,
|
||||
&i.EmailVerified,
|
||||
&i.PhoneVerified,
|
||||
&i.Status,
|
||||
|
|
@ -931,7 +916,7 @@ func (q *Queries) GetTotalUsers(ctx context.Context, role string) (int64, error)
|
|||
}
|
||||
|
||||
const GetUserByAppleID = `-- name: GetUserByAppleID :one
|
||||
SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
FROM users
|
||||
WHERE apple_id = $1
|
||||
`
|
||||
|
|
@ -959,7 +944,6 @@ func (q *Queries) GetUserByAppleID(ctx context.Context, appleID pgtype.Text) (Us
|
|||
&i.LanguageGoal,
|
||||
&i.LanguageChallange,
|
||||
&i.FavouriteTopic,
|
||||
&i.InitialAssessmentCompleted,
|
||||
&i.EmailVerified,
|
||||
&i.PhoneVerified,
|
||||
&i.Status,
|
||||
|
|
@ -1140,7 +1124,7 @@ func (q *Queries) GetUserByEmailPhone(ctx context.Context, arg GetUserByEmailPho
|
|||
}
|
||||
|
||||
const GetUserByGoogleID = `-- name: GetUserByGoogleID :one
|
||||
SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
FROM users
|
||||
WHERE google_id = $1
|
||||
`
|
||||
|
|
@ -1168,7 +1152,6 @@ func (q *Queries) GetUserByGoogleID(ctx context.Context, googleID pgtype.Text) (
|
|||
&i.LanguageGoal,
|
||||
&i.LanguageChallange,
|
||||
&i.FavouriteTopic,
|
||||
&i.InitialAssessmentCompleted,
|
||||
&i.EmailVerified,
|
||||
&i.PhoneVerified,
|
||||
&i.Status,
|
||||
|
|
@ -1192,7 +1175,7 @@ func (q *Queries) GetUserByGoogleID(ctx context.Context, googleID pgtype.Text) (
|
|||
}
|
||||
|
||||
const GetUserByID = `-- name: GetUserByID :one
|
||||
SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`
|
||||
|
|
@ -1220,7 +1203,6 @@ func (q *Queries) GetUserByID(ctx context.Context, id int64) (User, error) {
|
|||
&i.LanguageGoal,
|
||||
&i.LanguageChallange,
|
||||
&i.FavouriteTopic,
|
||||
&i.InitialAssessmentCompleted,
|
||||
&i.EmailVerified,
|
||||
&i.PhoneVerified,
|
||||
&i.Status,
|
||||
|
|
@ -1278,7 +1260,7 @@ func (q *Queries) GetUserSummary(ctx context.Context) (GetUserSummaryRow, error)
|
|||
}
|
||||
|
||||
const GetUsersByIDs = `-- name: GetUsersByIDs :many
|
||||
SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, initial_assessment_completed, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
SELECT id, first_name, last_name, gender, birth_day, email, phone_number, role, password, education_level, country, region, knowledge_level, nick_name, occupation, learning_goal, language_goal, language_challange, favourite_topic, email_verified, phone_verified, status, last_login, profile_completed, profile_picture_url, preferred_language, created_at, updated_at, age_group, google_id, google_email_verified, profile_completion_percentage, deletion_requested_at, deletion_scheduled_at, deletion_cancelled_at, apple_id, apple_email_verified
|
||||
FROM users
|
||||
WHERE id = ANY($1::BIGINT[])
|
||||
`
|
||||
|
|
@ -1312,7 +1294,6 @@ func (q *Queries) GetUsersByIDs(ctx context.Context, dollar_1 []int64) ([]User,
|
|||
&i.LanguageGoal,
|
||||
&i.LanguageChallange,
|
||||
&i.FavouriteTopic,
|
||||
&i.InitialAssessmentCompleted,
|
||||
&i.EmailVerified,
|
||||
&i.PhoneVerified,
|
||||
&i.Status,
|
||||
|
|
@ -1432,7 +1413,6 @@ SELECT
|
|||
language_challange,
|
||||
favourite_topic,
|
||||
|
||||
initial_assessment_completed,
|
||||
profile_picture_url,
|
||||
preferred_language,
|
||||
email_verified,
|
||||
|
|
@ -1479,7 +1459,6 @@ type SearchUserByNameOrPhoneRow struct {
|
|||
LanguageGoal pgtype.Text `json:"language_goal"`
|
||||
LanguageChallange pgtype.Text `json:"language_challange"`
|
||||
FavouriteTopic pgtype.Text `json:"favourite_topic"`
|
||||
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
|
||||
ProfilePictureUrl pgtype.Text `json:"profile_picture_url"`
|
||||
PreferredLanguage pgtype.Text `json:"preferred_language"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
|
|
@ -1519,7 +1498,6 @@ func (q *Queries) SearchUserByNameOrPhone(ctx context.Context, arg SearchUserByN
|
|||
&i.LanguageGoal,
|
||||
&i.LanguageChallange,
|
||||
&i.FavouriteTopic,
|
||||
&i.InitialAssessmentCompleted,
|
||||
&i.ProfilePictureUrl,
|
||||
&i.PreferredLanguage,
|
||||
&i.EmailVerified,
|
||||
|
|
@ -1574,35 +1552,33 @@ SET
|
|||
language_goal = COALESCE($11, language_goal),
|
||||
language_challange = COALESCE($12, language_challange),
|
||||
favourite_topic = COALESCE($13, favourite_topic),
|
||||
initial_assessment_completed = COALESCE($14, initial_assessment_completed),
|
||||
profile_picture_url = COALESCE($15, profile_picture_url),
|
||||
preferred_language = COALESCE($16, preferred_language),
|
||||
gender = COALESCE($17, gender),
|
||||
birth_day = COALESCE($18, birth_day),
|
||||
profile_picture_url = COALESCE($14, profile_picture_url),
|
||||
preferred_language = COALESCE($15, preferred_language),
|
||||
gender = COALESCE($16, gender),
|
||||
birth_day = COALESCE($17, birth_day),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $19
|
||||
WHERE id = $18
|
||||
`
|
||||
|
||||
type UpdateUserParams struct {
|
||||
FirstName pgtype.Text `json:"first_name"`
|
||||
LastName pgtype.Text `json:"last_name"`
|
||||
KnowledgeLevel pgtype.Text `json:"knowledge_level"`
|
||||
AgeGroup pgtype.Text `json:"age_group"`
|
||||
EducationLevel pgtype.Text `json:"education_level"`
|
||||
Country pgtype.Text `json:"country"`
|
||||
Region pgtype.Text `json:"region"`
|
||||
NickName pgtype.Text `json:"nick_name"`
|
||||
Occupation pgtype.Text `json:"occupation"`
|
||||
LearningGoal pgtype.Text `json:"learning_goal"`
|
||||
LanguageGoal pgtype.Text `json:"language_goal"`
|
||||
LanguageChallange pgtype.Text `json:"language_challange"`
|
||||
FavouriteTopic pgtype.Text `json:"favourite_topic"`
|
||||
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
|
||||
ProfilePictureUrl pgtype.Text `json:"profile_picture_url"`
|
||||
PreferredLanguage pgtype.Text `json:"preferred_language"`
|
||||
Gender pgtype.Text `json:"gender"`
|
||||
BirthDay pgtype.Date `json:"birth_day"`
|
||||
ID int64 `json:"id"`
|
||||
FirstName pgtype.Text `json:"first_name"`
|
||||
LastName pgtype.Text `json:"last_name"`
|
||||
KnowledgeLevel pgtype.Text `json:"knowledge_level"`
|
||||
AgeGroup pgtype.Text `json:"age_group"`
|
||||
EducationLevel pgtype.Text `json:"education_level"`
|
||||
Country pgtype.Text `json:"country"`
|
||||
Region pgtype.Text `json:"region"`
|
||||
NickName pgtype.Text `json:"nick_name"`
|
||||
Occupation pgtype.Text `json:"occupation"`
|
||||
LearningGoal pgtype.Text `json:"learning_goal"`
|
||||
LanguageGoal pgtype.Text `json:"language_goal"`
|
||||
LanguageChallange pgtype.Text `json:"language_challange"`
|
||||
FavouriteTopic pgtype.Text `json:"favourite_topic"`
|
||||
ProfilePictureUrl pgtype.Text `json:"profile_picture_url"`
|
||||
PreferredLanguage pgtype.Text `json:"preferred_language"`
|
||||
Gender pgtype.Text `json:"gender"`
|
||||
BirthDay pgtype.Date `json:"birth_day"`
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
|
||||
// Note: profile_completed and profile_completion_percentage are computed by database trigger
|
||||
|
|
@ -1621,7 +1597,6 @@ func (q *Queries) UpdateUser(ctx context.Context, arg UpdateUserParams) error {
|
|||
arg.LanguageGoal,
|
||||
arg.LanguageChallange,
|
||||
arg.FavouriteTopic,
|
||||
arg.InitialAssessmentCompleted,
|
||||
arg.ProfilePictureUrl,
|
||||
arg.PreferredLanguage,
|
||||
arg.Gender,
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
customlogger "Yimaru-Backend/internal/logger"
|
||||
"Rezina-Backend/internal/domain"
|
||||
customlogger "Rezina-Backend/internal/logger"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
|
@ -396,7 +396,7 @@ func (c *Config) loadEnv() error {
|
|||
|
||||
c.AFRO_SMS_SENDER_NAME = os.Getenv("AFRO_SMS_SENDER_NAME")
|
||||
if c.AFRO_SMS_SENDER_NAME == "" {
|
||||
c.AFRO_SMS_SENDER_NAME = "Yimaru Acad"
|
||||
c.AFRO_SMS_SENDER_NAME = "Rezina"
|
||||
}
|
||||
|
||||
c.AFRO_SMS_RECEIVER_PHONE_NUMBER = os.Getenv("AFRO_SMS_RECEIVER_PHONE_NUMBER")
|
||||
|
|
@ -564,7 +564,7 @@ func (c *Config) loadEnv() error {
|
|||
}
|
||||
|
||||
if strings.TrimSpace(c.MinIO.Bucket) == "" {
|
||||
c.MinIO.Bucket = "yimaru"
|
||||
c.MinIO.Bucket = "rezina"
|
||||
}
|
||||
minioUseSSL := os.Getenv("MINIO_USE_SSL")
|
||||
if minioUseSSL == "true" || minioUseSSL == "1" {
|
||||
|
|
|
|||
|
|
@ -1,449 +0,0 @@
|
|||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CEFR placement levels returned by the initial assessment.
|
||||
var InitialAssessmentCEFRLevels = []string{"A1", "A2", "B1", "B2", "C1", "C2"}
|
||||
|
||||
// DefaultInitialAssessmentThresholds are seeded when the table is empty / on first install.
|
||||
// min_percent is the pass mark for that CEFR level's question set (progressive placement).
|
||||
func DefaultInitialAssessmentThresholds() []InitialAssessmentLevelThreshold {
|
||||
return []InitialAssessmentLevelThreshold{
|
||||
{Level: "A1", MinPercent: 70, DisplayOrder: 1},
|
||||
{Level: "A2", MinPercent: 70, DisplayOrder: 2},
|
||||
{Level: "B1", MinPercent: 70, DisplayOrder: 3},
|
||||
{Level: "B2", MinPercent: 70, DisplayOrder: 4},
|
||||
{Level: "C1", MinPercent: 70, DisplayOrder: 5},
|
||||
{Level: "C2", MinPercent: 70, DisplayOrder: 6},
|
||||
}
|
||||
}
|
||||
|
||||
type InitialAssessmentLevelThreshold struct {
|
||||
Level string `json:"level"`
|
||||
MinPercent int `json:"min_percent"`
|
||||
DisplayOrder int `json:"display_order"`
|
||||
}
|
||||
|
||||
type PlacementAnswerInput struct {
|
||||
QuestionID int64 `json:"question_id"`
|
||||
SelectedOptionIDs []int64 `json:"selected_option_ids,omitempty"`
|
||||
TextAnswer *string `json:"text_answer,omitempty"`
|
||||
DynamicAnswers []PlacementDynamicAnswerInput `json:"dynamic_answers,omitempty"`
|
||||
}
|
||||
|
||||
type PlacementDynamicAnswerInput struct {
|
||||
ElementID string `json:"element_id"`
|
||||
SelectedOptionIDs []string `json:"selected_option_ids,omitempty"`
|
||||
TextAnswer *string `json:"text_answer,omitempty"`
|
||||
}
|
||||
|
||||
type PlacementQuestionResult struct {
|
||||
QuestionID int64 `json:"question_id"`
|
||||
QuestionType string `json:"question_type"`
|
||||
Gradable bool `json:"gradable"`
|
||||
Correct bool `json:"correct"`
|
||||
PointsEarned int32 `json:"points_earned"`
|
||||
PointsMax int32 `json:"points_max"`
|
||||
Skipped bool `json:"skipped"`
|
||||
}
|
||||
|
||||
type PlacementAssessmentResult struct {
|
||||
QuestionSetID int64 `json:"question_set_id"`
|
||||
LevelAttempted string `json:"level_attempted"`
|
||||
ScorePercent float64 `json:"score_percent"`
|
||||
Passed bool `json:"passed"`
|
||||
PassPercent int `json:"pass_percent"`
|
||||
NextLevel *string `json:"next_level,omitempty"`
|
||||
Completed bool `json:"completed"`
|
||||
Level string `json:"level"` // final knowledge level when completed; else last passed / attempted context
|
||||
PointsEarned int32 `json:"points_earned"`
|
||||
PointsMax int32 `json:"points_max"`
|
||||
GradableQuestions int `json:"gradable_questions"`
|
||||
CorrectQuestions int `json:"correct_questions"`
|
||||
SkippedUngradableQuestions int `json:"skipped_ungradable_questions"`
|
||||
Questions []PlacementQuestionResult `json:"questions"`
|
||||
KnowledgeLevel string `json:"knowledge_level,omitempty"`
|
||||
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
|
||||
}
|
||||
|
||||
// PlacementSession is the learner's progressive placement state.
|
||||
type PlacementSession struct {
|
||||
NextLevel string `json:"next_level,omitempty"`
|
||||
HighestPassedLevel *string `json:"highest_passed_level,omitempty"`
|
||||
Completed bool `json:"completed"`
|
||||
KnowledgeLevel string `json:"knowledge_level,omitempty"`
|
||||
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
|
||||
PublishedLevels []string `json:"published_levels"`
|
||||
}
|
||||
|
||||
// UserInitialAssessmentProgress persists in-progress progressive placement.
|
||||
type UserInitialAssessmentProgress struct {
|
||||
UserID int64
|
||||
NextLevel string
|
||||
HighestPassedLevel *string
|
||||
Completed bool
|
||||
}
|
||||
|
||||
func NormalizeCEFRLevel(level string) (string, error) {
|
||||
normalized := strings.ToUpper(strings.TrimSpace(level))
|
||||
for _, allowed := range InitialAssessmentCEFRLevels {
|
||||
if normalized == allowed {
|
||||
return normalized, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("level must be one of: %s", strings.Join(InitialAssessmentCEFRLevels, ", "))
|
||||
}
|
||||
|
||||
// NextCEFRLevel returns the following CEFR band, or "" after C2.
|
||||
func NextCEFRLevel(level string) string {
|
||||
normalized, err := NormalizeCEFRLevel(level)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for i, l := range InitialAssessmentCEFRLevels {
|
||||
if l == normalized {
|
||||
if i+1 < len(InitialAssessmentCEFRLevels) {
|
||||
return InitialAssessmentCEFRLevels[i+1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ValidateInitialAssessmentThresholds ensures every CEFR level is present once
|
||||
// with a pass mark between 0 and 100.
|
||||
func ValidateInitialAssessmentThresholds(rows []InitialAssessmentLevelThreshold) error {
|
||||
if len(rows) != len(InitialAssessmentCEFRLevels) {
|
||||
return fmt.Errorf("expected exactly %d thresholds (A1–C2)", len(InitialAssessmentCEFRLevels))
|
||||
}
|
||||
|
||||
byLevel := make(map[string]InitialAssessmentLevelThreshold, len(rows))
|
||||
for _, row := range rows {
|
||||
level, err := NormalizeCEFRLevel(row.Level)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, exists := byLevel[level]; exists {
|
||||
return fmt.Errorf("duplicate threshold for level %s", level)
|
||||
}
|
||||
if row.MinPercent < 0 || row.MinPercent > 100 {
|
||||
return fmt.Errorf("min_percent for %s must be between 0 and 100", level)
|
||||
}
|
||||
byLevel[level] = InitialAssessmentLevelThreshold{
|
||||
Level: level,
|
||||
MinPercent: row.MinPercent,
|
||||
DisplayOrder: row.DisplayOrder,
|
||||
}
|
||||
}
|
||||
|
||||
for _, level := range InitialAssessmentCEFRLevels {
|
||||
if _, ok := byLevel[level]; !ok {
|
||||
return fmt.Errorf("missing threshold for level %s", level)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PassPercentForLevel returns the configured pass mark for a CEFR level set.
|
||||
func PassPercentForLevel(level string, thresholds []InitialAssessmentLevelThreshold) (int, error) {
|
||||
normalized, err := NormalizeCEFRLevel(level)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(thresholds) == 0 {
|
||||
thresholds = DefaultInitialAssessmentThresholds()
|
||||
}
|
||||
thresholds = mergeThresholdDefaults(thresholds)
|
||||
for _, row := range thresholds {
|
||||
if row.Level == normalized {
|
||||
return row.MinPercent, nil
|
||||
}
|
||||
}
|
||||
return 0, fmt.Errorf("missing threshold for level %s", normalized)
|
||||
}
|
||||
|
||||
// ResolveCEFRLevelFromScore is retained for legacy single-test banding.
|
||||
// Progressive placement uses PassPercentForLevel instead.
|
||||
func ResolveCEFRLevelFromScore(scorePercent float64, thresholds []InitialAssessmentLevelThreshold) (string, error) {
|
||||
if len(thresholds) == 0 {
|
||||
thresholds = DefaultInitialAssessmentThresholds()
|
||||
}
|
||||
if err := ValidateInitialAssessmentThresholds(thresholds); err != nil {
|
||||
thresholds = mergeThresholdDefaults(thresholds)
|
||||
if err := ValidateInitialAssessmentThresholds(thresholds); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
sorted := append([]InitialAssessmentLevelThreshold(nil), thresholds...)
|
||||
sort.Slice(sorted, func(i, j int) bool {
|
||||
return sorted[i].MinPercent < sorted[j].MinPercent
|
||||
})
|
||||
|
||||
level := sorted[0].Level
|
||||
for _, row := range sorted {
|
||||
if scorePercent+1e-9 >= float64(row.MinPercent) {
|
||||
level = row.Level
|
||||
}
|
||||
}
|
||||
return level, nil
|
||||
}
|
||||
|
||||
func mergeThresholdDefaults(rows []InitialAssessmentLevelThreshold) []InitialAssessmentLevelThreshold {
|
||||
byLevel := make(map[string]InitialAssessmentLevelThreshold)
|
||||
for _, d := range DefaultInitialAssessmentThresholds() {
|
||||
byLevel[d.Level] = d
|
||||
}
|
||||
for _, row := range rows {
|
||||
level, err := NormalizeCEFRLevel(row.Level)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
row.Level = level
|
||||
byLevel[level] = row
|
||||
}
|
||||
out := make([]InitialAssessmentLevelThreshold, 0, len(InitialAssessmentCEFRLevels))
|
||||
for i, level := range InitialAssessmentCEFRLevels {
|
||||
row := byLevel[level]
|
||||
if row.DisplayOrder <= 0 {
|
||||
row.DisplayOrder = i + 1
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// GradePlacementAnswers scores published placement questions against submitted answers.
|
||||
// Auto-gradable: MCQ, TRUE_FALSE, SHORT_ANSWER, and DYNAMIC multiple-choice / option slots.
|
||||
// AUDIO and other dynamic kinds are skipped (not counted in score denominator).
|
||||
func GradePlacementAnswers(
|
||||
questions []QuestionWithDetails,
|
||||
answers []PlacementAnswerInput,
|
||||
) PlacementAssessmentResult {
|
||||
byID := make(map[int64]PlacementAnswerInput, len(answers))
|
||||
for _, a := range answers {
|
||||
byID[a.QuestionID] = a
|
||||
}
|
||||
|
||||
result := PlacementAssessmentResult{
|
||||
Questions: make([]PlacementQuestionResult, 0, len(questions)),
|
||||
}
|
||||
|
||||
for _, q := range questions {
|
||||
points := q.Points
|
||||
if points <= 0 {
|
||||
points = 1
|
||||
}
|
||||
qr := PlacementQuestionResult{
|
||||
QuestionID: q.ID,
|
||||
QuestionType: q.QuestionType,
|
||||
PointsMax: points,
|
||||
}
|
||||
ans, answered := byID[q.ID]
|
||||
|
||||
gradable, correct := gradeOnePlacementQuestion(q, ans, answered)
|
||||
qr.Gradable = gradable
|
||||
if !gradable {
|
||||
qr.Skipped = true
|
||||
result.SkippedUngradableQuestions++
|
||||
result.Questions = append(result.Questions, qr)
|
||||
continue
|
||||
}
|
||||
|
||||
result.GradableQuestions++
|
||||
result.PointsMax += points
|
||||
qr.Correct = correct
|
||||
if correct {
|
||||
qr.PointsEarned = points
|
||||
result.PointsEarned += points
|
||||
result.CorrectQuestions++
|
||||
}
|
||||
if !answered {
|
||||
qr.Skipped = true
|
||||
}
|
||||
result.Questions = append(result.Questions, qr)
|
||||
}
|
||||
|
||||
if result.PointsMax > 0 {
|
||||
result.ScorePercent = (float64(result.PointsEarned) / float64(result.PointsMax)) * 100
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func gradeOnePlacementQuestion(q QuestionWithDetails, ans PlacementAnswerInput, answered bool) (gradable bool, correct bool) {
|
||||
qType := strings.ToUpper(strings.TrimSpace(q.QuestionType))
|
||||
switch qType {
|
||||
case "MCQ", "TRUE_FALSE":
|
||||
return true, answered && gradeSelectedOptionIDs(q.Options, ans.SelectedOptionIDs)
|
||||
case "SHORT_ANSWER":
|
||||
text := ""
|
||||
if ans.TextAnswer != nil {
|
||||
text = *ans.TextAnswer
|
||||
}
|
||||
return true, answered && gradeShortAnswer(q.ShortAnswers, text)
|
||||
case "DYNAMIC":
|
||||
return gradeDynamicPlacementQuestion(q, ans, answered)
|
||||
default:
|
||||
// AUDIO and unknown types are not auto-graded in v1.
|
||||
return false, false
|
||||
}
|
||||
}
|
||||
|
||||
func gradeSelectedOptionIDs(options []QuestionOption, selected []int64) bool {
|
||||
correctIDs := make(map[int64]struct{})
|
||||
for _, opt := range options {
|
||||
if opt.IsCorrect {
|
||||
correctIDs[opt.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
if len(correctIDs) == 0 {
|
||||
return false
|
||||
}
|
||||
if len(selected) != len(correctIDs) {
|
||||
return false
|
||||
}
|
||||
seen := make(map[int64]struct{}, len(selected))
|
||||
for _, id := range selected {
|
||||
if _, ok := correctIDs[id]; !ok {
|
||||
return false
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
return len(seen) == len(correctIDs)
|
||||
}
|
||||
|
||||
func gradeShortAnswer(acceptable []QuestionShortAnswer, given string) bool {
|
||||
given = strings.TrimSpace(given)
|
||||
if given == "" || len(acceptable) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, sa := range acceptable {
|
||||
want := strings.TrimSpace(sa.AcceptableAnswer)
|
||||
match := strings.ToUpper(strings.TrimSpace(sa.MatchType))
|
||||
switch match {
|
||||
case string(MatchTypeContains):
|
||||
if strings.Contains(strings.ToLower(given), strings.ToLower(want)) {
|
||||
return true
|
||||
}
|
||||
case string(MatchTypeCaseInsensitive), "":
|
||||
if strings.EqualFold(given, want) {
|
||||
return true
|
||||
}
|
||||
default: // EXACT
|
||||
if given == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func gradeDynamicPlacementQuestion(q QuestionWithDetails, ans PlacementAnswerInput, answered bool) (gradable bool, correct bool) {
|
||||
if q.DynamicPayload == nil {
|
||||
return false, false
|
||||
}
|
||||
|
||||
type slotSpec struct {
|
||||
kind string
|
||||
correct []string
|
||||
short []string
|
||||
match string
|
||||
}
|
||||
|
||||
slots := make(map[string]slotSpec)
|
||||
collect := func(els []DynamicElementInstance) {
|
||||
for _, el := range els {
|
||||
id := strings.TrimSpace(el.ID)
|
||||
kind := strings.TrimSpace(el.Kind)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if isMultipleChoiceComponentKind(kind) {
|
||||
correctOpts := extractCorrectDynamicOptionIDs(el.Value)
|
||||
if len(correctOpts) == 0 {
|
||||
continue
|
||||
}
|
||||
slots[id] = slotSpec{kind: kind, correct: correctOpts}
|
||||
}
|
||||
}
|
||||
}
|
||||
collect(q.DynamicPayload.Stimulus)
|
||||
collect(q.DynamicPayload.Response)
|
||||
|
||||
if len(slots) == 0 {
|
||||
return false, false
|
||||
}
|
||||
|
||||
if !answered {
|
||||
return true, false
|
||||
}
|
||||
|
||||
byElement := make(map[string]PlacementDynamicAnswerInput, len(ans.DynamicAnswers))
|
||||
for _, da := range ans.DynamicAnswers {
|
||||
byElement[strings.TrimSpace(da.ElementID)] = da
|
||||
}
|
||||
|
||||
for id, spec := range slots {
|
||||
da, ok := byElement[id]
|
||||
if !ok {
|
||||
return true, false
|
||||
}
|
||||
if isMultipleChoiceComponentKind(spec.kind) {
|
||||
if !sameStringSet(spec.correct, da.SelectedOptionIDs) {
|
||||
return true, false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true, true
|
||||
}
|
||||
|
||||
func extractCorrectDynamicOptionIDs(value interface{}) []string {
|
||||
m, ok := value.(map[string]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
rawOpts, ok := m["options"].([]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
for _, o := range rawOpts {
|
||||
om, ok := o.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if c, _ := om["is_correct"].(bool); !c {
|
||||
continue
|
||||
}
|
||||
id, _ := om["id"].(string)
|
||||
id = strings.TrimSpace(id)
|
||||
if id != "" {
|
||||
out = append(out, id)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func sameStringSet(want, got []string) bool {
|
||||
if len(want) != len(got) {
|
||||
return false
|
||||
}
|
||||
set := make(map[string]struct{}, len(want))
|
||||
for _, w := range want {
|
||||
set[strings.TrimSpace(w)] = struct{}{}
|
||||
}
|
||||
if len(set) != len(want) {
|
||||
return false
|
||||
}
|
||||
for _, g := range got {
|
||||
if _, ok := set[strings.TrimSpace(g)]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
package domain
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPassPercentForLevel(t *testing.T) {
|
||||
thresholds := DefaultInitialAssessmentThresholds()
|
||||
got, err := PassPercentForLevel("B1", thresholds)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != 70 {
|
||||
t.Fatalf("got %d want 70", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateInitialAssessmentThresholds_allowsEqualPassMarks(t *testing.T) {
|
||||
rows := DefaultInitialAssessmentThresholds()
|
||||
if err := ValidateInitialAssessmentThresholds(rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateInitialAssessmentThresholds_rejectsOutOfRange(t *testing.T) {
|
||||
rows := DefaultInitialAssessmentThresholds()
|
||||
rows[2].MinPercent = 101
|
||||
if err := ValidateInitialAssessmentThresholds(rows); err == nil {
|
||||
t.Fatal("expected validation error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextCEFRLevel(t *testing.T) {
|
||||
if got := NextCEFRLevel("A1"); got != "A2" {
|
||||
t.Fatalf("got %s want A2", got)
|
||||
}
|
||||
if got := NextCEFRLevel("C2"); got != "" {
|
||||
t.Fatalf("got %q want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGradePlacementAnswers_mcqAndShort(t *testing.T) {
|
||||
questions := []QuestionWithDetails{
|
||||
{
|
||||
Question: Question{ID: 1, QuestionType: "MCQ", Points: 2},
|
||||
Options: []QuestionOption{
|
||||
{ID: 10, IsCorrect: true},
|
||||
{ID: 11, IsCorrect: false},
|
||||
},
|
||||
},
|
||||
{
|
||||
Question: Question{ID: 2, QuestionType: "SHORT_ANSWER", Points: 1},
|
||||
ShortAnswers: []QuestionShortAnswer{
|
||||
{AcceptableAnswer: "hello", MatchType: "CASE_INSENSITIVE"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Question: Question{ID: 3, QuestionType: "AUDIO", Points: 5},
|
||||
},
|
||||
}
|
||||
answers := []PlacementAnswerInput{
|
||||
{QuestionID: 1, SelectedOptionIDs: []int64{10}},
|
||||
{QuestionID: 2, TextAnswer: stringPtr("Hello")},
|
||||
}
|
||||
got := GradePlacementAnswers(questions, answers)
|
||||
if got.PointsMax != 3 {
|
||||
t.Fatalf("points max=%d want 3", got.PointsMax)
|
||||
}
|
||||
if got.PointsEarned != 3 {
|
||||
t.Fatalf("points earned=%d want 3", got.PointsEarned)
|
||||
}
|
||||
if got.SkippedUngradableQuestions != 1 {
|
||||
t.Fatalf("skipped=%d want 1", got.SkippedUngradableQuestions)
|
||||
}
|
||||
if got.ScorePercent != 100 {
|
||||
t.Fatalf("score=%v want 100", got.ScorePercent)
|
||||
}
|
||||
}
|
||||
|
||||
func stringPtr(s string) *string { return &s }
|
||||
|
|
@ -121,12 +121,14 @@ type InitiateSubscriptionPaymentRequest struct {
|
|||
}
|
||||
|
||||
type InitiateSubscriptionPaymentResponse struct {
|
||||
PaymentID int64 `json:"payment_id"`
|
||||
SessionID string `json:"session_id"`
|
||||
PaymentURL string `json:"payment_url"`
|
||||
Amount float64 `json:"amount"`
|
||||
Currency string `json:"currency"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
PaymentID int64 `json:"payment_id,omitempty"`
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
PaymentURL string `json:"payment_url,omitempty"`
|
||||
Amount float64 `json:"amount,omitempty"`
|
||||
Currency string `json:"currency,omitempty"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
FreeEnrollment bool `json:"free_enrollment,omitempty"`
|
||||
SubscriptionID int64 `json:"subscription_id,omitempty"`
|
||||
}
|
||||
|
||||
type VerifyPaymentRequest struct {
|
||||
|
|
|
|||
|
|
@ -4,18 +4,18 @@ import "time"
|
|||
|
||||
// Program is the top-level container in the LMS hierarchy (e.g. tracks like Beginner / Intermediate / Advanced).
|
||||
type Program struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
Category string `json:"category"`
|
||||
Thumbnail *string `json:"thumbnail,omitempty"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
Category string `json:"category"`
|
||||
Thumbnail *string `json:"thumbnail,omitempty"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
PublishStatus ContentPublishStatus `json:"publish_status"`
|
||||
AccessTier ContentAccessTier `json:"access_tier"`
|
||||
EffectiveAccessTier ContentAccessTier `json:"effective_access_tier,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt *time.Time `json:"updated_at,omitempty"`
|
||||
Access *LMSEntityAccess `json:"access,omitempty"`
|
||||
UpdatedAt *time.Time `json:"updated_at,omitempty"`
|
||||
Access *LMSEntityAccess `json:"access,omitempty"`
|
||||
}
|
||||
|
||||
// VisibleToLearners is true when the program appears in subscriber/catalog LMS APIs.
|
||||
|
|
@ -26,7 +26,7 @@ func (p Program) VisibleToLearners() bool {
|
|||
type CreateProgramInput struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
Category string `json:"category" validate:"required,oneof=LEARN_ENGLISH"`
|
||||
Category string `json:"category" validate:"required,oneof=EDUCATION"`
|
||||
Thumbnail *string `json:"thumbnail,omitempty"`
|
||||
// SortOrder inserts at this global program order when set; omit to append after current max (sort_order uniqueness is enforced).
|
||||
SortOrder *int `json:"sort_order,omitempty" validate:"omitempty,min=0"`
|
||||
|
|
@ -38,7 +38,7 @@ type CreateProgramInput struct {
|
|||
type UpdateProgramInput struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
Category *string `json:"category,omitempty" validate:"omitempty,oneof=LEARN_ENGLISH"`
|
||||
Category *string `json:"category,omitempty" validate:"omitempty,oneof=EDUCATION"`
|
||||
Thumbnail *string `json:"thumbnail,omitempty"`
|
||||
SortOrder *int `json:"sort_order,omitempty"`
|
||||
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
|
||||
|
|
|
|||
|
|
@ -22,12 +22,11 @@ const (
|
|||
type QuestionSetType string
|
||||
|
||||
const (
|
||||
QuestionSetTypePractice QuestionSetType = "PRACTICE"
|
||||
QuestionSetTypeInitialAssessment QuestionSetType = "INITIAL_ASSESSMENT"
|
||||
QuestionSetTypeQuiz QuestionSetType = "QUIZ"
|
||||
QuestionSetTypeExam QuestionSetType = "EXAM"
|
||||
QuestionSetTypeSurvey QuestionSetType = "SURVEY"
|
||||
QuestionSetTypeCapstone QuestionSetType = "CAPSTONE"
|
||||
QuestionSetTypePractice QuestionSetType = "PRACTICE"
|
||||
QuestionSetTypeQuiz QuestionSetType = "QUIZ"
|
||||
QuestionSetTypeExam QuestionSetType = "EXAM"
|
||||
QuestionSetTypeSurvey QuestionSetType = "SURVEY"
|
||||
QuestionSetTypeCapstone QuestionSetType = "CAPSTONE"
|
||||
)
|
||||
|
||||
type PracticeAccessBlock struct {
|
||||
|
|
@ -139,9 +138,9 @@ type QuestionSetQuestionTypeCount struct {
|
|||
|
||||
// QuestionSetQuestionTypesSummary summarizes distinct question types in a question set (e.g. linked practice).
|
||||
type QuestionSetQuestionTypesSummary struct {
|
||||
QuestionSetID int64 `json:"question_set_id"`
|
||||
QuestionSetID int64 `json:"question_set_id"`
|
||||
QuestionTypes []QuestionSetQuestionTypeCount `json:"question_types"`
|
||||
TotalQuestions int64 `json:"total_questions"`
|
||||
TotalQuestions int64 `json:"total_questions"`
|
||||
}
|
||||
|
||||
type QuestionSetItemWithQuestion struct {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package domain
|
||||
|
||||
import (
|
||||
dbgen "Yimaru-Backend/gen/db"
|
||||
dbgen "Rezina-Backend/gen/db"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
|
|
|||
|
|
@ -1,13 +1,23 @@
|
|||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrFreePlanMustHaveZeroPrice = errors.New("free plans must have price 0")
|
||||
ErrPaidPlanMustHavePositivePrice = errors.New("paid plans must have price greater than 0")
|
||||
// ErrDuplicateSubscriptionPlanPeriod: only one plan (free or paid) per category + billing period.
|
||||
ErrDuplicateSubscriptionPlanPeriod = errors.New("a subscription plan already exists for this category and billing period")
|
||||
)
|
||||
|
||||
type SubscriptionCategory string
|
||||
|
||||
const (
|
||||
SubscriptionCategoryEducation SubscriptionCategory = "EDUCATION"
|
||||
// SubscriptionCategoryLearnEnglish remains for historical plan and subscription records.
|
||||
SubscriptionCategoryLearnEnglish SubscriptionCategory = "LEARN_ENGLISH"
|
||||
SubscriptionCategoryIELTS SubscriptionCategory = "IELTS"
|
||||
SubscriptionCategoryDuolingo SubscriptionCategory = "DUOLINGO"
|
||||
|
|
@ -29,9 +39,7 @@ var ExamPrepSubscriptionGateDisabled = true
|
|||
// IsValidSubscriptionCategory reports whether category is a known plan category.
|
||||
func IsValidSubscriptionCategory(category string) bool {
|
||||
switch normalizeSubscriptionCategory(category) {
|
||||
case string(SubscriptionCategoryLearnEnglish),
|
||||
string(SubscriptionCategoryIELTS),
|
||||
string(SubscriptionCategoryDuolingo):
|
||||
case string(SubscriptionCategoryEducation):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
|
@ -40,7 +48,8 @@ func IsValidSubscriptionCategory(category string) bool {
|
|||
|
||||
// IsLMSSubscriptionCategory reports plan categories that unlock Learn English (LMS) content.
|
||||
func IsLMSSubscriptionCategory(category string) bool {
|
||||
return normalizeSubscriptionCategory(category) == string(SubscriptionCategoryLearnEnglish)
|
||||
normalized := normalizeSubscriptionCategory(category)
|
||||
return normalized == string(SubscriptionCategoryEducation) || normalized == string(SubscriptionCategoryLearnEnglish)
|
||||
}
|
||||
|
||||
// IsExamPrepSubscriptionCategory reports plan categories that unlock exam-prep content.
|
||||
|
|
@ -68,7 +77,7 @@ func SubscriptionGrantsContentAccess(subscriptionCategory, contentCategory strin
|
|||
sub := normalizeSubscriptionCategory(subscriptionCategory)
|
||||
content := normalizeSubscriptionCategory(contentCategory)
|
||||
if IsLMSContentCategory(content) {
|
||||
return sub == string(SubscriptionCategoryLearnEnglish)
|
||||
return IsLMSSubscriptionCategory(sub)
|
||||
}
|
||||
if IsExamPrepContentCategory(content) {
|
||||
return sub == content
|
||||
|
|
@ -108,6 +117,7 @@ type SubscriptionPlan struct {
|
|||
Price float64
|
||||
Currency string
|
||||
IsLifetime bool
|
||||
IsFree bool
|
||||
IsActive bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt *time.Time
|
||||
|
|
@ -145,6 +155,7 @@ type CreateSubscriptionPlanInput struct {
|
|||
Price float64
|
||||
Currency string
|
||||
IsLifetime bool
|
||||
IsFree bool
|
||||
IsActive *bool
|
||||
}
|
||||
|
||||
|
|
@ -157,9 +168,24 @@ type UpdateSubscriptionPlanInput struct {
|
|||
Price *float64
|
||||
Currency *string
|
||||
IsLifetime *bool
|
||||
IsFree *bool
|
||||
IsActive *bool
|
||||
}
|
||||
|
||||
// NormalizeSubscriptionPlanPricing enforces free vs paid pricing rules.
|
||||
func NormalizeSubscriptionPlanPricing(isFree bool, price float64) (bool, float64, error) {
|
||||
if isFree {
|
||||
if price > 0 {
|
||||
return false, 0, ErrFreePlanMustHaveZeroPrice
|
||||
}
|
||||
return true, 0, nil
|
||||
}
|
||||
if price <= 0 {
|
||||
return false, 0, ErrPaidPlanMustHavePositivePrice
|
||||
}
|
||||
return false, price, nil
|
||||
}
|
||||
|
||||
type CreateUserSubscriptionInput struct {
|
||||
UserID int64
|
||||
PlanID int64
|
||||
|
|
@ -215,7 +241,72 @@ func NormalizeLifetimePlanCreateDuration(isLifetime bool, durationValue int32, d
|
|||
if isLifetime {
|
||||
return LifetimeDurationValue, LifetimeDurationUnit
|
||||
}
|
||||
return durationValue, durationUnit
|
||||
return durationValue, strings.ToUpper(strings.TrimSpace(durationUnit))
|
||||
}
|
||||
|
||||
// SubscriptionPlanPeriod identifies a plan's category and billing period (price-independent).
|
||||
type SubscriptionPlanPeriod struct {
|
||||
Category string
|
||||
IsLifetime bool
|
||||
DurationValue int32
|
||||
DurationUnit string
|
||||
}
|
||||
|
||||
func SubscriptionPlanPeriodFromCreate(input CreateSubscriptionPlanInput) SubscriptionPlanPeriod {
|
||||
return subscriptionPlanPeriod(
|
||||
input.Category,
|
||||
input.IsLifetime,
|
||||
input.DurationValue,
|
||||
input.DurationUnit,
|
||||
)
|
||||
}
|
||||
|
||||
func SubscriptionPlanPeriodFromPlan(plan SubscriptionPlan) SubscriptionPlanPeriod {
|
||||
return subscriptionPlanPeriod(
|
||||
plan.Category,
|
||||
plan.IsLifetime,
|
||||
plan.DurationValue,
|
||||
plan.DurationUnit,
|
||||
)
|
||||
}
|
||||
|
||||
func SubscriptionPlanPeriodFromUpdate(existing SubscriptionPlan, input UpdateSubscriptionPlanInput) SubscriptionPlanPeriod {
|
||||
category := existing.Category
|
||||
if input.Category != nil {
|
||||
category = *input.Category
|
||||
}
|
||||
isLifetime := existing.IsLifetime
|
||||
if input.IsLifetime != nil {
|
||||
isLifetime = *input.IsLifetime
|
||||
}
|
||||
durationValue := existing.DurationValue
|
||||
if input.DurationValue != nil {
|
||||
durationValue = *input.DurationValue
|
||||
}
|
||||
durationUnit := existing.DurationUnit
|
||||
if input.DurationUnit != nil {
|
||||
durationUnit = *input.DurationUnit
|
||||
}
|
||||
return subscriptionPlanPeriod(category, isLifetime, durationValue, durationUnit)
|
||||
}
|
||||
|
||||
func subscriptionPlanPeriod(category string, isLifetime bool, durationValue int32, durationUnit string) SubscriptionPlanPeriod {
|
||||
dv, du := NormalizeLifetimePlanCreateDuration(isLifetime, durationValue, durationUnit)
|
||||
return SubscriptionPlanPeriod{
|
||||
Category: normalizeSubscriptionCategory(category),
|
||||
IsLifetime: isLifetime,
|
||||
DurationValue: dv,
|
||||
DurationUnit: du,
|
||||
}
|
||||
}
|
||||
|
||||
// SameSubscriptionPlanPeriod reports whether two plans share category and billing period
|
||||
// (is_free and price are ignored — free and paid plans cannot coexist for the same period).
|
||||
func SameSubscriptionPlanPeriod(a, b SubscriptionPlanPeriod) bool {
|
||||
return a.Category == b.Category &&
|
||||
a.IsLifetime == b.IsLifetime &&
|
||||
a.DurationValue == b.DurationValue &&
|
||||
a.DurationUnit == b.DurationUnit
|
||||
}
|
||||
|
||||
// CalculateSubscriptionExpiresAt returns when a subscription ends.
|
||||
|
|
|
|||
|
|
@ -40,6 +40,66 @@ func TestNormalizeLifetimePlanCreateDuration(t *testing.T) {
|
|||
if v != 3 || u != "MONTH" {
|
||||
t.Fatalf("got %d %s", v, u)
|
||||
}
|
||||
v, u = NormalizeLifetimePlanCreateDuration(false, 3, "month")
|
||||
if v != 3 || u != "MONTH" {
|
||||
t.Fatalf("expected trimmed uppercase unit, got %d %s", v, u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeSubscriptionPlanPricing(t *testing.T) {
|
||||
_, price, err := NormalizeSubscriptionPlanPricing(true, 10)
|
||||
if err != ErrFreePlanMustHaveZeroPrice || price != 0 {
|
||||
t.Fatalf("expected free plan price error, got price=%v err=%v", price, err)
|
||||
}
|
||||
isFree, price, err := NormalizeSubscriptionPlanPricing(true, 0)
|
||||
if err != nil || !isFree || price != 0 {
|
||||
t.Fatalf("expected free zero price, got isFree=%v price=%v err=%v", isFree, price, err)
|
||||
}
|
||||
_, _, err = NormalizeSubscriptionPlanPricing(false, 0)
|
||||
if err != ErrPaidPlanMustHavePositivePrice {
|
||||
t.Fatalf("expected paid plan error, got %v", err)
|
||||
}
|
||||
isFree, price, err = NormalizeSubscriptionPlanPricing(false, 99)
|
||||
if err != nil || isFree || price != 99 {
|
||||
t.Fatalf("expected paid plan 99, got isFree=%v price=%v err=%v", isFree, price, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameSubscriptionPlanPeriod_ignoresFreeVsPaid(t *testing.T) {
|
||||
free := SubscriptionPlanPeriodFromCreate(CreateSubscriptionPlanInput{
|
||||
Category: "LEARN_ENGLISH", IsLifetime: false, DurationValue: 1, DurationUnit: "MONTH", IsFree: true,
|
||||
})
|
||||
paid := SubscriptionPlanPeriodFromCreate(CreateSubscriptionPlanInput{
|
||||
Category: "LEARN_ENGLISH", IsLifetime: false, DurationValue: 1, DurationUnit: "MONTH", IsFree: false, Price: 99,
|
||||
})
|
||||
if !SameSubscriptionPlanPeriod(free, paid) {
|
||||
t.Fatal("free and paid plans with same category and period must conflict")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscriptionPlanPeriodFromCreate(t *testing.T) {
|
||||
lifetime := SubscriptionPlanPeriodFromCreate(CreateSubscriptionPlanInput{
|
||||
Category: "learn_english",
|
||||
IsLifetime: true,
|
||||
DurationValue: 6,
|
||||
DurationUnit: "MONTH",
|
||||
})
|
||||
if lifetime.Category != "LEARN_ENGLISH" || !lifetime.IsLifetime {
|
||||
t.Fatalf("unexpected lifetime period: %+v", lifetime)
|
||||
}
|
||||
if lifetime.DurationValue != LifetimeDurationValue || lifetime.DurationUnit != LifetimeDurationUnit {
|
||||
t.Fatalf("lifetime duration not normalized: %+v", lifetime)
|
||||
}
|
||||
|
||||
monthly := SubscriptionPlanPeriodFromCreate(CreateSubscriptionPlanInput{
|
||||
Category: "IELTS",
|
||||
IsLifetime: false,
|
||||
DurationValue: 1,
|
||||
DurationUnit: "MONTH",
|
||||
})
|
||||
if monthly.Category != "IELTS" || monthly.IsLifetime || monthly.DurationValue != 1 || monthly.DurationUnit != "MONTH" {
|
||||
t.Fatalf("unexpected monthly period: %+v", monthly)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscriptionGrantsContentAccess(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package domain
|
|||
|
||||
import "time"
|
||||
|
||||
// AppTimezoneName is the default business timezone for Yimaru (East Africa Time).
|
||||
// AppTimezoneName is the default business timezone for Rezina (East Africa Time).
|
||||
const AppTimezoneName = "Africa/Addis_Ababa"
|
||||
|
||||
// AppTimezone returns Africa/Addis_Ababa (EAT, UTC+3). Used as the default for
|
||||
|
|
|
|||
|
|
@ -76,14 +76,13 @@ type User struct {
|
|||
Region string
|
||||
|
||||
// Profile fields
|
||||
KnowledgeLevel string
|
||||
InitialAssessmentCompleted bool
|
||||
NickName string
|
||||
Occupation string
|
||||
LearningGoal string
|
||||
LanguageGoal string
|
||||
LanguageChallange string
|
||||
FavouriteTopic string
|
||||
KnowledgeLevel string
|
||||
NickName string
|
||||
Occupation string
|
||||
LearningGoal string
|
||||
LanguageGoal string
|
||||
LanguageChallange string
|
||||
FavouriteTopic string
|
||||
|
||||
EmailVerified bool
|
||||
PhoneVerified bool
|
||||
|
|
@ -116,13 +115,12 @@ type UserProfileResponse struct {
|
|||
Region string `json:"region,omitempty"`
|
||||
|
||||
// Profile fields
|
||||
InitialAssessmentCompleted bool `json:"initial_assessment_completed,omitempty"`
|
||||
NickName string `json:"nick_name,omitempty"`
|
||||
Occupation string `json:"occupation,omitempty"`
|
||||
LearningGoal string `json:"learning_goal,omitempty"`
|
||||
LanguageGoal string `json:"language_goal,omitempty"`
|
||||
LanguageChallange string `json:"language_challange,omitempty"`
|
||||
FavouriteTopic string `json:"favoutite_topic,omitempty"`
|
||||
NickName string `json:"nick_name,omitempty"`
|
||||
Occupation string `json:"occupation,omitempty"`
|
||||
LearningGoal string `json:"learning_goal,omitempty"`
|
||||
LanguageGoal string `json:"language_goal,omitempty"`
|
||||
LanguageChallange string `json:"language_challange,omitempty"`
|
||||
FavouriteTopic string `json:"favoutite_topic,omitempty"`
|
||||
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
PhoneVerified bool `json:"phone_verified"`
|
||||
|
|
@ -183,15 +181,14 @@ type UserFilter struct {
|
|||
ExpiresWithinDays *int32
|
||||
|
||||
// Engagement / activity
|
||||
LastLoginBefore ValidTime
|
||||
LastLoginAfter ValidTime
|
||||
DaysSinceLastLoginMin *int32
|
||||
DaysSinceLastLoginMax *int32
|
||||
ProfileCompleted *bool
|
||||
InitialAssessmentCompleted *bool
|
||||
MinLessonsCompleted *int32
|
||||
MinModulesCompleted *int32
|
||||
MinProfileCompletionPct *int32
|
||||
LastLoginBefore ValidTime
|
||||
LastLoginAfter ValidTime
|
||||
DaysSinceLastLoginMin *int32
|
||||
DaysSinceLastLoginMax *int32
|
||||
ProfileCompleted *bool
|
||||
MinLessonsCompleted *int32
|
||||
MinModulesCompleted *int32
|
||||
MinProfileCompletionPct *int32
|
||||
|
||||
// Technical / deliverability (device table only; push permission, timezone, app version not stored)
|
||||
DevicePlatform string
|
||||
|
|
@ -318,8 +315,6 @@ type UpdateUserReq struct {
|
|||
LanguageChallange string `json:"language_challange"`
|
||||
FavouriteTopic string `json:"favourite_topic"`
|
||||
|
||||
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
|
||||
|
||||
ProfilePictureURL string `json:"profile_picture_url"`
|
||||
PreferredLanguage string `json:"preferred_language"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
package infrastructure
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"encoding/csv"
|
||||
"os"
|
||||
"strconv"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package mongoLogger
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/config"
|
||||
"Rezina-Backend/internal/config"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package mongoLogger
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/config"
|
||||
"Rezina-Backend/internal/config"
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +0,0 @@
|
|||
package ports
|
||||
|
||||
// InitialAssessmentStore is now a marker interface.
|
||||
// The initial assessment functionality uses the unified questions system.
|
||||
// Use QuestionStore.GetInitialAssessmentSet() to get the initial assessment question set.
|
||||
type InitialAssessmentStore interface{}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package ports
|
|||
import (
|
||||
"context"
|
||||
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
)
|
||||
|
||||
// LmsPersonaReader resolves catalog personas referenced by LMS / exam-prep practices.
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package ports
|
|||
import (
|
||||
"context"
|
||||
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
)
|
||||
|
||||
type NotificationStore interface {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
package ports
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Rezina-Backend/internal/domain"
|
||||
"context"
|
||||
)
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user