Skip to content

Data Flow Architecture

Complete Data Movement Between Components and Firebase

graph TB
    subgraph Browser["🌐 Browser / Web App"]
        UI["React Components<br/>- WalletPage<br/>- AdminDashboard<br/>- MobileWalletPage"]
        Auth["Firebase Auth<br/>- signIn()<br/>- getIdToken()"]
        SDK["Firebase SDK<br/>- getAuth()<br/>- getFirestore()"]
    end

    subgraph Network["🔗 Network Layer"]
        HTTPS["HTTPS / WebSocket<br/>Encrypted Channel"]
    end

    subgraph Backend["☁️ Firebase Backend"]
        AuthServ["Firebase Authentication<br/>- JWT Token validation<br/>- Custom Claims (role)"]
        Functions["Cloud Functions<br/>Node.js Runtime<br/>- issueGiftCard()<br/>- redeemValue()<br/>- claimCode()<br/>- QR handlers"]
        AdminSDK["Firebase Admin SDK<br/>- Full Firestore access<br/>- Auth management"]
    end

    subgraph Database["💾 Cloud Firestore"]
        Users["📋 users/{userId}"]
        Products["📦 products/{productId}"]
        Wallet["🎁 wallet_items/{walletItemId}"]
        Ledger["📊 ledger_transactions/{txId}"]
        Projections["💹 wallet_projections/{userId}"]
        Claims["🔐 giftcard_claims/{claimId}"]
        Redemptions["✅ redemptions/{redemptionId}"]
        AuditLog["📝 admin_audit_log/{auditId}"]
        ExternalLinks["🔗 external_identity_links/{linkId}"]
        Config["⚙️ configuration/{docId}"]
    end

    subgraph Storage["🖼️ Cloud Storage"]
        Photos["📸 Photos<br/>/{userId}/{photoId}.jpg"]
        QRCodes["📲 QR Codes<br/>/{walletItemId}/qr.png"]
    end

    %% FRONTEND TO BACKEND
    UI -->|1. User Action| Auth
    Auth -->|2. signIn with<br/>credentials| AuthServ
    AuthServ -->|3. Issue JWT +<br/>Custom Claims| Auth
    UI -->|4. Call Function<br/>+ JWT Token| HTTPS
    HTTPS -->|5. Encrypted Request| Functions

    %% FUNCTION OPERATIONS
    Functions -->|6a. Verify JWT| AuthServ
    Functions -->|6b. Check Custom<br/>Claims for role| AuthServ
    AuthServ -->|7. Confirm Auth +<br/>Claims| Functions

    %% FUNCTION TO FIRESTORE - CREATE WALLET ITEM
    Functions -->|8a. Fetch product| AdminSDK
    AdminSDK -->|9a. Query| Products
    Products -->|10a. Return product<br/>data| AdminSDK
    AdminSDK -->|11a. Return to function| Functions

    Functions -->|8b. Create wallet<br/>item| AdminSDK
    AdminSDK -->|9b. Write| Wallet
    Wallet -->|10b. Confirm write<br/>+ snapshot| AdminSDK
    AdminSDK -->|11b. walletItemId| Functions

    %% FUNCTION TO FIRESTORE - CREATE LEDGER
    Functions -->|12. Create ledger<br/>transaction| AdminSDK
    AdminSDK -->|13. Write| Ledger
    Ledger -->|14. Confirm| AdminSDK

    %% FUNCTION TO FIRESTORE - UPDATE PROJECTION
    Functions -->|15. Update<br/>projection| AdminSDK
    AdminSDK -->|16. Read current| Projections
    Projections -->|17. Return| AdminSDK
    AdminSDK -->|18. Recalculate<br/>balance| Functions
    Functions -->|19. Write updated| AdminSDK
    AdminSDK -->|20. Confirm| Projections

    %% FUNCTION RESPONSE
    Functions -->|21. Return result<br/>success=true| HTTPS
    HTTPS -->|22. Encrypted<br/>Response| UI
    UI -->|23. Update local<br/>state + display| SDK
    SDK -->|24. Listen to<br/>real-time changes| HTTPS
    HTTPS -->|25. Subscribe to<br/>Firestore| AdminSDK
    AdminSDK -->|26. Observe| Wallet
    Wallet -->|27. Emit on_snapshot<br/>event| AdminSDK
    AdminSDK -->|28. Stream changes| HTTPS
    HTTPS -->|29. Real-time update<br/>to UI| UI

    %% PHOTO & GPS FLOW
    UI -->|30. Capture<br/>GPS + Photo| Photos
    UI -->|31. Upload<br/>to Storage| Storage
    Storage -->|32. Store in<br/>Cloud Storage| QRCodes
    Functions -->|33. Reference<br/>in transaction| Redemptions
    Redemptions -->|34. Link to<br/>wallet item| Wallet

    %% QR CODE FLOW
    Functions -->|35. Generate QR<br/>from walletItemId| Functions
    Functions -->|36. Upload<br/>QR image| Storage
    Storage -->|37. Store QR| QRCodes
    Functions -->|38. Store QR URL<br/>in wallet_item| Wallet
    UI -->|39. Download &<br/>display QR| Storage

    %% AUDIT & SECURITY
    Functions -->|40. Create audit<br/>entry| AdminSDK
    AdminSDK -->|41. Write| AuditLog
    AuditLog -->|42. Immutable<br/>record| Database

    %% EXTERNAL INTEGRATION
    Functions -->|43. Link external<br/>account| AdminSDK
    AdminSDK -->|44. Create/Update| ExternalLinks
    ExternalLinks -->|45. Link to user| Users

    style Browser fill:#e3f2fd,stroke:#1976d2
    style Network fill:#f3e5f5,stroke:#7b1fa2
    style Backend fill:#e8f5e9,stroke:#388e3c
    style Database fill:#fff3e0,stroke:#f57c00
    style Storage fill:#fce4ec,stroke:#c2185b
    style Auth fill:#e0f2f1,stroke:#00897b
    style SDK fill:#f1f8e9,stroke:#558b2f
    style HTTPS fill:#ede7f6,stroke:#512da8

