Add course purchases and affiliate program with documented APIs

This commit is contained in:
Yared Yemane 2026-11-20 22:39:13 +03:00
parent c02ac93760
commit 594bbbe941
70 changed files with 8385 additions and 219 deletions

View File

@ -0,0 +1,21 @@
BEGIN;
DROP TABLE course_purchases;
ALTER TABLE payments DROP CONSTRAINT payments_course_or_plan;
ALTER TABLE payments DROP COLUMN course_id;
-- Materialize inherited tiers before restoring the legacy premium cascade.
UPDATE exam_prep.units u SET access_tier=c.access_tier FROM exam_prep.catalog_courses c WHERE u.catalog_course_id=c.id AND u.access_tier='INHERIT';
UPDATE exam_prep.unit_modules m SET access_tier=u.access_tier FROM exam_prep.units u WHERE m.unit_id=u.id AND m.access_tier='INHERIT';
UPDATE exam_prep.unit_module_lessons l SET access_tier=m.access_tier FROM exam_prep.unit_modules m WHERE l.unit_module_id=m.id AND l.access_tier='INHERIT';
ALTER TABLE exam_prep.units DROP CONSTRAINT chk_exam_prep_units_access_tier;
ALTER TABLE exam_prep.units ADD CONSTRAINT chk_exam_prep_units_access_tier CHECK (access_tier IN ('FREE','PREMIUM'));
ALTER TABLE exam_prep.units ALTER COLUMN access_tier SET DEFAULT 'PREMIUM';
ALTER TABLE exam_prep.unit_modules DROP CONSTRAINT chk_exam_prep_unit_modules_access_tier;
ALTER TABLE exam_prep.unit_modules ADD CONSTRAINT chk_exam_prep_unit_modules_access_tier CHECK (access_tier IN ('FREE','PREMIUM'));
ALTER TABLE exam_prep.unit_modules ALTER COLUMN access_tier SET DEFAULT 'PREMIUM';
ALTER TABLE exam_prep.unit_module_lessons DROP CONSTRAINT chk_exam_prep_unit_module_lessons_access_tier;
ALTER TABLE exam_prep.unit_module_lessons ADD CONSTRAINT chk_exam_prep_unit_module_lessons_access_tier CHECK (access_tier IN ('FREE','PREMIUM'));
ALTER TABLE exam_prep.unit_module_lessons ALTER COLUMN access_tier SET DEFAULT 'PREMIUM';
ALTER TABLE exam_prep.catalog_courses DROP COLUMN price, DROP COLUMN currency;
COMMIT;

View File

@ -0,0 +1,48 @@
BEGIN;
-- Course purchases replace category subscriptions for learning content.
ALTER TABLE exam_prep.catalog_courses
ADD COLUMN price NUMERIC(12,2) NOT NULL DEFAULT 0 CHECK (price >= 0),
ADD COLUMN currency VARCHAR(3) NOT NULL DEFAULT 'ETB' CHECK (currency ~ '^[A-Z]{3}$');
ALTER TABLE exam_prep.units DROP CONSTRAINT chk_exam_prep_units_access_tier;
ALTER TABLE exam_prep.units ADD CONSTRAINT chk_exam_prep_units_access_tier CHECK (access_tier IN ('FREE','PREMIUM','INHERIT'));
ALTER TABLE exam_prep.units ALTER COLUMN access_tier SET DEFAULT 'INHERIT';
ALTER TABLE exam_prep.unit_modules DROP CONSTRAINT chk_exam_prep_unit_modules_access_tier;
ALTER TABLE exam_prep.unit_modules ADD CONSTRAINT chk_exam_prep_unit_modules_access_tier CHECK (access_tier IN ('FREE','PREMIUM','INHERIT'));
ALTER TABLE exam_prep.unit_modules ALTER COLUMN access_tier SET DEFAULT 'INHERIT';
ALTER TABLE exam_prep.unit_module_lessons DROP CONSTRAINT chk_exam_prep_unit_module_lessons_access_tier;
ALTER TABLE exam_prep.unit_module_lessons ADD CONSTRAINT chk_exam_prep_unit_module_lessons_access_tier CHECK (access_tier IN ('FREE','PREMIUM','INHERIT'));
ALTER TABLE exam_prep.unit_module_lessons ALTER COLUMN access_tier SET DEFAULT 'INHERIT';
-- Preserve the old effective restrictions; future children inherit unless overridden.
UPDATE exam_prep.unit_module_lessons l SET access_tier='PREMIUM'
FROM exam_prep.unit_modules m, exam_prep.units u, exam_prep.catalog_courses c
WHERE l.unit_module_id=m.id AND m.unit_id=u.id AND u.catalog_course_id=c.id
AND (m.access_tier='PREMIUM' OR u.access_tier='PREMIUM' OR c.access_tier='PREMIUM');
UPDATE exam_prep.unit_modules m SET access_tier='PREMIUM'
FROM exam_prep.units u, exam_prep.catalog_courses c
WHERE m.unit_id=u.id AND u.catalog_course_id=c.id AND (u.access_tier='PREMIUM' OR c.access_tier='PREMIUM');
UPDATE exam_prep.units u SET access_tier='PREMIUM' FROM exam_prep.catalog_courses c
WHERE u.catalog_course_id=c.id AND c.access_tier='PREMIUM';
-- Remove redundant explicit tiers bottom-up so later parent edits cascade by default.
UPDATE exam_prep.unit_module_lessons l SET access_tier='INHERIT' FROM exam_prep.unit_modules m WHERE l.unit_module_id=m.id AND l.access_tier=m.access_tier;
UPDATE exam_prep.unit_modules m SET access_tier='INHERIT' FROM exam_prep.units u WHERE m.unit_id=u.id AND m.access_tier=u.access_tier;
UPDATE exam_prep.units u SET access_tier='INHERIT' FROM exam_prep.catalog_courses c WHERE u.catalog_course_id=c.id AND u.access_tier=c.access_tier;
-- Internal containers must not override the chapter's tier.
UPDATE exam_prep.unit_modules m SET access_tier='INHERIT'
FROM exam_prep.chapter_lesson_containers cc WHERE cc.module_id=m.id;
ALTER TABLE payments ADD COLUMN course_id BIGINT REFERENCES exam_prep.catalog_courses(id) ON DELETE SET NULL;
ALTER TABLE payments ADD CONSTRAINT payments_course_or_plan CHECK (course_id IS NULL OR (plan_id IS NULL AND subscription_id IS NULL));
CREATE INDEX payments_course_user ON payments(user_id,course_id) WHERE course_id IS NOT NULL;
CREATE TABLE course_purchases (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
course_id BIGINT NOT NULL REFERENCES exam_prep.catalog_courses(id) ON DELETE CASCADE,
payment_id BIGINT NOT NULL UNIQUE REFERENCES payments(id),
purchased_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE(user_id,course_id)
);
COMMIT;

View File

@ -0,0 +1,66 @@
BEGIN;
-- Never silently discard financial audit or payout records during rollback.
DO $$ BEGIN
IF EXISTS(SELECT 1 FROM affiliate_sales) OR EXISTS(SELECT 1 FROM affiliate_payouts) OR EXISTS(SELECT 1 FROM affiliates) THEN
RAISE EXCEPTION 'Export and reconcile affiliate records before rollback';
END IF;
END $$;
DROP TRIGGER affiliate_settings_audit ON referral_settings;
DROP FUNCTION affiliate_settings_audit();
DROP FUNCTION affiliate_review_payout(BIGINT,TEXT,BIGINT,TEXT,TEXT);
DROP FUNCTION affiliate_request_payout(BIGINT,TEXT,TEXT,TEXT,TEXT);
CREATE OR REPLACE 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;
$$;
DROP FUNCTION affiliate_reverse_commission(BIGINT,BIGINT,TEXT);
DROP FUNCTION affiliate_review(BIGINT,TEXT,BIGINT,TEXT);
DROP FUNCTION affiliate_apply(BIGINT,TEXT);
CREATE OR REPLACE 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;
$$;
DROP TABLE affiliate_events,affiliate_sales;
ALTER TABLE referral_commissions DROP COLUMN course_id,DROP COLUMN available_at,DROP COLUMN payout_id,DROP COLUMN recovery_payout_id,DROP COLUMN reversal_reason,DROP COLUMN reversed_by;
ALTER TABLE referral_commissions ADD CONSTRAINT referral_commissions_referral_id_key UNIQUE(referral_id);
ALTER TABLE user_referrals DROP COLUMN attributed_until;
DROP TABLE affiliate_payouts,affiliates;
ALTER TABLE referral_settings DROP COLUMN share_base_url,DROP COLUMN commission_mode,DROP COLUMN attribution_days,DROP COLUMN holding_days;
COMMIT;

View File

@ -0,0 +1,205 @@
BEGIN;
ALTER TABLE referral_settings
ADD COLUMN share_base_url TEXT NOT NULL DEFAULT '',
ADD COLUMN commission_mode TEXT NOT NULL DEFAULT 'FIRST_PURCHASE' CHECK (commission_mode IN ('FIRST_PURCHASE','EVERY_COURSE')),
ADD COLUMN attribution_days INTEGER NOT NULL DEFAULT 30 CHECK (attribution_days BETWEEN 1 AND 365),
ADD COLUMN holding_days INTEGER NOT NULL DEFAULT 14 CHECK (holding_days BETWEEN 0 AND 365);
CREATE TABLE affiliates (
user_id BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE RESTRICT,
status TEXT NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','APPROVED','REJECTED','SUSPENDED')),
application TEXT NOT NULL CHECK (length(application) BETWEEN 10 AND 2000),
terms_accepted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
terms_version TEXT NOT NULL DEFAULT '1',
reviewed_by BIGINT REFERENCES team_members(id) ON DELETE SET NULL,
review_note TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE affiliate_payouts (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES affiliates(user_id) ON DELETE RESTRICT,
currency VARCHAR(3) NOT NULL CHECK (currency ~ '^[A-Z]{3}$'),
amount NUMERIC(12,2) NOT NULL CHECK (amount > 0),
status TEXT NOT NULL DEFAULT 'REQUESTED' CHECK (status IN ('REQUESTED','PAID','REJECTED')),
method TEXT NOT NULL CHECK (method IN ('BANK','MOBILE_MONEY')),
account_name TEXT NOT NULL CHECK (length(account_name) BETWEEN 2 AND 120),
account_reference TEXT NOT NULL CHECK (length(account_reference) BETWEEN 3 AND 120),
payment_reference TEXT,
review_note TEXT NOT NULL DEFAULT '',
reviewed_by BIGINT REFERENCES team_members(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), reviewed_at TIMESTAMPTZ,
CHECK (status <> 'PAID' OR length(trim(payment_reference)) BETWEEN 3 AND 120)
);
CREATE UNIQUE INDEX affiliate_paid_reference ON affiliate_payouts(payment_reference) WHERE status='PAID';
CREATE UNIQUE INDEX affiliate_pending_currency ON affiliate_payouts(user_id,currency) WHERE status='REQUESTED';
CREATE INDEX affiliate_payout_history ON affiliate_payouts(user_id,created_at DESC);
ALTER TABLE user_referrals ADD COLUMN attributed_until TIMESTAMPTZ NOT NULL DEFAULT (now()+interval '30 days');
UPDATE user_referrals SET attributed_until=created_at+interval '30 days';
ALTER TABLE referral_commissions DROP CONSTRAINT referral_commissions_referral_id_key;
ALTER TABLE referral_commissions
ADD COLUMN course_id BIGINT REFERENCES exam_prep.catalog_courses(id) ON DELETE SET NULL,
ADD COLUMN available_at TIMESTAMPTZ NOT NULL DEFAULT now(),
ADD COLUMN payout_id BIGINT REFERENCES affiliate_payouts(id) ON DELETE RESTRICT,
ADD COLUMN recovery_payout_id BIGINT REFERENCES affiliate_payouts(id) ON DELETE RESTRICT,
ADD COLUMN reversal_reason TEXT,
ADD COLUMN reversed_by BIGINT REFERENCES team_members(id) ON DELETE SET NULL;
CREATE UNIQUE INDEX affiliate_course_commission ON referral_commissions(referral_id,course_id) WHERE course_id IS NOT NULL;
CREATE INDEX affiliate_available_commissions ON referral_commissions(referrer_id,currency,available_at) WHERE reversed_at IS NULL AND payout_id IS NULL;
-- Immutable qualification snapshots also consume a sale when the configured rate is zero.
CREATE TABLE affiliate_sales (
payment_id BIGINT PRIMARY KEY REFERENCES payments(id) ON DELETE RESTRICT,
referral_id BIGINT NOT NULL REFERENCES user_referrals(id) ON DELETE RESTRICT,
course_id BIGINT REFERENCES exam_prep.catalog_courses(id) ON DELETE SET NULL,
commission_percent NUMERIC(5,2) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX affiliate_sale_course ON affiliate_sales(referral_id,course_id) WHERE course_id IS NOT NULL;
CREATE TABLE affiliate_events (
id BIGSERIAL PRIMARY KEY,
affiliate_user_id BIGINT REFERENCES affiliates(user_id) ON DELETE RESTRICT,
actor_id BIGINT REFERENCES team_members(id) ON DELETE SET NULL,
event TEXT NOT NULL, details JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE FUNCTION affiliate_apply(p_user BIGINT,p_application TEXT) RETURNS BIGINT LANGUAGE plpgsql AS $$
DECLARE result BIGINT;
BEGIN
IF NOT EXISTS(SELECT 1 FROM users WHERE id=p_user AND status='ACTIVE' AND role IN ('STUDENT','OPEN_LEARNER')) THEN
RAISE EXCEPTION 'Active learner account required' USING ERRCODE='23514';
END IF;
INSERT INTO affiliates(user_id,application) VALUES(p_user,p_application)
ON CONFLICT(user_id) DO UPDATE SET application=EXCLUDED.application,status='PENDING',terms_accepted_at=now(),reviewed_by=NULL,review_note='',updated_at=now()
WHERE affiliates.status='REJECTED' RETURNING user_id INTO result;
IF result IS NULL THEN RAISE EXCEPTION 'An application already exists' USING ERRCODE='23514'; END IF;
INSERT INTO affiliate_events(affiliate_user_id,event) VALUES(p_user,'APPLICATION_SUBMITTED');
RETURN result;
END; $$;
CREATE FUNCTION affiliate_review(p_user BIGINT,p_status TEXT,p_actor BIGINT,p_note TEXT) RETURNS BIGINT LANGUAGE plpgsql AS $$
DECLARE old_status TEXT;
BEGIN
SELECT status INTO old_status FROM affiliates WHERE user_id=p_user FOR UPDATE;
IF NOT FOUND THEN RAISE EXCEPTION 'Affiliate not found' USING ERRCODE='P0002'; END IF;
IF NOT ((old_status='PENDING' AND p_status IN ('APPROVED','REJECTED')) OR (old_status='APPROVED' AND p_status='SUSPENDED') OR (old_status='SUSPENDED' AND p_status='APPROVED')) THEN
RAISE EXCEPTION 'Invalid affiliate status transition' USING ERRCODE='23514';
END IF;
IF length(trim(p_note))<3 OR length(p_note)>2000 THEN RAISE EXCEPTION 'A review note is required' USING ERRCODE='23514'; END IF;
UPDATE affiliates SET status=p_status,reviewed_by=p_actor,review_note=p_note,updated_at=now() WHERE user_id=p_user;
INSERT INTO affiliate_events(affiliate_user_id,actor_id,event,details) VALUES(p_user,p_actor,'APPLICATION_REVIEWED',jsonb_build_object('from',old_status,'to',p_status,'note',p_note));
RETURN p_user;
END; $$;
CREATE FUNCTION affiliate_reverse_commission(p_id BIGINT,p_actor BIGINT,p_reason TEXT) RETURNS BIGINT LANGUAGE plpgsql AS $$
DECLARE c referral_commissions%ROWTYPE; owner_id BIGINT; pending_id BIGINT;
BEGIN
IF length(trim(p_reason))<3 OR length(p_reason)>2000 THEN RAISE EXCEPTION 'A reversal reason is required' USING ERRCODE='23514'; END IF;
SELECT referrer_id INTO owner_id FROM referral_commissions WHERE id=p_id;
IF NOT FOUND THEN RAISE EXCEPTION 'Commission not found' USING ERRCODE='P0002'; END IF;
-- All ledger mutations take the same affiliate lock before commission/payout locks.
PERFORM 1 FROM affiliates WHERE user_id=owner_id FOR UPDATE;
SELECT * INTO c FROM referral_commissions WHERE id=p_id FOR UPDATE;
IF c.reversed_at IS NOT NULL THEN RETURN p_id; END IF;
SELECT id INTO pending_id FROM affiliate_payouts WHERE user_id=owner_id AND currency=c.currency AND status='REQUESTED' FOR UPDATE;
IF pending_id IS NOT NULL THEN
UPDATE affiliate_payouts SET status='REJECTED',review_note='A reserved commission was reversed',reviewed_at=now() WHERE id=pending_id;
UPDATE referral_commissions SET payout_id=NULL WHERE payout_id=pending_id;
UPDATE referral_commissions SET recovery_payout_id=NULL WHERE recovery_payout_id=pending_id;
END IF;
UPDATE referral_commissions SET reversed_at=now(),reversal_reason=p_reason,reversed_by=p_actor WHERE id=p_id;
INSERT INTO affiliate_events(affiliate_user_id,actor_id,event,details)
SELECT owner_id,p_actor,'COMMISSION_REVERSED',jsonb_build_object('commission_id',p_id,'reason',p_reason) WHERE EXISTS(SELECT 1 FROM affiliates WHERE user_id=owner_id);
RETURN p_id;
END; $$;
CREATE OR REPLACE 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;
IF NOT EXISTS(SELECT 1 FROM affiliates a JOIN referral_codes rc ON rc.user_id=a.user_id WHERE a.user_id=NEW.referrer_id AND a.status='APPROVED' AND rc.id=NEW.referral_code_id) THEN
RAISE EXCEPTION 'Approved affiliate code required' USING ERRCODE='23514';
END IF;
RETURN NEW;
END; $$;
CREATE OR REPLACE FUNCTION credit_referral_commission() RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE r user_referrals%ROWTYPE; settings referral_settings%ROWTYPE; earned NUMERIC(12,2); existing_id BIGINT;
BEGIN
PERFORM 1 FROM users WHERE id=NEW.user_id FOR UPDATE;
IF NEW.status<>'SUCCESS' THEN
SELECT id INTO existing_id FROM referral_commissions WHERE payment_id=NEW.id AND reversed_at IS NULL;
IF existing_id IS NOT NULL THEN PERFORM affiliate_reverse_commission(existing_id,NULL,'Qualifying payment no longer successful'); END IF;
RETURN NEW;
END IF;
IF NEW.course_id IS NULL OR NEW.amount<=0 THEN RETURN NEW; END IF;
SELECT * INTO r FROM user_referrals WHERE referred_user_id=NEW.user_id;
IF NOT FOUND OR NEW.created_at<r.created_at OR now()>r.attributed_until THEN RETURN NEW; END IF;
PERFORM 1 FROM affiliates a JOIN users u ON u.id=a.user_id WHERE a.user_id=r.referrer_id AND a.status='APPROVED' AND u.status='ACTIVE' FOR UPDATE OF a;
IF NOT FOUND THEN RETURN NEW; END IF;
-- Snapshot a conversion even at 0%; retries must never earn a newly configured rate.
IF EXISTS(SELECT 1 FROM affiliate_sales WHERE payment_id=NEW.id) OR EXISTS(SELECT 1 FROM referral_commissions WHERE payment_id=NEW.id) OR r.conversion_payment_id=NEW.id THEN RETURN NEW; END IF;
SELECT * INTO settings FROM referral_settings WHERE id=TRUE;
IF settings.commission_mode='FIRST_PURCHASE' AND (r.conversion_payment_id IS NOT NULL OR EXISTS(SELECT 1 FROM payments WHERE user_id=NEW.user_id AND id<>NEW.id AND status='SUCCESS' AND amount>0)) THEN RETURN NEW; END IF;
-- A second payment for an already owned course is not another referral sale.
IF EXISTS(SELECT 1 FROM course_purchases WHERE user_id=NEW.user_id AND course_id=NEW.course_id AND payment_id<>NEW.id) THEN RETURN NEW; END IF;
INSERT INTO affiliate_sales(payment_id,referral_id,course_id,commission_percent) VALUES(NEW.id,r.id,NEW.course_id,settings.commission_percent) ON CONFLICT DO NOTHING RETURNING payment_id INTO existing_id;
IF existing_id IS NULL THEN RETURN NEW; END IF;
UPDATE user_referrals SET conversion_payment_id=COALESCE(conversion_payment_id,NEW.id),converted_at=COALESCE(converted_at,now()) WHERE id=r.id;
earned=ROUND(NEW.amount*settings.commission_percent/100,2);
IF earned>0 THEN
INSERT INTO referral_commissions(referral_id,referrer_id,payment_id,course_id,commission_percent,amount,currency,available_at)
VALUES(r.id,r.referrer_id,NEW.id,NEW.course_id,settings.commission_percent,earned,NEW.currency,now()+make_interval(days=>settings.holding_days)) ON CONFLICT DO NOTHING;
END IF;
RETURN NEW;
END; $$;
CREATE FUNCTION affiliate_request_payout(p_user BIGINT,p_currency TEXT,p_method TEXT,p_name TEXT,p_account TEXT) RETURNS BIGINT LANGUAGE plpgsql AS $$
DECLARE total NUMERIC(12,2); debt NUMERIC(12,2); payout BIGINT;
BEGIN
PERFORM 1 FROM affiliates a JOIN users u ON u.id=a.user_id WHERE a.user_id=p_user AND a.status='APPROVED' AND u.status='ACTIVE' FOR UPDATE OF a;
IF NOT FOUND THEN RAISE EXCEPTION 'Approved active affiliate required' USING ERRCODE='23514'; END IF;
IF EXISTS(SELECT 1 FROM affiliate_payouts WHERE user_id=p_user AND currency=p_currency AND status='REQUESTED') THEN RAISE EXCEPTION 'A payout is already pending for this currency' USING ERRCODE='23514'; END IF;
SELECT COALESCE(SUM(amount),0) INTO total FROM referral_commissions WHERE referrer_id=p_user AND currency=p_currency AND reversed_at IS NULL AND available_at<=now() AND payout_id IS NULL;
SELECT COALESCE(SUM(c.amount),0) INTO debt FROM referral_commissions c JOIN affiliate_payouts p ON p.id=c.payout_id WHERE c.referrer_id=p_user AND c.currency=p_currency AND c.reversed_at IS NOT NULL AND p.status='PAID' AND c.recovery_payout_id IS NULL;
IF total-debt<=0 THEN RAISE EXCEPTION 'No available earnings after reversals' USING ERRCODE='23514'; END IF;
INSERT INTO affiliate_payouts(user_id,currency,amount,method,account_name,account_reference) VALUES(p_user,p_currency,total-debt,p_method,p_name,p_account) RETURNING id INTO payout;
UPDATE referral_commissions SET payout_id=payout WHERE referrer_id=p_user AND currency=p_currency AND reversed_at IS NULL AND available_at<=now() AND payout_id IS NULL;
UPDATE referral_commissions c SET recovery_payout_id=payout FROM affiliate_payouts p WHERE c.payout_id=p.id AND p.status='PAID' AND c.referrer_id=p_user AND c.currency=p_currency AND c.reversed_at IS NOT NULL AND c.recovery_payout_id IS NULL;
INSERT INTO affiliate_events(affiliate_user_id,event,details) VALUES(p_user,'PAYOUT_REQUESTED',jsonb_build_object('payout_id',payout,'currency',p_currency,'amount',total-debt,'recovered',debt));
RETURN payout;
END; $$;
CREATE FUNCTION affiliate_review_payout(p_id BIGINT,p_status TEXT,p_actor BIGINT,p_reference TEXT,p_note TEXT) RETURNS BIGINT LANGUAGE plpgsql AS $$
DECLARE p affiliate_payouts%ROWTYPE; owner_id BIGINT;
BEGIN
SELECT user_id INTO owner_id FROM affiliate_payouts WHERE id=p_id;
IF NOT FOUND THEN RAISE EXCEPTION 'Payout not found' USING ERRCODE='P0002'; END IF;
PERFORM 1 FROM affiliates WHERE user_id=owner_id FOR UPDATE;
SELECT * INTO p FROM affiliate_payouts WHERE id=p_id FOR UPDATE;
IF p.status=p_status AND (p_status='REJECTED' OR p.payment_reference=p_reference) THEN RETURN p_id; END IF;
IF p.status<>'REQUESTED' OR p_status NOT IN ('PAID','REJECTED') THEN RAISE EXCEPTION 'Payout already reviewed or invalid status' USING ERRCODE='23514'; END IF;
IF length(trim(p_note))<3 OR length(p_note)>2000 THEN RAISE EXCEPTION 'A payout review note is required' USING ERRCODE='23514'; END IF;
IF p_status='PAID' THEN
IF NOT EXISTS(SELECT 1 FROM affiliates a JOIN users u ON u.id=a.user_id WHERE a.user_id=owner_id AND a.status='APPROVED' AND u.status='ACTIVE') THEN RAISE EXCEPTION 'Affiliate is not active and approved' USING ERRCODE='23514'; END IF;
IF length(trim(p_reference)) NOT BETWEEN 3 AND 120 THEN RAISE EXCEPTION 'An external payment reference is required' USING ERRCODE='23514'; END IF;
ELSE
UPDATE referral_commissions SET payout_id=NULL WHERE payout_id=p_id;
UPDATE referral_commissions SET recovery_payout_id=NULL WHERE recovery_payout_id=p_id;
END IF;
UPDATE affiliate_payouts SET status=p_status,reviewed_by=p_actor,payment_reference=CASE WHEN p_status='PAID' THEN p_reference ELSE NULL END,review_note=p_note,reviewed_at=now() WHERE id=p_id;
INSERT INTO affiliate_events(affiliate_user_id,actor_id,event,details) VALUES(owner_id,p_actor,'PAYOUT_REVIEWED',jsonb_build_object('payout_id',p_id,'status',p_status,'reference',p_reference,'note',p_note));
RETURN p_id;
END; $$;
CREATE FUNCTION affiliate_settings_audit() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO affiliate_events(actor_id,event,details) VALUES(NEW.updated_by,'SETTINGS_UPDATED',jsonb_build_object('percent',NEW.commission_percent,'mode',NEW.commission_mode,'attribution_days',NEW.attribution_days,'holding_days',NEW.holding_days,'share_base_url',NEW.share_base_url));
RETURN NEW;
END; $$;
CREATE TRIGGER affiliate_settings_audit AFTER UPDATE ON referral_settings FOR EACH ROW EXECUTE FUNCTION affiliate_settings_audit();
COMMIT;

72
db/query/affiliates.sql Normal file
View File

@ -0,0 +1,72 @@
-- name: AffiliateApply :one
SELECT affiliate_apply(sqlc.arg(user_id)::bigint,sqlc.arg(application)::text)::bigint AS user_id;
-- name: AffiliateReview :one
SELECT affiliate_review(sqlc.arg(user_id)::bigint,sqlc.arg(status)::text,sqlc.arg(actor_id)::bigint,sqlc.arg(note)::text)::bigint AS user_id;
-- name: AffiliateProfile :one
SELECT a.*,u.email,u.first_name,u.last_name,COALESCE(rc.code,'')::text AS code
FROM affiliates a JOIN users u ON u.id=a.user_id LEFT JOIN referral_codes rc ON rc.user_id=a.user_id WHERE a.user_id=$1;
-- name: AffiliateList :many
SELECT a.*,u.email,u.first_name,u.last_name,COALESCE(rc.code,'')::text AS code
FROM affiliates a JOIN users u ON u.id=a.user_id LEFT JOIN referral_codes rc ON rc.user_id=a.user_id
WHERE (sqlc.arg(status)::text='' OR a.status=sqlc.arg(status))
ORDER BY a.created_at DESC,a.user_id DESC LIMIT sqlc.arg(page_limit)::int OFFSET sqlc.arg(page_offset)::int;
-- name: AffiliateCount :one
SELECT COUNT(*) FROM affiliates WHERE (sqlc.arg(status)::text='' OR status=sqlc.arg(status));
-- name: AffiliateSettings :one
SELECT commission_percent::text AS commission_percent,commission_mode,attribution_days,holding_days,share_base_url,updated_at FROM referral_settings WHERE id=TRUE;
-- name: AffiliateUpdateSettings :one
UPDATE referral_settings SET commission_percent=sqlc.arg(commission_percent)::numeric,commission_mode=sqlc.arg(commission_mode)::text,
attribution_days=sqlc.arg(attribution_days)::int,holding_days=sqlc.arg(holding_days)::int,share_base_url=sqlc.arg(share_base_url)::text,updated_by=sqlc.arg(actor_id)::bigint,updated_at=now() WHERE id=TRUE
RETURNING commission_percent::text AS commission_percent,commission_mode,attribution_days,holding_days,share_base_url,updated_at;
-- name: AffiliateBalances :many
WITH earnings AS (
SELECT c.currency,
SUM(CASE WHEN c.reversed_at IS NULL AND c.payout_id IS NULL AND c.available_at>now() THEN c.amount ELSE 0 END) AS pending,
SUM(CASE WHEN c.reversed_at IS NULL AND c.payout_id IS NULL AND c.available_at<=now() THEN c.amount ELSE 0 END) AS available,
SUM(CASE WHEN c.reversed_at IS NOT NULL THEN c.amount ELSE 0 END) AS reversed,
SUM(CASE WHEN c.reversed_at IS NOT NULL AND c.recovery_payout_id IS NULL AND p.status='PAID' THEN c.amount ELSE 0 END) AS debt
FROM referral_commissions c LEFT JOIN affiliate_payouts p ON p.id=c.payout_id WHERE c.referrer_id=$1 GROUP BY c.currency
), payouts AS (
SELECT currency,SUM(CASE WHEN status='REQUESTED' THEN amount ELSE 0 END) AS reserved,SUM(CASE WHEN status='PAID' THEN amount ELSE 0 END) AS paid FROM affiliate_payouts WHERE user_id=$1 GROUP BY currency
)
SELECT e.currency,e.pending::text AS pending,(e.available-e.debt)::text AS available,e.reversed::text AS reversed,e.debt::text AS recovery_due,
COALESCE(p.reserved,0)::text AS reserved,COALESCE(p.paid,0)::text AS paid
FROM earnings e LEFT JOIN payouts p ON p.currency=e.currency ORDER BY e.currency;
-- name: AffiliateCommissions :many
SELECT c.id,c.referrer_id,c.payment_id,c.course_id,c.commission_percent::text AS commission_percent,c.amount::text AS amount,c.currency,c.created_at,c.available_at,c.reversed_at,c.reversal_reason,c.payout_id,
(CASE WHEN c.reversed_at IS NOT NULL THEN 'REVERSED' WHEN p.status='PAID' THEN 'PAID' WHEN p.status='REQUESTED' THEN 'RESERVED' WHEN c.available_at>now() THEN 'PENDING' ELSE 'AVAILABLE' END)::text AS status
FROM referral_commissions c LEFT JOIN affiliate_payouts p ON p.id=c.payout_id
WHERE (sqlc.arg(user_id)::bigint=0 OR c.referrer_id=sqlc.arg(user_id))
ORDER BY c.created_at DESC,c.id DESC LIMIT sqlc.arg(page_limit)::int OFFSET sqlc.arg(page_offset)::int;
-- name: AffiliateCommissionCount :one
SELECT COUNT(*) FROM referral_commissions WHERE (sqlc.arg(user_id)::bigint=0 OR referrer_id=sqlc.arg(user_id));
-- name: AffiliateReverseCommission :one
SELECT affiliate_reverse_commission(sqlc.arg(commission_id)::bigint,sqlc.arg(actor_id)::bigint,sqlc.arg(reason)::text)::bigint AS id;
-- name: AffiliateRequestPayout :one
SELECT affiliate_request_payout(sqlc.arg(user_id)::bigint,sqlc.arg(currency)::text,sqlc.arg(method)::text,sqlc.arg(account_name)::text,sqlc.arg(account_reference)::text)::bigint AS id;
-- name: AffiliateReviewPayout :one
SELECT affiliate_review_payout(sqlc.arg(payout_id)::bigint,sqlc.arg(status)::text,sqlc.arg(actor_id)::bigint,sqlc.arg(payment_reference)::text,sqlc.arg(note)::text)::bigint AS id;
-- name: AffiliatePayouts :many
SELECT id,user_id,currency,amount::text AS amount,status,method,account_name,account_reference,payment_reference,review_note,reviewed_by,created_at,reviewed_at
FROM affiliate_payouts WHERE (sqlc.arg(user_id)::bigint=0 OR user_id=sqlc.arg(user_id)) AND (sqlc.arg(status)::text='' OR status=sqlc.arg(status))
ORDER BY created_at DESC,id DESC LIMIT sqlc.arg(page_limit)::int OFFSET sqlc.arg(page_offset)::int;
-- name: AffiliatePayoutCount :one
SELECT COUNT(*) FROM affiliate_payouts WHERE (sqlc.arg(user_id)::bigint=0 OR user_id=sqlc.arg(user_id)) AND (sqlc.arg(status)::text='' OR status=sqlc.arg(status));
-- name: AffiliateEvents :many
SELECT id,affiliate_user_id,actor_id,event,details,created_at FROM affiliate_events
WHERE (sqlc.arg(user_id)::bigint=0 OR affiliate_user_id=sqlc.arg(user_id)) ORDER BY id DESC LIMIT sqlc.arg(page_limit)::int OFFSET sqlc.arg(page_offset)::int;

View File

@ -1,5 +1,5 @@
-- name: ExamPrepCreateCatalogCourse :one
INSERT INTO exam_prep.catalog_courses (name, description, category, thumbnail, sort_order, publish_status, access_tier)
INSERT INTO exam_prep.catalog_courses (name, description, category, thumbnail, sort_order, publish_status, access_tier, price, currency)
SELECT
$1,
$2,
@ -10,7 +10,9 @@ SELECT
max(c.sort_order)
FROM exam_prep.catalog_courses AS c), 0) + 1,
$5,
$6
$6,
sqlc.arg(price)::numeric,
sqlc.arg(currency)::varchar
RETURNING
*;
@ -81,6 +83,8 @@ SELECT
c.sort_order,
c.publish_status,
c.access_tier,
c.price,
c.currency,
COALESCE(cc.units_count, 0)::BIGINT AS units_count,
COALESCE(cc.modules_count, 0)::BIGINT AS modules_count,
COALESCE(cc.lessons_count, 0)::BIGINT AS lessons_count,
@ -150,6 +154,8 @@ SET
sort_order = coalesce(sqlc.narg('sort_order')::int, sort_order),
publish_status = coalesce(sqlc.narg('publish_status')::varchar, publish_status),
access_tier = coalesce(sqlc.narg('access_tier')::varchar, access_tier),
price = coalesce(sqlc.narg('price')::numeric, price),
currency = coalesce(sqlc.narg('currency')::varchar, currency),
updated_at = CURRENT_TIMESTAMP
WHERE id = sqlc.arg('id')
RETURNING

View File

@ -5,9 +5,9 @@
-- name: CreatePayment :one
INSERT INTO payments (
user_id, plan_id, subscription_id, session_id, transaction_id, nonce,
amount, currency, payment_method, status, payment_url, expires_at
amount, currency, payment_method, status, payment_url, expires_at, course_id
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, COALESCE($10, 'PENDING'), $11, $12)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, COALESCE($10, 'PENDING'), $11, $12, sqlc.narg(course_id)::bigint)
RETURNING *;
-- name: GetPaymentByID :one
@ -41,7 +41,7 @@ UPDATE payments
SET
status = $1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2;
WHERE id = $2 AND status <> 'SUCCESS';
-- name: UpdatePaymentStatusBySessionID :exec
UPDATE payments
@ -61,7 +61,7 @@ SET
payment_method = COALESCE(sqlc.arg(payment_method)::text, payment_method),
paid_at = CASE WHEN sqlc.arg(status)::varchar = 'SUCCESS' THEN CURRENT_TIMESTAMP ELSE paid_at END,
updated_at = CURRENT_TIMESTAMP
WHERE nonce = sqlc.arg(nonce)::text;
WHERE nonce = sqlc.arg(nonce)::text AND status <> 'SUCCESS';
-- name: UpdatePaymentSessionID :exec
UPDATE payments
@ -157,6 +157,7 @@ SELECT COUNT(*) FROM payments WHERE user_id = $1;
SELECT
p.id,
p.user_id,
p.course_id,
p.plan_id,
p.subscription_id,
p.session_id,

