> ## Documentation Index
> Fetch the complete documentation index at: https://kb.manage.management/llms.txt
> Use this file to discover all available pages before exploring further.

# MRI Integration Architecture

> Technical architecture and data flow diagrams for the MRI integration

## System Overview

The MRI integration connects Manage.Management with MRI's property management software through the MRI MIX API, enabling bi-directional data synchronization with enterprise-grade security.

### High-Level Architecture

```mermaid theme={null}
graph TB
    subgraph "Manage.Management"
        A[React Frontend]
        B[Supabase Edge Functions]
        C[MRI Service]
        D[MRI Sync Service]
        E[(Supabase Database)]
        F[Supabase Vault]
    end
    
    subgraph "MRI"
        G[MRI MIX API]
        H[MRI System]
    end
    
    A -->|HTTPS| B
    B -->|Encrypted| F
    B -->|Query| E
    C -->|HTTPS Basic Auth| G
    D -->|Scheduled Sync| C
    C -->|Store Data| E
    G <-->|Data Exchange| H
    
    style F fill:#f9f,stroke:#333,stroke-width:2px
    style G fill:#bbf,stroke:#333,stroke-width:2px
```

## Authentication Flow

### HTTP Basic Auth over HTTPS

```mermaid theme={null}
sequenceDiagram
    participant Director as Building Director
    participant Frontend as React App
    participant Backend as Supabase
    participant Vault as Supabase Vault
    participant MRI as MRI MIX API

    Director->>Frontend: Enter MIX API Credentials
    Frontend->>Backend: Store Credentials (HTTPS)
    Backend->>Vault: Encrypt & Store All Credentials
    Vault-->>Backend: Confirmation
    Backend-->>Frontend: Success

    Note over Backend,MRI: When Sync Starts

    Backend->>Vault: Retrieve Credentials
    Vault-->>Backend: Decrypted Credentials
    Backend->>Backend: Build Basic Auth Header

    loop Every API Call
        Backend->>MRI: API Request + Basic Auth Header
        Note right of Backend: Authorization: Basic base64(clientId:password)<br/>X-MRI-Database: dbName<br/>X-MRI-User: userName
        MRI-->>Backend: Data Response
    end
```

### Security Highlights

<CardGroup cols={2}>
  <Card title="Credential Encryption" icon="lock">
    Client secrets encrypted with AES-256-GCM in Supabase Vault
  </Card>

  <Card title="Token Management" icon="key">
    Short-lived tokens (1 hour) with automatic refresh
  </Card>

  <Card title="TLS 1.3" icon="shield">
    All communications encrypted in transit
  </Card>

  <Card title="Audit Logging" icon="file-text">
    Every credential access logged with IP and timestamp
  </Card>
</CardGroup>

## Data Synchronization Flow

### Sync Process

```mermaid theme={null}
graph LR
    A[Scheduled Trigger] --> B{Sync Enabled?}
    B -->|No| C[Skip]
    B -->|Yes| D[Authenticate]
    D --> E[Fetch from MRI]
    E --> F{Data Changed?}
    F -->|No| G[Skip Update]
    F -->|Yes| H{Conflict?}
    H -->|No| I[Update Database]
    H -->|Yes| J[Apply Resolution Strategy]
    J --> I
    I --> K[Log to Audit]
    K --> L[Update Sync Status]
```

### Entity Sync Order

Data is synchronized in a specific order to maintain referential integrity:

```mermaid theme={null}
graph TD
    A[1. Properties] --> B[2. Units]
    B --> C[3. Tenancies]
    C --> D[4. Contacts]
    D --> E[5. Transactions]
    E --> F[6. Budgets]
    F --> G[7. Invoices]
    G --> H[8. Maintenance]
    H --> I[9. Documents]
    
    style A fill:#e1f5e1
    style I fill:#e1f5e1
```

<Info>
  Properties must sync first as they're the foundation for all other entities. Documents sync last as they depend on all other data.
</Info>

## Data Flow Diagram

### Complete Data Journey

