From c04440914cc4f3987bd52e755b8ebedd72408d98 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Wed, 28 Oct 2026 17:51:56 +0300 Subject: [PATCH] Enforce LMS subscriptions and add configurable referral commissions --- README.md | 17 + db/migrations/000002_referrals.down.sql | 8 + db/migrations/000002_referrals.up.sql | 87 +++++ db/query/referrals.sql | 50 +++ db/query/subscriptions.sql | 11 +- db/tests/referrals.test.cjs | 77 +++++ docs/referral-system.md | 80 +++++ gen/db/models.go | 49 +++ gen/db/referrals.sql.go | 246 ++++++++++++++ gen/db/subscriptions.sql.go | 11 +- internal/domain/referrals.go | 22 ++ internal/domain/subscriptions.go | 3 - internal/domain/user.go | 22 +- internal/repository/user.go | 25 +- internal/services/referrals/service.go | 137 ++++++++ internal/services/referrals/service_test.go | 87 +++++ internal/services/user/register.go | 10 + .../web_server/content_access_middleware.go | 34 +- internal/web_server/handlers/handlers.go | 4 +- .../web_server/handlers/referal_handlers.go | 315 +++++++----------- .../web_server/handlers/referrals_test.go | 43 +++ internal/web_server/handlers/user.go | 1 + internal/web_server/middleware.go | 35 +- internal/web_server/routes.go | 62 ++-- .../web_server/subscription_access_test.go | 54 +++ 25 files changed, 1210 insertions(+), 280 deletions(-) create mode 100644 db/migrations/000002_referrals.down.sql create mode 100644 db/migrations/000002_referrals.up.sql create mode 100644 db/query/referrals.sql create mode 100644 db/tests/referrals.test.cjs create mode 100644 docs/referral-system.md create mode 100644 gen/db/referrals.sql.go create mode 100644 internal/domain/referrals.go create mode 100644 internal/services/referrals/service.go create mode 100644 internal/services/referrals/service_test.go create mode 100644 internal/web_server/handlers/referrals_test.go create mode 100644 internal/web_server/subscription_access_test.go diff --git a/README.md b/README.md index 13475b73..fdf2558a 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,23 @@ Golang API for **Rezina**, a remedial and makeup education LMS. It serves the le --- +Referral codes, admin-configured commissions, wallet APIs, and rollout instructions are documented in [Referral system](docs/referral-system.md). + +## Subscription access + +Learning content under `/api/v1/exam-prep` uses the EDUCATION subscription. +Student requests for lessons, practices, assessment collections, practice questions, +completion, and video engagement require an active subscription whose start date has +arrived and whose expiry date is in the future. Missing access returns HTTP 403. +Individual free lessons and practices remain accessible, provided all their ancestors +are free. Content collections require a subscription because they can contain premium +descendants. Catalog course, unit, and module browsing remains available for discovery. +Existing staff and OPEN_LEARNER exemptions are preserved. + +Checkout uses `/api/v1/payments/subscribe`; clients can inspect access through +`/api/v1/subscriptions/status` and `/api/v1/subscriptions/me`. These changes enforce +existing plans and payments; they do not add automatic recurring gateway charges. + ## Architecture Layered layout (ports & adapters style): diff --git a/db/migrations/000002_referrals.down.sql b/db/migrations/000002_referrals.down.sql new file mode 100644 index 00000000..ced7a34b --- /dev/null +++ b/db/migrations/000002_referrals.down.sql @@ -0,0 +1,8 @@ +DROP TRIGGER IF EXISTS credit_referral_commission ON payments; +DROP FUNCTION IF EXISTS credit_referral_commission(); +DROP TRIGGER IF EXISTS validate_referral_attribution ON user_referrals; +DROP FUNCTION IF EXISTS validate_referral_attribution(); +DROP TABLE IF EXISTS referral_commissions; +DROP TABLE IF EXISTS referral_settings; +DROP TABLE IF EXISTS user_referrals; +DROP TABLE IF EXISTS referral_codes; diff --git a/db/migrations/000002_referrals.up.sql b/db/migrations/000002_referrals.up.sql new file mode 100644 index 00000000..3e9ea783 --- /dev/null +++ b/db/migrations/000002_referrals.up.sql @@ -0,0 +1,87 @@ +CREATE TABLE referral_codes ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE, + code VARCHAR(24) NOT NULL UNIQUE CHECK (code ~ '^[A-Z0-9]{16}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE TABLE user_referrals ( + id BIGSERIAL PRIMARY KEY, + referrer_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + referred_user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE, + referral_code_id BIGINT NOT NULL REFERENCES referral_codes(id) ON DELETE CASCADE, + conversion_payment_id BIGINT UNIQUE REFERENCES payments(id) ON DELETE RESTRICT, + converted_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (referrer_id <> referred_user_id) +); +CREATE INDEX user_referrals_referrer_id_idx ON user_referrals(referrer_id, created_at DESC); + +-- Admin-managed percentage. Zero disables commissions until an admin configures it. +CREATE TABLE referral_settings ( + id BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (id), + commission_percent NUMERIC(5,2) NOT NULL DEFAULT 0 CHECK (commission_percent BETWEEN 0 AND 100), + updated_by BIGINT REFERENCES team_members(id) ON DELETE SET NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); +INSERT INTO referral_settings (id) VALUES (TRUE); +CREATE TABLE referral_commissions ( + id BIGSERIAL PRIMARY KEY, + referral_id BIGINT NOT NULL UNIQUE REFERENCES user_referrals(id) ON DELETE RESTRICT, + referrer_id BIGINT NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + payment_id BIGINT NOT NULL UNIQUE REFERENCES payments(id) ON DELETE RESTRICT, + commission_percent NUMERIC(5,2) NOT NULL, + amount NUMERIC(12,2) NOT NULL CHECK (amount > 0), + currency VARCHAR(3) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + reversed_at TIMESTAMPTZ +); +CREATE INDEX referral_commissions_wallet_idx ON referral_commissions(referrer_id, currency); + +CREATE FUNCTION validate_referral_attribution() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + PERFORM 1 FROM users WHERE id = NEW.referred_user_id FOR UPDATE; + IF EXISTS (SELECT 1 FROM payments WHERE user_id = NEW.referred_user_id AND status = 'SUCCESS' AND amount > 0) THEN + RAISE EXCEPTION 'Referral must be applied before the first payment' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER validate_referral_attribution BEFORE INSERT ON user_referrals +FOR EACH ROW EXECUTE FUNCTION validate_referral_attribution(); + +CREATE FUNCTION credit_referral_commission() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + referral user_referrals%ROWTYPE; + rate NUMERIC(5,2); +BEGIN + -- Serializes payments and attribution for the same learner. + PERFORM 1 FROM users WHERE id = NEW.user_id FOR UPDATE; + IF NEW.status <> 'SUCCESS' THEN + UPDATE referral_commissions SET reversed_at = COALESCE(reversed_at, CURRENT_TIMESTAMP) + WHERE payment_id = NEW.id; + RETURN NEW; + END IF; + IF NEW.amount <= 0 OR NEW.plan_id IS NULL OR NEW.subscription_id IS NULL THEN + RETURN NEW; + END IF; + SELECT * INTO referral FROM user_referrals WHERE referred_user_id = NEW.user_id; + IF NOT FOUND OR NEW.created_at < referral.created_at OR referral.conversion_payment_id IS NOT NULL THEN RETURN NEW; END IF; + -- A renewal must never earn the first-payment reward, even when the rate was zero. + IF EXISTS (SELECT 1 FROM payments WHERE user_id = NEW.user_id AND id <> NEW.id + AND status = 'SUCCESS' AND amount > 0 AND subscription_id IS NOT NULL) THEN + RETURN NEW; + END IF; + -- Record the conversion even at 0%, so a later retry cannot earn a new rate. + UPDATE user_referrals SET conversion_payment_id = NEW.id, converted_at = CURRENT_TIMESTAMP + WHERE id = referral.id; + SELECT commission_percent INTO rate FROM referral_settings WHERE id = TRUE; + IF rate > 0 AND ROUND(NEW.amount * rate / 100, 2) > 0 THEN + INSERT INTO referral_commissions (referral_id, referrer_id, payment_id, commission_percent, amount, currency) + VALUES (referral.id, referral.referrer_id, NEW.id, rate, ROUND(NEW.amount * rate / 100, 2), NEW.currency) + ON CONFLICT DO NOTHING; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER credit_referral_commission AFTER INSERT OR UPDATE ON payments +FOR EACH ROW EXECUTE FUNCTION credit_referral_commission(); diff --git a/db/query/referrals.sql b/db/query/referrals.sql new file mode 100644 index 00000000..43d8a527 --- /dev/null +++ b/db/query/referrals.sql @@ -0,0 +1,50 @@ +-- name: GetReferralCode :one +SELECT code FROM referral_codes WHERE user_id = $1; + +-- name: CreateReferralCode :one +INSERT INTO referral_codes (user_id, code) +SELECT users.id, $2 FROM users WHERE users.id = $1 AND role IN ('STUDENT', 'OPEN_LEARNER') AND status = 'ACTIVE' +ON CONFLICT (user_id) DO UPDATE SET user_id = EXCLUDED.user_id +RETURNING code; + +-- name: ApplyReferralCode :execrows +INSERT INTO user_referrals (referrer_id, referred_user_id, referral_code_id) +SELECT rc.user_id, u.id, rc.id +FROM referral_codes rc JOIN users owner ON owner.id = rc.user_id +JOIN users u ON u.id = sqlc.arg('referred_user_id') +WHERE rc.code = sqlc.arg('code') AND rc.user_id <> u.id +AND owner.status = 'ACTIVE' AND owner.role IN ('STUDENT', 'OPEN_LEARNER') +AND u.role IN ('STUDENT', 'OPEN_LEARNER') +AND u.created_at >= CURRENT_TIMESTAMP - INTERVAL '7 days' +AND NOT EXISTS (SELECT 1 FROM payments p WHERE p.user_id = u.id AND p.status = 'SUCCESS' AND p.amount > 0) +ON CONFLICT (referred_user_id) DO NOTHING; + +-- name: GetReferralSummary :one +SELECT COUNT(*) AS total_referrals, +COUNT(*) FILTER (WHERE r.conversion_payment_id IS NOT NULL) AS converted_referrals +FROM user_referrals r WHERE r.referrer_id = $1; + +-- name: ListMyReferrals :many +SELECT r.id, r.created_at, +(r.conversion_payment_id IS NOT NULL) AS converted +FROM user_referrals r WHERE r.referrer_id = $1 +ORDER BY r.created_at DESC, r.id DESC +LIMIT $2 OFFSET $3; + +-- name: GetReferralSettings :one +SELECT commission_percent::text AS commission_percent, updated_at FROM referral_settings WHERE id = TRUE; + +-- name: UpdateReferralSettings :one +UPDATE referral_settings SET commission_percent = sqlc.arg('commission_percent')::numeric, +updated_by = sqlc.arg('updated_by'), updated_at = CURRENT_TIMESTAMP WHERE id = TRUE +RETURNING commission_percent::text AS commission_percent, updated_at; + +-- name: GetReferralWallet :many +SELECT currency, SUM(CASE WHEN reversed_at IS NULL THEN amount ELSE 0 END)::text AS balance +FROM referral_commissions WHERE referrer_id = $1 GROUP BY currency ORDER BY currency; + +-- name: ListReferralCommissions :many +SELECT id, payment_id, commission_percent::text AS commission_percent, +amount::text AS amount, currency, created_at, reversed_at +FROM referral_commissions WHERE referrer_id = $1 +ORDER BY created_at DESC, id DESC LIMIT $2 OFFSET $3; diff --git a/db/query/subscriptions.sql b/db/query/subscriptions.sql index a4e6084e..e01600c2 100644 --- a/db/query/subscriptions.sql +++ b/db/query/subscriptions.sql @@ -110,7 +110,7 @@ SELECT COALESCE( (SELECT us.status::text FROM user_subscriptions us WHERE us.user_id = input.user_id - AND us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP + AND us.status = 'ACTIVE' AND us.starts_at <= CURRENT_TIMESTAMP AND us.expires_at > CURRENT_TIMESTAMP ORDER BY us.expires_at DESC LIMIT 1), (SELECT us.status::text FROM user_subscriptions us WHERE us.user_id = input.user_id @@ -124,7 +124,7 @@ FROM input; SELECT COALESCE( (SELECT us.status::text FROM user_subscriptions us WHERE us.user_id = $1 - AND us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP + AND us.status = 'ACTIVE' AND us.starts_at <= CURRENT_TIMESTAMP AND us.expires_at > CURRENT_TIMESTAMP ORDER BY us.expires_at DESC LIMIT 1), (SELECT us.status::text FROM user_subscriptions us WHERE us.user_id = $1 @@ -146,7 +146,7 @@ SELECT FROM user_subscriptions us JOIN subscription_plans sp ON sp.id = us.plan_id WHERE us.user_id = $1 - AND us.status = 'ACTIVE' + AND us.status = 'ACTIVE' AND us.starts_at <= CURRENT_TIMESTAMP AND us.expires_at > CURRENT_TIMESTAMP ORDER BY us.expires_at DESC LIMIT 1; @@ -196,7 +196,7 @@ SELECT FROM user_subscriptions us JOIN subscription_plans sp ON sp.id = us.plan_id WHERE us.user_id = $1 - AND us.status = 'ACTIVE' + AND us.status = 'ACTIVE' AND us.starts_at <= CURRENT_TIMESTAMP AND us.expires_at > CURRENT_TIMESTAMP ORDER BY us.expires_at DESC; @@ -290,6 +290,7 @@ SELECT EXISTS( SELECT 1 FROM user_subscriptions WHERE user_id = $1 AND status = 'ACTIVE' + AND starts_at <= CURRENT_TIMESTAMP AND expires_at > CURRENT_TIMESTAMP ) AS has_subscription; @@ -300,7 +301,7 @@ SELECT EXISTS( JOIN subscription_plans sp ON sp.id = us.plan_id WHERE us.user_id = $1 AND sp.category = $2 - AND us.status = 'ACTIVE' + AND us.status = 'ACTIVE' AND us.starts_at <= CURRENT_TIMESTAMP AND us.expires_at > CURRENT_TIMESTAMP ) AS has_subscription; diff --git a/db/tests/referrals.test.cjs b/db/tests/referrals.test.cjs new file mode 100644 index 00000000..245e40b8 --- /dev/null +++ b/db/tests/referrals.test.cjs @@ -0,0 +1,77 @@ +// Run with REFERRAL_TEST_PACKAGE_JSON pointing at a package.json beside an installed @electric-sql/pglite. +const { createRequire } = require('node:module'); +const { readFileSync } = require('node:fs'); +const path = require('node:path'); +const assert = require('node:assert/strict'); +const load = process.env.REFERRAL_TEST_PACKAGE_JSON ? createRequire(process.env.REFERRAL_TEST_PACKAGE_JSON) : require; +const { PGlite } = load('@electric-sql/pglite'); + +(async () => { + const db = new PGlite(); + try { + await db.exec(` + CREATE TABLE users (id BIGINT PRIMARY KEY, role TEXT DEFAULT 'STUDENT', status TEXT DEFAULT 'ACTIVE', created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP); + CREATE TABLE team_members (id BIGINT PRIMARY KEY); + CREATE TABLE payments (id BIGINT PRIMARY KEY, user_id BIGINT REFERENCES users(id), plan_id BIGINT, subscription_id BIGINT, amount NUMERIC(10,2), currency VARCHAR(3), status TEXT, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP); + INSERT INTO users (id) SELECT generate_series(1,12); + INSERT INTO team_members VALUES (99); + `); + await db.exec(readFileSync(path.join(__dirname, '../migrations/000002_referrals.up.sql'), 'utf8')); + await db.exec(`INSERT INTO referral_codes (user_id,code) VALUES (1,'ABCDEF0123456789'); + UPDATE referral_settings SET commission_percent=10,updated_by=99 WHERE id=TRUE;`); + async function refer(id) { await db.query(`INSERT INTO user_referrals (referrer_id,referred_user_id,referral_code_id) VALUES (1,$1,1)`,[id]); } + async function payment(id,user,amount=100,currency='ETB',status='SUCCESS',subscription=1) { + await db.query(`INSERT INTO payments (id,user_id,plan_id,subscription_id,amount,currency,status) VALUES ($1,$2,1,$3,$4,$5,$6)`,[id,user,subscription,amount,currency,status]); + } + async function commissions() { return (await db.query('SELECT payment_id,amount::text,currency,reversed_at FROM referral_commissions ORDER BY id')).rows; } + // Exercise the application query as well as the trigger constraints. + const querySource=readFileSync(path.join(__dirname,'../query/referrals.sql'),'utf8'); + function sql(name) { + const statement=querySource.split('-- name: '+name+' :')[1].split('\n').slice(1).join('\n').split('-- name:')[0]; + return statement.replaceAll("sqlc.arg('referred_user_id')",'$1').replaceAll("sqlc.arg('code')",'$2'); + } + assert.equal((await db.query(sql('ApplyReferralCode'),[1,'ABCDEF0123456789'])).affectedRows,0,'query blocks self referral'); + assert.equal((await db.query(sql('ApplyReferralCode'),[9,'UNKNOWN0000000000'])).affectedRows,0,'query blocks unknown codes'); + await db.exec("UPDATE users SET created_at=CURRENT_TIMESTAMP-INTERVAL '8 days' WHERE id=9"); + assert.equal((await db.query(sql('ApplyReferralCode'),[9,'ABCDEF0123456789'])).affectedRows,0,'query blocks late attribution'); + assert.equal((await db.query(sql('ApplyReferralCode'),[10,'ABCDEF0123456789'])).affectedRows,1,'eligible attribution'); + assert.equal((await db.query(sql('ApplyReferralCode'),[10,'ABCDEF0123456789'])).affectedRows,0,'query blocks reassignment'); + await refer(2);await payment(1,2,123.45); + assert.equal((await commissions())[0].amount,'12.35','numeric rounding'); + await db.exec(`UPDATE payments SET status='SUCCESS' WHERE id=1;`); + assert.equal((await commissions()).length,1,'duplicate webhook must not credit twice'); + await payment(2,2,500); + assert.equal((await commissions()).length,1,'renewals must not credit'); + await db.exec(`UPDATE referral_settings SET commission_percent=25;UPDATE payments SET status='SUCCESS' WHERE id=1;`); + assert.equal((await commissions())[0].amount,'12.35','old commissions keep their rate'); + await db.exec(`UPDATE payments SET status='CANCELLED' WHERE id=1;`); + assert.ok((await commissions())[0].reversed_at,'cancelled payment reverses commission'); + await db.exec(`UPDATE payments SET status='SUCCESS' WHERE id=1;`); + assert.ok((await commissions())[0].reversed_at,'a callback cannot restore a reversed commission'); + await refer(3);await payment(3,3,80,'USD'); + assert.equal((await commissions())[1].amount,'20.00');assert.equal((await commissions())[1].currency,'USD'); + await refer(4);await db.exec(`UPDATE referral_settings SET commission_percent=0;`);await payment(4,4); + await db.exec(`UPDATE referral_settings SET commission_percent=50;UPDATE payments SET status='SUCCESS' WHERE id=4;`); + await payment(5,4); + assert.equal((await commissions()).length,2,'zero-rate conversion must never earn a later rate'); + await refer(5);await payment(6,5,100,'ETB','FAILED'); + assert.equal((await commissions()).length,2,'failed payments do not credit'); + await db.exec(`UPDATE payments SET status='SUCCESS' WHERE id=6;`); + assert.equal((await commissions()).length,3,'successful callback credits once'); + await refer(6);await payment(7,6,100,'ETB','SUCCESS',null); + assert.equal((await commissions()).length,3,'unlinked payment cannot credit'); + await db.exec(`UPDATE payments SET subscription_id=5 WHERE id=7;`); + assert.equal((await commissions()).length,4,'late subscription linkage credits'); + await refer(7);await payment(8,7,0); + assert.equal((await commissions()).length,4,'free subscription cannot credit'); + await assert.rejects(refer(1),'self referral must fail'); + await assert.rejects(refer(2),'duplicate attribution must fail'); + await payment(9,8); + await assert.rejects(refer(8),'post-payment attribution must fail'); + await assert.rejects(db.exec('UPDATE referral_settings SET commission_percent=101'),'invalid percentage must fail'); + await db.exec(readFileSync(path.join(__dirname, '../migrations/000002_referrals.down.sql'), 'utf8')); + const tables=await db.query("SELECT tablename FROM pg_tables WHERE schemaname='public' AND tablename LIKE 'referral%'"); + assert.equal(tables.rows.length,0,'down migration removes referral tables'); + console.log('Referral SQL checks passed: rounding, retries, renewals, rate changes, zero-rate conversions, reversal, currency, late linkage, eligibility, and migration rollback.'); + } finally { await db.close(); } +})().catch(error => { console.error(error); process.exitCode=1; }); diff --git a/docs/referral-system.md b/docs/referral-system.md new file mode 100644 index 00000000..bc0948e2 --- /dev/null +++ b/docs/referral-system.md @@ -0,0 +1,80 @@ +# Referral codes and commission wallets + +## Rollout + +Apply `db/migrations/000002_referrals.up.sql` with the existing migration runner before deploying the API. +Deploy the accompanying RezinaLMS-Admin changes. Administrators can then open **Settings ? Referrals** +and save a commission percentage between 0 and 100, with at most two decimal places. +The initial rate is **0%**; this disables new commission credits until configured. +The migration has a matching down migration; rolling it back deletes referral and wallet history. + +## Attribution + +Active STUDENT and OPEN_LEARNER accounts can create a stable, cryptographically random share code. +A new account can supply `referral_code` in its existing registration request. User creation and +attribution commit together; an invalid code rolls both back. Codes ignore case and surrounding whitespace. +Authenticated learners registering through other providers can instead call the apply endpoint within +seven days of account creation and before any successful positive payment. + +Each account has at most one referrer. Self referral, replacement of the original attribution, +unknown codes, inactive referrers, and attribution after payment are rejected. No referred learner +names, email addresses, or phone numbers appear in learner referral lists. + +## Commission rules + +Only the **first successful positive subscription payment** after attribution qualifies. +The payment must have both a plan and subscription linked; late subscription linkage is supported. +Free plans, pending or failed payments, and renewals do not earn commissions. +Database triggers record conversion and wallet credit in the same transaction as the payment. +Duplicate callbacks cannot add another credit. Conversion is recorded even at 0%, so increasing the +rate or replaying a callback does not retroactively reward an earlier payment. + +The rate is read at conversion and saved on the credit. Changing settings affects future conversions. +Credits use PostgreSQL numeric arithmetic and round to two decimal places. Each currency has its own +balance; amounts and percentages are returned as decimal strings. A payment leaving SUCCESS reverses +its credit; subsequent callbacks cannot restore that credit automatically. + +The wallet currently records accrued commissions. It does not send money, process withdrawal requests, +convert currencies, or spend wallet credits at checkout. External payouts need a separate settlement flow. + +## APIs + +All paths below are relative to `/api/v1`, require authentication, and return the normal `data` envelope. +Learner endpoints are available without an active subscription. + +| Method | Path | Purpose | +| --- | --- | --- | +| POST / GET | `/referrals/code` | Create or return own share code: `{ "code": "ABCDEF0123456789" }` | +| POST | `/referrals/apply` | Apply `{ "code": "ABCDEF0123456789" }`; invalid or ineligible codes return 400 | +| GET | `/referrals/me` | Own code, current commission percentage, total referrals, conversions, and wallet balances | +| GET | `/referrals?limit=20&offset=0` | Own referral history with conversion flags | +| GET | `/referrals/wallet?limit=20&offset=0` | Own balances and commission ledger, including reversals | +| GET | `/admin/referrals/settings` | Read saved commission percentage (ADMIN / SUPER_ADMIN) | +| PUT | `/admin/referrals/settings` | Save `{ "commission_percent": 10.25 }` (ADMIN / SUPER_ADMIN); audited | + +Pagination accepts limit 1?100 and non-negative offset. Commission changes do not alter subscription +prices, access duration, or existing wallet entries. Admin settings changes require no subscription. + +Example registration addition: + +```json +{ + "email": "learner@example.com", + "password": "a-secure-password", + "referral_code": "ABCDEF0123456789" +} +``` + +Clients can attach the returned code to their signup URL and pass it to registration. The API returns +codes rather than guessing a learner-app URL. + +## Verification + +Run `go test ./internal/services/referrals ./internal/repository ./internal/web_server/... ./internal/services/user ./internal/domain`. +Run `npm run build` in the sibling `RezinaLMS-Admin` repository. + +The SQL regression script uses an isolated in-memory PostgreSQL engine (PGlite), not application data. +Install `@electric-sql/pglite` in a scratch directory and set `REFERRAL_TEST_PACKAGE_JSON` to that +directory's `package.json`, then run `node db/tests/referrals.test.cjs`. It verifies the actual migration +and application attribution query, numeric rounding, duplicate callbacks, renewals, rate changes, +0% conversions, reversals, currencies, late subscription linkage, eligibility, and migration rollback. diff --git a/gen/db/models.go b/gen/db/models.go index c6f5a4c6..05b346c3 100644 --- a/gen/db/models.go +++ b/gen/db/models.go @@ -59,6 +59,13 @@ type EmailTemplate struct { UpdatedAt pgtype.Timestamptz `json:"updated_at"` } +type ExamPrepAssessmentParent struct { + QuestionSetID int64 `json:"question_set_id"` + ParentKind string `json:"parent_kind"` + ParentID int64 `json:"parent_id"` + CreatedAt pgtype.Timestamptz `json:"created_at"` +} + type ExamPrepCatalogCourse struct { ID int64 `json:"id"` Name string `json:"name"` @@ -183,6 +190,12 @@ type LevelToSubCourse struct { SubCourseID int64 `json:"sub_course_id"` } +type LmsExamPrepMigrationMap struct { + EntityKind string `json:"entity_kind"` + LegacyID int64 `json:"legacy_id"` + MigratedID int64 `json:"migrated_id"` +} + type LmsPersona struct { ID int64 `json:"id"` Name string `json:"name"` @@ -474,6 +487,32 @@ type Rating struct { UpdatedAt pgtype.Timestamptz `json:"updated_at"` } +type ReferralCode struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + Code string `json:"code"` + CreatedAt pgtype.Timestamptz `json:"created_at"` +} + +type ReferralCommission struct { + ID int64 `json:"id"` + ReferralID int64 `json:"referral_id"` + ReferrerID int64 `json:"referrer_id"` + PaymentID int64 `json:"payment_id"` + CommissionPercent pgtype.Numeric `json:"commission_percent"` + Amount pgtype.Numeric `json:"amount"` + Currency string `json:"currency"` + CreatedAt pgtype.Timestamptz `json:"created_at"` + ReversedAt pgtype.Timestamptz `json:"reversed_at"` +} + +type ReferralSetting struct { + ID bool `json:"id"` + CommissionPercent pgtype.Numeric `json:"commission_percent"` + UpdatedBy pgtype.Int8 `json:"updated_by"` + UpdatedAt pgtype.Timestamptz `json:"updated_at"` +} + type RefreshToken struct { ID int64 `json:"id"` UserID int64 `json:"user_id"` @@ -696,6 +735,16 @@ type UserPracticeProgress struct { ParentID int64 `json:"parent_id"` } +type UserReferral struct { + ID int64 `json:"id"` + ReferrerID int64 `json:"referrer_id"` + ReferredUserID int64 `json:"referred_user_id"` + ReferralCodeID int64 `json:"referral_code_id"` + ConversionPaymentID pgtype.Int8 `json:"conversion_payment_id"` + ConvertedAt pgtype.Timestamptz `json:"converted_at"` + CreatedAt pgtype.Timestamptz `json:"created_at"` +} + type UserSubscription struct { ID int64 `json:"id"` UserID int64 `json:"user_id"` diff --git a/gen/db/referrals.sql.go b/gen/db/referrals.sql.go new file mode 100644 index 00000000..a17c1757 --- /dev/null +++ b/gen/db/referrals.sql.go @@ -0,0 +1,246 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.30.0 +// source: referrals.sql + +package dbgen + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const ApplyReferralCode = `-- name: ApplyReferralCode :execrows +INSERT INTO user_referrals (referrer_id, referred_user_id, referral_code_id) +SELECT rc.user_id, u.id, rc.id +FROM referral_codes rc JOIN users owner ON owner.id = rc.user_id +JOIN users u ON u.id = $1 +WHERE rc.code = $2 AND rc.user_id <> u.id +AND owner.status = 'ACTIVE' AND owner.role IN ('STUDENT', 'OPEN_LEARNER') +AND u.role IN ('STUDENT', 'OPEN_LEARNER') +AND u.created_at >= CURRENT_TIMESTAMP - INTERVAL '7 days' +AND NOT EXISTS (SELECT 1 FROM payments p WHERE p.user_id = u.id AND p.status = 'SUCCESS' AND p.amount > 0) +ON CONFLICT (referred_user_id) DO NOTHING +` + +type ApplyReferralCodeParams struct { + ReferredUserID int64 `json:"referred_user_id"` + Code string `json:"code"` +} + +func (q *Queries) ApplyReferralCode(ctx context.Context, arg ApplyReferralCodeParams) (int64, error) { + result, err := q.db.Exec(ctx, ApplyReferralCode, arg.ReferredUserID, arg.Code) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const CreateReferralCode = `-- name: CreateReferralCode :one +INSERT INTO referral_codes (user_id, code) +SELECT users.id, $2 FROM users WHERE users.id = $1 AND role IN ('STUDENT', 'OPEN_LEARNER') AND status = 'ACTIVE' +ON CONFLICT (user_id) DO UPDATE SET user_id = EXCLUDED.user_id +RETURNING code +` + +type CreateReferralCodeParams struct { + ID int64 `json:"id"` + Code string `json:"code"` +} + +func (q *Queries) CreateReferralCode(ctx context.Context, arg CreateReferralCodeParams) (string, error) { + row := q.db.QueryRow(ctx, CreateReferralCode, arg.ID, arg.Code) + var code string + err := row.Scan(&code) + return code, err +} + +const GetReferralCode = `-- name: GetReferralCode :one +SELECT code FROM referral_codes WHERE user_id = $1 +` + +func (q *Queries) GetReferralCode(ctx context.Context, userID int64) (string, error) { + row := q.db.QueryRow(ctx, GetReferralCode, userID) + var code string + err := row.Scan(&code) + return code, err +} + +const GetReferralSettings = `-- name: GetReferralSettings :one +SELECT commission_percent::text AS commission_percent, updated_at FROM referral_settings WHERE id = TRUE +` + +type GetReferralSettingsRow struct { + CommissionPercent string `json:"commission_percent"` + UpdatedAt pgtype.Timestamptz `json:"updated_at"` +} + +func (q *Queries) GetReferralSettings(ctx context.Context) (GetReferralSettingsRow, error) { + row := q.db.QueryRow(ctx, GetReferralSettings) + var i GetReferralSettingsRow + err := row.Scan(&i.CommissionPercent, &i.UpdatedAt) + return i, err +} + +const GetReferralSummary = `-- name: GetReferralSummary :one +SELECT COUNT(*) AS total_referrals, +COUNT(*) FILTER (WHERE r.conversion_payment_id IS NOT NULL) AS converted_referrals +FROM user_referrals r WHERE r.referrer_id = $1 +` + +type GetReferralSummaryRow struct { + TotalReferrals int64 `json:"total_referrals"` + ConvertedReferrals int64 `json:"converted_referrals"` +} + +func (q *Queries) GetReferralSummary(ctx context.Context, referrerID int64) (GetReferralSummaryRow, error) { + row := q.db.QueryRow(ctx, GetReferralSummary, referrerID) + var i GetReferralSummaryRow + err := row.Scan(&i.TotalReferrals, &i.ConvertedReferrals) + return i, err +} + +const GetReferralWallet = `-- name: GetReferralWallet :many +SELECT currency, SUM(CASE WHEN reversed_at IS NULL THEN amount ELSE 0 END)::text AS balance +FROM referral_commissions WHERE referrer_id = $1 GROUP BY currency ORDER BY currency +` + +type GetReferralWalletRow struct { + Currency string `json:"currency"` + Balance string `json:"balance"` +} + +func (q *Queries) GetReferralWallet(ctx context.Context, referrerID int64) ([]GetReferralWalletRow, error) { + rows, err := q.db.Query(ctx, GetReferralWallet, referrerID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []GetReferralWalletRow + for rows.Next() { + var i GetReferralWalletRow + if err := rows.Scan(&i.Currency, &i.Balance); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const ListMyReferrals = `-- name: ListMyReferrals :many +SELECT r.id, r.created_at, +(r.conversion_payment_id IS NOT NULL) AS converted +FROM user_referrals r WHERE r.referrer_id = $1 +ORDER BY r.created_at DESC, r.id DESC +LIMIT $2 OFFSET $3 +` + +type ListMyReferralsParams struct { + ReferrerID int64 `json:"referrer_id"` + Limit int32 `json:"limit"` + Offset int32 `json:"offset"` +} + +type ListMyReferralsRow struct { + ID int64 `json:"id"` + CreatedAt pgtype.Timestamptz `json:"created_at"` + Converted interface{} `json:"converted"` +} + +func (q *Queries) ListMyReferrals(ctx context.Context, arg ListMyReferralsParams) ([]ListMyReferralsRow, error) { + rows, err := q.db.Query(ctx, ListMyReferrals, arg.ReferrerID, arg.Limit, arg.Offset) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListMyReferralsRow + for rows.Next() { + var i ListMyReferralsRow + if err := rows.Scan(&i.ID, &i.CreatedAt, &i.Converted); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const ListReferralCommissions = `-- name: ListReferralCommissions :many +SELECT id, payment_id, commission_percent::text AS commission_percent, +amount::text AS amount, currency, created_at, reversed_at +FROM referral_commissions WHERE referrer_id = $1 +ORDER BY created_at DESC, id DESC LIMIT $2 OFFSET $3 +` + +type ListReferralCommissionsParams struct { + ReferrerID int64 `json:"referrer_id"` + Limit int32 `json:"limit"` + Offset int32 `json:"offset"` +} + +type ListReferralCommissionsRow struct { + ID int64 `json:"id"` + PaymentID int64 `json:"payment_id"` + CommissionPercent string `json:"commission_percent"` + Amount string `json:"amount"` + Currency string `json:"currency"` + CreatedAt pgtype.Timestamptz `json:"created_at"` + ReversedAt pgtype.Timestamptz `json:"reversed_at"` +} + +func (q *Queries) ListReferralCommissions(ctx context.Context, arg ListReferralCommissionsParams) ([]ListReferralCommissionsRow, error) { + rows, err := q.db.Query(ctx, ListReferralCommissions, arg.ReferrerID, arg.Limit, arg.Offset) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListReferralCommissionsRow + for rows.Next() { + var i ListReferralCommissionsRow + if err := rows.Scan( + &i.ID, + &i.PaymentID, + &i.CommissionPercent, + &i.Amount, + &i.Currency, + &i.CreatedAt, + &i.ReversedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const UpdateReferralSettings = `-- name: UpdateReferralSettings :one +UPDATE referral_settings SET commission_percent = $1::numeric, +updated_by = $2, updated_at = CURRENT_TIMESTAMP WHERE id = TRUE +RETURNING commission_percent::text AS commission_percent, updated_at +` + +type UpdateReferralSettingsParams struct { + CommissionPercent pgtype.Numeric `json:"commission_percent"` + UpdatedBy pgtype.Int8 `json:"updated_by"` +} + +type UpdateReferralSettingsRow struct { + CommissionPercent string `json:"commission_percent"` + UpdatedAt pgtype.Timestamptz `json:"updated_at"` +} + +func (q *Queries) UpdateReferralSettings(ctx context.Context, arg UpdateReferralSettingsParams) (UpdateReferralSettingsRow, error) { + row := q.db.QueryRow(ctx, UpdateReferralSettings, arg.CommissionPercent, arg.UpdatedBy) + var i UpdateReferralSettingsRow + err := row.Scan(&i.CommissionPercent, &i.UpdatedAt) + return i, err +} diff --git a/gen/db/subscriptions.sql.go b/gen/db/subscriptions.sql.go index 00270c12..cf63cf8b 100644 --- a/gen/db/subscriptions.sql.go +++ b/gen/db/subscriptions.sql.go @@ -282,7 +282,7 @@ SELECT FROM user_subscriptions us JOIN subscription_plans sp ON sp.id = us.plan_id WHERE us.user_id = $1 - AND us.status = 'ACTIVE' + AND us.status = 'ACTIVE' AND us.starts_at <= CURRENT_TIMESTAMP AND us.expires_at > CURRENT_TIMESTAMP ORDER BY us.expires_at DESC LIMIT 1 @@ -469,7 +469,7 @@ const GetSubscriptionDisplayStatusByUserID = `-- name: GetSubscriptionDisplaySta SELECT COALESCE( (SELECT us.status::text FROM user_subscriptions us WHERE us.user_id = $1 - AND us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP + AND us.status = 'ACTIVE' AND us.starts_at <= CURRENT_TIMESTAMP AND us.expires_at > CURRENT_TIMESTAMP ORDER BY us.expires_at DESC LIMIT 1), (SELECT us.status::text FROM user_subscriptions us WHERE us.user_id = $1 @@ -666,6 +666,7 @@ SELECT EXISTS( SELECT 1 FROM user_subscriptions WHERE user_id = $1 AND status = 'ACTIVE' + AND starts_at <= CURRENT_TIMESTAMP AND expires_at > CURRENT_TIMESTAMP ) AS has_subscription ` @@ -684,7 +685,7 @@ SELECT EXISTS( JOIN subscription_plans sp ON sp.id = us.plan_id WHERE us.user_id = $1 AND sp.category = $2 - AND us.status = 'ACTIVE' + AND us.status = 'ACTIVE' AND us.starts_at <= CURRENT_TIMESTAMP AND us.expires_at > CURRENT_TIMESTAMP ) AS has_subscription ` @@ -754,7 +755,7 @@ SELECT FROM user_subscriptions us JOIN subscription_plans sp ON sp.id = us.plan_id WHERE us.user_id = $1 - AND us.status = 'ACTIVE' + AND us.status = 'ACTIVE' AND us.starts_at <= CURRENT_TIMESTAMP AND us.expires_at > CURRENT_TIMESTAMP ORDER BY us.expires_at DESC ` @@ -960,7 +961,7 @@ SELECT COALESCE( (SELECT us.status::text FROM user_subscriptions us WHERE us.user_id = input.user_id - AND us.status = 'ACTIVE' AND us.expires_at > CURRENT_TIMESTAMP + AND us.status = 'ACTIVE' AND us.starts_at <= CURRENT_TIMESTAMP AND us.expires_at > CURRENT_TIMESTAMP ORDER BY us.expires_at DESC LIMIT 1), (SELECT us.status::text FROM user_subscriptions us WHERE us.user_id = input.user_id diff --git a/internal/domain/referrals.go b/internal/domain/referrals.go new file mode 100644 index 00000000..76d9df08 --- /dev/null +++ b/internal/domain/referrals.go @@ -0,0 +1,22 @@ +package domain + +import ( + "errors" + "strings" +) + +var ErrInvalidReferralCode = errors.New("referral code is invalid, already applied, or no longer eligible") + +// NormalizeReferralCode accepts share codes without case or surrounding-space sensitivity. +func NormalizeReferralCode(code string) (string, error) { + code = strings.ToUpper(strings.TrimSpace(code)) + if len(code) != 16 { + return "", ErrInvalidReferralCode + } + for _, char := range code { + if !(char >= 'A' && char <= 'Z') && !(char >= '0' && char <= '9') { + return "", ErrInvalidReferralCode + } + } + return code, nil +} diff --git a/internal/domain/subscriptions.go b/internal/domain/subscriptions.go index 2b05db93..e7fa02de 100644 --- a/internal/domain/subscriptions.go +++ b/internal/domain/subscriptions.go @@ -33,9 +33,6 @@ type SubscriptionExpiryReminder struct { // CategorySubscriptionGateDisabled skips subscription enforcement on learner-facing routes (temporary). var CategorySubscriptionGateDisabled = false -// ExamPrepSubscriptionGateDisabled skips IELTS/DUOLINGO subscription checks on exam-prep routes (temporary). -var ExamPrepSubscriptionGateDisabled = true - // IsValidSubscriptionCategory reports whether category is a known plan category. func IsValidSubscriptionCategory(category string) bool { switch normalizeSubscriptionCategory(category) { diff --git a/internal/domain/user.go b/internal/domain/user.go index f230369a..6e52a1e8 100644 --- a/internal/domain/user.go +++ b/internal/domain/user.go @@ -59,11 +59,12 @@ type UpdateKnowledgeLevelReq struct { } type User struct { - ID int64 - FirstName string - LastName string - Gender string - BirthDay time.Time `json:"birth_day"` + ReferralCode string `json:"-"` // Registration-only attribution; not persisted on users. + ID int64 + FirstName string + LastName string + Gender string + BirthDay time.Time `json:"birth_day"` // UserName string Email string PhoneNumber string @@ -239,11 +240,12 @@ type AccountDeletionRequest struct { } type RegisterUserReq struct { - Email string `json:"email"` - PhoneNumber string `json:"phone_number"` - Password string `json:"password"` - Role string `json:"role"` - OtpMedium OtpMedium `json:"otp_medium"` + ReferralCode string `json:"referral_code"` + Email string `json:"email"` + PhoneNumber string `json:"phone_number"` + Password string `json:"password"` + Role string `json:"role"` + OtpMedium OtpMedium `json:"otp_medium"` } type CreateUserReq struct { diff --git a/internal/repository/user.go b/internal/repository/user.go index 85b93a3d..401b41ce 100644 --- a/internal/repository/user.go +++ b/internal/repository/user.go @@ -207,10 +207,21 @@ func (s *Store) CreateUserWithoutOtp( ctx context.Context, user domain.User, ) (domain.User, error) { + queries := s.queries + var referralTx pgx.Tx + if user.ReferralCode != "" { + var err error + referralTx, err = s.conn.Begin(ctx) + if err != nil { + return domain.User{}, err + } + defer referralTx.Rollback(ctx) + queries = queries.WithTx(referralTx) + } email := normalizeEmail(user.Email) phone := normalizePhone(user.PhoneNumber) - userRes, err := s.queries.CreateUser(ctx, dbgen.CreateUserParams{ + userRes, err := queries.CreateUser(ctx, dbgen.CreateUserParams{ FirstName: pgtype.Text{String: user.FirstName}, LastName: pgtype.Text{String: user.LastName}, Gender: pgtype.Text{ @@ -280,6 +291,18 @@ func (s *Store) CreateUserWithoutOtp( return domain.User{}, mapUserUniqueViolation(err) } + if referralTx != nil { + affected, err := queries.ApplyReferralCode(ctx, dbgen.ApplyReferralCodeParams{ReferredUserID: userRes.ID, Code: user.ReferralCode}) + if err != nil { + return domain.User{}, err + } + if affected != 1 { + return domain.User{}, domain.ErrInvalidReferralCode + } + if err = referralTx.Commit(ctx); err != nil { + return domain.User{}, err + } + } var updatedAt *time.Time if userRes.UpdatedAt.Valid { updatedAt = &userRes.UpdatedAt.Time diff --git a/internal/services/referrals/service.go b/internal/services/referrals/service.go new file mode 100644 index 00000000..8a6e640e --- /dev/null +++ b/internal/services/referrals/service.go @@ -0,0 +1,137 @@ +package referrals + +import ( + dbgen "Rezina-Backend/gen/db" + "Rezina-Backend/internal/domain" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + "math" + "strconv" + "strings" +) + +type Store interface { + GetReferralCode(context.Context, int64) (string, error) + CreateReferralCode(context.Context, dbgen.CreateReferralCodeParams) (string, error) + ApplyReferralCode(context.Context, dbgen.ApplyReferralCodeParams) (int64, error) + GetReferralSummary(context.Context, int64) (dbgen.GetReferralSummaryRow, error) + ListMyReferrals(context.Context, dbgen.ListMyReferralsParams) ([]dbgen.ListMyReferralsRow, error) + GetReferralWallet(context.Context, int64) ([]dbgen.GetReferralWalletRow, error) + ListReferralCommissions(context.Context, dbgen.ListReferralCommissionsParams) ([]dbgen.ListReferralCommissionsRow, error) + GetReferralSettings(context.Context) (dbgen.GetReferralSettingsRow, error) + UpdateReferralSettings(context.Context, dbgen.UpdateReferralSettingsParams) (dbgen.UpdateReferralSettingsRow, error) +} +type Service struct{ store Store } + +func NewService(store Store) *Service { return &Service{store: store} } + +func (s *Service) Code(ctx context.Context, userID int64) (string, error) { + code, err := s.store.GetReferralCode(ctx, userID) + if err == nil { + return code, nil + } + if !errors.Is(err, pgx.ErrNoRows) { + return "", err + } + for attempt := 0; attempt < 3; attempt++ { + bytes := make([]byte, 8) + if _, err = rand.Read(bytes); err != nil { + return "", err + } + code, err = s.store.CreateReferralCode(ctx, dbgen.CreateReferralCodeParams{ID: userID, Code: strings.ToUpper(hex.EncodeToString(bytes))}) + var pgerr *pgconn.PgError + if errors.As(err, &pgerr) && pgerr.Code == "23505" { + continue + } + return code, err + } + return "", errors.New("could not allocate a unique referral code") +} +func (s *Service) Apply(ctx context.Context, userID int64, code string) error { + normalized, err := domain.NormalizeReferralCode(code) + if err != nil { + return err + } + count, err := s.store.ApplyReferralCode(ctx, dbgen.ApplyReferralCodeParams{ReferredUserID: userID, Code: normalized}) + var pgerr *pgconn.PgError + if errors.As(err, &pgerr) && (pgerr.Code == "23514" || pgerr.Code == "23505") { + return domain.ErrInvalidReferralCode + } + if err != nil { + return err + } + if count == 0 { + return domain.ErrInvalidReferralCode + } + return nil +} + +type Overview struct { + CommissionPercent string `json:"commission_percent"` + Code string `json:"code"` + dbgen.GetReferralSummaryRow + Wallet []dbgen.GetReferralWalletRow `json:"wallet"` +} + +func (s *Service) Overview(ctx context.Context, userID int64) (Overview, error) { + result := Overview{Wallet: []dbgen.GetReferralWalletRow{}} + var err error + result.Code, err = s.Code(ctx, userID) + if err != nil { + return result, err + } + result.GetReferralSummaryRow, err = s.store.GetReferralSummary(ctx, userID) + if err != nil { + return result, err + } + settings, err := s.store.GetReferralSettings(ctx) + if err != nil { + return result, err + } + result.CommissionPercent = settings.CommissionPercent + balances, err := s.store.GetReferralWallet(ctx, userID) + if balances != nil { + result.Wallet = balances + } + return result, err +} +func (s *Service) List(ctx context.Context, userID int64, limit, offset int32) ([]dbgen.ListMyReferralsRow, error) { + rows, err := s.store.ListMyReferrals(ctx, dbgen.ListMyReferralsParams{ReferrerID: userID, Limit: limit, Offset: offset}) + if rows == nil { + rows = []dbgen.ListMyReferralsRow{} + } + return rows, err +} +func (s *Service) Commissions(ctx context.Context, userID int64, limit, offset int32) ([]dbgen.ListReferralCommissionsRow, error) { + rows, err := s.store.ListReferralCommissions(ctx, dbgen.ListReferralCommissionsParams{ReferrerID: userID, Limit: limit, Offset: offset}) + if rows == nil { + rows = []dbgen.ListReferralCommissionsRow{} + } + return rows, err +} +func (s *Service) Settings(ctx context.Context) (dbgen.GetReferralSettingsRow, error) { + return s.store.GetReferralSettings(ctx) +} + +var ErrInvalidCommissionPercent = errors.New("commission_percent must be between 0 and 100 with at most two decimal places") + +func CommissionPercent(value float64) (pgtype.Numeric, error) { + if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 || value > 100 || math.Abs(value*100-math.Round(value*100)) > 0.000001 { + return pgtype.Numeric{}, ErrInvalidCommissionPercent + } + var percent pgtype.Numeric + err := percent.Scan(strconv.FormatFloat(value, 'f', 2, 64)) + return percent, err +} +func (s *Service) UpdateSettings(ctx context.Context, adminID int64, percent float64) (dbgen.UpdateReferralSettingsRow, error) { + value, err := CommissionPercent(percent) + if err != nil { + return dbgen.UpdateReferralSettingsRow{}, err + } + return s.store.UpdateReferralSettings(ctx, dbgen.UpdateReferralSettingsParams{CommissionPercent: value, UpdatedBy: pgtype.Int8{Int64: adminID, Valid: true}}) +} diff --git a/internal/services/referrals/service_test.go b/internal/services/referrals/service_test.go new file mode 100644 index 00000000..cef3215e --- /dev/null +++ b/internal/services/referrals/service_test.go @@ -0,0 +1,87 @@ +package referrals + +import ( + dbgen "Rezina-Backend/gen/db" + "Rezina-Backend/internal/domain" + "context" + "errors" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "math" + "testing" +) + +type fakeStore struct { + Store + existing string + created string + attempts int + collision bool + count int64 + apply dbgen.ApplyReferralCodeParams +} + +func (s *fakeStore) GetReferralCode(context.Context, int64) (string, error) { + if s.existing != "" { + return s.existing, nil + } + return "", pgx.ErrNoRows +} +func (s *fakeStore) CreateReferralCode(_ context.Context, p dbgen.CreateReferralCodeParams) (string, error) { + s.attempts++ + s.created = p.Code + if s.collision && s.attempts == 1 { + return "", &pgconn.PgError{Code: "23505"} + } + return p.Code, nil +} +func (s *fakeStore) ApplyReferralCode(_ context.Context, p dbgen.ApplyReferralCodeParams) (int64, error) { + s.apply = p + return s.count, nil +} +func TestStableCodeAndCollisionRetry(t *testing.T) { + existing := &fakeStore{existing: "ABCDEF0123456789"} + code, err := NewService(existing).Code(context.Background(), 42) + if err != nil || code != existing.existing || existing.attempts != 0 { + t.Fatalf("existing code: %q %v", code, err) + } + fresh := &fakeStore{collision: true} + code, err = NewService(fresh).Code(context.Background(), 42) + if err != nil || fresh.attempts != 2 { + t.Fatalf("retry: %d %v", fresh.attempts, err) + } + if _, err := domain.NormalizeReferralCode(code); err != nil { + t.Fatal(err) + } +} +func TestApplyValidationAndAttribution(t *testing.T) { + store := &fakeStore{count: 1} + svc := NewService(store) + if err := svc.Apply(context.Background(), 42, " abcdef0123456789 "); err != nil { + t.Fatal(err) + } + if store.apply.Code != "ABCDEF0123456789" || store.apply.ReferredUserID != 42 { + t.Fatalf("wrong attribution: %+v", store.apply) + } + store.count = 0 + if err := svc.Apply(context.Background(), 42, "ABCDEF0123456789"); !errors.Is(err, domain.ErrInvalidReferralCode) { + t.Fatalf("ineligible: %v", err) + } + for _, invalid := range []string{"", "short", "ABCDEF012345678!", "?BCDEF0123456789"} { + if err := svc.Apply(context.Background(), 42, invalid); !errors.Is(err, domain.ErrInvalidReferralCode) { + t.Errorf("accepted %q", invalid) + } + } +} +func TestCommissionPercent(t *testing.T) { + for _, v := range []float64{0, 5, 10.25, 100} { + if _, err := CommissionPercent(v); err != nil { + t.Errorf("%v: %v", v, err) + } + } + for _, v := range []float64{-1, 100.01, 1.001, math.NaN(), math.Inf(1)} { + if _, err := CommissionPercent(v); !errors.Is(err, ErrInvalidCommissionPercent) { + t.Errorf("accepted %v", v) + } + } +} diff --git a/internal/services/user/register.go b/internal/services/user/register.go index 09e1ebd1..04ae9ef8 100644 --- a/internal/services/user/register.go +++ b/internal/services/user/register.go @@ -3,6 +3,7 @@ package user import ( "Rezina-Backend/internal/domain" "context" + "strings" "time" ) @@ -36,6 +37,14 @@ func (s *Service) SendRegisterCode(ctx context.Context, medium domain.OtpMedium, } func (s *Service) RegisterUser(ctx context.Context, registerReq domain.RegisterUserReq) (domain.User, error) { + registerReq.ReferralCode = strings.TrimSpace(registerReq.ReferralCode) + if registerReq.ReferralCode != "" { + normalized, err := domain.NormalizeReferralCode(registerReq.ReferralCode) + if err != nil { + return domain.User{}, err + } + registerReq.ReferralCode = normalized + } // Check if the email or phone is already registered based on OTP medium phoneExists, emailExists, err := s.userStore.CheckPhoneEmailExist(ctx, registerReq.PhoneNumber, registerReq.Email) if err != nil { @@ -57,6 +66,7 @@ func (s *Service) RegisterUser(ctx context.Context, registerReq domain.RegisterU // Prepare the user userR := domain.User{ + ReferralCode: registerReq.ReferralCode, // FirstName: registerReq.FirstName, // LastName: registerReq.LastName, // UserName: registerReq.UserName, diff --git a/internal/web_server/content_access_middleware.go b/internal/web_server/content_access_middleware.go index bc6c7091..4f128b6c 100644 --- a/internal/web_server/content_access_middleware.go +++ b/internal/web_server/content_access_middleware.go @@ -203,25 +203,39 @@ func (a *App) resolveExamPrepEffectiveAccessTier(c *fiber.Ctx) (domain.ContentAc ctx := c.Context() routePath := c.Route().Path - if _, ok, err := parseRouteInt64(c, "catalogCourseId"); err != nil { - return "", false, err - } else if ok { - return "", false, nil + if strings.Contains(routePath, "/videos/engagement/heartbeat") { + var input domain.VideoEngagementHeartbeatInput + if err := c.BodyParser(&input); err != nil || input.ContentID <= 0 { + return "", false, fiber.NewError(fiber.StatusBadRequest, "Invalid video content") + } + return a.examPrepEffectiveTierForLesson(ctx, input.ContentID) } - if _, ok, err := parseRouteInt64(c, "unitId"); err != nil { + + if id, ok, err := parseRouteInt64(c, "catalogCourseId"); err != nil { return "", false, err } else if ok { - return "", false, nil + return a.examPrepEffectiveTierForCatalogCourse(ctx, id) } - if _, ok, err := parseRouteInt64(c, "moduleId"); err != nil { + if id, ok, err := parseRouteInt64(c, "unitId"); err != nil { return "", false, err } else if ok { - return "", false, nil + return a.examPrepEffectiveTierForUnit(ctx, id) } - if _, ok, err := parseRouteInt64(c, "lessonId"); err != nil { + if id, ok, err := parseRouteInt64(c, "moduleId"); err != nil { return "", false, err } else if ok { - return "", false, nil + return a.examPrepEffectiveTierForModule(ctx, id) + } + if id, ok, err := parseRouteInt64(c, "lessonId"); err != nil { + return "", false, err + } else if ok { + return a.examPrepEffectiveTierForLesson(ctx, id) + } + + if id, ok, err := parseRouteInt64(c, "practiceId"); err != nil { + return "", false, err + } else if ok { + return a.examPrepEffectiveTierForPractice(ctx, id) } switch { diff --git a/internal/web_server/handlers/handlers.go b/internal/web_server/handlers/handlers.go index 2daf6879..22253d3f 100644 --- a/internal/web_server/handlers/handlers.go +++ b/internal/web_server/handlers/handlers.go @@ -37,7 +37,7 @@ import ( "Rezina-Backend/internal/services/videoengagement" vimeoservice "Rezina-Backend/internal/services/vimeo" - // referralservice "Rezina-Backend/internal/services/referal" + "Rezina-Backend/internal/services/referrals" "Rezina-Backend/internal/services/settings" @@ -51,6 +51,7 @@ import ( ) type Handler struct { + referralSvc *referrals.Service questionsSvc *questions.Service faqSvc *faqs.Service appVersionSvc *appversions.Service @@ -134,6 +135,7 @@ func New( analyticsDB *dbgen.Queries, ) *Handler { return &Handler{ + referralSvc: referrals.NewService(analyticsDB), questionsSvc: questionsSvc, faqSvc: faqSvc, appVersionSvc: appVersionSvc, diff --git a/internal/web_server/handlers/referal_handlers.go b/internal/web_server/handlers/referal_handlers.go index 5334095b..bb5206d3 100644 --- a/internal/web_server/handlers/referal_handlers.go +++ b/internal/web_server/handlers/referal_handlers.go @@ -2,204 +2,141 @@ package handlers import ( "Rezina-Backend/internal/domain" - "Rezina-Backend/internal/web_server/response" - "fmt" - "time" - + "Rezina-Backend/internal/services/referrals" + "encoding/json" + "errors" "github.com/gofiber/fiber/v2" - "go.uber.org/zap" + "github.com/jackc/pgx/v5" + "strconv" ) -func (h *Handler) CreateReferralCode(c *fiber.Ctx) error { - - companyID := c.Locals("company_id").(domain.ValidInt64) - if !companyID.Valid { - h.BadRequestLogger().Error("invalid company id") - return fiber.NewError(fiber.StatusBadRequest, "invalid company id") +func referralLearner(c *fiber.Ctx) (int64, error) { + id, ok := c.Locals("user_id").(int64) + if !ok || id <= 0 { + return 0, fiber.NewError(401, "Unauthorized") } - userID, ok := c.Locals("user_id").(int64) - if !ok || userID == 0 { - h.mongoLoggerSvc.Info("Invalid user ID in context", - zap.Int("status_code", fiber.StatusInternalServerError), - zap.Int64("userID", userID), - zap.Time("timestamp", time.Now()), - ) - return fiber.NewError(fiber.StatusInternalServerError, "Invalid user identification") + role, _ := c.Locals("role").(domain.Role) + if !role.IsCustomerLearnerRole() { + return 0, fiber.NewError(403, "Learner account required") } - // referralCode, err := h.referralSvc.CreateReferralCode(c.Context(), userID, companyID.Value) - - // if err != nil { - // h.mongoLoggerSvc.Error("Failed to create referral", - // zap.Int64("userID", userID), - // zap.Int("status_code", fiber.StatusInternalServerError), - // zap.Error(err), - // zap.Time("timestamp", time.Now()), - // ) - // return fiber.NewError(fiber.StatusInternalServerError, "Failed to create referral") - // } - - fmt.Printf("Successfully created referral!") - - h.recordActivity(c, domain.ActionReferralCodeCreated, domain.ResourceReferral, &userID, fmt.Sprintf("Created referral code for user ID: %d", userID), nil) - - // res := domain.ConvertReferralCodeRes(referralCode) - - return response.WriteJSON(c, fiber.StatusOK, "Referral created successfully", nil, nil) + return id, nil } - -func (h *Handler) GetReferralCode(c *fiber.Ctx) error { - companyID := c.Locals("company_id").(domain.ValidInt64) - if !companyID.Valid { - h.BadRequestLogger().Error("invalid company id") - return fiber.NewError(fiber.StatusBadRequest, "invalid company id") +func referralAdmin(c *fiber.Ctx) (int64, error) { + id, ok := c.Locals("user_id").(int64) + if !ok || id <= 0 { + return 0, fiber.NewError(401, "Unauthorized") } - userID, ok := c.Locals("user_id").(int64) - if !ok || userID == 0 { - h.mongoLoggerSvc.Error("Invalid user ID in context", - zap.Int64("userID", userID), - zap.Int("status_code", fiber.StatusInternalServerError), - zap.Time("timestamp", time.Now()), - ) - return fiber.NewError(fiber.StatusInternalServerError, "Invalid user id") + role, _ := c.Locals("role").(domain.Role) + if role != domain.RoleAdmin && role != domain.RoleSuperAdmin { + return 0, fiber.NewError(403, "Administrator required") } - - _, err := h.userSvc.GetUserByID(c.Context(), userID) + return id, nil +} +func referralResponse(c *fiber.Ctx, data any, err error) error { if err != nil { - h.mongoLoggerSvc.Error("Failed to get user", - zap.Int64("userID", userID), - zap.Int("status_code", fiber.StatusInternalServerError), - zap.Error(err), - zap.Time("timestamp", time.Now()), - ) - return fiber.NewError(fiber.StatusInternalServerError, "Failed to retrieve user") + if errors.Is(err, domain.ErrInvalidReferralCode) || errors.Is(err, referrals.ErrInvalidCommissionPercent) { + return fiber.NewError(400, err.Error()) + } + if errors.Is(err, pgx.ErrNoRows) { + return fiber.NewError(403, "Active learner account required") + } + return fiber.NewError(500, "Unable to process referral request") } - - // if !user.OrganizationID.Valid || user.OrganizationID.Value != companyID.Value { - // h.mongoLoggerSvc.Warn("User attempt to login to different company", - // zap.Int64("userID", userID), - // zap.Int("status_code", fiber.StatusInternalServerError), - // zap.Error(err), - // zap.Time("timestamp", time.Now()), - // ) - // return fiber.NewError(fiber.StatusBadRequest, "Failed to retrieve user") - // } - - // referrals, err := h.referralSvc.GetReferralCodesByUser(c.Context(), user.ID) - - // if err != nil { - // h.mongoLoggerSvc.Error("Failed to get user referrals", - // zap.Int64("userID", userID), - // zap.Int("status_code", fiber.StatusInternalServerError), - // zap.Error(err), - // zap.Time("timestamp", time.Now()), - // ) - // return fiber.NewError(fiber.StatusInternalServerError, "Failed to retrieve user referral codes") - // } - - // result := domain.ConvertReferralCodeResList(referrals) - - return response.WriteJSON(c, fiber.StatusOK, "Referral Code Fetched Successfully", nil, nil) - + return c.JSON(domain.Response{Success: true, StatusCode: 200, Message: "Referral request successful", Data: data}) +} +func referralPagination(c *fiber.Ctx) (int32, int32, error) { + limit, err := strconv.Atoi(c.Query("limit", "20")) + if err != nil || limit < 1 || limit > 100 { + return 0, 0, fiber.NewError(400, "limit must be between 1 and 100") + } + offset, err := strconv.ParseInt(c.Query("offset", "0"), 10, 32) + if err != nil || offset < 0 { + return 0, 0, fiber.NewError(400, "offset must be a non-negative integer") + } + return int32(limit), int32(offset), nil } -// // UpdateReferralSettings godoc -// // @Summary Update referral settings -// // @Description Updates referral settings (admin only) -// // @Tags referral -// // @Accept json -// // @Produce json -// // @Param settings body domain.ReferralSettings true "Referral settings" -// // @Success 200 {object} response.APIResponse -// // @Failure 401 {object} response.APIResponse -// // @Failure 403 {object} response.APIResponse -// // @Failure 500 {object} response.APIResponse -// // @Security Bearer -// // @Router /api/v1/referral/settings [put] -// func (h *Handler) UpdateReferralSettings(c *fiber.Ctx) error { -// userID, ok := c.Locals("user_id").(int64) -// if !ok || userID == 0 { -// h.logger.Error("Invalid user ID in context") -// h.mongoLoggerSvc.Error("Failed to delete user", -// zap.Int64("userID", userID), -// zap.Int("status_code", fiber.StatusInternalServerError), -// zap.Time("timestamp", time.Now()), -// ) -// return fiber.NewError(fiber.StatusInternalServerError, "Invalid user id") -// } - -// user, err := h.userSvc.GetUserByID(c.Context(), userID) -// if err != nil { -// h.mongoLoggerSvc.Error("Failed to get user", -// zap.Int64("userID", userID), -// zap.Int("status_code", fiber.StatusInternalServerError), -// zap.Error(err), -// zap.Time("timestamp", time.Now()), -// ) -// return fiber.NewError(fiber.StatusInternalServerError, err.Error()) -// } - -// if user.Role != domain.RoleAdmin { -// h.mongoLoggerSvc.Error("Access Forbidden", -// zap.Int64("userID", userID), -// zap.Int("status_code", fiber.StatusForbidden), -// zap.Error(err), -// zap.Time("timestamp", time.Now()), -// ) -// return fiber.NewError(fiber.StatusForbidden, "Admin access required") -// } - -// var settings domain.ReferralSettings -// if err := c.BodyParser(&settings); err != nil { -// h.mongoLoggerSvc.Info("Failed to parse settings", -// zap.Int64("userID", userID), -// zap.Int("status_code", fiber.StatusBadRequest), -// zap.Error(err), -// zap.Time("timestamp", time.Now()), -// ) -// return fiber.NewError(fiber.StatusBadRequest, "Invalid request body") -// } - -// settings.UpdatedBy = user.PhoneNumber -// if err := h.referralSvc.UpdateReferralSettings(c.Context(), &settings); err != nil { -// h.mongoLoggerSvc.Error("Failed to update referral settings", -// zap.Int64("userID", userID), -// zap.Int("status_code", fiber.StatusInternalServerError), -// zap.Error(err), -// zap.Time("timestamp", time.Now()), -// ) -// return fiber.NewError(fiber.StatusInternalServerError, err.Error()) -// } - -// return response.WriteJSON(c, fiber.StatusOK, "Referral settings updated successfully", nil, nil) -// } - -// // GetReferralSettings godoc -// // @Summary Get referral settings -// // @Description Retrieves current referral settings (admin only) -// // @Tags referral -// // @Accept json -// // @Produce json -// // @Success 200 {object} domain.ReferralSettings -// // @Failure 401 {object} response.APIResponse -// // @Failure 403 {object} response.APIResponse -// // @Failure 500 {object} response.APIResponse -// // @Security Bearer -// // @Router /api/v1/referral/settings [get] -// func (h *Handler) GetReferralSettings(c *fiber.Ctx) error { -// // userID, ok := c.Locals("user_id").(int64) -// // if !ok || userID == 0 { -// // h.logger.Error("Invalid user ID in context") -// // return fiber.NewError(fiber.StatusUnauthorized, "Invalid user identification") -// // } -// settings, err := h.referralSvc.GetReferralSettings(c.Context()) -// if err != nil { -// h.mongoLoggerSvc.Error("Failed to get referral settings", -// zap.Int("status_code", fiber.StatusInternalServerError), -// zap.Error(err), -// zap.Time("timestamp", time.Now()), -// ) -// return fiber.NewError(fiber.StatusInternalServerError, err.Error()) -// } - -// return response.WriteJSON(c, fiber.StatusOK, "Referral settings retrieved successfully", settings, nil) -// } +// CreateReferralCode creates or returns the authenticated learner's stable share code. +func (h *Handler) CreateReferralCode(c *fiber.Ctx) error { + id, err := referralLearner(c) + if err != nil { + return err + } + code, err := h.referralSvc.Code(c.Context(), id) + return referralResponse(c, fiber.Map{"code": code}, err) +} +func (h *Handler) GetReferralCode(c *fiber.Ctx) error { return h.CreateReferralCode(c) } +func (h *Handler) GetMyReferrals(c *fiber.Ctx) error { + id, err := referralLearner(c) + if err != nil { + return err + } + data, err := h.referralSvc.Overview(c.Context(), id) + return referralResponse(c, data, err) +} +func (h *Handler) ApplyReferralCode(c *fiber.Ctx) error { + id, err := referralLearner(c) + if err != nil { + return err + } + var input struct { + Code string `json:"code"` + } + if c.BodyParser(&input) != nil { + return fiber.NewError(400, "Invalid request body") + } + return referralResponse(c, nil, h.referralSvc.Apply(c.Context(), id, input.Code)) +} +func (h *Handler) ListMyReferrals(c *fiber.Ctx) error { + id, err := referralLearner(c) + if err != nil { + return err + } + limit, offset, err := referralPagination(c) + if err != nil { + return err + } + data, err := h.referralSvc.List(c.Context(), id, limit, offset) + return referralResponse(c, fiber.Map{"items": data, "limit": limit, "offset": offset}, err) +} +func (h *Handler) GetReferralWallet(c *fiber.Ctx) error { + id, err := referralLearner(c) + if err != nil { + return err + } + limit, offset, err := referralPagination(c) + if err != nil { + return err + } + overview, err := h.referralSvc.Overview(c.Context(), id) + if err != nil { + return referralResponse(c, nil, err) + } + entries, err := h.referralSvc.Commissions(c.Context(), id, limit, offset) + return referralResponse(c, fiber.Map{"balances": overview.Wallet, "transactions": entries, "limit": limit, "offset": offset}, err) +} +func (h *Handler) GetReferralSettings(c *fiber.Ctx) error { + if _, err := referralAdmin(c); err != nil { + return err + } + data, err := h.referralSvc.Settings(c.Context()) + return referralResponse(c, data, err) +} +func (h *Handler) UpdateReferralSettings(c *fiber.Ctx) error { + id, err := referralAdmin(c) + if err != nil { + return err + } + var input struct { + Percent *float64 `json:"commission_percent"` + } + if c.BodyParser(&input) != nil || input.Percent == nil { + return fiber.NewError(400, "commission_percent is required") + } + data, err := h.referralSvc.UpdateSettings(c.Context(), id, *input.Percent) + if err == nil { + metadata, _ := json.Marshal(map[string]string{"commission_percent": data.CommissionPercent}) + h.recordActivity(c, domain.ActionSettingsUpdated, domain.ResourceSettings, nil, "Updated referral commission percentage", metadata) + } + return referralResponse(c, data, err) +} diff --git a/internal/web_server/handlers/referrals_test.go b/internal/web_server/handlers/referrals_test.go new file mode 100644 index 00000000..8c1fce0d --- /dev/null +++ b/internal/web_server/handlers/referrals_test.go @@ -0,0 +1,43 @@ +package handlers + +import ( + "Rezina-Backend/internal/domain" + "github.com/gofiber/fiber/v2" + "net/http/httptest" + "strings" + "testing" +) + +func TestReferralSettingsRejectsNonAdmins(t *testing.T) { + for _, role := range []domain.Role{domain.RoleStudent, domain.RoleOpenLearner, domain.RoleSupport, domain.RoleContentManager} { + t.Run(string(role), func(t *testing.T) { + app := fiber.New() + handler := &Handler{} + app.Put("/settings", func(c *fiber.Ctx) error { c.Locals("user_id", int64(1)); c.Locals("role", role); return c.Next() }, handler.UpdateReferralSettings) + req := httptest.NewRequest("PUT", "/settings", strings.NewReader(`{"commission_percent":100}`)) + req.Header.Set("Content-Type", "application/json") + response, err := app.Test(req) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != 403 { + t.Fatalf("status %d", response.StatusCode) + } + }) + } +} +func TestReferralPagination(t *testing.T) { + for _, query := range []string{"limit=0", "limit=101", "limit=no", "offset=-1", "offset=2147483648"} { + app := fiber.New() + app.Get("/", func(c *fiber.Ctx) error { _, _, err := referralPagination(c); return err }) + response, err := app.Test(httptest.NewRequest("GET", "/?"+query, nil)) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if response.StatusCode != 400 { + t.Errorf("accepted %s", query) + } + } +} diff --git a/internal/web_server/handlers/user.go b/internal/web_server/handlers/user.go index 05002902..ac791cb1 100644 --- a/internal/web_server/handlers/user.go +++ b/internal/web_server/handlers/user.go @@ -1065,6 +1065,7 @@ func (h *Handler) RegisterUser(c *fiber.Ctx) error { } user := domain.RegisterUserReq{ + ReferralCode: req.ReferralCode, // FirstName: req.FirstName, // LastName: req.LastName, // UserName: req.UserName, diff --git a/internal/web_server/middleware.go b/internal/web_server/middleware.go index 5a565448..3364b52c 100644 --- a/internal/web_server/middleware.go +++ b/internal/web_server/middleware.go @@ -269,9 +269,6 @@ func (a *App) RequireSubscriptionCategory(category domain.SubscriptionCategory) func (a *App) RequireExamPrepSubscription() fiber.Handler { return func(c *fiber.Ctx) error { - if isReadOnlyHTTPMethod(c.Method()) { - return c.Next() - } role, userID, err := subscriptionScopedUser(c) if err != nil { return err @@ -283,33 +280,9 @@ func (a *App) RequireExamPrepSubscription() fiber.Handler { if role != domain.RoleStudent { return c.Next() } - if domain.CategorySubscriptionGateDisabled || domain.ExamPrepSubscriptionGateDisabled { - return c.Next() - } - category, scoped, err := a.resolveExamPrepSubscriptionCategory(c) - if err != nil { - switch { - case errors.Is(err, examprepsvc.ErrCatalogCourseNotFound), - errors.Is(err, examprepsvc.ErrUnitNotFound), - errors.Is(err, examprepsvc.ErrModuleNotFound), - errors.Is(err, examprepsvc.ErrLessonNotFound), - errors.Is(err, examprepsvc.ErrPracticeNotFound): - return fiber.NewError(fiber.StatusNotFound, err.Error()) - default: - a.mongoLoggerSvc.Error("exam prep category resolution failed", - zap.Int64("userID", userID), - zap.String("path", c.Path()), - zap.Error(err), - zap.Time("timestamp", time.Now()), - ) - return fiber.NewError(fiber.StatusInternalServerError, "Failed to verify subscription") - } - } - - if !scoped { - return c.Next() - } + // The unified LMS catalog is unlocked by the EDUCATION plan. + category := domain.SubscriptionCategoryEducation tier, tierResolved, err := a.resolveExamPrepEffectiveAccessTier(c) if err != nil { @@ -324,7 +297,9 @@ func (a *App) RequireExamPrepSubscription() fiber.Handler { return fiber.NewError(fiber.StatusInternalServerError, "Failed to verify content access") } } - if tierResolved && !tier.RequiresSubscription() { + // Collection responses can contain premium descendants even under a free parent. + individualContent := c.Params("id") != "" || c.Params("practiceId") != "" || strings.Contains(c.Route().Path, "/videos/engagement/heartbeat") + if individualContent && tierResolved && !tier.RequiresSubscription() { return c.Next() } diff --git a/internal/web_server/routes.go b/internal/web_server/routes.go index f73597d0..0771815e 100644 --- a/internal/web_server/routes.go +++ b/internal/web_server/routes.go @@ -68,6 +68,16 @@ func (a *App) initAppRoutes() { // Groups groupV1 := a.fiber.Group("/api/v1", a.resolveFileURLsMiddleware) + // Referrals remain available without a subscription so new learners can participate. + groupV1.Post("/referrals/code", a.authMiddleware, h.CreateReferralCode) + groupV1.Get("/referrals/code", a.authMiddleware, h.GetReferralCode) + groupV1.Get("/referrals/me", a.authMiddleware, h.GetMyReferrals) + groupV1.Post("/referrals/apply", a.authMiddleware, h.ApplyReferralCode) + groupV1.Get("/referrals", a.authMiddleware, h.ListMyReferrals) + groupV1.Get("/referrals/wallet", a.authMiddleware, h.GetReferralWallet) + groupV1.Get("/admin/referrals/settings", a.authMiddleware, a.OnlyAdminAndAbove, h.GetReferralSettings) + groupV1.Put("/admin/referrals/settings", a.authMiddleware, a.OnlyAdminAndAbove, h.UpdateReferralSettings) + // Serve static files (profile pictures, etc.) a.fiber.Static("/static", "./static") @@ -101,33 +111,33 @@ func (a *App) initAppRoutes() { groupV1.Get("/exam-prep/modules/:id", a.authMiddleware, a.RequirePermission("exam_prep.modules.get"), h.GetExamPrepModuleByID) groupV1.Put("/exam-prep/modules/:id", a.authMiddleware, a.RequirePermission("exam_prep.modules.update"), h.UpdateExamPrepModule) groupV1.Delete("/exam-prep/modules/:id", a.authMiddleware, a.RequirePermission("exam_prep.modules.delete"), h.DeleteExamPrepModule) - groupV1.Post("/exam-prep/modules/:moduleId/lessons", a.authMiddleware, a.RequirePermission("exam_prep.lessons.create"), h.CreateExamPrepLesson) - groupV1.Get("/exam-prep/modules/:moduleId/lessons", a.authMiddleware, a.RequirePermission("exam_prep.lessons.list_by_module"), h.ListExamPrepLessonsByUnitModule) - groupV1.Put("/exam-prep/modules/:moduleId/lessons/reorder", a.authMiddleware, a.RequirePermission("exam_prep.lessons.reorder"), h.ReorderExamPrepLessonsInUnitModule) - groupV1.Get("/exam-prep/lessons/:id", a.authMiddleware, a.RequirePermission("exam_prep.lessons.get"), h.GetExamPrepLessonByID) - groupV1.Put("/exam-prep/lessons/:id", a.authMiddleware, a.RequirePermission("exam_prep.lessons.update"), h.UpdateExamPrepLesson) - groupV1.Delete("/exam-prep/lessons/:id", a.authMiddleware, a.RequirePermission("exam_prep.lessons.delete"), h.DeleteExamPrepLesson) - groupV1.Get("/exam-prep/assessments", a.authMiddleware, a.RequirePermission("question_sets.list"), h.ListExamPrepAssessments) - groupV1.Post("/exam-prep/assessments", a.authMiddleware, a.RequirePermission("question_sets.update"), h.LinkExamPrepAssessment) - groupV1.Delete("/exam-prep/assessments/:questionSetId/parents/:parentKind/:parentId", a.authMiddleware, a.RequirePermission("question_sets.update"), h.UnlinkExamPrepAssessment) - groupV1.Post("/exam-prep/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeFromInput) - groupV1.Get("/exam-prep/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.list"), h.ListAllExamPrepPractices) - groupV1.Get("/exam-prep/catalog-courses/:catalogCourseId/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.list_by_catalog_course"), h.ListExamPrepPracticesByCatalogCourse) - groupV1.Post("/exam-prep/catalog-courses/:catalogCourseId/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeForCatalogCourse) - groupV1.Get("/exam-prep/units/:unitId/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), h.ListExamPrepPracticesByUnit) - groupV1.Post("/exam-prep/units/:unitId/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateExamPrepPracticeForUnit) - groupV1.Get("/exam-prep/lessons/:lessonId/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.list_by_lesson"), h.ListExamPrepPracticesByLesson) - groupV1.Get("/exam-prep/practices/:id", a.authMiddleware, a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeByID) - groupV1.Get("/exam-prep/practices/:id/full", a.authMiddleware, a.RequirePermission("exam_prep.practices.get"), h.GetExamPrepPracticeFull) - groupV1.Put("/exam-prep/practices/:id", a.authMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPractice) - groupV1.Put("/exam-prep/practices/:id/full", a.authMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeFull) - groupV1.Put("/exam-prep/practices/:id/parents", a.authMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UpdateExamPrepPracticeParents) - groupV1.Delete("/exam-prep/practices/:id/parents/:parentKind/:parentId", a.authMiddleware, a.RequirePermission("exam_prep.practices.update"), h.UnlinkExamPrepPracticeParent) - groupV1.Delete("/exam-prep/practices/:id", a.authMiddleware, a.RequirePermission("exam_prep.practices.delete"), h.DeleteExamPrepPractice) - groupV1.Post("/exam-prep/progress/practices/:id/complete", a.authMiddleware, a.RequirePermission("progress.complete"), h.CompletePractice) - groupV1.Post("/exam-prep/videos/engagement/heartbeat", a.authMiddleware, a.RequirePermission("videos.track_engagement"), h.RecordVideoEngagementHeartbeat) + groupV1.Post("/exam-prep/modules/:moduleId/lessons", a.authMiddleware, a.RequirePermission("exam_prep.lessons.create"), a.RequireExamPrepSubscription(), h.CreateExamPrepLesson) + groupV1.Get("/exam-prep/modules/:moduleId/lessons", a.authMiddleware, a.RequirePermission("exam_prep.lessons.list_by_module"), a.RequireExamPrepSubscription(), h.ListExamPrepLessonsByUnitModule) + groupV1.Put("/exam-prep/modules/:moduleId/lessons/reorder", a.authMiddleware, a.RequirePermission("exam_prep.lessons.reorder"), a.RequireExamPrepSubscription(), h.ReorderExamPrepLessonsInUnitModule) + groupV1.Get("/exam-prep/lessons/:id", a.authMiddleware, a.RequirePermission("exam_prep.lessons.get"), a.RequireExamPrepSubscription(), h.GetExamPrepLessonByID) + groupV1.Put("/exam-prep/lessons/:id", a.authMiddleware, a.RequirePermission("exam_prep.lessons.update"), a.RequireExamPrepSubscription(), h.UpdateExamPrepLesson) + groupV1.Delete("/exam-prep/lessons/:id", a.authMiddleware, a.RequirePermission("exam_prep.lessons.delete"), a.RequireExamPrepSubscription(), h.DeleteExamPrepLesson) + groupV1.Get("/exam-prep/assessments", a.authMiddleware, a.RequirePermission("question_sets.list"), a.RequireExamPrepSubscription(), h.ListExamPrepAssessments) + groupV1.Post("/exam-prep/assessments", a.authMiddleware, a.RequirePermission("question_sets.update"), a.RequireExamPrepSubscription(), h.LinkExamPrepAssessment) + groupV1.Delete("/exam-prep/assessments/:questionSetId/parents/:parentKind/:parentId", a.authMiddleware, a.RequirePermission("question_sets.update"), a.RequireExamPrepSubscription(), h.UnlinkExamPrepAssessment) + groupV1.Post("/exam-prep/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.create"), a.RequireExamPrepSubscription(), h.CreateExamPrepPracticeFromInput) + groupV1.Get("/exam-prep/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.list"), a.RequireExamPrepSubscription(), h.ListAllExamPrepPractices) + groupV1.Get("/exam-prep/catalog-courses/:catalogCourseId/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.list_by_catalog_course"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByCatalogCourse) + groupV1.Post("/exam-prep/catalog-courses/:catalogCourseId/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.create"), a.RequireExamPrepSubscription(), h.CreateExamPrepPracticeForCatalogCourse) + groupV1.Get("/exam-prep/units/:unitId/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByUnit) + groupV1.Post("/exam-prep/units/:unitId/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.create"), a.RequireExamPrepSubscription(), h.CreateExamPrepPracticeForUnit) + groupV1.Get("/exam-prep/lessons/:lessonId/practices", a.authMiddleware, a.RequirePermission("exam_prep.practices.list_by_lesson"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByLesson) + groupV1.Get("/exam-prep/practices/:id", a.authMiddleware, a.RequirePermission("exam_prep.practices.get"), a.RequireExamPrepSubscription(), h.GetExamPrepPracticeByID) + groupV1.Get("/exam-prep/practices/:id/full", a.authMiddleware, a.RequirePermission("exam_prep.practices.get"), a.RequireExamPrepSubscription(), h.GetExamPrepPracticeFull) + groupV1.Put("/exam-prep/practices/:id", a.authMiddleware, a.RequirePermission("exam_prep.practices.update"), a.RequireExamPrepSubscription(), h.UpdateExamPrepPractice) + groupV1.Put("/exam-prep/practices/:id/full", a.authMiddleware, a.RequirePermission("exam_prep.practices.update"), a.RequireExamPrepSubscription(), h.UpdateExamPrepPracticeFull) + groupV1.Put("/exam-prep/practices/:id/parents", a.authMiddleware, a.RequirePermission("exam_prep.practices.update"), a.RequireExamPrepSubscription(), h.UpdateExamPrepPracticeParents) + groupV1.Delete("/exam-prep/practices/:id/parents/:parentKind/:parentId", a.authMiddleware, a.RequirePermission("exam_prep.practices.update"), a.RequireExamPrepSubscription(), h.UnlinkExamPrepPracticeParent) + groupV1.Delete("/exam-prep/practices/:id", a.authMiddleware, a.RequirePermission("exam_prep.practices.delete"), a.RequireExamPrepSubscription(), h.DeleteExamPrepPractice) + groupV1.Post("/exam-prep/progress/practices/:id/complete", a.authMiddleware, a.RequirePermission("progress.complete"), a.RequireExamPrepSubscription(), h.CompletePractice) + groupV1.Post("/exam-prep/videos/engagement/heartbeat", a.authMiddleware, a.RequirePermission("videos.track_engagement"), a.RequireExamPrepSubscription(), h.RecordVideoEngagementHeartbeat) groupV1.Get("/exam-prep/progress-summary", a.authMiddleware, a.RequirePermission("lms.get_my_progress"), h.GetMyLMSProgressSummary) - groupV1.Get("/exam-prep/practices/:practiceId/questions", a.authMiddleware, a.RequirePermission("question_set_items.list"), h.GetQuestionsByPractice) + groupV1.Get("/exam-prep/practices/:practiceId/questions", a.authMiddleware, a.RequirePermission("question_set_items.list"), a.RequireExamPrepSubscription(), h.GetQuestionsByPractice) // LMS personas (catalog referenced by persona_id on practices) groupV1.Get("/personas", a.authMiddleware, a.RequirePermission("personas.list"), h.ListPersonas) diff --git a/internal/web_server/subscription_access_test.go b/internal/web_server/subscription_access_test.go new file mode 100644 index 00000000..f1bce79c --- /dev/null +++ b/internal/web_server/subscription_access_test.go @@ -0,0 +1,54 @@ +package httpserver + +import ( + "Rezina-Backend/internal/domain" + "Rezina-Backend/internal/ports" + "Rezina-Backend/internal/services/subscriptions" + "context" + "github.com/gofiber/fiber/v2" + "net/http/httptest" + "testing" +) + +type accessSubscriptionStore struct { + ports.SubscriptionStore + active bool + calls int +} + +func (s *accessSubscriptionStore) HasActiveSubscriptionByCategory(_ context.Context, userID int64, category string) (bool, error) { + s.calls++ + if userID != 42 || category != "EDUCATION" { + panic("incorrect subscription scope") + } + return s.active, nil +} + +func TestLearningSubscriptionGate(t *testing.T) { + for _, tc := range []struct { + name string + role domain.Role + active bool + status, calls int + }{ + {"unsubscribed GET", domain.RoleStudent, false, 403, 1}, + {"subscribed GET", domain.RoleStudent, true, 204, 1}, + {"admin", domain.RoleAdmin, false, 204, 0}, + {"open learner", domain.RoleOpenLearner, false, 204, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + store := &accessSubscriptionStore{active: tc.active} + app := &App{subscriptionsSvc: subscriptions.NewService(store, nil)} + server := fiber.New() + server.Get("/exam-prep/practices", func(c *fiber.Ctx) error { c.Locals("role", tc.role); c.Locals("user_id", int64(42)); return c.Next() }, app.RequireExamPrepSubscription(), func(c *fiber.Ctx) error { return c.SendStatus(204) }) + response, err := server.Test(httptest.NewRequest("GET", "/exam-prep/practices", nil)) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != tc.status || store.calls != tc.calls { + t.Fatalf("status=%d calls=%d, want status=%d calls=%d", response.StatusCode, store.calls, tc.status, tc.calls) + } + }) + } +}