# Enterprise Wallet Implementation Plan (Apps Mode)

## 1. Objective
Build an enterprise-grade wallet platform in Elixir/Phoenix using apps mode (umbrella-style OTP applications) aligned to:
- `docs/wallet-system.txt`
- `docs/wallet-architcture.md` (OWF reference architecture principles)
- The layered architecture image (Frontend/API/DMZ/Core/Integration/Data/Observability)

This document is the execution baseline for phased implementation and later delivery tracking.

## 2. Feasibility Statement
Yes, this is feasible with Erlang/Elixir/Phoenix.
- OTP supervision, fault isolation, and BEAM concurrency are suitable for wallet workloads.
- Phoenix + PubSub + Oban + Broadway/GenStage support request/response + event-driven patterns.
- Strong consistency for financial writes is achievable with transactional persistence and strict domain boundaries.

Key constraint:
- Build in phases with strict financial-core-first sequencing. Do not implement all domains at once.

## 3. Target Repository Structure (Apps Mode)
Current repository is a single Phoenix app. Target is umbrella-style multi-app structure.

```text
wallet_app/
  apps/
    wallet_web/                  # Phoenix endpoint, controllers, LiveView, channels (BFF/API)
    wallet_api_contracts/        # JSON schemas, API version contracts, error envelopes
    wallet_auth/                 # AuthN/AuthZ, JWT, OTP, device/session security
    wallet_accounts/             # Customer profile, wallet account lifecycle
    wallet_ledger/               # Double-entry ledger, posting engine, immutable entries
    wallet_transfers/            # P2P and transfer orchestration commands
    wallet_limits_fees/          # Limits, fees, rules engine domain
    wallet_risk/                 # Fraud/risk signals and scoring orchestration
    wallet_journey/              # Journey coordinator and business process state machine
    wallet_settlement/           # Settlement and reconciliation jobs
    wallet_notifications/        # User notifications, templates, channel dispatch
    wallet_integrations/         # External adapters (payment, CBS, VAS, fraud providers)
    wallet_events/               # Event model, outbox/inbox, schema versioning
    wallet_state/                # Non-financial state: idempotency, locks, workflow cache
    wallet_observability/        # Telemetry, tracing, audit events, health probes
    wallet_compliance/           # AML/KYC orchestration and reporting workflows
    wallet_shared_kernel/        # Shared types/behaviors/utilities (minimal)
  config/
  docs/
```

Rules:
- `wallet_web` is delivery channel only (no financial business logic).
- `wallet_ledger` owns financial system-of-record invariants.
- `wallet_state` never stores financial truth.
- `wallet_integrations` isolates all external protocol details.
- Shared kernel must remain small to avoid coupling.

## 4. Layer-to-App Alignment
### 4.1 Digital Frontend Engagement Layer
- `wallet_web` (LiveView web/admin, mobile BFF APIs, partner APIs)

### 4.2 API Engagement Layer
- External: Kong/Nginx/GLB
- Internal: `wallet_web` + `wallet_api_contracts`

### 4.3 DMZ & Security Layer
- `wallet_auth` + Redis-backed session/rate-limiting integration

### 4.4 Private Secure Zone (Core Wallet)
- Financial domain: `wallet_accounts`, `wallet_ledger`, `wallet_transfers`
- Biz/VAS domain: `wallet_compliance`, later `wallet_lending` (optional future), rewards in `wallet_notifications` + separate rewards app if needed
- Process domain: `wallet_journey`, `wallet_limits_fees`, `wallet_risk`
- Async domain: `wallet_settlement`, `wallet_notifications`
- Event backbone: `wallet_events` + Phoenix PubSub

### 4.5 Integration & Adapter Layer
- `wallet_integrations`

### 4.6 Data Persistence & Core Banking Layer
- Financial DB ownership by `wallet_ledger` and `wallet_accounts`
- Integration state in `wallet_integrations`
- Event outbox/inbox in `wallet_events`

### 4.7 Observability, Operations & Security
- `wallet_observability` + app-level telemetry spans + centralized log forwarding

## 5. Non-Functional Targets (Initial)
- Availability: active-active app nodes, no single process SPOF.
- Consistency: exactly-once command handling for financial writes via idempotency.
- Latency (internal): p95 transfer authorization under 250ms before external calls.
- Auditability: immutable ledger + append-only audit stream.
- Security: short-lived JWT, refresh rotation, MFA/OTP, secrets externalization.
- Operability: full request-to-ledger trace IDs and correlation IDs.

