66 lines
7.6 KiB
Markdown
66 lines
7.6 KiB
Markdown
# 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.
|