View File

@ -1,23 +1,31 @@
-- name: GetReferralCode :one
SELECT code FROM referral_codes WHERE user_id = $1;
SELECT rc.code FROM referral_codes rc JOIN affiliates a ON a.user_id=rc.user_id AND a.status='APPROVED' JOIN users u ON u.id=rc.user_id AND u.status='ACTIVE' WHERE rc.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'
SELECT users.id, $2 FROM users WHERE users.id = $1 AND role IN ('STUDENT', 'OPEN_LEARNER') AND status = 'ACTIVE' AND EXISTS(SELECT 1 FROM affiliates a WHERE a.user_id=users.id AND a.status='APPROVED')
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
-- name: ApplyReferralCode :one
-- Same-code retries remain safe after purchase without replacing or renewing attribution.
WITH existing AS (
SELECT r.id FROM user_referrals r JOIN referral_codes rc ON rc.id=r.referral_code_id
WHERE r.referred_user_id=sqlc.arg('referred_user_id') AND rc.code=sqlc.arg('code')
), applied AS (
INSERT INTO user_referrals (referrer_id, referred_user_id, referral_code_id,attributed_until)
SELECT rc.user_id, u.id, rc.id,now()+make_interval(days=>rs.attribution_days)
FROM referral_codes rc JOIN users owner ON owner.id = rc.user_id JOIN affiliates a ON a.user_id=rc.user_id AND a.status='APPROVED' CROSS JOIN referral_settings rs
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 u.status='ACTIVE' AND NOT EXISTS(SELECT 1 FROM existing)
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;
ON CONFLICT (referred_user_id) DO UPDATE SET referred_user_id=user_referrals.referred_user_id
WHERE user_referrals.referrer_id=EXCLUDED.referrer_id AND user_referrals.referral_code_id=EXCLUDED.referral_code_id RETURNING id
)
SELECT ((SELECT count(*) FROM existing)+(SELECT count(*) FROM applied))::bigint AS applied_count;
-- name: GetReferralSummary :one
SELECT COUNT(*) AS total_referrals,
@ -40,7 +48,7 @@ updated_by = sqlc.arg('updated_by'), updated_at = CURRENT_TIMESTAMP WHERE id = T
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
SELECT currency, (SUM(CASE WHEN reversed_at IS NULL AND available_at<=now() AND payout_id IS NULL THEN amount ELSE 0 END) - SUM(CASE WHEN reversed_at IS NOT NULL AND recovery_payout_id IS NULL AND EXISTS(SELECT 1 FROM affiliate_payouts p WHERE p.id=referral_commissions.payout_id AND p.status='PAID') THEN amount ELSE 0 END))::text AS balance
FROM referral_commissions WHERE referrer_id = $1 GROUP BY currency ORDER BY currency;
-- name: ListReferralCommissions :many

65
docs/affiliate-program.md Normal file
View File

