# Admin Settings Page-by-Page Plan and Implementation Roadmap

## 1. Scope and Planning Assumptions

This plan covers all admin settings pages under `/admin/settings` grouped into:
- System (6 pages)
- Customer (6 pages)
- Merchant (6 pages)

Current baseline in code:
- Dashboard and routing exist.
- Sprint 1 starter pages exist for:
  - System Security
  - Customer Limits
  - Merchant Onboarding
- Remaining pages are currently routed through placeholder LiveView.

Primary goals of this plan:
- Define each page independently (separate delivery plan per page).
- Sequence implementation with clear dependencies.
- Standardize form behavior, validation, authorization, persistence, auditability, and testing.

---

## 2. Cross-Cutting Standards (Apply to Every Page)

### 2.1 Authorization and Visibility
- Route-level access remains back-office gated.
- Page-level access must check policy action in mount.
- Unauthorized users:
  - no data load,
  - flash message,
  - redirect to `/admin/settings`.

### 2.2 Data Persistence and Versioning
- Use `admin_configurations` as canonical storage for active/effective config values.
- Use `admin_configuration_audit` for immutable change history.
- Config identity pattern:
  - `namespace` = `system|customer|merchant`
  - `category` = page category (`security`, `limits`, etc.)
  - `config_key` = stable leaf key (`password.min_length`, `merchant.fees.mdr_tier_1`, etc.)
- Support effective dating with one active record per key at an effective timestamp.

### 2.3 Change Flow (Uniform UX)
- Every page supports:
  - load current effective config,
  - edit draft values,
  - validate,
  - preview delta,
  - save with reason,
  - optional schedule (`effective_from`).
- Save action writes audit record with actor and reason.

### 2.4 Validation
- Input-level validation in changesets.
- Domain validation in service layer (cross-field rules).
- Temporal validation for effective periods:
  - `effective_to` > `effective_from` when set,
  - no overlapping active windows for same key.

### 2.5 Reliability / Safety
- Idempotent updates per `(namespace, category, config_key, effective_from)`.
- Concurrency handling:
  - optimistic lock/version check at write boundary,
  - stale edit conflict message.

### 2.6 Observability
- Emit telemetry for:
  - page load,
  - validation failures,
  - successful saves,
  - denied authorization.
- Structured log fields:
  - `actor_id`, `namespace`, `category`, `changed_keys_count`, `effective_from`.

### 2.7 Testing Baseline per Page
- LiveView mount authorization tests.
- Render tests for key form sections.
- Validation tests (happy + negative cases).
- Save + audit trail tests.
- Effective date scheduling tests (if scheduling enabled for page).

---

## 3. Page-by-Page Delivery Plan

For each page: objective, config domains, policy action, UI sections, validation, tests, and dependencies.

## 3.1 System Pages

### 3.1.1 System General (`/admin/settings/system/general`)
- Policy Action: `:manage_system_settings`
- Objective:
  - Manage tenant branding and global defaults.
- Config Keys:
  - `tenant.name`
  - `tenant.logo_url`
  - `locale.default`
  - `currency.default`
  - `timezone.default`
- UI Sections:
  - Branding
  - Regional Defaults
  - Preview card (effective values)
- Validation:
  - Name required (3-120 chars)
  - Logo URL optional but must be valid URL
  - Locale/currency/timezone must be whitelisted
- Tests:
  - mount access allowed/denied
  - invalid locale/currency rejection
  - successful save writes audit row
- Dependencies:
  - shared lookup lists for locale/currency/timezone

### 3.1.2 System Security (`/admin/settings/system/security`)
- Policy Action: `:manage_security_config`
- Objective:
  - Control auth security posture and key governance.
- Config Keys:
  - `password.min_length`
  - `password.complexity`
  - `password.history_count`
  - `session.idle_timeout_minutes`
  - `mfa.required_actions`
  - `keys.rotation_days`
- UI Sections:
  - Password Policy
  - Session Controls
  - MFA Enforcement
  - Key Rotation
- Validation:
  - min length in accepted range
  - timeout and rotation bounds
  - mandatory MFA settings for privileged actions
- Tests:
  - role-based access
  - range validations
  - save + audit + effective scheduling
