Skip to content

Development Progress

Current Status: Week 8 - Investment Backend | Target: 12-week implementation

Track our progress as we build the IWM Platform - an MLM platform with investment marketplace, product marketplace, and administrative panel.


Milestone Checklist

Week 1: Architecture & Project Setup

  • ✅ Initialize Turborepo monorepo with pnpm workspaces
  • ✅ Configure TypeScript, ESLint, Prettier
  • ✅ Setup Docker Compose (PostgreSQL, Redis)
  • ✅ Configure GitHub Actions CI pipeline
  • ✅ Complete Prisma schema with all 25+ tables
  • ✅ Create initial database migration
  • ✅ Seed ranks (20 ranks) and leadership pools (7 pools)
  • ✅ Scaffold all NestJS modules
  • ✅ Create single React app with domain-aware routing
  • ✅ Configure Tailwind CSS and React Router
  • ✅ Setup shared packages (shared-types, shared-utils, ui-components)

Week 2-3: Basic Infrastructure

  • ✅ JWT authentication with refresh tokens
  • ✅ Password hashing and session management
  • ✅ Email verification and password reset flows
  • ✅ TOTP 2FA implementation
  • ✅ User profile CRUD and avatar upload
  • ✅ Sumsub KYC SDK integration
  • ✅ KYC webhook handler and status tracking
  • ✅ Auth frontend (login, register, forgot password) - with i18n and platform theming
  • ✅ OAuth authentication (Google, Yandex, Mail.ru) - optional providers with graceful fallback
  • ✅ Profile and KYC wizard UI
  • ✅ Referral attribution infrastructure (cookies, tracking, backend service)
  • ✅ Geo-detection service (IP-based region detection: EU/US/APAC)
  • ✅ Region confirmation modal UI
  • ✅ Regional subdomain routing (eu.iwm.com, us.iwm.com, apac.iwm.com)
  • ✅ Cross-domain session sharing (JWT cookies on regional domain)
  • ✅ SSO redirect flow between platforms (region redirector, mismatch modal)
  • ✅ KYC Hub architecture (external provider integration, level mapping)
  • ✅ KYC status propagation across platforms in region (shared database, useKycStatus hook)

Week 4-5: MLM Core

  • ✅ Partner entity with sponsor relationship
  • ✅ Closure table implementation for tree structure
  • ✅ Efficient tree traversal queries
  • ✅ 21-rank system with requirements and rates
  • ✅ Automatic rank advancement logic
  • ⬜ Instant partner activation on partner domain login
  • ⬜ Partner widget in user profile (mini stats, referral link)
  • ⬜ Partner domain routing (partner.region.iwm.com)
  • ✅ Partner activation event triggers for commissions
  • ✅ Referral links CRUD with UTM support
  • ✅ QR code generation for links
  • ✅ Partner dashboard UI (stats, charts) - 8 pages, 10 components
  • ✅ Interactive team tree visualization
  • ✅ Referral links management UI
  • ✅ Frontend hooks (usePartner, useRank, useReferralLinks, useTeamTree)
  • ✅ MLM API client with typed endpoints

Week 6: Commission Engine - Active Income

  • ✅ Commission transaction entity and recording
  • ✅ TYPE_1: Personal sales calculator
  • ✅ TYPE_2: Team sales differential calculator
  • ✅ TYPE_3: Repeat sales calculator
  • ✅ Entrance fee commission distribution
  • ✅ Balance management (credit/debit/pending)
  • ✅ Commission queueing with pg-boss
  • ✅ Idempotency pattern for commission distribution
  • ✅ Commission history and breakdown queries
  • ✅ 30-day pending period with maturation job

