Skip to content

MLM Module (Partners, Referrals, Commissions, Ranks)

Overview

The MLM (Multi-Level Marketing) Module is the core business engine of the IWM Platform. It manages the partner network, referral tracking, commission calculations, rank advancement, and payout processing. This module implements a Differential Commission Model with 7 income types where partners earn commissions based on the difference between their rank rate and their downline's rank rate, with unlimited depth.

Key Features

FeatureDescription
Commission ModelDifferential (not Unilevel)
DepthUnlimited
Income Types7 (3 Active + 3 Passive + 1 Leadership Pool)
Primary CurrencyUSD
Ranks21 (Consultant 0-11 with PRO variants)
Rank MaintenanceNon-expiring (ranks never decrease)

Responsibilities

  • Partner registration and lifecycle management
  • Referral link generation and attribution tracking
  • Network tree structure management (closure table)
  • Rank qualification and progression
  • Commission calculation (differential model)
  • 7 income types processing
  • Leadership pool distribution
  • Balance management (pending, available)
  • Payout request processing

Domain Entities

Partner

The central entity representing an MLM network member.

FieldTypeDescription
idUUIDPartner identifier
user_idUUIDReference to core.users
sponsor_idUUIDDirect upline partner
referral_codeVARCHAR(20)Unique referral code
statusENUMPartner status
current_rank_idUUIDCurrent rank
highest_rank_idUUIDHighest achieved rank (same as current - non-expiring)
direct_referrals_countINTDirect downline count
total_network_sizeINTTotal network size
tree_depthINTDepth in tree from root
total_structure_turnover_usdDECIMALTotal structure turnover in USD
personal_turnover_usdDECIMALPersonal turnover in USD
is_activatedBOOLEANHas made $1,100 personal purchase
joined_atTIMESTAMPRegistration timestamp
activated_atTIMESTAMPRank 1 activation timestamp

PartnerTreePath

Closure table for efficient tree queries (unlimited depth).

FieldTypeDescription
ancestor_idUUIDAncestor partner
descendant_idUUIDDescendant partner
depthINTDistance between nodes

Trackable referral links for attribution.

FieldTypeDescription
idUUIDLink identifier
partner_idUUIDOwning partner
codeVARCHAR(20)Unique link code
nameVARCHAR(100)Link label (Instagram, YouTube)
target_urlVARCHAR(500)Custom landing page
utm_sourceVARCHAR(100)UTM source parameter
utm_mediumVARCHAR(100)UTM medium parameter
utm_campaignVARCHAR(100)UTM campaign parameter
clicks_countINTTotal clicks
registrations_countINTRegistrations from link
conversions_countINTConversions (purchases/investments)
is_activeBOOLEANLink active status
expires_atTIMESTAMPOptional expiration

ReferralAttribution

Tracks referral source for users.

FieldTypeDescription
idUUIDAttribution identifier
user_idUUIDReferred user
partner_idUUIDReferring partner
link_idUUIDSource link (optional)
attribution_typeENUMFIRST_TOUCH or LAST_TOUCH
first_touch_atTIMESTAMPFirst interaction
last_touch_atTIMESTAMPLast interaction
converted_atTIMESTAMPConversion timestamp
cookie_idVARCHAR(100)Tracking cookie ID

Rank

MLM rank definitions (21-tier system).

FieldTypeDescription
idUUIDRank identifier
codeVARCHAR(20)Unique code (0, 1, 2, ..., 11, 4_PRO, ..., 11_PRO)
nameVARCHAR(100)Display name (Consultant 0, Consultant 1, etc.)
levelINTRank level (0-21)
is_proBOOLEANPRO variant flag
turnover_requirement_usdDECIMALTotal structure turnover required
personal_sales_rateDECIMALRate for active income (3%-20%)
entrance_fee_rateDECIMALRate for investment entrance fees (10.5%-20%)
passive_income_rateDECIMALRate for passive income (0%-20%)
leadership_pool_eligibleBOOLEANEligible for leadership pools
descriptionTEXTRank description
badge_urlVARCHAR(500)Rank badge image
color_codeVARCHAR(20)Brand color
is_activeBOOLEANRank available

