From 39c86600f23e5d1bcc4214b63d97c117bc14347f Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Mon, 2 Nov 2026 13:09:31 +0300 Subject: [PATCH] Adapt backend and demo curriculum for makeup artistry and clean up services --- .env.example | 151 ++++++++++++++++++ README.md | 10 +- cmd/demo-seed/main.go | 4 +- cmd/main.go | 4 +- .../000004_makeup_artistry_profiles.down.sql | 4 + .../000004_makeup_artistry_profiles.up.sql | 15 ++ .../000005_makeup_artistry_focus.down.sql | 2 + .../000005_makeup_artistry_focus.up.sql | 10 ++ docs/demo-and-public-catalog.md | 34 ++-- docs/environment-variables-guide.md | 7 + docs/makeup-artistry-backend.md | 70 ++++++++ internal/demoseed/curriculum.go | 96 +++++++++++ internal/demoseed/integration_test.go | 37 ++++- internal/demoseed/makeup_focus_options.sql | 9 ++ internal/demoseed/makeup_profile_options.sql | 15 ++ internal/demoseed/makeup_upgrade.go | 68 ++++++++ internal/demoseed/makeup_upgrade_test.go | 75 +++++++++ internal/demoseed/seed.go | 89 +++++------ internal/demoseed/seed_test.go | 73 +++++++++ internal/domain/exam_prep_catalog_course.go | 2 +- internal/domain/subscriptions.go | 1 + internal/pkgs/helpers/helpers.go | 36 +++-- internal/pkgs/helpers/helpers_test.go | 47 ++++++ internal/repository/store.go | 2 +- internal/repository/store_config_test.go | 20 +++ internal/services/authentication/service.go | 9 +- .../learnernotifications/subscription.go | 4 +- .../learnernotifications/subscription_test.go | 15 ++ internal/services/rbac/seeds.go | 66 ++++---- internal/services/team/password_reset.go | 5 +- internal/services/transaction/service.go | 141 +--------------- internal/services/user/common.go | 10 +- internal/web_server/handlers/admin_export.go | 22 +-- .../handlers/analytics_field_normalize.go | 23 +-- .../analytics_field_normalize_test.go | 24 ++- .../handlers/exam_prep_practice_handler.go | 4 +- .../handlers/practice_pagination_test.go | 39 +++++ internal/web_server/response/res.go | 42 +++-- internal/web_server/response/res_test.go | 53 ++++++ static/demo/course-cover.svg | 28 +++- 40 files changed, 1041 insertions(+), 325 deletions(-) create mode 100644 .env.example create mode 100644 db/migrations/000004_makeup_artistry_profiles.down.sql create mode 100644 db/migrations/000004_makeup_artistry_profiles.up.sql create mode 100644 db/migrations/000005_makeup_artistry_focus.down.sql create mode 100644 db/migrations/000005_makeup_artistry_focus.up.sql create mode 100644 docs/makeup-artistry-backend.md create mode 100644 internal/demoseed/curriculum.go create mode 100644 internal/demoseed/makeup_focus_options.sql create mode 100644 internal/demoseed/makeup_profile_options.sql create mode 100644 internal/demoseed/makeup_upgrade.go create mode 100644 internal/demoseed/makeup_upgrade_test.go create mode 100644 internal/pkgs/helpers/helpers_test.go create mode 100644 internal/repository/store_config_test.go create mode 100644 internal/web_server/handlers/practice_pagination_test.go create mode 100644 internal/web_server/response/res_test.go diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..702fc6d1 --- /dev/null +++ b/.env.example @@ -0,0 +1,151 @@ +# Complete backend example. Copy to .env and replace REPLACE_WITH_* values. +# Existing process environment variables override .env. Never commit real secrets. +# Host-run development using the repository Docker PostgreSQL and MongoDB ports. +# Inside Docker use service hostnames/ports instead: postgres:5432 and mongo:27017. + +# Core (required) +ENV=development +PORT=8080 +APP_VERSION=development +LOG_LEVEL=info +DB_URL=postgresql://root:secret@localhost:5592/gh?sslmode=disable +MONGODB_URL=mongodb://root:secret@localhost:27021/?authSource=admin +JWT_KEY=REPLACE_WITH_A_LONG_RANDOM_SIGNING_SECRET +ACCESS_EXPIRY=3600 +REFRESH_EXPIRY=604800 +REPORT_EXPORT_PATH=./exports + +# PostgreSQL connection pool +DB_MAX_CONNS=25 +DB_MIN_CONNS=5 +DB_MAX_CONN_LIFETIME_MINUTES=30 +DB_MAX_CONN_IDLE_MINUTES=5 +DB_HEALTH_CHECK_SECONDS=30 + +# SMS: API key required by startup validation, even when SMS is unused. +AFRO_SMS_API_KEY=REPLACE_WITH_AFROMESSAGE_TOKEN +AFRO_SMS_BASE_URL=https://api.afromessage.com +AFRO_SMS_SENDER_NAME=REPLACE_WITH_AUTHORIZED_SENDER +AFRO_SMS_IDENTIFIER_ID= +# Legacy loaded SMS fields +AFRO_SMS_HOST_URL=https://api.afromessage.com +AFRO_SMS_RECEIVER_PHONE_NUMBER= + +# Email: both required by startup validation. +RESEND_API_KEY=REPLACE_WITH_RESEND_API_KEY +RESEND_SENDER_EMAIL=REPLACE_WITH_AUTHORIZED_SENDER_EMAIL + +# Staff frontend links (admin dev server) +TEAM_INVITE_BASE_URL=http://localhost:5173/accept-invite +TEAM_PASSWORD_RESET_BASE_URL=http://localhost:5173/reset-password +TEAM_INVITE_EXPIRY_HOURS=168 +# Customer app URLs: replace with your customer app and checkout deployments. +LEARNER_APP_BASE_URL=https://learn.example.com +LEARNER_WEB_CHECKOUT_BASE_URL=https://checkout.example.com +# Loaded legacy setting; confirm your reset flow consumes it. +PASSWORD_RESET_BASE_URL=https://learn.example.com/reset-password + +# Google/Apple sign-in: leave blank when unused. +GOOGLE_OAUTH_CLIENT_ID= +GOOGLE_OAUTH_WEB_CLIENT_ID= +GOOGLE_OAUTH_CLIENT_SECRET= +GOOGLE_OAUTH_REDIRECT_URL=http://localhost:8080/api/v1/auth/google/callback +APPLE_SIGN_IN_CLIENT_IDS= + +# Firebase: leave both blank to disable push delivery. +# Prefer a mounted credential file, e.g. ./secrets/firebase-service-account.json. +# A nonempty file path must exist; file contents override inline JSON. +FCM_SERVICE_ACCOUNT_KEY_FILE= +FCM_SERVICE_ACCOUNT_KEY= + +# Vimeo / CloudConvert: set credentials before enabling. +VIMEO_ENABLED=false +VIMEO_ACCESS_TOKEN= +CLOUDCONVERT_ENABLED=false +CLOUDCONVERT_API_KEY= + +# MinIO: API endpoint, not browser console; no http:// prefix. +MINIO_ENABLED=false +MINIO_ENDPOINT=localhost:9000 +MINIO_ROOT_USER=REPLACE_WITH_STORAGE_ACCESS_ID +MINIO_ROOT_PASSWORD=REPLACE_WITH_STORAGE_SECRET +MINIO_BUCKET_NAME=rezina +MINIO_USE_SSL=false +# Optional legacy aliases (preferred names above take precedence). +MINIO_ACCESS_KEY= +MINIO_SECRET_KEY= +MINIO_BUCKET= + +# Chapa: optional until payment features are used. +# Provider callbacks require a publicly reachable backend URL. +CHAPA_SECRET_KEY= +CHAPA_WEBHOOK_SECRET= +CHAPA_PUBLIC_KEY= +CHAPA_ENCRYPTION_KEY= +CHAPA_BASE_URL=https://api.chapa.co/v1 +CHAPA_CALLBACK_URL=https://api.example.com/api/v1/payments/chapa/callback +CHAPA_RETURN_URL=https://checkout.example.com/payment-result +CHAPA_RECEIPT_URL= +CHAPA_TRANSFER_TYPE= +CHAPA_PAYMENT_TYPE= + +# ArifPay: populate according to your merchant integration when used. +ARIFPAY_API_KEY= +ARIFPAY_BASE_URL= +ARIFPAY_CANCEL_URL=https://checkout.example.com/payment-cancelled +ARIFPAY_ERROR_URL=https://checkout.example.com/payment-error +ARIFPAY_SUCCESS_URL=https://checkout.example.com/payment-success +ARIFPAY_C2B_NOTIFY_URL= +ARIFPAY_B2C_NOTIFY_URL= +ARIFPAY_BANK= +ARIFPAY_BENEFICIARY_ACCOUNT_NUMBER= +ARIFPAY_DESCRIPTION=Rezina LMS subscription +ARIFPAY_ITEM_NAME=Learning subscription + +# Background workers (current application defaults) +ACCOUNT_DELETION_PURGE_ENABLED=true +ACCOUNT_DELETION_PURGE_INTERVAL=1h +ACCOUNT_DELETION_PURGE_BATCH_SIZE=100 +PAYMENT_EXPIRY_WORKER_ENABLED=true +PAYMENT_EXPIRY_WORKER_INTERVAL=15m +SUBSCRIPTION_EXPIRY_REMINDER_WORKER_ENABLED=true +SUBSCRIPTION_EXPIRY_REMINDER_WORKER_INTERVAL=24h +INACTIVE_SUBMODULE_CONTENT_PURGE_ENABLED=false +INACTIVE_SUBMODULE_CONTENT_PURGE_INTERVAL=24h +INACTIVE_SUBMODULE_CONTENT_RETENTION_DAYS=30 + +# Loaded legacy infrastructure: not initialized by the current entrypoint. +REDIS_ADDR= +KAFKA_BROKERS= +FIXER_API_KEY= +FIXER_BASE_URL= +BASE_CURRENCY= + +# Legacy providers: configuration alone does not activate these integrations. +SANTIMPAY_SECRET_KEY= +SANTIMPAY_MERCHANT_ID= +SANTIMPAY_BASE_URL= +SANTIMPAY_NOTIFY_URL= +SANTIMPAY_CANCEL_URL= +# Known loader issue: FABRIC_APP_ID overwrites APP_SECRET; fix before use. +TELEBIRR_BASE_URL= +TELEBIRR_APP_SECRET= +TELEBIRR_FABRIC_APP_ID= +TELEBIRR_MERCHANT_CODE= +TELEBIRR_CALLBACK_URL= + +# Optional demo-seed command settings, never automatically seeded on startup. +# Run: go run ./cmd/demo-seed -environment development +# Leave password empty for the documented demo default RezinaDemo!2026. +DEMO_SEED_PASSWORD= +# Leave blank for the seeder's sample video. +DEMO_VIDEO_URL= +# Production safeguards checked by demo-seed (not the backend ENV setting). +APP_ENV=development +ENVIRONMENT=development +GO_ENV=development +# Opt-in destructive-to-fixtures test target: disposable migrated database only. +DEMO_TEST_DB_URL= + +# CORS currently lives in internal/web_server/app.go, allowing all origins (*). +# No CORS environment variable is supported by the current backend. diff --git a/README.md b/README.md index 62f4ac72..90370eeb 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Rezina Backend API -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. +Golang API for **Rezina**, a makeup artistry teaching LMS. It serves the learner apps and the [Rezina Admin](https://gitea.yaltopia.com/Rezina/Rezina-Admin) panel: authentication, makeup courses and chapters, video lessons and quizzes, subscriptions and payments, team RBAC, analytics, notifications, and more. | | | |---|---| @@ -126,7 +126,7 @@ make db-up # Postgres + migrate + Mongo (detached) # 3. Demo seed (optional, non-production only, after all migrations) go run ./cmd/demo-seed -environment development -# See docs/demo-and-public-catalog.md for role credentials and fixture details. +# Makeup artistry demo: see docs/demo-and-public-catalog.md for credentials and details. # 4. Run API with live reload make air @@ -260,12 +260,12 @@ Entry point: `cmd/main.go` (wires config, stores, services, Fiber, cron). | Target | Source | |--------|--------| -| `make seed_demo` | Current course/chapter/lesson demo, chapter quizzes, and role test accounts (`cmd/demo-seed`) | +| `make seed_demo` | Makeup artistry courses, chapters, lessons, quizzes, and role test accounts (`cmd/demo-seed`) | | `make seed_data` | `db/data/*.sql` | | `make seed_dev_data` | `db/dev_data/*.sql` (+ sequence fix script) | -Use `seed_demo` for the current hierarchy. The older SQL seed collections target -historical schemas. [Public catalog and demo setup](docs/demo-and-public-catalog.md) +Use `seed_demo` for the current makeup artistry hierarchy. The older SQL seed collections target +historical schemas. [Makeup backend model](docs/makeup-artistry-backend.md) and [public catalog and demo setup](docs/demo-and-public-catalog.md) documents anonymous browsing, test credentials, and database setup. ### Backup / restore diff --git a/cmd/demo-seed/main.go b/cmd/demo-seed/main.go index ac7cbf74..055e8d56 100644 --- a/cmd/demo-seed/main.go +++ b/cmd/demo-seed/main.go @@ -16,7 +16,7 @@ func main() { environment := flag.String("environment", "", "Required: development, test, or staging") flag.Parse() _ = godotenv.Load() - if err := demoseed.ValidateEnvironment(*environment, os.Getenv("APP_ENV"), os.Getenv("ENVIRONMENT"), os.Getenv("GO_ENV")); err != nil { + if err := demoseed.ValidateEnvironment(*environment, os.Getenv("APP_ENV"), os.Getenv("ENVIRONMENT"), os.Getenv("GO_ENV"), os.Getenv("ENV")); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } @@ -45,7 +45,7 @@ func main() { fmt.Fprintln(os.Stderr, "Demo seed failed:", err) os.Exit(1) } - fmt.Println("Demo seed complete: 3 published courses, 6 chapters, 18 lessons, 6 quizzes, 18 questions, and 1 hidden draft course.") + fmt.Println("Makeup artistry demo seed complete: 3 published courses, 6 chapters, 18 lessons, 6 quizzes, 18 questions, and 1 hidden draft course.") fmt.Println("Test accounts (password: DEMO_SEED_PASSWORD, or RezinaDemo!2026 when unset):") for _, a := range demoseed.Accounts { fmt.Printf(" %-36s %-16s %s\n", a.Email, a.Role, a.Audience) diff --git a/cmd/main.go b/cmd/main.go index bcb22bee..36fd4e9e 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -120,7 +120,7 @@ func main() { authSvc := authentication.NewService( repository.NewOTPStore(store), repository.NewUserStore(store), - *userSvc, + userSvc, repository.NewTokenStore(store), cfg.RefreshExpiry, ) @@ -165,7 +165,7 @@ func main() { // ) transactionSvc := transaction.NewService( repository.NewTransactionStore(store), - *userSvc, + userSvc, ) // reportSvc := report.NewService( diff --git a/db/migrations/000004_makeup_artistry_profiles.down.sql b/db/migrations/000004_makeup_artistry_profiles.down.sql new file mode 100644 index 00000000..9b233f41 --- /dev/null +++ b/db/migrations/000004_makeup_artistry_profiles.down.sql @@ -0,0 +1,4 @@ +-- Additive reference data is intentionally retained on rollback: removing these +-- codes could invalidate saved learner profiles or remove administrator edits. +-- No schema changes were introduced by this migration. +SELECT 1; diff --git a/db/migrations/000004_makeup_artistry_profiles.up.sql b/db/migrations/000004_makeup_artistry_profiles.up.sql new file mode 100644 index 00000000..1c4a28aa --- /dev/null +++ b/db/migrations/000004_makeup_artistry_profiles.up.sql @@ -0,0 +1,15 @@ +-- Add makeup-artistry choices without rewriting historical profile codes or custom options. +INSERT INTO field_options(field_key,code,label,display_order,status) VALUES + ('occupation','BEAUTY_STUDENT','Beauty and makeup student',1,'ACTIVE'), + ('occupation','MAKEUP_ARTIST','Makeup artist',2,'ACTIVE'), + ('occupation','BEAUTY_EDUCATOR','Makeup educator',3,'ACTIVE'), + ('occupation','SALON_PROFESSIONAL','Salon or studio professional',4,'ACTIVE'), + ('learning_goal','PERSONAL_MAKEUP','Develop personal makeup skills',1,'ACTIVE'), + ('learning_goal','PRO_MAKEUP_ARTIST','Become a professional makeup artist',2,'ACTIVE'), + ('learning_goal','BRIDAL_SPECIALIST','Specialize in bridal and occasion makeup',3,'ACTIVE'), + ('learning_goal','EDITORIAL_PORTFOLIO','Build an editorial makeup portfolio',4,'ACTIVE'), + ('favourite_topic','COMPLEXION_TECHNIQUES','Complexion and foundation techniques',1,'ACTIVE'), + ('favourite_topic','EYE_MAKEUP','Eye makeup and brow design',2,'ACTIVE'), + ('favourite_topic','BRIDAL_MAKEUP','Bridal and occasion looks',3,'ACTIVE'), + ('favourite_topic','EDITORIAL_MAKEUP','Creative and editorial artistry',4,'ACTIVE') +ON CONFLICT(field_key,code) DO NOTHING; diff --git a/db/migrations/000005_makeup_artistry_focus.down.sql b/db/migrations/000005_makeup_artistry_focus.down.sql new file mode 100644 index 00000000..f183a6de --- /dev/null +++ b/db/migrations/000005_makeup_artistry_focus.down.sql @@ -0,0 +1,2 @@ +-- Retain reference codes used by saved learner profiles. +SELECT 1; diff --git a/db/migrations/000005_makeup_artistry_focus.up.sql b/db/migrations/000005_makeup_artistry_focus.up.sql new file mode 100644 index 00000000..1b6ca837 --- /dev/null +++ b/db/migrations/000005_makeup_artistry_focus.up.sql @@ -0,0 +1,10 @@ +-- Legacy column names are retained for API compatibility. +INSERT INTO field_options(field_key,code,label,display_order,status) VALUES + ('language_challange','COLOR_MATCHING','Foundation and color matching',1,'ACTIVE'), + ('language_challange','BLENDING','Blending and application',2,'ACTIVE'), + ('language_challange','EYE_SYMMETRY','Eye makeup and symmetry',3,'ACTIVE'), + ('language_challange','CLIENT_CONFIDENCE','Working confidently with clients',4,'ACTIVE'), + ('language_goal','MAKEUP_FOUNDATIONS','Master makeup foundations',1,'ACTIVE'), + ('language_goal','PROFESSIONAL_ARTISTRY','Develop professional artistry',2,'ACTIVE'), + ('language_goal','CREATIVE_ARTISTRY','Explore creative artistry',3,'ACTIVE') +ON CONFLICT(field_key,code) DO NOTHING; diff --git a/docs/demo-and-public-catalog.md b/docs/demo-and-public-catalog.md index 12f42fb7..6871cd0d 100644 --- a/docs/demo-and-public-catalog.md +++ b/docs/demo-and-public-catalog.md @@ -1,4 +1,4 @@ -# Public discovery and pre-production demo +# Makeup academy discovery and pre-production demo ## Browse without signing in @@ -47,7 +47,7 @@ to start learning; authenticated playback, quiz, and progress APIs enforce acces ## Install the demo fixture -Apply database migrations through `000003_chapters_and_quizzes`, then run from +Apply database migrations through `000005_makeup_artistry_focus`, then run from the backend directory: ```powershell @@ -57,7 +57,7 @@ go run ./cmd/demo-seed -environment development The command reads `DB_URL` from the environment or the backend `.env`. It needs only PostgreSQL; it does not start the application or require payment, email, SMS, or storage provider credentials. `-environment` must explicitly be -`development`, `test`, or `staging`. `APP_ENV`, `ENVIRONMENT`, or `GO_ENV` set to +`development`, `test`, or `staging`. `APP_ENV`, `ENVIRONMENT`, `GO_ENV`, or `ENV` set to `production`/`prod` prevents seeding. For the repository's Docker PostgreSQL: @@ -83,8 +83,9 @@ Optional settings: | `DEMO_VIDEO_URL` | Public Big Buck Bunny sample clip for testing playback; replace with your own media URL for realistic lesson videos | | `DEMO_TEST_DB_URL` | Disposable, fully migrated PostgreSQL database used only by the opt-in integration test | -The supplied videos are playback fixtures, not instructional recordings for the -lesson subjects. A local SVG course cover is included in the backend image. +The supplied videos are playback fixtures, not makeup instructional recordings. +Use `DEMO_VIDEO_URL` or the lesson editor to attach your own licensed teaching +media. A black makeup artistry SVG course cover is included in the backend image. ## Demo accounts @@ -96,7 +97,7 @@ All accounts use **`RezinaDemo!2026`** unless `DEMO_SEED_PASSWORD` is set. | `admin@demo.rezina.test` | `ADMIN` | `POST /api/v1/admin/team/login` | Administrative permissions under existing role rules | | `contentmanager@demo.rezina.test` | `CONTENT_MANAGER` | `POST /api/v1/admin/team/login` | Content management permissions and restricted admin navigation | | `student@demo.rezina.test` | `STUDENT` | `POST /api/v1/auth/customer-login` | Unsubscribed learner; verifies premium restrictions | -| `premium@demo.rezina.test` | `STUDENT` | `POST /api/v1/auth/customer-login` | 30-day Education subscription, refreshed on seed rerun | +| `premium@demo.rezina.test` | `STUDENT` | `POST /api/v1/auth/customer-login` | 30-day makeup academy subscription (`EDUCATION`), refreshed on seed rerun | | `openlearner@demo.rezina.test` | `OPEN_LEARNER` | `POST /api/v1/auth/customer-login` | Existing unrestricted learner access rules | Both login endpoints accept `{"email":"...","password":"..."}`. Staff sign in @@ -114,22 +115,33 @@ restart a running backend after seeding so its permission cache reloads. ## Included learning data and reruns -- Everyday English: 2 chapters, 6 lessons, 2 quizzes; free course. -- Workplace Communication: 2 chapters, 6 lessons, 2 quizzes; premium course. -- Digital Skills Essentials: 2 chapters, 6 lessons, 2 quizzes; free course. -- Each quiz contains 3 published multiple-choice questions with correct answers. +- Makeup Artistry Foundations: 2 chapters, 6 lessons, 2 quizzes; free course. +- Bridal and Occasion Makeup: 2 chapters, 6 lessons, 2 quizzes; premium course. +- Creative and Editorial Makeup: 2 chapters, 6 lessons, 2 quizzes; free course. +- Each quiz contains 3 subject-specific multiple-choice questions, explanations, and varied correct-answer positions. - One unpublished course verifies that public discovery hides drafts. - One inactive demo subscription plan provides the premium test account access without appearing as a purchasable production plan. The fixture runs in one transaction under an advisory lock. It uses generated IDs and the `demo_seed_entities` ownership map rather than fixed IDs or table -truncation. Reruns reuse existing content, preserve edits to it, reset the six +truncation. Makeup fixtures have their own `makeup-*` keys. Reruns reuse existing +makeup content, preserve edits to it, reset the six demo account passwords/statuses to the configured test credentials, and refresh the seed-owned premium subscription. Existing unrelated accounts and learning content are not deleted. Keep these fixtures in a separate pre-production database; this command is not part of production migration or startup. +When upgrading the old general-learning demo, untouched seed-owned Everyday +English, Workplace Communication, and Digital Skills courses are changed to +drafts. Their records and progress are retained. Courses with recorded edits +or additions (including changed descendants) stay as authored. The original +inactive demo plan is relabeled as `[Demo] Makeup Academy Pass` only when its +name and description still match the original defaults; its ID and subscription +links are retained. The new course keys prevent old quiz attempts from being +reinterpreted as attempts on different subject matter. Demo learners receive +makeup profile defaults only for empty fields. + ## Verification ```powershell diff --git a/docs/environment-variables-guide.md b/docs/environment-variables-guide.md index ca2241d2..b8b53996 100644 --- a/docs/environment-variables-guide.md +++ b/docs/environment-variables-guide.md @@ -251,6 +251,13 @@ Pool settings fall back to defaults for missing, nonnumeric, or nonpositive valu For worker switches, empty values use the defaults above; explicit `true` or `1` enables them, and other nonempty values disable them. Intervals use Go duration syntax such as `30m`, `1h`, or `24h`; invalid or nonpositive durations fall back to defaults. Invalid batch sizes and retention periods also fall back to defaults. +## Complete configuration example + +See [`.env.example`](../.env.example) for all currently loaded settings, optional +integrations, legacy configuration, and demo-seed settings. It uses the repository +Docker database ports for a backend running on the host. Replace credential +placeholders before starting the app. Your existing `.env` is not overwritten. + ## Minimal configuration example This example covers startup configuration and the currently used SMS fields. Replace placeholders, prepare the PostgreSQL schema, and provide reachable databases before starting the app. It does not enable payments, social login, storage, or push notifications. diff --git a/docs/makeup-artistry-backend.md b/docs/makeup-artistry-backend.md new file mode 100644 index 00000000..bcd61b1b --- /dev/null +++ b/docs/makeup-artistry-backend.md @@ -0,0 +1,70 @@ +# Makeup artistry backend + +The current product teaches makeup artistry through courses, chapters, video +lessons, and chapter quizzes. Course publication, free/premium tiers, sequential +progress, and staff access use the existing backend services. + +## Compatibility + +`EDUCATION` remains the canonical content/subscription category. New API clients +must continue sending that value, not a new `MAKEUP` enum. Customer subscription +notifications and email package labels now describe makeup artistry access. +Historical `LEARN_ENGLISH`, `IELTS`, and `DUOLINGO` records retain their labels. + +The `exam_prep` schema, Go type names, permission keys, and legacy routes remain +storage/API compatibility identifiers. Current public catalog DTOs expose courses, +chapters, lessons, and quizzes. Do not rename database schemas or bulk-change +existing subscription categories to update the product terminology. Permission +display labels now describe makeup courses; authorization keys and grants are +unchanged. Staff roles remain `SUPER_ADMIN`, `ADMIN`, and `CONTENT_MANAGER`; +makeup instructors can author through the existing Content Manager role. + +## Learner profiles + +Apply migration `000004_makeup_artistry_profiles` to add active options for: + +- Occupation: beauty student, makeup artist, makeup educator, salon professional. +- Learning goal: personal makeup, professional artistry, bridal specialization, + and editorial portfolio development. +- Favourite topic: complexion, eye makeup, bridal looks, and editorial artistry. + +These use the existing `occupation`, `learning_goal`, and `favourite_topic` +fields and option APIs. Existing language preference remains a localization +preference, not a course subject. Historical language goal/challenge fields and +custom profile choices are retained for API and stored-profile compatibility. +The migration inserts missing codes only and does not overwrite administrator +edits. Its down migration intentionally retains reference choices so saved +profiles remain valid. + +## Demo curriculum + +Run `go run ./cmd/demo-seed -environment development` after starting PostgreSQL +and applying migrations. The seeder adds three makeup courses, six chapters, +eighteen lessons, six chapter quizzes, and eighteen distinct MCQs with answer +explanations. The bridal course is premium; foundations and editorial are free. +A special-effects draft verifies publication filtering. Questions cover kit +selection, brush control, workstation setup, complexion, client consultation, +bridal finishing, color, and portfolio practice. + +The inactive `[Demo] Makeup Academy Pass` supports the premium test learner. +It is not a publicly purchasable plan. Demo account emails/password settings +remain unchanged. The fixture never runs automatically on backend startup and +refuses production environment settings, including `ENV=production`. + +See [demo setup and compatibility](demo-and-public-catalog.md) for credentials, +media fixtures, upgrade behavior, and opt-in database integration tests. The old +`db/data` and `db/dev_data` collections target historical schemas; use the current +Go demo seeder for this curriculum. Replace sample playback clips with your own +teaching recordings before using demo lessons as instructional material. + +## Admin profile and analytics alignment + +Apply migration `000005_makeup_artistry_focus` for artistry focus and challenge choices. +The existing `language_goal` and `language_challange` JSON/storage keys remain for compatibility; +the admin presents them as Artistry focus and Artistry challenge. New options cover makeup +foundations, professional/creative artistry, color matching, blending, symmetry, and client confidence. +Missing profile values appear as Not provided rather than invented language-learning preferences. +Custom and historical values are preserved in analytics; historical courses remain accessible. +New subscription plans use EDUCATION, displayed as Makeup Artistry. Historical subscription categories +remain available in reports, while plan creation offers only the supported makeup category. +The embedded demo seed adds the new choices and fills only empty demo profile fields. diff --git a/internal/demoseed/curriculum.go b/internal/demoseed/curriculum.go new file mode 100644 index 00000000..f89c667b --- /dev/null +++ b/internal/demoseed/curriculum.go @@ -0,0 +1,96 @@ +package demoseed + +import ( + "fmt" + "strings" +) + +type Course struct { + Key, Name, Description, Tier string + Chapters []Chapter +} +type Chapter struct { + Name, Description string + Lessons []Lesson +} +type Lesson struct { + Title, Description, Question, Explanation string + Options []string + CorrectIndex int +} + +// Courses is the current makeup-artistry fixture. Keys are namespaced separately +// from the retired general-learning demo so existing learner progress is retained. +var Courses = []Course{ + {Key: "makeup-foundations", Name: "Makeup Artistry Foundations", Description: "Build a professional toolkit, prepare a clean workstation, and create a balanced everyday complexion.", Tier: "FREE", Chapters: []Chapter{ + {Name: "Your kit and studio", Description: "Get to know core tools and organize a thoughtful makeup practice routine.", Lessons: []Lesson{ + {Title: "Build your first makeup kit", Description: "Identify complexion, eye, and lip essentials. Organize products by purpose and create a kit checklist for a simple everyday look.", Question: "Which kit is the best starting point for practicing a complete everyday look?", Options: []string{"Only several shades of glitter", "Complexion products, eye and lip basics, and suitable brushes", "Only one foundation and no tools"}, CorrectIndex: 1, Explanation: "A balanced starter kit covers the main areas of the face and includes tools for controlled application."}, + {Title: "Choose and control your brushes", Description: "Compare dense and fluffy brushes. Practice light pressure and use separate tools to place, blend, and refine product.", Question: "Which brush is best suited to softly blending the edges of powder eyeshadow?", Options: []string{"A fluffy blending brush", "A rigid spatula", "A large body brush"}, CorrectIndex: 0, Explanation: "A fluffy blending brush helps diffuse powder edges using light pressure."}, + {Title: "Set up a clean workstation", Description: "Separate clean tools from used tools. Practice dispensing products onto a palette and using disposable applicators without returning them to the product.", Question: "After using a disposable lip applicator on a client, what should you do?", Options: []string{"Return it to the shared lip product", "Save it for the next client", "Discard it and use a fresh applicator when more product is needed"}, CorrectIndex: 2, Explanation: "A used disposable applicator should not be returned to a shared product or reused on another person."}, + }}, + {Name: "Complexion essentials", Description: "Explore shade matching, controlled coverage, and a natural-looking finish.", Lessons: []Lesson{ + {Title: "Match foundation and undertone", Description: "Compare foundation swatches near the jawline in even light. Observe how each shade relates to both face and neck before choosing a match.", Question: "What is the most useful way to compare foundation shades for a face-and-neck match?", Options: []string{"Choose the lightest shade in the range", "Compare jawline swatches in even light", "Choose from the color of the bottle alone"}, CorrectIndex: 1, Explanation: "Jawline swatches help compare the foundation with the surrounding face and neck."}, + {Title: "Build a thin, even base", Description: "Apply a small amount of foundation first. Blend the edges and add coverage only where the look calls for it.", Question: "How can you build coverage while retaining control of the finish?", Options: []string{"Apply several thick coats at once", "Leave product edges unblended", "Apply thin layers and assess each layer"}, CorrectIndex: 2, Explanation: "Thin layers make it easier to assess coverage, texture, and blending before adding more."}, + {Title: "Balance blush and powder", Description: "Practice placing blush with a light hand. Apply powder selectively and review the finished look in consistent lighting.", Question: "How should you approach blush when learning placement and intensity?", Options: []string{"Start lightly and build the color gradually", "Apply the maximum amount immediately", "Avoid checking the result in a mirror"}, CorrectIndex: 0, Explanation: "Gradual application gives you control of intensity and allows you to adjust placement."}, + }}, + }}, + {Key: "makeup-bridal", Name: "Bridal and Occasion Makeup", Description: "Plan a client-focused bridal look with refined eyes, balanced lips, and a repeatable finishing routine.", Tier: "PREMIUM", Chapters: []Chapter{ + {Name: "Design the bridal look", Description: "Translate a consultation into a cohesive look and practice polished eye techniques.", Lessons: []Lesson{ + {Title: "Run a bridal consultation", Description: "Discuss the client's preferred finish, reference images, event schedule, and styling. Record the agreed look and the products used during the trial.", Question: "What is the purpose of a bridal makeup trial record?", Options: []string{"To replace the client's preferences with a fixed look", "To record agreed choices and help reproduce the look", "To avoid discussing the event"}, CorrectIndex: 1, Explanation: "A trial record helps the artist and client agree on the design and reproduce it consistently."}, + {Title: "Create a soft neutral eye", Description: "Place transition, depth, and lid shades deliberately. Blend the borders and compare the balance of both eyes as you work.", Question: "What should you check while developing a balanced eye look?", Options: []string{"Only the brush handle color", "Only one eye until the entire look is finished", "Both eyes in consistent lighting"}, CorrectIndex: 2, Explanation: "Checking both eyes during application makes it easier to notice and refine differences."}, + {Title: "Refine brows and liner", Description: "Practice short, controlled strokes for brows and liner. Step back to compare shape and definition with the rest of the look.", Question: "Which approach provides control when refining a brow?", Options: []string{"Use short strokes and review the shape often", "Fill the entire area with one heavy stroke", "Choose the darkest possible product for every client"}, CorrectIndex: 0, Explanation: "Short strokes allow the artist to build definition gradually and reassess the shape."}, + }}, + {Name: "Finish and document", Description: "Balance the final details and prepare a clear record for an occasion look.", Lessons: []Lesson{ + {Title: "Shape a balanced lip", Description: "Outline a lip shape with controlled placement. Add color in thin layers and refine the edges with a clean detail brush.", Question: "Which tool can help refine an uneven lip-color edge?", Options: []string{"A used mascara wand", "A clean detail brush", "A large powder puff"}, CorrectIndex: 1, Explanation: "A clean detail brush gives controlled access to the edge of the lip color."}, + {Title: "Check the look on camera", Description: "Photograph the finished look in even light. Compare the image with the mirror view and note any visible color or blending differences.", Question: "Why review both a photograph and the mirror view of an occasion look?", Options: []string{"To guarantee identical results under every light", "To avoid asking the client for feedback", "To evaluate how the look reads in each view"}, CorrectIndex: 2, Explanation: "Comparing views helps identify details that may read differently on camera."}, + {Title: "Plan a touch-up kit", Description: "Choose touch-up items that match the products and finish of the agreed look. Label the kit and record concise application notes for the client.", Question: "What makes a useful touch-up kit for a bridal look?", Options: []string{"Items selected for the agreed look with clear application notes", "A random set of unrelated colors", "Unlabeled products without instructions"}, CorrectIndex: 0, Explanation: "A look-specific kit and clear notes make it easier to maintain the agreed finish."}, + }}, + }}, + {Key: "makeup-editorial", Name: "Creative and Editorial Makeup", Description: "Develop a visual concept, explore color and texture, and document a cohesive makeup portfolio.", Tier: "FREE", Chapters: []Chapter{ + {Name: "Color and concept", Description: "Build a mood board and use color relationships to plan an intentional design.", Lessons: []Lesson{ + {Title: "Build an editorial mood board", Description: "Collect references for color, shape, texture, and styling. Choose a clear focal point and sketch a face chart before application.", Question: "What should a useful makeup mood board communicate?", Options: []string{"Only the price of the products", "A coherent direction for color, shape, and texture", "Unrelated images with no design direction"}, CorrectIndex: 1, Explanation: "A focused mood board gives the team a shared visual direction for the makeup design."}, + {Title: "Work with color relationships", Description: "Compare neighboring and complementary colors on a color wheel. Make swatches and choose a limited palette for a creative look.", Question: "Which pair is complementary on a traditional artist's color wheel?", Options: []string{"Blue and orange", "Blue and green", "Red and orange"}, CorrectIndex: 0, Explanation: "Blue and orange sit opposite each other on a traditional artist's color wheel."}, + {Title: "Create a statement eye", Description: "Sketch a graphic eye shape on a face chart. Practice placement with controlled strokes and refine the outline before adding more detail.", Question: "What is a useful first step when planning a graphic eye design?", Options: []string{"Add every available color immediately", "Ignore the intended shape", "Sketch the shape and choose a focal point"}, CorrectIndex: 2, Explanation: "Planning the shape and focal point gives the artist a clear structure for application."}, + }}, + {Name: "Portfolio practice", Description: "Coordinate textures, capture consistent images, and reflect on the finished work.", Lessons: []Lesson{ + {Title: "Combine matte and luminous textures", Description: "Swatch matte and luminous finishes side by side. Place them intentionally so the texture supports the chosen focal point.", Question: "Why swatch different finishes before applying an editorial look?", Options: []string{"To make all products look identical", "To compare how their textures support the design", "To replace a design plan with random choices"}, CorrectIndex: 1, Explanation: "Swatching makes differences in finish visible before committing them to the full look."}, + {Title: "Photograph your finished look", Description: "Use consistent lighting, framing, and a simple background. Capture front and detail views that accurately show your blending and color choices.", Question: "Which practice makes a makeup portfolio easier to compare across looks?", Options: []string{"Use consistent lighting and framing", "Change the lighting dramatically for every image", "Hide all close-up details"}, CorrectIndex: 0, Explanation: "Consistent presentation makes it easier to compare the makeup work itself."}, + {Title: "Review and improve your technique", Description: "Compare the finished look with your face chart and references. Record one successful technique and one specific adjustment for your next practice.", Question: "Which reflection is the most actionable after completing a practice look?", Options: []string{"There is nothing to review", "I should change everything without choosing a goal", "I will refine one specific blending edge in my next practice"}, CorrectIndex: 2, Explanation: "A specific observation creates a practical goal for the next attempt."}, + }}, + }}, +} + +// validateCurriculum catches incomplete fixtures before opening a transaction. +func validateCurriculum(courses []Course) error { + if len(courses) == 0 { + return fmt.Errorf("demo curriculum is empty") + } + keys := map[string]bool{} + questions := map[string]bool{} + for _, course := range courses { + if course.Key == "" || keys[course.Key] || strings.TrimSpace(course.Name) == "" || strings.TrimSpace(course.Description) == "" || (course.Tier != "FREE" && course.Tier != "PREMIUM") || len(course.Chapters) == 0 { + return fmt.Errorf("invalid demo course %q", course.Key) + } + keys[course.Key] = true + for _, chapter := range course.Chapters { + if strings.TrimSpace(chapter.Name) == "" || strings.TrimSpace(chapter.Description) == "" || len(chapter.Lessons) == 0 { + return fmt.Errorf("incomplete chapter in %s", course.Key) + } + for _, lesson := range chapter.Lessons { + if strings.TrimSpace(lesson.Title) == "" || strings.TrimSpace(lesson.Description) == "" || strings.TrimSpace(lesson.Question) == "" || strings.TrimSpace(lesson.Explanation) == "" || len(lesson.Options) < 2 || lesson.CorrectIndex < 0 || lesson.CorrectIndex >= len(lesson.Options) || questions[lesson.Question] { + return fmt.Errorf("invalid knowledge check in %s: %s", course.Key, lesson.Title) + } + questions[lesson.Question] = true + options := map[string]bool{} + for _, option := range lesson.Options { + text := strings.ToLower(strings.TrimSpace(option)) + if text == "" || options[text] { + return fmt.Errorf("empty or duplicate option for %s", lesson.Title) + } + options[text] = true + } + } + } + } + return nil +} diff --git a/internal/demoseed/integration_test.go b/internal/demoseed/integration_test.go index ffe94d85..33c8ef0f 100644 --- a/internal/demoseed/integration_test.go +++ b/internal/demoseed/integration_test.go @@ -32,7 +32,7 @@ func TestDemoSeedAndPublicCatalogIntegration(t *testing.T) { } } var courses, lessons, quizzes int - if err = conn.QueryRow(ctx, `SELECT COUNT(*) FILTER(WHERE kind='course'),COUNT(*) FILTER(WHERE kind='lesson'),COUNT(*) FILTER(WHERE kind='quiz') FROM demo_seed_entities`).Scan(&courses, &lessons, &quizzes); err != nil { + if err = conn.QueryRow(ctx, `SELECT COUNT(*) FILTER(WHERE kind='course'),COUNT(*) FILTER(WHERE kind='lesson'),COUNT(*) FILTER(WHERE kind='quiz') FROM demo_seed_entities WHERE seed_key LIKE 'makeup-%' OR seed_key='draft'`).Scan(&courses, &lessons, &quizzes); err != nil { t.Fatal(err) } if courses != 4 || lessons != 18 || quizzes != 6 { @@ -58,7 +58,7 @@ func TestDemoSeedAndPublicCatalogIntegration(t *testing.T) { defer pool.Close() store := repository.NewStore(pool) var id, draftID int64 - if err = conn.QueryRow(ctx, `SELECT entity_id FROM demo_seed_entities WHERE kind='course' AND seed_key='everyday-english'`).Scan(&id); err != nil { + if err = conn.QueryRow(ctx, `SELECT entity_id FROM demo_seed_entities WHERE kind='course' AND seed_key='makeup-foundations'`).Scan(&id); err != nil { t.Fatal(err) } if err = conn.QueryRow(ctx, `SELECT entity_id FROM demo_seed_entities WHERE kind='course' AND seed_key='draft'`).Scan(&draftID); err != nil { @@ -84,6 +84,39 @@ func TestDemoSeedAndPublicCatalogIntegration(t *testing.T) { if page.TotalCount != 0 || len(page.Courses) != 0 { t.Fatal("draft course leaked into search") } + // The database must contain subject-specific MCQs with one correct option. + var questionText, explanation string + var optionCount, correctCount int + err = conn.QueryRow(ctx, `SELECT q.question_text,q.explanation,COUNT(o.id),COUNT(*) FILTER(WHERE o.is_correct) + FROM demo_seed_entities d JOIN questions q ON q.id=d.entity_id JOIN question_options o ON o.question_id=q.id + WHERE d.kind='question' AND d.seed_key='makeup-foundations/chapter-1/question-1' + GROUP BY q.id`).Scan(&questionText, &explanation, &optionCount, &correctCount) + if err != nil { + t.Fatal(err) + } + lesson := demoseed.Courses[0].Chapters[0].Lessons[0] + if questionText != lesson.Question || explanation != lesson.Explanation || optionCount != 3 || correctCount != 1 { + t.Fatal("makeup quiz payload is incomplete") + } + // Authored edits survive a subsequent seed run. + var lessonID int64 + if err = conn.QueryRow(ctx, `SELECT entity_id FROM demo_seed_entities WHERE kind='lesson' AND seed_key='makeup-foundations/chapter-1/lesson-1'`).Scan(&lessonID); err != nil { + t.Fatal(err) + } + if _, err = conn.Exec(ctx, `UPDATE exam_prep.unit_module_lessons SET title='Instructor revised kit lesson',updated_at=NOW() WHERE id=$1`, lessonID); err != nil { + t.Fatal(err) + } + defer conn.Exec(context.Background(), `UPDATE exam_prep.unit_module_lessons SET title=$2,updated_at=NULL WHERE id=$1`, lessonID, lesson.Title) + if err = demoseed.Run(ctx, conn, demoseed.DefaultPassword, ""); err != nil { + t.Fatal(err) + } + var preserved string + if err = conn.QueryRow(ctx, `SELECT title FROM exam_prep.unit_module_lessons WHERE id=$1`, lessonID).Scan(&preserved); err != nil { + t.Fatal(err) + } + if preserved != "Instructor revised kit lesson" { + t.Fatal("seed overwrote instructor edits") + } // A hidden chapter and all descendants must disappear from the public outline. chapterID := outline.Chapters[0].ID if _, err = conn.Exec(ctx, `UPDATE exam_prep.units SET publish_status='DRAFT' WHERE id=$1`, chapterID); err != nil { diff --git a/internal/demoseed/makeup_focus_options.sql b/internal/demoseed/makeup_focus_options.sql new file mode 100644 index 00000000..7a81140e --- /dev/null +++ b/internal/demoseed/makeup_focus_options.sql @@ -0,0 +1,9 @@ +INSERT INTO field_options(field_key,code,label,display_order,status) VALUES + ('language_challange','COLOR_MATCHING','Foundation and color matching',1,'ACTIVE'), + ('language_challange','BLENDING','Blending and application',2,'ACTIVE'), + ('language_challange','EYE_SYMMETRY','Eye makeup and symmetry',3,'ACTIVE'), + ('language_challange','CLIENT_CONFIDENCE','Working confidently with clients',4,'ACTIVE'), + ('language_goal','MAKEUP_FOUNDATIONS','Master makeup foundations',1,'ACTIVE'), + ('language_goal','PROFESSIONAL_ARTISTRY','Develop professional artistry',2,'ACTIVE'), + ('language_goal','CREATIVE_ARTISTRY','Explore creative artistry',3,'ACTIVE') +ON CONFLICT(field_key,code) DO NOTHING; diff --git a/internal/demoseed/makeup_profile_options.sql b/internal/demoseed/makeup_profile_options.sql new file mode 100644 index 00000000..1c4a28aa --- /dev/null +++ b/internal/demoseed/makeup_profile_options.sql @@ -0,0 +1,15 @@ +-- Add makeup-artistry choices without rewriting historical profile codes or custom options. +INSERT INTO field_options(field_key,code,label,display_order,status) VALUES + ('occupation','BEAUTY_STUDENT','Beauty and makeup student',1,'ACTIVE'), + ('occupation','MAKEUP_ARTIST','Makeup artist',2,'ACTIVE'), + ('occupation','BEAUTY_EDUCATOR','Makeup educator',3,'ACTIVE'), + ('occupation','SALON_PROFESSIONAL','Salon or studio professional',4,'ACTIVE'), + ('learning_goal','PERSONAL_MAKEUP','Develop personal makeup skills',1,'ACTIVE'), + ('learning_goal','PRO_MAKEUP_ARTIST','Become a professional makeup artist',2,'ACTIVE'), + ('learning_goal','BRIDAL_SPECIALIST','Specialize in bridal and occasion makeup',3,'ACTIVE'), + ('learning_goal','EDITORIAL_PORTFOLIO','Build an editorial makeup portfolio',4,'ACTIVE'), + ('favourite_topic','COMPLEXION_TECHNIQUES','Complexion and foundation techniques',1,'ACTIVE'), + ('favourite_topic','EYE_MAKEUP','Eye makeup and brow design',2,'ACTIVE'), + ('favourite_topic','BRIDAL_MAKEUP','Bridal and occasion looks',3,'ACTIVE'), + ('favourite_topic','EDITORIAL_MAKEUP','Creative and editorial artistry',4,'ACTIVE') +ON CONFLICT(field_key,code) DO NOTHING; diff --git a/internal/demoseed/makeup_upgrade.go b/internal/demoseed/makeup_upgrade.go new file mode 100644 index 00000000..aa92ba46 --- /dev/null +++ b/internal/demoseed/makeup_upgrade.go @@ -0,0 +1,68 @@ +package demoseed + +import _ "embed" + +//go:embed makeup_profile_options.sql +var makeupProfileOptionsSQL string + +func (s seed) seedMakeupProfileOptions() error { + _, err := s.tx.Exec(s.ctx, makeupProfileOptionsSQL+"\n"+makeupFocusOptionsSQL) + return err +} + +// Archive only untouched, seed-owned general-learning fixtures. Existing IDs, +// descendants and progress remain available to staff. Timestamp checks also +// protect fixtures to which staff have added or edited learning content. +func (s seed) archiveLegacyCourses() error { + legacy := []struct{ key, name, description string }{ + {"everyday-english", "Everyday English", "Build confidence with introductions, daily conversations, and practical vocabulary."}, + {"workplace-communication", "Workplace Communication", "Communicate clearly in meetings, write effective messages, and present your ideas."}, + {"digital-skills", "Digital Skills Essentials", "Learn practical habits for working online, organizing information, and collaborating safely."}, + } + for _, old := range legacy { + _, err := s.tx.Exec(s.ctx, `UPDATE exam_prep.catalog_courses c SET publish_status='DRAFT',updated_at=NOW() + FROM demo_seed_entities d + WHERE d.kind='course' AND d.seed_key=$1 AND c.id=d.entity_id + AND c.name=$2 AND c.description=$3 AND c.updated_at IS NULL + AND NOT EXISTS(SELECT 1 FROM exam_prep.units u WHERE u.catalog_course_id=c.id + AND (u.updated_at IS NOT NULL OR u.created_at>c.created_at)) + AND NOT EXISTS(SELECT 1 FROM exam_prep.unit_modules m JOIN exam_prep.units u ON u.id=m.unit_id + WHERE u.catalog_course_id=c.id AND (m.updated_at IS NOT NULL OR m.created_at>c.created_at)) + AND NOT EXISTS(SELECT 1 FROM exam_prep.unit_module_lessons l + JOIN exam_prep.unit_modules m ON m.id=l.unit_module_id JOIN exam_prep.units u ON u.id=m.unit_id + WHERE u.catalog_course_id=c.id AND (l.updated_at IS NOT NULL OR l.created_at>c.created_at)) + AND NOT EXISTS(SELECT 1 FROM exam_prep.lesson_practices p + JOIN exam_prep.practice_parents pp ON pp.practice_id=p.id + JOIN question_sets qs ON qs.id=p.question_set_id + WHERE ((pp.parent_kind='CATALOG_COURSE' AND pp.parent_id=c.id) + OR (pp.parent_kind='UNIT' AND pp.parent_id IN(SELECT id FROM exam_prep.units WHERE catalog_course_id=c.id)) + OR (pp.parent_kind='LESSON' AND pp.parent_id IN(SELECT l.id FROM exam_prep.unit_module_lessons l + JOIN exam_prep.unit_modules m ON m.id=l.unit_module_id JOIN exam_prep.units u ON u.id=m.unit_id WHERE u.catalog_course_id=c.id))) + AND (p.updated_at IS NOT NULL OR p.created_at>c.created_at OR qs.updated_at IS NOT NULL OR qs.created_at>c.created_at + OR EXISTS(SELECT 1 FROM question_set_items i JOIN questions q ON q.id=i.question_id + WHERE i.set_id=qs.id AND (q.updated_at IS NOT NULL OR q.created_at>c.created_at + OR EXISTS(SELECT 1 FROM question_options o WHERE o.question_id=q.id AND o.created_at>c.created_at)))))`, old.key, old.name, old.description) + if err != nil { + return err + } + } + return nil +} + +func (s seed) refreshLegacyDemoLabels() error { + _, err := s.tx.Exec(s.ctx, `UPDATE subscription_plans p + SET name='[Demo] Makeup Academy Pass',description='Testing only: grants premium makeup artistry course access for 30 days.' + FROM demo_seed_entities d WHERE d.kind='plan' AND d.seed_key='education-demo' AND p.id=d.entity_id + AND p.name='[Demo] Education access' AND p.description='Testing only: grants premium learning access for 30 days.'`) + if err != nil { + return err + } + _, err = s.tx.Exec(s.ctx, `UPDATE exam_prep.catalog_courses c + SET name='[Demo draft] Special Effects Makeup',description='Unpublished makeup artistry course: must not appear in the public catalog.' + FROM demo_seed_entities d WHERE d.kind='course' AND d.seed_key='draft' AND c.id=d.entity_id + AND c.name='[Demo draft] Coming soon' AND c.description='Unpublished fixture: must not appear in the public catalog.' AND c.updated_at IS NULL`) + return err +} + +//go:embed makeup_focus_options.sql +var makeupFocusOptionsSQL string diff --git a/internal/demoseed/makeup_upgrade_test.go b/internal/demoseed/makeup_upgrade_test.go new file mode 100644 index 00000000..d9df3e2f --- /dev/null +++ b/internal/demoseed/makeup_upgrade_test.go @@ -0,0 +1,75 @@ +package demoseed + +import ( + "context" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5" +) + +// This test only touches a disposable opt-in database, and rolls back its fixtures. +func TestLegacyDemoArchivalPreservesAuthoredContent(t *testing.T) { + url := os.Getenv("DEMO_TEST_DB_URL") + if url == "" { + t.Skip("set DEMO_TEST_DB_URL to a disposable migrated PostgreSQL database") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + conn, err := pgx.Connect(ctx, url) + if err != nil { + t.Fatal(err) + } + defer conn.Close(ctx) + tx, err := conn.Begin(ctx) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback(ctx) + if _, err = tx.Exec(ctx, `CREATE TEMP TABLE demo_seed_entities(kind text,seed_key text,entity_id bigint,PRIMARY KEY(kind,seed_key)) ON COMMIT DROP`); err != nil { + t.Fatal(err) + } + create := func(key, name, description string, owned bool) int64 { + t.Helper() + var id int64 + if err := tx.QueryRow(ctx, `INSERT INTO exam_prep.catalog_courses(name,description,category,publish_status,access_tier) VALUES($1,$2,'EDUCATION','PUBLISHED','FREE') RETURNING id`, name, description).Scan(&id); err != nil { + t.Fatal(err) + } + if owned { + if _, err := tx.Exec(ctx, `INSERT INTO demo_seed_entities VALUES('course',$1,$2)`, key, id); err != nil { + t.Fatal(err) + } + } + return id + } + untouched := create("everyday-english", "Everyday English", "Build confidence with introductions, daily conversations, and practical vocabulary.", true) + edited := create("workplace-communication", "Workplace Communication", "Communicate clearly in meetings, write effective messages, and present your ideas.", true) + renamed := create("digital-skills", "Instructor-authored portfolio course", "Learn practical habits for working online, organizing information, and collaborating safely.", true) + unrelated := create("", "Everyday English", "Build confidence with introductions, daily conversations, and practical vocabulary.", false) + var unit, module int64 + if err = tx.QueryRow(ctx, `INSERT INTO exam_prep.units(catalog_course_id,name,publish_status,access_tier) VALUES($1,'Edited chapter','PUBLISHED','FREE') RETURNING id`, edited).Scan(&unit); err != nil { + t.Fatal(err) + } + if err = tx.QueryRow(ctx, `INSERT INTO exam_prep.unit_modules(unit_id,name,publish_status,access_tier) VALUES($1,'__chapter_lessons__','PUBLISHED','FREE') RETURNING id`, unit).Scan(&module); err != nil { + t.Fatal(err) + } + if _, err = tx.Exec(ctx, `INSERT INTO exam_prep.unit_module_lessons(unit_module_id,title,publish_status,access_tier,sort_order,updated_at) VALUES($1,'Instructor edit','PUBLISHED','FREE',1,NOW())`, module); err != nil { + t.Fatal(err) + } + fixture := seed{tx: tx, ctx: ctx} + for i := 0; i < 2; i++ { + if err = fixture.archiveLegacyCourses(); err != nil { + t.Fatal(err) + } + } + for id, want := range map[int64]string{untouched: "DRAFT", edited: "PUBLISHED", renamed: "PUBLISHED", unrelated: "PUBLISHED"} { + var got string + if err = tx.QueryRow(ctx, `SELECT publish_status FROM exam_prep.catalog_courses WHERE id=$1`, id).Scan(&got); err != nil { + t.Fatal(err) + } + if got != want { + t.Errorf("course %d: got %s want %s", id, got, want) + } + } +} diff --git a/internal/demoseed/seed.go b/internal/demoseed/seed.go index 8209aeb9..ad2b5e0b 100644 --- a/internal/demoseed/seed.go +++ b/internal/demoseed/seed.go @@ -13,39 +13,15 @@ import ( const DefaultPassword = "RezinaDemo!2026" -type Account struct{ Email, Role, Audience string } +type Account struct{ Email, Role, Audience, Name string } var Accounts = []Account{ - {"superadmin@demo.rezina.test", "SUPER_ADMIN", "staff"}, - {"admin@demo.rezina.test", "ADMIN", "staff"}, - {"contentmanager@demo.rezina.test", "CONTENT_MANAGER", "staff"}, - {"student@demo.rezina.test", "STUDENT", "customer"}, - {"premium@demo.rezina.test", "STUDENT", "customer"}, - {"openlearner@demo.rezina.test", "OPEN_LEARNER", "customer"}, -} - -type Course struct { - Key, Name, Description, Tier string - Chapters []Chapter -} -type Chapter struct { - Name string - Lessons []string -} - -var Courses = []Course{ - {"everyday-english", "Everyday English", "Build confidence with introductions, daily conversations, and practical vocabulary.", "FREE", []Chapter{ - {"Meet and greet", []string{"Introduce yourself", "Ask friendly questions", "Start a conversation"}}, - {"Everyday situations", []string{"Order food and drinks", "Ask for directions", "Make simple plans"}}, - }}, - {"workplace-communication", "Workplace Communication", "Communicate clearly in meetings, write effective messages, and present your ideas.", "PREMIUM", []Chapter{ - {"Working together", []string{"Write a clear email", "Join a team meeting", "Give useful feedback"}}, - {"Present with confidence", []string{"Structure your message", "Explain an idea", "Answer audience questions"}}, - }}, - {"digital-skills", "Digital Skills Essentials", "Learn practical habits for working online, organizing information, and collaborating safely.", "FREE", []Chapter{ - {"Digital foundations", []string{"Organize files and folders", "Search with purpose", "Protect your accounts"}}, - {"Online collaboration", []string{"Share documents", "Work in a shared workspace", "Communicate online"}}, - }}, + {"superadmin@demo.rezina.test", "SUPER_ADMIN", "staff", "Academy Director"}, + {"admin@demo.rezina.test", "ADMIN", "staff", "Academy Admin"}, + {"contentmanager@demo.rezina.test", "CONTENT_MANAGER", "staff", "Makeup Instructor"}, + {"student@demo.rezina.test", "STUDENT", "customer", "Makeup Student"}, + {"premium@demo.rezina.test", "STUDENT", "customer", "Makeup Student"}, + {"openlearner@demo.rezina.test", "OPEN_LEARNER", "customer", "Guest Artist"}, } // ValidateEnvironment requires an explicit non-production target and refuses any @@ -95,6 +71,9 @@ func (s seed) entity(kind, key, table, insert string, args ...any) (int64, error } func Run(ctx context.Context, conn *pgx.Conn, password, videoURL string) error { + if err := validateCurriculum(Courses); err != nil { + return err + } if len(password) < 12 || len(password) > 72 { return fmt.Errorf("demo password must be 12-72 bytes") } @@ -121,17 +100,34 @@ func Run(ctx context.Context, conn *pgx.Conn, password, videoURL string) error { if _, err = tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS demo_seed_entities(kind text NOT NULL,seed_key text NOT NULL,entity_id bigint NOT NULL,PRIMARY KEY(kind,seed_key))`); err != nil { return err } + if err = s.seedMakeupProfileOptions(); err != nil { + return err + } + if err = s.archiveLegacyCourses(); err != nil { + return err + } userIDs := map[string]int64{} for _, a := range Accounts { var id int64 if a.Audience == "staff" { err = tx.QueryRow(ctx, `INSERT INTO team_members(first_name,last_name,email,password,team_role,status,email_verified,employment_type) - VALUES('Demo',$1,$2,$3,$4,'active',true,'full_time') ON CONFLICT(email) DO UPDATE SET password=EXCLUDED.password,team_role=EXCLUDED.team_role,status='active',email_verified=true - RETURNING id`, a.Role, a.Email, hash, a.Role).Scan(&id) + VALUES('Demo',$1,$2,$3,$4,'active',true,'full_time') ON CONFLICT(email) DO UPDATE SET password=EXCLUDED.password,team_role=EXCLUDED.team_role,status='active',email_verified=true, + last_name=CASE WHEN team_members.first_name='Demo' AND team_members.last_name=$4 THEN EXCLUDED.last_name ELSE team_members.last_name END + RETURNING id`, a.Name, a.Email, hash, a.Role).Scan(&id) } else { err = tx.QueryRow(ctx, `INSERT INTO users(first_name,last_name,email,password,role,status,email_verified,phone_verified,profile_completed,preferred_language) VALUES('Demo',$1,$2,$3,$4,'ACTIVE',true,false,true,'en') ON CONFLICT(lower(email)) WHERE email IS NOT NULL DO UPDATE - SET password=EXCLUDED.password,role=EXCLUDED.role,status='ACTIVE',email_verified=true,profile_completed=true RETURNING id`, a.Role, a.Email, hash, a.Role).Scan(&id) + SET password=EXCLUDED.password,role=EXCLUDED.role,status='ACTIVE',email_verified=true,profile_completed=true, + last_name=CASE WHEN users.first_name='Demo' AND users.last_name=$4 THEN EXCLUDED.last_name ELSE users.last_name END RETURNING id`, a.Name, a.Email, hash, a.Role).Scan(&id) + if err == nil { + _, err = tx.Exec(ctx, `UPDATE users SET + occupation=COALESCE(NULLIF(occupation,''),'BEAUTY_STUDENT'), + learning_goal=COALESCE(NULLIF(learning_goal,''),'PERSONAL_MAKEUP'), + favourite_topic=COALESCE(NULLIF(favourite_topic,''),'COMPLEXION_TECHNIQUES'), + language_challange=COALESCE(NULLIF(language_challange,''),'BLENDING'), +language_goal=COALESCE(NULLIF(language_goal,''),'MAKEUP_FOUNDATIONS'), +knowledge_level=COALESCE(NULLIF(knowledge_level,''),'BEGINNER') WHERE id=$1`, id) + } userIDs[a.Email] = id } if err != nil { @@ -141,7 +137,7 @@ func Run(ctx context.Context, conn *pgx.Conn, password, videoURL string) error { // Seed standard RBAC grants, rather than granting every permission to every role. for _, p := range rbac.AllPermissions { if _, err = tx.Exec(ctx, `INSERT INTO permissions(key,name,description,group_name) VALUES($1,$2,$3,$4) - ON CONFLICT(key) DO NOTHING`, p.Key, p.Name, p.Description, p.GroupName); err != nil { + ON CONFLICT(key) DO UPDATE SET name=EXCLUDED.name,description=EXCLUDED.description,group_name=EXCLUDED.group_name`, p.Key, p.Name, p.Description, p.GroupName); err != nil { return err } } @@ -164,7 +160,7 @@ func Run(ctx context.Context, conn *pgx.Conn, password, videoURL string) error { for ci, chapter := range course.Chapters { key := fmt.Sprintf("%s/chapter-%d", course.Key, ci+1) chapterID, err := s.entity("chapter", key, "exam_prep.units", `INSERT INTO exam_prep.units(catalog_course_id,name,description,sort_order,publish_status,access_tier) - VALUES($1,$2,$3,$4,'PUBLISHED','FREE') RETURNING id`, courseID, chapter.Name, "Practice the key ideas through short lessons and a chapter review quiz.", ci+1) + VALUES($1,$2,$3,$4,'PUBLISHED','FREE') RETURNING id`, courseID, chapter.Name, chapter.Description, ci+1) if err != nil { return err } @@ -179,14 +175,14 @@ func Run(ctx context.Context, conn *pgx.Conn, password, videoURL string) error { if err != nil { return err } - for li, title := range chapter.Lessons { + for li, lesson := range chapter.Lessons { _, err = s.entity("lesson", fmt.Sprintf("%s/lesson-%d", key, li+1), "exam_prep.unit_module_lessons", `INSERT INTO exam_prep.unit_module_lessons(unit_module_id,title,description,sort_order,publish_status,access_tier,video_url,thumbnail) - SELECT $1,$2,$3,COALESCE(MAX(sort_order),0)+1,'PUBLISHED','FREE',NULLIF($4,''),'/static/demo/course-cover.svg' FROM exam_prep.unit_module_lessons WHERE unit_module_id=$1 RETURNING id`, moduleID, title, "In this demo lesson, explore how to "+strings.ToLower(title)+". Review the examples, try it yourself, and complete the chapter quiz. The video is sample media for testing playback.", videoURL) + SELECT $1,$2,$3,COALESCE(MAX(sort_order),0)+1,'PUBLISHED','FREE',NULLIF($4,''),'/static/demo/course-cover.svg' FROM exam_prep.unit_module_lessons WHERE unit_module_id=$1 RETURNING id`, moduleID, lesson.Title, lesson.Description+" Demo media is a playback fixture, not an instructional recording of this technique.", videoURL) if err != nil { return err } } - setID, err := s.entity("question_set", key, "question_sets", `INSERT INTO question_sets(title,description,set_type,status,passing_score,shuffle_questions) VALUES($1,'Demo chapter review','QUIZ','PUBLISHED',60,false) RETURNING id`, chapter.Name+" review") + setID, err := s.entity("question_set", key, "question_sets", `INSERT INTO question_sets(title,description,set_type,status,passing_score,shuffle_questions) VALUES($1,'Makeup artistry knowledge check','QUIZ','PUBLISHED',60,false) RETURNING id`, chapter.Name+" review") if err != nil { return err } @@ -197,18 +193,18 @@ func Run(ctx context.Context, conn *pgx.Conn, password, videoURL string) error { if _, err = tx.Exec(ctx, `INSERT INTO exam_prep.practice_parents(practice_id,parent_kind,parent_id) VALUES($1,'UNIT',$2) ON CONFLICT DO NOTHING`, quizID, chapterID); err != nil { return err } - for qi, title := range chapter.Lessons { - questionID, err := s.entity("question", fmt.Sprintf("%s/question-%d", key, qi+1), "questions", `INSERT INTO questions(question_text,question_type,difficulty_level,points,explanation,status) VALUES($1,'MCQ','EASY',1,'Small, deliberate practice helps you apply what you learned.','PUBLISHED') RETURNING id`, "After the lesson '"+title+"', what is the best way to improve?") + for qi, lesson := range chapter.Lessons { + questionID, err := s.entity("question", fmt.Sprintf("%s/question-%d", key, qi+1), "questions", `INSERT INTO questions(question_text,question_type,difficulty_level,points,explanation,status) VALUES($1,'MCQ','EASY',1,$2,'PUBLISHED') RETURNING id`, lesson.Question, lesson.Explanation) if err != nil { return err } - for oi, option := range []string{"Try a small real-world example and reflect on it", "Skip practice entirely", "Avoid asking questions"} { + for oi, option := range lesson.Options { var exists bool if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM question_options WHERE question_id=$1 AND option_order=$2)`, questionID, oi+1).Scan(&exists); err != nil { return err } if !exists { - if _, err = tx.Exec(ctx, `INSERT INTO question_options(question_id,option_text,option_order,is_correct) VALUES($1,$2,$3,$4)`, questionID, option, oi+1, oi == 0); err != nil { + if _, err = tx.Exec(ctx, `INSERT INTO question_options(question_id,option_text,option_order,is_correct) VALUES($1,$2,$3,$4)`, questionID, option, oi+1, oi == lesson.CorrectIndex); err != nil { return err } } @@ -221,14 +217,17 @@ func Run(ctx context.Context, conn *pgx.Conn, password, videoURL string) error { } // A draft fixture verifies that public browsing cannot reveal unpublished content. if _, err = s.entity("course", "draft", "exam_prep.catalog_courses", `INSERT INTO exam_prep.catalog_courses(name,description,category,sort_order,publish_status,access_tier) - SELECT '[Demo draft] Coming soon','Unpublished fixture: must not appear in the public catalog.','EDUCATION',COALESCE(MAX(sort_order),0)+1,'DRAFT','FREE' FROM exam_prep.catalog_courses RETURNING id`); err != nil { + SELECT '[Demo draft] Special Effects Makeup','Unpublished makeup artistry course: must not appear in the public catalog.','EDUCATION',COALESCE(MAX(sort_order),0)+1,'DRAFT','FREE' FROM exam_prep.catalog_courses RETURNING id`); err != nil { return err } planID, err := s.entity("plan", "education-demo", "subscription_plans", `INSERT INTO subscription_plans(name,description,duration_value,duration_unit,price,currency,is_active,category,is_free) - VALUES('[Demo] Education access','Testing only: grants premium learning access for 30 days.',1,'MONTH',0,'ETB',false,'EDUCATION',true) RETURNING id`) + VALUES('[Demo] Makeup Academy Pass','Testing only: grants premium makeup artistry course access for 30 days.',1,'MONTH',0,'ETB',false,'EDUCATION',true) RETURNING id`) if err != nil { return err } + if err = s.refreshLegacyDemoLabels(); err != nil { + return err + } _, err = s.entity("subscription", "premium-student", "user_subscriptions", `INSERT INTO user_subscriptions(user_id,plan_id,starts_at,expires_at,status,payment_method,auto_renew) VALUES($1,$2,NOW(),NOW()+INTERVAL '30 days','ACTIVE','DEMO',false) RETURNING id`, userIDs["premium@demo.rezina.test"], planID) if err != nil { diff --git a/internal/demoseed/seed_test.go b/internal/demoseed/seed_test.go index 120ff5af..61e2c3f8 100644 --- a/internal/demoseed/seed_test.go +++ b/internal/demoseed/seed_test.go @@ -2,6 +2,8 @@ package demoseed import ( "Rezina-Backend/internal/domain" + "os" + "strings" "testing" ) @@ -42,3 +44,74 @@ func TestAccountsCoverSupportedRoles(t *testing.T) { } } } + +func TestMakeupCurriculum(t *testing.T) { + if err := validateCurriculum(Courses); err != nil { + t.Fatal(err) + } + chapters, lessons := 0, 0 + tiers := map[string]bool{} + answers := map[int]bool{} + expected := map[string]bool{"makeup-foundations": false, "makeup-bridal": false, "makeup-editorial": false} + for _, course := range Courses { + if _, ok := expected[course.Key]; !ok { + t.Fatalf("unexpected course %s", course.Key) + } + expected[course.Key] = true + tiers[course.Tier] = true + for _, chapter := range course.Chapters { + chapters++ + for _, lesson := range chapter.Lessons { + lessons++ + answers[lesson.CorrectIndex] = true + if len(lesson.Options) != 3 { + t.Errorf("%s must have three choices", lesson.Title) + } + if strings.Contains(lesson.Question, "best way to improve") { + t.Errorf("generic quiz content remains in %s", lesson.Title) + } + } + } + } + if len(Courses) != 3 || chapters != 6 || lessons != 18 || !tiers["FREE"] || !tiers["PREMIUM"] || len(answers) != 3 { + t.Fatalf("incomplete makeup fixture: courses=%d chapters=%d lessons=%d answer positions=%v", len(Courses), chapters, lessons, answers) + } + for key, present := range expected { + if !present { + t.Errorf("missing %s", key) + } + } +} + +func TestCurriculumRejectsInvalidKnowledgeChecks(t *testing.T) { + for _, bad := range []Lesson{ + {Title: "Test", Description: "Demo", Question: "Question", Explanation: "Why", Options: []string{"A", "B"}, CorrectIndex: 2}, + {Title: "Test", Description: "Demo", Question: "Question", Explanation: "Why", Options: []string{"A", " a "}, CorrectIndex: 0}, + {Title: "Test", Description: "Demo", Question: "Question", Options: []string{"A", "B"}, CorrectIndex: 0}, + } { + course := Course{Key: "test", Name: "Test", Description: "Demo", Tier: "FREE", Chapters: []Chapter{{Name: "Chapter", Description: "Demo", Lessons: []Lesson{bad}}}} + if validateCurriculum([]Course{course}) == nil { + t.Errorf("accepted invalid lesson %+v", bad) + } + } +} + +func TestDemoAndMigrationProfileOptionsMatch(t *testing.T) { + data, err := os.ReadFile("../../db/migrations/000004_makeup_artistry_profiles.up.sql") + if err != nil { + t.Fatal(err) + } + if string(data) != makeupProfileOptionsSQL { + t.Fatal("standalone seed and deployed profile options differ") + } +} + +func TestMakeupFocusOptionsMatchMigration(t *testing.T) { + migration, err := os.ReadFile("../../db/migrations/000005_makeup_artistry_focus.up.sql") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(migration), strings.TrimSpace(makeupFocusOptionsSQL)) { + t.Fatal("demo focus choices must match the database migration") + } +} diff --git a/internal/domain/exam_prep_catalog_course.go b/internal/domain/exam_prep_catalog_course.go index 6e96e1a0..147a6c94 100644 --- a/internal/domain/exam_prep_catalog_course.go +++ b/internal/domain/exam_prep_catalog_course.go @@ -2,7 +2,7 @@ package domain import "time" -// ExamPrepCatalogCourse is a top-level exam-prep track (e.g. DET, IELTS) in schema exam_prep — separate from LMS Learn English courses. +// ExamPrepCatalogCourse stores the makeup academy catalog under the legacy exam_prep schema. type ExamPrepCatalogCourse struct { ID int64 `json:"id"` Name string `json:"name"` diff --git a/internal/domain/subscriptions.go b/internal/domain/subscriptions.go index e7fa02de..7ae041f9 100644 --- a/internal/domain/subscriptions.go +++ b/internal/domain/subscriptions.go @@ -16,6 +16,7 @@ var ( type SubscriptionCategory string const ( + // EDUCATION is the canonical category for makeup artistry courses and passes. SubscriptionCategoryEducation SubscriptionCategory = "EDUCATION" // SubscriptionCategoryLearnEnglish remains for historical plan and subscription records. SubscriptionCategoryLearnEnglish SubscriptionCategory = "LEARN_ENGLISH" diff --git a/internal/pkgs/helpers/helpers.go b/internal/pkgs/helpers/helpers.go index 8bfc338b..a192eb77 100644 --- a/internal/pkgs/helpers/helpers.go +++ b/internal/pkgs/helpers/helpers.go @@ -4,11 +4,11 @@ import ( random "crypto/rand" "encoding/hex" "fmt" + "math/big" + "math/rand/v2" "strings" "github.com/google/uuid" - "math/big" - "math/rand/v2" ) func GenerateID() string { @@ -23,18 +23,22 @@ func GenerateInviteToken() (string, error) { return hex.EncodeToString(b), nil } -func GenerateOTP() string { - num := 100000 + rand.UintN(899999) - return fmt.Sprintf("%d", num) // 6 digit random number [100,000 - 999,999] +// GenerateOTP returns a cryptographically random six-digit code. +func GenerateOTP() (string, error) { + num, err := random.Int(random.Reader, big.NewInt(900000)) + if err != nil { + return "", fmt.Errorf("generate OTP: %w", err) + } + return fmt.Sprintf("%d", 100000+num.Int64()), nil } func GenerateFastCode() string { const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - var code string - for i := 0; i < 6; i++ { - code += string(letters[rand.UintN(uint(len(letters)))]) + var code [6]byte + for i := range code { + code[i] = letters[rand.UintN(uint(len(letters)))] } - return code + return string(code[:]) } func GenerateCashoutID() (string, error) { @@ -58,12 +62,22 @@ func MaskPhone(phone string) string { if phone == "" { return "" } - return phone[:4] + "**" + phone[len(phone)-2:] + runes := []rune(phone) + if len(runes) <= 6 { + return "**" + } + return string(runes[:4]) + "**" + string(runes[len(runes)-2:]) } func MaskEmail(email string) string { if email == "" { return "" } - return email[:3] + "**" + email[strings.Index(email, "@"):] + local, domain, ok := strings.Cut(email, "@") + if !ok || local == "" || domain == "" { + return "**" + } + runes := []rune(local) + visible := min(3, len(runes)-1) + return string(runes[:visible]) + "**@" + domain } diff --git a/internal/pkgs/helpers/helpers_test.go b/internal/pkgs/helpers/helpers_test.go new file mode 100644 index 00000000..961eef1d --- /dev/null +++ b/internal/pkgs/helpers/helpers_test.go @@ -0,0 +1,47 @@ +package helpers + +import ( + "strconv" + "testing" +) + +func TestMaskPhone(t *testing.T) { + for _, tc := range []struct{ input, want string }{ + {"", ""}, {"1", "**"}, {"123456", "**"}, {"1234567", "1234**67"}, + {"+251911234567", "+251**67"}, {"\u1230\u120b\u121d12345", "\u1230\u120b\u121d1**45"}, + } { + t.Run(tc.input, func(t *testing.T) { + if got := MaskPhone(tc.input); got != tc.want { + t.Errorf("MaskPhone(%q) = %q, want %q", tc.input, got, tc.want) + } + }) + } +} + +func TestMaskEmail(t *testing.T) { + for _, tc := range []struct{ input, want string }{ + {"", ""}, {"invalid", "**"}, {"@example.com", "**"}, {"abc@", "**"}, + {"a@example.com", "**@example.com"}, {"ab@example.com", "a**@example.com"}, + {"abc@example.com", "ab**@example.com"}, {"alice@example.com", "ali**@example.com"}, + {"\u1230\u120b\u121d@example.com", "\u1230\u120b**@example.com"}, + } { + t.Run(tc.input, func(t *testing.T) { + if got := MaskEmail(tc.input); got != tc.want { + t.Errorf("MaskEmail(%q) = %q, want %q", tc.input, got, tc.want) + } + }) + } +} + +func TestGenerateOTP(t *testing.T) { + for range 100 { + code, err := GenerateOTP() + if err != nil { + t.Fatal(err) + } + value, err := strconv.Atoi(code) + if err != nil || len(code) != 6 || value < 100000 || value > 999999 { + t.Fatalf("invalid OTP %q", code) + } + } +} diff --git a/internal/repository/store.go b/internal/repository/store.go index 5169f7ef..ac4a9cef 100644 --- a/internal/repository/store.go +++ b/internal/repository/store.go @@ -62,7 +62,7 @@ func envInt32(key string, fallback int32) int32 { if raw == "" { return fallback } - n, err := strconv.Atoi(raw) + n, err := strconv.ParseInt(raw, 10, 32) if err != nil || n <= 0 { return fallback } diff --git a/internal/repository/store_config_test.go b/internal/repository/store_config_test.go new file mode 100644 index 00000000..ebd6d167 --- /dev/null +++ b/internal/repository/store_config_test.go @@ -0,0 +1,20 @@ +package repository + +import "testing" + +func TestEnvInt32(t *testing.T) { + for _, tc := range []struct { + value string + want int32 + }{ + {"", 25}, {"invalid", 25}, {"0", 25}, {"-1", 25}, {"2147483648", 25}, + {"4294967321", 25}, {"2147483647", 2147483647}, {"50", 50}, + } { + t.Run(tc.value, func(t *testing.T) { + t.Setenv("REZINA_TEST_POOL_SIZE", tc.value) + if got := envInt32("REZINA_TEST_POOL_SIZE", 25); got != tc.want { + t.Errorf("got %d, want %d", got, tc.want) + } + }) + } +} diff --git a/internal/services/authentication/service.go b/internal/services/authentication/service.go index 08b9135a..35c266fa 100644 --- a/internal/services/authentication/service.go +++ b/internal/services/authentication/service.go @@ -5,11 +5,6 @@ import ( "Rezina-Backend/internal/services/user" ) -// type EmailPhone struct { -// Email ValidString -// PhoneNumber ValidString -// Password ValidString -// } type ValidString struct { Value string Valid bool @@ -21,12 +16,12 @@ type Tokens struct { type Service struct { otpStore ports.OtpStore userStore ports.UserStore - UserSvc user.Service + UserSvc *user.Service tokenStore ports.TokenStore RefreshExpiry int } -func NewService(otpStore ports.OtpStore, userStore ports.UserStore, userSvc user.Service, tokenStore ports.TokenStore, RefreshExpiry int) *Service { +func NewService(otpStore ports.OtpStore, userStore ports.UserStore, userSvc *user.Service, tokenStore ports.TokenStore, RefreshExpiry int) *Service { return &Service{ otpStore: otpStore, userStore: userStore, diff --git a/internal/services/learnernotifications/subscription.go b/internal/services/learnernotifications/subscription.go index ab35d5bf..0c044352 100644 --- a/internal/services/learnernotifications/subscription.go +++ b/internal/services/learnernotifications/subscription.go @@ -12,7 +12,7 @@ func subscriptionPackageLabel(planCategory string) string { case string(domain.SubscriptionCategoryLearnEnglish): return "Learn English" case string(domain.SubscriptionCategoryEducation): - return "Education" + return "Makeup Artistry" case string(domain.SubscriptionCategoryIELTS): return "IELTS" case string(domain.SubscriptionCategoryDuolingo): @@ -28,7 +28,7 @@ func subscriptionActivatedMessage(planCategory, planName string) string { case string(domain.SubscriptionCategoryLearnEnglish): return "Your \"" + planName + "\" Learn English package is now active. Enjoy your learning journey!" case string(domain.SubscriptionCategoryEducation): - return "Your \"" + planName + "\" education package is now active. Enjoy your learning journey!" + return "Your \"" + planName + "\" makeup artistry pass is now active. Explore your courses and practice your techniques!" case string(domain.SubscriptionCategoryIELTS): return "Your \"" + planName + "\" IELTS package is now active. Start preparing today!" case string(domain.SubscriptionCategoryDuolingo): diff --git a/internal/services/learnernotifications/subscription_test.go b/internal/services/learnernotifications/subscription_test.go index b1c8d2bc..c0c58e7e 100644 --- a/internal/services/learnernotifications/subscription_test.go +++ b/internal/services/learnernotifications/subscription_test.go @@ -1,6 +1,7 @@ package learnernotifications import ( + "strings" "testing" "time" @@ -36,3 +37,17 @@ func TestSubscriptionActivatedMessage(t *testing.T) { t.Fatalf("unexpected message: %q", msg) } } + +func TestMakeupArtistrySubscriptionMessages(t *testing.T) { + if label := subscriptionPackageLabel(" education "); label != "Makeup Artistry" { + t.Fatalf("label=%q", label) + } + message := subscriptionActivatedMessage("EDUCATION", "Bridal Academy Pass") + if !strings.Contains(message, "Bridal Academy Pass") || !strings.Contains(message, "makeup artistry") || strings.Contains(message, "English") { + t.Fatalf("unexpected makeup message: %q", message) + } + // Historical subscriptions retain their original labels and behavior. + if label := subscriptionPackageLabel("LEARN_ENGLISH"); label != "Learn English" { + t.Fatalf("legacy label=%q", label) + } +} diff --git a/internal/services/rbac/seeds.go b/internal/services/rbac/seeds.go index 955763c5..0928969a 100644 --- a/internal/services/rbac/seeds.go +++ b/internal/services/rbac/seeds.go @@ -29,39 +29,39 @@ var AllPermissions = []domain.PermissionSeed{ {Key: "programs.delete", Name: "Delete Program", Description: "Delete a program", GroupName: "Programs"}, {Key: "programs.reorder", Name: "Reorder Programs", Description: "Set program order for the learning path (batch)", GroupName: "Programs"}, - // Exam prep (schema exam_prep — DET / IELTS / TOEFL tracks; separate from LMS Learn English) - {Key: "exam_prep.catalog_courses.create", Name: "Create Exam Prep Catalog Course", Description: "Create a top-level exam prep catalog entry", GroupName: "Exam Prep"}, - {Key: "exam_prep.catalog_courses.list", Name: "List Exam Prep Catalog Courses", Description: "List exam prep catalog courses", GroupName: "Exam Prep"}, - {Key: "exam_prep.catalog_courses.get", Name: "Get Exam Prep Catalog Course", Description: "Get an exam prep catalog course by ID", GroupName: "Exam Prep"}, - {Key: "exam_prep.catalog_courses.update", Name: "Update Exam Prep Catalog Course", Description: "Update an exam prep catalog course", GroupName: "Exam Prep"}, - {Key: "exam_prep.catalog_courses.delete", Name: "Delete Exam Prep Catalog Course", Description: "Delete an exam prep catalog course", GroupName: "Exam Prep"}, - {Key: "exam_prep.catalog_courses.reorder", Name: "Reorder Exam Prep Catalog Courses", Description: "Set global order of exam prep catalog courses", GroupName: "Exam Prep"}, - {Key: "exam_prep.units.create", Name: "Create Exam Prep Unit", Description: "Create a unit under a catalog course", GroupName: "Exam Prep"}, - {Key: "exam_prep.units.list", Name: "List Exam Prep Units", Description: "List units under a catalog course", GroupName: "Exam Prep"}, - {Key: "exam_prep.units.get", Name: "Get Exam Prep Unit", Description: "Get an exam prep unit by ID", GroupName: "Exam Prep"}, - {Key: "exam_prep.units.update", Name: "Update Exam Prep Unit", Description: "Update an exam prep unit", GroupName: "Exam Prep"}, - {Key: "exam_prep.units.delete", Name: "Delete Exam Prep Unit", Description: "Delete an exam prep unit", GroupName: "Exam Prep"}, - {Key: "exam_prep.units.reorder", Name: "Reorder Exam Prep Units", Description: "Reorder units within a catalog course", GroupName: "Exam Prep"}, - {Key: "exam_prep.modules.create", Name: "Create Exam Prep Module", Description: "Create a module under an exam prep unit", GroupName: "Exam Prep"}, - {Key: "exam_prep.modules.list", Name: "List Exam Prep Modules", Description: "List modules under a unit", GroupName: "Exam Prep"}, - {Key: "exam_prep.modules.get", Name: "Get Exam Prep Module", Description: "Get an exam prep module by ID", GroupName: "Exam Prep"}, - {Key: "exam_prep.modules.update", Name: "Update Exam Prep Module", Description: "Update an exam prep module", GroupName: "Exam Prep"}, - {Key: "exam_prep.modules.delete", Name: "Delete Exam Prep Module", Description: "Delete an exam prep module", GroupName: "Exam Prep"}, - {Key: "exam_prep.modules.reorder", Name: "Reorder Exam Prep Modules", Description: "Reorder modules within a unit", GroupName: "Exam Prep"}, - {Key: "exam_prep.lessons.create", Name: "Create Exam Prep Lesson", Description: "Create a lesson under an exam prep unit module", GroupName: "Exam Prep"}, - {Key: "exam_prep.lessons.list_by_module", Name: "List Exam Prep Lessons by Module", Description: "List lessons under an exam prep unit module", GroupName: "Exam Prep"}, - {Key: "exam_prep.lessons.get", Name: "Get Exam Prep Lesson", Description: "Get an exam prep lesson by ID", GroupName: "Exam Prep"}, - {Key: "exam_prep.lessons.update", Name: "Update Exam Prep Lesson", Description: "Update an exam prep lesson", GroupName: "Exam Prep"}, - {Key: "exam_prep.lessons.delete", Name: "Delete Exam Prep Lesson", Description: "Delete an exam prep lesson", GroupName: "Exam Prep"}, - {Key: "exam_prep.lessons.reorder", Name: "Reorder Exam Prep Lessons", Description: "Reorder lessons within an exam prep unit module", GroupName: "Exam Prep"}, - {Key: "exam_prep.practices.create", Name: "Create Exam Prep Practice", Description: "Create an exam prep practice (optional catalog course, unit, or lesson parent; references question_sets)", GroupName: "Exam Prep"}, - {Key: "exam_prep.practices.list", Name: "List Exam Prep Practices", Description: "List exam prep practices globally or unlinked only", GroupName: "Exam Prep"}, - {Key: "exam_prep.practices.list_by_catalog_course", Name: "List Exam Prep Practices by Catalog Course", Description: "List practices for an exam prep catalog course", GroupName: "Exam Prep"}, - {Key: "exam_prep.practices.list_by_unit", Name: "List Exam Prep Practices by Unit", Description: "List practices for an exam prep unit", GroupName: "Exam Prep"}, - {Key: "exam_prep.practices.list_by_lesson", Name: "List Exam Prep Practices by Lesson", Description: "List practices for an exam prep lesson", GroupName: "Exam Prep"}, - {Key: "exam_prep.practices.get", Name: "Get Exam Prep Practice", Description: "Get an exam prep practice by ID", GroupName: "Exam Prep"}, - {Key: "exam_prep.practices.update", Name: "Update Exam Prep Practice", Description: "Update an exam prep practice", GroupName: "Exam Prep"}, - {Key: "exam_prep.practices.delete", Name: "Delete Exam Prep Practice", Description: "Delete an exam prep practice", GroupName: "Exam Prep"}, + // Makeup course hierarchy; exam_prep permission keys remain stable for existing clients. + {Key: "exam_prep.catalog_courses.create", Name: "Create Makeup Course", Description: "Create a top-level makeup course", GroupName: "Makeup Courses"}, + {Key: "exam_prep.catalog_courses.list", Name: "List Makeup Courses", Description: "List makeup courses", GroupName: "Makeup Courses"}, + {Key: "exam_prep.catalog_courses.get", Name: "Get Makeup Course", Description: "Get a makeup course by ID", GroupName: "Makeup Courses"}, + {Key: "exam_prep.catalog_courses.update", Name: "Update Makeup Course", Description: "Update a makeup course", GroupName: "Makeup Courses"}, + {Key: "exam_prep.catalog_courses.delete", Name: "Delete Makeup Course", Description: "Delete a makeup course", GroupName: "Makeup Courses"}, + {Key: "exam_prep.catalog_courses.reorder", Name: "Reorder Makeup Courses", Description: "Set global order of makeup courses", GroupName: "Makeup Courses"}, + {Key: "exam_prep.units.create", Name: "Create Course Chapter", Description: "Create a unit under a catalog course", GroupName: "Makeup Courses"}, + {Key: "exam_prep.units.list", Name: "List Course Chapters", Description: "List units under a catalog course", GroupName: "Makeup Courses"}, + {Key: "exam_prep.units.get", Name: "Get Course Chapter", Description: "Get a course chapter by ID", GroupName: "Makeup Courses"}, + {Key: "exam_prep.units.update", Name: "Update Course Chapter", Description: "Update a course chapter", GroupName: "Makeup Courses"}, + {Key: "exam_prep.units.delete", Name: "Delete Course Chapter", Description: "Delete a course chapter", GroupName: "Makeup Courses"}, + {Key: "exam_prep.units.reorder", Name: "Reorder Course Chapters", Description: "Reorder units within a catalog course", GroupName: "Makeup Courses"}, + {Key: "exam_prep.modules.create", Name: "Create Lesson Container", Description: "Create a module under a course chapter", GroupName: "Makeup Courses"}, + {Key: "exam_prep.modules.list", Name: "List Lesson Containers", Description: "List modules under a unit", GroupName: "Makeup Courses"}, + {Key: "exam_prep.modules.get", Name: "Get Lesson Container", Description: "Get a lesson container by ID", GroupName: "Makeup Courses"}, + {Key: "exam_prep.modules.update", Name: "Update Lesson Container", Description: "Update a lesson container", GroupName: "Makeup Courses"}, + {Key: "exam_prep.modules.delete", Name: "Delete Lesson Container", Description: "Delete a lesson container", GroupName: "Makeup Courses"}, + {Key: "exam_prep.modules.reorder", Name: "Reorder Lesson Containers", Description: "Reorder modules within a unit", GroupName: "Makeup Courses"}, + {Key: "exam_prep.lessons.create", Name: "Create Makeup Lesson", Description: "Create a lesson under a course chapter module", GroupName: "Makeup Courses"}, + {Key: "exam_prep.lessons.list_by_module", Name: "List Makeup Lessons by Module", Description: "List lessons under a course chapter module", GroupName: "Makeup Courses"}, + {Key: "exam_prep.lessons.get", Name: "Get Makeup Lesson", Description: "Get an exam prep lesson by ID", GroupName: "Makeup Courses"}, + {Key: "exam_prep.lessons.update", Name: "Update Makeup Lesson", Description: "Update an exam prep lesson", GroupName: "Makeup Courses"}, + {Key: "exam_prep.lessons.delete", Name: "Delete Makeup Lesson", Description: "Delete an exam prep lesson", GroupName: "Makeup Courses"}, + {Key: "exam_prep.lessons.reorder", Name: "Reorder Makeup Lessons", Description: "Reorder lessons within a course chapter module", GroupName: "Makeup Courses"}, + {Key: "exam_prep.practices.create", Name: "Create Artistry Practice", Description: "Create an artistry practice (optional catalog course, unit, or lesson parent; references question_sets)", GroupName: "Makeup Courses"}, + {Key: "exam_prep.practices.list", Name: "List Artistry Practices", Description: "List artistry practices globally or unlinked only", GroupName: "Makeup Courses"}, + {Key: "exam_prep.practices.list_by_catalog_course", Name: "List Artistry Practices by Catalog Course", Description: "List practices for a makeup course", GroupName: "Makeup Courses"}, + {Key: "exam_prep.practices.list_by_unit", Name: "List Artistry Practices by Unit", Description: "List practices for a course chapter", GroupName: "Makeup Courses"}, + {Key: "exam_prep.practices.list_by_lesson", Name: "List Artistry Practices by Lesson", Description: "List practices for an exam prep lesson", GroupName: "Makeup Courses"}, + {Key: "exam_prep.practices.get", Name: "Get Artistry Practice", Description: "Get an artistry practice by ID", GroupName: "Makeup Courses"}, + {Key: "exam_prep.practices.update", Name: "Update Artistry Practice", Description: "Update an artistry practice", GroupName: "Makeup Courses"}, + {Key: "exam_prep.practices.delete", Name: "Delete Artistry Practice", Description: "Delete an artistry practice", GroupName: "Makeup Courses"}, // Modules (LMS, under a course) {Key: "modules.create", Name: "Create Module", Description: "Create a module in a course", GroupName: "Modules"}, diff --git a/internal/services/team/password_reset.go b/internal/services/team/password_reset.go index 9c171842..44a3d7a6 100644 --- a/internal/services/team/password_reset.go +++ b/internal/services/team/password_reset.go @@ -37,7 +37,10 @@ func (s *Service) SendPasswordReset(ctx context.Context, email string) error { return domain.ErrTeamMemberPendingInvitation } - otpCode := helpers.GenerateOTP() + otpCode, err := helpers.GenerateOTP() + if err != nil { + return err + } resetLink := buildTeamPasswordResetLink(baseURL, email, otpCode) rendered, err := s.emailTemplateSvc.Render(ctx, domain.EmailTemplateSlugPasswordReset, map[string]any{ diff --git a/internal/services/transaction/service.go b/internal/services/transaction/service.go index 79fec905..dcd135af 100644 --- a/internal/services/transaction/service.go +++ b/internal/services/transaction/service.go @@ -20,12 +20,12 @@ var ( type Service struct { transactionStore ports.TransactionStore - userSvc user.Service + userSvc *user.Service } func NewService( transactionStore ports.TransactionStore, - userSvc user.Service, + userSvc *user.Service, ) *Service { return &Service{ transactionStore: transactionStore, @@ -33,142 +33,9 @@ func NewService( } } -// func (s *Service) CreateShopTransaction(ctx context.Context, transaction domain.CreateShopTransaction) (domain.ShopTransaction, error) { -// return s.transactionStore.CreateShopTransaction(ctx, transaction) -// } -// func (s *Service) GetShopTransactionByID(ctx context.Context, id int64) (domain.ShopTransactionDetail, error) { -// return s.transactionStore.GetShopTransactionByID(ctx, id) -// } -// func (s *Service) GetAllShopTransactions(ctx context.Context, filter domain.ShopTransactionFilter) ([]domain.ShopTransactionDetail, error) { -// return s.transactionStore.GetAllShopTransactions(ctx, filter) -// } -// func (s *Service) GetShopTransactionByBranch(ctx context.Context, id int64) ([]domain.ShopTransactionDetail, error) { -// return s.transactionStore.GetShopTransactionByBranch(ctx, id) -// } -// func (s *Service) UpdateShopTransactionVerified(ctx context.Context, id int64, verified bool, approvedBy int64, role domain.Role, companyID domain.ValidInt64, branchID domain.ValidInt64) error { -// // TODO: Move this into a service role verification service -// // Checks to make sure only the same company and branch can modify this -// transaction, err := s.GetShopTransactionByID(ctx, id) -// if role != domain.RoleSuperAdmin { -// if !companyID.Valid || companyID.Value != transaction.CompanyID { -// // s.logger.Error("Failed to parse UpdateTransactionVerified request", "error", err) -// return fmt.Errorf("user cannot modify another companies data") -// } -// if role == domain.RoleCashier { -// if !branchID.Valid || branchID.Value != transaction.BranchID { -// // h.logger.Error("Failed to parse UpdateTransactionVerified request", "error", "Unauthorized") -// return fmt.Errorf("user cannot modify another companies data") -// } -// } -// } - -// if err != nil { -// return err -// } -// // switch transaction.Type { -// // case domain.TRANSACTION_BET: -// // if verified { -// // bet, err := s.GetShopBetByShopTransactionID(ctx, transaction.ID) - -// // if err != nil { -// // return err -// // } - -// // var firstEvent time.Time = bet.Outcomes[0].Expires -// // for _, outcome := range bet.Outcomes { -// // if outcome.Expires.Before(firstEvent) { -// // firstEvent = outcome.Expires -// // } -// // } - -// // fmt.Printf("\n\n Shop bet expire %v - now %v \n\n", firstEvent, time.Now().UTC()) -// // if firstEvent.Before(time.Now()) { -// // return ErrShopBetHasExpired -// // } - -// // } - -// // case domain.TRANSACTION_DEPOSIT: -// // if !verified { -// // // TODO: Figure out what to do here? Should i return the money or verify the faulty verify -// // return ErrDepositCannotBeUnverified -// // } - -// // deposit, err := s.GetShopDepositByShopTransactionID(ctx, transaction.ID) -// // if err != nil { -// // return err -// // } -// // customerWallet, err := s.walletSvc.GetCustomerWallet(ctx, deposit.CustomerID) - -// // if err != nil { -// // return ErrUserHasNoCustomerWallet -// // } - -// // transfer, err := s.walletSvc.TransferToWallet(ctx, -// // deposit.BranchWalletID, customerWallet.RegularID, transaction.Amount, domain.TRANSFER_DIRECT, domain.ValidInt64{ -// // Value: transaction.UserID, -// // Valid: true, -// // }, -// // fmt.Sprintf("Transferred %v to customer wallet due to shop deposit", transaction.Amount), -// // ) - -// // if err != nil { -// // return err -// // } - -// // err = s.UpdateShopDepositTransferID(ctx, deposit.ID, domain.ValidInt64{ -// // Value: transfer.ID, -// // Valid: true, -// // }) - -// // if err != nil { -// // return err -// // } -// // } - -// return s.transactionStore.UpdateShopTransactionVerified(ctx, id, verified, approvedBy) -// } - func (s *Service) GetBranchByRole(ctx context.Context, branchID *int64, role domain.Role, userID int64, userCompanyID domain.ValidInt64) (*int64, *int64, error) { - // var branchID int64 - // var companyID int64 - - switch role { - case domain.RoleAdmin, domain.RoleSuperAdmin: - if branchID == nil { - // h.logger.Error("CashoutReq Branch ID is required for this user role") - return nil, nil, ErrBranchRequiredForRole - } - // branch, err := s.branchSvc.GetBranchByID(ctx, *branchID) - // if err != nil { - // // h.logger.Error("CashoutReq no branches") - // return nil, nil, err - // } - - // Check if the user has access to the company - if role != domain.RoleSuperAdmin { - // if userCompanyID.Valid && userCompanyID.Value != branch.CompanyID { - // return nil, nil, ErrUnauthorizedCompanyID - // } - } - - // if role == domain.RoleBranchManager { - // // if branch.BranchManagerID != userID { - // // return nil, nil, ErrUnauthorizedBranchManager - // // } - // } - - // return &branch.ID, &branch.CompanyID, nil - case domain.RoleInstructor: - // branch, err := s.branchSvc.GetBranchByCashier(ctx, userID) - // if err != nil { - // // h.logger.Error("CashoutReq failed, branch id invalid") - // return nil, nil, ErrInvalidBranchID - // } - // return &branch.ID, &branch.CompanyID, nil - default: - return nil, nil, ErrCustomerRoleNotAuthorized + if (role == domain.RoleAdmin || role == domain.RoleSuperAdmin) && branchID == nil { + return nil, nil, ErrBranchRequiredForRole } - return nil, nil, ErrCustomerRoleNotAuthorized } diff --git a/internal/services/user/common.go b/internal/services/user/common.go index e9d24a79..9bfad608 100644 --- a/internal/services/user/common.go +++ b/internal/services/user/common.go @@ -20,7 +20,10 @@ func (s *Service) ResendOtp( return err } - otpCode := helpers.GenerateOTP() + otpCode, err := helpers.GenerateOTP() + if err != nil { + return err + } otp, err := s.otpStore.GetOtp(ctx, user.ID) if err != nil { @@ -60,7 +63,10 @@ func (s *Service) ResendOtp( } func (s *Service) SendOtp(ctx context.Context, userID int64, sentTo string, otpFor domain.OtpFor, medium domain.OtpMedium, provider domain.SMSProvider) error { - otpCode := helpers.GenerateOTP() + otpCode, err := helpers.GenerateOTP() + if err != nil { + return err + } firstName := "" if userID > 0 { diff --git a/internal/web_server/handlers/admin_export.go b/internal/web_server/handlers/admin_export.go index 2874b492..968e651d 100644 --- a/internal/web_server/handlers/admin_export.go +++ b/internal/web_server/handlers/admin_export.go @@ -15,14 +15,13 @@ import ( const exportRequestTimeout = 10 * time.Minute -// exportRequestContext keeps DB work alive after the handler returns while the CSV body streams. -func exportRequestContext(c *fiber.Ctx) context.Context { +// exportRequestContext bounds batched DB reads while the CSV response is buffered. +func exportRequestContext(c *fiber.Ctx) (context.Context, context.CancelFunc) { base := c.UserContext() if base == nil { base = context.Background() } - ctx, _ := context.WithTimeout(context.WithoutCancel(base), exportRequestTimeout) - return ctx + return context.WithTimeout(base, exportRequestTimeout) } func (h *Handler) csvStreamErrorLogger(resource string) func(error) { @@ -130,7 +129,8 @@ func (h *Handler) ExportAdminPaymentsCSV(c *fiber.Ctx) error { "payment_method", "status", "paid_at", "expires_at", "created_at", "updated_at", } - ctx := exportRequestContext(c) + ctx, cancel := exportRequestContext(c) + defer cancel() return h.writeCSVExport(c, "payments", exportFilename("payments"), headers, func(offset, limit int32) ([][]string, error) { filter.Limit = limit filter.Offset = offset @@ -200,7 +200,8 @@ func (h *Handler) ExportUsersCSV(c *fiber.Ctx) error { "profile_completed", "created_at", "updated_at", "last_login", } - ctx := exportRequestContext(c) + ctx, cancel := exportRequestContext(c) + defer cancel() batchSize := int32(response.ExportBatchSize) return h.writeCSVExport(c, "users", exportFilename("users"), headers, func(offset, limit int32) ([][]string, error) { filter.Page = int64(offset / batchSize) @@ -281,7 +282,8 @@ func (h *Handler) ExportActivityLogsCSV(c *fiber.Ctx) error { "ip_address", "user_agent", "created_at", } - ctx := exportRequestContext(c) + ctx, cancel := exportRequestContext(c) + defer cancel() return h.writeCSVExport(c, "activity-logs", exportFilename("activity-logs"), headers, func(offset, limit int32) ([][]string, error) { filter.Limit = limit filter.Offset = offset @@ -342,7 +344,8 @@ func (h *Handler) ExportUserSubscriptionsCSV(c *fiber.Ctx) error { "cancelled_at", "created_at", "updated_at", } - ctx := exportRequestContext(c) + ctx, cancel := exportRequestContext(c) + defer cancel() return h.writeCSVExport(c, "subscriptions", exportFilename("subscriptions"), headers, func(offset, limit int32) ([][]string, error) { filter.Limit = limit filter.Offset = offset @@ -395,7 +398,8 @@ func (h *Handler) ExportUserSubscriptionsCSV(c *fiber.Ctx) error { // @Failure 500 {object} domain.ErrorResponse "Internal server error" func (h *Handler) ExportTeamMembersCSV(c *fiber.Ctx) error { filter := parseTeamMemberListFilter(c) - ctx := exportRequestContext(c) + ctx, cancel := exportRequestContext(c) + defer cancel() headers := []string{ "id", "first_name", "last_name", "email", "phone_number", diff --git a/internal/web_server/handlers/analytics_field_normalize.go b/internal/web_server/handlers/analytics_field_normalize.go index ebf2cbd1..f431586b 100644 --- a/internal/web_server/handlers/analytics_field_normalize.go +++ b/internal/web_server/handlers/analytics_field_normalize.go @@ -9,18 +9,10 @@ import ( const analyticsOtherLabel = "OTHER" -// Default codes when a stored profile value is empty, OTHER, unknown, or not in field_options. -var analyticsFieldDefaults = map[string]string{ - domain.ProfileFieldAgeGroup: "25_34", - domain.ProfileFieldOccupation: "STUDENTS", - domain.ProfileFieldEthiopiaRegions: "ADDIS_ABABA", - domain.ProfileFieldEducationLevel: "HIGH_SCHOOL", - domain.ProfileFieldLearningGoal: "EVERYDAY_CONVERSATION", - domain.ProfileFieldLanguageChallange: "PRONUNCIATION", - domain.ProfileFieldCountry: "ET", -} +// Do not infer demographic or learning preferences from missing profile data. +var analyticsFieldDefaults = map[string]string{} -const analyticsKnowledgeLevelDefault = "BEGINNER" +const analyticsKnowledgeLevelDefault = "UNASSIGNED" // analyticsProfileFieldKeys are user-profile breakdowns validated against field_options. var analyticsProfileFieldKeys = []string{ @@ -74,13 +66,12 @@ func analyticsDefaultForField(fieldKey string) string { return "" } -// resolveAnalyticsFieldLabel maps a stored user value to a static field_options code. -// Empty / "unknown" / OTHER / values not in the option list become the field default -// (never OTHER — analytics should not surface an Other bucket). +// resolveAnalyticsFieldLabel keeps known codes and custom values distinct. +// Missing values use an unassigned bucket unless the caller supplies a fallback. func resolveAnalyticsFieldLabel(raw string, options []domain.ProfileFieldOption, defaultCode string) string { fallback := strings.TrimSpace(defaultCode) if fallback == "" { - fallback = analyticsOtherLabel + fallback = "UNASSIGNED" } trimmed := strings.TrimSpace(raw) @@ -104,7 +95,7 @@ func resolveAnalyticsFieldLabel(raw string, options []domain.ProfileFieldOption, return code } } - return fallback + return trimmed } func collapseAnalyticsLabelCounts( diff --git a/internal/web_server/handlers/analytics_field_normalize_test.go b/internal/web_server/handlers/analytics_field_normalize_test.go index 881964cd..5a18a72c 100644 --- a/internal/web_server/handlers/analytics_field_normalize_test.go +++ b/internal/web_server/handlers/analytics_field_normalize_test.go @@ -27,9 +27,9 @@ func TestResolveAnalyticsFieldLabel(t *testing.T) { {"Ethiopia", "ET"}, {"EVERYDAY_CONVERSATION", "EVERYDAY_CONVERSATION"}, {"Everyday conversation", "EVERYDAY_CONVERSATION"}, - {"Learn to Speak English", "ET"}, - {"Nurse", "ET"}, - {"addis abeba", "ET"}, + {"Learn to Speak English", "Learn to Speak English"}, + {"Nurse", "Nurse"}, + {"addis abeba", "addis abeba"}, {"Addis Ababa", "ADDIS_ABABA"}, } @@ -59,7 +59,8 @@ func TestCollapseAnalyticsLabelCounts(t *testing.T) { got := collapseAnalyticsLabelCounts(rows, options, "PRONUNCIATION") want := map[string]int64{ "ET": 12, - "PRONUNCIATION": 13, // 3 Pronunciation + 5 unknown + 1 Grammar + 4 OTHER + "PRONUNCIATION": 12, // 3 Pronunciation + 5 unknown + 4 OTHER + "Grammar": 1, } if len(got) != len(want) { t.Fatalf("got %d rows, want %d: %+v", len(got), len(want), got) @@ -148,3 +149,18 @@ func TestCollapseGenderAnalytics(t *testing.T) { } } } + +func TestMakeupAnalyticsPreservesCustomValuesAndMissingData(t *testing.T) { + options := []domain.ProfileFieldOption{{Code: "PERSONAL_MAKEUP", Label: "Develop personal makeup skills"}} + rows := []domain.AnalyticsLabelCount{{Label: "PERSONAL_MAKEUP", Count: 2}, {Label: "", Count: 3}, {Label: "Custom artistry goal", Count: 1}} + got := collapseAnalyticsField(rows, domain.ProfileFieldLearningGoal, map[string][]domain.ProfileFieldOption{domain.ProfileFieldLearningGoal: options}) + want := map[string]int64{"PERSONAL_MAKEUP": 2, "UNASSIGNED": 3, "Custom artistry goal": 1} + if len(got) != len(want) { + t.Fatalf("unexpected rows: %+v", got) + } + for _, row := range got { + if want[row.Label] != row.Count { + t.Fatalf("unexpected row: %+v", row) + } + } +} diff --git a/internal/web_server/handlers/exam_prep_practice_handler.go b/internal/web_server/handlers/exam_prep_practice_handler.go index 0fd5a122..9827e425 100644 --- a/internal/web_server/handlers/exam_prep_practice_handler.go +++ b/internal/web_server/handlers/exam_prep_practice_handler.go @@ -672,14 +672,14 @@ func (h *Handler) ListExamPrepPracticesByUnit(c *fiber.Ctx) error { // When offset is omitted, offset defaults to 0. func parseOptionalExamPrepPracticePagination(c *fiber.Ctx) (limit, offset int32, err error) { if ls := c.Query("limit"); ls != "" { - n, parseErr := strconv.Atoi(ls) + n, parseErr := strconv.ParseInt(ls, 10, 32) if parseErr != nil || n < 1 { return 0, 0, fmt.Errorf("limit must be a positive integer") } limit = int32(n) } if os := c.Query("offset"); os != "" { - n, parseErr := strconv.Atoi(os) + n, parseErr := strconv.ParseInt(os, 10, 32) if parseErr != nil || n < 0 { return 0, 0, fmt.Errorf("offset must be a non-negative integer") } diff --git a/internal/web_server/handlers/practice_pagination_test.go b/internal/web_server/handlers/practice_pagination_test.go new file mode 100644 index 00000000..19f507fd --- /dev/null +++ b/internal/web_server/handlers/practice_pagination_test.go @@ -0,0 +1,39 @@ +package handlers + +import ( + "github.com/gofiber/fiber/v2" + "net/http/httptest" + "testing" +) + +func TestOptionalPracticePagination(t *testing.T) { + for _, tc := range []struct { + query string + limit, offset int32 + invalid bool + }{ + {"", 0, 0, false}, {"limit=10&offset=20", 10, 20, false}, + {"limit=2147483647&offset=2147483647", 2147483647, 2147483647, false}, + {"limit=0", 0, 0, true}, {"limit=-1", 0, 0, true}, {"limit=no", 0, 0, true}, + {"limit=2147483648", 0, 0, true}, {"offset=2147483648", 0, 0, true}, {"offset=-1", 0, 0, true}, + } { + t.Run(tc.query, func(t *testing.T) { + app := fiber.New() + app.Get("/", func(c *fiber.Ctx) error { + limit, offset, err := parseOptionalExamPrepPracticePagination(c) + if (err != nil) != tc.invalid { + t.Errorf("error = %v, invalid = %v", err, tc.invalid) + } + if err == nil && (limit != tc.limit || offset != tc.offset) { + t.Errorf("got (%d, %d), want (%d, %d)", limit, offset, tc.limit, tc.offset) + } + return c.SendStatus(200) + }) + res, err := app.Test(httptest.NewRequest("GET", "/?"+tc.query, nil)) + if err != nil { + t.Fatal(err) + } + res.Body.Close() + }) + } +} diff --git a/internal/web_server/response/res.go b/internal/web_server/response/res.go index 16960699..92ae63d9 100644 --- a/internal/web_server/response/res.go +++ b/internal/web_server/response/res.go @@ -14,19 +14,19 @@ const ( ) type APIResponse struct { - Status Status `json:"status"` - Message string `json:"message"` - Data interface{} `json:"data,omitempty" swaggerignore:"true"` + Status Status `json:"status"` + Message string `json:"message"` + Data any `json:"data,omitempty" swaggerignore:"true"` // Optional endpoint-specific metadata; omitted when there is no metadata. - Metadata interface{} `json:"metadata,omitempty" swaggertype:"object"` - Page *int `json:"page,omitempty"` - Total *int `json:"total,omitempty"` - Timestamp time.Time `json:"timestamp"` + Metadata any `json:"metadata,omitempty" swaggertype:"object"` + Page *int `json:"page,omitempty"` + Total *int `json:"total,omitempty"` + Timestamp time.Time `json:"timestamp"` } func NewAPIResponse( status Status, message string, - data interface{}, metadata interface{}, + data any, metadata any, page *int, total *int, ) APIResponse { @@ -40,25 +40,19 @@ func NewAPIResponse( Total: total, } } -func WriteJSON(c *fiber.Ctx, status int, message string, data, metadata interface{}) error { - var apiStatus Status +func WriteJSON(c *fiber.Ctx, status int, message string, data, metadata any) error { + return writeJSON(c, status, message, data, metadata, nil, nil) +} +func WritePaginatedJSON(c *fiber.Ctx, status int, message string, data, metadata any, page int, total int) error { + return writeJSON(c, status, message, data, metadata, &page, &total) +} + +func writeJSON(c *fiber.Ctx, status int, message string, data, metadata any, page, total *int) error { + apiStatus := Error if status >= 200 && status <= 299 { apiStatus = Success - } else { - apiStatus = Error } - apiRes := NewAPIResponse(apiStatus, message, data, metadata, nil, nil) - - return c.Status(status).JSON(apiRes) -} -func WritePaginatedJSON(c *fiber.Ctx, status int, message string, data, metadata interface{}, page int, total int) error { - var apiStatus Status - if status >= 200 && status <= 299 { - apiStatus = Success - } else { - apiStatus = Error - } - apiRes := NewAPIResponse(apiStatus, message, data, metadata, &page, &total) + apiRes := NewAPIResponse(apiStatus, message, data, metadata, page, total) return c.Status(status).JSON(apiRes) } diff --git a/internal/web_server/response/res_test.go b/internal/web_server/response/res_test.go new file mode 100644 index 00000000..8d7763a0 --- /dev/null +++ b/internal/web_server/response/res_test.go @@ -0,0 +1,53 @@ +package response + +import ( + "encoding/json" + "fmt" + "github.com/gofiber/fiber/v2" + "net/http/httptest" + "testing" +) + +func TestResponseEnvelope(t *testing.T) { + for _, status := range []int{200, 299, 300, 400, 500} { + for _, paginated := range []bool{false, true} { + t.Run(fmt.Sprintf("%d/paginated=%v", status, paginated), func(t *testing.T) { + app := fiber.New() + app.Get("/", func(c *fiber.Ctx) error { + if paginated { + return WritePaginatedJSON(c, status, "result", []string{}, nil, 0, 0) + } + return WriteJSON(c, status, "result", []string{}, nil) + }) + res, err := app.Test(httptest.NewRequest("GET", "/", nil)) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + var body map[string]json.RawMessage + if err := json.NewDecoder(res.Body).Decode(&body); err != nil { + t.Fatal(err) + } + wantStatus := `"error"` + if status < 300 { + wantStatus = `"success"` + } + if res.StatusCode != status || string(body["status"]) != wantStatus { + t.Fatalf("status %d, body %s", res.StatusCode, body["status"]) + } + if _, ok := body["metadata"]; ok { + t.Error("nil metadata should be omitted") + } + for _, key := range []string{"page", "total"} { + raw, ok := body[key] + if ok != paginated || (paginated && string(raw) != "0") { + t.Errorf("%s = %s, present=%v", key, raw, ok) + } + } + if len(body["timestamp"]) == 0 { + t.Error("missing timestamp") + } + }) + } + } +} diff --git a/static/demo/course-cover.svg b/static/demo/course-cover.svg index 4092fdf5..8b60194c 100644 --- a/static/demo/course-cover.svg +++ b/static/demo/course-cover.svg @@ -1,9 +1,21 @@ - - - - - - - - Learn something new with Rezina + + Makeup artistry academy + Black academy cover with an illustrated makeup brush, a powder palette, and makeup artistry lettering. + + + REZINA ACADEMY + Makeup + Artistry + + FOUNDATIONS / BRIDAL / EDITORIAL + + + + + + + + + +