Week 7: Passive Income + Pools + Design Phase 1

  • ⬜ TYPE_4: Portfolio returns calculator (not commission - partner's own investment returns)
  • ✅ TYPE_5: Client profits calculator
  • ✅ TYPE_6: Network profits differential calculator
  • ✅ Leadership pools configuration (7 pools with qualification thresholds)
  • ✅ 50% branch rule implementation
  • ✅ Weekly/monthly pool distribution jobs (pg-boss cron)
  • ✅ Payout request and approval workflow
  • ⬜ Extract design tokens from Figma
  • ⬜ Style all primitive components
  • ⬜ Build design system foundation

Week 8: Investment Backend + Design Phase 2

  • ✅ Investment strategies entity and CRUD (StrategyService, StrategyController, StrategyRepository)
  • ✅ External provider aggregator architecture (all strategies external, webhook-first event pipeline)
  • ✅ Investment creation via provider webhooks (WebhookProcessorService, InvestmentService)
  • ✅ Webhook event audit log (WebhookEventLog model, HMAC signature verification guard)
  • ✅ Commission triggers on investment events (InvestmentCreatedEvent, InvestmentProfitDistributedEvent)
  • ✅ External provider SSO token generation (ProviderSsoService, JWT with 5min expiry)
  • ✅ Provider redirect service (auto-login to external platforms via signed JWT)
  • ✅ Bi-directional KYC sync webhooks (Provider → IWM via kyc.synced event)
  • ✅ KYC sync background jobs (IWM → Provider via pg-boss every 6 hours)
  • ✅ External provider status tracking (ExternalProvider with apiBaseUrl, ssoAudience)
  • ✅ Portfolio summary and investment history endpoints (InvestmentController)
  • ✅ Idempotent webhook processing (externalEventId uniqueness per provider)
  • ⬜ Apply design to all auth pages
  • ⬜ Apply design to profile/KYC pages
  • ⬜ Apply design to MLM dashboard
  • ⬜ Apply design to commission/payout pages

Week 9: Investment Frontend

  • ⬜ Finalize profit distribution jobs
  • ⬜ External provider redirect UI flow
  • ⬜ Provider connection status in portfolio
  • ✅ Strategy catalog with filters
  • ✅ Strategy detail page with risk indicators + external provider banner
  • ✅ 6-step participation wizard UI
  • ✅ Portfolio overview with profit charts
  • ✅ Investment detail and transaction history
  • ✅ Withdrawal request functionality

Week 10: Product Marketplace

  • ⬜ Product categories (hierarchical)
  • ⬜ Product entity with images and attributes
  • ⬜ Full-text product search
  • ⬜ Cart operations (add, update, remove)
  • ⬜ Checkout session and order creation
  • ⬜ Order status flow and tracking
  • ⬜ Commerce commission triggers
  • ✅ Product catalog frontend - 12 pages, 9 components
  • ✅ Cart and checkout UI - 4-step wizard
  • ✅ Order history and tracking

Week 11: Admin Panel & Integrations

  • ⬜ Admin role-based access control
  • ⬜ User and partner management
  • ⬜ KYC review workflow interface
  • ⬜ Commission management and adjustments
  • ⬜ Payout approval workflow
  • ⬜ Payment provider abstraction layer
  • ⬜ Notification system (email, in-app)
  • ⬜ Analytics event tracking
  • ✅ Admin dashboard with reports - 8 pages, 9 components
  • ⬜ System settings management

Week 12: Testing & Launch

  • ⬜ Unit tests for commission engine
  • ⬜ Unit tests for rank system
  • ⬜ Integration tests for auth flows
  • ⬜ Integration tests for investment wizard
  • ⬜ Integration tests for checkout
  • ⬜ E2E test suite for critical paths
  • ⬜ Security audit (OWASP Top 10)
  • ⬜ Performance testing (API < 200ms p95)
  • ✅ Production deployment (Caddy reverse proxy + PM2)
  • ⬜ Monitoring and alerting setup

Changelog

Development updates will be logged here as work progresses.

2026-02-13 (Week 8 - Investment Backend)

  • Completed: External Provider Aggregator Architecture
    • All investment strategies are external (managed by third-party providers)
    • Webhook-first event pipeline: raw events stored in WebhookEventLog, then processed
    • HMAC-SHA256 signature verification on all incoming webhooks (WebhookHmacGuard)
    • Idempotent webhook processing via @@unique([providerId, externalEventId])
  • Completed: Investment Module (39 files, clean architecture)
    • Domain: 4 entities, 4 repository interfaces, 3 events, 4 exceptions
    • Infrastructure: 4 Prisma repository implementations, 1 HMAC guard
    • Application: 5 services (Strategy, Investment, ProviderSSO, WebhookProcessor, KycSync), 4 DTO files, 1 pg-boss job
    • Presentation: 3 controllers (Strategy, Investment, Webhook)
    • Module wired with all DI tokens and exports
  • Completed: External Provider SSO
    • JWT token generation with per-provider signing keys (env vars)
    • Token payload: userId, email, fullName, kycStatus, kycLevel, strategyCode
    • 5-minute expiry, configurable audience per provider
    • Redirect URL construction with token and strategy code
  • Completed: Webhook Processing Pipeline
    • 5 event types: investment.created, profit.distributed, investment.updated, investment.withdrawn, kyc.synced
    • investment.created → creates Investment + DEPOSIT transaction → emits InvestmentCreatedEvent (triggers commissions)
    • profit.distributed → creates PROFIT transaction → emits InvestmentProfitDistributedEvent (triggers Type 5/6)
    • investment.withdrawn → creates WITHDRAWAL transaction → updates status
    • kyc.synced → logs provider KYC data for admin review
  • Completed: KYC Sync (IWM → Provider)
    • pg-boss job runs every 6 hours
    • Pushes KYC data to providers via HMAC-signed POST requests
    • Only syncs users who have investments with the target provider
  • Completed: Portfolio & Strategy Endpoints
    • GET /investment/strategies — list with filters (category, risk, status, search)
    • GET /investment/strategies/:id — detail with provider info
    • GET /investment/strategies/categories — enum values
    • GET /investment/portfolio — aggregated summary (invested, profit, withdrawn, current value)
    • GET /investment/participations — user's investments
    • GET /investment/participations/:id — detail with transaction history
    • POST /investment/strategies/:id/sso-redirect — generate SSO redirect URL
    • POST /investment/webhooks/:providerCode — webhook ingestion endpoint
  • Schema: Added WebhookEventLog model, WebhookEventStatus enum, extended ExternalProvider (apiBaseUrl, ssoAudience), extended Investment (externalInvestmentId with unique constraint)
  • Schema: Added KYC_SYNC_PUSH to pg-boss JobType enum

2026-02-12 (Week 7 - Passive Income & Payouts)

  • Completed: Passive Income Commission Types
    • TYPE_3 (Repeat Sales): Detects existing purchases, mirrors TYPE_1 rates with REPEAT_SALES income type
    • TYPE_5 (Client Profits): Sponsor earns passiveIncomeRate on referred client's investment profit
    • TYPE_6 (Network Profits Differential): Upline traversal with passiveIncomeRate differential (skip-on-zero logic)
    • InvestmentProfitDistributedEvent handler for passive commission triggers
  • Completed: Leadership Pool Distribution (TYPE_7)
    • Pool distribution repository with raw SQL for turnover and branch volume calculations
    • 50% branch rule: No single branch contributes >50% of qualifying volume
    • Weekly (Mon 00:00 UTC) and Monthly (1st 00:00 UTC) pg-boss scheduled jobs
    • PRO vs base rank threshold qualification
    • Equal split among qualified partners, immediate balance credit (no 30-day pending)
    • Idempotent distribution with period-based duplicate prevention
  • Completed: Payout Module
    • Domain: PayoutRequestEntity with state machine (canCancel, canApprove, canReject, canProcess, canComplete, canAdminCancel)
    • Domain: PayoutMethodEntity, PayoutValidationException
    • Repositories: IPayoutRequestRepository, IPayoutMethodRepository with Prisma implementations
    • PayoutService: Create/cancel requests, admin approve/reject/process/complete/cancel with balance debit/refund
    • PayoutController: 13 endpoints (methods CRUD, requests lifecycle, admin workflow)
    • PayoutModule registered in AppModule with MlmModule and CommissionModule integration
  • Schema: Added qualification volume thresholds to LeadershipPool (qualificationVolumeUsd, qualificationVolumeProUsd)

2026-02-11 (Week 6 - Commission Engine)

  • Completed: Commission Engine - Active Income (Types 1-2)
    • Schema: Added idempotencyKey to CommissionTransaction for duplicate prevention
    • Schema: Added composite index [status, createdAt] for maturation query optimization
    • Jobs Module: pg-boss@9.0.3 integration with typed job service and cron scheduling
    • Commission Domain: CommissionEntity, events (CommissionCalculated, CommissionMatured)
    • Repository Interfaces: ICommissionRepository, IBalanceRepository with atomic operations
    • Repository Implementations: Upsert patterns, atomic balance updates, groupBy queries
    • Balance Service: Credit pending, mature commissions, withdrawal with validation
    • Commission Calculator: TYPE_1 (Personal Sales), TYPE_2 (Team Sales Differential)
    • Event Handlers: InvestmentCreatedHandler, OrderPaidHandler with @OnEvent decorators
    • Maturation Job: Daily pg-boss job for 30-day pending period with batch processing
    • Commission Controller: History, summary, balance endpoints with full Swagger docs
    • Commission Module: Full wiring with MlmModule integration
    • Dependencies: pg-boss@9.0.3, date-fns@4.1.0
  • Code Quality: Comprehensive fixes applied
    • Race conditions: Replaced check-then-create with atomic upsert operations
    • Idempotency: Unique constraint error handling instead of TOCTOU pattern
    • Transaction boundaries: Wrapped balance+status updates in $transaction
    • Negative balance protection: Atomic updateMany with balance validation
    • Event precision: Changed amount from number to string for Decimal safety
    • Query optimization: Parallelized summary queries with Promise.all
    • Worker cleanup: Proper OnModuleDestroy with offWork() unsubscription
    • Error handling: Contextual pg-boss startup errors, handler try-catch
    • DTO validation: Removed defaults, added @Max(100) limit, Swagger decorators
    • Module encapsulation: Removed raw PG_BOSS export, only PgBossService exposed
  • Note: TYPE_3 (Repeat Sales) deferred to Week 7 as planned

2026-02-11 (Week 4-5 - MLM Core)

  • Completed: MLM Core Backend Infrastructure
    • Domain entities: PartnerEntity, RankEntity, ReferralLinkEntity
    • Domain events: PartnerActivatedEvent, PartnerRankChangedEvent
    • Repository interfaces and implementations for Partner, Rank, ReferralLink
    • PartnerTreeRepository with closure table for efficient tree traversal
    • PartnerService: create, activate, network stats, upline/downline queries
    • ReferralLinkService: CRUD, QR code generation with qrcode library
    • RankService: rank advancement logic, progress calculation, requirement checking
    • DTOs: Partner, ReferralLink, Rank with full Swagger documentation
    • Controllers: PartnerController, ReferralLinkController, RankController
    • MlmModule updated with all new providers and exports
  • Completed: Frontend MLM Integration
    • mlmApi.ts: typed API client for Partner, ReferralLinks, Ranks endpoints
    • usePartner hook: partner profile, stats, create/activate
    • useReferralLinks hook: CRUD operations, QR code fetching
    • useRank hook: rank data, progress, advancement checking
    • useTeamTree hook: downline tree, upline chain, direct team
  • Added: qrcode and @types/qrcode dependencies
  • Week 4-5 MLM Core: Backend COMPLETE (remaining: partner domain routing, profile widget)

2026-02-10

  • Completed: Regional Subdomain Routing
    • Backend: region extractor utility for parsing region from hostname
    • Backend: CookieAuthService for regional JWT cookie management
    • Backend: JWT strategy updated to read from cookies with header fallback
    • Backend: Auth controller sets cookies on login/register/refresh
    • Frontend: regionRedirector service for platform-first subdomain routing
    • Frontend: useRegionRedirect hook for automatic region detection and redirect
  • Completed: Cross-Domain Session Sharing
    • JWT cookies set on regional domain (.eu.iwm.com) for SSO within region
    • Home region cookie on root domain for cross-region detection
    • Cookies support: HttpOnly, Secure, SameSite=Lax
  • Completed: SSO Redirect Flow
    • Frontend: RegionMismatchModal for cross-region access notification
    • Frontend: useRegionMismatch hook for detecting home vs current region
    • i18n: region mismatch translations (EN/RU)
  • Completed: KYC Status Propagation
    • Frontend: useKycStatus hook for fetching and caching KYC status
    • Frontend: KYC_REQUIREMENTS config for platform-specific KYC levels
    • Shared database ensures instant KYC status consistency across platforms
  • Week 2-3 Basic Infrastructure: COMPLETE

2026-02-08

  • Completed: Referral Attribution Infrastructure
    • Frontend: attribution cookies, cookie utils, attribution service
    • Frontend: useReferralAttribution and useRegistrationAttribution hooks
    • Backend: attribution DTOs, service, controller in MLM module
    • Integration: RegisterPage captures attribution data on signup
  • Completed: Geo-Detection & Regional SSO Foundation
    • Frontend: geo detection service with country-to-region mapping
    • Frontend: useGeoDetection hook with confirmation state
    • Frontend: RegionConfirmModal component
    • i18n: geo translations (EN/RU)
  • Completed: KYC Hub Architecture
    • Domain events: KycStatusChangedEvent
    • Exceptions: KycRequiredException, KycUpgradeRequiredException
    • Guards: KycGuard with @RequireKyc decorator
    • External provider integration: DTOs, level mapping service, controller
    • KYC service: event emission, updateFromExternalProvider method
  • Extended: Week 2-3 (Basic Infrastructure)
    • Geo-detection and region confirmation
    • Regional subdomain routing (EU/US/APAC)
    • Cross-domain SSO within region
    • KYC Hub architecture (Invest as central verification)
  • Extended: Week 4-5 (MLM Core)
    • Instant partner activation on partner domain login
    • Partner widget in user profile
    • Partner domain routing
  • Extended: Week 8-9 (Investment)
    • External provider deep SSO integration
    • Bi-directional KYC sync (IWM ↔ Provider)
    • Provider redirect flow with auto-login

2026-02-02

  • Completed: i18n foundation with react-i18next (EN/RU translations, language detection)
  • Completed: Platform theme system with domain-based theming
  • Completed: Landing page with platform cards (shop, invest, partner, admin)
  • Completed: Platform-specific auth layouts with theming
  • Completed: Investment module external provider integration
  • Completed: API service layer foundation (apiClient, authApi)
  • Completed: OAuth authentication (Google, Yandex, Mail.ru)
    • NestJS Passport strategies with optional provider pattern
    • OAuth-enabled guards (503 response when provider not configured)
    • Frontend SocialLoginButtons component with i18n
    • OAuthCallbackPage for token handling
    • Prisma schema: AuthProvider enum, oauthId field, unique constraint
  • Completed: Production deployment to *.iwm-platform.octosparrow.space
    • Caddy reverse proxy configuration
    • PM2 process management
    • OAuth callback URLs configured for production
  • Files: i18n/, config/platformTheme.ts, modules/landing/, layouts/auth/, services/api/, modules/auth/infrastructure/strategies/, modules/auth/presentation/guards/, modules/auth/components/SocialLoginButtons.tsx

2026-01-31

  • Completed: Full Prisma schema with 25+ models across 4 schemas (core, mlm, investment, commerce)
  • Completed: Database seeding for 20 ranks and 7 leadership pools
  • Completed: Documentation updates for referral tracking at User level and regional fields
  • Completed: JWT authentication with refresh tokens and session management
  • Completed: Email verification and password reset flows with SendGrid integration
  • Completed: TOTP 2FA implementation (generate secret, enable, disable)
  • Completed: User profile CRUD and avatar upload with validation
  • Files: prisma/schema.prisma, prisma/seed.ts, auth module, email module, users module, two-factor service

Last updated: 2026-02-13 (Week 8 Investment Backend: External provider aggregator, JWT SSO, HMAC webhooks, KYC sync, portfolio endpoints)