```mermaid theme={null}
graph TB
    subgraph "MRI"
        MRI[MRI Database]
    end
    
    subgraph "MRI MIX API Layer"
        API[REST API Endpoints]
    end
    
    subgraph "Manage.Management Backend"
        Auth[Auth Service]
        Sync[Sync Service]
        Queue[Rate Limit Queue]
        Transform[Data Transformer]
    end
    
    subgraph "Database Layer"
        RLS[Row Level Security]
        Tables[(MRI Tables)]
        Audit[(Audit Logs)]
    end
    
    subgraph "Frontend"
        UI[React Components]
        Dashboard[MRI Dashboard]
    end
    
    MRI --> API
    API -->|HTTPS Basic Auth| Auth
    Auth --> Sync
    Sync --> Queue
    Queue --> Transform
    Transform --> RLS
    RLS --> Tables
    Transform --> Audit
    Tables --> UI
    Tables --> Dashboard
    
    style Auth fill:#ffe6e6
    style RLS fill:#e6f3ff
    style Audit fill:#fff4e6
```

## Security Architecture

### Defense in Depth

```mermaid theme={null}
graph TB
    subgraph "Layer 1: Application Security"
        A1[HTTP Basic Auth over HTTPS]
        A2[Role-Based Access Control]
    end
    
    subgraph "Layer 2: Transport Security"
        B1[TLS 1.3 Encryption]
        B2[Certificate Pinning]
    end
    
    subgraph "Layer 3: Data Security"
        C1[AES-256 Encryption at Rest]
        C2[Supabase Vault for Secrets]
    end
    
    subgraph "Layer 4: Database Security"
        D1[Row Level Security Policies]
        D2[Building-Scoped Access]
    end
    
    subgraph "Layer 5: Monitoring"
        E1[Comprehensive Audit Logging]
        E2[Real-time Alerting]
    end
    
    A1 --> B1
    A2 --> B2
    B1 --> C1
    B2 --> C2
    C1 --> D1
    C2 --> D2
    D1 --> E1
    D2 --> E2
```

### Credential Storage Architecture

```mermaid theme={null}
graph LR
    subgraph "Building Director Actions"
        A[Enter Credentials]
    end

    subgraph "Frontend (Browser)"
        B[React Form]
        C[HTTPS Request]
    end

    subgraph "Backend (Supabase)"
        D[Edge Function]
        E[Encryption Service]
        F[Vault Storage]
        G[Audit Logger]
    end

    subgraph "Database"
        H[(mri_credentials_secure)]
        I[(mri_audit_log)]
    end

    A --> B
    B --> C
    C --> D
    D --> E
    E --> F
    F --> H
    D --> G
    G --> I

    style F fill:#f9f,stroke:#333,stroke-width:3px
    style H fill:#e1f5e1
    style I fill:#fff4e6
```

**Key Points:**

* ✅ Credentials **never** stored in plain text
* ✅ Encryption happens **before** database storage
* ✅ Every access is **logged** with user ID and IP
* ✅ Only **building directors** can access credentials
* ✅ Vault uses **automatic key rotation**

## Rate Limiting & Performance

### Request Queue Management

```mermaid theme={null}
graph TB
    A[API Request] --> B{Rate Limit Check}
    B -->|Under Limit| C[Execute Immediately]
    B -->|Over Limit| D[Add to Queue]
    D --> E[Wait for Slot]
    E --> F{Retry Count < 3?}
    F -->|Yes| G[Exponential Backoff]
    G --> H[Retry Request]
    F -->|No| I[Log Error & Fail]
    H --> J{Success?}
    J -->|Yes| K[Return Data]
    J -->|No| F
    C --> K

    style D fill:#ffe6e6
    style G fill:#fff4e6
    style K fill:#e1f5e1
```

### Rate Limits

| Limit Type     | Threshold      | Action                    |
| -------------- | -------------- | ------------------------- |
| **Per Minute** | 60 requests    | Queue additional requests |
| **Per Hour**   | 1,000 requests | Queue and delay           |
| **Burst**      | 10 concurrent  | Throttle new requests     |
| **Timeout**    | 30 seconds     | Fail and retry            |

## Database Schema

### MRI Integration Tables