CommissionTransaction

Individual commission record with income type.

FieldTypeDescription
idUUIDTransaction identifier
partner_idUUIDReceiving partner
income_typeENUM7 income types
source_typeENUMORDER, INVESTMENT, INVESTMENT_PROFIT, POOL_DISTRIBUTION
source_idUUIDSource entity ID
source_partner_idUUIDPartner who triggered this commission
own_rateDECIMALPartner's applicable rate
source_rateDECIMALSource partner's rate
differential_rateDECIMALDifference between rates
gross_amount_usdDECIMALAmount before deductions
net_amount_usdDECIMALFinal amount
currencyVARCHAR(3)Currency (USD)
statusENUMTransaction status
period_idVARCHAR(20)Accounting period
idempotency_keyVARCHAR(255)Duplicate prevention

PartnerBalance

Partner financial state in USD.

FieldTypeDescription
idUUIDBalance identifier
partner_idUUIDPartner reference
available_balance_usdDECIMALWithdrawable amount
pending_balance_usdDECIMALAwaiting holding period
total_earned_usdDECIMALLifetime earnings
total_withdrawn_usdDECIMALLifetime withdrawals
income_personal_sales_usdDECIMALType 1 lifetime earnings
income_team_sales_usdDECIMALType 2 lifetime earnings
income_repeat_sales_usdDECIMALType 3 lifetime earnings
income_portfolio_returns_usdDECIMALType 4 lifetime earnings
income_client_profits_usdDECIMALType 5 lifetime earnings
income_network_profits_usdDECIMALType 6 lifetime earnings
income_leadership_pool_usdDECIMALType 7 lifetime earnings
currencyVARCHAR(3)Balance currency (USD)
versionINTOptimistic lock version
last_calculated_atTIMESTAMPLast commission calculation

LeadershipPool

Leadership pool configuration.

FieldTypeDescription
idUUIDPool identifier
pool_codeVARCHAR(20)Unique code (POOL_5, POOL_6, etc.)
eligible_ranksVARCHAR[]Ranks eligible for this pool
percentage_of_turnoverDECIMALPercentage of company turnover
distribution_frequencyENUMWEEKLY or MONTHLY
qualification_volumesJSONBRequired volumes by rank
is_activeBOOLEANPool active status

PoolDistribution

Record of pool distribution event.

FieldTypeDescription
idUUIDDistribution identifier
pool_idUUIDReference to leadership pool
period_startTIMESTAMPPeriod start date
period_endTIMESTAMPPeriod end date
total_turnover_usdDECIMALTotal company turnover
pool_amount_usdDECIMALTotal pool amount
qualified_participantsINTNumber of qualified partners
per_person_amount_usdDECIMALAmount per participant
statusENUMPROCESSING, DISTRIBUTED
distributed_atTIMESTAMPDistribution completion time

PayoutRequest

Withdrawal request from partner.

FieldTypeDescription
idUUIDRequest identifier
partner_idUUIDRequesting partner
amount_usdDECIMALRequested amount in USD
currencyVARCHAR(3)Currency code
payout_method_typeENUMBANK_CARD, BANK_TRANSFER, CRYPTO, EWALLET
payout_detailsJSONBEncrypted payment info
statusENUMRequest status
rejection_reasonTEXTIf rejected
processed_byUUIDAdmin who processed
external_referenceVARCHAR(255)Payment provider reference

Partner Lifecycle

Registration Flow

Partner Status Flow

Rank 0 to Rank 1 Activation

The transition from Rank 0 to Rank 1 unlocks the full marketing plan:

RequirementDetails
Personal PurchaseMinimum $1,100 personal purchase
Qualifying ProductsSi14 AG shares OR any investment product
UnlocksFull marketing plan with all 7 income types

