# C4 Model - Royalty Accounting System

This document demonstrates the C4 model for the Royalty Accounting System using Structurizr DSL. The C4 model provides a hierarchical view of software architecture at different levels of abstraction.

## What is the C4 Model?

The C4 model consists of four levels:
- **Level 1: System Context** - Shows how the system fits into the world
- **Level 2: Container** - Shows the high-level technical building blocks
- **Level 3: Component** - Shows components within a container
- **Level 4: Code** - Shows how components are implemented (optional)

Note: we typically do not create Level 4 diagrams as they are too detailed for most architecture documentation.

## Complete Royalty Accounting System

This example shows all four C4 levels for the royalty accounting system.

```structurizr
workspace "Royalty Accounting System" {
    model {
        # People
        user = person "User" "A business user who uses the royalty accounting system"
        
        # External Systems
        dsp = softwareSystem "Digital Service Providers" "Spotify, Apple Music, YouTube, etc." "External"
        
        # Main Enterprise Systems
        royaltyAccounting = softwareSystem "Royalty Accounting" "Manages royalty calculations and payments" {
            # Containers within Royalty Accounting
            abacus = container "ABACUS" "Core royalty calculation engine" "Application" {
                # Components within ABACUS
                frontendRoyalties = component "Frontend Royalties" "User interface for royalty management" "React"
                graphqlApi = component "GraphQL API" "Provides data access via GraphQL" "Node.js/Apollo"
                database = component "Database" "Stores royalty data" "PostgreSQL"
                dagOrchestrator = component "DAG Orchestrator" "Orchestrates data processing workflows" "Apache Airflow"
                lambdaFunctions = component "AWS Lambda Functions" "Serverless compute functions" "Python/Node.js"
            }
            
            ca = container "Customer Accounting (CA)" "Manages customer-specific accounting" "Application"
            tap = container "Taxes & Payments (TAP)" "Handles tax calculations and payments" "Application"
            collabs = container "Collaborators" "Manages collaborator splits and payments" "Application"
        }
        
        content = softwareSystem "Content" "Manages music catalog and metadata"
        insights = softwareSystem "Insights" "Provides analytics and reporting"
        
        # System Context relationships
        user -> royaltyAccounting "Uses to manage royalties"
        royaltyAccounting -> content "Retrieves catalog data from"
        royaltyAccounting -> insights "Sends metrics to"
        dsp -> royaltyAccounting "Sends sales data to"
        
        # Container relationships
        abacus -> ca "Sends accounting data to"
        abacus -> tap "Sends payment data to"
        abacus -> collabs "Sends split data to"
        
        # Component relationships within ABACUS
        user -> frontendRoyalties "Uses"
        frontendRoyalties -> graphqlApi "Makes API calls to" "HTTPS/GraphQL"
        graphqlApi -> database "Reads from and writes to" "SQL"
        graphqlApi -> dagOrchestrator "Triggers DAG runs"
        graphqlApi -> lambdaFunctions "Invokes functions"
        dagOrchestrator -> database "Reads from and writes to" "SQL"
        dagOrchestrator -> lambdaFunctions "Triggers functions"
        lambdaFunctions -> database "Reads from and writes to" "SQL"
    }
    
    views {
        # Level 1: System Context
        systemContext royaltyAccounting "SystemContext" {
            include *
            autoLayout
            title "System Context - Royalty Accounting System"
            description "Shows how the Royalty Accounting system fits into the enterprise landscape"
        }
        
        # Level 2: Container
        container royaltyAccounting "Containers" {
            include *
            autoLayout
            title "Container Diagram - Royalty Accounting System"
            description "Shows the high-level containers within the Royalty Accounting system"
        }
        
        # Level 3: Component (ABACUS)
        component abacus "AbacusComponents" {
            include *
            autoLayout
            title "Component Diagram - ABACUS Container"
            description "Shows the components within the ABACUS container and their interactions"
        }
        
        # Dynamic view showing data flow
        dynamic abacus "UserQueryFlow" "Shows how a user query flows through the system" {
            user -> frontendRoyalties "1. User requests royalty data"
            frontendRoyalties -> graphqlApi "2. GraphQL query"
            graphqlApi -> database "3. SQL query"
            database -> graphqlApi "4. Return data"
            graphqlApi -> frontendRoyalties "5. JSON response"
            frontendRoyalties -> user "6. Display results"
            autoLayout
            title "Dynamic Diagram - User Query Flow"
        }
        
        dynamic abacus "DagProcessingFlow" "Shows how DAG processing works" {
            graphqlApi -> dagOrchestrator "1. Trigger DAG run"
            dagOrchestrator -> lambdaFunctions "2. Execute Lambda function"
            lambdaFunctions -> database "3. Process and write data"
            database -> lambdaFunctions "4. Return results"
            lambdaFunctions -> dagOrchestrator "5. Complete task"
            dagOrchestrator -> graphqlApi "6. Notify completion"
            autoLayout
            title "Dynamic Diagram - DAG Processing Flow"
        }
        
        styles {
            element "Person" {
                shape person
                background #E6F3FF
                color #000000
            }
            element "Software System" {
                background #1E90FF
                color #ffffff
            }
            element "External" {
                background #999999
                color #ffffff
            }
            element "Container" {
                background #E6F3FF
                color #000000
            }
            element "Component" {
                background #87CEEB
                color #000000
            }
            element "Application" {
                background #E6F3FF
                color #000000
            }
        }
    }
}
```