Data Flow Sequences

🔐 Authentication Flow

User Input (Credentials)
    ↓
Firebase Auth.signIn()
    ↓
JWT Token + Custom Claims
    ↓
Store in Client Memory
    ↓
Attach to Function Calls

🎁 Issue Giftcard Flow

UI: AdminDashboard (Wallet Management)
    
Data: {productId, targetUserId, claimCode, idempotencyKey}
    
Function: issueGiftCard()
    
Step 1: Verify JWT + Check role=ADMIN
Step 2: Acquire idempotency lock
Step 3: Fetch product details
Step 4: Create wallet_items document
Step 5: Create ledger_transactions (ISSUE)
Step 6: Update wallet_projections
Step 7: Store idempotency result
    
Return: {walletItemId, ledgerTxId, success}
    
UI: Display in WalletItemsList

✅ Redeem Value Flow

UI: WalletPage / Mobile (User redeems)
    
Data: {walletItemId, amount, location?, photos?}
    
Function: redeemValue()
    
Step 1: Verify JWT (current user)
Step 2: Fetch wallet_items (validate ownership)
Step 3: Check status=ACTIVE, amount  available
Step 4: Upload photos to Cloud Storage (if provided)
Step 5: Create redemptions document
Step 6: Create ledger_transactions (REDEEM)
Step 7: Update wallet_item (usedAmount)
Step 8: Update wallet_projections
Step 9: Create audit_log entry
    
Return: {redemptionId, remainingBalance}
    
UI: Show success + updated balance
    
Real-time Listener: wallet_items changes

📲 QR Scanning Flow

UI: Mobile Scanner (Camera)
    
Extract: walletItemId from QR
    
Function: lookupQRCode()
    
Step 1: Query wallet_items by QR hash
Step 2: Verify status=ACTIVE
Step 3: Fetch product details
Step 4: Return: item details + owner info
    
UI: Display giftcard details
    
User Action: Confirm redemption
    
Function: redeemValue() (from QR scan)

📸 GPS & Photo Capture Flow

Browser: Geolocation API
    
Get: {latitude, longitude, accuracy}
    
Browser: Camera/Photo Input
    
User: Select/Take photo
    
File: Blob/File object
    
Compress & Prepare Upload
    
Cloud Storage Upload
    
Get: downloadURL
    
Create Redemption Document:
{
  redemptionId,
  walletItemId,
  userId,
  amount,
  location: {lat, lng},
  photoUrl: "gs://bucket/path/photo.jpg",
  timestamp
}
    
Firestore: redemptions/{redemptionId}

🔄 Real-time Synchronization

Frontend subscribes:
    onSnapshot(walletItemsQuery)
    ↓
Backend: Any wallet_item change
    ↓
Firestore: Emits change event
    ↓
Frontend: Receives via WebSocket
    ↓
Update UI state + re-render

Collection Dependencies

users/{userId}
    
wallet_items/{walletItemId} [userId reference]
    
ledger_transactions/{txId} [userId, walletItemId reference]
    
redemptions/{redemptionId} [userId, walletItemId reference]

admin_audit_log/{auditId} [userId, targetUserId, resourceId]
external_identity_links/{linkId} [userId reference]
wallet_projections/{userId} [derived from ledger_transactions]
giftcard_claims/{claimId} [userId, walletItemId reference]

Security & Validation Points

Layer Check Method
Network HTTPS TLS 1.3
Auth JWT validity Firebase Auth
Auth Role check Custom Claims
DB Firestore Rules Read/Write filters by role
Function Input validation Schema validation
Function Idempotency Unique key lock
DB Audit Trail Immutable ledger