Referral System

Partners can create multiple referral links for different channels:

UTM Parameter Tracking

Links support full UTM tracking:

ParameterExamplePurpose
utm_sourceinstagramTraffic source
utm_mediumsocialMarketing medium
utm_campaignsummer_2024Campaign identifier

Attribution Rules:

  • Cookie lifetime: 30 days
  • Attribution type: Last-touch (most recent referrer wins)
  • Override: New referral link click updates attribution
  • Persistence: Attribution locked at conversion (purchase/investment)

Tree Structure

Closure Table Pattern (Unlimited Depth)

The partner network uses a closure table for efficient hierarchical queries with unlimited depth:

Key Queries

Get Direct Referrals (Level 1):

sql
SELECT descendant_id FROM partner_tree_paths
WHERE ancestor_id = :partner_id AND depth = 1

Get Full Downline (Unlimited Depth):

sql
SELECT descendant_id, depth FROM partner_tree_paths
WHERE ancestor_id = :partner_id AND depth > 0
ORDER BY depth

Get Upline Chain (For Differential Commission):

sql
SELECT
    p.id as partner_id,
    p.status,
    r.code as rank_code,
    r.personal_sales_rate,
    r.passive_income_rate,
    r.entrance_fee_rate,
    ptp.depth
FROM partner_tree_paths ptp
JOIN partners p ON p.id = ptp.ancestor_id
JOIN ranks r ON r.id = p.current_rank_id
WHERE ptp.descendant_id = :partner_id AND ptp.depth >= 1
ORDER BY ptp.depth ASC

Rank System

21-Tier Rank Hierarchy

Commission Rates by Rank

RankTurnover ($)Personal SalesEntrance FeePassive Income
003%10.5%0%
11,1005%11%5%
210,0008%11.5%8%
350,00010%12%10%
4100,00012%12.5%12%
4_PRO200,00013%13%13%
5400,00014%13.5%14%
5_PRO700,00015%14%15%
61,000,00016%14.5%16%
6_PRO1,500,00016.5%15%16.5%
72,000,00017%15.5%17%
7_PRO3,000,00017.5%16%17.5%
85,000,00018%16.5%18%
8_PRO7,000,00018.5%17%18.5%
910,000,00019%17.5%19%
9_PRO15,000,00019.25%18%19.25%
1025,000,00019.5%18.5%19.5%
10_PRO50,000,00019.75%19%19.75%
11100,000,00020%19.5%20%
11_PRO800,000,00020%20%20%

Rank Qualification Rules

RuleDescription
Automatic AdvancementRanks increase immediately when turnover threshold is met
Non-ExpiringOnce achieved, ranks never expire or decrease
No MaintenanceNo monthly maintenance requirements
Instant BenefitsCommission rates apply immediately upon rank change

Rank 0 vs Rank 1+

CapabilityRank 0Rank 1+
Referral LinkYesYes
Personal Sales Commission3%5%-20%
Team Sales (Differential)NoYes
Passive IncomeNoYes
Leadership PoolsNoRank 5+

The 7 Income Types

Overview

Active Income (Types 1-3)

TypeNameTriggerCalculation
1Personal SalesDirect sale to own clientpersonal_rate × amount
2Team SalesDownline partner makes saleDifferential on sale amount
3Repeat SalesExisting client repurchasesSame as Personal Sales

Passive Income (Types 4-6)

TypeNameTriggerCalculation
4Portfolio ReturnsOwn investment generates profitStrategy-specific returns
5Client ProfitsPersonal client earns profitpassive_rate × client_profit
6Network ProfitsDownline's client earns profitDifferential on profit amount

Leadership Income (Type 7)

TypeNameTriggerCalculation
7Leadership PoolWeekly/Monthly distributionEqual share among qualified

Commission Calculation

Differential Commission Model

The core formula for Team Sales and Network Profits:

IF consultant_rank > source_partner_rank:
    commission = (consultant_rate - source_rate) × amount