- Dependencies:
  - integration point with auth/security modules

### 3.1.3 System Integrations (`/admin/settings/system/integrations`)
- Policy Action: `:manage_integrations`
- Objective:
  - Configure provider adapters and connection policies.
- Config Keys:
  - `integrations.<provider>.enabled`
  - `integrations.<provider>.base_url`
  - `integrations.<provider>.timeout_ms`
  - `integrations.<provider>.retry_policy`
- UI Sections:
  - Provider Toggle Matrix
  - Endpoint and Timeout Config
  - Credentials Reference (masked)
  - Health Check Status
- Validation:
  - URL validity
  - timeout/retry bounds
  - at least one active provider for mandatory capability
- Tests:
  - per-provider validation
  - invalid endpoint failure
  - save audit capture
- Dependencies:
  - adapters registry + health check service

### 3.1.4 System Storage (`/admin/settings/system/storage`)
- Policy Action: `:manage_storage_config`
- Objective:
  - Define retention, encryption, backup and purge policy.
- Config Keys:
  - `retention.transactions_days`
  - `retention.audit_days`
  - `encryption.at_rest_mode`
  - `backup.frequency`
  - `purge.grace_days`
- UI Sections:
  - Retention Policy
  - Encryption Controls
  - Backup Schedule
  - Purge Rules
- Validation:
  - retention minimums enforced
  - purge grace not greater than retention
  - valid backup frequency enum
- Tests:
  - cross-field validation
  - denied role behavior
  - audit trail integrity
- Dependencies:
  - storage lifecycle jobs and encryption policy service

### 3.1.5 System Notifications (`/admin/settings/system/notifications`)
- Policy Action: `:manage_notification_templates`
- Objective:
  - Govern templates, channels, and webhook delivery policies.
- Config Keys:
  - `notifications.channels.enabled`
  - `notifications.template.default_locale`
  - `notifications.webhook.retry_policy`
  - `notifications.webhook.timeout_ms`
- UI Sections:
  - Channel Enablement
  - Template Defaults
  - Webhook Delivery Policy
- Validation:
  - at least one customer-facing channel enabled
  - webhook timeout/retry ranges
- Tests:
  - template/channel settings persistence
  - invalid retries rejected
- Dependencies:
  - wallet_notifications capability contracts

### 3.1.6 System API (`/admin/settings/system/api`)
- Policy Action: `:manage_api_config`
- Objective:
  - Configure platform API limits and partner controls.
- Config Keys:
  - `api.rate_limit.default_rpm`
  - `api.rate_limit.partner_overrides`
  - `api.keys.rotation_days`
  - `api.environment.sandbox_enabled`
- UI Sections:
  - Global Rate Limits
  - Partner Overrides
  - Key Rotation Policy
  - Environment Controls
- Validation:
  - override limits must be >= baseline constraints
  - rotation day bounds
- Tests:
  - limit enforcement config save
  - malformed partner overrides fail
- Dependencies:
  - API gateway/rate limiter integration contract

## 3.2 Customer Pages

### 3.2.1 Customer Enrollment (`/admin/settings/customer/enrollment`)
- Policy Action: `:manage_enrollment_config`
- Objective:
  - Configure registration and KYC tier onboarding rules.
- Config Keys:
  - `enrollment.required_fields`
  - `enrollment.kyc.tier_requirements`
  - `enrollment.verification.document_types`
  - `enrollment.auto_approve_rules`
- UI Sections:
  - Registration Requirements
  - KYC Tier Matrix
  - Verification Rules
- Validation:
  - each tier has mandatory requirements
  - document types from whitelist
- Tests:
  - tier rule completeness
  - successful save with audit reason
- Dependencies:
  - wallet_compliance onboarding policies

### 3.2.2 Customer Limits (`/admin/settings/customer/limits`)
- Policy Action: `:manage_limit_policies`
- Objective:
  - Configure tier and corridor transaction limits.
- Config Keys:
  - `limits.<tier>.<corridor>.daily`
  - `limits.<tier>.<corridor>.monthly`
  - `limits.<tier>.<corridor>.single_txn`
  - `limits.velocity.rules`