## 6. Cross-Cutting Design Decisions
1. Domain boundaries first, then implementation.
2. Command side synchronous for posting, side effects asynchronous.
3. Outbox pattern for external effects and inter-app reliable events.
4. Versioned events from day 1.
5. Idempotency required on all money movement endpoints.
6. ETS first for fast volatile state; Mnesia only when distributed shared state is required.
7. Avoid direct DB access across apps; use explicit service interfaces.

## 7. Phased Implementation Plan

## Phase 0: Program Setup and Architecture Baseline (2-3 weeks)
Goal:
- Establish delivery governance, coding standards, and app decomposition blueprint.

Scope:
- Create umbrella/apps-mode migration branch and ADR template.
- Define app ownership map and dependency direction (allowed imports/calls).
- Define canonical error envelope, correlation headers, API versioning policy.
- Define security baseline (token policy, OTP policy, secret handling).
- Define initial SLOs and observability minimums.

Deliverables:
- ADR set (architecture decisions).
- Repo standards doc for app boundaries.
- Initial risk register.

Exit criteria:
- Approved app map and dependency rules.
- Team sign-off on phase sequencing.

## Phase 1: Umbrella Migration and Skeleton Apps (2-4 weeks)
Goal:
- Move from single Phoenix app to umbrella with compile/runtime parity.

Scope:
- Create `apps/` and split existing web/app/repo concerns.
- Bootstrap minimal apps listed in section 3 with supervision trees.
- Establish inter-app contracts and compile-time boundaries.
- Keep existing homepage working during migration.

Deliverables:
- Running umbrella project in dev and CI.
- App-level README per OTP app with responsibility and public interface.

Exit criteria:
- `mix test` and `mix phx.server` equivalent works in umbrella mode.
- No circular dependencies across apps.

## Phase 2: Security and Access Foundation (3-4 weeks)
Goal:
- Implement DMZ-compatible auth/security controls before money features.

Scope:
- `wallet_auth`: login, token issuance/validation, refresh rotation, device session tracking.
- OTP challenge service and anti-abuse controls.
- API gateway contract integration points (headers, claims propagation).
- Initial RBAC for admin/ops/internal service roles.

Deliverables:
- Auth APIs and middleware plugs.
- Threat model v1 and abuse cases.

Exit criteria:
- Auth flows fully tested (happy + abuse + lockout).
- Security review passed for baseline controls.

## Phase 3: Financial Core - Accounts and Ledger (5-7 weeks)
Goal:
- Build wallet financial system of record.

Scope:
- `wallet_accounts`: wallet/account lifecycle state machine.
- `wallet_ledger`: double-entry posting engine, atomic transactions, immutable journal.
- Posting policies: debit/credit invariants, balance rules, freeze/unfreeze support.
- Ledger query APIs for balances and transaction history snapshots.

Deliverables:
- Ledger schema + migration set.
- Posting service with deterministic commands.

Exit criteria:
- Property tests for accounting invariants.
- Reproducible ledger under concurrent load tests.

## Phase 4: Transfers, Limits, Fees, and Journey Orchestration (4-6 weeks)
Goal:
- Deliver end-to-end internal money movement with policy enforcement.

Scope:
- `wallet_transfers`: transfer command handling and lifecycle states.
- `wallet_limits_fees`: configurable rules and fee calculations.
- `wallet_journey`: orchestration state machine for transfer journey.
- Idempotency keys and dedup checks in `wallet_state`.

Deliverables:
- P2P transfer API v1.
- Transfer lifecycle events and replay-safe handlers.

Exit criteria:
- Exactly-once transfer behavior under retries/timeouts.
- Policy decisions auditable and explainable.

## Phase 5: Async Processing, Settlement, Reconciliation, Notifications (4-6 weeks)
Goal:
- Move non-critical side effects off synchronous request path.

Scope:
- `wallet_settlement`: scheduled jobs, reconciliation pipelines, exception queues.
- `wallet_notifications`: transaction alerts and templated messaging.
- Oban queues with isolation by criticality.
- Retry, poison-message handling, operational dashboards.

Deliverables:
- Settlement and reconciliation runbooks.
- Notification preference model and delivery tracking.

Exit criteria:
- Core transaction latency unaffected by downstream failures.
- Reconciliation variance reports generated daily.

## Phase 6: Integrations and External Adapters (5-8 weeks)
Goal:
- Add external payment rails and core banking adapters safely.

