# BoonTrack Atlas — System Architecture

## Overview
BoonTrack Atlas employs a decoupled, stateless, event-driven architecture designed for high availability, sub-second latency, and deterministic execution across multi-tenant commerce operations. The platform serves as the unified operating engine for Unified Commerce Engine, multi-tenant order orchestration, and server-side marketing attribution.

---

## 1. High-Level Platform Topology

```mermaid
flowchart TD
    subgraph Clients_Layer ["Traffic & Interaction Channels"]
        Shopper["Shopper / Web Client"]
        Merchant["Merchant / Operator"]
        CreatorNode["Creator / Affiliate"]
        WhatsAppUser["WhatsApp User / Buyer"]
    end

    subgraph Edge_Layer ["Edge Infrastructure (Cloudflare Anycast)"]
        CF["Cloudflare Edge (WAF, SSL Termination, Asset Caching)"]
    end

    subgraph Presentation_Layer ["Decoupled Presentation Layer"]
        Storefront["Sub-Second Storefronts (Next.js SSR/SSG)"]
        Backoffice["Merchant Dashboard & Management Portal"]
    end

    subgraph Unified_Engine ["The Unified Engine (BoonTrack Atlas Core)"]
        FastAPI["Stateless Core Engine (FastAPI Containers)"]
        FSM["Enterprise State Machine (Deterministic FSM)"]
        Outbox["Transactional Outbox & Event Dispatcher"]
    end

    subgraph Integrated_Pillars ["4 Integrated Digital Pillars"]
        PillarShop["Shop: Instant Sub-Second Transactions & Catalogs"]
        PillarDashboard["Dashboard: Multi-Tenant Ops, POS & CS Escalation"]
        PillarStudio["Studio: High-Converting Video & Live Commerce"]
        PillarCreator["Creator: Monetization, Bio Links & Membership"]
    end

    subgraph Queue_State_Layer ["Asynchronous Messaging & State"]
        Redis[("Redis 7+ (Streams, Distributed Lock, Session State)")]
        Workers["Background Task Workers (Async Outbox Consumers)"]
    end

    subgraph Persistence_Layer ["Relational Persistence"]
        PG[("PostgreSQL 16 (Logical Multi-Tenant Isolation)")]
    end

    subgraph External_Rails ["External Commerce & Messaging Rails"]
        WA["Official Meta WhatsApp Cloud API (Zero-Scraping Policy)"]
        CAPI["Meta Conversions API (Server-Side CAPI)"]
        PGW["Payment Rails (Native Dynamic QRIS Engine)"]
    end

    Shopper -->|HTTPS| CF
    Merchant -->|HTTPS| CF
    CreatorNode -->|HTTPS| CF
    WhatsAppUser -->|Encrypted Webhook| CF

    CF --> Storefront
    CF --> Backoffice
    Storefront -->|REST API| FastAPI
    Backoffice -->|REST API| FastAPI
    CF -->|Webhook Ingestion| FastAPI

    FastAPI --- FSM
    FastAPI --- Outbox
    FastAPI --- Integrated_Pillars

    FastAPI -->|Enqueue Tasks| Redis
    Redis --> Workers
    FastAPI -->|ACID Transactions| PG
    Workers -->|State Reconciliation| PG

    Workers -->|Official Graph API| WA
    Workers -->|Server Events| CAPI
    FastAPI -->|Dynamic QRIS Generation| PGW
```

---

## 2. Core Architectural Tenets (BoonTrack Atlas)

### 2.1 The Unified Engine & The 4 Integrated Pillars
BoonTrack operates a single, cohesive engine that interconnects four digital pillars without data silos:
- **BoonTrack Shop**: Instant, sub-second headless storefronts for physical and digital products, with automated shipping rate calculation, real-time inventory locking, and instant dynamic QRIS generation.
- **BoonTrack Dashboard**: Centralized operational management and real-time customer service (CS) escalation. Provides merchants with single-pane-of-glass order processing, automated notifications, and multi-branch isolation.
- **BoonTrack Studio**: Creative production facility and live commerce broadcasting, engineered for high-converting marketing campaigns and media production.
- **Creator Ecosystem**: Comprehensive monetization infrastructure featuring custom link-in-bio storefronts, digital asset delivery, and automated membership management via WhatsApp.