ELSE:
    commission = 0  // No commission when rank is equal or lower

Differential Calculation Flow

Commission Example

Scenario: Partner at Rank 2 (8% rate) makes a $10,000 sale

Upline PartnerRankRateDifferentialCommission
Source Partner28%N/A (Personal Sales)$800
Direct Sponsor412%12% - 8% = 4%$400
Level 2514%14% - 12% = 2%$200
Level 3616%16% - 14% = 2%$200
Level 4616%16% - 16% = 0%$0
Level 51120%20% - 16% = 4%$400
Level 6+AnyAnyAll remaining$0 (max rate reached)

Total distributed: $800 + $400 + $200 + $200 + $400 = $2,000 (20% of sale)

Commission Triggers

TriggerSource TypeIncome Types
Order CompletedORDERPersonal Sales, Team Sales, Repeat Sales
Investment ActivatedINVESTMENTPersonal Sales (entrance fee), Team Sales
Investment ProfitINVESTMENT_PROFITClient Profits, Network Profits
Pool DistributionPOOL_DISTRIBUTIONLeadership Pool

Commission Status Flow

StatusDescriptionBalance Impact
PENDINGCalculated, awaiting holding period+pending_balance
APPROVEDHolding period completepending → available
PAIDIn partner's available balanceAlready in available
REVERSEDOrder refunded before payout-pending_balance
CLAWBACKOrder refunded after payout-available_balance

Leadership Pools

Pool Configuration

PoolEligible Ranks% of TurnoverFrequencyQualification
POOL_55, 5_PRO1%Weekly$5,000 / $10,000 weekly volume
POOL_66, 6_PRO0.5%Weekly$20,000 / $30,000 weekly volume
POOL_77, 7_PRO0.5%Weekly$45,000 / $60,000 weekly volume
POOL_88, 8_PRO0.5%Weekly$90,000 / $120,000 weekly volume
POOL_99, 9_PRO1%MonthlyRank achievement only
POOL_1010, 10_PRO1%MonthlyRank achievement only
POOL_1111, 11_PRO1%MonthlyRank achievement only

Note: Pools 9-11 do not require separate volume qualification. Partners who achieve and maintain these ranks automatically participate in monthly distribution. The rank's turnover requirement ($10M-$800M) serves as the qualification threshold.

50% Branch Rule (Pools 5-8 only)

No single branch (direct downline leg) can contribute more than 50% of qualification volume:

Example:
- Required qualification: $10,000
- Branch A volume: $80,000 → counts as max $5,000 (50% cap)
- Branch B volume: $15,000 → counts as $5,000+ (remainder needed)
- Result: Qualified (diverse structure)

Distribution Process


Balance Management

Balance Types

Pending Period by Source

Source TypePending PeriodReason
Product Order14 daysRefund/return window
Investment7 daysFund verification
Passive Income7 daysProfit confirmation
Leadership Pool0 daysImmediate upon distribution

Income Breakdown

Balance tracks earnings by income type:

FieldIncome Type
income_personal_sales_usdType 1: Personal Sales
income_team_sales_usdType 2: Team Sales
income_repeat_sales_usdType 3: Repeat Sales
income_portfolio_returns_usdType 4: Portfolio Returns
income_client_profits_usdType 5: Client Profits
income_network_profits_usdType 6: Network Profits
income_leadership_pool_usdType 7: Leadership Pool

Concurrency Safety

Balance operations use optimistic locking with version numbers:

typescript
// Example: Update balance with version check
const result = await tx.partnerBalance.update({
  where: {
    partnerId: partner.id,
    version: expectedVersion,
  },
  data: {
    pendingBalanceUsd: { increment: amount },
    version: { increment: 1 },
    updatedAt: new Date(),
  },
});

Payout System

Payout Request Flow