- UI Sections:
  - Tier Limit Matrix
  - Velocity Rules
  - Risk Multipliers
- Validation:
  - daily <= monthly
  - single_txn <= daily
  - velocity thresholds non-negative
- Tests:
  - matrix validation failures
  - update persistence by tier/corridor
- Dependencies:
  - policy engine rule application

### 3.2.3 Customer Fees (`/admin/settings/customer/fees`)
- Policy Action: `:manage_fee_policies`
- Objective:
  - Configure fee schedules, waivers, and discount rules.
- Config Keys:
  - `fees.customer.schedule`
  - `fees.customer.waiver_rules`
  - `fees.customer.tier_discounts`
- UI Sections:
  - Fee Schedule Table
  - Waiver Rules
  - Discount Policy
- Validation:
  - non-negative fee constraints
  - waiver rules must have valid scope and expiry
- Tests:
  - schedule CRUD behaviors
  - conflicting waiver rules blocked
- Dependencies:
  - fee calculator module contracts

### 3.2.4 Customer Channels (`/admin/settings/customer/channels`)
- Policy Action: `:manage_channel_config`
- Objective:
  - Configure enabled channels and channel-level restrictions.
- Config Keys:
  - `channels.customer.web.enabled`
  - `channels.customer.mobile.enabled`
  - `channels.customer.ussd.enabled`
  - `channels.customer.<channel>.limits`
- UI Sections:
  - Channel Toggle Board
  - Channel-Specific Limits
- Validation:
  - at least one channel enabled
  - per-channel limits valid against global limits
- Tests:
  - channel disable/enable behavior
  - conflicting limit setups rejected
- Dependencies:
  - channel gateway capability flags

### 3.2.5 Customer Products (`/admin/settings/customer/products`)
- Policy Action: `:manage_product_config`
- Objective:
  - Configure product availability and defaults (cards, loans, insurance, rewards).
- Config Keys:
  - `products.cards.enabled`
  - `products.loans.enabled`
  - `products.insurance.enabled`
  - `products.rewards.enabled`
  - `products.defaults.*`
- UI Sections:
  - Product Enablement Grid
  - Product Defaults
- Validation:
  - dependency constraints (e.g., rewards requires core eligibility)
- Tests:
  - product toggle persistence
  - dependency rule enforcement
- Dependencies:
  - wallet_cards, wallet_loans, wallet_insurance, wallet_rewards

### 3.2.6 Customer Consent (`/admin/settings/customer/consent`)
- Policy Action: `:manage_consent_config`
- Objective:
  - Manage consent policy versioning and privacy controls.
- Config Keys:
  - `consent.policy.current_version`
  - `consent.required_types`
  - `privacy.retention_overrides`
  - `privacy.rights.sla_days`
- UI Sections:
  - Consent Types
  - Policy Version Management
  - Data Rights SLA
- Validation:
  - version monotonicity
  - required consent types non-empty
- Tests:
  - version increment behavior
  - SLA range validation
- Dependencies:
  - consent/profile domain integration

## 3.3 Merchant Pages

### 3.3.1 Merchant Onboarding (`/admin/settings/merchant/onboarding`)
- Policy Action: `:manage_merchant_onboarding_config`
- Objective:
  - Define onboarding workflow, KYB requirements, and approval gates.
- Config Keys:
  - `merchant.onboarding.workflow_steps`
  - `merchant.onboarding.kyb_required_docs`
  - `merchant.onboarding.approval_thresholds`
- UI Sections:
  - Workflow Stages
  - KYB Requirements
  - Approval Thresholds
- Validation:
  - mandatory workflow stages present
  - required docs non-empty
- Tests:
  - stage ordering validation
  - successful save and audit
- Dependencies:
  - merchant onboarding workflow module

### 3.3.2 Merchant Fees (`/admin/settings/merchant/fees`)
- Policy Action: `:manage_merchant_fees`
- Objective:
  - Configure MDR and merchant-related fee schedules.
- Config Keys:
  - `merchant.fees.mdr_by_category`
  - `merchant.fees.settlement_charges`
  - `merchant.fees.chargeback_fees`
- UI Sections:
  - MDR Table
  - Settlement and Chargeback Fees
