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 unilevel compensation structure where partners earn commissions from their direct referrals and their downline network.

Responsibilities

  • Partner registration and lifecycle management
  • Referral link generation and attribution tracking
  • Network tree structure management (closure table)
  • Rank qualification and progression
  • Commission calculation and 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
direct_referrals_countINTDirect downline count
total_network_sizeINTTotal network size
tree_depthINTDepth in tree from root
joined_atTIMESTAMPRegistration timestamp
activated_atTIMESTAMPFirst qualifying action

PartnerTreePath

Closure table for efficient tree queries.

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.

FieldTypeDescription
idUUIDRank identifier
nameVARCHAR(100)Display name
codeVARCHAR(50)Unique code
levelINTRank level (1 = lowest)
descriptionTEXTRank description
badge_urlVARCHAR(500)Rank badge image
color_codeVARCHAR(20)Brand color
is_activeBOOLEANRank available

CommissionPlan

Commission calculation rules.

FieldTypeDescription
idUUIDPlan identifier
nameVARCHAR(100)Plan name
codeVARCHAR(50)Unique code
source_typeENUMINVESTMENT, PRODUCT, ALL
max_levelsINTMaximum depth for commissions
is_activeBOOLEANPlan active
valid_fromTIMESTAMPEffective start
valid_toTIMESTAMPEffective end

CommissionTransaction

Individual commission record.

FieldTypeDescription
idUUIDTransaction identifier
partner_idUUIDReceiving partner
source_typeENUMORDER, INVESTMENT, BONUS, RANK_BONUS
source_idUUIDSource entity ID
source_partner_idUUIDPartner who generated
level_depthINTNetwork level
plan_idUUIDApplied commission plan
gross_amountDECIMALAmount before deductions
net_amountDECIMALFinal amount
career_pointsDECIMALPoints earned
statusENUMTransaction status
period_idVARCHAR(20)Accounting period
idempotency_keyVARCHAR(255)Duplicate prevention

PartnerBalance

Partner financial state.

FieldTypeDescription
idUUIDBalance identifier
partner_idUUIDPartner reference
available_balanceDECIMALWithdrawable amount
pending_balanceDECIMALAwaiting approval
total_earnedDECIMALLifetime earnings
total_withdrawnDECIMALLifetime withdrawals
career_points_totalDECIMALLifetime points
career_points_periodDECIMALCurrent period points
currencyVARCHAR(3)Balance currency
versionINTOptimistic lock version

PayoutRequest

Withdrawal request from partner.

FieldTypeDescription
idUUIDRequest identifier
partner_idUUIDRequesting partner
amountDECIMALRequested amount
currencyVARCHAR(3)Currency code
payout_method_typeENUMBANK_CARD, BANK_TRANSFER, 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

Activation Criteria

A partner is activated (PENDING -> ACTIVE) upon:

  • First product purchase (minimum order value)
  • First investment participation
  • Manual admin activation

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

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

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:

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

Get Upline Chain:

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

Get Network at Specific Levels (for commissions):

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

Rank System

Rank Hierarchy

Qualification Rules

Ranks have multiple requirement types:

Requirement TypeDescription
CAREER_POINTS_TOTALLifetime career points
CAREER_POINTS_PERIODPoints in current period
PERSONAL_VOLUMEPersonal purchases/investments
GROUP_VOLUMETotal network volume
DIRECT_REFERRALSNumber of direct recruits
ACTIVE_REFERRALSActive direct recruits
TEAM_SIZETotal network size
REFERRALS_AT_RANKDirect referrals at specific rank

Qualification Example (Gold Rank)

RequirementThresholdPeriod
Career Points50,000LIFETIME
Personal Volume10,000 RUBMONTHLY
Group Volume100,000 RUBMONTHLY
Direct Referrals10LIFETIME
Active Referrals5MONTHLY

Rank Maintenance

  • Ranks must be maintained monthly
  • Failure to meet requirements results in demotion
  • Highest achieved rank preserved for benefits calculation
  • Grace period: 1 month warning before demotion

Rank Benefits

RankCommission BonusExclusive Benefits
Bronze+2% on levels 1-3Basic training access
Silver+3% on levels 1-5Monthly webinars
Gold+5% on all levelsQuarterly events
Platinum+7% on all levelsAnnual retreat
Diamond+10% on all levelsLeadership council

Commission Calculation

Unilevel Model

Commissions flow up the network from the source partner:

Commission Tiers

LevelBase PercentageWith Gold Rank
15%10%
23%6%
32%4%
41%2%
5-100.5%1%

Calculation Flow

Commission Triggers

TriggerSource TypeDescription
Order CompletedORDERProduct purchase delivered
Investment ActivatedINVESTMENTInvestment participation funded
Rank AchievementRANK_BONUSOne-time rank promotion bonus
Period BonusBONUSMonthly/quarterly performance bonus

Commission Status Flow


Balance Management

Balance Types

Pending vs Available

BalanceDescriptionCan Withdraw
PendingCommissions awaiting approvalNo
AvailableApproved, withdrawableYes

Holds

Commissions can be placed on hold for:

  • Fraud investigation
  • Dispute resolution
  • Compliance review

Concurrency Safety

Balance operations use optimistic locking with version numbers:

typescript
// Example: Withdraw from balance
const result = await updateBalanceOptimistic(
  partnerId,
  amount,
  'WITHDRAW',
  expectedVersion
);

if (!result.success) {
  if (result.error_message.includes('Version mismatch')) {
    // Retry with fresh version
  }
}

Payout System

Payout Request Flow

Payout Rules

  1. Minimum Amount: 100 RUB 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

Payout Methods

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

Approval Workflow


Events Published

EventTriggerPayload
PartnerRegisteredNew partner createdpartnerId, userId, sponsorId
PartnerActivatedFirst qualifying actionpartnerId, activationType
PartnerStatusChangedStatus transitionpartnerId, fromStatus, toStatus
ReferralLinkCreatedNew link createdlinkId, partnerId, code
ReferralLinkClickedLink visitedlinkId, partnerId, visitorInfo
ReferralAttributedUser attributed to partneruserId, partnerId, linkId
CommissionCalculatedCommission createdtransactionId, partnerId, amount
CommissionApprovedCommission approvedtransactionId, 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 promotion/demotionpartnerId, fromRank, toRank, type
RankAchievedNew highest rankpartnerId, rankId, isFirst

Events Consumed

EventSourceHandler
UserRegisteredCoreCreate partner if referral code present
OrderCompletedCommerceCalculate commissions
OrderRefundedCommerceReverse commissions
InvestmentActivatedInvestmentCalculate commissions
InvestmentWithdrawnInvestmentHandle early withdrawal penalties

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

Commission Rules

  1. Commissions calculated only for ACTIVE upline partners
  2. Maximum 10 levels of commission depth
  3. Idempotency key prevents duplicate commissions
  4. Commissions require admin approval (configurable threshold)
  5. Reversed/cancelled source reverses all related commissions

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 amount enforced
  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

Consumes from Other Modules

InterfaceProviderPurpose
IUserLookupServiceCoreGet user profile data
IKycStatusServiceCoreCheck KYC level for payouts