Payout Rules

  1. Minimum Amount: $100 USD minimum withdrawal
  2. Single Pending: Only one pending payout per partner
  3. KYC Required: STANDARD KYC level required
  4. Balance Deduction: Amount deducted immediately on request
  5. Failure Refund: Balance restored if payment fails
  6. Partner Status: Must be ACTIVE to request payout

Payout Methods

MethodProviderProcessing Time
Bank CardStripe/YooKassa1-3 business days
Bank TransferManual3-5 business days
CryptoVariousSame day
E-WalletVariousSame day

Events Published

EventTriggerPayload
PartnerRegisteredNew partner createdpartnerId, userId, sponsorId
PartnerActivated$1,100 purchase (Rank 0→1)partnerId, activationType
PartnerStatusChangedStatus transitionpartnerId, fromStatus, toStatus
ReferralLinkCreatedNew link createdlinkId, partnerId, code
ReferralLinkClickedLink visitedlinkId, partnerId, visitorInfo
ReferralAttributedUser attributed to partneruserId, partnerId, linkId
CommissionCalculatedCommission createdtransactionId, partnerId, incomeType, amount
CommissionApprovedHolding period completetransactionId, partnerId, amount
CommissionPaidCommission moved to availabletransactionId, partnerId, amount
CommissionReversedCommission reversedtransactionId, partnerId, reason
BalanceUpdatedBalance changedpartnerId, type, amount, newBalance
PayoutRequestedPayout submittedpayoutId, partnerId, amount
PayoutApprovedPayout approvedpayoutId, partnerId
PayoutCompletedPayout processedpayoutId, partnerId, reference
PayoutRejectedPayout rejectedpayoutId, partnerId, reason
RankChangedRank promotionpartnerId, fromRank, toRank
PoolDistributedLeadership pool paidpoolId, amount, participants

Events Consumed

EventSourceHandler
UserRegisteredCoreCreate partner if referral code present
OrderCompletedCommerceCalculate Personal/Team/Repeat Sales
OrderRefundedCommerceReverse commissions
InvestmentActivatedInvestmentCalculate entrance fee commissions
InvestmentProfitDistributedInvestmentCalculate Client/Network Profits

Business Rules and Invariants

Partner Rules

  1. One partner per user (1:1 relationship)
  2. Partner cannot sponsor themselves
  3. Sponsor cannot be changed after registration
  4. Only ACTIVE partners earn commissions
  5. TERMINATED partners cannot be reactivated
  6. All partners start at Rank 0

Commission Rules

  1. Commissions calculated only for ACTIVE upline partners
  2. Unlimited depth for differential commissions
  3. Differential stops when rate reaches 20%
  4. Idempotency key prevents duplicate commissions
  5. Reversed/cancelled source reverses all related commissions
  6. Leadership pool distributions are immediate (no pending period)

Rank Rules

  1. Ranks are non-expiring (never decrease)
  2. Rank advancement is automatic upon meeting turnover threshold
  3. Rank 0→1 requires $1,100 personal purchase
  4. All subsequent ranks qualify on Total Structure Turnover
  5. Commission rates apply immediately upon rank change

Balance Rules

  1. Available balance cannot be negative
  2. Pending balance cannot be negative
  3. Version must match for update (optimistic locking)
  4. Total earned >= total withdrawn + available + pending

Payout Rules

  1. Only one pending/processing payout per partner
  2. Minimum withdrawal: $100 USD
  3. KYC verification required
  4. Partner must be ACTIVE to request payout

Integration Points

Provides to Other Modules

InterfaceConsumersPurpose
IPartnerLookupServiceCommerce, InvestmentGet partner by referral code
ICommissionServiceCommerce, InvestmentTrigger commission calculation
IAttributionServiceCommerce, InvestmentGet referral attribution for user
IPassiveIncomeServiceInvestmentTrigger client/network profit calculations

Consumes from Other Modules

InterfaceProviderPurpose
IUserLookupServiceCoreGet user profile data
IKycStatusServiceCoreCheck KYC level for payouts
IInvestmentProfitServiceInvestmentGet profit data for passive income