# Kuwait Prepaid Card Program — Implementation Initiated ✅

**Date:** 2026-04-20  
**Status:** Gap & Proposal Complete → Ready for Sprint 0 Kickoff  
**Branch:** `prepaid-card-system`

---

## 📊 Current State

### What We Have (40% ready)
- ✅ Full payment & ledger infrastructure (wallet_ledger, wallet_transfers, wallet_settlement)
- ✅ Card lifecycle domain (wallet_cards: single-card issuance, freeze, reset PIN)
- ✅ Admin monitoring console (26+ LiveViews: transactions, audit, statements)
- ✅ PIN change command (WalletAuth.Pin.Commands.ChangePIN)
- ✅ POS authorization hook (wallet_merchant.AuthorizePosPayment)
- ✅ Batch salary credit pattern (wallet_wps.BatchPostSalaryCredits — reusable)
- ✅ Compliance pipeline (KYC, AML, data governance)
- ✅ Report generation engine (wallet_reporting)

### What We're Building (60% new)
- ❌ `apps/wallet_prepaid` umbrella app (entire new domain)
- ❌ Bilingual cardholder fields (name_en, name_ar, national_id encrypted)
- ❌ Bulk CSV card issuance (6,000 cards in <5s with 14-day SLA)
- ❌ Statement-driven batch top-up (2-day SLA enforcement)
- ❌ Closed-loop merchant allowlist (purchase only at cooperatives)
- ❌ Monthly programme balance report (all 6k cards with names, IDs, balances)
- ❌ Customer PIN change LiveView (self-service)
- ❌ Arabic locale + RTL UI (full bilingual console)
- ❌ On-premise deployment packaging (Docker Compose + scripts)

---

## 📋 10 Sprints Planned (18–20 working days)

| Sprint | Feature | Days | Dependencies |
|--------|---------|------|--------------|
| **0** | Scaffold `wallet_prepaid` app | 0.5 | None |
| **1** | DB migrations (6 tables + 2 updates) | 1.0 | S0 |
| **2** | PrepaidProgram domain (4 stores, 4 cmds, 4 events) | 1.5 | S1 |
| **3** | Bulk issuance (CSV parser + BulkIssueCards cmd) | 2.0 | S2 |
| **4** | Batch top-up + sweep (SLA enforcement) | 1.5 | S3 |
| **5** | Monthly balance report | 0.5 | S4 |
| **6** | Admin LiveViews (8 new views) | 3.0 | S5 |
| **7** | Customer PIN change LiveView | 0.5 | S6 |
| **8** | Closed-loop POS guard | 1.0 | S2 (parallel) |
| **9** | Arabic/RTL UI + Gettext | 1.5 | S6 |
| **10** | Docker Compose deployment | 2.0 | All sprints |
| — | Integration & E2E testing | 3.0 | All sprints |

**Estimated Total: 18–20 working days**

---

## 🎯 Deliverables Summary

### App: `apps/wallet_prepaid`
- **4 Stores** (ETS + MySQL write-through): ProgramStore, ProgramMerchantStore, IssuanceBatchStore, TopUpBatchStore
- **8 Commands**: CreatePrepaidProgram, BulkIssueCards, BatchTopUpFromStatement, SweepProgramBalances, AddProgramMerchant, etc.
- **4 Events**: PrepaidProgramCreated, BulkIssuanceCompleted, BatchTopUpCompleted, BalanceSweepCompleted
- **1 Policy**: ClosedLoopPolicy (authorize_purchase/2)
- **2 Parsers**: CsvParser (bulk issuance), StatementParser (batch top-up)

### Database (in `wallet_database`)
- **6 New Migrations**: prepaid_programs, prepaid_program_merchants, prepaid_issuance_batches, prepaid_top_up_batches
- **2 Schema Updates**: users (name_en, name_ar, national_id), cards (program_id, is_prepaid, top_up_amount)

### Admin Console (in `wallet_web`)
- **8 LiveViews**: Programs, ProgramShow, Cardholders, BulkIssuance, BatchTopUp, BalanceSweep, Merchants, MonthlyReport
- **1 Customer LiveView**: ChangePinLive
- **Navigation**: New "Prepaid" menu section with 8 items

