# Wallet Reporting

**Phase 13 Sprint A - P13-SA-A01: Reporting Domain Foundation**

Comprehensive reporting capabilities for the wallet system with support for on-demand and scheduled report generation across multiple categories and output formats.

## Features

### Report Categories
- **KPI Reports**: Key Performance Indicators and business metrics
- **Balance Reports**: Account balance summaries and analytics
- **Settlement Reports**: Settlement and reconciliation data
- **Dispute Reports**: Dispute tracking and resolution metrics
- **Usage Reports**: Usage analytics and system metrics

### Output Formats
- **CSV**: Comma-separated values for data analysis
- **PDF**: Formatted documents for sharing and archival
- **JSON**: Machine-readable format for API integration

### Report Lifecycle
1. **Queued**: Report request created and waiting for processing
2. **Generating**: Report generation in progress
3. **Ready**: Report completed successfully with artifact available
4. **Failed**: Report generation failed with error details
5. **Expired**: Request expired before completion

## Domain Model

### Core Entities

#### ReportCatalog
Defines available reports with metadata, parameters, and scheduling options.

```elixir
%ReportCatalog{
  report_id: "rpt_abc123",
  name: "Daily Balance Summary",
  description: "Account balance summary for all active accounts",
  category: :balance,
  output_formats: [:csv, :pdf],
  schedule: "0 9 * * *",  # Daily at 9 AM
  params: [
    %{name: "start_date", type: :date, required: true, default: nil},
    %{name: "include_inactive", type: :boolean, required: false, default: false}
  ],
  active: true
}
```

#### ReportRequest
Individual report generation requests with full lifecycle tracking.

```elixir
%ReportRequest{
  request_id: "rreq_xyz789",
  user_id: "usr_admin_001",
  report_id: "rpt_abc123",
  status: :ready,
  output_format: :csv,
  parameters: %{start_date: "2026-01-01", include_inactive: false},
  requested_at: ~U[2026-03-28 10:00:00Z],
  started_at: ~U[2026-03-28 10:00:05Z],
  completed_at: ~U[2026-03-28 10:00:45Z],
  expires_at: ~U[2026-03-28 11:00:00Z],
  artifact_path: "/reports/balance_2026-03-28.csv"
}
```

#### ReportSchedule
Recurring report generation with flexible scheduling.

```elixir
%ReportSchedule{
  schedule_id: "rsch_weekly_001",
  report_id: "rpt_abc123",
  name: "Weekly Balance Report",
  frequency: :weekly,
  output_format: :pdf,
  parameters: %{include_inactive: true},
  recipients: ["finance@company.com", "ceo@company.com"],
  active: true,
  next_run_at: ~U[2026-04-04 09:00:00Z]
}
```

## Store Operations

### ReportRequestStore
ETS-backed storage with comprehensive indexing:
- Primary key: `request_id`
- Indexes: `user_id`, `status`, `report_id`
- Operations: `store/1`, `get/1`, `update/1`, `list_by_user/1`, `list_by_status/1`, `list_expired/0`

### ReportScheduleStore
ETS-backed storage for schedule management:
- Primary key: `schedule_id`
- Indexes: `report_id`, `active`
- Operations: `store/1`, `get/1`, `update/1`, `list_by_report/1`, `list_active/0`, `list_due_for_execution/0`

## Commands

### RequestReport
Creates on-demand report requests.

```elixir
alias WalletReporting.Commands.RequestReport

{:ok, request} = RequestReport.execute(
  "usr_admin_001",           # user_id
  "rpt_balance_daily",       # report_id
  :csv,                      # output_format
  %{start_date: "2026-01-01"}, # parameters
  expires_minutes: 120       # options
)
```

### ScheduleReport
Sets up recurring report generation.

```elixir
alias WalletReporting.Commands.ScheduleReport

{:ok, schedule} = ScheduleReport.execute(
  "rpt_balance_daily",       # report_id
  "Daily Balance Report",    # name
  :daily,                    # frequency
  :pdf,                      # output_format
  %{include_inactive: false}, # parameters
  ["admin@company.com"],     # recipients
  cron_expression: "0 9 * * *" # options
)
```

## Events

### Domain Events
All operations emit structured domain events:

- **ReportRequested.v1**: Report request created
- **ReportCompleted.v1**: Report generation succeeded
- **ReportFailed.v1**: Report generation failed
- **ReportScheduled.v1**: Report schedule created

### Event Structure
```elixir
%{
  event_name: "ReportRequested.v1",
  aggregate_type: "ReportRequest",
  aggregate_id: "rreq_xyz789",
  correlation_id: "corr_abc123",
  occurred_at: ~U[2026-03-28 10:00:00Z],
  payload: %{
    user_id: "usr_admin_001",
    report_id: "rpt_abc123",
    output_format: :csv,
    parameters: %{start_date: "2026-01-01"}
  }
}
```

## Testing

Comprehensive test suite with 25+ tests covering:
- Report catalog validation and structure
- Report request lifecycle state machine
- Report schedule functionality
- Store operations and indexing
- Command execution and event emission

```bash
# Run all reporting tests
mix test apps/wallet_reporting/test/

# Run specific domain tests
mix test apps/wallet_reporting/test/wallet_reporting/reporting_domain_test.exs
```

## Architecture Compliance

- **Umbrella Pattern**: Self-contained OTP app with proper supervision
- **ETS Stores**: Concurrent, indexed storage with proper reset capabilities
- **Event Emission**: Domain events and audit trails for all operations
- **DI Pattern**: Configurable PubSub integration for cross-app boundaries
- **Error Handling**: Comprehensive validation and error reporting

## Dependencies

- `wallet_shared_kernel`: TypedId, Money, Correlation utilities
- `wallet_observability`: AuditEvent schema and telemetry
- `wallet_events`: DomainEvent behaviour implementation
- `phoenix_pubsub`: Event broadcasting and subscription

## Integration

The reporting domain integrates with:
- **Authentication**: User-scoped report requests
- **Authorization**: Role-based report access controls
- **Notification**: Report completion and failure alerts
- **Storage**: Artifact persistence and retrieval
- **Observability**: Comprehensive audit and telemetry

## Future Extensions (Phase 13 Sprint B)

- Report generation pipeline with async job processing
- Template-based report rendering with customization
- Report artifact storage and retrieval mechanisms
- Advanced scheduling with cron expression support
- Report sharing and collaboration features

