RezinaLMS-BackEnd/scripts/affiliate-ledger-test.mjs

57 lines
6.2 KiB
JavaScript

// 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();