@ -0,0 +1,65 @@
# Affiliate program
This implementation sells courses and credits approved affiliates for verified course payments. Subscription payments do not generate new affiliate earnings. Historical referral records and commissions are retained; existing code owners must apply and be approved before their codes can attract new referrals.
## Default rules
- Applications require explicit acceptance of version 1 of the rules returned by `GET /api/v1/affiliates/me`. ADMIN and SUPER_ADMIN can approve/reject pending applications, suspend approved affiliates, and restore suspended affiliates. Rejected applicants can resubmit; suspension cannot be bypassed by reapplying.
- First-touch attribution is permanent for a learner account and must be submitted before the first successful positive payment. Self-referrals, replacing a referrer, inactive affiliates, and unapproved codes are rejected. Existing learners can apply a code before their first purchase. Applying a code snapshots its expiry; the default attribution period is 30 days.
- The default commission policy is FIRST_PURCHASE. Admins may choose EVERY_COURSE to reward each distinct course bought within attribution. A repeated purchase of the same course never earns another commission. Attribution expires at payment confirmation, not checkout initiation.
- Default commission is 0%, intentionally disabled until configured. Qualifying zero-rate sales are recorded, preventing later retries from earning a changed rate. Rates, attribution windows, and hold periods are not retroactive. Old first-payment conversions remain consumed.
- Default earning hold is 14 days. Wallets distinguish pending, available, reserved, paid, reversed, and recovery due. Currencies never combine and commissions use the gross verified course payment amount, and all money calculations use PostgreSQL NUMERIC with two-decimal rounding.
- Payout requests reserve all matured available earnings in one currency after outstanding recovery debts. Only one pending payout is allowed per affiliate/currency. The request snapshots BANK/MOBILE_MONEY beneficiary details. No arbitrary withdrawal amount is accepted from the client.
- Payouts are manual: transfer money externally, then record PAID with a unique transfer reference and review note. The API does not initiate bank/mobile money transfers. Rejection releases the reservation. Suspended/inactive affiliates cannot request payouts or have payouts marked paid.
- Reversing a commission rejects any pending payout for that affiliate/currency and releases its reservations. If already paid, the commission becomes recovery debt deducted from a future payout. Settled transfers are immutable. An admin reversal requires a reason and does not itself refund the learner or remove course access. If a payment leaves SUCCESS through a supported accounting operation, the database trigger reverses its commission automatically. Normal gateway callbacks cannot downgrade confirmed course payments.
- Financial mutations and settings changes produce affiliate_events records. User and ledger foreign keys retain financial audit history; do not hard-delete affiliate identities without accounting reconciliation.
## Learner API
All paths below use `/api/v1` and authenticated learner tokens. Requests are scoped to the authenticated account; learner-supplied user IDs never select another affiliate's records.
| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/affiliates/me` | Application status, current rules/settings, share link, conversions, balances |
| POST | `/affiliates/apply` | `{ "application":"How I promote courses...", "accept_terms":true, "terms_version":"1" }` |
| GET | `/affiliates/commissions?limit=20&offset=0` | Own earning ledger |
| GET | `/affiliates/payouts?limit=20&offset=0&status=REQUESTED` | Own payout history |
| POST | `/affiliates/payouts` | `{ "currency":"ETB", "method":"BANK", "account_name":"Artist Name", "account_reference":"bank/account details" }` |
| POST | `/referrals/apply` | `{ "code":"ABCDEF0123456789" }` before first purchase |
| POST | `/courses/:courseId/checkout` | Optional `referral_code` applies attribution before creating checkout |
Share URLs add `ref=CODE` to the configured learner registration URL, preserving other query values. No destination is invented when it is unconfigured. Learner web/mobile clients must retain that code through login and submit it to `/referrals/apply` (or in course checkout) before payment. This repository adds APIs and admin UI; no learner mobile app is present here. Codes continue to work independently of share URLs.
The learner dashboard exposes no referred-user email/name. Existing `/referrals` summary/history/wallet endpoints remain for compatibility. Their balance now means available, unreserved earnings after unrecovered paid reversals. Approved affiliation is required to obtain/share codes.
## Admin integration
The panel's `/affiliates` page has Applications, Commissions, Payouts, Events, and Settings tabs. Only ADMIN and SUPER_ADMIN can use the backend admin endpoints; the frontend also checks that role. Review and financial actions use dialogs with required notes. The old referral settings tab links here and still adjusts the same global percentage.
Admin API root: `/api/v1/admin/affiliates`:
- `GET /` filters applications by status with pagination.
- `PUT /:id/review` accepts `{status,note}`; id is the learner user ID.
- `GET/PUT /settings` uses `{commission_percent,commission_mode,attribution_days,holding_days,share_base_url}`.
- `GET /commissions` and `GET /payouts` accept `user_id`, `limit`, `offset`; payouts also accept status.
- `POST /commissions/:id/reverse` accepts `{reason}`.
- `PUT /payouts/:id/review` accepts `{status:"PAID"|"REJECTED",note,payment_reference}`.
- `GET /events` returns newest-first audit entries, optionally filtered by `user_id`.
Mutation conflicts return 409, malformed inputs 400, missing records 404, and non-admin requests 403. Lists cap page size at 100. Payout details contain personal financial information and are only exposed to their owner and admins.
## Rollout and checks
Apply `000008_course_purchases` followed by `000009_affiliate_program` before running this backend. Configure the rate and learner registration URL, publish priced courses, approve affiliates, and connect learner clients to the API flow above. The migration intentionally grants no automatic affiliate approval and issues no money transfers. Rollback refuses to discard existing affiliate applications, sales, or payouts; reconcile and export records first.
Run `go test ./...`, `npm run test:learning`, and `npm run build` in the admin project. `AFFILIATE_TEST_DB_URL` enables a transaction-rolled-back integration test on a disposable PostgreSQL database migrated through 000009. Never point that test at production. The ledger uses a consistent affiliate-first lock order for payouts/reversals and serializes payments/attribution by learner to avoid duplicate rewards and overspending under concurrent requests.
An isolated PostgreSQL engine check can run without Docker or a live database:
```powershell
npm install --prefix tmp/affiliate-db-qa @electric-sql/pglite --no-audit --no-fund
node scripts/affiliate-ledger-test.mjs
```
It creates an in-memory minimal payment/course fixture, applies the actual referral and affiliate migrations, and exercises approvals, duplicate confirmations, distinct-course rewards, zero-rate snapshots, payout reservations, paid reversals and debt recovery, holds, expiry, suspension, first-purchase policy, and automatic reversal. This validates SQL behavior but does not replace testing the complete production schema or concurrent transactions against a migrated PostgreSQL server.

43
docs/course-pricing.md Normal file
View File

@ -0,0 +1,43 @@
# Course pricing and access
Learning content is sold through one-time course purchases. A verified purchase permanently unlocks premium content in that course only. Subscription plans no longer grant access to the current learning catalog, including for existing subscribers. Subscription and payment history remain available.
Courses expose `price` (up to two decimal places, nonnegative) and `currency` (three uppercase letters; default `ETB`). Set these with the existing admin course create/update APIs. No chapter or lesson has its own price. A positive course price is required for checkout. Existing courses start at zero during migration: configure their actual selling prices before enabling checkout in clients. Zero-priced premium content stays locked until a price is configured or its access tier is changed.
Courses retain `FREE` and `PREMIUM`. Chapters and lessons accept `INHERIT`, `FREE`, or `PREMIUM`. Omission on creation defaults to `INHERIT`; omission on update preserves the current value. Send `INHERIT` to reset an override. The nearest explicit tier wins:
| Course | Chapter | Lesson | Effective lesson access |
| --- | --- | --- | --- |
| PREMIUM | INHERIT | INHERIT | PREMIUM |
| FREE | INHERIT | INHERIT | FREE |
| PREMIUM | FREE | INHERIT | FREE |
| PREMIUM | PREMIUM | FREE | FREE |
| FREE | FREE | PREMIUM | PREMIUM |
Changing a parent changes all descendants that inherit it. Explicit child overrides remain in place. A free course may have a positive price for its explicitly premium descendants; the course's tier controls default access, while its price is the purchase amount. Quizzes inherit the chapter's effective tier. Publication restrictions still apply. Staff and `OPEN_LEARNER` retain their existing bypass behavior.
## API
- `POST /api/v1/courses/:courseId/checkout`, authenticated: optional `{ "phone": "..." }`. The server loads the course's price/currency and learner email, creates a Chapa checkout, and returns `payment_id`, `session_id`, `payment_url`, `course_id`, `amount`, and `currency`. Purchasing an owned course returns 409; unpublished, archived, or zero-price courses cannot be purchased.
- Existing payment verification, signed webhook, and callback endpoints confirm payment. Amount and currency must match the checkout snapshot. Payment success and course entitlement commit atomically; repeated confirmation is idempotent.
- Course catalog responses include `price` and `currency`. Learner course/chapter/lesson responses expose purchase restrictions through `access.is_accessible` and `access.reason`. Locked lesson lists omit `video_url`; an explicit free preview remains available without purchase.
- Premium lesson retrieval, quiz/practice questions, completion, and video heartbeats require the containing course purchase. A blocked consumption request returns 403 with `code: COURSE_PURCHASE_REQUIRED` and `course_id`. File URL generation/refresh also checks course access for known lesson videos.
- Learner subscription-plan listing and subscription checkout routes now return 410, directing clients to course checkout. Historical subscription status, history, cancellation, and payment records remain available. Old direct subscription payment initiation routes also return 410. Existing pending subscription payments may still settle for historical accounting, but do not grant course access.
Example admin course body:
```json
{"name":"Bridal Makeup","access_tier":"PREMIUM","price":1500,"currency":"ETB"}
```
Example preview lesson body:
```json
{"title":"Introduction","access_tier":"FREE"}
```
## Rollout
Apply `000008_course_purchases` before running this backend. It adds course pricing, a course reference on payments, and course purchase records. Existing effective access restrictions are preserved; redundant child tiers become inherited so later parent edits cascade. Legacy internal chapter containers inherit rather than overriding the chapter.
Configure course prices and update frontend/mobile checkout to use course IDs instead of plan IDs. Existing subscribers must purchase courses after this switch; this migration intentionally grants no ownership from subscription records. No existing subscription/payment history is deleted. Rollback removes course purchases/pricing and restores legacy tier constraints, so export purchase records before rolling back a live rollout.

File diff suppressed because it is too large Load Diff

View File

@ -26,8 +26,8 @@ Create a question set with `set_type: "QUIZ"`, then create its chapter quiz with
`question_set_id` and an optional `title`. Omit parent fields: the chapter URL
determines placement. Both the quiz and its question set must be published for
learner visibility. Learners read questions at `/quizzes/:id/questions` and submit
completion at `POST /progress/quizzes/:id/complete`. Existing subscription and
content access rules still apply.
completion at `POST /progress/quizzes/:id/complete`. Course purchase and
content access rules still apply. See [Course pricing](course-pricing.md).
## Admin integration and Swagger
@ -76,3 +76,7 @@ historical progress discriminators remain storage details for compatibility.
Public practice parents serialize as `COURSE`, `CHAPTER`, or `LESSON`.
Migration backup tables preserve original category and lesson placement for a
rollback; newly authored lessons stay in their chapter containers on rollback.
## Course pricing
Learning access uses course purchases instead of subscription plans. Courses have custom `price` and `currency`; chapters and lessons default to `INHERIT` and can override access with `FREE` or `PREMIUM`. See [Course pricing](course-pricing.md) for checkout and rollout details.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

557
gen/db/affiliates.sql.go Normal file
View File

@ -0,0 +1,557 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: affiliates.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const AffiliateApply = `-- name: AffiliateApply :one
SELECT affiliate_apply($1::bigint,$2::text)::bigint AS user_id
`
type AffiliateApplyParams struct {
UserID int64 `json:"user_id"`
Application string `json:"application"`
}
func (q *Queries) AffiliateApply(ctx context.Context, arg AffiliateApplyParams) (int64, error) {
row := q.db.QueryRow(ctx, AffiliateApply, arg.UserID, arg.Application)
var user_id int64
err := row.Scan(&user_id)
return user_id, err
}
const AffiliateBalances = `-- name: AffiliateBalances :many
WITH earnings AS (
SELECT c.currency,
SUM(CASE WHEN c.reversed_at IS NULL AND c.payout_id IS NULL AND c.available_at>now() THEN c.amount ELSE 0 END) AS pending,
SUM(CASE WHEN c.reversed_at IS NULL AND c.payout_id IS NULL AND c.available_at<=now() THEN c.amount ELSE 0 END) AS available,
SUM(CASE WHEN c.reversed_at IS NOT NULL THEN c.amount ELSE 0 END) AS reversed,
SUM(CASE WHEN c.reversed_at IS NOT NULL AND c.recovery_payout_id IS NULL AND p.status='PAID' THEN c.amount ELSE 0 END) AS debt
FROM referral_commissions c LEFT JOIN affiliate_payouts p ON p.id=c.payout_id WHERE c.referrer_id=$1 GROUP BY c.currency
), payouts AS (
SELECT currency,SUM(CASE WHEN status='REQUESTED' THEN amount ELSE 0 END) AS reserved,SUM(CASE WHEN status='PAID' THEN amount ELSE 0 END) AS paid FROM affiliate_payouts WHERE user_id=$1 GROUP BY currency
)
SELECT e.currency,e.pending::text AS pending,(e.available-e.debt)::text AS available,e.reversed::text AS reversed,e.debt::text AS recovery_due,
COALESCE(p.reserved,0)::text AS reserved,COALESCE(p.paid,0)::text AS paid
FROM earnings e LEFT JOIN payouts p ON p.currency=e.currency ORDER BY e.currency
`
type AffiliateBalancesRow struct {
Currency string `json:"currency"`
Pending string `json:"pending"`
Available string `json:"available"`
Reversed string `json:"reversed"`
RecoveryDue string `json:"recovery_due"`
Reserved string `json:"reserved"`
Paid string `json:"paid"`
}
func (q *Queries) AffiliateBalances(ctx context.Context, referrerID int64) ([]AffiliateBalancesRow, error) {
rows, err := q.db.Query(ctx, AffiliateBalances, referrerID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AffiliateBalancesRow
for rows.Next() {
var i AffiliateBalancesRow
if err := rows.Scan(
&i.Currency,
&i.Pending,
&i.Available,
&i.Reversed,
&i.RecoveryDue,
&i.Reserved,
&i.Paid,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const AffiliateCommissionCount = `-- name: AffiliateCommissionCount :one
SELECT COUNT(*) FROM referral_commissions WHERE ($1::bigint=0 OR referrer_id=$1)
`
func (q *Queries) AffiliateCommissionCount(ctx context.Context, userID int64) (int64, error) {
row := q.db.QueryRow(ctx, AffiliateCommissionCount, userID)
var count int64
err := row.Scan(&count)
return count, err
}
const AffiliateCommissions = `-- name: AffiliateCommissions :many
SELECT c.id,c.referrer_id,c.payment_id,c.course_id,c.commission_percent::text AS commission_percent,c.amount::text AS amount,c.currency,c.created_at,c.available_at,c.reversed_at,c.reversal_reason,c.payout_id,
(CASE WHEN c.reversed_at IS NOT NULL THEN 'REVERSED' WHEN p.status='PAID' THEN 'PAID' WHEN p.status='REQUESTED' THEN 'RESERVED' WHEN c.available_at>now() THEN 'PENDING' ELSE 'AVAILABLE' END)::text AS status
FROM referral_commissions c LEFT JOIN affiliate_payouts p ON p.id=c.payout_id
WHERE ($1::bigint=0 OR c.referrer_id=$1)
ORDER BY c.created_at DESC,c.id DESC LIMIT $3::int OFFSET $2::int
`
type AffiliateCommissionsParams struct {
UserID int64 `json:"user_id"`
PageOffset int32 `json:"page_offset"`
PageLimit int32 `json:"page_limit"`
}
type AffiliateCommissionsRow struct {
ID int64 `json:"id"`
ReferrerID int64 `json:"referrer_id"`
PaymentID int64 `json:"payment_id"`
CourseID pgtype.Int8 `json:"course_id"`
CommissionPercent string `json:"commission_percent"`
Amount string `json:"amount"`
Currency string `json:"currency"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
AvailableAt pgtype.Timestamptz `json:"available_at"`
ReversedAt pgtype.Timestamptz `json:"reversed_at"`
ReversalReason pgtype.Text `json:"reversal_reason"`
PayoutID pgtype.Int8 `json:"payout_id"`
Status string `json:"status"`
}
func (q *Queries) AffiliateCommissions(ctx context.Context, arg AffiliateCommissionsParams) ([]AffiliateCommissionsRow, error) {
rows, err := q.db.Query(ctx, AffiliateCommissions, arg.UserID, arg.PageOffset, arg.PageLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AffiliateCommissionsRow
for rows.Next() {
var i AffiliateCommissionsRow
if err := rows.Scan(
&i.ID,
&i.ReferrerID,
&i.PaymentID,
&i.CourseID,
&i.CommissionPercent,
&i.Amount,
&i.Currency,
&i.CreatedAt,
&i.AvailableAt,
&i.ReversedAt,
&i.ReversalReason,
&i.PayoutID,
&i.Status,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const AffiliateCount = `-- name: AffiliateCount :one
SELECT COUNT(*) FROM affiliates WHERE ($1::text='' OR status=$1)
`
func (q *Queries) AffiliateCount(ctx context.Context, status string) (int64, error) {
row := q.db.QueryRow(ctx, AffiliateCount, status)
var count int64
err := row.Scan(&count)
return count, err
}
const AffiliateEvents = `-- name: AffiliateEvents :many
SELECT id,affiliate_user_id,actor_id,event,details,created_at FROM affiliate_events
WHERE ($1::bigint=0 OR affiliate_user_id=$1) ORDER BY id DESC LIMIT $3::int OFFSET $2::int
`
type AffiliateEventsParams struct {
UserID int64 `json:"user_id"`
PageOffset int32 `json:"page_offset"`
PageLimit int32 `json:"page_limit"`
}
func (q *Queries) AffiliateEvents(ctx context.Context, arg AffiliateEventsParams) ([]AffiliateEvent, error) {
rows, err := q.db.Query(ctx, AffiliateEvents, arg.UserID, arg.PageOffset, arg.PageLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AffiliateEvent
for rows.Next() {
var i AffiliateEvent
if err := rows.Scan(
&i.ID,
&i.AffiliateUserID,
&i.ActorID,
&i.Event,
&i.Details,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const AffiliateList = `-- name: AffiliateList :many
SELECT a.user_id, a.status, a.application, a.terms_accepted_at, a.terms_version, a.reviewed_by, a.review_note, a.created_at, a.updated_at,u.email,u.first_name,u.last_name,COALESCE(rc.code,'')::text AS code
FROM affiliates a JOIN users u ON u.id=a.user_id LEFT JOIN referral_codes rc ON rc.user_id=a.user_id
WHERE ($1::text='' OR a.status=$1)
ORDER BY a.created_at DESC,a.user_id DESC LIMIT $3::int OFFSET $2::int
`
type AffiliateListParams struct {
Status string `json:"status"`
PageOffset int32 `json:"page_offset"`
PageLimit int32 `json:"page_limit"`
}
type AffiliateListRow struct {
UserID int64 `json:"user_id"`
Status string `json:"status"`
Application string `json:"application"`
TermsAcceptedAt pgtype.Timestamptz `json:"terms_accepted_at"`
TermsVersion string `json:"terms_version"`
ReviewedBy pgtype.Int8 `json:"reviewed_by"`
ReviewNote string `json:"review_note"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Email pgtype.Text `json:"email"`
FirstName pgtype.Text `json:"first_name"`
LastName pgtype.Text `json:"last_name"`
Code string `json:"code"`
}
func (q *Queries) AffiliateList(ctx context.Context, arg AffiliateListParams) ([]AffiliateListRow, error) {
rows, err := q.db.Query(ctx, AffiliateList, arg.Status, arg.PageOffset, arg.PageLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AffiliateListRow
for rows.Next() {
var i AffiliateListRow
if err := rows.Scan(
&i.UserID,
&i.Status,
&i.Application,
&i.TermsAcceptedAt,
&i.TermsVersion,
&i.ReviewedBy,
&i.ReviewNote,
&i.CreatedAt,
&i.UpdatedAt,
&i.Email,
&i.FirstName,
&i.LastName,
&i.Code,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const AffiliatePayoutCount = `-- name: AffiliatePayoutCount :one
SELECT COUNT(*) FROM affiliate_payouts WHERE ($1::bigint=0 OR user_id=$1) AND ($2::text='' OR status=$2)
`
type AffiliatePayoutCountParams struct {
UserID int64 `json:"user_id"`
Status string `json:"status"`
}
func (q *Queries) AffiliatePayoutCount(ctx context.Context, arg AffiliatePayoutCountParams) (int64, error) {
row := q.db.QueryRow(ctx, AffiliatePayoutCount, arg.UserID, arg.Status)
var count int64
err := row.Scan(&count)
return count, err
}
const AffiliatePayouts = `-- name: AffiliatePayouts :many
SELECT id,user_id,currency,amount::text AS amount,status,method,account_name,account_reference,payment_reference,review_note,reviewed_by,created_at,reviewed_at
FROM affiliate_payouts WHERE ($1::bigint=0 OR user_id=$1) AND ($2::text='' OR status=$2)
ORDER BY created_at DESC,id DESC LIMIT $4::int OFFSET $3::int
`
type AffiliatePayoutsParams struct {
UserID int64 `json:"user_id"`
Status string `json:"status"`
PageOffset int32 `json:"page_offset"`
PageLimit int32 `json:"page_limit"`
}
type AffiliatePayoutsRow struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Currency string `json:"currency"`
Amount string `json:"amount"`
Status string `json:"status"`
Method string `json:"method"`
AccountName string `json:"account_name"`
AccountReference string `json:"account_reference"`
PaymentReference pgtype.Text `json:"payment_reference"`
ReviewNote string `json:"review_note"`
ReviewedBy pgtype.Int8 `json:"reviewed_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
ReviewedAt pgtype.Timestamptz `json:"reviewed_at"`
}
func (q *Queries) AffiliatePayouts(ctx context.Context, arg AffiliatePayoutsParams) ([]AffiliatePayoutsRow, error) {
rows, err := q.db.Query(ctx, AffiliatePayouts,
arg.UserID,
arg.Status,
arg.PageOffset,
arg.PageLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AffiliatePayoutsRow
for rows.Next() {
var i AffiliatePayoutsRow
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.Currency,
&i.Amount,
&i.Status,
&i.Method,
&i.AccountName,
&i.AccountReference,
&i.PaymentReference,
&i.ReviewNote,
&i.ReviewedBy,
&i.CreatedAt,
&i.ReviewedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const AffiliateProfile = `-- name: AffiliateProfile :one
SELECT a.user_id, a.status, a.application, a.terms_accepted_at, a.terms_version, a.reviewed_by, a.review_note, a.created_at, a.updated_at,u.email,u.first_name,u.last_name,COALESCE(rc.code,'')::text AS code
FROM affiliates a JOIN users u ON u.id=a.user_id LEFT JOIN referral_codes rc ON rc.user_id=a.user_id WHERE a.user_id=$1
`
type AffiliateProfileRow struct {
UserID int64 `json:"user_id"`
Status string `json:"status"`
Application string `json:"application"`
TermsAcceptedAt pgtype.Timestamptz `json:"terms_accepted_at"`
TermsVersion string `json:"terms_version"`
ReviewedBy pgtype.Int8 `json:"reviewed_by"`
ReviewNote string `json:"review_note"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Email pgtype.Text `json:"email"`
FirstName pgtype.Text `json:"first_name"`
LastName pgtype.Text `json:"last_name"`
Code string `json:"code"`
}
func (q *Queries) AffiliateProfile(ctx context.Context, userID int64) (AffiliateProfileRow, error) {
row := q.db.QueryRow(ctx, AffiliateProfile, userID)
var i AffiliateProfileRow
err := row.Scan(
&i.UserID,
&i.Status,
&i.Application,
&i.TermsAcceptedAt,
&i.TermsVersion,
&i.ReviewedBy,
&i.ReviewNote,
&i.CreatedAt,
&i.UpdatedAt,
&i.Email,
&i.FirstName,
&i.LastName,
&i.Code,
)
return i, err
}
const AffiliateRequestPayout = `-- name: AffiliateRequestPayout :one
SELECT affiliate_request_payout($1::bigint,$2::text,$3::text,$4::text,$5::text)::bigint AS id
`
type AffiliateRequestPayoutParams struct {
UserID int64 `json:"user_id"`
Currency string `json:"currency"`
Method string `json:"method"`
AccountName string `json:"account_name"`
AccountReference string `json:"account_reference"`
}
func (q *Queries) AffiliateRequestPayout(ctx context.Context, arg AffiliateRequestPayoutParams) (int64, error) {
row := q.db.QueryRow(ctx, AffiliateRequestPayout,
arg.UserID,
arg.Currency,
arg.Method,
arg.AccountName,
arg.AccountReference,
)
var id int64
err := row.Scan(&id)
return id, err
}
const AffiliateReverseCommission = `-- name: AffiliateReverseCommission :one
SELECT affiliate_reverse_commission($1::bigint,$2::bigint,$3::text)::bigint AS id
`
type AffiliateReverseCommissionParams struct {
CommissionID int64 `json:"commission_id"`
ActorID int64 `json:"actor_id"`
Reason string `json:"reason"`
}
func (q *Queries) AffiliateReverseCommission(ctx context.Context, arg AffiliateReverseCommissionParams) (int64, error) {
row := q.db.QueryRow(ctx, AffiliateReverseCommission, arg.CommissionID, arg.ActorID, arg.Reason)
var id int64
err := row.Scan(&id)
return id, err
}
const AffiliateReview = `-- name: AffiliateReview :one
SELECT affiliate_review($1::bigint,$2::text,$3::bigint,$4::text)::bigint AS user_id
`
type AffiliateReviewParams struct {
UserID int64 `json:"user_id"`
Status string `json:"status"`
ActorID int64 `json:"actor_id"`
Note string `json:"note"`
}
func (q *Queries) AffiliateReview(ctx context.Context, arg AffiliateReviewParams) (int64, error) {
row := q.db.QueryRow(ctx, AffiliateReview,
arg.UserID,
arg.Status,
arg.ActorID,
arg.Note,
)
var user_id int64
err := row.Scan(&user_id)
return user_id, err
}
const AffiliateReviewPayout = `-- name: AffiliateReviewPayout :one
SELECT affiliate_review_payout($1::bigint,$2::text,$3::bigint,$4::text,$5::text)::bigint AS id
`
type AffiliateReviewPayoutParams struct {
PayoutID int64 `json:"payout_id"`
Status string `json:"status"`
ActorID int64 `json:"actor_id"`
PaymentReference string `json:"payment_reference"`
Note string `json:"note"`
}
func (q *Queries) AffiliateReviewPayout(ctx context.Context, arg AffiliateReviewPayoutParams) (int64, error) {
row := q.db.QueryRow(ctx, AffiliateReviewPayout,
arg.PayoutID,
arg.Status,
arg.ActorID,
arg.PaymentReference,
arg.Note,
)
var id int64
err := row.Scan(&id)
return id, err
}
const AffiliateSettings = `-- name: AffiliateSettings :one
SELECT commission_percent::text AS commission_percent,commission_mode,attribution_days,holding_days,share_base_url,updated_at FROM referral_settings WHERE id=TRUE
`
type AffiliateSettingsRow struct {
CommissionPercent string `json:"commission_percent"`
CommissionMode string `json:"commission_mode"`
AttributionDays int32 `json:"attribution_days"`
HoldingDays int32 `json:"holding_days"`
ShareBaseUrl string `json:"share_base_url"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
func (q *Queries) AffiliateSettings(ctx context.Context) (AffiliateSettingsRow, error) {
row := q.db.QueryRow(ctx, AffiliateSettings)
var i AffiliateSettingsRow
err := row.Scan(
&i.CommissionPercent,
&i.CommissionMode,
&i.AttributionDays,
&i.HoldingDays,
&i.ShareBaseUrl,
&i.UpdatedAt,
)
return i, err
}
const AffiliateUpdateSettings = `-- name: AffiliateUpdateSettings :one
UPDATE referral_settings SET commission_percent=$1::numeric,commission_mode=$2::text,
attribution_days=$3::int,holding_days=$4::int,share_base_url=$5::text,updated_by=$6::bigint,updated_at=now() WHERE id=TRUE
RETURNING commission_percent::text AS commission_percent,commission_mode,attribution_days,holding_days,share_base_url,updated_at
`
type AffiliateUpdateSettingsParams struct {
CommissionPercent pgtype.Numeric `json:"commission_percent"`
CommissionMode string `json:"commission_mode"`
AttributionDays int32 `json:"attribution_days"`
HoldingDays int32 `json:"holding_days"`
ShareBaseUrl string `json:"share_base_url"`
ActorID int64 `json:"actor_id"`
}
type AffiliateUpdateSettingsRow struct {
CommissionPercent string `json:"commission_percent"`
CommissionMode string `json:"commission_mode"`
AttributionDays int32 `json:"attribution_days"`
HoldingDays int32 `json:"holding_days"`
ShareBaseUrl string `json:"share_base_url"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
func (q *Queries) AffiliateUpdateSettings(ctx context.Context, arg AffiliateUpdateSettingsParams) (AffiliateUpdateSettingsRow, error) {
row := q.db.QueryRow(ctx, AffiliateUpdateSettings,
arg.CommissionPercent,
arg.CommissionMode,
arg.AttributionDays,
arg.HoldingDays,
arg.ShareBaseUrl,
arg.ActorID,
)
var i AffiliateUpdateSettingsRow
err := row.Scan(
&i.CommissionPercent,
&i.CommissionMode,
&i.AttributionDays,
&i.HoldingDays,
&i.ShareBaseUrl,
&i.UpdatedAt,
)
return i, err
}

View File

@ -12,7 +12,7 @@ import (
)
const ExamPrepCreateCatalogCourse = `-- name: ExamPrepCreateCatalogCourse :one
INSERT INTO exam_prep.catalog_courses (name, description, category, thumbnail, sort_order, publish_status, access_tier)
INSERT INTO exam_prep.catalog_courses (name, description, category, thumbnail, sort_order, publish_status, access_tier, price, currency)
SELECT
$1,
$2,
@ -23,18 +23,22 @@ SELECT
max(c.sort_order)
FROM exam_prep.catalog_courses AS c), 0) + 1,
$5,
$6
$6,
$7::numeric,
$8::varchar
RETURNING
id, name, description, thumbnail, sort_order, created_at, updated_at, category, publish_status, access_tier
id, name, description, thumbnail, sort_order, created_at, updated_at, category, publish_status, access_tier, price, currency
`
type ExamPrepCreateCatalogCourseParams struct {
Name string `json:"name"`
Description pgtype.Text `json:"description"`
Category string `json:"category"`
Thumbnail pgtype.Text `json:"thumbnail"`
PublishStatus string `json:"publish_status"`
AccessTier string `json:"access_tier"`
Name string `json:"name"`
Description pgtype.Text `json:"description"`
Category string `json:"category"`
Thumbnail pgtype.Text `json:"thumbnail"`
PublishStatus string `json:"publish_status"`
AccessTier string `json:"access_tier"`
Price pgtype.Numeric `json:"price"`
Currency string `json:"currency"`
}
func (q *Queries) ExamPrepCreateCatalogCourse(ctx context.Context, arg ExamPrepCreateCatalogCourseParams) (ExamPrepCatalogCourse, error) {
@ -45,6 +49,8 @@ func (q *Queries) ExamPrepCreateCatalogCourse(ctx context.Context, arg ExamPrepC
arg.Thumbnail,
arg.PublishStatus,
arg.AccessTier,
arg.Price,
arg.Currency,
)
var i ExamPrepCatalogCourse
err := row.Scan(
@ -58,6 +64,8 @@ func (q *Queries) ExamPrepCreateCatalogCourse(ctx context.Context, arg ExamPrepC
&i.Category,
&i.PublishStatus,
&i.AccessTier,
&i.Price,
&i.Currency,
)
return i, err
}
@ -74,7 +82,7 @@ func (q *Queries) ExamPrepDeleteCatalogCourse(ctx context.Context, id int64) err
const ExamPrepGetCatalogCourseByID = `-- name: ExamPrepGetCatalogCourseByID :one
SELECT
c.id, c.name, c.description, c.thumbnail, c.sort_order, c.created_at, c.updated_at, c.category, c.publish_status, c.access_tier,
c.id, c.name, c.description, c.thumbnail, c.sort_order, c.created_at, c.updated_at, c.category, c.publish_status, c.access_tier, c.price, c.currency,
EXISTS (
SELECT 1
FROM exam_prep.lesson_practices p
@ -126,6 +134,8 @@ type ExamPrepGetCatalogCourseByIDRow struct {
Category string `json:"category"`
PublishStatus string `json:"publish_status"`
AccessTier string `json:"access_tier"`
Price pgtype.Numeric `json:"price"`
Currency string `json:"currency"`
HasPractice bool `json:"has_practice"`
}
@ -143,6 +153,8 @@ func (q *Queries) ExamPrepGetCatalogCourseByID(ctx context.Context, id int64) (E
&i.Category,
&i.PublishStatus,
&i.AccessTier,
&i.Price,
&i.Currency,
&i.HasPractice,
)
return i, err
@ -200,6 +212,8 @@ SELECT
c.sort_order,
c.publish_status,
c.access_tier,
c.price,
c.currency,
COALESCE(cc.units_count, 0)::BIGINT AS units_count,
COALESCE(cc.modules_count, 0)::BIGINT AS modules_count,
COALESCE(cc.lessons_count, 0)::BIGINT AS lessons_count,
@ -270,6 +284,8 @@ type ExamPrepListCatalogCoursesRow struct {
SortOrder int32 `json:"sort_order"`
PublishStatus string `json:"publish_status"`
AccessTier string `json:"access_tier"`
Price pgtype.Numeric `json:"price"`
Currency string `json:"currency"`
UnitsCount int64 `json:"units_count"`
ModulesCount int64 `json:"modules_count"`
LessonsCount int64 `json:"lessons_count"`
@ -297,6 +313,8 @@ func (q *Queries) ExamPrepListCatalogCourses(ctx context.Context, arg ExamPrepLi
&i.SortOrder,
&i.PublishStatus,
&i.AccessTier,
&i.Price,
&i.Currency,
&i.UnitsCount,
&i.ModulesCount,
&i.LessonsCount,
@ -324,21 +342,25 @@ SET
sort_order = coalesce($5::int, sort_order),
publish_status = coalesce($6::varchar, publish_status),
access_tier = coalesce($7::varchar, access_tier),
price = coalesce($8::numeric, price),
currency = coalesce($9::varchar, currency),
updated_at = CURRENT_TIMESTAMP
WHERE id = $8
WHERE id = $10
RETURNING
id, name, description, thumbnail, sort_order, created_at, updated_at, category, publish_status, access_tier
id, name, description, thumbnail, sort_order, created_at, updated_at, category, publish_status, access_tier, price, currency
`
type ExamPrepUpdateCatalogCourseParams struct {
Name pgtype.Text `json:"name"`
Description pgtype.Text `json:"description"`
Category pgtype.Text `json:"category"`
Thumbnail pgtype.Text `json:"thumbnail"`
SortOrder pgtype.Int4 `json:"sort_order"`
PublishStatus pgtype.Text `json:"publish_status"`
AccessTier pgtype.Text `json:"access_tier"`
ID int64 `json:"id"`
Name pgtype.Text `json:"name"`
Description pgtype.Text `json:"description"`
Category pgtype.Text `json:"category"`
Thumbnail pgtype.Text `json:"thumbnail"`
SortOrder pgtype.Int4 `json:"sort_order"`
PublishStatus pgtype.Text `json:"publish_status"`
AccessTier pgtype.Text `json:"access_tier"`
Price pgtype.Numeric `json:"price"`
Currency pgtype.Text `json:"currency"`
ID int64 `json:"id"`
}
func (q *Queries) ExamPrepUpdateCatalogCourse(ctx context.Context, arg ExamPrepUpdateCatalogCourseParams) (ExamPrepCatalogCourse, error) {
@ -350,6 +372,8 @@ func (q *Queries) ExamPrepUpdateCatalogCourse(ctx context.Context, arg ExamPrepU
arg.SortOrder,
arg.PublishStatus,
arg.AccessTier,
arg.Price,
arg.Currency,
arg.ID,
)
var i ExamPrepCatalogCourse
@ -364,6 +388,8 @@ func (q *Queries) ExamPrepUpdateCatalogCourse(ctx context.Context, arg ExamPrepU
&i.Category,
&i.PublishStatus,
&i.AccessTier,
&i.Price,
&i.Currency,
)
return i, err
}

View File

@ -8,6 +8,19 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
type AcademyArchivedCourse struct {
CourseID int64 `json:"course_id"`
PreviousPublishStatus string `json:"previous_publish_status"`
PreviousUpdatedAt pgtype.Timestamptz `json:"previous_updated_at"`
ArchivedAt pgtype.Timestamptz `json:"archived_at"`
Reason string `json:"reason"`
}
type AcademyCurriculumCourse struct {
SeedKey string `json:"seed_key"`
CourseID int64 `json:"course_id"`
}
type ActivityLog struct {
ID int64 `json:"id"`
ActorID pgtype.Int8 `json:"actor_id"`
@ -22,6 +35,51 @@ type ActivityLog struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type Affiliate struct {
UserID int64 `json:"user_id"`
Status string `json:"status"`
Application string `json:"application"`
TermsAcceptedAt pgtype.Timestamptz `json:"terms_accepted_at"`
TermsVersion string `json:"terms_version"`
ReviewedBy pgtype.Int8 `json:"reviewed_by"`
ReviewNote string `json:"review_note"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type AffiliateEvent struct {
ID int64 `json:"id"`
AffiliateUserID pgtype.Int8 `json:"affiliate_user_id"`
ActorID pgtype.Int8 `json:"actor_id"`
Event string `json:"event"`
Details []byte `json:"details"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type AffiliatePayout struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Currency string `json:"currency"`
Amount pgtype.Numeric `json:"amount"`
Status string `json:"status"`
Method string `json:"method"`
AccountName string `json:"account_name"`
AccountReference string `json:"account_reference"`
PaymentReference pgtype.Text `json:"payment_reference"`
ReviewNote string `json:"review_note"`
ReviewedBy pgtype.Int8 `json:"reviewed_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
ReviewedAt pgtype.Timestamptz `json:"reviewed_at"`
}
type AffiliateSale struct {
PaymentID int64 `json:"payment_id"`
ReferralID int64 `json:"referral_id"`
CourseID pgtype.Int8 `json:"course_id"`
CommissionPercent pgtype.Numeric `json:"commission_percent"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
type Course struct {
ID int64 `json:"id"`
ProgramID int64 `json:"program_id"`
@ -35,6 +93,20 @@ type Course struct {
AccessTier string `json:"access_tier"`
}
type CoursePurchase struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
CourseID int64 `json:"course_id"`
PaymentID int64 `json:"payment_id"`
PurchasedAt pgtype.Timestamptz `json:"purchased_at"`
}
type DemoSeedEntity struct {
Kind string `json:"kind"`
SeedKey string `json:"seed_key"`
EntityID int64 `json:"entity_id"`
}
type Device struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
@ -77,6 +149,8 @@ type ExamPrepCatalogCourse struct {
Category string `json:"category"`
PublishStatus string `json:"publish_status"`
AccessTier string `json:"access_tier"`
Price pgtype.Numeric `json:"price"`
Currency string `json:"currency"`
}
type ExamPrepChapterLessonContainer struct {
@ -349,6 +423,7 @@ type Payment struct {
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
CourseID pgtype.Int8 `json:"course_id"`
}
type Permission struct {
@ -522,6 +597,12 @@ type ReferralCommission struct {
Currency string `json:"currency"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
ReversedAt pgtype.Timestamptz `json:"reversed_at"`
CourseID pgtype.Int8 `json:"course_id"`
AvailableAt pgtype.Timestamptz `json:"available_at"`
PayoutID pgtype.Int8 `json:"payout_id"`
RecoveryPayoutID pgtype.Int8 `json:"recovery_payout_id"`
ReversalReason pgtype.Text `json:"reversal_reason"`
ReversedBy pgtype.Int8 `json:"reversed_by"`
}
type ReferralSetting struct {
@ -529,6 +610,10 @@ type ReferralSetting struct {
CommissionPercent pgtype.Numeric `json:"commission_percent"`
UpdatedBy pgtype.Int8 `json:"updated_by"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
ShareBaseUrl string `json:"share_base_url"`
CommissionMode string `json:"commission_mode"`
AttributionDays int32 `json:"attribution_days"`
HoldingDays int32 `json:"holding_days"`
}
type RefreshToken struct {
@ -761,6 +846,7 @@ type UserReferral struct {
ConversionPaymentID pgtype.Int8 `json:"conversion_payment_id"`
ConvertedAt pgtype.Timestamptz `json:"converted_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
AttributedUntil pgtype.Timestamptz `json:"attributed_until"`
}
type UserSubscription struct {

View File

@ -155,7 +155,7 @@ VALUES (
'SUCCESS',
CURRENT_TIMESTAMP
)
RETURNING id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at
RETURNING id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at, course_id
`
type CreateAdminPaymentParams struct {
@ -198,6 +198,7 @@ func (q *Queries) CreateAdminPayment(ctx context.Context, arg CreateAdminPayment
&i.ExpiresAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.CourseID,
)
return i, err
}
@ -206,10 +207,10 @@ const CreatePayment = `-- name: CreatePayment :one
INSERT INTO payments (
user_id, plan_id, subscription_id, session_id, transaction_id, nonce,
amount, currency, payment_method, status, payment_url, expires_at
amount, currency, payment_method, status, payment_url, expires_at, course_id
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, COALESCE($10, 'PENDING'), $11, $12)
RETURNING id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, COALESCE($10, 'PENDING'), $11, $12, $13::bigint)
RETURNING id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at, course_id
`
type CreatePaymentParams struct {
@ -225,6 +226,7 @@ type CreatePaymentParams struct {
Column10 interface{} `json:"column_10"`
PaymentUrl pgtype.Text `json:"payment_url"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
CourseID pgtype.Int8 `json:"course_id"`
}
// =====================
@ -244,6 +246,7 @@ func (q *Queries) CreatePayment(ctx context.Context, arg CreatePaymentParams) (P
arg.Column10,
arg.PaymentUrl,
arg.ExpiresAt,
arg.CourseID,
)
var i Payment
err := row.Scan(
@ -263,6 +266,7 @@ func (q *Queries) CreatePayment(ctx context.Context, arg CreatePaymentParams) (P
&i.ExpiresAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.CourseID,
)
return i, err
}
@ -299,7 +303,7 @@ func (q *Queries) ExpireStalePendingPayments(ctx context.Context) (int64, error)
}
const GetExpiredPendingPayments = `-- name: GetExpiredPendingPayments :many
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at FROM payments
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at, course_id FROM payments
WHERE status = 'PENDING'
AND expires_at IS NOT NULL
AND expires_at <= CURRENT_TIMESTAMP
@ -331,6 +335,7 @@ func (q *Queries) GetExpiredPendingPayments(ctx context.Context) ([]Payment, err
&i.ExpiresAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.CourseID,
); err != nil {
return nil, err
}
@ -343,7 +348,7 @@ func (q *Queries) GetExpiredPendingPayments(ctx context.Context) ([]Payment, err
}
const GetPaymentByID = `-- name: GetPaymentByID :one
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at FROM payments WHERE id = $1
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at, course_id FROM payments WHERE id = $1
`
func (q *Queries) GetPaymentByID(ctx context.Context, id int64) (Payment, error) {
@ -366,12 +371,13 @@ func (q *Queries) GetPaymentByID(ctx context.Context, id int64) (Payment, error)
&i.ExpiresAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.CourseID,
)
return i, err
}
const GetPaymentByNonce = `-- name: GetPaymentByNonce :one
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at FROM payments WHERE nonce = $1
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at, course_id FROM payments WHERE nonce = $1
`
func (q *Queries) GetPaymentByNonce(ctx context.Context, nonce string) (Payment, error) {
@ -394,12 +400,13 @@ func (q *Queries) GetPaymentByNonce(ctx context.Context, nonce string) (Payment,
&i.ExpiresAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.CourseID,
)
return i, err
}
const GetPaymentBySessionID = `-- name: GetPaymentBySessionID :one
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at FROM payments WHERE session_id = $1
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at, course_id FROM payments WHERE session_id = $1
`
func (q *Queries) GetPaymentBySessionID(ctx context.Context, sessionID pgtype.Text) (Payment, error) {
@ -422,12 +429,13 @@ func (q *Queries) GetPaymentBySessionID(ctx context.Context, sessionID pgtype.Te
&i.ExpiresAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.CourseID,
)
return i, err
}
const GetPaymentByTransactionID = `-- name: GetPaymentByTransactionID :one
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at FROM payments WHERE transaction_id = $1
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at, course_id FROM payments WHERE transaction_id = $1
`
func (q *Queries) GetPaymentByTransactionID(ctx context.Context, transactionID pgtype.Text) (Payment, error) {
@ -450,12 +458,13 @@ func (q *Queries) GetPaymentByTransactionID(ctx context.Context, transactionID p
&i.ExpiresAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.CourseID,
)
return i, err
}
const GetPaymentsByUserID = `-- name: GetPaymentsByUserID :many
SELECT p.id, p.user_id, p.plan_id, p.subscription_id, p.session_id, p.transaction_id, p.nonce, p.amount, p.currency, p.payment_method, p.status, p.payment_url, p.paid_at, p.expires_at, p.created_at, p.updated_at, sp.name AS plan_name
SELECT p.id, p.user_id, p.plan_id, p.subscription_id, p.session_id, p.transaction_id, p.nonce, p.amount, p.currency, p.payment_method, p.status, p.payment_url, p.paid_at, p.expires_at, p.created_at, p.updated_at, p.course_id, sp.name AS plan_name
FROM payments p
LEFT JOIN subscription_plans sp ON sp.id = p.plan_id
WHERE p.user_id = $1
@ -487,6 +496,7 @@ type GetPaymentsByUserIDRow struct {
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
CourseID pgtype.Int8 `json:"course_id"`
PlanName pgtype.Text `json:"plan_name"`
}
@ -516,6 +526,7 @@ func (q *Queries) GetPaymentsByUserID(ctx context.Context, arg GetPaymentsByUser
&i.ExpiresAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.CourseID,
&i.PlanName,
); err != nil {
return nil, err
@ -529,7 +540,7 @@ func (q *Queries) GetPaymentsByUserID(ctx context.Context, arg GetPaymentsByUser
}
const GetPendingPaymentsByUserID = `-- name: GetPendingPaymentsByUserID :many
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at FROM payments
SELECT id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at, course_id FROM payments
WHERE user_id = $1 AND status = 'PENDING'
ORDER BY created_at DESC
`
@ -560,6 +571,7 @@ func (q *Queries) GetPendingPaymentsByUserID(ctx context.Context, userID int64)
&i.ExpiresAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.CourseID,
); err != nil {
return nil, err
}
@ -593,6 +605,7 @@ const ListPaymentsAdmin = `-- name: ListPaymentsAdmin :many
SELECT
p.id,
p.user_id,
p.course_id,
p.plan_id,
p.subscription_id,
p.session_id,
@ -662,6 +675,7 @@ type ListPaymentsAdminParams struct {
type ListPaymentsAdminRow struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
CourseID pgtype.Int8 `json:"course_id"`
PlanID pgtype.Int8 `json:"plan_id"`
SubscriptionID pgtype.Int8 `json:"subscription_id"`
SessionID pgtype.Text `json:"session_id"`
@ -713,6 +727,7 @@ func (q *Queries) ListPaymentsAdmin(ctx context.Context, arg ListPaymentsAdminPa
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.CourseID,
&i.PlanID,
&i.SubscriptionID,
&i.SessionID,
@ -768,7 +783,7 @@ UPDATE payments
SET
status = $1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2
WHERE id = $2 AND status <> 'SUCCESS'
`
type UpdatePaymentStatusParams struct {
@ -789,7 +804,7 @@ SET
payment_method = COALESCE($3::text, payment_method),
paid_at = CASE WHEN $1::varchar = 'SUCCESS' THEN CURRENT_TIMESTAMP ELSE paid_at END,
updated_at = CURRENT_TIMESTAMP
WHERE nonce = $4::text
WHERE nonce = $4::text AND status <> 'SUCCESS'
`
type UpdatePaymentStatusByNonceParams struct {

View File

@ -11,17 +11,24 @@ import (
"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
const ApplyReferralCode = `-- name: ApplyReferralCode :one
WITH existing AS (
SELECT r.id FROM user_referrals r JOIN referral_codes rc ON rc.id=r.referral_code_id
WHERE r.referred_user_id=$1 AND rc.code=$2
), applied AS (
INSERT INTO user_referrals (referrer_id, referred_user_id, referral_code_id,attributed_until)
SELECT rc.user_id, u.id, rc.id,now()+make_interval(days=>rs.attribution_days)
FROM referral_codes rc JOIN users owner ON owner.id = rc.user_id JOIN affiliates a ON a.user_id=rc.user_id AND a.status='APPROVED' CROSS JOIN referral_settings rs
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 u.status='ACTIVE' AND NOT EXISTS(SELECT 1 FROM existing)
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
ON CONFLICT (referred_user_id) DO UPDATE SET referred_user_id=user_referrals.referred_user_id
WHERE user_referrals.referrer_id=EXCLUDED.referrer_id AND user_referrals.referral_code_id=EXCLUDED.referral_code_id RETURNING id
)
SELECT ((SELECT count(*) FROM existing)+(SELECT count(*) FROM applied))::bigint AS applied_count
`
type ApplyReferralCodeParams struct {
@ -29,17 +36,17 @@ type ApplyReferralCodeParams struct {
Code string `json:"code"`
}
// Same-code retries remain safe after purchase without replacing or renewing attribution.
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
row := q.db.QueryRow(ctx, ApplyReferralCode, arg.ReferredUserID, arg.Code)
var applied_count int64
err := row.Scan(&applied_count)
return applied_count, err
}
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'
SELECT users.id, $2 FROM users WHERE users.id = $1 AND role IN ('STUDENT', 'OPEN_LEARNER') AND status = 'ACTIVE' AND EXISTS(SELECT 1 FROM affiliates a WHERE a.user_id=users.id AND a.status='APPROVED')
ON CONFLICT (user_id) DO UPDATE SET user_id = EXCLUDED.user_id
RETURNING code
`
@ -57,7 +64,7 @@ func (q *Queries) CreateReferralCode(ctx context.Context, arg CreateReferralCode
}
const GetReferralCode = `-- name: GetReferralCode :one
SELECT code FROM referral_codes WHERE user_id = $1
SELECT rc.code FROM referral_codes rc JOIN affiliates a ON a.user_id=rc.user_id AND a.status='APPROVED' JOIN users u ON u.id=rc.user_id AND u.status='ACTIVE' WHERE rc.user_id = $1
`
func (q *Queries) GetReferralCode(ctx context.Context, userID int64) (string, error) {
@ -102,7 +109,7 @@ func (q *Queries) GetReferralSummary(ctx context.Context, referrerID int64) (Get
}
const GetReferralWallet = `-- name: GetReferralWallet :many
SELECT currency, SUM(CASE WHEN reversed_at IS NULL THEN amount ELSE 0 END)::text AS balance
SELECT currency, (SUM(CASE WHEN reversed_at IS NULL AND available_at<=now() AND payout_id IS NULL THEN amount ELSE 0 END) - SUM(CASE WHEN reversed_at IS NOT NULL AND recovery_payout_id IS NULL AND EXISTS(SELECT 1 FROM affiliate_payouts p WHERE p.id=referral_commissions.payout_id AND p.status='PAID') THEN amount ELSE 0 END))::text AS balance
FROM referral_commissions WHERE referrer_id = $1 GROUP BY currency ORDER BY currency
`

View File

@ -0,0 +1,223 @@
package domain
import (
"encoding/json"
"errors"
"math"
"net/url"
"strings"
"time"
"unicode/utf8"
)
var ErrAffiliateInput = errors.New("invalid affiliate request")
type AffiliateApplicationInput struct {
Application string `json:"application"`
TermsVersion string `json:"terms_version"`
AcceptTerms bool `json:"accept_terms"`
}
type AffiliateReviewInput struct {
Status string `json:"status" enums:"APPROVED,REJECTED,SUSPENDED"`
Note string `json:"note"`
}
type AffiliateSettingsInput struct {
CommissionPercent *float64 `json:"commission_percent" minimum:"0" maximum:"100"`
CommissionMode string `json:"commission_mode" enums:"FIRST_PURCHASE,EVERY_COURSE"`
AttributionDays int32 `json:"attribution_days" minimum:"1" maximum:"365"`
HoldingDays int32 `json:"holding_days" minimum:"0" maximum:"365"`
ShareBaseURL string `json:"share_base_url"`
}
type AffiliatePayoutInput struct {
Currency string `json:"currency"`
Method string `json:"method" enums:"BANK,MOBILE_MONEY"`
AccountName string `json:"account_name"`
AccountReference string `json:"account_reference"`
}
type AffiliatePayoutReviewInput struct {
Status string `json:"status" enums:"PAID,REJECTED"`
PaymentReference string `json:"payment_reference"`
Note string `json:"note"`
}
type AffiliateReversalInput struct {
Reason string `json:"reason"`
}
func AffiliateTextValid(value string, min, max int) bool {
value = strings.TrimSpace(value)
return utf8.RuneCountInString(value) >= min && utf8.RuneCountInString(value) <= max && !strings.ContainsAny(value, "\x00\r")
}
func ValidateAffiliateSettings(input AffiliateSettingsInput) error {
if input.CommissionPercent == nil {
return ErrAffiliateInput
}
p := *input.CommissionPercent
if math.IsNaN(p) || math.IsInf(p, 0) || p < 0 || p > 100 || math.Abs(p*100-math.Round(p*100)) > 0.000001 {
return ErrAffiliateInput
}
if input.CommissionMode != "FIRST_PURCHASE" && input.CommissionMode != "EVERY_COURSE" {
return ErrAffiliateInput
}
if input.AttributionDays < 1 || input.AttributionDays > 365 || input.HoldingDays < 0 || input.HoldingDays > 365 {
return ErrAffiliateInput
}
if input.ShareBaseURL != "" {
u, err := url.Parse(input.ShareBaseURL)
if err != nil || u.Host == "" || u.User != nil || (u.Scheme != "https" && u.Scheme != "http") || len(input.ShareBaseURL) > 2000 {
return ErrAffiliateInput
}
}
return nil
}
func ValidateAffiliatePayout(input AffiliatePayoutInput) error {
if len(input.Currency) != 3 {
return ErrAffiliateInput
}
for _, ch := range input.Currency {
if ch < 'A' || ch > 'Z' {
return ErrAffiliateInput
}
}
if input.Method != "BANK" && input.Method != "MOBILE_MONEY" {
return ErrAffiliateInput
}
if !AffiliateTextValid(input.AccountName, 2, 120) || !AffiliateTextValid(input.AccountReference, 3, 120) {
return ErrAffiliateInput
}
return nil
}
func AffiliateShareURL(base, code string) string {
if base == "" || code == "" {
return ""
}
u, err := url.Parse(base)
if err != nil {
return ""
}
q := u.Query()
q.Set("ref", code)
u.RawQuery = q.Encode()
return u.String()
}
type AffiliateProfile struct {
TermsVersion string `json:"terms_version"`
UserID int64 `json:"user_id"`
Status string `json:"status"`
Application string `json:"application"`
TermsAcceptedAt time.Time `json:"terms_accepted_at"`
ReviewNote string `json:"review_note"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Code string `json:"code"`
}
type AffiliateSettings struct {
CommissionPercent string `json:"commission_percent"`
CommissionMode string `json:"commission_mode"`
AttributionDays int32 `json:"attribution_days"`
HoldingDays int32 `json:"holding_days"`
ShareBaseURL string `json:"share_base_url"`
UpdatedAt time.Time `json:"updated_at"`
}
type AffiliateBalance struct {
Currency string `json:"currency"`
Pending string `json:"pending"`
Available string `json:"available"`
Reversed string `json:"reversed"`
RecoveryDue string `json:"recovery_due"`
Reserved string `json:"reserved"`
Paid string `json:"paid"`
}
type AffiliateTerms struct {
Version string `json:"version"`
Rules []string `json:"rules"`
}
func CurrentAffiliateTerms() AffiliateTerms {
return AffiliateTerms{Version: "1", Rules: []string{
"Administrator approval is required before promoting courses or requesting payouts.",
"Use your code or referral link before the learner's first paid purchase. Self-referrals and replacing an existing referrer are not allowed.",
"Only verified positive course payments qualify, within the configured attribution window. The current rate and commission policy apply at payment confirmation.",
"Earnings are held for the configured period. Reversed sales cancel unpaid earnings; reversals after payout reduce future payouts.",
"Payout requests reserve available earnings in a single currency. Administrators record externally completed transfers; a request is not a completed payment.",
"Do not use misleading promotion, spam, or fraudulent purchases. Suspension stops new commissions and payout completion.",
}}
}
type AffiliateDashboard struct {
Terms AffiliateTerms `json:"terms"`
Profile *AffiliateProfile `json:"profile"`
Settings AffiliateSettings `json:"settings"`
ShareURL string `json:"share_url"`
TotalReferrals int64 `json:"total_referrals"`
ConvertedReferrals int64 `json:"converted_referrals"`
Balances []AffiliateBalance `json:"balances"`
}
type AffiliateCommission struct {
ID int64 `json:"id"`
ReferrerID int64 `json:"referrer_id"`
PaymentID int64 `json:"payment_id"`
CourseID *int64 `json:"course_id"`
CommissionPercent string `json:"commission_percent"`
Amount string `json:"amount"`
Currency string `json:"currency"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
AvailableAt time.Time `json:"available_at"`
ReversedAt *time.Time `json:"reversed_at"`
ReversalReason *string `json:"reversal_reason"`
PayoutID *int64 `json:"payout_id"`
}
type AffiliatePayout struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Currency string `json:"currency"`
Amount string `json:"amount"`
Status string `json:"status"`
Method string `json:"method"`
AccountName string `json:"account_name"`
AccountReference string `json:"account_reference"`
PaymentReference *string `json:"payment_reference"`
ReviewNote string `json:"review_note"`
CreatedAt time.Time `json:"created_at"`
ReviewedAt *time.Time `json:"reviewed_at"`
}
type AffiliateListData struct {
Items []AffiliateProfile `json:"items"`
TotalCount int64 `json:"total_count"`
Limit int32 `json:"limit"`
Offset int32 `json:"offset"`
}
type AffiliateCommissionData struct {
Items []AffiliateCommission `json:"items"`
TotalCount int64 `json:"total_count"`
Limit int32 `json:"limit"`
Offset int32 `json:"offset"`
}
type AffiliatePayoutData struct {
Items []AffiliatePayout `json:"items"`
TotalCount int64 `json:"total_count"`
Limit int32 `json:"limit"`
Offset int32 `json:"offset"`
}
type AffiliateMutationData struct {
ID int64 `json:"id"`
}
type AffiliateEvent struct {
ID int64 `json:"id"`
AffiliateUserID *int64 `json:"affiliate_user_id"`
ActorID *int64 `json:"actor_id"`
Event string `json:"event"`
// Event-specific audit fields, such as from/to status, note, payout_id, commission_id, and rate snapshots.
Details json.RawMessage `json:"details" swaggertype:"object"`
CreatedAt time.Time `json:"created_at"`
}
type AffiliateEventData struct {
Items []AffiliateEvent `json:"items"`
Limit int32 `json:"limit"`
Offset int32 `json:"offset"`
}

View File

@ -0,0 +1,69 @@
package domain
import (
"math"
"net/url"
"testing"
)
func TestAffiliateSettingsValidation(t *testing.T) {
rate := 10.25
valid := AffiliateSettingsInput{CommissionPercent: &rate, CommissionMode: "EVERY_COURSE", AttributionDays: 30, HoldingDays: 14, ShareBaseURL: "https://academy.example/register"}
if err := ValidateAffiliateSettings(valid); err != nil {
t.Fatal(err)
}
for _, p := range []float64{-1, 101, 0.001, math.NaN(), math.Inf(1)} {
v := valid
v.CommissionPercent = &p
if ValidateAffiliateSettings(v) == nil {
t.Errorf("accepted rate %v", p)
}
}
for _, u := range []string{"javascript:alert(1)", "https://user:pass@example.com", "/register"} {
v := valid
v.ShareBaseURL = u
if ValidateAffiliateSettings(v) == nil {
t.Errorf("accepted URL %s", u)
}
}
v := valid
v.AttributionDays = 0
if ValidateAffiliateSettings(v) == nil {
t.Fatal("accepted zero attribution")
}
v = valid
v.HoldingDays = -1
if ValidateAffiliateSettings(v) == nil {
t.Fatal("accepted negative hold")
}
v = valid
v.CommissionMode = "ANY"
if ValidateAffiliateSettings(v) == nil {
t.Fatal("accepted unknown mode")
}
}
func TestAffiliatePayoutValidation(t *testing.T) {
valid := AffiliatePayoutInput{Currency: "ETB", Method: "BANK", AccountName: "Test Artist", AccountReference: "123456"}
if err := ValidateAffiliatePayout(valid); err != nil {
t.Fatal(err)
}
invalid := []AffiliatePayoutInput{{Currency: "ETB", Method: "CASH", AccountName: "Test", AccountReference: "123"}, {Currency: "etb", Method: "BANK", AccountName: "Test", AccountReference: "123"}, {Currency: "ETB", Method: "BANK", AccountName: " ", AccountReference: "123"}}
for _, in := range invalid {
if ValidateAffiliatePayout(in) == nil {
t.Errorf("accepted %+v", in)
}
}
}
func TestAffiliateShareURL(t *testing.T) {
result := AffiliateShareURL("https://academy.example/register?campaign=makeup&ref=old#start", "ABCDEF0123456789")
u, err := url.Parse(result)
if err != nil {
t.Fatal(err)
}
if u.Query().Get("ref") != "ABCDEF0123456789" || u.Query().Get("campaign") != "makeup" || u.Fragment != "start" {
t.Fatal(result)
}
if AffiliateShareURL("", "code") != "" {
t.Fatal("blank base URL should not invent a destination")
}
}

View File

@ -3,10 +3,11 @@ package domain
import "strings"
// ContentAccessTier controls whether learners need an active subscription to consume content.
// Effective tier cascades at read time: any PREMIUM ancestor makes descendants PREMIUM.
// Current courses resolve the nearest explicit override; legacy LMS callers retain premium cascading.
type ContentAccessTier string
const (
ContentAccessInherit ContentAccessTier = "INHERIT"
ContentAccessFree ContentAccessTier = "FREE"
ContentAccessPremium ContentAccessTier = "PREMIUM"
)
@ -14,6 +15,8 @@ const (
// ContentAccessTierFromDB normalizes persisted values.
func ContentAccessTierFromDB(raw string) ContentAccessTier {
switch strings.TrimSpace(strings.ToUpper(raw)) {
case string(ContentAccessInherit):
return ContentAccessInherit
case string(ContentAccessFree):
return ContentAccessFree
default:
@ -52,3 +55,21 @@ func ContentAccessTierForRole(role Role, tier ContentAccessTier) ContentAccessTi
}
return tier
}
// ResolveContentAccessTier applies the nearest explicit override, from root to leaf.
func ResolveContentAccessTier(tiers ...ContentAccessTier) ContentAccessTier {
result := ContentAccessPremium
for _, tier := range tiers {
if tier == ContentAccessFree || tier == ContentAccessPremium {
result = tier
}
}
return result
}
func ChildContentAccessTierForCreate(raw *string) string {
if raw == nil || strings.TrimSpace(*raw) == "" {
return string(ContentAccessInherit)
}
return string(ContentAccessTierFromDB(*raw))
}

View File

@ -0,0 +1,44 @@
package domain
import (
"math"
"testing"
)
func TestCoursePriceValidation(t *testing.T) {
for _, tt := range []struct {
price float64
currency string
valid bool
}{
{0, "ETB", true}, {1500.99, "ETB", true}, {-1, "ETB", false}, {1.001, "ETB", false}, {1500, "etb", false}, {1500, "123", false}, {math.Inf(1), "ETB", false}, {math.NaN(), "ETB", false},
} {
if err := ValidateCoursePricing(tt.price, tt.currency); (err == nil) != tt.valid {
t.Errorf("%v %q: %v", tt.price, tt.currency, err)
}
}
}
func TestCourseAccessInheritanceAndOverrides(t *testing.T) {
tests := []struct {
name string
chain []ContentAccessTier
want ContentAccessTier
}{
{"paid defaults", []ContentAccessTier{ContentAccessPremium, ContentAccessInherit, ContentAccessInherit}, ContentAccessPremium},
{"free defaults", []ContentAccessTier{ContentAccessFree, ContentAccessInherit, ContentAccessInherit}, ContentAccessFree},
{"free chapter preview", []ContentAccessTier{ContentAccessPremium, ContentAccessFree, ContentAccessInherit}, ContentAccessFree},
{"free lesson in paid chapter", []ContentAccessTier{ContentAccessPremium, ContentAccessPremium, ContentAccessFree}, ContentAccessFree},
{"paid lesson in free chapter", []ContentAccessTier{ContentAccessFree, ContentAccessFree, ContentAccessPremium}, ContentAccessPremium},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ResolveContentAccessTier(tt.chain...); got != tt.want {
t.Fatalf("got %s want %s", got, tt.want)
}
})
}
if got := ChildContentAccessTierForCreate(nil); got != "INHERIT" {
t.Fatalf("new children should inherit, got %s", got)
}
}

View File

@ -0,0 +1,44 @@
package domain
import (
"errors"
"math"
)
var ErrInvalidCoursePricing = errors.New("course price must be nonnegative with at most two decimal places and currency must be three uppercase letters")
func ValidateCoursePricing(price float64, currency string) error {
if math.IsNaN(price) || math.IsInf(price, 0) || price < 0 || price > 9999999999.99 || math.Abs(price-math.Round(price*100)/100) > 1e-9 {
return ErrInvalidCoursePricing
}
if len(currency) != 3 {
return ErrInvalidCoursePricing
}
for _, ch := range currency {
if ch < 'A' || ch > 'Z' {
return ErrInvalidCoursePricing
}
}
return nil
}
// CourseContentAccess is resolved from storage so every consumption path uses the same policy.
type CourseContentAccess struct {
CourseID int64
Tier ContentAccessTier
Published bool
}
type CourseCheckoutRequest struct {
ReferralCode string `json:"referral_code,omitempty"`
Phone string `json:"phone,omitempty"`
}
type CourseCheckoutResponse struct {
PaymentID int64 `json:"payment_id"`
SessionID string `json:"session_id"`
PaymentURL string `json:"payment_url"`
CourseID int64 `json:"course_id"`
Amount float64 `json:"amount"`
Currency string `json:"currency"`
}

View File

@ -4,6 +4,8 @@ import "time"
// ExamPrepCatalogCourse stores the makeup academy catalog under the legacy exam_prep schema.
type ExamPrepCatalogCourse struct {
Price float64 `json:"price"`
Currency string `json:"currency"`
IsArchived bool `json:"is_archived"`
ID int64 `json:"id"`
Name string `json:"name"`
@ -29,6 +31,8 @@ func (c ExamPrepCatalogCourse) VisibleToLearners() bool {
}
type CreateExamPrepCatalogCourseInput struct {
Price float64 `json:"price" validate:"min=0,max=9999999999.99"`
Currency string `json:"currency" validate:"omitempty,len=3,alpha,uppercase"`
Name string `json:"name" validate:"required"`
Description *string `json:"description,omitempty"`
Category string `json:"-"`
@ -39,11 +43,13 @@ type CreateExamPrepCatalogCourseInput struct {
}
type UpdateExamPrepCatalogCourseInput struct {
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
Category *string `json:"-"`
Thumbnail *string `json:"thumbnail,omitempty"`
SortOrder *int `json:"sort_order,omitempty"`
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium"`
Price *float64 `json:"price,omitempty" validate:"omitempty,min=0,max=9999999999.99"`
Currency *string `json:"currency,omitempty" validate:"omitempty,len=3,alpha,uppercase"`
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
Category *string `json:"-"`
Thumbnail *string `json:"thumbnail,omitempty"`
SortOrder *int `json:"sort_order,omitempty"`
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium"`
}

View File

@ -33,7 +33,7 @@ type CreateExamPrepLessonInput struct {
Description *string `json:"description,omitempty"`
// Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium INHERIT inherit"`
}
type UpdateExamPrepLessonInput struct {
@ -43,5 +43,5 @@ type UpdateExamPrepLessonInput struct {
Description *string `json:"description,omitempty"`
SortOrder *int `json:"sort_order,omitempty"`
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium INHERIT inherit"`
}

View File

@ -4,22 +4,22 @@ import "time"
// ExamPrepModule is a module under an exam-prep unit (stored in exam_prep.unit_modules).
type ExamPrepModule struct {
ID int64 `json:"id"`
UnitID int64 `json:"unit_id"`
Name string `json:"name"`
Description *string `json:"description,omitempty"`
Thumbnail *string `json:"thumbnail,omitempty"`
Icon *string `json:"icon,omitempty"`
SortOrder int `json:"sort_order"`
ID int64 `json:"id"`
UnitID int64 `json:"unit_id"`
Name string `json:"name"`
Description *string `json:"description,omitempty"`
Thumbnail *string `json:"thumbnail,omitempty"`
Icon *string `json:"icon,omitempty"`
SortOrder int `json:"sort_order"`
PublishStatus ContentPublishStatus `json:"publish_status"`
AccessTier ContentAccessTier `json:"access_tier"`
EffectiveAccessTier ContentAccessTier `json:"effective_access_tier,omitempty"`
LessonsCount *int64 `json:"lessons_count,omitempty"`
PracticesCount *int64 `json:"practices_count,omitempty"`
HasPractice bool `json:"has_practice"`
Access *LMSEntityAccess `json:"access,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
PracticesCount *int64 `json:"practices_count,omitempty"`
HasPractice bool `json:"has_practice"`
Access *LMSEntityAccess `json:"access,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
}
// VisibleToLearners is true when the module appears in student/learner exam-prep APIs.
@ -34,7 +34,7 @@ type CreateExamPrepModuleInput struct {
Icon *string `json:"icon,omitempty"`
// Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium INHERIT inherit"`
}
type UpdateExamPrepModuleInput struct {
@ -44,5 +44,5 @@ type UpdateExamPrepModuleInput struct {
Icon *string `json:"icon,omitempty"`
SortOrder *int `json:"sort_order,omitempty"`
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium INHERIT inherit"`
}

View File

@ -35,7 +35,7 @@ type CreateExamPrepUnitInput struct {
SortOrder *int `json:"sort_order,omitempty" validate:"omitempty,min=0"`
// Omit or empty defaults to DRAFT; set PUBLISHED to make visible to learners immediately.
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium INHERIT inherit"`
}
type UpdateExamPrepUnitInput struct {
@ -44,5 +44,5 @@ type UpdateExamPrepUnitInput struct {
Thumbnail *string `json:"thumbnail,omitempty"`
SortOrder *int `json:"sort_order,omitempty"`
PublishStatus *string `json:"publish_status,omitempty" validate:"omitempty,oneof=DRAFT draft PUBLISHED published"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium"`
AccessTier *string `json:"access_tier,omitempty" validate:"omitempty,oneof=FREE free PREMIUM premium INHERIT inherit"`
}

View File

@ -18,6 +18,7 @@ const (
)
type Payment struct {
CourseID *int64
ID int64
UserID int64
PlanID *int64
@ -72,6 +73,7 @@ type PaymentListPage struct {
}
type CreatePaymentInput struct {
CourseID *int64
UserID int64
PlanID *int64
SubscriptionID *int64

View File

@ -2,14 +2,16 @@ package domain
// Public catalog DTOs deliberately contain no playback URLs, answers, or user data.
type PublicCourse struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Thumbnail string `json:"thumbnail"`
AccessTier string `json:"access_tier" enums:"FREE,PREMIUM"`
ChapterCount int64 `json:"chapter_count"`
LessonCount int64 `json:"lesson_count"`
QuizCount int64 `json:"quiz_count"`
Price float64 `json:"price"`
Currency string `json:"currency"`
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Thumbnail string `json:"thumbnail"`
AccessTier string `json:"access_tier" enums:"FREE,PREMIUM"`
ChapterCount int64 `json:"chapter_count"`
LessonCount int64 `json:"lesson_count"`
QuizCount int64 `json:"quiz_count"`
}
type PublicCatalogPage struct {

View File

@ -0,0 +1,14 @@
package ports
import (
"Rezina-Backend/internal/domain"
"context"
)
type CoursePurchaseStore interface {
CourseVideoLessonIDs(context.Context, string) ([]int64, error)
HasCoursePurchase(context.Context, int64, int64) (bool, error)
CourseContentAccess(context.Context, string, int64) (domain.CourseContentAccess, error)
// CompleteCoursePayment atomically marks payment successful and grants access, idempotently.
CompleteCoursePayment(context.Context, int64, string, string) error
}

View File

@ -21,7 +21,7 @@ func (s *Store) GetChapterLessonContainer(ctx context.Context, chapterID int64)
err = tx.QueryRow(ctx, `SELECT module_id FROM exam_prep.chapter_lesson_containers WHERE chapter_id=$1`, chapterID).Scan(&id)
if err == pgx.ErrNoRows {
err = tx.QueryRow(ctx, `INSERT INTO exam_prep.unit_modules (unit_id,name,sort_order,publish_status,access_tier)
SELECT $1,'__chapter_lessons__',COALESCE(MAX(sort_order),0)+1,'PUBLISHED','FREE'
SELECT $1,'__chapter_lessons__',COALESCE(MAX(sort_order),0)+1,'PUBLISHED','INHERIT'
FROM exam_prep.unit_modules WHERE unit_id=$1 RETURNING id`, chapterID).Scan(&id)
if err != nil {
return 0, err

View File

@ -0,0 +1,84 @@
package repository
import (
"Rezina-Backend/internal/domain"
"context"
"fmt"
)
// Match canonical object keys and stored minio/HTTP references without SQL wildcards.
func (s *Store) CourseVideoLessonIDs(ctx context.Context, key string) ([]int64, error) {
rows, err := s.conn.Query(ctx, `SELECT id FROM exam_prep.unit_module_lessons WHERE video_url=$1 OR right(split_part(video_url,'?',1),length($1)+1)='/' || $1`, key)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (s *Store) HasCoursePurchase(ctx context.Context, userID, courseID int64) (bool, error) {
var owned bool
err := s.conn.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM course_purchases WHERE user_id=$1 AND course_id=$2)`, userID, courseID).Scan(&owned)
return owned, err
}
func (s *Store) CourseContentAccess(ctx context.Context, kind string, id int64) (domain.CourseContentAccess, error) {
var out domain.CourseContentAccess
// Resource selectors are fixed SQL, never user-supplied SQL fragments.
var query string
switch kind {
case "course":
query = `SELECT c.id,c.access_tier,c.publish_status='PUBLISHED' AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.id) FROM exam_prep.catalog_courses c WHERE c.id=$1`
case "chapter":
query = `SELECT c.id,COALESCE(NULLIF(u.access_tier,'INHERIT'),c.access_tier),c.publish_status='PUBLISHED' AND u.publish_status='PUBLISHED' AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.id) FROM exam_prep.units u JOIN exam_prep.catalog_courses c ON c.id=u.catalog_course_id WHERE u.id=$1`
case "lesson":
query = `SELECT c.id,COALESCE(NULLIF(l.access_tier,'INHERIT'),NULLIF(m.access_tier,'INHERIT'),NULLIF(u.access_tier,'INHERIT'),c.access_tier),c.publish_status='PUBLISHED' AND u.publish_status='PUBLISHED' AND m.publish_status='PUBLISHED' AND l.publish_status='PUBLISHED' AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.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 JOIN exam_prep.catalog_courses c ON c.id=u.catalog_course_id WHERE l.id=$1`
case "practice":
var parentKind string
var parentID int64
var published bool
err := s.conn.QueryRow(ctx, `SELECT pp.parent_kind,pp.parent_id,p.publish_status='PUBLISHED' AND qs.status='PUBLISHED' 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 p.id=$1`, id).Scan(&parentKind, &parentID, &published)
if err != nil {
return out, err
}
names := map[string]string{"CATALOG_COURSE": "course", "UNIT": "chapter", "LESSON": "lesson"}
out, err = s.CourseContentAccess(ctx, names[parentKind], parentID)
out.Published = out.Published && published
return out, err
default:
return out, fmt.Errorf("unsupported course resource %q", kind)
}
err := s.conn.QueryRow(ctx, query, id).Scan(&out.CourseID, &out.Tier, &out.Published)
return out, err
}
func (s *Store) CompleteCoursePayment(ctx context.Context, paymentID int64, reference, method string) error {
tx, err := s.conn.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var userID, courseID int64
// Serialize webhook/callback/poll races; payment status and entitlement commit together.
err = tx.QueryRow(ctx, `SELECT user_id,course_id FROM payments WHERE id=$1 AND course_id IS NOT NULL FOR UPDATE`, paymentID).Scan(&userID, &courseID)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `UPDATE payments SET status='SUCCESS',transaction_id=$2,payment_method=$3,paid_at=COALESCE(paid_at,now()),updated_at=now() WHERE id=$1`, paymentID, reference, method)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `INSERT INTO course_purchases(user_id,course_id,payment_id) VALUES($1,$2,$3) ON CONFLICT(user_id,course_id) DO NOTHING`, userID, courseID, paymentID)
if err != nil {
return err
}
return tx.Commit(ctx)
}

View File

@ -14,6 +14,8 @@ import (
func examPrepCatalogCourseToDomain(c dbgen.ExamPrepCatalogCourse) domain.ExamPrepCatalogCourse {
out := domain.ExamPrepCatalogCourse{
ID: c.ID,
Price: fromPgNumeric(c.Price),
Currency: c.Currency,
Name: c.Name,
Category: c.Category,
SortOrder: int(c.SortOrder),
@ -33,6 +35,8 @@ func examPrepCatalogCourseToDomain(c dbgen.ExamPrepCatalogCourse) domain.ExamPre
func (s *Store) CreateExamPrepCatalogCourse(ctx context.Context, input domain.CreateExamPrepCatalogCourseInput) (domain.ExamPrepCatalogCourse, error) {
c, err := s.queries.ExamPrepCreateCatalogCourse(ctx, dbgen.ExamPrepCreateCatalogCourseParams{
Name: input.Name,
Price: toPgNumeric(input.Price),
Currency: input.Currency,
Description: toPgText(input.Description),
Category: input.Category,
Thumbnail: toPgText(input.Thumbnail),
@ -55,6 +59,8 @@ func (s *Store) GetExamPrepCatalogCourseByID(ctx context.Context, id int64) (dom
}
out := examPrepCatalogCourseToDomain(dbgen.ExamPrepCatalogCourse{
ID: c.ID,
Price: c.Price,
Currency: c.Currency,
Name: c.Name,
Description: c.Description,
Category: c.Category,
@ -92,6 +98,8 @@ func (s *Store) ListExamPrepCatalogCourses(ctx context.Context, publishedOnly bo
}
item := examPrepCatalogCourseToDomain(dbgen.ExamPrepCatalogCourse{
ID: r.ID,
Price: r.Price,
Currency: r.Currency,
Name: r.Name,
Description: r.Description,
Category: r.Category,
@ -148,6 +156,8 @@ func (s *Store) UpdateExamPrepCatalogCourse(ctx context.Context, id int64, input
}
c, err := s.queries.ExamPrepUpdateCatalogCourse(ctx, dbgen.ExamPrepUpdateCatalogCourseParams{
ID: id,
Price: optionalCoursePrice(input.Price),
Currency: optionalTextUpdate(input.Currency),
Name: nameText,
Description: optionalTextUpdate(input.Description),
Category: optionalTextUpdate(input.Category),
@ -168,3 +178,10 @@ func (s *Store) UpdateExamPrepCatalogCourse(ctx context.Context, id int64, input
func (s *Store) DeleteExamPrepCatalogCourse(ctx context.Context, id int64) error {
return s.queries.ExamPrepDeleteCatalogCourse(ctx, id)
}
func optionalCoursePrice(price *float64) pgtype.Numeric {
if price == nil {
return pgtype.Numeric{}
}
return toPgNumeric(*price)
}

View File

@ -39,7 +39,7 @@ func (s *Store) CreateExamPrepUnitModuleLesson(ctx context.Context, unitModuleID
Thumbnail: toPgText(input.Thumbnail),
Description: toPgText(input.Description),
PublishStatus: string(domain.ContentPublishStatusFromCreateInput(input.PublishStatus)),
AccessTier: contentAccessTierForCreate(input.AccessTier),
AccessTier: domain.ChildContentAccessTierForCreate(input.AccessTier),
})
if err != nil {
return domain.ExamPrepLesson{}, err

View File

@ -39,7 +39,7 @@ func (s *Store) CreateExamPrepUnitModule(ctx context.Context, unitID int64, inpu
Thumbnail: toPgText(input.Thumbnail),
Icon: toPgText(input.Icon),
PublishStatus: string(domain.ContentPublishStatusFromCreateInput(input.PublishStatus)),
AccessTier: contentAccessTierForCreate(input.AccessTier),
AccessTier: domain.ChildContentAccessTierForCreate(input.AccessTier),
})
if err != nil {
return domain.ExamPrepModule{}, err

View File

@ -49,7 +49,7 @@ func (s *Store) CreateExamPrepUnit(ctx context.Context, catalogCourseID int64, i
Thumbnail: toPgText(input.Thumbnail),
SortOrder: pgtype.Int4{Int32: target, Valid: true},
PublishStatus: pub,
AccessTier: contentAccessTierForCreate(input.AccessTier),
AccessTier: domain.ChildContentAccessTierForCreate(input.AccessTier),
})
if err != nil {
return domain.ExamPrepUnit{}, err
@ -67,7 +67,7 @@ func (s *Store) CreateExamPrepUnit(ctx context.Context, catalogCourseID int64, i
Thumbnail: toPgText(input.Thumbnail),
SortOrder: pgtype.Int4{Valid: false},
PublishStatus: pub,
AccessTier: contentAccessTierForCreate(input.AccessTier),
AccessTier: domain.ChildContentAccessTierForCreate(input.AccessTier),
})
if err != nil {
return domain.ExamPrepUnit{}, err

View File

@ -11,6 +11,7 @@ import (
func (s *Store) CreatePayment(ctx context.Context, input domain.CreatePaymentInput) (*domain.Payment, error) {
payment, err := s.queries.CreatePayment(ctx, dbgen.CreatePaymentParams{
UserID: input.UserID,
CourseID: int64PtrToPgInt8(input.CourseID),
PlanID: int64PtrToPgInt8(input.PlanID),
SubscriptionID: int64PtrToPgInt8(input.SubscriptionID),
SessionID: pgtype.Text{Valid: false},
@ -97,6 +98,7 @@ func (s *Store) GetPaymentsByUserID(ctx context.Context, userID int64, limit, of
result[i] = domain.Payment{
ID: p.ID,
UserID: p.UserID,
CourseID: int8PtrToInt64Ptr(p.CourseID),
PlanID: int8PtrToInt64Ptr(p.PlanID),
SubscriptionID: int8PtrToInt64Ptr(p.SubscriptionID),
SessionID: fromPgTextPtr(p.SessionID),
@ -263,6 +265,7 @@ func paymentAdminRowToDomain(row dbgen.ListPaymentsAdminRow) domain.Payment {
return domain.Payment{
ID: row.ID,
UserID: row.UserID,
CourseID: int8PtrToInt64Ptr(row.CourseID),
PlanID: int8PtrToInt64Ptr(row.PlanID),
SubscriptionID: int8PtrToInt64Ptr(row.SubscriptionID),
SessionID: fromPgTextPtr(row.SessionID),
@ -298,6 +301,7 @@ func paymentToDomain(p dbgen.Payment) *domain.Payment {
return &domain.Payment{
ID: p.ID,
UserID: p.UserID,
CourseID: int8PtrToInt64Ptr(p.CourseID),
PlanID: int8PtrToInt64Ptr(p.PlanID),
SubscriptionID: int8PtrToInt64Ptr(p.SubscriptionID),
SessionID: fromPgTextPtr(p.SessionID),

View File

@ -143,7 +143,7 @@ func optionalAccessTierUpdate(val *string) pgtype.Text {
}
s := strings.TrimSpace(strings.ToUpper(*val))
switch s {
case string(domain.ContentAccessFree), string(domain.ContentAccessPremium):
case string(domain.ContentAccessFree), string(domain.ContentAccessPremium), string(domain.ContentAccessInherit):
return pgtype.Text{String: s, Valid: true}
default:
return pgtype.Text{Valid: false}

View File

@ -5,7 +5,7 @@ import (
"context"
)
const publicCourseColumns = `c.id,c.name,COALESCE(c.description,''),COALESCE(c.thumbnail,''),c.access_tier,
const publicCourseColumns = `c.id,c.name,COALESCE(c.description,''),COALESCE(c.thumbnail,''),c.access_tier,c.price,c.currency,
(SELECT COUNT(*) FROM exam_prep.units u WHERE u.catalog_course_id=c.id AND u.publish_status='PUBLISHED'),
(SELECT COUNT(*) 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 u.publish_status='PUBLISHED'
@ -29,7 +29,7 @@ func (s *Store) PublicCatalogCourses(ctx context.Context, search string, limit,
defer rows.Close()
for rows.Next() {
var c domain.PublicCourse
if err := rows.Scan(&c.ID, &c.Name, &c.Description, &c.Thumbnail, &c.AccessTier, &c.ChapterCount, &c.LessonCount, &c.QuizCount); err != nil {
if err := rows.Scan(&c.ID, &c.Name, &c.Description, &c.Thumbnail, &c.AccessTier, &c.Price, &c.Currency, &c.ChapterCount, &c.LessonCount, &c.QuizCount); err != nil {
return out, err
}
out.Courses = append(out.Courses, c)
@ -40,7 +40,7 @@ func (s *Store) PublicCatalogCourses(ctx context.Context, search string, limit,
func (s *Store) PublicCatalogCourse(ctx context.Context, id int64) (domain.PublicCourseOutline, error) {
out := domain.PublicCourseOutline{Chapters: []domain.PublicChapter{}}
err := s.conn.QueryRow(ctx, `SELECT `+publicCourseColumns+` FROM exam_prep.catalog_courses c WHERE c.id=$1 AND c.publish_status='PUBLISHED' AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.id)`, id).
Scan(&out.ID, &out.Name, &out.Description, &out.Thumbnail, &out.AccessTier, &out.ChapterCount, &out.LessonCount, &out.QuizCount)
Scan(&out.ID, &out.Name, &out.Description, &out.Thumbnail, &out.AccessTier, &out.Price, &out.Currency, &out.ChapterCount, &out.LessonCount, &out.QuizCount)
if err != nil {
return out, err
}
@ -67,7 +67,7 @@ func (s *Store) PublicCatalogCourse(ctx context.Context, id int64) (domain.Publi
return out, err
}
rows, err = s.conn.Query(ctx, `SELECT u.id,l.id,l.title,COALESCE(l.description,''),COALESCE(l.thumbnail,''),
CASE WHEN c.access_tier='PREMIUM' OR u.access_tier='PREMIUM' OR m.access_tier='PREMIUM' OR l.access_tier='PREMIUM' THEN 'PREMIUM' ELSE 'FREE' END
COALESCE(NULLIF(l.access_tier,'INHERIT'),NULLIF(m.access_tier,'INHERIT'),NULLIF(u.access_tier,'INHERIT'),c.access_tier)
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 JOIN exam_prep.catalog_courses c ON c.id=u.catalog_course_id
WHERE c.id=$1 AND c.publish_status='PUBLISHED' AND NOT EXISTS(SELECT 1 FROM academy_archived_courses a WHERE a.course_id=c.id) AND u.publish_status='PUBLISHED' AND m.publish_status='PUBLISHED' AND l.publish_status='PUBLISHED'

View File

@ -0,0 +1,91 @@
package affiliates
import (
"context"
"fmt"
"github.com/jackc/pgx/v5"
"os"
"testing"
"time"
)
// Run against a disposable migrated DB. All fixtures and setting edits roll back.
func TestPostgresAffiliateLedger(t *testing.T) {
url := os.Getenv("AFFILIATE_TEST_DB_URL")
if url == "" {
t.Skip("set AFFILIATE_TEST_DB_URL to a disposable database migrated through 000009")
}
ctx, cancel := context.WithTimeout(context.Background(), 45*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)
exec := func(sql string, args ...any) {
t.Helper()
if _, err := tx.Exec(ctx, sql, args...); err != nil {
t.Fatal(err)
}
}
scalar := func(sql string, args ...any) int64 {
t.Helper()
var v int64
if err := tx.QueryRow(ctx, sql, args...).Scan(&v); err != nil {
t.Fatal(err)
}
return v
}
user := func() int64 {
return scalar(`INSERT INTO users(email,password,role,status) VALUES($1,'test','STUDENT','ACTIVE') RETURNING id`, fmt.Sprintf("affiliate-test-%d@example.test", time.Now().UnixNano()))
}
owner, learner := user(), user()
exec(`INSERT INTO affiliates(user_id,status,application) VALUES($1,'APPROVED','Test makeup promotion')`, owner)
code := fmt.Sprintf("%016X", owner)
codeID := scalar(`INSERT INTO referral_codes(user_id,code) VALUES($1,$2) RETURNING id`, owner, code)
exec(`UPDATE referral_settings SET commission_percent=10,commission_mode='EVERY_COURSE',holding_days=0 WHERE id=TRUE`)
exec(`INSERT INTO user_referrals(referrer_id,referred_user_id,referral_code_id) VALUES($1,$2,$3)`, owner, learner, codeID)
course := func() int64 {
return scalar(`INSERT INTO exam_prep.catalog_courses(name,category,publish_status,access_tier,price,currency) VALUES('Affiliate test','EDUCATION','PUBLISHED','PREMIUM',1000,'ETB') RETURNING id`)
}
pay := func(c int64) int64 {
return scalar(`INSERT INTO payments(user_id,course_id,amount,currency,nonce,status) VALUES($1,$2,1000,'ETB',$3,'SUCCESS') RETURNING id`, learner, c, fmt.Sprintf("affiliate-%d", time.Now().UnixNano()))
}
c1 := course()
p1 := pay(c1)
exec(`UPDATE payments SET status='SUCCESS' WHERE id=$1`, p1)
if n := scalar(`SELECT COUNT(*) FROM referral_commissions WHERE referrer_id=$1`, owner); n != 1 {
t.Fatalf("duplicate confirmation: %d", n)
}
pay(c1)
if n := scalar(`SELECT COUNT(*) FROM referral_commissions WHERE referrer_id=$1`, owner); n != 1 {
t.Fatalf("duplicate course: %d", n)
}
payout := scalar(`SELECT affiliate_request_payout($1,'ETB','BANK','Test Artist','bank-123')`, owner)
if amount := scalar(`SELECT amount::bigint FROM affiliate_payouts WHERE id=$1`, payout); amount != 100 {
t.Fatalf("payout=%d", amount)
}
// A reserved commission reversal rejects and releases its payout atomically.
commission := scalar(`SELECT id FROM referral_commissions WHERE payment_id=$1`, p1)
scalar(`SELECT affiliate_reverse_commission($1,NULL,'Test reversal')`, commission)
if n := scalar(`SELECT COUNT(*) FROM affiliate_payouts WHERE id=$1 AND status='REJECTED'`, payout); n != 1 {
t.Fatal("reversal did not reject reserved payout")
}
// Hold prevents withdrawing an otherwise valid sale.
exec(`UPDATE referral_settings SET holding_days=14 WHERE id=TRUE`)
p2 := pay(course())
if n := scalar(`SELECT COUNT(*) FROM referral_commissions WHERE payment_id=$1 AND available_at>now()`, p2); n != 1 {
t.Fatal("hold was not applied")
}
// Expired attribution prevents later commissions.
exec(`UPDATE user_referrals SET attributed_until=now()-interval '1 day' WHERE referred_user_id=$1`, learner)
p3 := pay(course())
if n := scalar(`SELECT COUNT(*) FROM referral_commissions WHERE payment_id=$1`, p3); n != 0 {
t.Fatal("expired referral earned commission")
}
}

View File

@ -0,0 +1,198 @@
package affiliates
import (
dbgen "Rezina-Backend/gen/db"
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/services/referrals"
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"strings"
)
type Service struct {
q *dbgen.Queries
referrals *referrals.Service
}
func NewService(q *dbgen.Queries) *Service { return &Service{q: q, referrals: referrals.NewService(q)} }
func profile(r dbgen.AffiliateProfileRow) domain.AffiliateProfile {
return domain.AffiliateProfile{UserID: r.UserID, Status: r.Status, Application: r.Application, TermsAcceptedAt: r.TermsAcceptedAt.Time, TermsVersion: r.TermsVersion, ReviewNote: r.ReviewNote, CreatedAt: r.CreatedAt.Time, UpdatedAt: r.UpdatedAt.Time, Email: r.Email.String, FirstName: r.FirstName.String, LastName: r.LastName.String, Code: r.Code}
}
func settings(r dbgen.AffiliateSettingsRow) domain.AffiliateSettings {
return domain.AffiliateSettings{CommissionPercent: r.CommissionPercent, CommissionMode: r.CommissionMode, AttributionDays: r.AttributionDays, HoldingDays: r.HoldingDays, ShareBaseURL: r.ShareBaseUrl, UpdatedAt: r.UpdatedAt.Time}
}
func (s *Service) Settings(ctx context.Context) (domain.AffiliateSettings, error) {
r, e := s.q.AffiliateSettings(ctx)
return settings(r), e
}
func (s *Service) UpdateSettings(ctx context.Context, actor int64, in domain.AffiliateSettingsInput) (domain.AffiliateSettings, error) {
in.ShareBaseURL = strings.TrimSpace(in.ShareBaseURL)
if err := domain.ValidateAffiliateSettings(in); err != nil {
return domain.AffiliateSettings{}, err
}
percent, err := referrals.CommissionPercent(*in.CommissionPercent)
if err != nil {
return domain.AffiliateSettings{}, err
}
r, err := s.q.AffiliateUpdateSettings(ctx, dbgen.AffiliateUpdateSettingsParams{ActorID: actor, CommissionPercent: percent, CommissionMode: in.CommissionMode, AttributionDays: in.AttributionDays, HoldingDays: in.HoldingDays, ShareBaseUrl: in.ShareBaseURL})
return settings(dbgen.AffiliateSettingsRow(r)), err
}
func (s *Service) Apply(ctx context.Context, user int64, in domain.AffiliateApplicationInput) (int64, error) {
in.Application = strings.TrimSpace(in.Application)
if !in.AcceptTerms || in.TermsVersion != domain.CurrentAffiliateTerms().Version || !domain.AffiliateTextValid(in.Application, 10, 2000) {
return 0, domain.ErrAffiliateInput
}
return s.q.AffiliateApply(ctx, dbgen.AffiliateApplyParams{UserID: user, Application: in.Application})
}
func (s *Service) Review(ctx context.Context, user, actor int64, in domain.AffiliateReviewInput) (int64, error) {
in.Note = strings.TrimSpace(in.Note)
if !domain.AffiliateTextValid(in.Note, 3, 2000) || (in.Status != "APPROVED" && in.Status != "REJECTED" && in.Status != "SUSPENDED") {
return 0, domain.ErrAffiliateInput
}
return s.q.AffiliateReview(ctx, dbgen.AffiliateReviewParams{UserID: user, ActorID: actor, Status: in.Status, Note: in.Note})
}
func (s *Service) Self(ctx context.Context, user int64) (domain.AffiliateDashboard, error) {
out := domain.AffiliateDashboard{Balances: []domain.AffiliateBalance{}, Terms: domain.CurrentAffiliateTerms()}
var err error
out.Settings, err = s.Settings(ctx)
if err != nil {
return out, err
}
row, err := s.q.AffiliateProfile(ctx, user)
if errors.Is(err, pgx.ErrNoRows) {
return out, nil
}
if err != nil {
return out, err
}
p := profile(row)
if p.Status == "APPROVED" {
p.Code, err = s.referrals.Code(ctx, user)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return out, err
}
out.ShareURL = domain.AffiliateShareURL(out.Settings.ShareBaseURL, p.Code)
} else {
p.Code = ""
}
out.Profile = &p
out.Balances, err = s.Balances(ctx, user)
if err != nil {
return out, err
}
summary, err := s.q.GetReferralSummary(ctx, user)
if err != nil {
return out, err
}
out.TotalReferrals = summary.TotalReferrals
out.ConvertedReferrals = summary.ConvertedReferrals
return out, nil
}
func (s *Service) Balances(ctx context.Context, user int64) ([]domain.AffiliateBalance, error) {
rows, err := s.q.AffiliateBalances(ctx, user)
out := []domain.AffiliateBalance{}
for _, r := range rows {
out = append(out, domain.AffiliateBalance(r))
}
return out, err
}
func (s *Service) List(ctx context.Context, status string, limit, offset int32) (domain.AffiliateListData, error) {
out := domain.AffiliateListData{Items: []domain.AffiliateProfile{}, Limit: limit, Offset: offset}
if status != "" && status != "PENDING" && status != "APPROVED" && status != "REJECTED" && status != "SUSPENDED" {
return out, domain.ErrAffiliateInput
}
rows, err := s.q.AffiliateList(ctx, dbgen.AffiliateListParams{Status: status, PageLimit: limit, PageOffset: offset})
if err != nil {
return out, err
}
for _, r := range rows {
out.Items = append(out.Items, profile(dbgen.AffiliateProfileRow(r)))
}
out.TotalCount, err = s.q.AffiliateCount(ctx, status)
return out, err
}
func intPtr(p pgtype.Int8) *int64 {
if !p.Valid {
return nil
}
return &p.Int64
}
func textPtr(p pgtype.Text) *string {
if !p.Valid {
return nil
}
return &p.String
}
func (s *Service) Commissions(ctx context.Context, user int64, limit, offset int32) (domain.AffiliateCommissionData, error) {
out := domain.AffiliateCommissionData{Items: []domain.AffiliateCommission{}, Limit: limit, Offset: offset}
rows, err := s.q.AffiliateCommissions(ctx, dbgen.AffiliateCommissionsParams{UserID: user, PageLimit: limit, PageOffset: offset})
if err != nil {
return out, err
}
for _, r := range rows {
c := domain.AffiliateCommission{ID: r.ID, ReferrerID: r.ReferrerID, PaymentID: r.PaymentID, CourseID: intPtr(r.CourseID), CommissionPercent: r.CommissionPercent, Amount: r.Amount, Currency: r.Currency, Status: r.Status, CreatedAt: r.CreatedAt.Time, AvailableAt: r.AvailableAt.Time, ReversalReason: textPtr(r.ReversalReason), PayoutID: intPtr(r.PayoutID)}
if r.ReversedAt.Valid {
t := r.ReversedAt.Time
c.ReversedAt = &t
}
out.Items = append(out.Items, c)
}
out.TotalCount, err = s.q.AffiliateCommissionCount(ctx, user)
return out, err
}
func (s *Service) RequestPayout(ctx context.Context, user int64, in domain.AffiliatePayoutInput) (int64, error) {
in.Currency = strings.ToUpper(strings.TrimSpace(in.Currency))
in.AccountName = strings.TrimSpace(in.AccountName)
in.AccountReference = strings.TrimSpace(in.AccountReference)
if err := domain.ValidateAffiliatePayout(in); err != nil {
return 0, err
}
return s.q.AffiliateRequestPayout(ctx, dbgen.AffiliateRequestPayoutParams{UserID: user, Currency: in.Currency, Method: in.Method, AccountName: in.AccountName, AccountReference: in.AccountReference})
}
func (s *Service) Payouts(ctx context.Context, user int64, status string, limit, offset int32) (domain.AffiliatePayoutData, error) {
out := domain.AffiliatePayoutData{Items: []domain.AffiliatePayout{}, Limit: limit, Offset: offset}
if status != "" && status != "REQUESTED" && status != "PAID" && status != "REJECTED" {
return out, domain.ErrAffiliateInput
}
rows, err := s.q.AffiliatePayouts(ctx, dbgen.AffiliatePayoutsParams{UserID: user, Status: status, PageLimit: limit, PageOffset: offset})
if err != nil {
return out, err
}
for _, r := range rows {
p := domain.AffiliatePayout{ID: r.ID, UserID: r.UserID, Currency: r.Currency, Amount: r.Amount, Status: r.Status, Method: r.Method, AccountName: r.AccountName, AccountReference: r.AccountReference, PaymentReference: textPtr(r.PaymentReference), ReviewNote: r.ReviewNote, CreatedAt: r.CreatedAt.Time}
if r.ReviewedAt.Valid {
t := r.ReviewedAt.Time
p.ReviewedAt = &t
}
out.Items = append(out.Items, p)
}
out.TotalCount, err = s.q.AffiliatePayoutCount(ctx, dbgen.AffiliatePayoutCountParams{UserID: user, Status: status})
return out, err
}
func (s *Service) ReviewPayout(ctx context.Context, id, actor int64, in domain.AffiliatePayoutReviewInput) (int64, error) {
in.Note = strings.TrimSpace(in.Note)
in.PaymentReference = strings.TrimSpace(in.PaymentReference)
if !domain.AffiliateTextValid(in.Note, 3, 2000) || (in.Status != "PAID" && in.Status != "REJECTED") || (in.Status == "PAID" && !domain.AffiliateTextValid(in.PaymentReference, 3, 120)) {
return 0, domain.ErrAffiliateInput
}
return s.q.AffiliateReviewPayout(ctx, dbgen.AffiliateReviewPayoutParams{PayoutID: id, ActorID: actor, Status: in.Status, PaymentReference: in.PaymentReference, Note: in.Note})
}
func (s *Service) Reverse(ctx context.Context, id, actor int64, reason string) (int64, error) {
reason = strings.TrimSpace(reason)
if !domain.AffiliateTextValid(reason, 3, 2000) {
return 0, domain.ErrAffiliateInput
}
return s.q.AffiliateReverseCommission(ctx, dbgen.AffiliateReverseCommissionParams{CommissionID: id, ActorID: actor, Reason: reason})
}
func (s *Service) Events(ctx context.Context, user int64, limit, offset int32) (domain.AffiliateEventData, error) {
out := domain.AffiliateEventData{Items: []domain.AffiliateEvent{}, Limit: limit, Offset: offset}
rows, err := s.q.AffiliateEvents(ctx, dbgen.AffiliateEventsParams{UserID: user, PageLimit: limit, PageOffset: offset})
for _, r := range rows {
out.Items = append(out.Items, domain.AffiliateEvent{ID: r.ID, AffiliateUserID: intPtr(r.AffiliateUserID), ActorID: intPtr(r.ActorID), Event: r.Event, Details: r.Details, CreatedAt: r.CreatedAt.Time})
}
return out, err
}

View File

@ -0,0 +1,38 @@
package affiliates
import (
"Rezina-Backend/internal/domain"
"context"
"errors"
"testing"
)
func TestAffiliateMutationsValidateBeforeStorage(t *testing.T) {
s := NewService(nil)
ctx := context.Background()
tests := []func() error{
func() error {
_, e := s.Apply(ctx, 42, domain.AffiliateApplicationInput{Application: "I promote makeup courses", AcceptTerms: false, TermsVersion: "1"})
return e
},
func() error {
_, e := s.Apply(ctx, 42, domain.AffiliateApplicationInput{Application: "I promote makeup courses", AcceptTerms: true, TermsVersion: "old"})
return e
},
func() error {
_, e := s.Review(ctx, 42, 1, domain.AffiliateReviewInput{Status: "APPROVED", Note: " "})
return e
},
func() error { _, e := s.RequestPayout(ctx, 42, domain.AffiliatePayoutInput{}); return e },
func() error {
_, e := s.ReviewPayout(ctx, 1, 1, domain.AffiliatePayoutReviewInput{Status: "PAID", Note: "Paid externally"})
return e
},
func() error { _, e := s.Reverse(ctx, 1, 1, ""); return e },
}
for i, fn := range tests {
if err := fn(); !errors.Is(err, domain.ErrAffiliateInput) {
t.Fatalf("case %d: %v", i, err)
}
}
}

View File

@ -0,0 +1,87 @@
package chapa
import (
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/ports"
"context"
"errors"
"fmt"
"github.com/google/uuid"
"math"
"strconv"
"strings"
"time"
)
var ErrCourseNotPurchasable = errors.New("course is unavailable for purchase or has no configured price")
var ErrCourseAlreadyOwned = errors.New("course already purchased")
type courseCheckoutStore interface {
ports.CoursePurchaseStore
ports.ExamPrepCatalogCourseStore
}
func (s *Service) InitiateCoursePayment(ctx context.Context, userID, courseID int64, req domain.CourseCheckoutRequest) (*domain.CourseCheckoutResponse, error) {
if err := s.configured(); err != nil {
return nil, err
}
store, ok := s.paymentStore.(courseCheckoutStore)
if !ok {
return nil, errors.New("course checkout store unavailable")
}
course, err := store.GetExamPrepCatalogCourseByID(ctx, courseID)
if err != nil {
return nil, ErrCourseNotPurchasable
}
if !course.VisibleToLearners() || course.Price <= 0 || math.IsNaN(course.Price) || math.IsInf(course.Price, 0) {
return nil, ErrCourseNotPurchasable
}
owned, err := store.HasCoursePurchase(ctx, userID, courseID)
if err != nil {
return nil, err
}
if owned {
return nil, ErrCourseAlreadyOwned
}
user, err := s.userStore.GetUserByID(ctx, userID)
if err != nil {
return nil, err
}
ref := uuid.NewString()
method := "chapa"
expires := time.Now().Add(3 * time.Hour)
// The server snapshots price/currency; clients cannot choose the amount charged.
payment, err := s.paymentStore.CreatePayment(ctx, domain.CreatePaymentInput{UserID: userID, CourseID: &courseID, Amount: course.Price, Currency: course.Currency, PaymentMethod: &method, Nonce: ref, ExpiresAt: &expires})
if err != nil {
return nil, err
}
init := domain.ChapaInitializeRequest{Amount: formatAmount(course.Price), Currency: course.Currency, Email: user.Email, FirstName: user.FirstName, LastName: user.LastName, PhoneNumber: formatChapaPhone(req.Phone), TxRef: ref, CallbackURL: s.cfg.CHAPA_CALLBACK_URL, ReturnURL: s.cfg.CHAPA_RETURN_URL}
if strings.TrimSpace(init.FirstName) == "" {
init.FirstName = "Customer"
}
if strings.TrimSpace(init.LastName) == "" {
init.LastName = "User"
}
if init.PhoneNumber == "" {
init.PhoneNumber = formatChapaPhone(user.PhoneNumber)
}
init.Customization.Title = sanitizeChapaCustomization("Rezina Academy")
init.Customization.Description = sanitizeChapaCustomization(course.Name)
url, err := s.initializeTransaction(ctx, init)
if err != nil {
_ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed))
return nil, err
}
if err = s.paymentStore.UpdatePaymentSessionID(ctx, payment.ID, ref, url); err != nil {
return nil, err
}
return &domain.CourseCheckoutResponse{PaymentID: payment.ID, SessionID: ref, PaymentURL: url, CourseID: courseID, Amount: course.Price, Currency: course.Currency}, nil
}
func validateCoursePaymentAmount(payment *domain.Payment, data domain.ChapaTransactionData) error {
amount, err := strconv.ParseFloat(data.Amount.String(), 64)
if err != nil || math.IsNaN(amount) || math.IsInf(amount, 0) || math.Abs(amount-payment.Amount) > 0.001 || !strings.EqualFold(data.Currency, payment.Currency) {
return fmt.Errorf("verified course payment amount or currency does not match checkout")
}
return nil
}

View File

@ -0,0 +1,102 @@
package chapa
import (
"Rezina-Backend/internal/config"
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/ports"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
type coursePaymentStore struct {
ports.PaymentStore
ports.ExamPrepCatalogCourseStore
ports.CoursePurchaseStore
course domain.ExamPrepCatalogCourse
owned bool
created domain.CreatePaymentInput
completed int
payment domain.Payment
}
func (s *coursePaymentStore) GetExamPrepCatalogCourseByID(context.Context, int64) (domain.ExamPrepCatalogCourse, error) {
return s.course, nil
}
func (s *coursePaymentStore) HasCoursePurchase(context.Context, int64, int64) (bool, error) {
return s.owned, nil
}
func (s *coursePaymentStore) CreatePayment(_ context.Context, in domain.CreatePaymentInput) (*domain.Payment, error) {
s.created = in
return &domain.Payment{ID: 71}, nil
}
func (s *coursePaymentStore) UpdatePaymentSessionID(context.Context, int64, string, string) error {
return nil
}
func (s *coursePaymentStore) GetPaymentByNonce(context.Context, string) (*domain.Payment, error) {
return &s.payment, nil
}
func (s *coursePaymentStore) CompleteCoursePayment(context.Context, int64, string, string) error {
s.completed++
return nil
}
type courseCheckoutUserStore struct{ ports.UserStore }
func (s courseCheckoutUserStore) GetUserByID(context.Context, int64) (domain.User, error) {
return domain.User{Email: "learner@example.com", FirstName: "Test", LastName: "Learner"}, nil
}
func TestCourseCheckoutUsesServerPriceAndNoSubscription(t *testing.T) {
var request domain.ChapaInitializeRequest
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
t.Error(err)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"status":"success","data":{"checkout_url":"https://checkout.example/course"}}`))
}))
defer server.Close()
store := &coursePaymentStore{course: domain.ExamPrepCatalogCourse{ID: 12, Price: 1250.50, Currency: "ETB", PublishStatus: domain.ContentPublishPublished}}
svc := NewService(&config.Config{CHAPA_SECRET_KEY: "test", CHAPA_BASE_URL: server.URL}, server.Client(), store, nil, courseCheckoutUserStore{})
out, err := svc.InitiateCoursePayment(context.Background(), 42, 12, domain.CourseCheckoutRequest{})
if err != nil {
t.Fatal(err)
}
if out.Amount != 1250.50 || request.Amount != "1250.50" || request.Currency != "ETB" {
t.Fatalf("incorrect checkout: %+v / %+v", out, request)
}
if store.created.CourseID == nil || *store.created.CourseID != 12 || store.created.PlanID != nil || store.created.SubscriptionID != nil {
t.Fatalf("incorrect purchase scope: %+v", store.created)
}
store.owned = true
if _, err := svc.InitiateCoursePayment(context.Background(), 42, 12, domain.CourseCheckoutRequest{}); err != ErrCourseAlreadyOwned {
t.Fatalf("expected already owned, got %v", err)
}
store.owned = false
store.course.Price = 0
if _, err := svc.InitiateCoursePayment(context.Background(), 42, 12, domain.CourseCheckoutRequest{}); err != ErrCourseNotPurchasable {
t.Fatalf("zero price should not charge, got %v", err)
}
}
func TestCoursePaymentVerificationRejectsMismatches(t *testing.T) {
id := int64(12)
for _, tt := range []struct {
name, amount, currency string
want bool
}{
{"valid", "1250.50", "ETB", true}, {"underpayment", "1", "ETB", false}, {"wrong currency", "1250.50", "USD", false}, {"missing amount", "", "ETB", false}, {"nan", "NaN", "ETB", false},
} {
t.Run(tt.name, func(t *testing.T) {
store := &coursePaymentStore{payment: domain.Payment{ID: 71, CourseID: &id, Amount: 1250.50, Currency: "ETB", Nonce: "ref"}}
svc := NewService(nil, nil, store, nil, nil)
err := svc.applyVerifiedTransaction(context.Background(), domain.ChapaTransactionData{TxRef: "ref", Reference: "verified", Status: "success", Amount: domain.ChapaFlexibleString(tt.amount), Currency: tt.currency})
if (err == nil) != tt.want || (store.completed == 1) != tt.want {
t.Fatalf("err=%v grants=%d", err, store.completed)
}
})
}
}

View File

@ -330,6 +330,18 @@ func (s *Service) applyVerifiedTransaction(ctx context.Context, data domain.Chap
return fmt.Errorf("payment not found for tx_ref %s: %w", data.TxRef, err)
}
if payment.CourseID != nil {
if err := validateCoursePaymentAmount(payment, data); err != nil {
return err
}
if mapChapaStatus(data.Status) == string(domain.PaymentStatusSuccess) {
store, ok := s.paymentStore.(ports.CoursePurchaseStore)
if !ok {
return errors.New("course purchase store unavailable")
}
return store.CompleteCoursePayment(ctx, payment.ID, data.Reference, data.PaymentMethod)
}
}
if payment.Status == string(domain.PaymentStatusSuccess) {
return ErrPaymentAlreadyPaid
}

View File

@ -25,6 +25,7 @@ var ErrExamPrepPracticeParentLinkNotFound = errors.New("practice is not linked t
// examPrepStore is implemented by *repository.Store (catalog courses, units, modules, lessons, practices, personas).
type examPrepStore interface {
ports.CoursePurchaseStore
PublicCatalogCourses(context.Context, string, int32, int32) (domain.PublicCatalogPage, error)
PublicCatalogCourse(context.Context, int64) (domain.PublicCourseOutline, error)
ListChapterQuizzes(ctx context.Context, chapterID int64, publishedOnly bool, limit, offset int32) ([]domain.ExamPrepPractice, int64, error)
@ -60,6 +61,12 @@ func (s *Service) ensurePersonaRef(ctx context.Context, id int64) error {
func (s *Service) CreateCatalogCourse(ctx context.Context, input domain.CreateExamPrepCatalogCourseInput) (domain.ExamPrepCatalogCourse, error) {
input.Category = "EDUCATION"
if input.Currency == "" {
input.Currency = "ETB"
}
if err := domain.ValidateCoursePricing(input.Price, input.Currency); err != nil {
return domain.ExamPrepCatalogCourse{}, err
}
return s.store.CreateExamPrepCatalogCourse(ctx, input)
}
@ -88,6 +95,22 @@ func (s *Service) ListCatalogCourses(ctx context.Context, publishedOnly bool, li
}
func (s *Service) UpdateCatalogCourse(ctx context.Context, id int64, input domain.UpdateExamPrepCatalogCourseInput) (domain.ExamPrepCatalogCourse, error) {
if input.Price != nil || input.Currency != nil {
current, err := s.GetCatalogCourseByID(ctx, id)
if err != nil {
return domain.ExamPrepCatalogCourse{}, err
}
price, currency := current.Price, current.Currency
if input.Price != nil {
price = *input.Price
}
if input.Currency != nil {
currency = *input.Currency
}
if err := domain.ValidateCoursePricing(price, currency); err != nil {
return domain.ExamPrepCatalogCourse{}, err
}
}
c, err := s.store.UpdateExamPrepCatalogCourse(ctx, id, input)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@ -715,3 +738,14 @@ func (s *Service) GetChapterLessonContainer(ctx context.Context, chapterID int64
}
return s.store.GetChapterLessonContainer(ctx, chapterID)
}
func (s *Service) HasCoursePurchase(ctx context.Context, userID, courseID int64) (bool, error) {
return s.store.HasCoursePurchase(ctx, userID, courseID)
}
func (s *Service) CourseVideoLessonIDs(ctx context.Context, key string) ([]int64, error) {
return s.store.CourseVideoLessonIDs(ctx, key)
}
func (s *Service) CourseContentAccess(ctx context.Context, kind string, id int64) (domain.CourseContentAccess, error) {
return s.store.CourseContentAccess(ctx, kind, id)
}

View File

@ -290,7 +290,7 @@ func (a *App) examPrepEffectiveTierForUnit(ctx context.Context, unitID int64) (d
if err != nil {
return "", false, err
}
return domain.EffectiveContentAccessTier(cc.AccessTier, unit.AccessTier), true, nil
return domain.ResolveContentAccessTier(cc.AccessTier, unit.AccessTier), true, nil
}
func (a *App) examPrepEffectiveTierForModule(ctx context.Context, moduleID int64) (domain.ContentAccessTier, bool, error) {
@ -306,7 +306,7 @@ func (a *App) examPrepEffectiveTierForModule(ctx context.Context, moduleID int64
if err != nil {
return "", false, err
}
return domain.EffectiveContentAccessTier(cc.AccessTier, unit.AccessTier, module.AccessTier), true, nil
return domain.ResolveContentAccessTier(cc.AccessTier, unit.AccessTier, module.AccessTier), true, nil
}
func (a *App) examPrepEffectiveTierForLesson(ctx context.Context, lessonID int64) (domain.ContentAccessTier, bool, error) {
@ -326,7 +326,7 @@ func (a *App) examPrepEffectiveTierForLesson(ctx context.Context, lessonID int64
if err != nil {
return "", false, err
}
return domain.EffectiveContentAccessTier(cc.AccessTier, unit.AccessTier, module.AccessTier, lesson.AccessTier), true, nil
return domain.ResolveContentAccessTier(cc.AccessTier, unit.AccessTier, module.AccessTier, lesson.AccessTier), true, nil
}
func (a *App) examPrepEffectiveTierForPractice(ctx context.Context, practiceID int64) (domain.ContentAccessTier, bool, error) {

View File

@ -0,0 +1,71 @@
package httpserver
import (
"Rezina-Backend/internal/domain"
"errors"
"github.com/gofiber/fiber/v2"
"github.com/jackc/pgx/v5"
"strings"
)
// RequireCoursePurchase protects consumption. Collection metadata is redacted by handlers.
func (a *App) RequireCoursePurchase() fiber.Handler {
return func(c *fiber.Ctx) error {
role, userID, err := subscriptionScopedUser(c)
if err != nil {
return err
}
if bypassSubscriptionForRole(role) {
return c.Next()
}
kind := ""
id := int64(0)
path := c.Route().Path
if strings.Contains(path, "/videos/engagement/heartbeat") {
var req domain.VideoEngagementHeartbeatInput
if err := c.BodyParser(&req); err != nil || req.ContentID <= 0 {
return fiber.NewError(400, "Invalid video heartbeat")
}
kind = "lesson"
id = req.ContentID
} else if strings.Contains(path, "/lessons/:id") {
kind = "lesson"
id, _, err = parseRouteInt64(c, "id")
} else if strings.Contains(path, "/quizzes/") || strings.Contains(path, "/practices/") {
for _, param := range []string{"practiceId", "id"} {
if c.Params(param) != "" {
kind = "practice"
id, _, err = parseRouteInt64(c, param)
break
}
}
}
if err != nil {
return err
}
if kind == "" {
return c.Next()
}
access, err := a.examPrepSvc.CourseContentAccess(c.Context(), kind, id)
if errors.Is(err, pgx.ErrNoRows) {
return fiber.NewError(404, "Content not found")
}
if err != nil {
return fiber.NewError(500, "Failed to verify course access")
}
if !access.Published {
return fiber.NewError(404, "Content not found")
}
if access.Tier == domain.ContentAccessFree {
return c.Next()
}
owned, err := a.examPrepSvc.HasCoursePurchase(c.Context(), userID, access.CourseID)
if err != nil {
return fiber.NewError(500, "Failed to verify course purchase")
}
if !owned {
return c.Status(403).JSON(fiber.Map{"message": "Purchase this course to access premium content", "course_id": access.CourseID, "code": "COURSE_PURCHASE_REQUIRED"})
}
return c.Next()
}
}

View File

@ -0,0 +1,64 @@
package httpserver
import (
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/repository"
"Rezina-Backend/internal/services/examprep"
"context"
"github.com/gofiber/fiber/v2"
"net/http/httptest"
"testing"
)
type purchaseAccessStore struct {
*repository.Store
tier domain.ContentAccessTier
published bool
ownedCourse int64
checkedCourse int64
}
func (s *purchaseAccessStore) CourseContentAccess(context.Context, string, int64) (domain.CourseContentAccess, error) {
return domain.CourseContentAccess{CourseID: 12, Tier: s.tier, Published: s.published}, nil
}
func (s *purchaseAccessStore) HasCoursePurchase(_ context.Context, userID, courseID int64) (bool, error) {
s.checkedCourse = courseID
return userID == 42 && courseID == s.ownedCourse, nil
}
func TestCoursePurchaseGate(t *testing.T) {
for _, tt := range []struct {
name string
tier domain.ContentAccessTier
owned int64
published bool
role domain.Role
status int
}{
{"free preview", domain.ContentAccessFree, 0, true, domain.RoleStudent, 204},
{"unpaid", domain.ContentAccessPremium, 0, true, domain.RoleStudent, 403},
{"owns course", domain.ContentAccessPremium, 12, true, domain.RoleStudent, 204},
{"another course purchase", domain.ContentAccessPremium, 99, true, domain.RoleStudent, 403},
{"hidden content", domain.ContentAccessFree, 12, false, domain.RoleStudent, 404},
{"staff", domain.ContentAccessPremium, 0, false, domain.RoleAdmin, 204},
{"open learner", domain.ContentAccessPremium, 0, true, domain.RoleOpenLearner, 204},
} {
t.Run(tt.name, func(t *testing.T) {
store := &purchaseAccessStore{tier: tt.tier, published: tt.published, ownedCourse: tt.owned}
app := &App{examPrepSvc: examprep.NewService(store)}
server := fiber.New()
server.Get("/lessons/:id", func(c *fiber.Ctx) error { c.Locals("role", tt.role); c.Locals("user_id", int64(42)); return c.Next() }, app.RequireCoursePurchase(), func(c *fiber.Ctx) error { return c.SendStatus(204) })
response, err := server.Test(httptest.NewRequest("GET", "/lessons/7", nil))
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
if response.StatusCode != tt.status {
t.Fatalf("got %d want %d", response.StatusCode, tt.status)
}
if tt.tier == domain.ContentAccessFree && store.checkedCourse != 0 {
t.Fatal("free preview checked purchase")
}
})
}
}

View File

@ -0,0 +1,468 @@
package handlers
import (
"Rezina-Backend/internal/domain"
"errors"
"github.com/gofiber/fiber/v2"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"strconv"
)
func affiliateResponse(c *fiber.Ctx, data any, err error) error {
if err != nil {
if errors.Is(err, domain.ErrAffiliateInput) {
return fiber.NewError(400, "Invalid affiliate fields; check amounts, status, terms, and required notes")
}
if errors.Is(err, pgx.ErrNoRows) {
return fiber.NewError(404, "Affiliate record not found")
}
var p *pgconn.PgError
if errors.As(err, &p) {
if p.Code == "23514" || p.Code == "23505" {
return fiber.NewError(409, "Affiliate operation conflicts with current status, balance, or payment reference")
}
if p.Code == "P0002" {
return fiber.NewError(404, "Affiliate record not found")
}
}
return fiber.NewError(500, "Unable to process affiliate request")
}
return c.JSON(domain.Response{Success: true, StatusCode: 200, Message: "Affiliate request successful", Data: data})
}
func affiliateFilter(c *fiber.Ctx) (int64, error) {
raw := c.Query("user_id")
if raw == "" {
return 0, nil
}
id, e := strconv.ParseInt(raw, 10, 64)
if e != nil || id <= 0 {
return 0, fiber.NewError(400, "Invalid user_id")
}
return id, nil
}
// GetAffiliateSelf godoc
// @Summary Get my affiliate dashboard and program rules
// @Description Returns the authenticated learner application (null before applying), versioned program rules, current settings, referral counts, and separate currency balances. Approved affiliates receive a share code and, when configured, a share URL. No referred-user personal data is exposed.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateDashboard}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/affiliates/me [get]
func (h *Handler) GetAffiliateSelf(c *fiber.Ctx) error {
user, err := referralLearner(c)
if err != nil {
return err
}
data, err := h.affiliateSvc.Self(c.Context(), user)
return affiliateResponse(c, data, err)
}
// ApplyAffiliate godoc
// @Summary Apply to the affiliate program
// @Description Requires an active learner, accept_terms=true, the current terms_version from GET /affiliates/me, and a 10-2000 character application. New applications are PENDING. Rejected applicants may reapply; pending, approved, or suspended accounts cannot replace their application.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateMutationData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/affiliates/apply [post]
// @Accept json
// @Param body body domain.AffiliateApplicationInput true "Request"
func (h *Handler) ApplyAffiliate(c *fiber.Ctx) error {
user, err := referralLearner(c)
if err != nil {
return err
}
var input domain.AffiliateApplicationInput
if err := c.BodyParser(&input); err != nil {
return fiber.NewError(400, "Invalid request body")
}
data, err := h.affiliateSvc.Apply(c.Context(), user, input)
return affiliateResponse(c, domain.AffiliateMutationData{ID: data}, err)
}
// GetAffiliateCommissions godoc
// @Summary List my affiliate commissions
// @Description Returns only the authenticated learner earnings. Status is PENDING during the holding period, AVAILABLE after maturity, RESERVED for a requested payout, PAID after payout settlement, or REVERSED. Monetary values are decimal strings and never combined across currencies.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateCommissionData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/affiliates/commissions [get]
// @Param limit query int false "Page size (1-100)"
// @Param offset query int false "Offset"
func (h *Handler) GetAffiliateCommissions(c *fiber.Ctx) error {
user, err := referralLearner(c)
if err != nil {
return err
}
limit, offset, err := referralPagination(c)
if err != nil {
return err
}
data, err := h.affiliateSvc.Commissions(c.Context(), user, limit, offset)
return affiliateResponse(c, data, err)
}
// GetAffiliatePayouts godoc
// @Summary List my affiliate payouts
// @Description Returns only the authenticated learner payout requests, including snapshotted beneficiary details and external transfer references. Optional status is REQUESTED, PAID, or REJECTED.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliatePayoutData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/affiliates/payouts [get]
// @Param limit query int false "Page size (1-100)"
// @Param offset query int false "Offset"
// @Param status query string false "Status filter"
func (h *Handler) GetAffiliatePayouts(c *fiber.Ctx) error {
user, err := referralLearner(c)
if err != nil {
return err
}
limit, offset, err := referralPagination(c)
if err != nil {
return err
}
data, err := h.affiliateSvc.Payouts(c.Context(), user, c.Query("status"), limit, offset)
return affiliateResponse(c, data, err)
}
// RequestAffiliatePayout godoc
// @Summary Request payout of available affiliate earnings
// @Description Requires an approved active affiliate. Reserves all matured available earnings in the requested currency after outstanding recovery debt. The server calculates the amount; clients cannot select an amount. One REQUESTED payout per currency is allowed. This endpoint does not transfer money.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateMutationData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/affiliates/payouts [post]
// @Accept json
// @Param body body domain.AffiliatePayoutInput true "Request"
func (h *Handler) RequestAffiliatePayout(c *fiber.Ctx) error {
user, err := referralLearner(c)
if err != nil {
return err
}
var input domain.AffiliatePayoutInput
if err := c.BodyParser(&input); err != nil {
return fiber.NewError(400, "Invalid request body")
}
data, err := h.affiliateSvc.RequestPayout(c.Context(), user, input)
return affiliateResponse(c, domain.AffiliateMutationData{ID: data}, err)
}
// ListAffiliates godoc
// @Summary List affiliate applications
// @Description ADMIN and SUPER_ADMIN only. Returns applications and learner contact details. Optional status is PENDING, APPROVED, REJECTED, or SUSPENDED. Lists return items, total_count, limit, and offset.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateListData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/affiliates [get]
// @Param limit query int false "Page size (1-100)"
// @Param offset query int false "Offset"
// @Param status query string false "Status filter"
func (h *Handler) ListAffiliates(c *fiber.Ctx) error {
actor, err := referralAdmin(c)
if err != nil {
return err
}
_ = actor
limit, offset, err := referralPagination(c)
if err != nil {
return err
}
data, err := h.affiliateSvc.List(c.Context(), c.Query("status"), limit, offset)
return affiliateResponse(c, data, err)
}
// ReviewAffiliate godoc
// @Summary Approve, reject, or suspend an affiliate
// @Description ADMIN and SUPER_ADMIN only. The path id is the affiliate learner user ID. Allowed transitions: PENDING to APPROVED or REJECTED, APPROVED to SUSPENDED, and SUSPENDED to APPROVED. A 3-2000 character review note is required. Changes are audited.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateMutationData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse "Record not found"
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/affiliates/{id}/review [put]
// @Param id path int true "Record ID"
// @Accept json
// @Param body body domain.AffiliateReviewInput true "Request"
func (h *Handler) ReviewAffiliate(c *fiber.Ctx) error {
actor, err := referralAdmin(c)
if err != nil {
return err
}
_ = actor
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil || id <= 0 {
return fiber.NewError(400, "Invalid record ID")
}
var input domain.AffiliateReviewInput
if err := c.BodyParser(&input); err != nil {
return fiber.NewError(400, "Invalid request body")
}
data, err := h.affiliateSvc.Review(c.Context(), id, actor, input)
return affiliateResponse(c, domain.AffiliateMutationData{ID: data}, err)
}
// GetAffiliateSettings godoc
// @Summary Get affiliate program settings
// @Description ADMIN and SUPER_ADMIN only. Returns the commission percentage, FIRST_PURCHASE or EVERY_COURSE policy, attribution window, earning hold, and learner share URL base. Initial defaults are 0 percent, FIRST_PURCHASE, 30 attribution days, and 14 holding days.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateSettings}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/affiliates/settings [get]
func (h *Handler) GetAffiliateSettings(c *fiber.Ctx) error {
actor, err := referralAdmin(c)
if err != nil {
return err
}
_ = actor
data, err := h.affiliateSvc.Settings(c.Context())
return affiliateResponse(c, data, err)
}
// UpdateAffiliateSettings godoc
// @Summary Update affiliate program settings
// @Description ADMIN and SUPER_ADMIN only. Commission percentage is 0-100 with at most two decimals; zero disables future earnings. Attribution is 1-365 days and holding is 0-365 days. FIRST_PURCHASE rewards the first paid purchase; EVERY_COURSE rewards each distinct eligible course. Rates and holds are snapshotted on successful payment; attribution expiry is snapshotted when the code is applied. Changes are audited. Optional share_base_url must be an absolute HTTP(S) learner URL; share links append ref=CODE.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateSettings}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/affiliates/settings [put]
// @Accept json
// @Param body body domain.AffiliateSettingsInput true "Request"
func (h *Handler) UpdateAffiliateSettings(c *fiber.Ctx) error {
actor, err := referralAdmin(c)
if err != nil {
return err
}
_ = actor
var input domain.AffiliateSettingsInput
if err := c.BodyParser(&input); err != nil {
return fiber.NewError(400, "Invalid request body")
}
data, err := h.affiliateSvc.UpdateSettings(c.Context(), actor, input)
return affiliateResponse(c, data, err)
}
// ListAffiliateCommissions godoc
// @Summary List affiliate course commissions
// @Description ADMIN and SUPER_ADMIN only. Lists the course commission ledger across affiliates or for a positive user_id filter. Amount and commission_percent are decimal strings. Includes maturity, payout association, and reversal information.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateCommissionData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/affiliates/commissions [get]
// @Param limit query int false "Page size (1-100)"
// @Param offset query int false "Offset"
// @Param user_id query int false "Affiliate user ID"
func (h *Handler) ListAffiliateCommissions(c *fiber.Ctx) error {
actor, err := referralAdmin(c)
if err != nil {
return err
}
_ = actor
limit, offset, err := referralPagination(c)
if err != nil {
return err
}
user, err := affiliateFilter(c)
if err != nil {
return err
}
data, err := h.affiliateSvc.Commissions(c.Context(), user, limit, offset)
return affiliateResponse(c, data, err)
}
// ReverseAffiliateCommission godoc
// @Summary Reverse an affiliate commission
// @Description ADMIN and SUPER_ADMIN only. The path id is the commission ID. Requires a 3-2000 character reason. Reversing an earning rejects any pending payout in the same affiliate/currency and releases reservations. Already-paid earnings become recovery debt deducted from future payouts. Repeated reversal is idempotent. This does not refund the learner or revoke course access.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateMutationData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse "Record not found"
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/affiliates/commissions/{id}/reverse [post]
// @Param id path int true "Record ID"
// @Accept json
// @Param body body domain.AffiliateReversalInput true "Request"
func (h *Handler) ReverseAffiliateCommission(c *fiber.Ctx) error {
actor, err := referralAdmin(c)
if err != nil {
return err
}
_ = actor
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil || id <= 0 {
return fiber.NewError(400, "Invalid record ID")
}
var input domain.AffiliateReversalInput
if err := c.BodyParser(&input); err != nil {
return fiber.NewError(400, "Invalid request body")
}
data, err := h.affiliateSvc.Reverse(c.Context(), id, actor, input.Reason)
return affiliateResponse(c, domain.AffiliateMutationData{ID: data}, err)
}
// ListAffiliatePayouts godoc
// @Summary List affiliate payout requests
// @Description ADMIN and SUPER_ADMIN only. Lists payout requests and beneficiary details. Optional status is REQUESTED, PAID, or REJECTED. Optional positive user_id filters one affiliate. These sensitive records must only be shown to authorized administrators.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliatePayoutData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/affiliates/payouts [get]
// @Param limit query int false "Page size (1-100)"
// @Param offset query int false "Offset"
// @Param user_id query int false "Affiliate user ID"
// @Param status query string false "Status filter"
func (h *Handler) ListAffiliatePayouts(c *fiber.Ctx) error {
actor, err := referralAdmin(c)
if err != nil {
return err
}
_ = actor
limit, offset, err := referralPagination(c)
if err != nil {
return err
}
user, err := affiliateFilter(c)
if err != nil {
return err
}
data, err := h.affiliateSvc.Payouts(c.Context(), user, c.Query("status"), limit, offset)
return affiliateResponse(c, data, err)
}
// ReviewAffiliatePayout godoc
// @Summary Record an externally paid payout or reject a request
// @Description ADMIN and SUPER_ADMIN only. The path id is the payout request ID. Review a REQUESTED payout as PAID or REJECTED with a 3-2000 character note. PAID requires an already completed external transfer and a unique 3-120 character payment_reference; this API never sends money. Affiliate must still be approved and active. REJECTED releases reservations. Matching repeated reviews are idempotent; conflicting final-state reviews return 409.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateMutationData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse "Record not found"
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/affiliates/payouts/{id}/review [put]
// @Param id path int true "Record ID"
// @Accept json
// @Param body body domain.AffiliatePayoutReviewInput true "Request"
func (h *Handler) ReviewAffiliatePayout(c *fiber.Ctx) error {
actor, err := referralAdmin(c)
if err != nil {
return err
}
_ = actor
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil || id <= 0 {
return fiber.NewError(400, "Invalid record ID")
}
var input domain.AffiliatePayoutReviewInput
if err := c.BodyParser(&input); err != nil {
return fiber.NewError(400, "Invalid request body")
}
data, err := h.affiliateSvc.ReviewPayout(c.Context(), id, actor, input)
return affiliateResponse(c, domain.AffiliateMutationData{ID: data}, err)
}
// GetAffiliateEvents godoc
// @Summary List affiliate audit events
// @Description ADMIN and SUPER_ADMIN only. Returns newest-first application, settings, payout, and commission reversal audit events. Details contain event-specific fields without beneficiary account details. Optional positive user_id filters an affiliate. This list returns items, limit, and offset without a total_count.
// @Tags affiliates
// @Security Bearer
// @Produce json
// @Success 200 {object} domain.Response{data=domain.AffiliateEventData}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 403 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/affiliates/events [get]
// @Param limit query int false "Page size (1-100)"
// @Param offset query int false "Offset"
// @Param user_id query int false "Affiliate user ID"
func (h *Handler) GetAffiliateEvents(c *fiber.Ctx) error {
actor, err := referralAdmin(c)
if err != nil {
return err
}
_ = actor
limit, offset, err := referralPagination(c)
if err != nil {
return err
}
user, err := affiliateFilter(c)
if err != nil {
return err
}
data, err := h.affiliateSvc.Events(c.Context(), user, limit, offset)
return affiliateResponse(c, data, err)
}

View File

@ -0,0 +1,40 @@
package handlers
import (
"Rezina-Backend/internal/domain"
"github.com/gofiber/fiber/v2"
"net/http/httptest"
"testing"
)
func TestAffiliateAdminOperationsRejectNonAdmins(t *testing.T) {
for _, role := range []domain.Role{domain.RoleStudent, domain.RoleOpenLearner, domain.RoleSupport, domain.RoleContentManager} {
h := &Handler{}
for _, handler := range []fiber.Handler{h.ListAffiliates, h.ReviewAffiliate, h.UpdateAffiliateSettings, h.ListAffiliatePayouts, h.ReviewAffiliatePayout, h.ReverseAffiliateCommission, h.GetAffiliateEvents} {
app := fiber.New()
app.Post("/", func(c *fiber.Ctx) error { c.Locals("user_id", int64(42)); c.Locals("role", role); return c.Next() }, handler)
r, err := app.Test(httptest.NewRequest("POST", "/", nil))
if err != nil {
t.Fatal(err)
}
r.Body.Close()
if r.StatusCode != 403 {
t.Fatalf("role=%s status=%d", role, r.StatusCode)
}
}
}
}
func TestAffiliateUserFilterCannotSelectAllWithZero(t *testing.T) {
for _, query := range []string{"0", "-1", "bad", "9223372036854775808"} {
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error { _, err := affiliateFilter(c); return err })
r, err := app.Test(httptest.NewRequest("GET", "/?user_id="+query, nil))
if err != nil {
t.Fatal(err)
}
r.Body.Close()
if r.StatusCode != 400 {
t.Fatalf("accepted %s", query)
}
}
}

View File

@ -25,6 +25,7 @@ type initiatePaymentReq struct {
}
type paymentRes struct {
CourseID *int64 `json:"course_id,omitempty"`
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
PlanID *int64 `json:"plan_id,omitempty"`
@ -47,7 +48,8 @@ type paymentRes struct {
// InitiateSubscriptionPayment godoc
// @Summary Initiate subscription payment
// @Description Creates a payment session for a subscription plan
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
// @Failure 410 {object} domain.ErrorResponse
// @Tags payments
// @Accept json
// @Produce json
@ -464,7 +466,8 @@ type verifyOTPReq struct {
// InitiateDirectPayment godoc
// @Summary Initiate direct payment
// @Description Creates a payment session and initiates direct payment (OTP-based)
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
// @Failure 410 {object} domain.ErrorResponse
// @Tags payments
// @Accept json
// @Produce json
@ -604,6 +607,7 @@ func paymentToRes(p *domain.Payment) *paymentRes {
ID: p.ID,
UserID: p.UserID,
PlanID: p.PlanID,
CourseID: p.CourseID,
SubscriptionID: p.SubscriptionID,
SessionID: p.SessionID,
Amount: p.Amount,

View File

@ -165,9 +165,22 @@ func (h *Handler) HandleChapaSuccessPage(c *fiber.Ctx) error {
}
}
} else {
page.Helper = "Return to Rezina and refresh your subscription status if you do not see access immediately."
page.Helper = "Return to Rezina and refresh your course if you do not see access immediately."
}
if txRef != "" {
if payment, err := h.chapaSvc.LookupPayment(c.Context(), txRef); err == nil && payment.CourseID != nil {
page.PlanName = ""
page.Title = "Course Payment"
page.StatusLabel = "Processing confirmation"
page.Body = "We are confirming your course payment. Return to Rezina and refresh your course shortly."
page.Helper = "Your purchase unlocks this course."
if payment.Status == string(domain.PaymentStatusSuccess) {
page.StatusLabel = "Course unlocked"
page.Body = "Your course purchase is confirmed. You can now access its premium learning content."
}
}
}
html, err := renderPaymentSuccessPage(page)
if err != nil {
return c.Status(fiber.StatusInternalServerError).SendString("Failed to render success page")

View File

@ -24,7 +24,8 @@ type authorizeChapaDirectPaymentReq struct {
// InitiateChapaDirectPayment godoc
// @Summary Initiate Chapa direct charge subscription payment
// @Description Starts a Chapa Direct Charge (USSD push or OTP) for a subscription plan without hosted checkout redirect.
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
// @Failure 410 {object} domain.ErrorResponse
// @Tags payments
// @Accept json
// @Produce json

View File

@ -65,21 +65,21 @@ func applyExamPrepCatalogCourseEffectiveAccessTier(cc *domain.ExamPrepCatalogCou
func applyExamPrepUnitEffectiveAccessTier(unit *domain.ExamPrepUnit, catalogCourse domain.ExamPrepCatalogCourse, role domain.Role) {
unit.EffectiveAccessTier = domain.ContentAccessTierForRole(
role,
domain.EffectiveContentAccessTier(catalogCourse.AccessTier, unit.AccessTier),
domain.ResolveContentAccessTier(catalogCourse.AccessTier, unit.AccessTier),
)
}
func applyExamPrepModuleEffectiveAccessTier(module *domain.ExamPrepModule, catalogCourse domain.ExamPrepCatalogCourse, unit domain.ExamPrepUnit, role domain.Role) {
module.EffectiveAccessTier = domain.ContentAccessTierForRole(
role,
domain.EffectiveContentAccessTier(catalogCourse.AccessTier, unit.AccessTier, module.AccessTier),
domain.ResolveContentAccessTier(catalogCourse.AccessTier, unit.AccessTier, module.AccessTier),
)
}
func applyExamPrepLessonEffectiveAccessTier(lesson *domain.ExamPrepLesson, catalogCourse domain.ExamPrepCatalogCourse, unit domain.ExamPrepUnit, module domain.ExamPrepModule, role domain.Role) {
lesson.EffectiveAccessTier = domain.ContentAccessTierForRole(
role,
domain.EffectiveContentAccessTier(catalogCourse.AccessTier, unit.AccessTier, module.AccessTier, lesson.AccessTier),
domain.ResolveContentAccessTier(catalogCourse.AccessTier, unit.AccessTier, module.AccessTier, lesson.AccessTier),
)
}

View File

@ -0,0 +1,62 @@
package handlers
import (
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/services/chapa"
"errors"
"github.com/gofiber/fiber/v2"
"strconv"
)
// CheckoutCourse godoc
// @Summary Purchase a course
// @Description Creates a one-time Chapa checkout at the course's server-configured price. Verified payment grants permanent access to this course only. Optional referral_code applies first-touch affiliate attribution before checkout; same-code retries preserve the original expiry. Invalid or conflicting codes return 400.
// @Tags learning
// @Accept json
// @Produce json
// @Param courseId path int true "Course ID"
// @Param body body domain.CourseCheckoutRequest false "Optional checkout phone"
// @Success 200 {object} domain.Response{data=domain.CourseCheckoutResponse}
// @Failure 400 {object} domain.ErrorResponse
// @Failure 401 {object} domain.ErrorResponse
// @Failure 409 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Security Bearer
// @Router /api/v1/courses/{courseId}/checkout [post]
func (h *Handler) CheckoutCourse(c *fiber.Ctx) error {
id, err := strconv.ParseInt(c.Params("courseId"), 10, 64)
if err != nil || id <= 0 {
return fiber.NewError(400, "Invalid course ID")
}
userID, ok := c.Locals("user_id").(int64)
if !ok || userID <= 0 {
return fiber.NewError(401, "Unauthorized")
}
var req domain.CourseCheckoutRequest
if len(c.Body()) > 0 {
if err := c.BodyParser(&req); err != nil {
return fiber.NewError(400, "Invalid request body")
}
}
if req.ReferralCode != "" {
// Attribution is first-touch and persisted before the payment snapshot is created.
if err := h.referralSvc.Apply(c.Context(), userID, req.ReferralCode); err != nil {
return referralResponse(c, nil, err)
}
}
out, err := h.chapaSvc.InitiateCoursePayment(c.Context(), userID, id, req)
if errors.Is(err, chapa.ErrCourseAlreadyOwned) {
return fiber.NewError(409, err.Error())
}
if errors.Is(err, chapa.ErrCourseNotPurchasable) {
return fiber.NewError(400, err.Error())
}
if err != nil {
return fiber.NewError(500, "Failed to initialize course checkout")
}
return c.JSON(domain.Response{Success: true, Message: "Course checkout created", Data: out})
}
func (h *Handler) RetiredSubscriptionCheckout(c *fiber.Ctx) error {
return c.Status(fiber.StatusGone).JSON(domain.ErrorResponse{Message: "Subscription plans have been replaced by course purchases. Use POST /courses/:courseId/checkout."})
}

View File

@ -0,0 +1,62 @@
package handlers
import (
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/repository"
"Rezina-Backend/internal/services/examprep"
"context"
"github.com/gofiber/fiber/v2"
"net/http/httptest"
"testing"
)
type courseVideoAccessStore struct {
*repository.Store
tier domain.ContentAccessTier
owned bool
}
func (s *courseVideoAccessStore) CourseVideoLessonIDs(context.Context, string) ([]int64, error) {
return []int64{7}, nil
}
func (s *courseVideoAccessStore) CourseContentAccess(context.Context, string, int64) (domain.CourseContentAccess, error) {
return domain.CourseContentAccess{CourseID: 12, Tier: s.tier, Published: true}, nil
}
func (s *courseVideoAccessStore) HasCoursePurchase(context.Context, int64, int64) (bool, error) {
return s.owned, nil
}
func TestVideoURLRefreshRequiresCoursePurchase(t *testing.T) {
for _, tt := range []struct {
name string
tier domain.ContentAccessTier
owned bool
status int
}{
{"premium key blocked", domain.ContentAccessPremium, false, 403},
{"purchased key allowed", domain.ContentAccessPremium, true, 204},
{"preview key allowed", domain.ContentAccessFree, false, 204},
} {
t.Run(tt.name, func(t *testing.T) {
store := &courseVideoAccessStore{tier: tt.tier, owned: tt.owned}
h := &Handler{examPrepSvc: examprep.NewService(store)}
app := fiber.New()
app.Get("/refresh", func(c *fiber.Ctx) error {
c.Locals("role", domain.RoleStudent)
c.Locals("user_id", int64(42))
if err := h.authorizeCourseVideoReference(c, "lessons/video.mp4"); err != nil {
return err
}
return c.SendStatus(204)
})
resp, err := app.Test(httptest.NewRequest("GET", "/refresh", nil))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.status {
t.Fatalf("got %d want %d", resp.StatusCode, tt.status)
}
})
}
}

View File

@ -40,6 +40,9 @@ func (h *Handler) CreateExamPrepCatalogCourse(c *fiber.Ctx) error {
}
out, err := h.examPrepSvc.CreateCatalogCourse(c.Context(), req)
if err != nil {
if errors.Is(err, domain.ErrInvalidCoursePricing) {
return fiber.NewError(400, err.Error())
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to create course",
Error: err.Error(),
@ -233,6 +236,9 @@ func (h *Handler) UpdateExamPrepCatalogCourse(c *fiber.Ctx) error {
}
out, err := h.examPrepSvc.UpdateCatalogCourse(c.Context(), id, req)
if err != nil {
if errors.Is(err, domain.ErrInvalidCoursePricing) {
return fiber.NewError(400, err.Error())
}
if errors.Is(err, examprep.ErrCatalogCourseNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Course not found",

View File

@ -55,7 +55,7 @@ func (h *Handler) applyExamPrepAccessCatalogCourses(ctx context.Context, c *fibe
return nil
}
for i := range items {
if err := h.lmsProgressSvc.ApplyExamPrepAccessCatalogCourse(ctx, role, userID, &items[i]); err != nil {
if err := h.applyExamPrepAccessCatalogCourse(ctx, c, &items[i]); err != nil {
return err
}
}
@ -71,7 +71,10 @@ func (h *Handler) applyExamPrepAccessCatalogCourse(ctx context.Context, c *fiber
if !ok || userID == 0 {
return nil
}
return h.lmsProgressSvc.ApplyExamPrepAccessCatalogCourse(ctx, role, userID, item)
if err := h.lmsProgressSvc.ApplyExamPrepAccessCatalogCourse(ctx, role, userID, item); err != nil {
return err
}
return h.applyCoursePurchaseAccess(ctx, c, "course", item.ID, item.Access)
}
func (h *Handler) applyExamPrepAccessUnits(ctx context.Context, c *fiber.Ctx, items []domain.ExamPrepUnit) error {
@ -84,7 +87,7 @@ func (h *Handler) applyExamPrepAccessUnits(ctx context.Context, c *fiber.Ctx, it
return nil
}
for i := range items {
if err := h.lmsProgressSvc.ApplyExamPrepAccessUnit(ctx, role, userID, &items[i]); err != nil {
if err := h.applyExamPrepAccessUnit(ctx, c, &items[i]); err != nil {
return err
}
}
@ -100,7 +103,10 @@ func (h *Handler) applyExamPrepAccessUnit(ctx context.Context, c *fiber.Ctx, ite
if !ok || userID == 0 {
return nil
}
return h.lmsProgressSvc.ApplyExamPrepAccessUnit(ctx, role, userID, item)
if err := h.lmsProgressSvc.ApplyExamPrepAccessUnit(ctx, role, userID, item); err != nil {
return err
}
return h.applyCoursePurchaseAccess(ctx, c, "chapter", item.ID, item.Access)
}
func (h *Handler) applyExamPrepAccessModules(ctx context.Context, c *fiber.Ctx, items []domain.ExamPrepModule) error {
@ -142,7 +148,7 @@ func (h *Handler) applyExamPrepAccessLessons(ctx context.Context, c *fiber.Ctx,
return nil
}
for i := range items {
if err := h.lmsProgressSvc.ApplyExamPrepAccessLesson(ctx, role, userID, &items[i]); err != nil {
if err := h.applyExamPrepAccessLesson(ctx, c, &items[i]); err != nil {
return err
}
}
@ -158,5 +164,43 @@ func (h *Handler) applyExamPrepAccessLesson(ctx context.Context, c *fiber.Ctx, i
if !ok || userID == 0 {
return nil
}
return h.lmsProgressSvc.ApplyExamPrepAccessLesson(ctx, role, userID, item)
if err := h.lmsProgressSvc.ApplyExamPrepAccessLesson(ctx, role, userID, item); err != nil {
return err
}
if err := h.applyCoursePurchaseAccess(ctx, c, "lesson", item.ID, item.Access); err != nil {
return err
}
if item.Access != nil && !item.Access.IsAccessible {
item.VideoURL = nil
}
return nil
}
func (h *Handler) applyCoursePurchaseAccess(ctx context.Context, c *fiber.Ctx, kind string, id int64, access *domain.LMSEntityAccess) error {
role, _ := c.Locals("role").(domain.Role)
if role.BypassesSubscription() || access == nil {
return nil
}
resource, err := h.examPrepSvc.CourseContentAccess(ctx, kind, id)
if err != nil {
return err
}
if !resource.Published {
access.IsAccessible = false
access.Reason = "Content is not published"
return nil
}
if resource.Tier == domain.ContentAccessFree {
return nil
}
userID, _ := c.Locals("user_id").(int64)
owned, err := h.examPrepSvc.HasCoursePurchase(ctx, userID, resource.CourseID)
if err != nil {
return err
}
if !owned {
access.IsAccessible = false
access.Reason = "Purchase this course to access premium content"
}
return nil
}

View File

@ -98,6 +98,9 @@ func (h *Handler) GetFileURL(c *fiber.Ctx) error {
})
}
if err := h.authorizeCourseVideoReference(c, key); err != nil {
return err
}
url, err := h.minioSvc.GetURL(c.Context(), key, 1*time.Hour)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
@ -160,6 +163,9 @@ func (h *Handler) RefreshFileURL(c *fiber.Ctx) error {
})
}
if err := h.authorizeCourseVideoReference(c, objectKey); err != nil {
return err
}
freshURL, err := h.minioSvc.GetURL(c.Context(), objectKey, 1*time.Hour)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
@ -967,3 +973,43 @@ func (h *Handler) SubmitAudioAnswer(c *fiber.Ctx) error {
StatusCode: fiber.StatusOK,
})
}
// A known object key must not bypass the course paywall via URL refresh.
func (h *Handler) authorizeCourseVideoReference(c *fiber.Ctx, reference string) error {
role, _ := c.Locals("role").(domain.Role)
if !role.IsCustomerLearnerRole() || role.BypassesSubscription() {
return nil
}
key, err := h.extractObjectKeyFromReference(reference)
if err != nil {
return fiber.NewError(400, "Invalid file reference")
}
ids, err := h.examPrepSvc.CourseVideoLessonIDs(c.Context(), key)
if err != nil {
return fiber.NewError(500, "Failed to verify video access")
}
userID, _ := c.Locals("user_id").(int64)
for _, id := range ids {
resource, err := h.examPrepSvc.CourseContentAccess(c.Context(), "lesson", id)
if err != nil {
return fiber.NewError(500, "Failed to verify video access")
}
if !resource.Published {
continue
}
if resource.Tier == domain.ContentAccessFree {
return nil
}
owned, err := h.examPrepSvc.HasCoursePurchase(c.Context(), userID, resource.CourseID)
if err != nil {
return fiber.NewError(500, "Failed to verify course purchase")
}
if owned {
return nil
}
}
if len(ids) > 0 {
return fiber.NewError(403, "Purchase this course to access its video")
}
return nil
}

View File

@ -37,6 +37,7 @@ import (
"Rezina-Backend/internal/services/videoengagement"
vimeoservice "Rezina-Backend/internal/services/vimeo"
"Rezina-Backend/internal/services/affiliates"
"Rezina-Backend/internal/services/referrals"
"Rezina-Backend/internal/services/settings"
@ -52,6 +53,7 @@ import (
type Handler struct {
referralSvc *referrals.Service
affiliateSvc *affiliates.Service
questionsSvc *questions.Service
faqSvc *faqs.Service
appVersionSvc *appversions.Service
@ -136,6 +138,7 @@ func New(
) *Handler {
return &Handler{
referralSvc: referrals.NewService(analyticsDB),
affiliateSvc: affiliates.NewService(analyticsDB),
questionsSvc: questionsSvc,
faqSvc: faqSvc,
appVersionSvc: appVersionSvc,

View File

@ -14,6 +14,7 @@ import (
type adminPaymentRes struct {
ID int64 `json:"id"`
CourseID *int64 `json:"course_id,omitempty"`
UserID int64 `json:"user_id"`
PlanID *int64 `json:"plan_id,omitempty"`
SubscriptionID *int64 `json:"subscription_id,omitempty"`
@ -38,6 +39,7 @@ type adminPaymentRes struct {
type adminPaymentListItemRes struct {
ID int64 `json:"id"`
CourseID *int64 `json:"course_id,omitempty"`
UserID int64 `json:"user_id"`
PlanID *int64 `json:"plan_id,omitempty"`
SubscriptionID *int64 `json:"subscription_id,omitempty"`
@ -224,6 +226,7 @@ func adminPaymentListToRes(p *domain.Payment) adminPaymentListItemRes {
UserID: p.UserID,
PlanID: p.PlanID,
SubscriptionID: p.SubscriptionID,
CourseID: p.CourseID,
SessionID: p.SessionID,
TransactionID: p.TransactionID,
Nonce: p.Nonce,
@ -259,6 +262,7 @@ func adminPaymentToRes(p *domain.Payment) adminPaymentRes {
UserID: p.UserID,
PlanID: p.PlanID,
SubscriptionID: p.SubscriptionID,
CourseID: p.CourseID,
SessionID: p.SessionID,
TransactionID: p.TransactionID,
Nonce: p.Nonce,

View File

@ -38,7 +38,7 @@ func referralResponse(c *fiber.Ctx, data any, err error) error {
return fiber.NewError(400, err.Error())
}
if errors.Is(err, pgx.ErrNoRows) {
return fiber.NewError(403, "Active learner account required")
return fiber.NewError(403, "Approved active affiliate account required")
}
return fiber.NewError(500, "Unable to process referral request")
}
@ -61,7 +61,7 @@ func referralPagination(c *fiber.Ctx) (int32, int32, error) {
// @Summary Create Referral Code
// @Tags referrals
// @Security Bearer
// @Description Creates or returns the authenticated learner's stable share code. Requires an active STUDENT or OPEN_LEARNER account; a subscription is not required.
// @Description Creates or returns the authenticated learner's stable share code. Requires an approved affiliate with an active STUDENT or OPEN_LEARNER account.
// @Success 200 {object} domain.Response{data=ReferralCodeData}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
@ -167,7 +167,7 @@ func (h *Handler) ListMyReferrals(c *fiber.Ctx) error {
// @Tags referrals
// @Router /api/v1/referrals/wallet [get]
// @Security Bearer
// @Description Returns wallet balances separately by currency and a paginated commission ledger. Decimal amounts and percentages are strings. Only the first successful positive subscription payment earns a commission; duplicate callbacks and renewals do not. Reversed credits are excluded from balances. This endpoint does not initiate cash payouts.
// @Description Returns wallet balances separately by currency and a paginated commission ledger. Decimal amounts and percentages are strings. Only the qualifying course payment earns a commission; duplicate callbacks and renewals do not. Reversed credits are excluded from balances. This endpoint does not initiate cash payouts.
// @Success 200 {object} domain.Response{data=ReferralWalletData}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
@ -217,7 +217,7 @@ func (h *Handler) GetReferralSettings(c *fiber.Ctx) error {
// @Tags referrals
// @Router /api/v1/admin/referrals/settings [put]
// @Security Bearer
// @Description Sets the percentage credited on a referred learner's first successful positive subscription payment. Accepts 0 through 100 with at most two decimal places. Zero disables new credits. Changes affect future conversions only; existing credits retain their rate. Restricted to ADMIN and SUPER_ADMIN; changes are audited.
// @Description Sets the percentage credited on a referred learner's qualifying course payment. Accepts 0 through 100 with at most two decimal places. Zero disables new credits. Changes affect future conversions only; existing credits retain their rate. Restricted to ADMIN and SUPER_ADMIN; changes are audited.
// @Accept json
// @Param body body updateReferralSettingsReq true "Commission percentage configuration"
// @Success 200 {object} domain.Response{data=ReferralSettingsData}

View File

@ -26,7 +26,8 @@ type requestCheckoutLinkRes struct {
// RequestSubscriptionCheckoutLink godoc
// @Summary Send web checkout link to learner
// @Description Sends the standalone web checkout URL to the learner by email or SMS (registration channel). Intended when mobile clients show a subscription-required state.
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
// @Failure 410 {object} domain.ErrorResponse
// @Tags subscriptions
// @Accept json
// @Produce json

View File

@ -202,7 +202,8 @@ func (h *Handler) CreateSubscriptionPlan(c *fiber.Ctx) error {
// ListSubscriptionPlans godoc
// @Summary List subscription plans
// @Description Returns subscription plans. Optional category filter: EDUCATION.
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
// @Failure 410 {object} domain.ErrorResponse
// @Tags subscriptions
// @Produce json
// @Param active_only query bool false "Customer requests always return active plans; false is honored only by the admin endpoint" default(true)
@ -250,7 +251,8 @@ func (h *Handler) ListSubscriptionPlans(c *fiber.Ctx) error {
// GetSubscriptionPlan godoc
// @Summary Get a subscription plan
// @Description Returns a single subscription plan by ID
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
// @Failure 410 {object} domain.ErrorResponse
// @Tags subscriptions
// @Produce json
// @Param id path int true "Plan ID"
@ -453,7 +455,8 @@ func (h *Handler) DeleteSubscriptionPlan(c *fiber.Ctx) error {
// Subscribe godoc
// @Summary Subscribe to a plan (Admin only - bypasses payment)
// @Description Creates a new subscription for the authenticated user. For regular users, use /payments/subscribe instead.
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
// @Failure 410 {object} domain.ErrorResponse
// @Tags subscriptions
// @Accept json
// @Produce json
@ -524,7 +527,8 @@ func (h *Handler) Subscribe(c *fiber.Ctx) error {
// SubscribeWithPayment godoc
// @Summary Subscribe to a plan with payment
// @Description Initiates payment for a subscription plan. Returns payment URL for checkout.
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
// @Failure 410 {object} domain.ErrorResponse
// @Tags subscriptions
// @Accept json
// @Produce json

View File

@ -10,7 +10,7 @@ type applyReferralReq struct {
}
type updateReferralSettingsReq struct {
// Percentage of the first successful positive subscription payment, with at most two decimal places. Zero disables new commissions.
// Percentage of the qualifying verified course payment, with at most two decimal places. Zero disables new commissions.
Percent *float64 `json:"commission_percent" validate:"required" minimum:"0" maximum:"100" example:"10.25"`
}

View File

@ -7,6 +7,15 @@ import (
)
func (a *App) initAdminRoutes(api fiber.Router, h *handlers.Handler) {
api.Get("/affiliates", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.ListAffiliates)
api.Put("/affiliates/:id/review", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.ReviewAffiliate)
api.Get("/affiliates/settings", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.GetAffiliateSettings)
api.Put("/affiliates/settings", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.UpdateAffiliateSettings)
api.Get("/affiliates/commissions", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.ListAffiliateCommissions)
api.Post("/affiliates/commissions/:id/reverse", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.ReverseAffiliateCommission)
api.Get("/affiliates/payouts", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.ListAffiliatePayouts)
api.Put("/affiliates/payouts/:id/review", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.ReviewAffiliatePayout)
api.Get("/affiliates/events", a.adminAuthMiddleware, a.OnlyAdminAndAbove, h.GetAffiliateEvents)
api.Get("/chapters/:chapterId/quizzes", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), h.ListChapterQuizzes)
api.Post("/chapters/:chapterId/quizzes", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.create"), h.CreateChapterQuiz)
api.Get("/quizzes/:id", a.adminAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), h.RequireChapterQuiz, h.GetChapterQuiz)

View File

@ -6,34 +6,40 @@ import (
)
func (a *App) initClientRoutes(api fiber.Router, h *handlers.Handler) {
api.Get("/affiliates/me", a.clientAuthMiddleware, h.GetAffiliateSelf)
api.Post("/affiliates/apply", a.clientAuthMiddleware, h.ApplyAffiliate)
api.Get("/affiliates/commissions", a.clientAuthMiddleware, h.GetAffiliateCommissions)
api.Get("/affiliates/payouts", a.clientAuthMiddleware, h.GetAffiliatePayouts)
api.Post("/affiliates/payouts", a.clientAuthMiddleware, h.RequestAffiliatePayout)
api.Get("/catalog/courses", h.ListPublicCourses)
api.Get("/catalog/courses/:id", h.GetPublicCourse)
api.Get("/chapters/:chapterId/quizzes", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), a.RequireExamPrepSubscription(), h.ListChapterQuizzes)
api.Get("/quizzes/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), a.RequireExamPrepSubscription(), h.RequireChapterQuiz, h.GetChapterQuiz)
api.Post("/progress/quizzes/:id/complete", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("progress.complete"), a.RequireExamPrepSubscription(), h.RequireChapterQuiz, h.CompleteChapterQuiz)
api.Get("/quizzes/:practiceId/questions", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_set_items.list"), a.RequireExamPrepSubscription(), h.RequireChapterQuiz, h.GetChapterQuizQuestions)
api.Get("/chapters/:chapterId/quizzes", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), a.RequireCoursePurchase(), h.ListChapterQuizzes)
api.Get("/quizzes/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), a.RequireCoursePurchase(), h.RequireChapterQuiz, h.GetChapterQuiz)
api.Post("/progress/quizzes/:id/complete", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("progress.complete"), a.RequireCoursePurchase(), h.RequireChapterQuiz, h.CompleteChapterQuiz)
api.Get("/quizzes/:practiceId/questions", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_set_items.list"), a.RequireCoursePurchase(), h.RequireChapterQuiz, h.GetChapterQuizQuestions)
api.Post("/referrals/code", apiAudience("client"), a.clientAuthMiddleware, h.CreateReferralCode)
api.Get("/referrals/code", apiAudience("client"), a.clientAuthMiddleware, h.GetReferralCode)
api.Get("/referrals/me", apiAudience("client"), a.clientAuthMiddleware, h.GetMyReferrals)
api.Post("/referrals/apply", apiAudience("client"), a.clientAuthMiddleware, h.ApplyReferralCode)
api.Get("/referrals", apiAudience("client"), a.clientAuthMiddleware, h.ListMyReferrals)
api.Get("/referrals/wallet", apiAudience("client"), a.clientAuthMiddleware, h.GetReferralWallet)
api.Post("/courses/:courseId/checkout", apiAudience("client"), a.clientAuthMiddleware, h.CheckoutCourse)
api.Get("/courses", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.list"), h.ListExamPrepCatalogCourses)
api.Get("/courses/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.catalog_courses.get"), h.GetExamPrepCatalogCourseByID)
api.Get("/courses/:courseId/chapters", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.units.list"), h.ListExamPrepUnitsByCatalogCourse)
api.Get("/chapters/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.units.get"), h.GetExamPrepUnitByID)
api.Get("/chapters/:chapterId/lessons", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.lessons.list_by_module"), a.RequireExamPrepSubscription(), h.ResolveChapterLessonContainer, h.ListExamPrepLessonsByUnitModule)
api.Get("/lessons/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.lessons.get"), a.RequireExamPrepSubscription(), h.GetExamPrepLessonByID)
api.Get("/assessments", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_sets.list"), a.RequireExamPrepSubscription(), h.ListExamPrepAssessments)
api.Get("/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list"), a.RequireExamPrepSubscription(), h.ListAllExamPrepPractices)
api.Get("/courses/:courseId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_catalog_course"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByCatalogCourse)
api.Get("/chapters/:chapterId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByUnit)
api.Get("/lessons/:lessonId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_lesson"), a.RequireExamPrepSubscription(), h.ListExamPrepPracticesByLesson)
api.Get("/practices/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), a.RequireExamPrepSubscription(), h.GetExamPrepPracticeByID)
api.Post("/progress/practices/:id/complete", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("progress.complete"), a.RequireExamPrepSubscription(), h.CompletePractice)
api.Post("/videos/engagement/heartbeat", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("videos.track_engagement"), a.RequireExamPrepSubscription(), h.RecordVideoEngagementHeartbeat)
api.Get("/chapters/:chapterId/lessons", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.lessons.list_by_module"), a.RequireCoursePurchase(), h.ResolveChapterLessonContainer, h.ListExamPrepLessonsByUnitModule)
api.Get("/lessons/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.lessons.get"), a.RequireCoursePurchase(), h.GetExamPrepLessonByID)
api.Get("/assessments", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_sets.list"), a.RequireCoursePurchase(), h.ListExamPrepAssessments)
api.Get("/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list"), a.RequireCoursePurchase(), h.ListAllExamPrepPractices)
api.Get("/courses/:courseId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_catalog_course"), a.RequireCoursePurchase(), h.ListExamPrepPracticesByCatalogCourse)
api.Get("/chapters/:chapterId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_unit"), a.RequireCoursePurchase(), h.ListExamPrepPracticesByUnit)
api.Get("/lessons/:lessonId/practices", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.list_by_lesson"), a.RequireCoursePurchase(), h.ListExamPrepPracticesByLesson)
api.Get("/practices/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("exam_prep.practices.get"), a.RequireCoursePurchase(), h.GetExamPrepPracticeByID)
api.Post("/progress/practices/:id/complete", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("progress.complete"), a.RequireCoursePurchase(), h.CompletePractice)
api.Post("/videos/engagement/heartbeat", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("videos.track_engagement"), a.RequireCoursePurchase(), h.RecordVideoEngagementHeartbeat)
api.Get("/progress-summary", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("lms.get_my_progress"), h.GetMyLMSProgressSummary)
api.Get("/practices/:practiceId/questions", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_set_items.list"), a.RequireExamPrepSubscription(), h.GetQuestionsByPractice)
api.Get("/practices/:practiceId/questions", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("question_set_items.list"), a.RequireCoursePurchase(), h.GetQuestionsByPractice)
api.Get("/personas", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("personas.list"), h.ListPersonas)
api.Get("/personas/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("personas.get"), h.GetPersona)
api.Get("/files/url", apiAudience("client"), a.clientAuthMiddleware, h.GetFileURL)
@ -48,26 +54,26 @@ func (a *App) initClientRoutes(api fiber.Router, h *handlers.Handler) {
api.Get("/app/version/check", apiAudience("client"), h.CheckMobileAppVersion)
api.Get("/field-options", apiAudience("client"), h.ListPublicFieldOptions)
api.Get("/field-options/fields", apiAudience("client"), h.ListFieldKeys)
api.Get("/subscription-plans", apiAudience("client"), h.ListSubscriptionPlans)
api.Get("/subscription-plans/:id", apiAudience("client"), h.GetSubscriptionPlan)
api.Post("/subscriptions", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.create"), h.Subscribe)
api.Post("/subscriptions/checkout", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.checkout"), h.SubscribeWithPayment)
api.Post("/subscriptions/request-checkout-link", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.request_checkout_link"), h.RequestSubscriptionCheckoutLink)
api.Get("/subscription-plans", apiAudience("client"), h.RetiredSubscriptionCheckout)
api.Get("/subscription-plans/:id", apiAudience("client"), h.RetiredSubscriptionCheckout)
api.Post("/subscriptions", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.create"), h.RetiredSubscriptionCheckout)
api.Post("/subscriptions/checkout", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.checkout"), h.RetiredSubscriptionCheckout)
api.Post("/subscriptions/request-checkout-link", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.request_checkout_link"), h.RetiredSubscriptionCheckout)
api.Get("/subscriptions/me", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.get_mine"), h.GetMySubscription)
api.Get("/subscriptions/history", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.history"), h.GetMySubscriptionHistory)
api.Get("/subscriptions/status", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.status"), h.CheckSubscriptionStatus)
api.Post("/subscriptions/:id/cancel", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.cancel"), h.CancelSubscription)
api.Put("/subscriptions/:id/auto-renew", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("subscriptions.set_auto_renew"), h.SetAutoRenew)
api.Post("/payments/subscribe", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.initiate"), h.InitiateSubscriptionPayment)
api.Post("/payments/subscribe", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.initiate"), h.RetiredSubscriptionCheckout)
api.Get("/payments/verify/:session_id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.verify"), h.VerifyPayment)
api.Get("/payments", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.list_mine"), h.GetMyPayments)
api.Get("/payments/methods", apiAudience("client"), h.GetChapaPaymentMethods)
api.Get("/payments/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.get"), h.GetPaymentByID)
api.Post("/payments/:id/cancel", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.cancel"), h.CancelPayment)
api.Post("/payments/chapa/direct", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.direct_initiate"), h.InitiateChapaDirectPayment)
api.Post("/payments/chapa/direct", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.direct_initiate"), h.RetiredSubscriptionCheckout)
api.Post("/payments/chapa/direct/authorize", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.direct_verify_otp"), h.AuthorizeChapaDirectPayment)
api.Get("/payments/chapa/direct/methods", apiAudience("client"), h.GetChapaDirectPaymentMethods)
api.Post("/payments/direct", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.direct_initiate"), h.InitiateDirectPayment)
api.Post("/payments/direct", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.direct_initiate"), h.RetiredSubscriptionCheckout)
api.Post("/payments/direct/verify-otp", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("payments.direct_verify_otp"), h.VerifyDirectPaymentOTP)
api.Get("/payments/direct/methods", apiAudience("client"), h.GetDirectPaymentMethods)
api.Post("/auth/google/android", apiAudience("client"), h.GoogleAndroidLogin)

View File

@ -0,0 +1,56 @@
// Optional isolated PostgreSQL/WASM ledger test; see docs/affiliate-program.md.
import { PGlite } from '../tmp/affiliate-db-qa/node_modules/@electric-sql/pglite/dist/index.js';
import { readFile } from 'node:fs/promises';
import assert from 'node:assert/strict';
const db=new PGlite();
await db.exec(`CREATE TABLE users(id BIGSERIAL PRIMARY KEY,role text NOT NULL,status text NOT NULL);CREATE TABLE team_members(id BIGSERIAL PRIMARY KEY);
CREATE SCHEMA exam_prep;CREATE TABLE exam_prep.catalog_courses(id BIGSERIAL PRIMARY KEY);
CREATE TABLE payments(id BIGSERIAL PRIMARY KEY,user_id bigint REFERENCES users(id),course_id bigint REFERENCES exam_prep.catalog_courses(id),plan_id bigint,subscription_id bigint,amount numeric(12,2),currency varchar(3),status text,created_at timestamptz default now());
CREATE TABLE course_purchases(user_id bigint,course_id bigint,payment_id bigint);`);
for(const file of ['000002_referrals.up.sql','000009_affiliate_program.up.sql'])await db.exec(await readFile(`db/migrations/${file}`,'utf8'));
const q=async(sql,args=[]) => (await db.query(sql,args)).rows;
const scalar=async(sql,args=[])=>Object.values((await q(sql,args))[0])[0];
await db.exec(`INSERT INTO users(role,status) VALUES('STUDENT','ACTIVE'),('STUDENT','ACTIVE'),('STUDENT','ACTIVE'),('STUDENT','ACTIVE');INSERT INTO team_members VALUES(1);INSERT INTO exam_prep.catalog_courses VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);`);
assert.equal(Number(await scalar(`SELECT affiliate_apply(1,'I promote makeup artistry courses')`)),1);
await assert.rejects(()=>q(`SELECT affiliate_review(1,'SUSPENDED',1,'Invalid transition')`));
await q(`SELECT affiliate_review(1,'APPROVED',1,'Verified artist')`);
await db.exec(`INSERT INTO referral_codes(user_id,code) VALUES(1,'ABCDEF0123456789');INSERT INTO user_referrals(referrer_id,referred_user_id,referral_code_id) VALUES(1,2,1),(1,3,1),(1,4,1);UPDATE referral_settings SET commission_percent=10,commission_mode='EVERY_COURSE',holding_days=0;`);
const pay=async(course,user=2)=>Number(await scalar(`INSERT INTO payments(user_id,course_id,amount,currency,status) VALUES($1,$2,1000,'ETB','SUCCESS') RETURNING id`,[user,course]));
const count=()=>scalar(`SELECT count(*)::int FROM referral_commissions`);
const generated=await readFile('gen/db/referrals.sql.go','utf8');
const attribution=generated.match(/const ApplyReferralCode = `([\s\S]*?)`/)[1];
const expiry=await scalar('SELECT attributed_until::text FROM user_referrals WHERE referred_user_id=2');
await q(attribution,[2,'ABCDEF0123456789']);await q(attribution,[2,'ABCDEF0123456789']);
assert.equal(await scalar('SELECT attributed_until::text FROM user_referrals WHERE referred_user_id=2'),expiry);
assert.equal(Number(await scalar('SELECT count(*)::int FROM user_referrals WHERE referred_user_id=2')),1);
const p1=await pay(1);assert.equal(await count(),1);
const retry=await q(attribution,[2,'ABCDEF0123456789']);assert.equal(Number(retry[0].applied_count),1);
assert.equal(await scalar('SELECT attributed_until::text FROM user_referrals WHERE referred_user_id=2'),expiry);
await q(`UPDATE payments SET status='SUCCESS' WHERE id=$1`,[p1]);assert.equal(await count(),1);
await pay(1);assert.equal(await count(),1);
const payout1=await scalar(`SELECT affiliate_request_payout(1,'ETB','BANK','Artist','account-123')`);
assert.equal(await scalar(`SELECT amount::text FROM affiliate_payouts WHERE id=$1`,[payout1]),'100.00');
await assert.rejects(()=>q(`SELECT affiliate_request_payout(1,'ETB','BANK','Artist','account-123')`));
await q(`SELECT affiliate_review_payout($1,'PAID',1,'BANK-ONE','External transfer confirmed')`,[payout1]);
await q(`SELECT affiliate_review_payout($1,'PAID',1,'BANK-ONE','Retry confirmation')`,[payout1]);
await pay(2);const payout2=await scalar(`SELECT affiliate_request_payout(1,'ETB','BANK','Artist','account-123')`);
const commission1=await scalar(`SELECT id FROM referral_commissions WHERE payment_id=$1`,[p1]);
await q(`SELECT affiliate_reverse_commission($1,1,'Refund after payout')`,[commission1]);
assert.equal(await scalar(`SELECT status FROM affiliate_payouts WHERE id=$1`,[payout2]),'REJECTED');
await assert.rejects(()=>q(`SELECT affiliate_request_payout(1,'ETB','BANK','Artist','account-123')`));
await pay(3);const payout3=await scalar(`SELECT affiliate_request_payout(1,'ETB','BANK','Artist','account-123')`);
assert.equal(await scalar(`SELECT amount::text FROM affiliate_payouts WHERE id=$1`,[payout3]),'100.00');
await q(`SELECT affiliate_review_payout($1,'PAID',1,'BANK-THREE','External transfer')`,[payout3]);
await db.exec(`UPDATE referral_settings SET holding_days=14;`);const held=await pay(4);
assert.equal(Number(await scalar(`SELECT count(*)::int FROM referral_commissions WHERE payment_id=$1 AND available_at>now()`,[held])),1);
await assert.rejects(()=>q(`SELECT affiliate_request_payout(1,'ETB','BANK','Artist','account-123')`));
await db.exec(`UPDATE referral_settings SET holding_days=0,commission_percent=0;`);const zero=await pay(5);const before=await count();
await db.exec(`UPDATE referral_settings SET commission_percent=10;`);await q(`UPDATE payments SET status='SUCCESS' WHERE id=$1`,[zero]);assert.equal(await count(),before);
await db.exec(`UPDATE user_referrals SET attributed_until=now()-interval '1 day' WHERE referred_user_id=2;`);await pay(6);assert.equal(await count(),before);
await q(`SELECT affiliate_review(1,'SUSPENDED',1,'Fraud investigation')`);await pay(7,3);assert.equal(await count(),before);
await assert.rejects(()=>q(`SELECT affiliate_request_payout(1,'ETB','BANK','Artist','account-123')`));
await q(`SELECT affiliate_review(1,'APPROVED',1,'Investigation resolved')`);
await db.exec(`UPDATE referral_settings SET commission_mode='FIRST_PURCHASE';`);await pay(8,4);const firstCount=await count();await pay(9,4);assert.equal(await count(),firstCount);
const c=await scalar(`SELECT id FROM referral_commissions WHERE payment_id=$1`,[held]);await q(`UPDATE payments SET status='FAILED' WHERE id=$1`,[held]);assert.equal(await scalar(`SELECT reversed_at IS NOT NULL FROM referral_commissions WHERE id=$1`,[c]),true);
console.log('PASS: PostgreSQL migration, approvals, course commissions, retry/zero-rate idempotency, payout reservations, paid reversals/recovery, holds, expiry, suspension, first-purchase policy, and automatic reversals');
await db.close();