All four pillars share the same transaction ledger, catalog definitions, and customer profile records, ensuring zero inconsistency between channels.

### 2.2 Unified Commerce Engine (Pre-built API Integration Layer)
BoonTrack is a Meta Tech Provider specializing in enterprise WhatsApp Business Cloud API orchestration:
- **Strict Zero-Scraping Policy**: Operates exclusively through Meta's official WhatsApp Business Cloud API. The platform enforces an absolute ban on unofficial web scrapers, reverse-engineered clients, or headless browser automation, guaranteeing complete immunity from WhatsApp business number bans.
- **High-Throughput Webhook Processing**: Idempotent webhook processing utilizing message ID (`wamid`) tracking in high-speed in-memory caches to eliminate duplicate executions during network retries.
- **Enterprise SLA & Compliance**: End-to-end encrypted message delivery, automated template management, and compliance with Meta's developer standards and terms of service.

### 2.3 Enterprise State Machine & Deterministic Consistency
Every transaction within the BoonTrack ecosystem is managed by an Enterprise State Machine (Finite State Machine / FSM):
- **Deterministic Status Transitions**: Transaction states follow a strict, non-reversible state graph (`CREATED` &rarr; `PAYMENT_PENDING` &rarr; `PAID` &rarr; `PROCESSING` &rarr; `COMPLETED` / `EXPIRED` / `CANCELLED`), precluding race conditions and intermediate corrupted states.
- **Transactional Outbox Pattern**: Order state changes and external notification events are committed in a single atomic database transaction. Background workers process pending outbox events using concurrency locks, guaranteeing that customers and merchants receive notifications only after payment is irreversibly verified.
- **Commercial Transparency**: Complete audit trail logging for every transition, providing full accountability for payments, status changes, and logistics updates.

---

## 3. Layer Breakdown

### 3.1 Stateless Backend Engine (FastAPI)
- **Containerized Stateless Execution**: Independent container nodes handling incoming REST requests and webhooks with horizontal scaling capabilities.
- **Asynchronous Non-Blocking I/O**: High-throughput I/O powered by Python's `asyncio` event loop.
- **Strict Schema Validation**: Request and response integrity enforced by `Pydantic v2` with automated OpenAPI 3.1 contract compliance.
- **Logical Tenant Isolation**: Tenant context dynamically resolved and injected into every execution context, preventing cross-tenant data leakage.

### 3.2 Decoupled Sub-Second Storefronts (Next.js)
- **Headless Storefronts**: Independent deployment cycle from core business APIs.
- **Edge Performance**: Server Components and Edge Caching achieve sub-second TTFB and lightning-fast checkout experiences for mobile buyers.

### 3.3 Dynamic QRIS & Payment Rails
- **Adapter-Based Orchestration**: Pluggable payment rails generating native, unique dynamic QRIS codes per transaction.
- **Reconciliation Engine**: Background cron workers reconcile payment statuses and automatically expire stale QRIS codes within deterministic TTL windows.

### 3.4 Server-Side Attribution (Meta CAPI)
- **High Event Match Quality (EMQ)**: Direct server-to-server Conversions API dispatch with SHA-256 customer data normalization.
- **Event Deduplication**: Deduplication across browser Pixel events and server events using deterministic `event_id` keys.

### 3.5 Zero-Trust Security & Identity Isolation
- **Zero-Trust Identity Validation**: All client requests are authenticated against a single source of truth; unauthenticated role claims are strictly disregarded.
- **Cryptographic Credential Protection**: Passwords and sensitive merchant credentials are irreversibly hashed and protected against public exposure.
- **Concurrent Task Locking**: Event consumption is protected with distributed concurrency locks, preventing duplicate event handling.