- Validation:
  - percentage bounds for MDR
  - fee floor/ceiling constraints
- Tests:
  - MDR tier update tests
  - invalid percentage rejection
- Dependencies:
  - merchant settlement + billing contracts

### 3.3.3 Merchant Settlement (`/admin/settings/merchant/settlement`)
- Policy Action: `:manage_settlement_config`
- Objective:
  - Configure settlement cycles, cutoffs, and holiday behavior.
- Config Keys:
  - `merchant.settlement.cycle`
  - `merchant.settlement.cutoff_time`
  - `merchant.settlement.holiday_policy`
  - `merchant.settlement.auto_trigger`
- UI Sections:
  - Cycle Configuration
  - Cutoff and Calendar Policy
  - Auto-Settlement Triggers
- Validation:
  - cycle enum validity
  - cutoff time format/timezone constraints
- Tests:
  - cycle/cutoff persistence
  - holiday rule validation
- Dependencies:
  - settlement scheduler and calendar service

### 3.3.4 Merchant Acceptance (`/admin/settings/merchant/acceptance`)
- Policy Action: `:manage_acceptance_config`
- Objective:
  - Configure POS/QR/SoftPOS acceptance rules.
- Config Keys:
  - `merchant.acceptance.pos.enabled`
  - `merchant.acceptance.softpos.enabled`
  - `merchant.acceptance.qr.mode`
  - `merchant.acceptance.limits`
- UI Sections:
  - Channel Enablement
  - QR Mode and Constraints
  - Acceptance Limits
- Validation:
  - qr mode enum (static/dynamic/both)
  - limits within risk constraints
- Tests:
  - acceptance mode transitions
  - invalid limit combinations blocked
- Dependencies:
  - merchant channel processing and QR services

### 3.3.5 Merchant Risk (`/admin/settings/merchant/risk`)
- Policy Action: `:manage_merchant_risk_rules`
- Objective:
  - Configure merchant risk scoring and intervention thresholds.
- Config Keys:
  - `merchant.risk.score_thresholds`
  - `merchant.risk.velocity_limits`
  - `merchant.risk.manual_review_rules`
- UI Sections:
  - Score Threshold Matrix
  - Velocity Controls
  - Review Escalation Rules
- Validation:
  - threshold monotonicity (low < medium < high)
  - velocity values non-negative
- Tests:
  - threshold consistency validation
  - save and audit assertions
- Dependencies:
  - risk engine scoring/rule adaptor

### 3.3.6 Merchant Compliance (`/admin/settings/merchant/compliance`)
- Policy Action: `:manage_merchant_compliance`
- Objective:
  - Configure compliance requirements and periodic review cadence.
- Config Keys:
  - `merchant.compliance.required_controls`
  - `merchant.compliance.review_cycle_days`
  - `merchant.compliance.doc_expiry_rules`
- UI Sections:
  - Requirement Set
  - Review Cadence
  - Document Expiry Rules
- Validation:
  - review cycle minimum threshold
  - expiry rules include notification lead times
- Tests:
  - cadence validation
  - control set persistence
- Dependencies:
  - compliance case lifecycle integration

---

## 4. Unified Implementation Plan

## 4.1 Delivery Phases

### Phase A: Foundation Hardening (Week 1)
- Finalize settings router and mount authorization conventions.
- Build shared `AdminConfig` context API:
  - `get_effective(namespace, category)`
  - `upsert_config_set(actor, reason, entries, effective_from)`
  - `list_audit(namespace, category, pagination)`
- Add Ecto schemas and migrations for:
  - `admin_configurations`
  - `admin_configuration_audit`
- Add shared LiveView form helpers:
  - save reason modal,
  - effective date picker,
  - diff preview component,
  - common error rendering.

### Phase B: Sprint 1 Completion (Week 2)
- Productionize existing sprint 1 pages:
  - System Security
  - Customer Limits
  - Merchant Onboarding
- Replace static scaffolds with real read/write config service.
- Add full test suite for these 3 pages (auth, render, validation, save, audit).