```mermaid theme={null}
erDiagram
    buildings ||--o{ mri_credentials_secure : has
    buildings ||--o{ mri_properties : syncs
    mri_properties ||--o{ mri_units : contains
    mri_properties ||--o{ mri_tenancies : has
    mri_properties ||--o{ mri_contacts : manages
    mri_properties ||--o{ mri_transactions : records
    mri_properties ||--o{ mri_budgets : plans
    mri_properties ||--o{ mri_invoices : receives
    mri_properties ||--o{ mri_maintenance : tracks
    mri_properties ||--o{ mri_documents : stores

    buildings ||--o{ mri_sync_configs : configures
    buildings ||--o{ mri_sync_status : monitors
    buildings ||--o{ mri_audit_log : logs

    mri_credentials_secure {
        uuid id PK
        uuid building_id FK
        text client_id
        uuid client_secret_vault_id
        text api_base_url
        text environment
        boolean is_active
        timestamptz last_rotated_at
    }

    mri_properties {
        uuid id PK
        uuid building_id FK
        text mri_property_id
        text name
        text address
        jsonb metadata
        timestamptz synced_at
    }

    mri_sync_configs {
        uuid id PK
        uuid building_id FK
        jsonb sync_frequencies
        text conflict_resolution
        boolean is_enabled
    }

    mri_audit_log {
        uuid id PK
        uuid building_id FK
        text table_name
        text action
        uuid changed_by FK
        inet ip_address
        text user_agent
        jsonb old_values
        jsonb new_values
        timestamptz created_at
    }
```

### Row Level Security (RLS)

All MRI tables have RLS policies enforcing:

1. **Building Scoping** - Users only see data for their buildings
2. **Role-Based Access** - Directors have full access, homeowners read-only
3. **Credential Protection** - Only directors can access credentials
4. **Audit Immutability** - Audit logs are append-only

## Error Handling & Resilience

### Retry Strategy

```mermaid theme={null}
graph LR
    A[Request Fails] --> B{Error Type?}
    B -->|Network| C[Retry Immediately]
    B -->|Rate Limit| D[Wait & Retry]
    B -->|Auth| E[Re-authenticate]
    B -->|Server Error| F[Exponential Backoff]

    C --> G{Attempt < 3?}
    D --> G
    E --> G
    F --> G

    G -->|Yes| H[Retry with Delay]
    G -->|No| I[Log Error & Alert]

    H --> J{Success?}
    J -->|Yes| K[Continue]
    J -->|No| A

    style I fill:#ffe6e6
    style K fill:#e1f5e1
```

### Error Categories

| Error Type          | HTTP Code | Action              | Retry      |
| ------------------- | --------- | ------------------- | ---------- |
| **Network Timeout** | -         | Immediate retry     | Yes (3x)   |
| **Rate Limited**    | 429       | Queue & wait        | Yes (auto) |
| **Unauthorized**    | 401       | Re-authenticate     | Yes (1x)   |
| **Forbidden**       | 403       | Log & alert         | No         |
| **Not Found**       | 404       | Skip record         | No         |
| **Server Error**    | 500-599   | Exponential backoff | Yes (3x)   |
| **Bad Request**     | 400       | Log & skip          | No         |

## Monitoring & Observability

### Metrics Tracked

```mermaid theme={null}
graph TB
    subgraph "Performance Metrics"
        A[Sync Duration]
        B[API Response Time]
        C[Records Processed/sec]
    end

    subgraph "Health Metrics"
        D[Success Rate]
        E[Error Rate]
        F[Authentication Failures]
    end

    subgraph "Business Metrics"
        G[Records Synced]
        H[Data Freshness]
        I[Conflict Rate]
    end

    subgraph "Security Metrics"
        J[Credential Access Count]
        K[Failed Auth Attempts]
        L[Unusual Activity Alerts]
    end

    A --> M[Dashboard]
    B --> M
    C --> M
    D --> M
    E --> M
    F --> M
    G --> M
    H --> M
    I --> M
    J --> N[Security Dashboard]
    K --> N
    L --> N
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Setup Guide" icon="gear" href="/integrations/mri-qube-setup">
    Configure the integration step-by-step
  </Card>

  <Card title="Security Guide" icon="shield" href="/integrations/mri-qube-security">
    Learn about security measures
  </Card>

  <Card title="API Reference" icon="code" href="/integrations/mri-qube-api">
    Technical API documentation
  </Card>

  <Card title="FAQ" icon="circle-question" href="/integrations/mri-qube-faq">
    Common questions and troubleshooting
  </Card>
</CardGroup>