### Infrastructure (in `deploy/`)
- **Docker Compose**: app + MySQL + Nginx + Redis
- **Scripts**: setup.sh, migrate.sh, backup_db.sh, health_check.sh
- **Nginx Config**: reverse proxy, SSL, rate limiting, IP allowlist for /admin/*

### Localization (in `wallet_web`)
- **Gettext**: Arabic locale files (errors.po, default.po, prepaid.po)
- **RTL CSS**: Tailwind variants, direction toggles
- **SetLocale Plug**: Session-based locale switching

---

## 📚 Documentation Created

| File | Purpose | Location |
|------|---------|----------|
| **PHASE_TRACKER.md** | Sprint-by-sprint roadmap (MASTER DOC) | `/docs/prepaid_card/PHASE_TRACKER.md` |
| **new_gap_analysis.md** | Gap table: what exists vs. missing (P0/P1) | `/docs/prepaid_card/new_gap_analysis.md` |
| **kuwait-prepaid-card-proposal.md** | Full technical specification + rationale | `/docs/prepaid_card/kuwait-prepaid-card-proposal.md` |
| **SPRINT_0_QUICK_START.md** | Step-by-step app scaffold guide | `/docs/prepaid_card/SPRINT_0_QUICK_START.md` |
| **prepaid_project_status.md** | Memory save for future conversations | `/memory/prepaid_project_status.md` |

---

## 🚀 Next Actions (Priority Order)

### Immediate (Sprint 0 — Today/Tomorrow)
1. [ ] Review PHASE_TRACKER.md for complete sprint breakdown
2. [ ] Read SPRINT_0_QUICK_START.md for step-by-step app scaffold
3. [ ] Create `apps/wallet_prepaid/` structure (10 min)
4. [ ] Update root `mix.exs` with new app + nimble_csv (5 min)
5. [ ] Run `mix compile` — verify 0 warnings (5 min)
6. [ ] Commit: `feat: scaffold wallet_prepaid app (Sprint 0)`

### This Week (Sprint 1–2)
7. [ ] Create 6 database migrations (Sprint 1)
8. [ ] Update User + Card schemas (Sprint 1)
9. [ ] Build PrepaidProgram domain: stores, commands, events (Sprint 2)
10. [ ] Build ClosedLoopPolicy authorization (Sprint 2)

### Following Week (Sprint 3–6)
11. [ ] Build bulk issuance pipeline with CSV parser (Sprint 3)
12. [ ] Build batch top-up with SLA tracking (Sprint 4)
13. [ ] Build monthly balance report (Sprint 5)
14. [ ] Build 8 admin LiveViews (Sprint 6)

---

## 📊 Success Metrics

By end of implementation:

| Metric | Target | Note |
|--------|--------|------|
| **Sprints** | 10 complete + integration | 18–20 working days |
| **Tests** | 350+ passing | Domain + UI + integration tests |
| **Compilation** | 0 warnings | All 30 apps compile |
| **Database** | 6 migrations applied | All tables + schemas created |
| **Coverage** | ~40% → 100% | Gap analysis requirements met |
| **Demo Ready** | Bulk issuance → top-up → sweep | Full E2E workflow |

---

## 🔗 How to Use This Setup

### For Sprint Execution
1. Open `/docs/prepaid_card/PHASE_TRACKER.md` (main reference)
2. Find your current sprint section
3. Follow deliverables + tests checklist
4. Update status when complete
5. Move to next sprint

### For Progress Tracking
- Update `prepaid_project_status.md` (memory) with weekly status
- Update PHASE_TRACKER.md status log at bottom
- Commit with `feat/fix: <sprint>-<item>` for traceability

### For Context in Future Conversations
- Memory file (`prepaid_project_status.md`) loads automatically
- Reference PHASE_TRACKER.md for "where are we in the plan"
- Review gap analysis if requirements drift

---

## ✅ Readiness Checklist

- ✅ Gap analysis complete (8 P0 gaps identified, prioritized)
- ✅ Technical proposal approved (10-sprint roadmap)
- ✅ Phase tracker created (detailed per-sprint deliverables)
- ✅ App scaffold guide written (Sprint 0 instructions)
- ✅ Memory documented (persists across conversations)
- ✅ Dependencies identified (wallet_cards, wallet_ledger, etc.)
- ✅ Database schema designed (6 tables + 2 updates)
- ✅ Test strategy defined (350+ tests, existing patterns)

**Status: 🟢 READY FOR SPRINT 0 KICKOFF**

---

## 💡 Key Design Decisions

1. **Wallet-as-Card**: Leverage existing CardBalanceSyncRecord — no new architecture, just extend
2. **ETS + Persistence**: Follow existing pattern (GenServer stores + write-through to DB)
3. **Command/Event Pattern**: Reuse `wallet_events` behaviour for domain events + audit
4. **Closed-Loop**: Lightweight policy module (not breaking wallet_merchant — just guard at API layer)
5. **Bulk Processing**: Adapt WPS pattern (BatchPostSalaryCredits) — proven idempotency approach
6. **SLA Tracking**: Deadline fields on batch tables (14 days issuance, 2 days top-up)
7. **Arabic Support**: Gettext (already configured) + RTL CSS (Tailwind variants)
8. **Deployment**: Docker Compose single-node (6k cards = ~1.4 TPS avg = no clustering needed)

---

## 🎓 What This Covers

**For the Kuwait client:**
- ✅ F01-F16 functional requirements + NF01-NF04 non-functional
- ✅ 5,000–6,000 card volume support
- ✅ 14-day issuance SLA, 2-day top-up SLA
- ✅ Real-time reporting + admin console
- ✅ Closed-loop purchases at cooperatives only
- ✅ Balance sweep and refund pipeline
- ✅ On-premise deployment ready
- ✅ Arabic UI + bilingual reports

**For MomentPay:**
- ✅ Reusable `wallet_prepaid` app for future programs
- ✅ Extensible closed-loop policy engine
- ✅ Template for bulk operations (issuance, top-up)
- ✅ Bilingual infrastructure for international expansion

---

## 📞 Questions?

- **Gaps in domain logic?** → Check `new_gap_analysis.md`
- **Sprint details?** → Open `PHASE_TRACKER.md` for your sprint
- **How to start S0?** → Read `SPRINT_0_QUICK_START.md`
- **Architecture reasoning?** → See `kuwait-prepaid-card-proposal.md` § 5–6
- **Why these choices?** → Check `prepaid_project_status.md` + memory

---

**Next Step:** Begin Sprint 0 using `SPRINT_0_QUICK_START.md`