[Try this in Structurizr DSL Editor](https://structurizr.com/dsl)

## Detailed Component Breakdown

### ABACUS Container Components

#### 1. Frontend Royalties
- **Technology**: React
- **Purpose**: User interface for royalty management
- **Interactions**:
  - Receives user input
  - Makes GraphQL API calls
  - Displays royalty data and visualizations

#### 2. GraphQL API
- **Technology**: Node.js/Apollo Server
- **Purpose**: Central API gateway for all data operations
- **Interactions**:
  - Serves GraphQL queries and mutations from frontend
  - Queries and updates database
  - Triggers DAG workflows in Airflow
  - Invokes AWS Lambda functions

#### 3. Database
- **Technology**: PostgreSQL
- **Purpose**: Primary data store for royalty information
- **Interactions**:
  - Receives queries from GraphQL API
  - Receives updates from DAG Orchestrator
  - Receives updates from Lambda functions

#### 4. DAG Orchestrator (Airflow)
- **Technology**: Apache Airflow
- **Purpose**: Orchestrates complex data processing workflows
- **Interactions**:
  - Triggered by GraphQL API
  - Executes Lambda functions as tasks
  - Reads from and writes to database
  - Manages workflow state and dependencies

#### 5. AWS Lambda Functions
- **Technology**: Python/Node.js
- **Purpose**: Serverless compute for specific tasks
- **Interactions**:
  - Invoked by GraphQL API for synchronous operations
  - Invoked by DAG Orchestrator for batch operations
  - Performs data transformations and calculations
  - Reads from and writes to database

## System Architecture Highlights

### Data Flow Patterns

1. **User-Initiated Query Flow**:
   - User → Frontend → GraphQL API → Database → GraphQL API → Frontend → User

2. **Batch Processing Flow**:
   - GraphQL API → DAG Orchestrator → Lambda Functions → Database

3. **Real-time Computation Flow**:
   - GraphQL API → Lambda Functions → Database → GraphQL API

### Container Relationships

- **ABACUS** serves as the core calculation engine
- **CA (Customer Accounting)** receives processed accounting data from ABACUS
- **TAP (Taxes & Payments)** receives payment-ready data from ABACUS
- **Collaborators** receives split calculation data from ABACUS

## Benefits of C4 Model

- **Clear Abstraction Levels**: Each diagram serves a different audience
  - System Context: Business stakeholders
  - Container: Architects and technical leads
  - Component: Developers
  
- **Zooming**: Ability to zoom in and out of the architecture
- **Consistency**: Same notation across all levels
- **Tool Support**: Structurizr provides excellent tooling
- **Living Documentation**: Can be kept up to date as code

## Alternative Visualization - Simplified System Context

For presentations or documentation that needs a simpler view:

```structurizr
workspace "Simplified Royalty System" {
    model {
        user = person "Business User"
        
        royaltyAccounting = softwareSystem "Royalty Accounting" "Calculates and manages royalty payments"
        content = softwareSystem "Content" "Music catalog"
        insights = softwareSystem "Insights" "Analytics"
        
        user -> royaltyAccounting "Manages royalties"
        royaltyAccounting -> content "Gets catalog data"
        royaltyAccounting -> insights "Sends metrics"
    }
    
    views {
        systemContext royaltyAccounting "SimplifiedContext" {
            include *
            autoLayout
        }
        
        styles {
            element "Person" {
                shape person
                background #E6F3FF
                color #000000
            }
            element "Software System" {
                background #1E90FF
                color #ffffff
            }
        }
    }
}
```

[Try this in Structurizr DSL Editor](https://structurizr.com/dsl)

## Next Steps

To use this C4 model:

1. **Copy the DSL code** to a `.dsl` file
2. **Render locally** using Structurizr Lite:
   ```bash
   docker run -it --rm -p 8080:8080 \
     -v $(pwd):/usr/local/structurizr \
     structurizr/lite
   ```
3. **Export diagrams** for documentation:
   ```bash
   # Export to PlantUML
   structurizr export -workspace workspace.dsl -format plantuml
   
   # Export to PNG images
   structurizr export -workspace workspace.dsl -format png
   ```

## Resources

- **C4 Model**: https://c4model.com
- **Structurizr**: https://structurizr.com
- **Structurizr DSL**: https://github.com/structurizr/dsl
- **Examples**: https://structurizr.com/share