Scope:
- `wallet_integrations`: adapter behaviors and provider-specific modules.
- Outbox/inbox + webhook verification and replay handling.
- CBS integration contracts and failure compensation strategies.
- External fraud provider hooks for augmenting `wallet_risk`.

Deliverables:
- At least one production-grade payment adapter.
- Integration simulation and contract test suite.

Exit criteria:
- Adapter failures do not break ledger consistency.
- Full reconciliation between wallet and external references.

## Phase 7: Compliance, Risk Maturity, and Audit Readiness (4-6 weeks)
Goal:
- Reach regulated-operational baseline.

Scope:
- `wallet_compliance`: KYC/KYB states, AML screening hooks, SAR workflow scaffolding.
- `wallet_risk`: rules + stream scoring integration and case management hooks.
- Immutable audit timeline with actor/action/context records.

Deliverables:
- Compliance evidence checklist mapped to controls.
- Risk decision traceability report.

Exit criteria:
- Internal audit dry run passed.
- Control tests automated in CI where possible.

## Phase 8: Resilience, Scale, and Production Readiness (4-8 weeks)
Goal:
- Harden for active-active deployment and incident operations.

Scope:
- Multi-node clustering, failover drills, capacity/perf tests.
- Back-pressure and queue saturation safeguards.
- Secrets/HSM integration, SIEM forwarding, incident playbooks.
- DR procedures and data recovery rehearsal.

Deliverables:
- Production readiness report.
- Cutover and rollback plan.

Exit criteria:
- SLO validation under load and fault injection.
- Go-live review board approval.

## 8. Dependency Order (Critical)
1. Phase 0-1 must complete before feature work.
2. Phase 2 must complete before exposing financial APIs.
3. Phase 3 must complete before transfer orchestration.
4. Phase 4 must complete before partner/external transfers.
5. Phase 5 should be in place before scaling traffic.
6. Phase 6-8 require stable observability and audit trails from earlier phases.

## 9. Suggested Team Topology
- Platform/Core team: umbrella infra, CI/CD, observability.
- Financial domain team: accounts/ledger/transfers.
- Security/compliance team: auth, controls, audit/compliance.
- Integration team: adapters and reconciliation.
- SRE/Operations team: reliability, deployment, incident readiness.

## 10. Testing Strategy by Layer
- Unit tests: per app command/query logic.
- Property tests: ledger invariants and arithmetic correctness.
- Contract tests: app-to-app and adapter/provider contracts.
- Integration tests: end-to-end transfer journey and reconciliation.
- Load tests: transfer authorization/posting critical path.
- Chaos tests: dependency outages and delayed external callbacks.

## 11. Initial Backlog Seeds (First 6 Sprints)
Sprint 1:
- Umbrella skeleton + architecture guardrails.
- API error contract and trace ID propagation.

Sprint 2:
- Auth baseline and session/device tracking.
- OTP challenge and lockout controls.

Sprint 3:
- Wallet account lifecycle + ledger schema.
- Posting command v1.

Sprint 4:
- Transfer command lifecycle + idempotency.
- Limits and fee rule engine v1.

Sprint 5:
- Oban queues + notification async path.
- Settlement job scaffolding.

Sprint 6:
- First payment adapter sandbox + reconciliation report v1.
- Observability dashboards and alert baselines.

## 12. Risks and Mitigations
- Risk: Over-coupled shared kernel.
  Mitigation: strict dependency linting and API boundaries.

- Risk: Event schema churn breaking consumers.
  Mitigation: versioned events and compatibility policy.

- Risk: Inconsistent financial state under retries.
  Mitigation: idempotent command processing + atomic posting.

- Risk: External adapter instability.
  Mitigation: outbox/inbox, retries with jitter, circuit breakers.

- Risk: Compliance gap discovered late.
  Mitigation: compliance controls introduced by Phase 2-3, not deferred.

## 13. Definition of Done (Program Level)
- All critical flows have traceability from API request to ledger entries.
- Financial posting invariants proven with automated tests.
- Reconciliation and audit exports are operational.
- Security controls validated via test evidence.
- Runbooks, dashboards, and incident process are in place.

## 14. Next Artifact Set to Create
After plan approval, create:
1. `docs/adr/` initial ADRs (app boundaries, eventing, idempotency, SoR ownership).
2. `docs/domain-map.md` with commands/events per domain app.
3. `docs/non-functional-slo.md` with concrete SLI/SLO thresholds.
4. `docs/phase-tracker.md` with milestone status and owners.