### Phase C: Sprint 2 Pages (Weeks 3-4)
- Implement medium-priority pages:
  - System Integrations
  - Customer Fees
  - Merchant Fees
  - Merchant Settlement
  - System Notifications
- Add adapter-level validation where external dependencies apply.
- Expand telemetry and dashboard counters for change events.

### Phase D: Sprint 3 Pages and Completion (Weeks 5-6)
- Implement remaining pages:
  - System General, System Storage, System API
  - Customer Enrollment, Customer Channels, Customer Products, Customer Consent
  - Merchant Acceptance, Merchant Risk, Merchant Compliance
- Add audit history UI and filterable change timeline.
- Add bulk import/export for selected categories.

### Phase E: Stabilization and Release Readiness (Week 7)
- End-to-end back-office UAT per role matrix.
- Performance tests for dashboard + heavy config categories.
- Security review for sensitive fields and audit integrity.
- Rollout plan with feature flags and rollback procedure.

## 4.2 Workstream Breakdown

### Workstream 1: Domain and Persistence
- Ecto schemas and migrations
- Config service API and invariants
- Versioning and effective date logic

### Workstream 2: UI/LiveView
- Shared settings components
- Page-specific LiveViews
- UX consistency and error handling

### Workstream 3: Policy and Access
- Ensure all actions exist in policy map
- Role mapping tests for admin/ops/compliance/sre

### Workstream 4: Testing and Quality
- LiveView tests for each page
- Context unit tests for validation and versioning
- Integration tests for save + audit path

### Workstream 5: Operations and Observability
- Telemetry events
- Structured logs
- Runbook updates and release checklist

## 4.3 Implementation Order (Concrete Sequence)

1. Migrations + schemas + shared config service.
2. Shared UI components for all settings pages.
3. Wire sprint 1 pages to persistent service.
4. Implement sprint 2 pages in this order:
   - System Integrations
   - System Notifications
   - Customer Fees
   - Merchant Fees
   - Merchant Settlement
5. Implement sprint 3 pages in this order:
   - System General
   - System Storage
   - System API
   - Customer Enrollment
   - Customer Channels
   - Customer Products
   - Customer Consent
   - Merchant Acceptance
   - Merchant Risk
   - Merchant Compliance
6. Add history timeline + bulk import/export.
7. Finalize UAT, load/security checks, release.

## 4.4 Definition of Done (Per Page)
- Policy action enforced at mount and covered by tests.
- Config values read from and persisted to `admin_configurations`.
- Save operation writes `admin_configuration_audit` entry with actor + reason.
- Validation includes field-level + domain-level rules.
- Effective date scheduling supported or explicitly documented as N/A.
- Telemetry events emitted for success and failure paths.
- Page appears correctly in dashboard and route contract tests pass.

## 4.5 Risks and Mitigations
- Risk: Policy-action drift between menu, routes, and page mount checks.
  - Mitigation: Contract test asserting 1:1 action mapping.
- Risk: Overlapping effective periods causing ambiguous config reads.
  - Mitigation: DB uniqueness + service-level overlap checks.
- Risk: Inconsistent page UX and save behavior.
  - Mitigation: shared settings form components and standard save workflow.
- Risk: External integration misconfiguration impact.
  - Mitigation: health-check pre-save warning + staged rollout using effective dates.

---

## 5. Suggested File Targets for Implementation

- Navigation and dashboard:
  - `apps/wallet_web/lib/wallet_web/navigation/admin_settings_menu.ex`
  - `apps/wallet_web/lib/wallet_web/live/admin/settings/admin_settings_live.ex`
- Pages:
  - `apps/wallet_web/lib/wallet_web/live/admin/settings/*_live.ex`
- Policy:
  - `apps/wallet_web/lib/wallet_web/authorization/policy.ex`
- Persistence:
  - `apps/wallet_database/lib/**/admin_configuration*.ex`
  - `apps/wallet_database/priv/repo/migrations/*admin_configurations*.exs`
- Tests:
  - `apps/wallet_web/test/wallet_web/live/admin/*settings*_test.exs`
  - `apps/wallet_web/test/wallet_web/navigation/admin_settings_menu_test.exs`

This document is the implementation source-of-truth for delivering each settings page independently while maintaining a single coherent rollout plan.
