# Business Requirements

BRD, functional/non-functional requirements, user stories, acceptance criteria, traceability

# Business Requirements Document (BRD): Drop — Fintech Payment App

# Business Requirements Document (BRD): Drop — Fintech Payment App

> **Project:** Drop — Remittance + QR Payments
> **Version:** 1.0
> **Date:** 2026-02-08 (updated 2026-02-23)
> **Author:** John (AI Director) + product agent + finance agent + legal agent
> **Status:** Approved
> **Reviewers:** Alem Bašić (CEO)

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1 | 2026-02-08 | product + finance + legal agents | Initial 2-round analysis |
| 1.0 | 2026-02-23 | John | Formalised with current state; updated for pass-through model |

---

## 1. Executive Summary

**Project Overview:** Drop is a PSD2 pass-through fintech payment app for all residents in Norway/Scandinavia, built by ALAI Holding AS (org.nr 932 516 136). It offers two core services: international remittance at 0.5% fee and QR-based merchant payments at 1% fee, both executed via Open Banking (AISP/PISP) directly from users' Norwegian bank accounts — Drop never holds customer money.

**Business Problem:** Residents of Norway are systematically overcharged for international money transfers (5-10% fees) and local merchants pay excessive payment processing fees to Vipps (1.75-2.75%), with no single app combining both needs affordably.

**Proposed Solution:** A BankID-native mobile payment app leveraging PSD2 Open Banking to initiate payments directly from users' bank accounts — eliminating the need for wallets, top-ups, or money holding — at fees 10-20x lower than existing remittance providers.

**Expected Outcomes:**
- 3,000 users and 200 merchants by Month 12 post-launch
- 130,000 NOK Monthly Recurring Revenue by Month 12
- ALAI Holding AS generates sustainable product revenue independent of consulting
- Drop becomes the default remittance + QR payment tool in Norwegian immigrant communities

**Investment:** ~250,000 NOK | **Timeline:** ~20 weeks (Phases 0.5–3) | **Priority:** High

---

## 2. Business Objectives & Goals

| ID | Objective | Description | Target | Timeframe |
|----|-----------|-------------|--------|-----------|
| BO-01 | Generate product revenue | Establish recurring transaction fee revenue for ALAI | 130,000 NOK MRR | Month 12 post-launch |
| BO-02 | Capture remittance market share | Become preferred app for Norwegian residents sending money abroad | 3,000 active users | Month 12 post-launch |
| BO-03 | Onboard local merchants | Establish QR payment network with local businesses | 200 merchants | Month 12 post-launch |
| BO-04 | Demonstrate AI-native product development | Drop proves ALAI can build fintech products at 10K NOK dev cost | MVP shipped in < 8 weeks | 2026-04-01 |
| BO-05 | Secure regulatory compliance | Obtain PISP/AISP registration with Finanstilsynet | Registration submitted | 2026-05-15 |

**Alignment to Strategic Goals:**
- **ALAI product revenue:** Drop is ALAI's first internal SaaS product, reducing dependence on consulting revenue
- **Innovasjon Norge grant:** Drop is the flagship product for the 150K NOK Oppstartstilskudd application

---

## 3. Current State Analysis (AS-IS)

### 3.1 Current Process Overview

Norwegian residents who need to send money internationally currently use Western Union, MoneyGram, or Wise. Each requires account setup, separate registration, and charges significantly higher fees. For local payments, Vipps dominates — but charges merchants 1.75-2.75% per transaction. No single app serves both needs.

### 3.2 AS-IS Process Flow (Remittance)

```mermaid
flowchart LR
    A([User needs to send money abroad]) --> B[Open Western Union / Wise app]
    B --> C[Register / log in]
    C --> D[Enter recipient details + bank account]
    D --> E[Enter amount]
    E --> F{Fee check — 5-10%}
    F -->|Accept| G[Pay with card / bank transfer]
    F -->|Too expensive| H[Try alternative — multiple apps]
    G --> I[Money transfers in 1-3 business days]
    H --> B
    I --> J([Recipient receives funds])
```

### 3.3 Current Systems & Tools

| System / Tool | Purpose | Users | Limitations |
|--------------|---------|-------|-------------|
| Western Union | International remittance | ~500K Norwegians | 5-10% fees; outdated UX; physical location required |
| Wise | International transfers | Tech-savvy immigrants | 0.7-1.5% fees; no QR payments; not community-focused |
| Vipps | Local payments | 5M+ Norwegians | No remittance; 1.75-2.75% merchant fees; no international |
| Revolut | Multi-currency | Young professionals | Complex; no QR; not trusted by older communities |
| MoneyGram | Remittance | Diaspora | 4-8% fees; physical agents; poor UX |
| Manual (cash / hawala) | Informal remittance | Undocumented users | Unregulated; no tracking; risk |

### 3.4 Current State Pain Points

| # | Pain Point | Category | Affected Users | Business Impact | Severity |
|---|-----------|----------|---------------|-----------------|----------|
| PP-01 | Remittance fees of 5-10% (vs technically possible < 1%) | Financial | ~500K immigrants in Norway | ~285M NOK/year overcharged on 5.7B NOK market | High |
| PP-02 | Vipps merchant fees 1.75-2.75% cut into margins | Financial | ~195K Norwegian SMEs | Kebab shop at 50K NOK/month pays up to 1,375 NOK in fees | High |
| PP-03 | Multiple apps needed — remittance app + payment app | UX | All users | Friction; low adoption; no flywheel | Medium |
| PP-04 | Existing apps require top-up / wallet — not trusted | Trust | Immigrant communities | Lower conversion; money movement risk | High |
| PP-05 | No app designed for Norwegian immigrant community trust | Cultural | ~1M immigrants | Generic apps have low cultural fit; word-of-mouth weak | Medium |

### 3.5 Current State Metrics (Baseline)

| Metric | Current Value | Source | Notes |
|--------|-------------|--------|-------|
| Average remittance fee from Norway | 5-10% | World Bank 2025 | WU/MoneyGram dominant |
| Remittance market size (Norway) | 5.7B NOK/year | World Bank | Total outbound |
| Vipps merchant fee | 1.75-2.75% | Vipps pricing 2026 | Per transaction |
| Wise fee (NOK corridor) | 0.7-1.5% | Wise website 2026 | Cheapest legal alternative |
| Drop target fee (remittance) | 0.5% | Internal model | PSD2 pass-through enables |
| Drop target fee (QR) | 1% | Internal model | vs Vipps 1.75-2.75% |

---

## 4. Future State Vision (TO-BE)

### 4.1 Future State Description

A resident of Norway opens Drop, verifies via BankID once, links their Norwegian bank account, and can immediately send money to Serbia, Pakistan, or Poland at 0.5% — directly from their bank account. No top-up, no wallet, no holding period. The recipient gets cash or bank transfer within 1-2 business days. Later, the same user walks into a local kebab shop, scans the Drop QR code at the counter, and pays 129 NOK — faster than tapping a card, with the shop paying just 1.29 NOK in fees.

### 4.2 TO-BE Process Flow (Remittance)

```mermaid
flowchart LR
    A([User opens Drop]) --> B[BankID verification — once]
    B --> C[Select: Send Money]
    C --> D[Choose country + recipient]
    D --> E[Enter amount — see fee 0.5%]
    E --> F[Confirm — PISP initiates from bank]
    F --> G[Drop backend processes via BaaS]
    G --> H[Recipient bank/cash pickup]
    H --> I([Recipient receives in 1-2 days])
```

### 4.3 Key Improvements

| Area | AS-IS | TO-BE | Improvement |
|------|-------|-------|-------------|
| Remittance fee | 5-10% | 0.5% | 10-20x cheaper |
| QR merchant fee | 1.75-2.75% (Vipps) | 1% | 43-63% cheaper |
| Apps needed | 2+ (remittance + payment) | 1 (Drop) | Single app flywheel |
| Money held by app | Yes (wallet top-up) | No (bank stays in bank) | Better user trust |
| BankID integration | No (separate app) | Yes (native SCA) | Norwegian-native UX |
| Onboarding time | 15-20 minutes | < 3 minutes | 80%+ faster |

---

## 5. Market Analysis & Competitive Landscape

### 5.1 Market Context

Norway has ~1,000,000 immigrants (SSB 2025) who send 5.7 billion NOK abroad annually via remittance. Additionally, ~195,000 SMEs in Norway accept payments — predominantly via Vipps. The PSD2 Open Banking regulation enables new entrants to initiate payments directly from customer bank accounts (PISP) and read account data (AISP) without holding funds — enabling Drop's pass-through model.

### 5.2 Competitive Analysis

| Competitor | Solution Type | Key Features | Pricing | Our Advantage |
|-----------|--------------|-------------|---------|---------------|
| Western Union | Direct (remittance) | Global reach; cash pickup; brand recognition | 5-10% fee | 10-20x cheaper; better UX; digital-only |
| Wise | Direct (remittance) | 0.7-1.5% fee; multi-currency | 0.7-1.5% | Cheaper (0.5%); QR payments combo; community trust |
| Vipps | Direct (QR/local) | 5M users; ubiquitous in Norway | 1.75-2.75% merchant | Remittance combo; 43-63% cheaper merchant fee |
| Revolut | Indirect | Multi-feature; international | 0.5-1.5% | Simpler; Norwegian-native; QR payments |
| MoneyGram | Direct (remittance) | Global cash network | 4-8% | 8-16x cheaper; mobile-native |

### 5.3 Positioning

**Unique Value Proposition:** Drop is the only app in Norway combining remittance (0.5% fee) + QR merchant payments (1% fee), BankID-native, pass-through — money stays in your bank.
**Target Market:** All residents in Norway/Scandinavia who send money abroad or pay at local businesses
**Differentiators:** Only app doing both remittance + QR; PSD2 pass-through (no wallet); BankID-native; community trust

---

## 6. Stakeholder Needs Analysis

| Stakeholder Group | Primary Needs | Secondary Needs | Pain Points Addressed |
|------------------|--------------|----------------|----------------------|
| Consumer users (remittance) | Cheap, reliable international transfers | Easy onboarding; recipient doesn't need app | PP-01, PP-03, PP-04 |
| Consumer users (QR payments) | Fast, cheap local payments | Same app as remittance | PP-02, PP-03 |
| Merchants | Lower fees than Vipps; no terminal hardware | Daily payouts; dashboard analytics | PP-02 |
| Alem Bašić (ALAI CEO) | Product revenue; regulatory compliance | Investor/partnership readiness | BO-01, BO-05 |
| Finanstilsynet | PSD2 compliance; consumer protection | AML/KYC standards | BO-05 |
| BaaS partner (Swan/SpareBank1) | API adoption; transaction volume | Liability clarity | DEP-01 |

---

## 7. Business Requirements

| ID | Requirement | Description | Priority | Rationale | BO Ref |
|----|------------|-------------|----------|-----------|--------|
| BR-001 | BankID-based identity verification | Users must verify identity via Norwegian BankID before any transaction | Must Have | Legal (SCA), AML, age verification | BO-02, BO-05 |
| BR-002 | Minimum age enforcement (18+) | System must reject users under 18 based on BankID date of birth | Must Have | Norwegian financial law; PSD2 SCA | BO-05 |
| BR-003 | Remittance to 30+ countries | Users can send money to 30+ countries at 0.5% fee | Must Have | Core revenue stream (BO-01, BO-02) | BO-01 |
| BR-004 | QR merchant payments at 1% fee | Users can pay merchants by scanning QR code; 1% merchant fee | Must Have | Core revenue stream (BO-01, BO-03) | BO-01 |
| BR-005 | PSD2 pass-through model only | Drop NEVER holds customer money; all payments via PISP from user bank | Must Have | Avoids e-money licence requirement | BO-05 |
| BR-006 | Merchant onboarding (self-service) | Merchants can register, verify KYC, receive QR code in < 5 minutes | Must Have | Merchant adoption target (BO-03) | BO-03 |
| BR-007 | GDPR-compliant data handling | All user data stored and processed in compliance with GDPR | Must Have | Legal requirement; EU regulation | BO-05 |
| BR-008 | Real-time transaction notifications | Users and merchants receive push notifications for transactions | Should Have | User trust and merchant reconciliation | BO-02, BO-03 |
| BR-009 | Transaction history with filters | Users can view all transactions with date, type, amount filters | Should Have | User experience; AML audit trail | BO-02 |
| BR-010 | AISP balance view from linked bank | Users can view bank account balance in Drop without holding funds | Should Have | User trust; shows money stays in bank | BO-02 |
| BR-011 | Merchant analytics dashboard | Merchants can view transaction volume, fees, daily totals | Should Have | Merchant retention | BO-03 |
| BR-012 | Loyalty / rewards programme | Users earn points for remittance; redeem for fee discounts | Could Have | Flywheel growth; retention | BO-02 |
| BR-013 | Multi-language support (Norwegian + English) | App available in Norwegian and English | Could Have | Accessibility for all residents | BO-02 |
| BR-014 | Virtual card (feature-flagged) | Users can order virtual Mastercard linked to bank account | Won't Have (this release) | Requires card partner; Phase 4 | — |

---

## 8. Success Metrics & KPIs

| ID | KPI | Category | Baseline | Target | Measurement Method | Evaluation Date |
|----|-----|----------|----------|--------|--------------------|-----------------|
| KPI-01 | Monthly Recurring Revenue | Revenue | 0 NOK | 130,000 NOK/month | Transaction logs | Month 12 post-launch |
| KPI-02 | Registered users | Adoption | 0 | 3,000 | App analytics | Month 12 post-launch |
| KPI-03 | Onboarded merchants | Adoption | 0 | 200 | Merchant dashboard | Month 12 post-launch |
| KPI-04 | Remittance fee vs competitors | Competitiveness | 5-10% (WU) | 0.5% Drop | Fee schedule | Ongoing |
| KPI-05 | System uptime | Reliability | N/A | ≥ 99.5% | Monitoring | Ongoing post-launch |
| KPI-06 | Payment success rate | Quality | N/A | ≥ 99% | Transaction logs | Ongoing post-launch |
| KPI-07 | Onboarding completion rate | UX | N/A | ≥ 70% | Analytics funnel | 30 days post-launch |
| KPI-08 | Security score | Security | 57/100 (audit 2026-02-11) | ≥ 80/100 | Security audit | Pre-launch |

---

## 9. Business Rules & Constraints

### 9.1 Business Rules

| ID | Rule | Category | Source | Enforced By |
|----|------|----------|--------|-------------|
| RUL-001 | Minimum user age: 18 years | Legal | Norwegian financial law | BankID DOB validation |
| RUL-002 | Norwegian BankID required for all users | Legal | PSD2 SCA requirement | Onboarding flow |
| RUL-003 | Drop NEVER holds customer money | Business / Legal | ADR-003 (pass-through model) | Architecture; no wallet tables |
| RUL-004 | NEVER use word "banking" without licence disclaimer | Legal | Legal review 2026-02-08 | UI copy review |
| RUL-005 | Remittance fee: 0.5% of transaction amount | Financial | Business model | Transaction service |
| RUL-006 | QR merchant fee: 1% of transaction amount | Financial | Business model | Transaction service |
| RUL-007 | Minimum remittance: 100 NOK; Maximum: 50,000 NOK per transaction | Financial / AML | Internal policy + AML | Validation layer |
| RUL-008 | KYC approval required before first transaction | Legal | AML directive | KYC gate in transaction flow |
| RUL-009 | GDPR: User data must not leave EEA | Legal | GDPR | Infrastructure hosting |
| RUL-010 | PCI-DSS: Full card numbers/CVV must NEVER be stored or returned via API | Legal | PCI-DSS Level 1 | Cards service tokenisation |

### 9.2 Regulatory & Compliance Requirements

| Regulation | Applicability | Key Requirements | Responsible |
|------------|--------------|-----------------|-------------|
| PSD2 (EU) | Yes | PISP/AISP licence or operating under BaaS partner licence; SCA (BankID) | John + Legal + Finanstilsynet |
| GDPR | Yes | Data minimisation; right to deletion; consent; DPA with BaaS provider | John + Legal |
| AML / AMLD6 | Yes | KYC verification; transaction monitoring; suspicious activity reporting | John + KYC provider (Sumsub) |
| DORA (EU) | Yes | ICT risk management; incident reporting | John + Legal (2025 compliance deadline) |
| PCI-DSS | Partial | Card tokenisation; no CVV storage (cards feature only) | John + card partner |

### 9.3 Technical Constraints

- Must use Norwegian BankID for SCA (locks initial market to Norway)
- Must use PSD2 Open Banking (AISP/PISP) — no wallet/balance storage
- Must run on Vercel (landing) + Fly.io or equivalent (backend) — EEA data residency
- Database must migrate from SQLite to PostgreSQL at 200+ concurrent users
- All API endpoints must be rate-limited and CSRF-protected before production

---

## 10. Assumptions & Dependencies

### 10.1 Assumptions

| # | Assumption | Risk if False | Owner |
|---|-----------|--------------|-------|
| A-01 | BaaS partner (Swan or SpareBank1) confirmed by Phase 2 start | Phase 2 blocked indefinitely | Alem |
| A-02 | Finanstilsynet PISP/AISP registration process takes ~3 months | Launch delayed | Alem + Legal |
| A-03 | Target users have Norwegian BankID and Norwegian bank account | Onboarding conversion fails | Alem (user research) |
| A-04 | Open Banking PISP enables direct bank-to-bank transfers without holding | Architecture pivot required | John |

### 10.2 Dependencies

| # | Dependency | Type | Impact if Unavailable | Target Date | Status |
|---|-----------|------|----------------------|-------------|--------|
| DEP-01 | BaaS provider (Swan / SpareBank1) | External | Phase 2+ blocked | 2026-03-01 | SpareBank1 pitched; Swan backup |
| DEP-02 | Finanstilsynet PISP/AISP registration | External / Regulatory | Real payments blocked | 2026-05-15 | Not started |
| DEP-03 | BankID via BaaS | External | SCA blocked | After BaaS confirmed | Pending |
| DEP-04 | KYC provider (Sumsub) | External | AML compliance blocked | After BaaS confirmed | Mock in place |

---

## 11. ROI Analysis

### 11.1 Investment Summary

| Cost Category | One-Time (NOK) | Annual (NOK) | Notes |
|--------------|---------------|-------------|-------|
| Development (AI-first) | 10,000 | ~13,200 | Claude Code costs |
| Open Banking / BaaS setup | 15,000 | Variable | BaaS API costs scale with volume |
| Legal + compliance | 50,000 | ~20,000 | Ongoing compliance |
| Marketing | 100,000 | 360,000–600,000 | Scaled to growth |
| Infrastructure | 5,000 | 24,000 | Fly.io + Vercel |
| **Total Year 1** | **180,000** | **417,200–637,200** | |

### 11.2 Benefit Projections

| Benefit | Year 1 (NOK) | Year 2 (NOK) | Year 3 (NOK) | Confidence |
|---------|-------------|-------------|-------------|-----------|
| Remittance fee revenue | 360,000 | 960,000 | 1,800,000 | Medium |
| Merchant QR fee revenue | 1,200,000 | 3,000,000 | 6,000,000 | Medium |
| **Total Benefits** | **1,560,000** | **3,960,000** | **7,800,000** | |

### 11.3 ROI Summary

| Metric | Value |
|--------|-------|
| Total Investment (Year 1) | ~250,000 NOK |
| Net Benefit (Year 1) | ~1,310,000 NOK |
| Payback Period | 7-9 months |
| 3-Year ROI | ~1,800% |
| 3-Year NPV (discount rate: 10%) | ~9,500,000 NOK |

---

## 12. Implementation Roadmap

| Phase | Description | Key Deliverables | Duration | Success Criteria |
|-------|-------------|-----------------|----------|-----------------|
| Phase 0.5 — Hardening | Security fixes; architecture cleanup | All critical security issues fixed; 217 tests green; staging live | 2 weeks | Security score > 70; staging at drop-staging.fly.dev |
| Phase 1 — Demo App | Full 10-screen demo with mock Open Banking | Next.js app; all flows; BankID mock; investor-ready | 4 weeks | Demo presentable to investors and SpareBank1 |
| Phase 2 — Banking Integration | Real Open Banking; BankID; KYC | Real AISP + PISP; 10 beta users | 8 weeks | Real bank transfers working |
| Phase 3 — Launch | App Store; merchant onboarding; marketing | Live on iOS + Android; 200 merchants | 6 weeks | 1,000 users; revenue flowing |

---

## 13. Risk Assessment

| # | Risk | Probability | Business Impact | Mitigation |
|---|------|------------|-----------------|------------|
| BR-R01 | BaaS partner unavailable — revenue delayed | High | High | Multi-provider; Swan backup |
| BR-R02 | Regulatory delay (Finanstilsynet) | High | High | Early engagement; bank partner licence interim |
| BR-R03 | Vipps launches remittance — narrows moat | Medium | High | Community trust + fees advantage; accelerate adoption |
| BR-R04 | Slow merchant adoption — QR revenue lower than projected | Medium | Medium | Door-to-door; 0% fee launch offer |

> Full technical risk register: `[../PROJECT-GOVERNANCE/risk-register.md](../PROJECT-GOVERNANCE/risk-register.md)`

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | John (AI Director) | 2026-02-08 | Approved (AI) |
| Business Analyst | product agent | 2026-02-08 | Approved (AI) |
| Product Owner | John | 2026-02-08 | Approved |
| AI Director (John) | John | 2026-02-23 | Approved |
| CEO (Alem) | Alem Bašić | 2026-02-08 | Approved |

# Non-Functional Requirements (NFR): Drop — Fintech Payment App

# Non-Functional Requirements (NFR): Drop — Fintech Payment App

> **Project:** Drop — Remittance + QR Payments
> **Version:** 1.0
> **Date:** 2026-02-23
> **Author:** John (AI Director)
> **Status:** Approved
> **Reviewers:** Alem Bašić (CEO)

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1 | 2026-02-23 | John | Initial draft; targets from security audit + business case |

---

## 1. NFR Overview

| Category | # Requirements | Highest Priority | Owner |
|----------|---------------|-----------------|-------|
| Performance | 6 | Must Have | John (Tech Lead) |
| Scalability | 4 | Must Have | John / DevOps |
| Availability | 6 | Must Have | John / DevOps |
| Security | 12 | Critical | John + Security agent |
| Reliability | 5 | Must Have | John |
| Usability | 5 | Should Have | John (Designer) |
| Compatibility | 4 | Must Have | John |
| Maintainability | 5 | Should Have | John |
| Compliance | 8 | Critical | John + Legal |
| Data | 5 | Must Have | John |

---

## 2. Performance Requirements

| ID | Requirement | Metric | Target | Measurement Conditions | Method | Priority |
|----|------------|--------|--------|----------------------|--------|----------|
| NFR-P01 | Page load time (initial) | Time to Interactive | < 3 seconds | 4G connection, cold cache | Lighthouse | Must Have |
| NFR-P02 | API response time (standard) | p95 response time | < 500ms | Normal load (200 concurrent users) | APM / k6 | Must Have |
| NFR-P03 | API response time (bcrypt operations) | p95 response time | < 1,000ms | Normal load | Benchmark tests | Must Have |
| NFR-P04 | Database query time | p95 query time | < 10ms (SELECT), < 20ms (INSERT) | Normal load | api-benchmarks.test.ts | Must Have |
| NFR-P05 | Core Web Vitals: LCP | Largest Contentful Paint | < 2.5 seconds | Mobile, 4G | Lighthouse | Must Have |
| NFR-P06 | 50 concurrent rate limit checks | Total time | < 2,000ms total | 50 concurrent calls | api-benchmarks.test.ts | Should Have |

---

## 3. Scalability Requirements

| ID | Requirement | Metric | MVP Target | Phase 2 Target | Method | Priority |
|----|------------|--------|-----------|----------------|--------|----------|
| NFR-S01 | Concurrent users | Active sessions | 200 users (SQLite limit) | 5,000+ users (PostgreSQL) | Load testing | Must Have |
| NFR-S02 | Database migration trigger | Concurrent users | Migrate at 200 concurrent | PostgreSQL in Phase 2 | Monitoring | Must Have |
| NFR-S03 | API rate limits | Max requests per IP | 10 req/min (auth), 60 req/min (general) | Same | Rate limiter config | Must Have |
| NFR-S04 | Storage growth | DB size | < 1GB on Fly.io persistent volume | Managed PostgreSQL | Storage monitoring | Should Have |

---

## 4. Availability Requirements

| ID | Requirement | Target | Period | Exclusions | Priority |
|----|------------|--------|--------|------------|----------|
| NFR-A01 | System uptime SLA | ≥ 99.5% | Monthly rolling | Scheduled maintenance (advance notice) | Must Have |
| NFR-A02 | Scheduled maintenance window | Max 4 hours/month | Monthly | Tue-Thu 02:00-06:00 CET preferred | Must Have |
| NFR-A03 | Maintenance notice lead time | ≥ 24 hours | Per event | Emergency patches: ASAP notify | Must Have |
| NFR-A04 | RPO (Recovery Point Objective) | Max 24 hours data loss | Per incident | Daily backup schedule | Must Have |
| NFR-A05 | RTO (Recovery Time Objective) | System restored within 4 hours | Per incident | For staging; production target 2 hours | Must Have |
| NFR-A06 | Database backup | Daily automated backup | Ongoing | Fly.io persistent volume | Must Have |

**SLA Reference:**
| Uptime % | Monthly Downtime |
|----------|----------------|
| 99.9% | 43.8 minutes |
| 99.5% | 3.6 hours |
| 99.0% | 7.3 hours |

---

## 5. Security Requirements

**Context:** Drop is a fintech app handling real money flows. Security is Critical priority. See `security/drop-security-rapport.md` for full audit (score: 57/100 pre-Phase 0.5; target: 80/100 post-hardening).

| ID | Requirement | Category | Target / Standard | Method | Priority |
|----|------------|----------|------------------|--------|----------|
| NFR-SEC01 | Authentication | Auth | JWT (jose library) in httpOnly cookie; SameSite=Strict; 7-day expiry | Code review + audit | Must Have |
| NFR-SEC02 | Password hashing | Auth | bcrypt, 12 rounds; NO SHA-256 fallback | auth.test.ts | Must Have |
| NFR-SEC03 | JWT secret | Secrets | JWT_SECRET must be set via env var — fail fast if missing | Code review | Must Have |
| NFR-SEC04 | CSRF protection | Injection | CSRF middleware on all POST/PATCH/DELETE endpoints | Code review + test | Must Have |
| NFR-SEC05 | Rate limiting | Abuse | 10 req/min on auth; 60/min general; persistent (DB-backed, not in-memory) | middleware.test.ts | Must Have |
| NFR-SEC06 | Input validation | Injection | All inputs sanitized server-side; parameterized SQL (no raw queries) | validation.test.ts | Must Have |
| NFR-SEC07 | XSS prevention | Injection | CSP headers (script-src 'self'); no dangerouslySetInnerHTML | OWASP ZAP | Must Have |
| NFR-SEC08 | Security headers | HTTP | HSTS, X-Frame-Options: DENY, X-Content-Type-Options: nosniff, CSP | securityheaders.com | Must Have |
| NFR-SEC09 | Card data | PCI-DSS | NEVER store or return full card number or CVV; only last_four + token_ref | Code review + db.test.ts | Must Have |
| NFR-SEC10 | Audit logging | Compliance | All auth events, transactions, KYC changes logged with user_id + IP + timestamp | Code review | Must Have |
| NFR-SEC11 | Per-user transaction locks | Financial | Concurrent transactions from same user serialised; no double-spend | Integration test | Must Have |
| NFR-SEC12 | Penetration testing | Operations | External pentest before production launch | Third-party report | Should Have |

---

## 6. Reliability Requirements

| ID | Requirement | Metric | Target | Method | Priority |
|----|------------|--------|--------|--------|----------|
| NFR-R01 | Application error rate | 5xx errors / total requests | < 0.1% | Monitoring | Must Have |
| NFR-R02 | Transaction integrity | Atomic transactions | ACID compliance; no partial updates | db.test.ts | Must Have |
| NFR-R03 | MTTR | Average recovery time | < 4 hours | Incident log | Must Have |
| NFR-R04 | Data integrity | Database constraints | Zero orphaned records; FK constraints enabled | db.test.ts | Must Have |
| NFR-R05 | Health check | System observability | GET /api/health returns 200 with DB status | CI smoke tests | Must Have |

---

## 7. Usability Requirements

| ID | Requirement | Target | Method | Priority |
|----|------------|--------|--------|----------|
| NFR-U01 | Onboarding completion | New user completes onboarding (3 steps) in < 3 minutes | Usability testing | Must Have |
| NFR-U02 | Remittance flow time | Registered user sends money in < 2 minutes | Usability testing | Must Have |
| NFR-U03 | Mobile responsiveness | Fully functional on 375px–1440px (primary: 375-428px mobile) | Manual + automated | Must Have |
| NFR-U04 | Error recovery | User can recover from any form error without page reload | Manual testing | Must Have |
| NFR-U05 | Language | Norwegian (primary) and English (secondary) | Content audit | Should Have |

---

## 8. Compatibility Requirements

| ID | Requirement | Category | Target | Priority |
|----|------------|----------|--------|----------|
| NFR-C01 | Web browsers | Browser | Chrome 100+, Firefox 100+, Safari 16+, Edge 100+ | Must Have |
| NFR-C02 | Mobile browsers | Browser | Safari iOS 15+, Chrome Android 100+ (primary platform) | Must Have |
| NFR-C03 | Screen resolutions | Responsive | 375px (iPhone SE) to 1440px (desktop); mobile-first | Must Have |
| NFR-C04 | API versioning | API | Next.js API Routes (no versioning in MVP); semantic versioning in Phase 2 | Should Have |

---

## 9. Maintainability Requirements

| ID | Requirement | Metric | Target | Method | Priority |
|----|------------|--------|--------|--------|----------|
| NFR-M01 | Test coverage | % code covered | ≥ 80% overall; 100% for auth + transaction paths | CI coverage (Vitest) | Must Have |
| NFR-M02 | CI/CD pipeline | Deployment frequency | Bug fix to staging in < 30 minutes from merge | GitHub Actions | Must Have |
| NFR-M03 | Feature flags | Feature control | All gated features controllable via env vars without redeploy | feature-flags.test.ts | Should Have |
| NFR-M04 | Documentation currency | Doc coverage | All API endpoints documented in docs/backend/API-REFERENCE.md | Doc review | Should Have |
| NFR-M05 | Dependency currency | CVE exposure | 0 critical CVEs in production dependencies | npm audit in CI | Must Have |

---

## 10. Compliance Requirements

| ID | Regulation | Applicability | Requirement | Technical Implementation | Priority |
|----|-----------|--------------|-------------|------------------------|----------|
| NFR-COMP01 | GDPR (EU) | Yes — Norwegian users | Lawful basis; right to deletion; DPA with BaaS; 72h breach notification | Data deletion API; audit logs; DPA contract | Must Have |
| NFR-COMP02 | GDPR — Data minimisation | Yes | Collect only data necessary for stated purpose | BA review of DB schema | Must Have |
| NFR-COMP03 | PSD2 (EU) | Yes — payment initiation | PISP/AISP registration with Finanstilsynet; or operate under bank partner licence | Finanstilsynet registration | Must Have |
| NFR-COMP04 | AML / AMLD6 | Yes — money transfer | KYC verification before transaction; transaction monitoring; SAR capability | Sumsub integration; monitoring alerts | Must Have |
| NFR-COMP05 | PCI-DSS | Partial (cards feature) | No card number/CVV storage; tokenisation only | last_four + token_ref only; tokenisation via partner | Must Have |
| NFR-COMP06 | DORA (EU) | Yes | ICT risk management; incident reporting framework | Incident report template; business continuity | Should Have |
| NFR-COMP07 | Norwegian Personvernloven | Yes | National GDPR implementation; same requirements | Legal review | Must Have |
| NFR-COMP08 | Financial licence disclaimer | Yes | NEVER use "banking" without licence disclaimer in UI | UI copy review; `/learning-opportunity` on violations | Must Have |

---

## 11. Data Requirements

| ID | Requirement | Category | Target | Implementation | Priority |
|----|------------|----------|--------|---------------|----------|
| NFR-D01 | Data retention — user data | Retention | User data deleted within 30 days of account deletion request | Scheduled deletion job (GDPR Art.17) | Must Have |
| NFR-D02 | Data retention — audit logs | Retention | Audit logs: 5 years (AML requirement) | Log rotation policy | Must Have |
| NFR-D03 | PII field documentation | Privacy | All PII fields identified in DATABASE-SCHEMA.md | Data dictionary in docs/backend/ | Must Have |
| NFR-D04 | Data anonymisation (non-prod) | Privacy | No real user data in staging/dev environments | Seed data only; no prod data migration | Must Have |
| NFR-D05 | GDPR data export | Portability | User can export their data (GDPR Art.20) | Data export endpoint | Should Have |

---

## 12. NFR Testing & Verification Plan

| NFR Category | Testing Method | Tools | Frequency | Pass Criteria |
|-------------|---------------|-------|-----------|---------------|
| Performance | Benchmark tests + load testing | api-benchmarks.test.ts, Lighthouse | Per sprint + pre-launch | All NFR-P targets met |
| Security | Security audit + automated tests | validation.test.ts, OWASP ZAP, external pentest | Per sprint + pre-launch | Score ≥ 80/100; no critical open |
| Availability | Uptime monitoring | Fly.io metrics, health endpoint | Ongoing | ≥ 99.5% monthly |
| Compliance | Legal review + audit | Manual + Sumsub | Pre-launch + annual | All compliance items verified |
| Reliability | Unit + integration tests | Vitest (db.test.ts) | Per commit | Zero failed integrity tests |

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | John (AI Director) | 2026-02-23 | Approved (AI) |
| Tech Lead | John | 2026-02-23 | Approved |
| AI Director (John) | John | 2026-02-23 | Approved |
| CEO (Alem) | Alem Bašić | TBD | |

# Non-Functional Requirements

# Non-Functional Requirements (NFR): {{PROJECT_NAME}}

> **Project:** {{PROJECT_NAME}}
> **Version:** {{VERSION}}
> **Date:** {{DATE}}
> **Author:** {{AUTHOR}}
> **Status:** Draft | In Review | Approved
> **Reviewers:** {{REVIEWERS}}

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1     | {{DATE}} | {{AUTHOR}} | Initial draft |

---

<!-- GUIDANCE: Non-functional requirements define HOW WELL the system performs its functions.
They are quality attributes — measurable SLAs and constraints that must be met in production.
Every NFR must have a specific, measurable target (not "fast" but "< 2 seconds at p95").
NFRs drive architecture decisions; involve the Tech Lead in defining targets. -->

## 1. NFR Overview

| Category | # Requirements | Highest Priority | Owner |
|----------|---------------|-----------------|-------|
| Performance | {{COUNT}} | {{HIGH/MED/LOW}} | Tech Lead |
| Scalability | {{COUNT}} | | Tech Lead / DevOps |
| Availability | {{COUNT}} | | DevOps |
| Security | {{COUNT}} | Critical | Tech Lead + Security |
| Reliability | {{COUNT}} | | Tech Lead / DevOps |
| Usability | {{COUNT}} | | Designer |
| Compatibility | {{COUNT}} | | Tech Lead |
| Maintainability | {{COUNT}} | | Tech Lead |
| Compliance | {{COUNT}} | | Tech Lead + Legal |
| Data | {{COUNT}} | | Tech Lead |

---

## 2. Performance Requirements

<!-- GUIDANCE: Performance requirements prevent "it works but it's slow" deployments.
Define targets under realistic load conditions, not best-case empty-server scenarios.
p95 = 95th percentile (95% of requests must complete within this time). -->

| ID | Requirement | Metric | Target | Measurement Conditions | Measurement Method | Priority |
|----|------------|--------|--------|----------------------|-------------------|----------|
| NFR-P01 | Page load time (initial) | Time to Interactive | < 3 seconds | 4G connection, cold cache | Lighthouse / WebPageTest | Must Have |
| NFR-P02 | Page load time (subsequent) | Time to Interactive | < 1.5 seconds | Warm cache | Lighthouse | Must Have |
| NFR-P03 | API response time (standard) | p95 response time | < 500ms | Normal load ({{CONCURRENT_USERS}} users) | APM tool / k6 | Must Have |
| NFR-P04 | API response time (complex queries) | p95 response time | < 2 seconds | Normal load | APM tool | Should Have |
| NFR-P05 | Database query time | p95 query time | < 100ms | Normal load | DB monitoring | Must Have |
| NFR-P06 | File upload throughput | Upload speed | {{SIZE}}MB in < {{TIME}}s | Single user | Load testing | {{PRIORITY}} |
| NFR-P07 | Search response time | p95 response time | < 1 second | Normal load | APM tool | Should Have |
| NFR-P08 | Report generation | Completion time | < {{TIME}} seconds | Normal load | APM tool | Could Have |
| NFR-P09 | Core Web Vitals: LCP | Largest Contentful Paint | < 2.5 seconds | Mobile, 4G | Lighthouse | Must Have |
| NFR-P10 | Core Web Vitals: CLS | Cumulative Layout Shift | < 0.1 | Any device | Lighthouse | Must Have |

---

## 3. Scalability Requirements

<!-- GUIDANCE: Scalability requirements ensure the system grows with usage.
Define targets for launch AND for projected growth 12-24 months out.
Horizontal scaling (more instances) is generally preferred over vertical (bigger server). -->

| ID | Requirement | Metric | Launch Target | 12-Month Target | Measurement Method | Priority |
|----|------------|--------|-------------|----------------|-------------------|----------|
| NFR-S01 | Concurrent users | Simultaneous active sessions | {{X}} users | {{X}} users | Load testing (k6/JMeter) | Must Have |
| NFR-S02 | Peak load handling | Requests per second | {{X}} RPS | {{X}} RPS | Load testing | Must Have |
| NFR-S03 | Data volume growth | Database size growth | {{X}}GB/year | {{X}}GB/year | Storage monitoring | Should Have |
| NFR-S04 | API rate limits | Max requests per user/hour | {{X}} requests | {{X}} requests | API gateway metrics | Must Have |
| NFR-S05 | File storage growth | Storage volume | {{X}}GB | {{X}}GB | Storage monitoring | Should Have |
| NFR-S06 | Auto-scaling response | Time to scale out under load | < 2 minutes | < 2 minutes | Cloud console metrics | Should Have |
| NFR-S07 | Geographic distribution | Regions supported | {{REGIONS}} | {{REGIONS}} | CDN configuration | {{PRIORITY}} |

---

## 4. Availability Requirements

<!-- GUIDANCE: Availability requirements define uptime expectations and maintenance windows.
Calculate SLA targets carefully: 99.9% = 8.7 hours downtime/year; 99.5% = 43.8 hours/year.
Scheduled maintenance windows are EXCLUDED from SLA calculations if agreed in advance. -->

| ID | Requirement | Target | Measurement Period | Exclusions | Priority |
|----|------------|--------|-------------------|------------|----------|
| NFR-A01 | System uptime SLA | ≥ {{99.5 / 99.9}}% | Monthly rolling | Scheduled maintenance | Must Have |
| NFR-A02 | Scheduled maintenance window | Max {{X}} hours/month | Monthly | {{PREFERRED_WINDOW}} | Must Have |
| NFR-A03 | Maintenance notification lead time | ≥ 48 hours notice | Per event | Emergency patches: 4 hours | Must Have |
| NFR-A04 | RPO (Recovery Point Objective) | Max {{X}} hours data loss | Per incident | N/A | Must Have |
| NFR-A05 | RTO (Recovery Time Objective) | System restored within {{X}} hours | Per incident | N/A | Must Have |
| NFR-A06 | Database backup frequency | Every {{X}} hours | Ongoing | N/A | Must Have |
| NFR-A07 | Backup retention | {{X}} days rolling | Ongoing | N/A | Must Have |
| NFR-A08 | Disaster recovery test | Pass DR drill | Annually | N/A | Should Have |

**SLA Calculation Reference:**
| Uptime % | Annual Downtime | Monthly Downtime |
|----------|----------------|-----------------|
| 99.9% | 8.7 hours | 43.8 minutes |
| 99.5% | 43.8 hours | 3.6 hours |
| 99.0% | 87.6 hours | 7.3 hours |

---

## 5. Security Requirements

<!-- GUIDANCE: Security requirements are non-negotiable. Define concrete measures, not aspirations.
Every web application must address at minimum: authentication, authorization, data encryption,
input validation, audit logging, and secure dependency management.
Reference OWASP Top 10 for web; adjust for your specific context. -->

| ID | Requirement | Category | Target / Standard | Measurement Method | Priority |
|----|------------|----------|------------------|-------------------|----------|
| NFR-SEC01 | Authentication method | Auth | {{JWT/OAuth2/OIDC}} + MFA optional | Code review + pentest | Must Have |
| NFR-SEC02 | Password policy | Auth | Min 8 chars, 1 uppercase, 1 number, 1 special | Automated test | Must Have |
| NFR-SEC03 | Session management | Auth | Timeout: 30min idle; absolute: 8 hours | Automated test | Must Have |
| NFR-SEC04 | Data encryption in transit | Encryption | TLS 1.3 minimum | SSL Labs scan (grade A+) | Must Have |
| NFR-SEC05 | Data encryption at rest | Encryption | AES-256 for PII; database encryption | Infrastructure review | Must Have |
| NFR-SEC06 | Input validation | Injection Prevention | All inputs sanitized server-side; parameterized queries | Code review + SAST | Must Have |
| NFR-SEC07 | XSS prevention | Injection Prevention | CSP headers; output encoding | OWASP ZAP / DAST | Must Have |
| NFR-SEC08 | CSRF protection | Injection Prevention | CSRF tokens on all state-changing requests | Code review | Must Have |
| NFR-SEC09 | Rate limiting | DDoS/Abuse | API: {{X}} req/min per IP; login: 5 attempts/15min | Load testing | Must Have |
| NFR-SEC10 | Audit logging | Compliance | All auth events, data mutations logged with user + timestamp | Log review | Must Have |
| NFR-SEC11 | Dependency security | Supply Chain | No known critical CVEs in dependencies | Automated scan (Snyk/Dependabot) | Must Have |
| NFR-SEC12 | Secret management | Secrets | No secrets in code/git; use env vars or vault | Code scan + git history check | Must Have |
| NFR-SEC13 | Role-based access control | Authorization | Principle of least privilege; no role escalation | Code review + penetration test | Must Have |
| NFR-SEC14 | Security headers | HTTP Security | HSTS, X-Frame-Options, X-Content-Type-Options | securityheaders.com scan | Must Have |
| NFR-SEC15 | Vulnerability scanning | Operations | Automated scan in CI; critical issues block deploy | CI pipeline | Should Have |
| NFR-SEC16 | Penetration testing | Operations | Annual external pentest | Third-party report | Should Have |

---

## 6. Reliability Requirements

<!-- GUIDANCE: Reliability is the probability of the system performing its intended function
without failure over a specified period. Define acceptable error rates and failure recovery. -->

| ID | Requirement | Metric | Target | Measurement Method | Priority |
|----|------------|--------|--------|-------------------|----------|
| NFR-R01 | Application error rate | 5xx errors / total requests | < 0.1% | APM monitoring | Must Have |
| NFR-R02 | Client-side error rate | JS errors per session | < 1% of sessions | Error tracking (Sentry) | Should Have |
| NFR-R03 | MTBF (Mean Time Between Failures) | Average time between incidents | > {{X}} days | Incident tracking | Should Have |
| NFR-R04 | MTTR (Mean Time To Recovery) | Average time to restore service | < {{X}} hours | Incident tracking | Must Have |
| NFR-R05 | Data integrity | Zero data corruption events | 0 incidents | Database integrity checks | Must Have |
| NFR-R06 | Transaction integrity | Atomic transactions | ACID compliance | Database tests | Must Have |
| NFR-R07 | Graceful degradation | Partial failure handling | Non-critical features fail gracefully; core stays up | Chaos testing | Should Have |
| NFR-R08 | Health check endpoint | System health observable | /health returns 200 when healthy | Monitoring | Must Have |

---

## 7. Usability Requirements

<!-- GUIDANCE: Usability requirements ensure the system is accessible and easy to use.
These directly impact user adoption (KPI-02) and satisfaction (KPI-04). -->

| ID | Requirement | Target | Measurement Method | Priority |
|----|------------|--------|-------------------|----------|
| NFR-U01 | Time to complete core task | New user completes {{KEY_TASK}} in < {{X}} minutes | Usability testing | Must Have |
| NFR-U02 | Error recovery | User can recover from any error without help | Usability testing | Must Have |
| NFR-U03 | WCAG compliance | WCAG 2.1 Level AA | Automated axe-core + manual review | Must Have |
| NFR-U04 | Keyboard navigation | All interactive elements reachable by keyboard | Manual testing | Must Have |
| NFR-U05 | Screen reader support | Compatible with NVDA / VoiceOver | Manual testing | Should Have |
| NFR-U06 | Mobile responsiveness | Fully functional on 375px–1440px width | Manual + automated | Must Have |
| NFR-U07 | Color contrast | ≥ 4.5:1 for normal text; ≥ 3:1 for large text | Contrast checker | Must Have |
| NFR-U08 | Onboarding completion | {{X}}% of new users complete onboarding | Analytics | Should Have |
| NFR-U09 | Help / documentation | All key features documented in-app or in help center | Content audit | Should Have |

---

## 8. Compatibility Requirements

<!-- GUIDANCE: Define supported platforms explicitly. "It should work everywhere" is not a requirement.
Use market share data to prioritize browser/OS targets. -->

| ID | Requirement | Category | Target | Priority |
|----|------------|----------|--------|----------|
| NFR-C01 | Web browsers | Browser | Chrome 100+, Firefox 100+, Safari 16+, Edge 100+ | Must Have |
| NFR-C02 | Mobile browsers | Browser | Safari iOS 15+, Chrome Android 100+ | Must Have |
| NFR-C03 | Mobile operating systems | OS | iOS 15+, Android 11+ | Must Have |
| NFR-C04 | Desktop operating systems | OS | Windows 10+, macOS 12+, Ubuntu 20.04+ | Must Have |
| NFR-C05 | Screen resolutions | Responsive | 375px to 2560px width | Must Have |
| NFR-C06 | Minimum device specs | Performance | Works on mid-range 2020+ devices | Should Have |
| NFR-C07 | Third-party integrations | API | {{EXTERNAL_SYSTEM}} API version {{VERSION}} | Must Have |
| NFR-C08 | Email clients | Email | Gmail, Outlook, Apple Mail, mobile clients | Should Have |

---

## 9. Maintainability Requirements

<!-- GUIDANCE: Maintainability requirements ensure the codebase can be evolved over time without
exponential cost increases. These protect the long-term investment. -->

| ID | Requirement | Metric | Target | Measurement Method | Priority |
|----|------------|--------|--------|-------------------|----------|
| NFR-M01 | Test coverage | % of code covered by automated tests | ≥ 80% overall; ≥ 95% for critical paths | CI coverage report | Must Have |
| NFR-M02 | Code documentation | % of public APIs documented | 100% of public APIs | Code review | Must Have |
| NFR-M03 | Cyclomatic complexity | Per-function complexity | Max 10 per function; refactor if exceeded | Static analysis (SonarQube) | Should Have |
| NFR-M04 | Dependency currency | % of dependencies on current major version | ≥ 80% current; 0 dependencies with critical CVEs | Automated scan | Should Have |
| NFR-M05 | Deployment frequency | Time to deploy a bug fix to production | < 1 hour from merge | CI/CD metrics | Should Have |
| NFR-M06 | Feature flag support | Ability to disable features without deploy | Available for all major features | Code review | Could Have |
| NFR-M07 | Logging completeness | Log coverage for operations | All external calls, errors, and user mutations logged | Log review | Must Have |
| NFR-M08 | Monitoring observability | Dashboards for key metrics | Dashboards for error rate, response time, uptime | Monitoring tool | Must Have |

---

## 10. Compliance Requirements

<!-- GUIDANCE: Compliance requirements are legal obligations — failure can result in penalties.
Identify which apply to your system and document specific technical implementations required. -->

| ID | Regulation | Applicability | Requirement | Technical Implementation | Priority |
|----|-----------|--------------|-------------|------------------------|----------|
| NFR-COMP01 | GDPR | {{YES — if handling EU personal data}} | Lawful basis for processing; right to deletion; DPA required; breach notification within 72h | User data deletion API; audit logs; DPA in place | Must Have |
| NFR-COMP02 | GDPR — Cookie consent | {{YES — if using tracking cookies}} | Explicit consent before non-essential cookies | Cookie consent banner; opt-in only tracking | Must Have |
| NFR-COMP03 | GDPR — Data minimization | Yes | Collect only data necessary for stated purpose | BA review of data model | Must Have |
| NFR-COMP04 | {{HIPAA}} | {{YES/NO — healthcare data}} | PHI protection; audit logs; BAA required | Role-based access; encrypted PHI fields | {{PRIORITY}} |
| NFR-COMP05 | {{PCI-DSS}} | {{YES/NO — payment card data}} | SAQ compliance; tokenization; no card storage | Stripe/payment gateway tokenization | {{PRIORITY}} |
| NFR-COMP06 | Norwegian Personvernloven | {{YES}} | Alignment with GDPR national implementation | Legal review | Must Have |
| NFR-COMP07 | WCAG 2.1 AA | {{YES}} | Digital accessibility | NFR-U01 to NFR-U07 | Must Have |

---

## 11. Data Requirements

<!-- GUIDANCE: Data requirements define how the system handles data throughout its lifecycle.
Often overlooked — data governance failures are costly (GDPR fines, data loss). -->

| ID | Requirement | Category | Target | Implementation | Priority |
|----|------------|----------|--------|---------------|----------|
| NFR-D01 | Data retention — user data | Retention | {{X}} years active; deleted within 30 days of account deletion request | Scheduled deletion job | Must Have |
| NFR-D02 | Data retention — logs | Retention | Application logs: 90 days; Audit logs: 3 years | Log rotation policy | Must Have |
| NFR-D03 | Database backup frequency | Backup | Full backup daily; transaction logs every {{X}} hours | Automated backup schedule | Must Have |
| NFR-D04 | Backup encryption | Backup | Backups encrypted with AES-256 | Infrastructure config | Must Have |
| NFR-D05 | Data integrity checks | Integrity | Database constraints; no orphaned records | DB schema + integration tests | Must Have |
| NFR-D06 | PII identification | Privacy | All PII fields identified and documented | Data dictionary | Must Have |
| NFR-D07 | Data export | Portability | User can export their data in machine-readable format (GDPR Article 20) | Export API endpoint | Must Have |
| NFR-D08 | Data anonymization | Privacy | Anonymize user data in non-production environments | Dev/staging data scripts | Must Have |
| NFR-D09 | Archival strategy | Retention | Data older than {{X}} years archived to cold storage | Archive schedule | Should Have |

---

## 12. NFR Testing & Verification Plan

<!-- GUIDANCE: Every NFR must have a defined testing approach. NFRs without test plans
are aspirations, not requirements. -->

| NFR Category | Testing Method | Tools | Frequency | Pass Criteria |
|-------------|---------------|-------|-----------|---------------|
| Performance | Load testing | k6, JMeter, Lighthouse | Pre-launch + monthly | All NFR-P targets met |
| Scalability | Stress testing | k6 | Pre-launch | System gracefully handles 2× peak load |
| Security | SAST + DAST + Pentest | Snyk, OWASP ZAP, external pentest | CI (SAST), Pre-launch (DAST+Pentest), Annual | No critical/high vulnerabilities unresolved |
| Accessibility | Automated + manual | axe-core, manual screen reader | Per sprint | WCAG 2.1 AA |
| Availability | Monitoring + DR drill | Uptime monitor | Ongoing + annual | SLA targets met |
| Compliance | Legal review + audit | Manual + automated | Pre-launch + annual | All compliance items verified |

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | | | |
| Reviewer | | | |
| Tech Lead | | | |
| Business Analyst | | | |
| Product Owner | | | |
| AI Director (John) | | | |
| Client Representative | | | |

# Acceptance Criteria: Drop — Fintech Payment App

# Acceptance Criteria: Drop — Fintech Payment App

> **Project:** Drop — Remittance + QR Payments
> **Version:** 1.0
> **Date:** 2026-02-23
> **Author:** John (AI Director)
> **Status:** Approved
> **Reviewers:** Alem Bašić (CEO)

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1 | 2026-02-23 | John | Initial AC based on integration tests and E2E test suite |

---

## 1. Purpose & Methodology

### 1.1 What Are Acceptance Criteria?

Acceptance criteria define the conditions under which Drop features are considered done and accepted by the business. They answer: **"How will we know when this feature is done?"**

### 1.2 Format: Given / When / Then

```
Given [initial context / precondition]
When  [action or event occurs]
Then  [expected outcome observed]
And   [additional chained outcomes]
```

### 1.3 Categories

| Category | Description |
|----------|-------------|
| **Positive (Happy Path)** | System works with valid inputs |
| **Negative (Sad Path)** | System handles invalid inputs gracefully |
| **Edge Case** | Boundary conditions |
| **Security** | Injection, auth, abuse prevention |
| **Compliance** | Regulatory requirements |

---

## 2. Feature Acceptance Criteria

---

### Module: Authentication & Onboarding

---

#### Feature: User Registration — 3-step Onboarding (FR-001)

**Feature Description:** New residents register via email + DOB validation → OTP → PIN. BankID replaces DOB in Phase 2.
**Business Requirement:** BR-001, BR-002
**Linked User Stories:** US-001

**Positive Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-001 | Successful registration | Valid email, password ≥8 chars, Norwegian phone (+47), DOB ≥18 years | User submits registration form | 201 created; user proceeds to OTP step; no password hash in response |
| AC-002 | OTP verification passes | Account created; OTP sent to phone | User enters correct 6-digit OTP | User proceeds to PIN setup |
| AC-003 | PIN setup completes | OTP verified | User enters and confirms 4-digit PIN | Account activated; JWT cookie set; redirect to dashboard |

**Negative Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-004 | Under-18 rejected | DOB indicating age < 18 | User submits registration | 422 with message "Du må være minst 18 år" |
| AC-005 | Duplicate email | Existing account for email | User submits same email | 409 "Email already in use" |
| AC-006 | Missing required field | Registration form | User submits without first_name | 422 validation error with field details array |
| AC-007 | Short password | Password < 8 characters | User submits | 422 "Password must be at least 8 characters" |
| AC-008 | Invalid phone format | Non-+47 phone number | User submits | 422 validation error |

**Edge Cases:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-009 | Boundary age (exactly 18) | DOB = today minus 18 years exactly | Registration submitted | Account created successfully |
| AC-010 | Invalid JSON body | Malformed JSON in request | POST /api/auth/register | 400 "Invalid JSON body" |

**Security Acceptance Criteria:**

| # | Category | Criterion |
|---|----------|-----------|
| AC-011 | Auth | Password hash not returned in any API response |
| AC-012 | Auth | bcrypt used (hash starts with $2); SHA-256 rejected |
| AC-013 | Rate limiting | 10+ registrations from same IP in 1 min → 429 |

---

#### Feature: User Login (FR-002)

**Business Requirement:** BR-001
**Linked User Stories:** US-002

**Positive Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-020 | Successful login | Registered user with valid credentials | POST /api/auth/login | 200; JWT in httpOnly cookie; user object returned |
| AC-021 | Authenticated route access | Valid JWT cookie | GET /api/auth/me | 200; current user object returned |

**Negative Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-022 | Wrong password | Registered user | Submits incorrect password | 401 "Invalid email or password" (no enumeration) |
| AC-023 | Non-existent email | No account with that email | Login submitted | 401 "Invalid email or password" (same error — no enumeration) |
| AC-024 | Rate limiting | 10+ login attempts from same IP in 1 minute | Next attempt | 429 rate limit response |
| AC-025 | Missing credentials | Empty email or password | Login submitted | 400 "Email and password required" |

**Edge Cases:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-026 | Invalid JSON | Malformed body | POST /api/auth/login | 400 "Invalid JSON body" |

---

### Module: Remittance (Send Money)

---

#### Feature: Remittance Transaction (FR-020)

**Business Requirement:** BR-003, BR-005
**Linked User Stories:** US-010

**Positive Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-030 | Successful remittance | Authenticated + KYC-approved user; valid recipient; sufficient balance | POST /api/transactions/remittance with amount=1000, currency=RSD | 201; transaction created; fee = 5 NOK (0.5%); transaction in history |
| AC-031 | Fee calculation correct | Amount = 2000 NOK | Remittance submitted | fee = 10 NOK; recipient_amount = 2000 NOK (gross) |
| AC-032 | Transaction in history | Successful remittance | GET /api/transactions | Transaction appears with status=completed |

**Negative Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-033 | Unauthenticated user | No JWT cookie | POST /api/transactions/remittance | 401 Unauthorized |
| AC-034 | KYC not approved | kyc_status=pending | Remittance submitted | 403 "KYC verification required" |
| AC-035 | Recipient not found | Invalid recipientId | Remittance submitted | 404 "Recipient not found" |
| AC-036 | Insufficient balance | Balance < (amount + fee) | Remittance submitted | 402 "Insufficient balance" |
| AC-037 | Amount below minimum | amount = 99 NOK | Submitted | 400 "Amount must be between 100 and 50000 NOK" |
| AC-038 | Amount above maximum | amount = 50001 NOK | Submitted | 400 validation error |
| AC-039 | Invalid amount (NaN) | amount = "abc" | Submitted | 400 "Invalid amount" |

**Compliance Criteria:**

| # | Category | Criterion |
|---|----------|-----------|
| AC-040 | AML | Transaction > 50,000 NOK rejected; daily limits enforced |
| AC-041 | Pass-through | No `balance` column in users table; DB test verifies absence |

---

#### Feature: Exchange Rates API (FR-021)

**Positive Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-050 | All rates returned | GET /api/rates | Called | 6 NOK exchange rates returned (RSD, BAM, PKR, TRY, PLN, EUR) |
| AC-051 | Single rate returned | GET /api/rates/RSD | Called | NOK→RSD rate returned |
| AC-052 | Case insensitive | GET /api/rates/rsd (lowercase) | Called | Same result as /api/rates/RSD |

**Negative Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-053 | Unsupported currency | GET /api/rates/XXX | Called | 404 Not Found |

---

### Module: QR Payments

---

#### Feature: QR Payment — Consumer (FR-030)

**Business Requirement:** BR-004, BR-005
**Linked User Stories:** US-020

**Positive Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-060 | Successful QR payment | Authenticated + KYC-approved user; valid merchantId; sufficient balance | POST /api/transactions/qr-payment with amount=129, merchantId=valid | 201; merchant_fee = 1.29 NOK (1%); transaction created |
| AC-061 | Fee calculation | amount = 200 NOK | QR payment submitted | merchant_fee = 2 NOK (1%) |

**Negative Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-062 | Invalid merchant | Non-existent merchantId | Payment submitted | 404 "Merchant not found" |
| AC-063 | Amount < 1 NOK | amount = 0 | Submitted | 400 validation error |
| AC-064 | Missing merchantId | No merchantId in body | Submitted | 400 "Merchant ID is required" |
| AC-065 | Unauthenticated | No JWT | Submitted | 401 Unauthorized |

---

#### Feature: Merchant Registration + QR Generation (FR-031)

**Positive Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-070 | Merchant registered | Authenticated user | POST /api/merchants with business_name, bank_account | Merchant created with unique QR code value |
| AC-071 | QR code retrievable | Registered merchant | GET /api/merchants/me | Merchant details + QR code returned |

---

### Module: Security (Cross-cutting)

---

#### Feature: Input Validation (FR-001 through FR-080, all)

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-080 | XSS in name field | `<script>alert(1)</script>` as firstName | Registration submitted | 422 validation error; no script executed |
| AC-081 | SQL injection in email | `'; DROP TABLE users;--` as email | Registration submitted | 422 validation error; no DB mutation |
| AC-082 | 10KB password | 10,000 character password | Registration submitted | 422 "Password too long" or validation error |
| AC-083 | Unicode in name | Bosnian chars (š, đ, ć, č, ž) in name | Registration submitted | 201 created; name stored correctly |
| AC-084 | Underage DOB | DOB indicating 17 years old | Registration submitted | 422 age validation error |

---

### Module: Compliance

---

#### Feature: PCI-DSS Card Data Protection (FR-080, Cards feature)

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-090 | No CVV in DB | Cards table | DB schema check | cards table has NO `card_number` or `cvv` columns |
| AC-091 | No balance in users | Users table | DB schema check | users table has NO `balance` column (pass-through model) |
| AC-092 | Only last_four returned | Authenticated user | GET /api/cards/[id] | Response contains `last_four` only; no full card number |

---

## 3. Integration Scenarios

| # | Integration | Scenario | Expected Behavior | Test Environment |
|---|------------|---------|------------------|-----------------|
| INT-001 | Sumsub KYC | KYC webhook callback (approved) | User kyc_status updated to 'approved' | Mock webhook in integration tests |
| INT-002 | BaaS PISP | Payment initiation | Transaction recorded; confirmation returned | Mock PISP in NEXT_PUBLIC_SERVICE_MODE=mock |
| INT-003 | BaaS AISP | Balance read from bank | User account balance returned from BaaS | Mock AISP service |
| INT-004 | Exchange rates | Rate data missing | Error handled gracefully; GET /api/rates/XXX → 404 | Integration test |
| INT-005 | BaaS unavailable | BaaS API down | System shows user-friendly error; transaction not created | Mocked timeout in tests |

---

## 4. Non-Functional Acceptance Criteria

### 4.1 Performance

| # | Criterion | Target | Test Method |
|---|-----------|--------|-------------|
| NF-AC-001 | bcrypt hashing time | < 1,000ms | api-benchmarks.test.ts |
| NF-AC-002 | Rate limit check time | < 50ms | api-benchmarks.test.ts |
| NF-AC-003 | DB SELECT query | < 10ms | api-benchmarks.test.ts |
| NF-AC-004 | DB INSERT query | < 20ms | api-benchmarks.test.ts |
| NF-AC-005 | 50 concurrent rate limit calls | < 2,000ms total | api-benchmarks.test.ts |

### 4.2 Security

| # | Criterion | Target | Test Method |
|---|-----------|--------|-------------|
| NF-AC-010 | SHA-256 passwords rejected | verifyPassword returns false for SHA-256 hashes | auth.test.ts |
| NF-AC-011 | JWT tampered tokens rejected | Invalid signature → exception | auth.test.ts |
| NF-AC-012 | Rate limiting blocks after limit | 11th request from same IP → 429 | middleware.test.ts |
| NF-AC-013 | Input validation completeness | 10+ validation test cases pass | validation.test.ts |
| NF-AC-014 | Foreign key constraints enabled | Sessions cannot be created for non-existent users | db.test.ts |

### 4.3 Compliance

| # | Criterion | Target | Test Method |
|---|-----------|--------|-------------|
| NF-AC-020 | No balance column in users table | users table schema has no 'balance' | db.test.ts |
| NF-AC-021 | No card_number/cvv in cards table | cards table has no 'card_number' or 'cvv' | db.test.ts |
| NF-AC-022 | Transaction types limited | Only 'remittance' and 'qr_payment' accepted | db.test.ts |

---

## 5. UAT Scenario Mapping

| AC ID | AC Description | UAT Scenario ID | Priority |
|-------|---------------|-----------------|---------|
| AC-001 | Successful registration | UAT-001 | Critical |
| AC-004 | Under-18 rejected | UAT-002 | Critical |
| AC-020 | Successful login | UAT-003 | Critical |
| AC-030 | Successful remittance | UAT-010 | Critical |
| AC-060 | Successful QR payment | UAT-020 | Critical |
| AC-090 | No CVV in DB | UAT-SEC-001 | Critical |

---

## 6. Traceability to Requirements

| AC ID | Acceptance Criterion | FR Reference | BR Reference | US Reference |
|-------|---------------------|-------------|-------------|-------------|
| AC-001 | Successful registration | FR-001 | BR-001 | US-001 |
| AC-004 | Under-18 rejected | FR-001 | BR-002 | US-001 |
| AC-020 | Successful login | FR-002 | BR-001 | US-002 |
| AC-030 | Successful remittance | FR-020 | BR-003, BR-005 | US-010 |
| AC-060 | Successful QR payment | FR-030 | BR-004, BR-005 | US-020 |
| AC-090 | No CVV in DB | FR-080 | BR-005, RUL-010 | — |
| NF-AC-020 | No balance column | FR-001 | BR-005, RUL-003 | US-001 |

> Full traceability matrix: `[requirements-traceability-matrix.md](requirements-traceability-matrix.md)`

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | John (AI Director) | 2026-02-23 | Approved (AI) |
| QA Engineer | Validator agent | 2026-02-23 | Approved (AI) |
| Product Owner | John | 2026-02-23 | Approved |
| AI Director (John) | John | 2026-02-23 | Approved |
| CEO (Alem) | Alem Bašić | TBD | |

# Requirements Traceability Matrix (RTM): Drop — Fintech Payment App

# Requirements Traceability Matrix (RTM): Drop — Fintech Payment App

> **Project:** Drop — Remittance + QR Payments
> **Version:** 1.0
> **Date:** 2026-02-23
> **Author:** John (AI Director)
> **Status:** Active
> **Reviewers:** Alem Bašić (CEO)

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1 | 2026-02-23 | John | Initial RTM — mapped from brd.md, functional-requirements.md, TEST-INVENTORY.md |

---

## 1. Purpose of Traceability

The RTM maps requirements through the full SDLC:
Business Requirement → Functional Requirement → User Story → Code → Test Cases

Functions:
1. **Coverage Assurance** — Every business requirement has a test
2. **Change Impact** — When requirement changes, see all affected code and tests
3. **Gap Detection** — Requirements with no tests; tests with no requirements
4. **Audit Trail** — Demonstrates compliance for Finanstilsynet / investor due diligence

---

## 2. Document References

| Document | Location | Version | Last Updated |
|----------|----------|---------|-------------|
| Business Requirements Document | `brd.md` | 1.0 | 2026-02-23 |
| Functional Requirements Spec | `functional-requirements.md` | 1.0 | 2026-02-23 |
| Non-Functional Requirements | `non-functional-requirements.md` | 1.0 | 2026-02-23 |
| User Stories | `user-stories.md` | 1.0 | 2026-02-23 |
| Acceptance Criteria | `acceptance-criteria.md` | 1.0 | 2026-02-23 |
| Testing Guide | `../../docs/testing/TESTING-GUIDE.md` | — | 2026-02-13 |
| Test Inventory | `../../docs/testing/TEST-INVENTORY.md` | — | 2026-02-13 |
| Test Plan | `../templates-testing/test-plan.md` | 1.0 | 2026-02-23 |

---

## 3. Forward Traceability Matrix

### 3.1 Functional Requirements Traceability

| BR ID | Business Requirement | FR ID | Functional Requirement | US ID | Code Module | Unit Test | Integration Test | E2E Test | AC ID | Status |
|-------|---------------------|-------|----------------------|-------|-------------|-----------|-----------------|----------|-------|--------|
| BR-001 | BankID identity verification | FR-001 | User Registration (3-step) | US-001 | `src/app/api/auth/register/route.ts` | api-routes.test.ts | api-endpoints.test.ts | user-flows.spec.ts | AC-001 | ✅ Implemented |
| BR-001 | BankID identity verification | FR-002 | User Login | US-002 | `src/app/api/auth/login/route.ts` | api-routes.test.ts | api-endpoints.test.ts | user-flows.spec.ts | AC-020 | ✅ Implemented |
| BR-001 | BankID identity verification | FR-003 | Session Management | US-003 | `src/app/api/auth/logout/route.ts` | api-routes.test.ts | api-routes.test.ts | full-flows.spec.ts | AC-021 | ✅ Implemented |
| BR-002 | Minimum age 18 enforcement | FR-001 | User Registration — DOB validation | US-001 | `src/app/api/auth/register/route.ts` | api-routes.test.ts | api-endpoints.test.ts | input-chaos.spec.ts | AC-004 | ✅ Implemented |
| BR-003 | Remittance to 30+ countries | FR-020 | Send Money Remittance | US-010 | `src/app/api/transactions/remittance/route.ts` | api-routes.test.ts | api-endpoints.test.ts | full-flows.spec.ts | AC-030 | ✅ Implemented |
| BR-003 | Remittance to 30+ countries | FR-021 | Exchange Rates API | US-011 | `src/app/api/rates/route.ts` | api-routes.test.ts | api-endpoints.test.ts | user-flows.spec.ts | AC-050 | ✅ Implemented |
| BR-003 | Remittance to 30+ countries | FR-022 | Recipients Management | US-012 | `src/app/api/recipients/route.ts` | api-routes.test.ts | api-endpoints.test.ts | — | — | ✅ Implemented |
| BR-004 | QR merchant payments at 1% | FR-030 | QR Payment Consumer Flow | US-020 | `src/app/api/transactions/qr-payment/route.ts` | api-routes.test.ts | api-endpoints.test.ts | full-flows.spec.ts | AC-060 | ✅ Implemented |
| BR-004 | QR merchant payments at 1% | FR-031 | Merchant Registration + QR | US-021 | `src/app/api/merchants/route.ts` | api-routes.test.ts | api-endpoints.test.ts | — | AC-070 | ✅ Implemented |
| BR-005 | PSD2 pass-through model | FR-001 | No balance column | US-001 | `src/lib/db.ts` (schema) | db.test.ts | — | — | AC-091 | ✅ Verified |
| BR-006 | Merchant self-service onboarding | FR-031 | Merchant Registration | US-021 | `src/app/api/merchants/route.ts` | api-routes.test.ts | api-endpoints.test.ts | — | AC-070 | ✅ Implemented |
| BR-007 | GDPR compliance | FR-070 | User Profile + deletion | US-041 | `src/app/api/auth/me/route.ts` | — | — | full-flows.spec.ts | — | ⏳ Partial |
| BR-008 | Real-time notifications | FR-060 | Transaction Notifications | US-041 | `src/app/api/notifications/route.ts` | api-routes.test.ts | — | — | — | ✅ Implemented |
| BR-009 | Transaction history | FR-050 | Transaction History | US-040 | `src/app/api/transactions/route.ts` | api-routes.test.ts | api-endpoints.test.ts | user-flows.spec.ts | — | ✅ Implemented |
| BR-010 | AISP balance view | FR-040 | Bank Account Balance | US-030 | `src/app/api/bank-accounts/route.ts` | — | — | full-flows.spec.ts | — | ⏳ Mock only |
| BR-011 | Merchant dashboard analytics | FR-032 | Merchant Dashboard | US-022 | `src/app/api/merchants/dashboard/route.ts` | api-routes.test.ts | — | — | — | ✅ Implemented |
| BR-014 | Feature flags | FR-080 | Feature Flag Control | — | `src/lib/feature-flags.ts` | feature-flags.test.ts | — | — | — | ✅ Implemented |

### 3.2 Non-Functional Requirements Traceability

| NFR ID | Requirement | Target | Test Type | Test File | Status |
|--------|------------|--------|-----------|-----------|--------|
| NFR-SEC01 | JWT auth in httpOnly cookie | httpOnly + SameSite=Strict | Unit | auth.test.ts | ✅ |
| NFR-SEC02 | bcrypt password hashing (no SHA-256) | bcrypt 12 rounds; SHA-256 rejected | Unit | auth.test.ts | ✅ |
| NFR-SEC05 | Rate limiting (persistent) | DB-backed; 10/min auth | Unit | middleware.test.ts | ✅ |
| NFR-SEC06 | Input validation | Parameterized SQL; server-side validation | Unit | validation.test.ts | ✅ |
| NFR-SEC09 | PCI-DSS card data | No card_number/cvv in DB or API | Unit | db.test.ts | ✅ |
| NFR-R02 | Transaction integrity (ACID) | No orphaned sessions; FK constraints | Unit | db.test.ts | ✅ |
| NFR-P03 | bcrypt < 1,000ms | < 1,000ms | Performance | api-benchmarks.test.ts | ✅ |
| NFR-P04 | DB queries < 10-20ms | SELECT < 10ms; INSERT < 20ms | Performance | api-benchmarks.test.ts | ✅ |
| NFR-P05 | Rate limit check < 50ms | < 50ms | Performance | api-benchmarks.test.ts | ✅ |
| NFR-COMP01 | GDPR compliance | Right to deletion API | Legal review | — | ⏳ Pending |
| NFR-COMP03 | PSD2 registration | Finanstilsynet registration | Regulatory | — | ❌ Not started |
| NFR-COMP04 | AML/KYC | Sumsub integration | Integration | — | ⏳ Mock only |
| NFR-COMP05 | PCI-DSS cards | No CVV storage | Unit | db.test.ts | ✅ |
| NFR-A01 | 99.5% uptime | Monthly SLA | Operations monitoring | — | ⏳ Staging only |
| NFR-M01 | ≥80% test coverage | Vitest coverage | CI | vitest.config.ts | ⏳ Measuring |

---

## 4. Backward Traceability Matrix

| Test File | Test Description | AC ID | FR ID | BR ID | Has Requirement? |
|-----------|-----------------|-------|-------|-------|-----------------|
| auth.test.ts | bcrypt hash produces $2 prefix | AC-012 | FR-002 | BR-001 | ✅ Yes |
| auth.test.ts | SHA-256 hashes rejected | NF-AC-010 | FR-002 | BR-001 | ✅ Yes |
| auth.test.ts | JWT round-trip sign/verify | NF-AC-011 | FR-003 | BR-001 | ✅ Yes |
| db.test.ts | No balance column in users | AC-091, NF-AC-020 | FR-001 | BR-005 | ✅ Yes |
| db.test.ts | No card_number/cvv in cards | AC-090, NF-AC-021 | FR-080 | BR-005 | ✅ Yes |
| db.test.ts | Transaction type constraint | NF-AC-022 | FR-020, FR-030 | BR-003, BR-004 | ✅ Yes |
| middleware.test.ts | Rate limit allows within limit | AC-024 | FR-002 | BR-001 | ✅ Yes |
| middleware.test.ts | Rate limit blocks after exceeded | NF-AC-012 | FR-002 | BR-001 | ✅ Yes |
| validation.test.ts | XSS payloads rejected | AC-080 | FR-001 | BR-001 | ✅ Yes |
| validation.test.ts | SQL injection rejected | AC-081 | FR-001 | BR-001 | ✅ Yes |
| feature-flags.test.ts | topUpViaCard flag absent | — | FR-080 | BR-014 | ✅ Yes (removed feature) |
| api-endpoints.test.ts | Register → 201 with valid input | AC-001 | FR-001 | BR-001 | ✅ Yes |
| api-endpoints.test.ts | Register → 409 duplicate email | AC-005 | FR-001 | BR-001 | ✅ Yes |
| api-endpoints.test.ts | Remittance → 201 with valid data | AC-030 | FR-020 | BR-003 | ✅ Yes |
| api-endpoints.test.ts | Remittance → 403 KYC not approved | AC-034 | FR-020, FR-010 | BR-001 | ✅ Yes |
| api-endpoints.test.ts | QR payment → 201 with valid data | AC-060 | FR-030 | BR-004 | ✅ Yes |
| api-benchmarks.test.ts | bcrypt < 1,000ms | NF-AC-001 | FR-002 | BR-001 | ✅ Yes |
| user-flows.spec.ts (E2E) | Login redirects to dashboard | AC-020 | FR-002 | BR-001 | ✅ Yes |
| full-flows.spec.ts (E2E) | Send money flow | AC-030 | FR-020 | BR-003 | ✅ Yes |
| full-flows.spec.ts (E2E) | QR payment flow | AC-060 | FR-030 | BR-004 | ✅ Yes |
| input-chaos.spec.ts (E2E) | XSS in firstName | AC-080 | FR-001 | BR-001 | ✅ Yes |
| input-chaos.spec.ts (E2E) | Underage DOB | AC-084 | FR-001 | BR-002 | ✅ Yes |

---

## 5. Coverage Analysis

### 5.1 Requirement Coverage Summary (2026-02-23)

| Category | Total | Fully Covered | Partially Covered | Not Covered | Coverage % |
|----------|-------|--------------|-------------------|-------------|-----------|
| Business Requirements (BR) | 14 | 11 | 2 (BR-007, BR-010) | 1 (BR-012 — won't have) | 93% |
| Functional Requirements (FR) | 15 | 12 | 2 (FR-040, FR-070) | 1 (FR-080 cards) | 93% |
| Non-Functional Requirements (NFR) | ~40 | 15 | 10 | 15 (compliance/monitoring) | 62% |
| User Stories (US) | 13 | 11 | 2 (Phase 2) | 0 | 100% defined |
| Acceptance Criteria (AC) | ~30 | 25 | 3 | 2 | 92% |

**Overall Requirement Coverage:** ~85% (Phase 1 MVP)
**Target before Phase 2 launch:** ≥ 95%

### 5.2 Test Coverage Summary (2026-02-13 data)

| Test Type | Total Tests | Passing | Failing | Coverage |
|-----------|------------|---------|---------|----------|
| Unit tests (Vitest) | 40 | 40 | 0 | High |
| Integration tests (Vitest) | 20+ | 20+ | 0 | High |
| Performance tests | 8 | 8 | 0 | Benchmarks passing |
| Regression tests | 4 groups | All | 0 | Bug regressions covered |
| E2E tests (Playwright) | 3 projects | Configured | 0 | User flows + chaos |

**Total test files:** 14 | **Total Vitest tests:** 40+ passing

---

## 6. Gap Identification

### 6.1 Requirements Without Full Test Coverage

| Requirement ID | Description | Gap Type | Action Required | Owner | Target |
|---------------|-------------|----------|----------------|-------|--------|
| FR-040 | Bank account AISP balance | Mock only; no real integration test | Write integration test with BaaS sandbox | John | Phase 2 |
| FR-070 | GDPR user deletion | No API endpoint test | Add deletion endpoint + test | John | Phase 2 |
| NFR-COMP01 | GDPR compliance | Legal review not complete | Engage external legal advisor | Alem | Phase 2 |
| NFR-COMP03 | PSD2 Finanstilsynet registration | Not started | Initiate registration process | Alem + Legal | 2026-05-15 |
| NFR-COMP04 | AML/KYC Sumsub | Mock only in production path | Sumsub contract + integration | John | Phase 2 |
| NFR-A01 | 99.5% uptime SLA | Staging only; no production monitoring | Set up production monitoring + alerts | John | Phase 3 |
| NFR-SEC12 | External penetration test | Not conducted | External pentest before launch | John + External | Phase 3 |

### 6.2 Test Cases Without Requirements (Orphans)

| Test File | Description | Status | Action |
|-----------|-------------|--------|--------|
| known-bugs.test.ts — BUG-001 | rateLimit missing await | Linked to regression fix | ✅ Keep — valid regression |
| known-bugs.test.ts — BUG-002 | Generic validation messages | Linked to UX fix | ✅ Keep |
| known-bugs.test.ts — BUG-003 | Email without @ | Linked to FR-001 validation | ✅ Keep |
| known-bugs.test.ts — BUG-004 | Missing getDb import | Linked to FR-001 | ✅ Keep |

No orphaned test cases identified.

---

## 7. Change Impact Tracking

| Change Request ID | Changed Requirement | Impact on FR | Impact on Code | Impact on Tests | Status |
|-----------------|--------------------|--------------|--------------|-----------------|----|
| ADR-001 | Consolidate backends (FontelePay removed) | FR-030 updated (no FontelePay in payments) | Architecture cleanup done | Tests updated | ✅ Closed |
| ADR-002 | Separate FontelePay | FR-030 | src/lib/services removed FontelePay | Tests updated | ✅ Closed |
| ADR-003 | PSD2 pass-through model | FR-001 (no balance), FR-040 | users table no balance; db.test.ts | db.test.ts updated | ✅ Closed |
| Phase 0.5 | Security hardening (8 critical issues) | FR-001 through FR-080 (all auth/tx routes) | auth, middleware, security headers | validation.test.ts, middleware.test.ts | ⏳ In progress |

---

## 8. Traceability Status Dashboard

**Last Updated:** 2026-02-23
**Updated By:** John (AI Director)

| Metric | Value | Target | Status |
|--------|-------|--------|--------|
| Total Business Requirements | 14 | — | |
| BRs with FR coverage | 13/14 | 100% | ✅ |
| FRs with test coverage | 12/15 | 100% | ⚠️ 3 in progress |
| Test cases passing | 40+/40+ (Vitest) | 100% | ✅ |
| Open gaps | 7 (Phase 2 items) | 0 at Phase 2 launch | ⚠️ |
| Change requests open | 1 (Phase 0.5 security) | ≤ 3 at a time | ✅ |
| UAT sign-off pending | Not started (Phase 3) | 0 at launch | ❌ |

**Overall RTM Health:** AMBER (Phase 1 MVP complete; Phase 2 compliance gaps tracked)

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | John (AI Director) | 2026-02-23 | Approved (AI) |
| QA Engineer | Validator agent | 2026-02-23 | Reviewed |
| Tech Lead | John | 2026-02-23 | Approved |
| AI Director (John) | John | 2026-02-23 | Approved |
| CEO (Alem) | Alem Bašić | TBD | |

# User Stories: Drop — Fintech Payment App

# User Stories: Drop — Fintech Payment App

> **Project:** Drop — Remittance + QR Payments
> **Version:** 1.0
> **Date:** 2026-02-23
> **Author:** John (AI Director)
> **Status:** Approved
> **Reviewers:** Alem Bašić (CEO)

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1 | 2026-02-23 | John | Initial stories from user journeys in business-case-v2.md |

---

## 1. Epic Overview

| Epic ID | Epic Name | Business Goal | Story Count | Status | Target Release |
|---------|----------|--------------|-------------|--------|---------------|
| EP-01 | User Onboarding & Authentication | BO-02 — user acquisition | 4 | Done (Phase 0.5) | Phase 1 |
| EP-02 | Remittance (Send Money) | BO-01, BO-02 — revenue + users | 5 | Done (Phase 1) | Phase 1 |
| EP-03 | QR Merchant Payments | BO-01, BO-03 — revenue + merchants | 5 | Done (Phase 1) | Phase 1 |
| EP-04 | Open Banking (AISP) | BO-02 — user trust | 2 | Mock (Phase 2) | Phase 2 |
| EP-05 | Transaction History & Notifications | BO-02, BO-03 | 3 | Done (Phase 1) | Phase 1 |
| EP-06 | Merchant Analytics | BO-03 — merchant retention | 2 | Done (Phase 1) | Phase 1 |
| EP-07 | KYC & Compliance | BO-05 — regulatory | 2 | Mock (Phase 2) | Phase 2 |

---

## 2. Story Format Guide

**Standard Story Format:**
```
As a [persona/role],
I want [feature/action],
So that [benefit/outcome].
```

**Acceptance Criteria Format (Given/When/Then):**
```
Given [a precondition that must be true],
When [the user performs an action],
Then [the expected outcome occurs].
```

---

## 4. Story Backlog

### Epic EP-01: User Onboarding & Authentication

---

#### US-001: Account Registration (3-step onboarding)

| Attribute | Value |
|-----------|-------|
| Epic | EP-01: Onboarding |
| Priority | Must Have |
| Story Points | 8 |
| Sprint | Sprint 1 |
| Assigned To | Builder agent |
| Status | Done |
| FR Reference | FR-001 |
| BR Reference | BR-001, BR-002 |

**Story:**
As a **Norwegian resident (18+)**,
I want **to register for Drop with my email and date of birth**,
So that **I can access remittance and QR payments at lower fees than existing services**.

**Context:**
3-step flow: (1) personal details + DOB validation, (2) OTP on Norwegian phone (+47), (3) PIN setup. BankID integration in Phase 2 replaces DOB validation with real SCA.

**Acceptance Criteria:**
- [ ] **Given** valid email, password ≥8 chars, Norwegian phone (+47), DOB ≥18 years, **when** user submits registration, **then** 201 created; user proceeds to OTP step
- [ ] **Given** DOB under 18 years, **when** user submits, **then** 422 "Du må være minst 18 år"
- [ ] **Given** duplicate email, **when** submitted, **then** 409 "Email already in use"
- [ ] **Given** OTP sent, **when** user enters correct 6 digits, **then** user proceeds to PIN setup
- [ ] **Given** valid 4-digit PIN entered and confirmed, **when** submitted, **then** account activated; JWT cookie set

**Technical Notes:**
- Age validation: `(today - DOB) >= 18 years`
- OTP: 6-digit code; in MVP any code accepted (mock); real SMS in Phase 2
- Password: bcrypt 12 rounds

**UI/UX Notes:**
- Screen: `mockups/figma-make-export/src/components/Onboarding.js`
- 3-step progress indicator shown

**Dependencies:** Blocked by: None | Blocks: US-002, US-003, US-010

---

#### US-002: User Login

| Attribute | Value |
|-----------|-------|
| Epic | EP-01 |
| Priority | Must Have |
| Story Points | 3 |
| Sprint | Sprint 1 |
| Status | Done |
| FR Reference | FR-002 |

**Story:**
As a **registered Drop user**,
I want **to log in with my email and password**,
So that **I can access my account and make payments**.

**Acceptance Criteria:**
- [ ] **Given** valid email + password, **when** login submitted, **then** JWT cookie set; redirected to dashboard
- [ ] **Given** wrong password, **when** submitted, **then** 401 "Invalid email or password" (no enumeration)
- [ ] **Given** 10 failed attempts from same IP, **when** next attempt, **then** 429 rate limit error

**Dependencies:** Blocked by: US-001

---

#### US-003: Session Logout

| Attribute | Value |
|-----------|-------|
| Epic | EP-01 |
| Priority | Must Have |
| Story Points | 1 |
| Sprint | Sprint 1 |
| Status | Done |
| FR Reference | FR-003 |

**Story:**
As a **logged-in Drop user**,
I want **to log out of my account**,
So that **my session is securely terminated on shared devices**.

**Acceptance Criteria:**
- [ ] **Given** authenticated user, **when** they POST /api/auth/logout, **then** JWT cookie cleared; session revoked in DB
- [ ] **Given** logged-out user, **when** they access protected routes, **then** 401 redirect to login

**Dependencies:** Blocked by: US-002

---

#### US-004: BankID Verification (Phase 2)

| Attribute | Value |
|-----------|-------|
| Epic | EP-01 |
| Priority | Must Have |
| Story Points | 8 |
| Sprint | Sprint 4 (Phase 2) |
| Status | Backlog |
| FR Reference | FR-001 |

**Story:**
As a **Norwegian resident**,
I want **to verify my identity via Norwegian BankID**,
So that **my account is secured with Strong Customer Authentication (SCA) as required by PSD2**.

**Acceptance Criteria:**
- [ ] **Given** user at onboarding step 1, **when** they complete BankID verification, **then** DOB, name, and national ID extracted from BankID response
- [ ] **Given** BankID shows DOB < 18 years, **when** verification complete, **then** registration rejected with age error
- [ ] **Given** successful BankID, **when** verification complete, **then** kyc_status set to approved

**Dependencies:** Blocked by: BaaS provider confirmed (DEP-01)

---

### Epic EP-02: Remittance (Send Money)

---

#### US-010: Send Money to Recipient

| Attribute | Value |
|-----------|-------|
| Epic | EP-02: Remittance |
| Priority | Must Have |
| Story Points | 8 |
| Sprint | Sprint 1 |
| Status | Done |
| FR Reference | FR-020 |
| BR Reference | BR-003, BR-005 |

**Story:**
As a **Drop user who wants to support family abroad**,
I want **to send money to a recipient in Serbia/Pakistan/Bosnia/Poland/Turkey/EUR zone at 0.5% fee**,
So that **my family receives money faster and 10x cheaper than Western Union**.

**Context:**
"Amir wants to send 2,000 NOK to his mother Jasmina in Sarajevo. He opens Drop, taps 'Pošalji novac', selects Bosnia, enters Jasmina's IBAN, enters 2,000 NOK. Drop shows: mama receives 4,660 BAM, fee 10 NOK. He confirms. Mama gets SMS notification."

**Acceptance Criteria:**
- [ ] **Given** authenticated + KYC-approved user, **when** POST /api/transactions/remittance with amount 100-50,000 NOK and valid recipientId, **then** 201; transaction created; fee = amount × 0.005
- [ ] **Given** user with insufficient balance, **when** submitting, **then** 402 "Insufficient balance"
- [ ] **Given** amount < 100 NOK or > 50,000 NOK, **when** submitted, **then** 400 validation error
- [ ] **Given** unauthenticated user, **when** submitting, **then** 401 Unauthorized
- [ ] **Given** KYC-pending user, **when** submitting, **then** 403 "KYC verification required"

**Technical Notes:**
- 6 corridors in MVP: NOK→RSD, NOK→BAM, NOK→PKR, NOK→TRY, NOK→PLN, NOK→EUR
- In Phase 2: real PISP via BaaS
- Exchange rates from `exchange_rates` table, updated daily

**UI/UX Notes:** Screen: `mockups/figma-make-export/src/components/SendMoney.js`

**Dependencies:** Blocked by: US-001, US-012, US-013

---

#### US-011: View Exchange Rates

| Attribute | Value |
|-----------|-------|
| Epic | EP-02 |
| Priority | Must Have |
| Story Points | 2 |
| Sprint | Sprint 1 |
| Status | Done |
| FR Reference | FR-021 |

**Story:**
As a **Drop user planning to send money**,
I want **to see current exchange rates before confirming a transfer**,
So that **I know exactly how much my recipient will receive**.

**Acceptance Criteria:**
- [ ] **Given** any user, **when** GET /api/rates, **then** all 6 NOK exchange rates returned (RSD, BAM, PKR, TRY, PLN, EUR)
- [ ] **Given** GET /api/rates/RSD, **when** called, **then** specific NOK→RSD rate returned
- [ ] **Given** GET /api/rates/XXX invalid, **when** called, **then** 404 Not Found

**Dependencies:** None

---

#### US-012: Add Recipient

| Attribute | Value |
|-----------|-------|
| Epic | EP-02 |
| Priority | Must Have |
| Story Points | 3 |
| Sprint | Sprint 1 |
| Status | Done |
| FR Reference | FR-022 |

**Story:**
As a **Drop user sending money regularly to the same person**,
I want **to save recipient details (name, IBAN, country)**,
So that **I don't have to re-enter them every time I send money**.

**Acceptance Criteria:**
- [ ] **Given** authenticated user, **when** POST /api/recipients with valid name, IBAN, country, **then** recipient saved
- [ ] **Given** authenticated user, **when** GET /api/recipients, **then** all user's recipients returned
- [ ] **Given** invalid IBAN format, **when** submitted, **then** 422 validation error

**Dependencies:** Blocked by: US-002

---

### Epic EP-03: QR Merchant Payments

---

#### US-020: Pay Merchant via QR Scan

| Attribute | Value |
|-----------|-------|
| Epic | EP-03: QR Payments |
| Priority | Must Have |
| Story Points | 8 |
| Sprint | Sprint 2 |
| Status | Done |
| FR Reference | FR-030 |
| BR Reference | BR-004, BR-005 |

**Story:**
As a **Drop user at a local merchant**,
I want **to scan the merchant's QR code and pay directly from my bank account**,
So that **I pay 1% merchant fee instead of Vipps' 1.75-2.75%, without needing cash or card terminal**.

**Context:**
"Amir walks into Ahmet's kebab shop. On the counter is a Drop QR sticker. Amir opens Drop, taps 'Skeniraj', points camera at QR → 'Ahmetov Kebab' appears. He enters 129 NOK, taps 'Betal'. Ahmet's phone buzzes: 129 NOK received."

**Acceptance Criteria:**
- [ ] **Given** authenticated + KYC-approved user, **when** POST /api/transactions/qr-payment with valid merchantId and amount ≥1 NOK, **then** 201; merchant_fee = amount × 0.01
- [ ] **Given** invalid merchantId, **when** submitted, **then** 404 "Merchant not found"
- [ ] **Given** amount < 1 NOK, **when** submitted, **then** 400 validation error
- [ ] **Given** missing merchantId, **when** submitted, **then** 400 validation error

**UI/UX Notes:** Screen: `mockups/figma-make-export/src/components/ScanQR.js`

**Dependencies:** Blocked by: US-001, US-021

---

#### US-021: Merchant Business Registration

| Attribute | Value |
|-----------|-------|
| Epic | EP-03 |
| Priority | Must Have |
| Story Points | 5 |
| Sprint | Sprint 2 |
| Status | Done |
| FR Reference | FR-031 |

**Story:**
As a **local business owner**,
I want **to register my business in Drop and receive a QR code**,
So that **I can start accepting payments at 1% fee within 5 minutes**.

**Acceptance Criteria:**
- [ ] **Given** authenticated user, **when** POST /api/merchants with business_name, bank_account, address, **then** merchant created with unique QR code
- [ ] **Given** merchant, **when** GET /api/merchants/me, **then** merchant details + QR code returned
- [ ] **Given** QR code scanned by Drop consumer, **when** payment submitted, **then** merchant correctly identified

**Dependencies:** Blocked by: US-002

---

#### US-022: Merchant Dashboard

| Attribute | Value |
|-----------|-------|
| Epic | EP-03 |
| Priority | Should Have |
| Story Points | 5 |
| Sprint | Sprint 2 |
| Status | Done |
| FR Reference | FR-032 |

**Story:**
As a **merchant using Drop**,
I want **to see my daily/weekly/monthly transaction volume and fees**,
So that **I can understand my Drop revenue and reconcile with my bank statement**.

**Acceptance Criteria:**
- [ ] **Given** authenticated merchant, **when** GET /api/merchants/dashboard?period=week, **then** total_transactions, gross_volume, total_fees returned for that period
- [ ] **Given** GET with period=today, period=month, **when** called, **then** correct period data returned

**Dependencies:** Blocked by: US-021

---

### Epic EP-04: Open Banking (AISP)

---

#### US-030: View Bank Account Balance

| Attribute | Value |
|-----------|-------|
| Epic | EP-04: Open Banking |
| Priority | Should Have |
| Story Points | 5 |
| Sprint | Sprint 4 (Phase 2) |
| Status | Mock (Phase 2) |
| FR Reference | FR-040 |

**Story:**
As a **Drop user**,
I want **to see my Norwegian bank account balance in the Drop app**,
So that **I know if I have enough funds before sending money — without needing to open my banking app**.

**Acceptance Criteria:**
- [ ] **Given** authenticated user with linked bank account, **when** GET /api/bank-accounts, **then** masked account number + balance returned
- [ ] **Given** no linked account, **when** viewing accounts screen, **then** prompt to link via BankID

**Technical Notes:** Real AISP requires BaaS partner (DEP-01) — currently mock data in demo

**Dependencies:** Blocked by: DEP-01 (BaaS partner)

---

### Epic EP-05: Transaction History & Notifications

---

#### US-040: Transaction History

| Attribute | Value |
|-----------|-------|
| Epic | EP-05 |
| Priority | Should Have |
| Story Points | 3 |
| Sprint | Sprint 1 |
| Status | Done |
| FR Reference | FR-050 |

**Story:**
As a **Drop user**,
I want **to see a history of all my transactions**,
So that **I can track my spending and verify payments went through**.

**Acceptance Criteria:**
- [ ] **Given** authenticated user, **when** GET /api/transactions, **then** all user's transactions returned (most recent first)
- [ ] **Given** ?type=remittance query, **when** called, **then** only remittance transactions returned

**Dependencies:** Blocked by: US-010 or US-020

---

#### US-041: Transaction Notifications

| Attribute | Value |
|-----------|-------|
| Epic | EP-05 |
| Priority | Should Have |
| Story Points | 3 |
| Sprint | Sprint 2 |
| Status | Done |
| FR Reference | FR-060 |

**Story:**
As a **Drop user or merchant**,
I want **to receive notifications when transactions occur**,
So that **I know immediately when money is sent or received**.

**Acceptance Criteria:**
- [ ] **Given** completed transaction, **when** GET /api/notifications, **then** new notification appears in list
- [ ] **Given** user marks notification as read, **when** PATCH /api/notifications/[id], **then** status updated to read

**Dependencies:** Blocked by: US-010 or US-020

---

## 5. Story Estimation Guide

| Points | Complexity | Examples |
|--------|-----------|---------|
| 1 | Trivial | Fix a label, add config option |
| 2 | Simple | Read-only data display, static endpoint |
| 3 | Moderate | CRUD for one entity, simple filter |
| 5 | Complex | Multi-step form, API integration |
| 8 | Very Complex | New module with CRUD + logic + UI + tests |
| 13+ | Too Large | Break into smaller stories |

---

## 6. Definition of Ready Checklist

Before a story enters a sprint:

- [ ] Story is in As a / I want / So that format
- [ ] Story has at least 2 acceptance criteria (Given/When/Then)
- [ ] Story has been estimated in story points
- [ ] Dependencies are identified and not blocking
- [ ] UI/UX design exists (Figma Make export for core screens)
- [ ] Technical approach is understood
- [ ] Priority assigned (MoSCoW)
- [ ] Story size ≤ 8 points
- [ ] FR reference documented

---

## 7. Story Map

```
USER JOURNEY:  [Register] → [Verify KYC] → [Send Money] → [Pay QR] → [View History]

Phase 1        US-001       US-007(mock)  US-010        US-020     US-040
(Demo)         US-002                     US-011        US-021     US-041
               US-003                     US-012        US-022

Phase 2        US-004       US-007(real)  [Real PISP]   [Real PISP] US-030
(Banking)      (BankID)     (Sumsub)
```

---

## 8. Backlog Summary

| Epic | Total Stories | Estimated Points | Done | Remaining |
|------|-------------|-----------------|------|-----------|
| EP-01: Onboarding | 4 | 20 | 3 | 1 (US-004, Phase 2) |
| EP-02: Remittance | 3 | 13 | 3 | 0 |
| EP-03: QR Payments | 3 | 18 | 3 | 0 |
| EP-04: Open Banking | 1 | 5 | 0 | 1 (Phase 2) |
| EP-05: History/Notifications | 2 | 6 | 2 | 0 |
| **Total** | **13** | **62** | **11** | **2 (Phase 2)** |

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | John (AI Director) | 2026-02-23 | Approved (AI) |
| Product Owner | John | 2026-02-23 | Approved |
| AI Director (John) | John | 2026-02-23 | Approved |

# Business Requirements Document (BRD)

# Business Requirements Document (BRD): {{PROJECT_NAME}}

> **Project:** {{PROJECT_NAME}}
> **Version:** {{VERSION}}
> **Date:** {{DATE}}
> **Author:** {{AUTHOR}}
> **Status:** Draft | In Review | Approved
> **Reviewers:** {{REVIEWERS}}

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1     | {{DATE}} | {{AUTHOR}} | Initial draft |

---

<!-- GUIDANCE: The BRD describes WHAT the business needs, not HOW to build it.
Technology decisions belong in the Functional Requirements Spec (FRS) and Technical Spec.
This document is written by a Business Analyst and owned by the Product Owner.
It requires sign-off from the client before development begins. -->

## 1. Executive Summary

<!-- GUIDANCE: 200-300 words maximum. Answer: What problem does this project solve?
Who benefits? What is the proposed solution? What are the expected outcomes?
Write this section LAST, after all other sections are complete. -->

**Project Overview:**
{{EXECUTIVE_SUMMARY_PARAGRAPH}}

**Business Problem:**
{{PROBLEM_SUMMARY_1_SENTENCE}}

**Proposed Solution:**
{{SOLUTION_SUMMARY_1_SENTENCE}}

**Expected Outcomes:**
- {{OUTCOME_1}}
- {{OUTCOME_2}}
- {{OUTCOME_3}}

**Investment:** {{BUDGET_RANGE}} NOK | **Timeline:** {{DURATION}} | **Priority:** {{HIGH/MEDIUM/LOW}}

---

## 2. Business Objectives & Goals

<!-- GUIDANCE: Business objectives are what the organization wants to achieve.
Each objective should be SMART: Specific, Measurable, Achievable, Relevant, Time-bound.
Objectives drive everything else in this document — every requirement should trace to at least one. -->

| ID | Objective | Description | Target | Timeframe |
|----|-----------|-------------|--------|-----------|
| BO-01 | {{OBJECTIVE_TITLE}} | {{DETAILED_DESCRIPTION}} | {{MEASURABLE_TARGET}} | {{DATE/TIMEFRAME}} |
| BO-02 | | | | |
| BO-03 | | | | |
| BO-04 | | | | |

**Alignment to Strategic Goals:**
This project supports the following organizational priorities:
- **{{STRATEGIC_GOAL_1}}:** {{HOW_THIS_PROJECT_SUPPORTS_IT}}
- **{{STRATEGIC_GOAL_2}}:** {{HOW_THIS_PROJECT_SUPPORTS_IT}}

---

## 3. Current State Analysis (AS-IS)

<!-- GUIDANCE: Document the current situation in detail. How does the business operate today?
What processes exist? What systems are used? What are the pain points, inefficiencies, and gaps?
This section forms the baseline against which the TO-BE state is measured. -->

### 3.1 Current Process Overview

{{CURRENT_PROCESS_DESCRIPTION}}

### 3.2 AS-IS Process Flow

```mermaid
flowchart LR
    A([Start]) --> B[{{STEP_1}}]
    B --> C{{{DECISION_POINT}}}
    C -->|Yes| D[{{STEP_2A}}]
    C -->|No| E[{{STEP_2B}}]
    D --> F[{{STEP_3}}]
    E --> F
    F --> G([End])
```

### 3.3 Current Systems & Tools

| System / Tool | Purpose | Users | Limitations |
|--------------|---------|-------|-------------|
| {{SYSTEM_NAME}} | {{PURPOSE}} | {{USER_COUNT/TYPE}} | {{LIMITATIONS}} |
| Manual process | {{WHAT_IS_MANUAL}} | {{WHO}} | Time-consuming, error-prone |

### 3.4 Current State Pain Points

| # | Pain Point | Category | Affected Users | Business Impact | Severity |
|---|-----------|----------|---------------|-----------------|----------|
| PP-01 | {{PAIN_POINT}} | Process / Technology / Data | {{USERS}} | {{IMPACT}} | High/Med/Low |
| PP-02 | | | | | |
| PP-03 | | | | | |

### 3.5 Current State Metrics (Baseline)

<!-- GUIDANCE: These baselines are crucial for proving the project delivered value post-launch. -->

| Metric | Current Value | Source | Notes |
|--------|-------------|--------|-------|
| {{METRIC}} | {{VALUE}} | {{HOW_MEASURED}} | {{CONTEXT}} |
| Process cycle time | {{VALUE}} | Observation / timing | Time from start to finish |
| Error rate | {{VALUE}}% | Issue logs | Manual error rate |
| User satisfaction | {{VALUE}}/10 | Survey | Last measured {{DATE}} |

---

## 4. Future State Vision (TO-BE)

<!-- GUIDANCE: Describe the desired future state. What will the process look like after the project?
What changes for users? What becomes automated? What decisions become data-driven?
Be aspirational but realistic. -->

### 4.1 Future State Description

{{TO_BE_STATE_DESCRIPTION}}

### 4.2 TO-BE Process Flow

```mermaid
flowchart LR
    A([Start]) --> B[{{NEW_STEP_1}}]
    B --> C[{{NEW_STEP_2_AUTOMATED}}]
    C --> D{{{DECISION_POINT_DATA_DRIVEN}}}
    D -->|Threshold met| E[{{NEW_OUTCOME_1}}]
    D -->|Threshold not met| F[{{NEW_OUTCOME_2}}]
    E --> G([End — Automated])
    F --> G
```

### 4.3 Key Improvements

| Area | AS-IS | TO-BE | Improvement |
|------|-------|-------|-------------|
| {{AREA}} | {{CURRENT}} | {{FUTURE}} | {{QUANTIFIED_IMPROVEMENT}} |
| Cycle time | {{VALUE}} | {{VALUE}} | {{X}}% faster |
| Error rate | {{VALUE}}% | {{VALUE}}% | {{X}}% reduction |
| User experience | {{RATING}} | {{RATING}} | Significant improvement |

---

## 5. Market Analysis & Competitive Landscape

<!-- GUIDANCE: Provide context on the market and competition. This helps stakeholders understand
why the project is necessary and how it positions the business. Keep it concise. -->

### 5.1 Market Context

{{MARKET_CONTEXT_PARAGRAPH}}

### 5.2 Competitive Analysis

| Competitor | Solution Type | Key Features | Pricing | Our Advantage |
|-----------|--------------|-------------|---------|---------------|
| {{COMPETITOR}} | Direct / Indirect | {{FEATURES}} | {{PRICING}} | {{ADVANTAGE}} |

### 5.3 Positioning

**Unique Value Proposition:** {{VALUE_PROP}}
**Target Market:** {{MARKET_SEGMENT}}
**Differentiators:** {{DIFFERENTIATORS}}

---

## 6. Stakeholder Needs Analysis

<!-- GUIDANCE: Different stakeholders have different — sometimes conflicting — needs.
Document each stakeholder group's needs before writing requirements.
Requirements that conflict need to be resolved with the PO before finalizing. -->

| Stakeholder Group | Primary Needs | Secondary Needs | Pain Points Addressed | Priority |
|------------------|--------------|----------------|----------------------|----------|
| {{STAKEHOLDER_1}} | {{PRIMARY_NEEDS}} | {{SECONDARY_NEEDS}} | PP-01, PP-02 | High |
| {{STAKEHOLDER_2}} | | | | |
| {{STAKEHOLDER_3}} | | | | |

---

## 7. Business Requirements

<!-- GUIDANCE: Business requirements describe WHAT the business needs, in business language.
NOT technical specifications. Each requirement must:
- Have a unique ID (BR-XXX)
- Trace to at least one business objective (BO-XX)
- Have a clear priority (MoSCoW: Must/Should/Could/Won't)
- Be verifiable (can you test whether it is met?) -->

| ID | Requirement | Description | Priority | Rationale | Source | BO Reference |
|----|------------|-------------|----------|-----------|--------|-------------|
| BR-001 | {{REQUIREMENT_TITLE}} | {{DETAILED_DESCRIPTION}} | Must Have | {{WHY_NEEDED}} | {{STAKEHOLDER/INTERVIEW}} | BO-01 |
| BR-002 | | | Must Have | | | |
| BR-003 | | | Must Have | | | |
| BR-004 | | | Should Have | | | |
| BR-005 | | | Should Have | | | |
| BR-006 | | | Could Have | | | |
| BR-007 | | | Won't Have (this release) | | | |

**MoSCoW Definitions:**
- **Must Have** — Essential for launch; system fails without it
- **Should Have** — High value; include unless significant constraints force exclusion
- **Could Have** — Nice to have; include only if time/budget allow
- **Won't Have** — Explicitly out of scope for this release (prevents scope creep)

---

## 8. Success Metrics & KPIs

<!-- GUIDANCE: Define specific, measurable targets. Each KPI needs a baseline (from current state),
a target, a measurement method, and an evaluation timeline. This enables objective project evaluation. -->

| ID | KPI | Category | Baseline | Target | Measurement Method | Evaluation Date | Owner |
|----|-----|----------|----------|--------|--------------------|-----------------|-------|
| KPI-01 | {{KPI_NAME}} | Revenue / Efficiency / Quality / UX | {{BASELINE}} | {{TARGET}} | {{HOW_MEASURED}} | {{DATE}} | {{OWNER}} |
| KPI-02 | User adoption rate | Adoption | 0% | {{TARGET}}% in 90 days | Analytics | 90 days post-launch | PM |
| KPI-03 | Process cycle time | Efficiency | {{BASELINE}} | {{TARGET}} | System monitoring | 30 days post-launch | Tech Lead |
| KPI-04 | User satisfaction (CSAT) | Quality | {{BASELINE}} | ≥ 8/10 | Post-launch survey | 60 days post-launch | PM |
| KPI-05 | System uptime | Reliability | N/A | ≥ 99.5% | Monitoring | Ongoing | DevOps |

---

## 9. Business Rules & Constraints

<!-- GUIDANCE: Business rules are non-negotiable operational constraints — often from legal,
regulatory, or organizational policy. They are NOT functional requirements but constrain them. -->

### 9.1 Business Rules

| ID | Rule | Category | Source | Enforced By |
|----|------|----------|--------|-------------|
| RUL-01 | {{RULE_DESCRIPTION}} | Legal / Operational / Financial | {{SOURCE}} | {{SYSTEM/PROCESS}} |
| RUL-02 | GDPR: User data must not leave EEA | Legal | GDPR Regulation | Infrastructure |
| RUL-03 | Financial transactions > {{AMOUNT}} require dual approval | Financial | Internal policy | Application |

### 9.2 Regulatory & Compliance Requirements

| Regulation | Applicability | Requirements | Responsible |
|------------|--------------|-------------|-------------|
| GDPR | {{YES/NO}} | Data minimization, right to deletion, DPA required | Tech Lead + Legal |
| {{REGULATION}} | | | |

### 9.3 Technical Constraints

<!-- GUIDANCE: System constraints imposed by the business environment, not technical preference. -->

- Must integrate with: {{EXISTING_SYSTEM}}
- Must support: {{BROWSER/DEVICE/OS}}
- Must run on: {{INFRASTRUCTURE}} (if mandated)
- Data residency: {{COUNTRY/REGION}} only
- {{ADDITIONAL_CONSTRAINT}}

---

## 10. Assumptions & Dependencies

### 10.1 Assumptions

| # | Assumption | Risk if False | Validation Owner |
|---|-----------|--------------|-----------------|
| A-01 | {{ASSUMPTION}} | {{RISK}} | {{OWNER}} |
| A-02 | Client will provide {{RESOURCE/ACCESS}} by {{DATE}} | Delays requirements phase | PM |
| A-03 | Existing {{SYSTEM}} API is stable during development | Integration rework required | Tech Lead |

### 10.2 Dependencies

| # | Dependency | Type | Impact if Unavailable | Target Date | Status |
|---|-----------|------|----------------------|-------------|--------|
| DEP-01 | {{DEPENDENCY}} | Internal / External | {{IMPACT}} | {{DATE}} | Pending |
| DEP-02 | Client data export from legacy system | Client | Cannot populate initial data | {{DATE}} | Pending |

---

## 11. ROI Analysis / Cost-Benefit

<!-- GUIDANCE: Quantify the business case. Use conservative estimates.
NPV = Net Present Value (future cash flows discounted to today's value). -->

### 11.1 Investment Summary

| Cost Category | One-Time (NOK) | Annual (NOK) | Notes |
|--------------|---------------|-------------|-------|
| Development | {{AMOUNT}} | — | One-time |
| Infrastructure | {{AMOUNT}} | {{AMOUNT}} | Ongoing hosting |
| Licenses | {{AMOUNT}} | {{AMOUNT}} | |
| Maintenance | — | {{AMOUNT}} | Post-launch support |
| **Total Year 1** | **{{TOTAL}}** | **{{ANNUAL}}** | |

### 11.2 Benefit Projections

| Benefit | Year 1 (NOK) | Year 2 (NOK) | Year 3 (NOK) | Confidence |
|---------|-------------|-------------|-------------|-----------|
| Revenue increase | {{AMOUNT}} | {{AMOUNT}} | {{AMOUNT}} | {{HIGH/MED/LOW}} |
| Cost reduction | {{AMOUNT}} | {{AMOUNT}} | {{AMOUNT}} | {{HIGH/MED/LOW}} |
| Risk reduction value | {{AMOUNT}} | {{AMOUNT}} | {{AMOUNT}} | {{HIGH/MED/LOW}} |
| **Total Benefits** | **{{TOTAL}}** | **{{TOTAL}}** | **{{TOTAL}}** | |

### 11.3 ROI Summary

| Metric | Value |
|--------|-------|
| Total Investment | {{NOK}} |
| Net Benefit (Year 1) | {{NOK}} |
| Payback Period | {{MONTHS}} months |
| 3-Year ROI | {{PERCENT}}% |
| 3-Year NPV (discount rate: {{RATE}}%) | {{NOK}} |

---

## 12. Implementation Roadmap

<!-- GUIDANCE: Phase the implementation to reduce risk and deliver early value.
Each phase should be independently valuable (not a half-built system). -->

| Phase | Description | Key Deliverables | Duration | Success Criteria |
|-------|-------------|-----------------|----------|-----------------|
| Phase 1 — MVP | Core {{FEATURE}} functionality | {{DELIVERABLES}} | {{DURATION}} | {{SUCCESS_CRITERIA}} |
| Phase 2 — Full Release | Complete feature set | {{DELIVERABLES}} | {{DURATION}} | {{SUCCESS_CRITERIA}} |
| Phase 3 — Enhancement | Advanced features, integrations | {{DELIVERABLES}} | {{DURATION}} | {{SUCCESS_CRITERIA}} |

```mermaid
timeline
    title {{PROJECT_NAME}} — Implementation Roadmap
    section Phase 1 — MVP
        {{START_DATE}} : Requirements & Design
        {{DATE}} : Core Development
        {{DATE}} : MVP Launch
    section Phase 2 — Full Release
        {{DATE}} : Advanced Features
        {{DATE}} : Integrations
        {{DATE}} : Full Launch
    section Phase 3 — Enhancement
        {{DATE}} : Performance & Scale
        {{DATE}} : Analytics & Reporting
```

---

## 13. Risk Assessment

<!-- GUIDANCE: High-level business risks. Technical risks are in the risk register.
Focus on business, organizational, and market risks here. -->

| # | Risk | Probability | Business Impact | Mitigation |
|---|------|------------|-----------------|------------|
| BR-R01 | {{RISK}} | H/M/L | H/M/L | {{MITIGATION}} |
| BR-R02 | Market change reduces project value | Low | High | Quarterly business case review |
| BR-R03 | Key business stakeholder changes role | Medium | High | Document all decisions; dual-approver model |

> Full technical risk register: `[../PROJECT-GOVERNANCE/risk-register.md](../PROJECT-GOVERNANCE/risk-register.md)`

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | | | |
| Reviewer | | | |
| Business Analyst | | | |
| Product Owner | | | |
| AI Director (John) | | | |
| Client Sponsor | | | |
| CEO (Alem) | | | |

# User Stories

# User Stories: {{PROJECT_NAME}}

> **Project:** {{PROJECT_NAME}}
> **Version:** {{VERSION}}
> **Date:** {{DATE}}
> **Author:** {{AUTHOR}}
> **Status:** Draft | In Review | Approved
> **Reviewers:** {{REVIEWERS}}

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1     | {{DATE}} | {{AUTHOR}} | Initial draft |

---

<!-- GUIDANCE: User stories capture requirements from the user's perspective.
This document contains the full story backlog organized by Epic.
Individual story cards live in Mission Control (task system); this document is the
structured reference that feeds the backlog. -->

## 1. Epic Overview

<!-- GUIDANCE: Epics are large user stories that span multiple sprints.
Each epic should represent a meaningful business capability.
Stories within an epic deliver incremental value toward that capability. -->

| Epic ID | Epic Name | Business Goal | Story Count | Status | Target Release |
|---------|----------|--------------|-------------|--------|---------------|
| EP-01 | {{EPIC_NAME}} | {{BUSINESS_GOAL}} | {{COUNT}} | Backlog / In Progress | {{RELEASE}} |
| EP-02 | | | | | |
| EP-03 | | | | | |

---

## 2. Epic Templates

### Epic: EP-01 — {{EPIC_NAME}}

<!-- GUIDANCE: An epic describes a large feature or business area. It includes:
- The business goal it serves
- The persona(s) who benefit
- A narrative description
- The individual stories that break it down -->

**Epic Statement:**
As a **{{PERSONA}}**, I need **{{CAPABILITY}}** so that **{{BUSINESS_VALUE}}**.

**Business Goal:** {{BUSINESS_OBJECTIVE_REFERENCE}}
**Priority:** Must Have | Should Have | Could Have
**Estimated Size:** {{X}} story points (rough)
**Target Sprint(s):** Sprint {{X}} – Sprint {{Y}}

**Acceptance Criteria at Epic Level:**
- [ ] {{HIGH_LEVEL_CRITERION_1}}
- [ ] {{HIGH_LEVEL_CRITERION_2}}
- [ ] {{HIGH_LEVEL_CRITERION_3}}

**Stories in This Epic:**
- US-001: {{STORY_TITLE}}
- US-002: {{STORY_TITLE}}
- US-003: {{STORY_TITLE}}

---

## 3. Story Format Guide

<!-- GUIDANCE: Every story follows this format. Read before writing stories. -->

**Standard Story Format:**
```
As a [persona/role],
I want [feature/action],
So that [benefit/outcome].
```

**Acceptance Criteria Format (Given/When/Then):**
```
Given [a precondition that must be true],
When [the user performs an action],
Then [the expected outcome occurs].
```

**Key Principles:**
- Stories describe WHAT the user needs, not HOW to build it
- Each story must be independently valuable and testable
- Stories should be completable within a single sprint
- If a story takes > 8 story points, break it into smaller stories
- Acceptance criteria should be written as tests (they become test cases)

---

## 4. Story Backlog

<!-- GUIDANCE: Add all stories organized by Epic. Use the template for each story.
Copy the story block and fill in each field. Leave no field empty — use TBD if unknown. -->

### Epic EP-01: {{EPIC_NAME}}

---

#### US-001: {{STORY_TITLE}}

| Attribute | Value |
|-----------|-------|
| Epic | EP-01: {{EPIC_NAME}} |
| Priority | Must Have | Should Have | Could Have |
| Story Points | 1 | 2 | 3 | 5 | 8 |
| Sprint | {{SPRINT_NUMBER}} |
| Assigned To | {{AGENT/PERSON}} |
| Status | Backlog | Ready | In Progress | Review | Done |
| FR Reference | FR-{{XXX}} |
| BR Reference | BR-{{XXX}} |

**Story:**
As a **{{PERSONA}}**,
I want **{{ACTION/FEATURE}}**,
So that **{{BENEFIT/OUTCOME}}**.

**Context:**
{{ADDITIONAL_CONTEXT_THAT_HELPS_UNDERSTAND_THE_STORY}}

**Acceptance Criteria:**
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}
- [ ] **Given** {{ERROR_CONDITION}}, **when** {{USER_ACTION}}, **then** {{ERROR_HANDLING}}

**Technical Notes:**
<!-- GUIDANCE: Optional — add only if there are specific implementation constraints or hints -->
- {{TECHNICAL_CONSTRAINT_OR_HINT}}

**UI/UX Notes:**
- Screen / component: {{SCREEN_NAME}}
- Design reference: {{FIGMA_LINK_OR_FILE}}
- Responsive behavior: {{NOTES}}

**Dependencies:**
- Blocked by: {{US-XXX | None}}
- Blocks: {{US-XXX | None}}
- External: {{THIRD_PARTY_DEPENDENCY | None}}

**Definition of Done:**
- [ ] Code complete and follows coding standards
- [ ] Unit tests written (≥ 80% coverage on new code)
- [ ] Code review approved by Tech Lead
- [ ] Merged to `develop`
- [ ] Deployed to staging
- [ ] All acceptance criteria manually verified
- [ ] No critical or high bugs open
- [ ] Documentation updated (if applicable)

---

#### US-002: {{STORY_TITLE}}

| Attribute | Value |
|-----------|-------|
| Epic | EP-01 |
| Priority | Must Have |
| Story Points | {{POINTS}} |
| Sprint | {{SPRINT}} |
| Assigned To | {{AGENT}} |
| Status | Backlog |
| FR Reference | FR-{{XXX}} |

**Story:**
As a **{{PERSONA}}**,
I want **{{ACTION}}**,
So that **{{BENEFIT}}**.

**Acceptance Criteria:**
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}

**Dependencies:** Blocked by: {{US-001 | None}}

**Definition of Done:** _(same as standard DoD above)_

---

### Epic EP-02: {{EPIC_NAME}}

---

#### US-010: {{STORY_TITLE}}

| Attribute | Value |
|-----------|-------|
| Epic | EP-02 |
| Priority | Should Have |
| Story Points | {{POINTS}} |
| Sprint | {{SPRINT}} |
| Assigned To | {{AGENT}} |
| Status | Backlog |

**Story:**
As a **{{PERSONA}}**,
I want **{{ACTION}}**,
So that **{{BENEFIT}}**.

**Acceptance Criteria:**
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}

**Dependencies:** None

**Definition of Done:** _(standard DoD)_

---

## 5. Story Estimation Guide

<!-- GUIDANCE: Use this guide for consistent story point estimation.
Story points measure complexity + effort + uncertainty, NOT hours. -->

| Points | Complexity | Examples |
|--------|-----------|---------|
| 1 | Trivial | Update a label, fix a CSS bug, add a config option |
| 2 | Simple | Simple form field, read-only data display, static page |
| 3 | Moderate | CRUD for one entity, simple filter, email notification |
| 5 | Complex | Multi-step form, API integration, complex UI component |
| 8 | Very Complex | New module with CRUD + logic + UI + tests |
| 13+ | Too Large | Break into smaller stories |

**Planning Poker:** Use async estimation — each team member estimates independently, then compare and discuss outliers.

---

## 6. Definition of Ready Checklist

<!-- GUIDANCE: A story is "ready" to enter a sprint only when ALL of these are true.
Moving stories into sprints before they're ready is a leading cause of sprint failure. -->

Before a story can be added to a sprint, verify:

- [ ] Story is written in As a / I want / So that format
- [ ] Story has at least 2 acceptance criteria in Given/When/Then format
- [ ] Story has been estimated in story points
- [ ] Dependencies are identified and not blocking
- [ ] UI/UX design exists (or story is backend-only)
- [ ] Technical approach is understood (no major unknowns)
- [ ] Priority is assigned (MoSCoW)
- [ ] Story size is ≤ 8 points (or confirmed as a spike)
- [ ] Acceptance criteria are testable by QA
- [ ] FR reference documented

---

## 7. Story Breakdown Techniques

<!-- GUIDANCE: Use these techniques when a story is too large for one sprint. -->

| Technique | When to Use | How |
|-----------|------------|-----|
| **CRUD Split** | Create/Read/Update/Delete are all in one story | Split into 4 stories (View, Create, Edit, Delete) |
| **Happy Path First** | Story handles many edge cases | First story = happy path only; subsequent stories = edge cases |
| **Data Variations** | Story handles many data types | Split by data type or category |
| **Workflow Steps** | Multi-step process in one story | Split by step (Step 1 as standalone value, etc.) |
| **User Type Split** | Different users, different experiences | One story per user type |
| **Performance Deferred** | Core function + performance optimization mixed | Functional story first; performance story second |
| **UI + API Split** | Full-stack story too large | API story first; UI story depends on API story |

---

## 8. Story Mapping Visualization

<!-- GUIDANCE: Story mapping organizes stories on a 2D grid:
- Horizontal axis: user journey / workflow (left to right = sequence)
- Vertical axis: priority (top = MVP, bottom = later releases)
This helps plan MVP scope and identify gaps in the user journey. -->

```
USER JOURNEY:  [Discovery] → [Registration] → [Core Feature] → [Management] → [Reporting]

MVP           US-001         US-020           US-030           US-040           —
(Release 1)

Release 2     —              US-021           US-031           US-041           US-050

Release 3     —              —                US-032           US-042           US-051
```

> _Replace with actual story IDs mapped to user journey steps and release priority_

---

## 9. Backlog Summary

<!-- GUIDANCE: Keep this summary table updated. It provides a quick view of backlog health. -->

| Epic | Total Stories | Estimated Points | In Sprint | Done | Remaining |
|------|-------------|-----------------|-----------|------|-----------|
| EP-01: {{NAME}} | {{COUNT}} | {{POINTS}} | {{COUNT}} | {{COUNT}} | {{COUNT}} |
| EP-02: {{NAME}} | | | | | |
| **Total** | | | | | |

**Velocity (last sprint):** {{STORY_POINTS_COMPLETED}}
**Projected completion:** Sprint {{X}} ({{DATE}})

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | | | |
| Reviewer | | | |
| Business Analyst | | | |
| Product Owner | | | |
| AI Director (John) | | | |

# Acceptance Criteria

# Acceptance Criteria: {{PROJECT_NAME}}

> **Project:** {{PROJECT_NAME}}
> **Version:** {{VERSION}}
> **Date:** {{DATE}}
> **Author:** {{AUTHOR}}
> **Status:** Draft | In Review | Approved
> **Reviewers:** {{REVIEWERS}}

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1     | {{DATE}} | {{AUTHOR}} | Initial draft |

---

<!-- GUIDANCE: Acceptance criteria define the conditions under which a feature is considered
"done" and accepted by the business. This document consolidates acceptance criteria at the
feature/module level (complementing the granular criteria in individual user stories).
It serves as the basis for UAT test cases and final sign-off. -->

## 1. Purpose & Methodology

### 1.1 What Are Acceptance Criteria?

Acceptance criteria are the conditions that a system must satisfy to be accepted by a stakeholder.
They answer the question: **"How will we know when this feature is done?"**

Good acceptance criteria are:
- **Testable** — Can be verified with a specific test procedure
- **Clear** — Unambiguous; no room for interpretation
- **Complete** — Cover happy path, error paths, and edge cases
- **Agreed** — Signed off by the business BEFORE development begins

### 1.2 Format: Given / When / Then (Gherkin-Style)

```
Given [an initial context / precondition that is true]
When  [an action or event occurs]
Then  [the expected outcome is observed]
And   [additional expected outcomes, chained]
```

**Example — User Login:**
```
Given a registered user with valid credentials
When the user submits the login form
Then the user is redirected to the dashboard
And a session token is created and stored in a secure cookie
And the last login timestamp is updated in the database
```

### 1.3 Categories of Acceptance Criteria

| Category | Description | Example |
|----------|-------------|---------|
| **Positive (Happy Path)** | System works as expected with valid inputs | Successful login |
| **Negative (Sad Path)** | System handles invalid inputs gracefully | Wrong password error |
| **Edge Case** | Boundary conditions and unusual but valid scenarios | Login at exact session timeout |
| **Integration** | System works correctly with external services | Payment processed via Stripe |
| **Non-Functional** | Performance, accessibility, security criteria | Page loads in < 2 seconds |
| **Data** | Correct data storage, retrieval, and validation | Fields saved with correct types |

---

## 2. Feature Acceptance Criteria

<!-- GUIDANCE: Organize by module/feature. For each feature, provide:
- Feature reference (FR-XXX)
- Business requirement reference (BR-XXX)
- Positive scenarios (at least 1)
- Negative scenarios (at least 1 per input type)
- Edge cases (boundary conditions)
Copy the feature block below for each feature. -->

---

### Module: {{MODULE_1_NAME}}

---

#### Feature: {{FEATURE_1_NAME}} (FR-{{XXX}})

**Feature Description:** {{BRIEF_DESCRIPTION}}
**Business Requirement:** BR-{{XXX}}
**Linked User Stories:** US-{{XXX}}, US-{{XXX}}

**Positive Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-001 | {{SCENARIO_NAME}} | {{PRECONDITION}} | {{ACTION}} | {{EXPECTED_RESULT}} |
| AC-002 | | | | |

**Negative Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-003 | {{INVALID_INPUT_SCENARIO}} | {{PRECONDITION_WITH_BAD_DATA}} | {{ACTION}} | {{ERROR_MESSAGE_OR_BEHAVIOR}} |
| AC-004 | | | | |

**Edge Cases:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-005 | {{BOUNDARY_CONDITION}} | {{EDGE_CONDITION}} | {{ACTION}} | {{EXPECTED_RESULT}} |

**Non-Functional Acceptance Criteria:**

| # | Category | Criterion |
|---|----------|-----------|
| AC-006 | Performance | Feature completes in < {{X}} seconds under normal load |
| AC-007 | Accessibility | Feature is fully operable by keyboard; ARIA labels present |
| AC-008 | Security | {{SECURITY_CRITERION_IF_APPLICABLE}} |

---

#### Feature: User Registration (FR-020)

**Feature Description:** New users can create accounts using email and password.
**Business Requirement:** BR-{{XXX}}
**Linked User Stories:** US-{{XXX}}

**Positive Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-010 | Successful registration | A user visits /register with a valid, unregistered email | User submits form with valid email, strong password, and required fields | Account is created; confirmation email sent; user redirected to email verification page |
| AC-011 | Email verification sent | Account was just created | System processes registration | Verification email arrives within 2 minutes with unique, expiring link |
| AC-012 | Verification link works | User receives verification email | User clicks verification link | Email verified; user redirected to login; account marked as verified |

**Negative Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-013 | Duplicate email | An account already exists with email@example.com | User submits registration with email@example.com | Error "An account with this email already exists" shown; no new account created |
| AC-014 | Weak password | User is on registration form | User submits password "abc123" | Inline error shown: "Password must be at least 8 characters and include uppercase, number, and special character" |
| AC-015 | Invalid email format | User is on registration form | User submits "notanemail" in email field | Inline validation error shown before form submission |
| AC-016 | Empty required field | User is on registration form | User submits with required field empty | Inline error shown; form not submitted |

**Edge Cases:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-017 | Email with plus addressing | User submits user+tag@example.com | Registration submitted | Account created; treated as valid email |
| AC-018 | Verification link expiry | Verification link generated 25+ hours ago | User clicks expired link | Error "Verification link has expired"; option to resend verification email shown |
| AC-019 | Double registration attempt | User submits form; due to slow network submits twice | Two identical POST requests sent | Only one account created; second request returns appropriate error |

---

#### Feature: User Login (FR-021)

**Positive Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-020 | Successful login | A verified user with valid credentials | User submits login form | Authenticated; redirected to dashboard; session created |
| AC-021 | Remember me | A verified user checks "Remember Me" | User submits login form | Session persists for 30 days; user stays logged in after browser close |

**Negative Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-022 | Wrong password | A registered user exists | User submits incorrect password | Generic error "Invalid email or password" (no enumeration); login not granted |
| AC-023 | Non-existent email | No account for this email | User submits login | Same generic error "Invalid email or password" (prevent user enumeration) |
| AC-024 | Account locked | User has made 5 failed attempts | User attempts login again | Message: "Account temporarily locked. Try again in 15 minutes." |

**Edge Cases:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-025 | Session expiry | User has been idle for 31 minutes | User attempts to navigate | Redirected to login; session cleared; unsaved work warning shown |
| AC-026 | Login on unverified account | Account created but email not verified | User attempts to log in | Error "Please verify your email before logging in" with option to resend |

---

#### Feature: {{NEXT_FEATURE_NAME}} (FR-{{XXX}})

<!-- Copy and fill this block for each additional feature -->

**Positive Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-{{NEXT}} | | | | |

**Negative Scenarios:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-{{NEXT}} | | | | |

**Edge Cases:**

| # | Scenario | Given | When | Then |
|---|----------|-------|------|------|
| AC-{{NEXT}} | | | | |

---

## 3. Integration Scenarios

<!-- GUIDANCE: Integration scenarios test that your system works correctly with external services.
These often require special test environments (sandbox mode, mock services). -->

| # | Integration | Scenario | Expected Behavior | Test Environment |
|---|------------|---------|------------------|-----------------|
| INT-001 | {{EXTERNAL_SERVICE}} | {{SCENARIO}} | {{EXPECTED}} | Sandbox / Mock |
| INT-002 | Email provider | Transactional email delivery | Email received within 2 minutes | Mailtrap / staging |
| INT-003 | {{PAYMENT_PROVIDER}} | Successful payment | Transaction recorded; confirmation shown; webhook received | Stripe test mode |
| INT-004 | {{PAYMENT_PROVIDER}} | Payment declined | User sees friendly error; no order created; no double-charge | Stripe test mode |
| INT-005 | {{THIRD_PARTY_API}} | API timeout | System shows user-friendly error; request logged; no data corruption | Mocked timeout |
| INT-006 | {{THIRD_PARTY_API}} | API unavailable | System degrades gracefully; non-dependent features still work | Service unavailable mock |

---

## 4. Non-Functional Acceptance Criteria

<!-- GUIDANCE: These criteria apply across all features. Reference the NFR document for targets.
Each item here is a must-pass before any milestone or production release. -->

### 4.1 Performance

| # | Criterion | Target | Test Method |
|---|-----------|--------|-------------|
| NF-AC-001 | All pages load within target time | < 3s initial, < 1.5s subsequent | Lighthouse on staging |
| NF-AC-002 | All API endpoints respond within target | < 500ms at p95 under normal load | k6 load test |
| NF-AC-003 | Core Web Vitals pass | LCP < 2.5s, CLS < 0.1, FCP < 1.8s | Lighthouse |

### 4.2 Accessibility

| # | Criterion | Target | Test Method |
|---|-----------|--------|-------------|
| NF-AC-010 | No critical accessibility violations | 0 critical violations | axe-core automated scan |
| NF-AC-011 | Keyboard navigation complete | All features operable without mouse | Manual test |
| NF-AC-012 | Color contrast compliant | ≥ 4.5:1 text/background | Contrast checker |

### 4.3 Security

| # | Criterion | Target | Test Method |
|---|-----------|--------|-------------|
| NF-AC-020 | No OWASP Top 10 vulnerabilities | 0 critical/high findings | OWASP ZAP scan |
| NF-AC-021 | All user inputs sanitized | No XSS/injection vulnerabilities | SAST + manual testing |
| NF-AC-022 | No sensitive data in client-side code | No API keys, tokens in browser | Code review + browser DevTools |

---

## 5. UAT Scenario Mapping

<!-- GUIDANCE: This table maps acceptance criteria to UAT test scenarios.
The UAT team uses this to prepare their test scripts. -->

| AC ID | AC Description | UAT Scenario ID | UAT Tester | Status |
|-------|---------------|-----------------|-----------|--------|
| AC-010 | Successful registration | UAT-001 | {{TESTER}} | Not Started |
| AC-011 | Email verification sent | UAT-002 | | |
| AC-020 | Successful login | UAT-003 | | |
| INT-003 | Payment success | UAT-010 | | |
| NF-AC-001 | Page load performance | UAT-P01 | | |

---

## 6. Traceability to Requirements

<!-- GUIDANCE: Every acceptance criterion must trace back to a requirement.
Orphaned acceptance criteria (no requirement) suggest scope creep.
Requirements with no acceptance criteria will not be verifiable. -->

| AC ID | Acceptance Criterion | FR Reference | BR Reference | US Reference |
|-------|---------------------|-------------|-------------|-------------|
| AC-001 | {{CRITERION}} | FR-{{XXX}} | BR-{{XXX}} | US-{{XXX}} |
| AC-010 | Successful registration | FR-020 | BR-{{XXX}} | US-{{XXX}} |

> Full traceability: `[requirements-traceability-matrix.md](requirements-traceability-matrix.md)`

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | | | |
| Reviewer | | | |
| Business Analyst | | | |
| Product Owner | | | |
| QA Engineer | | | |
| AI Director (John) | | | |
| Client Representative | | | |

# Requirements Traceability Matrix

# Requirements Traceability Matrix (RTM): {{PROJECT_NAME}}

> **Project:** {{PROJECT_NAME}}
> **Version:** {{VERSION}}
> **Date:** {{DATE}}
> **Author:** {{AUTHOR}}
> **Status:** Draft | In Review | Approved
> **Reviewers:** {{REVIEWERS}}

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1     | {{DATE}} | {{AUTHOR}} | Initial draft |

---

<!-- GUIDANCE: The RTM maps requirements through the full SDLC:
Business Requirement → Functional Requirement → User Story → Design → Code → Test Cases.
Purpose: Ensure every requirement is implemented and tested; catch gaps and orphans.
Maintain this document throughout the project — update it when requirements or tests change. -->

## 1. Purpose of Traceability

The Requirements Traceability Matrix serves four functions:

1. **Coverage Assurance** — Every business requirement has an implementation path and test cases
2. **Change Impact** — When a requirement changes, quickly identify all affected code and tests
3. **Gap Detection** — Identify requirements with no tests (coverage gap) or tests with no requirements (scope creep)
4. **Audit Trail** — Demonstrates compliance with processes for client sign-off and quality gates

**Traceability Directions:**
- **Forward Traceability** — BR → FR → Code → Test (did we build what was required?)
- **Backward Traceability** — Test → Code → FR → BR (does everything we built have a justification?)

---

## 2. Document References

| Document | Location | Version | Last Updated |
|----------|----------|---------|-------------|
| Business Requirements Document (BRD) | `[brd.md](brd.md)` | {{VERSION}} | {{DATE}} |
| Functional Requirements Spec (FRS) | `[functional-requirements.md](functional-requirements.md)` | {{VERSION}} | {{DATE}} |
| Non-Functional Requirements | `[non-functional-requirements.md](non-functional-requirements.md)` | {{VERSION}} | {{DATE}} |
| User Stories | `[user-stories.md](user-stories.md)` | {{VERSION}} | {{DATE}} |
| Acceptance Criteria | `[acceptance-criteria.md](acceptance-criteria.md)` | {{VERSION}} | {{DATE}} |
| Test Plan | `[../../TESTING/test-plan.md](../../TESTING/test-plan.md)` | {{VERSION}} | {{DATE}} |
| Test Cases | `[../../TESTING/test-case.md](../../TESTING/test-case.md)` | {{VERSION}} | {{DATE}} |

---

## 3. Forward Traceability Matrix

<!-- GUIDANCE: This is the primary traceability table. Every row = one business requirement.
Columns trace it through design, implementation, and testing.
Status codes: ✅ Complete | ⏳ In Progress | ❌ Not Started | N/A Not Applicable | ⚠️ At Risk -->

### 3.1 Functional Requirements Traceability

| BR ID | Business Requirement | FR ID | Functional Requirement | US ID | Design Reference | Code Module / Component | Unit Test | Integration Test | AC ID | Status |
|-------|---------------------|-------|----------------------|-------|-----------------|------------------------|-----------|-----------------|-------|--------|
| BR-001 | {{BUSINESS_REQ}} | FR-001 | {{FUNC_REQ}} | US-001 | `figma/screen-01` | `src/modules/{{MODULE}}` | ✅ | ⏳ | AC-001 | ⏳ In Progress |
| BR-002 | | FR-002 | | US-002 | | | ❌ | ❌ | AC-003 | ❌ Not Started |
| BR-003 | | FR-010 | | US-010 | | | | | | |
| BR-004 | | FR-011 | | US-011 | | | | | | |
| BR-005 | | FR-020 | User Registration | US-020 | `figma/register` | `src/auth/register` | ⏳ | ❌ | AC-010 | ⏳ |
| BR-006 | | FR-021 | User Login | US-021 | `figma/login` | `src/auth/login` | ⏳ | ❌ | AC-020 | ⏳ |
| BR-007 | | FR-030 | | | | | | | | |

### 3.2 Non-Functional Requirements Traceability

| NFR ID | Requirement | Target | Test Type | Test Case ID | Status |
|--------|------------|--------|-----------|-------------|--------|
| NFR-P01 | Page load time < 3s | < 3s (initial) | Performance | PERF-001 | ❌ |
| NFR-P03 | API response < 500ms | p95 < 500ms | Performance | PERF-002 | ❌ |
| NFR-SEC01 | Authentication | JWT/OAuth2 | Security | SEC-001 | ❌ |
| NFR-SEC06 | Input validation | No injection | Security / SAST | SEC-010 | ❌ |
| NFR-U03 | WCAG 2.1 AA | Level AA | Accessibility | A11Y-001 | ❌ |
| NFR-A01 | Uptime SLA ≥ 99.5% | 99.5% monthly | Operations | OPS-001 | N/A |
| NFR-COMP01 | GDPR compliance | Full compliance | Compliance audit | COMP-001 | ❌ |

---

## 4. Backward Traceability Matrix

<!-- GUIDANCE: Start from test cases and trace back to requirements.
This reveals whether any test cases test functionality that wasn't actually required (potential scope creep)
or whether test cases exist without requirements (danger zone). -->

| Test Case ID | Test Description | AC ID | FR ID | BR ID | Has Requirement? |
|-------------|-----------------|-------|-------|-------|-----------------|
| TC-001 | {{TEST_DESCRIPTION}} | AC-{{XXX}} | FR-{{XXX}} | BR-{{XXX}} | ✅ Yes |
| TC-002 | | | | | ✅ Yes |
| TC-010 | {{TEST_WITHOUT_REQUIREMENT}} | — | — | — | ⚠️ No — investigate |

---

## 5. Coverage Analysis

<!-- GUIDANCE: Update this section weekly during development.
Low coverage numbers are early warning signs — address before they become testing blockers. -->

### 5.1 Requirement Coverage Summary

| Category | Total Count | Fully Covered | Partially Covered | Not Covered | Coverage % |
|----------|-------------|--------------|-------------------|-------------|-----------|
| Business Requirements (BR) | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{PCT}}% |
| Functional Requirements (FR) | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{PCT}}% |
| Non-Functional Requirements (NFR) | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{PCT}}% |
| User Stories (US) | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{PCT}}% |
| Acceptance Criteria (AC) | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{PCT}}% |

**Overall Requirement Coverage:** {{PCT}}%
**Target:** ≥ 95% before UAT; 100% before production release

### 5.2 Test Coverage Summary

| Test Type | Total Tests | Passing | Failing | Skipped | Coverage |
|-----------|------------|---------|---------|---------|----------|
| Unit tests | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{PCT}}% |
| Integration tests | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{PCT}}% |
| E2E / UAT scenarios | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{COUNT}} | {{PCT}}% |
| Performance tests | {{COUNT}} | | | | |
| Security tests | {{COUNT}} | | | | |

---

## 6. Gap Identification

<!-- GUIDANCE: A gap is a requirement that has no test case, or a test case that has no requirement.
List ALL gaps here and assign owners to close them before the next milestone. -->

### 6.1 Requirements Without Test Coverage

| Requirement ID | Description | Gap Type | Action Required | Owner | Target Date |
|---------------|-------------|----------|----------------|-------|-------------|
| FR-{{XXX}} | {{DESCRIPTION}} | No test cases written | Create test cases TC-{{XXX}} | QA | {{DATE}} |
| BR-{{XXX}} | | No functional requirement | Write FR-{{XXX}} | BA | {{DATE}} |

### 6.2 Test Cases Without Requirements (Orphans)

<!-- GUIDANCE: Orphaned test cases may indicate scope creep or deleted requirements.
Investigate each one — either link it to a requirement or delete the test case. -->

| Test Case ID | Description | Status | Action |
|-------------|-------------|--------|--------|
| TC-{{XXX}} | {{DESCRIPTION}} | Orphaned | Investigate: link to req or delete |

### 6.3 Requirements Without Design Reference

| Requirement ID | Description | Action |
|---------------|-------------|--------|
| FR-{{XXX}} | {{DESCRIPTION}} | Request design mockup from Designer |

---

## 7. Change Impact Tracking

<!-- GUIDANCE: When a requirement changes, this table tracks what else must change.
Use this BEFORE approving change requests to understand full impact. -->

| Change Request ID | Changed Requirement | Impact on FR | Impact on Code | Impact on Tests | Impact Assessment | CR Status |
|-----------------|--------------------|--------------|--------------|-----------------|--------------------|-----------|
| CR-001 | {{REQUIREMENT_CHANGE}} | FR-{{XXX}} needs update | `src/{{MODULE}}` affected | TC-{{XXX}} needs update | {{EFFORT_ESTIMATE}} | {{APPROVED/PENDING}} |

---

## 8. Traceability Status Dashboard

<!-- GUIDANCE: This summary is updated weekly and presented at sprint reviews.
It gives stakeholders a single-page view of requirements health. -->

**Last Updated:** {{DATE}}
**Updated By:** {{NAME}}

| Metric | Value | Target | Status |
|--------|-------|--------|--------|
| Total Business Requirements | {{COUNT}} | — | |
| BRs with FR coverage | {{COUNT}} / {{TOTAL}} | 100% | {{✅/⚠️/❌}} |
| FRs with test coverage | {{COUNT}} / {{TOTAL}} | 100% | {{✅/⚠️/❌}} |
| Test cases passing | {{COUNT}} / {{TOTAL}} | 100% | {{✅/⚠️/❌}} |
| Open gaps | {{COUNT}} | 0 | {{✅/⚠️/❌}} |
| Change requests open | {{COUNT}} | ≤ 3 at a time | {{✅/⚠️/❌}} |
| UAT sign-off pending | {{COUNT}} | 0 at launch | {{✅/⚠️/❌}} |

**Overall RTM Health:** {{GREEN / AMBER / RED}}

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | | | |
| Reviewer | | | |
| Business Analyst | | | |
| QA Engineer | | | |
| Tech Lead | | | |
| AI Director (John) | | | |

# Functional Requirements

# Functional Requirements Specification (FRS): {{PROJECT_NAME}}

> **Project:** {{PROJECT_NAME}}
> **Version:** {{VERSION}}
> **Date:** {{DATE}}
> **Author:** {{AUTHOR}}
> **Status:** Draft | In Review | Approved
> **Reviewers:** {{REVIEWERS}}

## Document History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 0.1     | {{DATE}} | {{AUTHOR}} | Initial draft |

---

<!-- GUIDANCE: The FRS describes system behavior in detail — what the system does, not how it is built.
It bridges the BRD (business needs) and the Technical Spec (implementation).
Written by BA + Tech Lead. Every requirement must be testable and trace to a business requirement. -->

## 1. System Overview

<!-- GUIDANCE: Describe the system at a high level. What is it? Who uses it? What are its main capabilities?
Include a context diagram showing the system and its external interactions. -->

**System Name:** {{SYSTEM_NAME}}
**System Purpose:** {{PURPOSE_2_3_SENTENCES}}

**System Context Diagram:**

```mermaid
graph TB
    subgraph "{{SYSTEM_NAME}}"
        UI[Web / Mobile UI]
        API[Backend API]
        DB[(Database)]
    end
    U1[{{USER_TYPE_1}}] -->|Uses| UI
    U2[{{USER_TYPE_2}}] -->|Uses| UI
    API -->|Reads/Writes| DB
    API -->|Integrates| EXT1[{{EXTERNAL_SERVICE_1}}]
    API -->|Integrates| EXT2[{{EXTERNAL_SERVICE_2}}]
    ADM[Admin] -->|Manages| UI
```

---

## 2. Actors & Personas

<!-- GUIDANCE: Actors are all users and external systems that interact with the system.
Personas add context about who these users really are, which drives UX decisions. -->

| Actor ID | Actor Name | Type | Description | Access Level |
|----------|-----------|------|-------------|-------------|
| ACT-01 | {{ACTOR_NAME}} | Human / System | {{DESCRIPTION}} | {{ROLE/PERMISSIONS}} |
| ACT-02 | End User | Human | {{PERSONA_DESCRIPTION}} | Authenticated user |
| ACT-03 | Administrator | Human | Manages system configuration and users | Admin |
| ACT-04 | {{EXTERNAL_SYSTEM}} | System | External service integrated via API | System |

### Persona Detail

<!-- GUIDANCE: For each key human actor, add a brief persona card. -->

**Persona: {{PERSONA_NAME}}**
- **Role:** {{JOB_TITLE}}
- **Goal:** {{PRIMARY_GOAL_USING_SYSTEM}}
- **Pain Points:** {{CURRENT_FRUSTRATIONS}}
- **Tech Savviness:** Low / Medium / High
- **Frequency of Use:** Daily / Weekly / Monthly

---

## 3. Functional Requirements

<!-- GUIDANCE: Organize requirements by module/feature. Within each module:
- FR-XXX = unique ID (sequential across all modules)
- Priority = MoSCoW (Must/Should/Could/Won't for this release)
- Acceptance Criteria = Given/When/Then (testable conditions for done)
- Trace = BRD requirement ID this satisfies -->

### 3.1 Module: {{MODULE_1_NAME}}
<!-- GUIDANCE: e.g., Authentication, User Management, Dashboard, Reporting, Notifications -->

#### Module Overview
{{MODULE_DESCRIPTION}}

---

**FR-001: {{FEATURE_NAME}}**

| Attribute | Value |
|-----------|-------|
| Module | {{MODULE_1_NAME}} |
| Priority | Must Have |
| Trace | BR-{{XXX}} |
| UI Reference | `[Figma link or mockup filename]` |

**Description:**
{{FEATURE_DESCRIPTION_IN_BUSINESS_LANGUAGE}}

**Acceptance Criteria:**
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}
- [ ] **Given** invalid input, **when** {{USER_ACTION}}, **then** {{ERROR_HANDLING}}

**Data Requirements:**
- Input: {{INPUT_DATA_FIELDS_AND_TYPES}}
- Output: {{OUTPUT_DATA}}
- Validation: {{VALIDATION_RULES}}

**Business Rules:**
- RUL-{{XX}}: {{APPLICABLE_BUSINESS_RULE}}

**Dependencies:** FR-{{XXX}}, DEP-{{XX}}

---

**FR-002: {{FEATURE_NAME}}**

| Attribute | Value |
|-----------|-------|
| Module | {{MODULE_1_NAME}} |
| Priority | Must Have |
| Trace | BR-{{XXX}} |
| UI Reference | |

**Description:**
{{FEATURE_DESCRIPTION}}

**Acceptance Criteria:**
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}

**Data Requirements:**
- Input: {{INPUT}}
- Output: {{OUTPUT}}
- Validation: {{VALIDATION}}

**Business Rules:** {{APPLICABLE_RULES}}

**Dependencies:** {{DEPENDENCIES}}

---

### 3.2 Module: {{MODULE_2_NAME}}

#### Module Overview
{{MODULE_DESCRIPTION}}

---

**FR-010: {{FEATURE_NAME}}**

| Attribute | Value |
|-----------|-------|
| Module | {{MODULE_2_NAME}} |
| Priority | Must Have |
| Trace | BR-{{XXX}} |
| UI Reference | |

**Description:**
{{FEATURE_DESCRIPTION}}

**Acceptance Criteria:**
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}
- [ ] **Given** {{PRECONDITION}}, **when** {{USER_ACTION}}, **then** {{EXPECTED_RESULT}}

**Data Requirements:**
- Input: {{INPUT}}
- Output: {{OUTPUT}}
- Validation: {{VALIDATION}}

**Business Rules:** {{APPLICABLE_RULES}}

**Dependencies:** {{DEPENDENCIES}}

---

### 3.3 Module: Authentication & Authorization

<!-- GUIDANCE: Every system with user accounts needs this section. Adapt to the auth method used. -->

**FR-020: User Registration**
| Attribute | Value |
|-----------|-------|
| Priority | Must Have |
| Trace | BR-{{XXX}} |

**Description:** Users can create a new account using email and password.

**Acceptance Criteria:**
- [ ] **Given** a valid email and password (≥8 chars, 1 uppercase, 1 number), **when** user submits registration form, **then** account is created and confirmation email is sent
- [ ] **Given** an already-registered email, **when** user tries to register, **then** system shows "Email already in use" error
- [ ] **Given** password does not meet complexity rules, **when** user submits, **then** inline validation error shown before submit

**Data Requirements:**
- Input: email (unique), password, {{ADDITIONAL_FIELDS}}
- Output: user record, confirmation token
- Validation: email format, password complexity, duplicate check

---

**FR-021: User Login**
| Attribute | Value |
|-----------|-------|
| Priority | Must Have |
| Trace | BR-{{XXX}} |

**Description:** Authenticated users can log in with email and password.

**Acceptance Criteria:**
- [ ] **Given** valid credentials, **when** user submits login form, **then** user is authenticated and redirected to dashboard
- [ ] **Given** invalid credentials, **when** user submits, **then** generic error "Invalid email or password" is shown (no enumeration)
- [ ] **Given** 5 consecutive failed attempts, **when** user tries again, **then** account is temporarily locked for 15 minutes
- [ ] **Given** an authenticated session, **when** user is idle for 30 minutes, **then** session expires and user is redirected to login

---

### 3.4 Module: {{MODULE_N_NAME}}

**FR-030: {{FEATURE_NAME}}**
<!-- Add as many modules and features as needed following the pattern above -->

---

## 4. Use Case Diagrams

<!-- GUIDANCE: Use case diagrams show which actors can perform which actions.
Create one diagram per major module, or one overall diagram for simpler systems. -->

### 4.1 {{MODULE_1_NAME}} Use Cases

```mermaid
graph LR
    A1(({{ACTOR_1}})) --> UC1[FR-001: {{FEATURE}}]
    A1 --> UC2[FR-002: {{FEATURE}}]
    A2(({{ACTOR_2}})) --> UC3[FR-010: {{FEATURE}}]
    A2 --> UC4[FR-011: {{FEATURE}}]
    A3((Admin)) --> UC5[FR-020: {{FEATURE}}]
    A3 --> UC6[FR-021: {{FEATURE}}]
```

### 4.2 System-Level Use Case Overview

```mermaid
graph LR
    subgraph "{{SYSTEM_NAME}}"
        UC1[{{MODULE_1}} Functions]
        UC2[{{MODULE_2}} Functions]
        UC3[Auth Functions]
    end
    ACT1(({{ACTOR_1}})) --> UC1
    ACT1 --> UC3
    ACT2(({{ACTOR_2}})) --> UC2
    ACT2 --> UC3
    ACT3((Admin)) --> UC1
    ACT3 --> UC2
    ACT3 --> UC3
```

---

## 5. System Behavior Specifications

<!-- GUIDANCE: Document system-level behaviors that apply across multiple features.
These are not tied to a single feature but are fundamental to how the system operates. -->

### 5.1 Error Handling

- All user-facing errors must display a human-readable message (no stack traces)
- All errors must be logged with correlation ID, timestamp, user ID (if authenticated), and action
- Validation errors shown inline, adjacent to the invalid field
- System errors show generic message + contact info; full detail logged server-side only

### 5.2 Data Persistence

- All user-submitted data must be persisted within {{X}} seconds
- Optimistic UI updates must be rolled back if server confirmation fails
- All mutations (create/update/delete) must be audited with user ID and timestamp

### 5.3 Session & State

- Session timeout: {{X}} minutes of inactivity
- Concurrent session behavior: {{ALLOW/BLOCK/NOTIFY}}
- Browser refresh: application state must be restored from server

### 5.4 Notifications

- Email notifications: {{WHICH_EVENTS_TRIGGER_EMAILS}}
- In-app notifications: {{WHICH_EVENTS_TRIGGER_IN_APP}}
- Push notifications: {{IF_APPLICABLE}}
- Unsubscribe mechanism required for all marketing emails (GDPR)

### 5.5 Accessibility

- WCAG 2.1 Level AA compliance required
- Keyboard navigation for all interactive elements
- Screen reader compatibility (ARIA labels)
- Color contrast ratio ≥ 4.5:1

---

## 6. Requirements Summary Table

<!-- GUIDANCE: This summary table enables quick scanning of all requirements.
Update this table as requirements are added, changed, or approved. -->

| ID | Feature Name | Module | Priority | Status | Trace |
|----|-------------|--------|----------|--------|-------|
| FR-001 | {{FEATURE}} | {{MODULE}} | Must Have | Draft | BR-001 |
| FR-002 | | | | | |
| FR-010 | | | | | |
| FR-020 | User Registration | Auth | Must Have | Draft | BR-xxx |
| FR-021 | User Login | Auth | Must Have | Draft | BR-xxx |

**Requirements Count:**
- Must Have: {{COUNT}}
- Should Have: {{COUNT}}
- Could Have: {{COUNT}}
- Won't Have (this release): {{COUNT}}

---

## 7. Traceability to Business Requirements

<!-- GUIDANCE: Every functional requirement must trace to at least one business requirement from the BRD.
Orphaned requirements (no trace) should be questioned. -->

| FR ID | Feature Name | Business Requirement (BR ID) | Business Objective (BO ID) |
|-------|-------------|------------------------------|---------------------------|
| FR-001 | {{FEATURE}} | BR-{{XXX}} | BO-{{XX}} |
| FR-002 | | | |

> Full traceability matrix: `[requirements-traceability-matrix.md](requirements-traceability-matrix.md)`

---

## Approval

| Role | Name | Date | Signature |
|------|------|------|-----------|
| Author | | | |
| Reviewer | | | |
| Business Analyst | | | |
| Tech Lead | | | |
| Product Owner | | | |
| AI Director (John) | | | |
| Client Representative | | | |

# Functional Requirements Specification

# Functional Requirements Specification (FRS): Bilko

> **Project:** Bilko — Balkan Accounting SaaS
> **Version:** 1.0
> **Date:** 2026-02-25
> **Author:** John (AI Director)
> **Status:** Final
> **Reviewers:** Alem Bašić (CEO)

## Document History

| Version | Date       | Author             | Changes                            |
| ------- | ---------- | ------------------ | ---------------------------------- |
| 0.1     | 2026-02-23 | John (AI Director) | Initial draft — Phase 1 Serbia MVP |
| 1.0     | 2026-02-25 | John (AI Director) | Finalized for v1.0 release         |

---

## 1. System Overview

**System Name:** Bilko — Balkan Accounting SaaS
**System Purpose:** Bilko is a cloud-based accounting platform for Balkan SMBs that handles e-invoicing (Serbian SEF), expense tracking, double-entry bookkeeping, bank reconciliation, VAT/PDV management, and financial reporting. It provides a simple, compliant, affordable alternative to legacy ERP systems, accessible from any browser.

**System Context Diagram:**

```mermaid
graph TB
    subgraph "Bilko Platform"
        UI[Web App\nNext.js 15 + React 19]
        API[Backend API\nExpress + TypeScript]
        DB[(PostgreSQL\nPrisma ORM)]
    end
    U1[SMB Owner] -->|Uses| UI
    U2[Accountant] -->|Uses| UI
    U3[Viewer / Employee] -->|Read-only| UI
    API -->|Reads/Writes| DB
    API -->|Submits e-invoices| SEF[SEF Platform\nefaktura.gov.rs]
    API -->|Sends invoice PDFs| EMAIL[Email Provider\nTransactional]
    API -->|Fetches rates| FX[Exchange Rate API\nECB / fixer.io]
    ADM[Admin\nOrg Owner] -->|Manages org + users| UI
```

---

## 2. Actors & Personas

| Actor ID | Actor Name         | Type   | Description                                                | Access Level                                             |
| -------- | ------------------ | ------ | ---------------------------------------------------------- | -------------------------------------------------------- |
| ACT-01   | Organization Owner | Human  | Business owner who created the Bilko account; full control | Owner role — all permissions                             |
| ACT-02   | Admin              | Human  | Designated admin (accountant or office manager)            | Admin role — all except billing                          |
| ACT-03   | Accountant         | Human  | External bookkeeper managing the organization's books      | Accountant role — financial data, reports; cannot delete |
| ACT-04   | Viewer             | Human  | Employee or partner with read-only access                  | Viewer role — read only                                  |
| ACT-05   | SEF Platform       | System | Serbian government e-invoice platform                      | External API                                             |
| ACT-06   | Email Provider     | System | Transactional email for invoice delivery                   | External API                                             |
| ACT-07   | Exchange Rate API  | System | Currency rate provider (ECB / fixer.io)                    | External API                                             |

### Persona Detail

**Persona: Marko Petrović — SMB Owner**

- **Role:** Owner of a 8-person IT consulting firm in Belgrade
- **Goal:** Create and submit SEF invoices fast; see real-time P&L; file PDV without an accountant
- **Pain Points:** SEF portal is slow; Pantheon is complex; doesn't understand bookkeeping jargon
- **Tech Savviness:** Medium — uses Google Suite, smartphones, but not accounting software
- **Frequency of Use:** Daily (invoices) + monthly (PDV report)

**Persona: Ana Nikolić — Accountant**

- **Role:** Independent bookkeeper managing 12 SMB clients
- **Goal:** Access all client organizations from one login; export VAT reports in required formats
- **Pain Points:** Each client uses different software; reconciliation takes too long each month
- **Tech Savviness:** High — experienced with accounting software, Excel, CSV workflows
- **Frequency of Use:** Daily across multiple client orgs

---

## 3. Functional Requirements

### 3.1 Module: Authentication & User Management

#### Module Overview

Handles user registration, login, session management, organization creation, and role-based access control (RBAC). Multi-tenant: one user can belong to multiple organizations.

---

**FR-001: User Registration**

> ⚠️ **SUPERSEDED (2026-06-25).** Email/password registration is RETIRED. Auth is **Microsoft Entra External ID (CIAM) SSO only** — the email/password endpoints return HTTP 410 (`AuthRoutes.kt` ~242/254). New users are provisioned via Entra JIT on first SSO login, or via the FR-003 tokenized invite flow (`/accept-invite` → Entra SSO). The criteria below (password complexity, verification email) DO NOT apply. Retained for historical trace only.

| Attribute    | Value                 |
| ------------ | --------------------- |
| Module       | Authentication        |
| Priority     | Must Have             |
| Trace        | BR-014                |
| UI Reference | `/auth/register` page |

**Description:**
A new user registers with email and password. On successful registration, a verification email is sent and a default organization is created for the user with Owner role.

**Acceptance Criteria:**

- [ ] **Given** a valid, unregistered email and strong password (≥8 chars, 1 uppercase, 1 number), **when** user submits registration form, **then** account is created, verification email sent, user redirected to email verification page
- [ ] **Given** an already-registered email, **when** user submits, **then** error "An account with this email already exists" shown; no account created
- [ ] **Given** password does not meet complexity rules, **when** user submits, **then** inline validation error shown before submission

**Data Requirements:**

- Input: email (unique), password, full name, organization name
- Output: user record, organization record, Owner role assignment, verification token
- Validation: email format, password complexity, uniqueness check

**Business Rules:** RUL-08 (org scoping from first login)

---

**FR-002: User Login**

> ⚠️ **SUPERSEDED (2026-06-25).** Email/password login is RETIRED (HTTP 410). Login is **Microsoft Entra External ID (CIAM) SSO only** — `/login` triggers `signInWithMicrosoft()` → `*.ciamlogin.com`; backend issues the session from the Entra id_token (`AuthService.createSessionFromEntraIdToken`). The email/password criteria below DO NOT apply. Retained for historical trace only.

| Attribute    | Value              |
| ------------ | ------------------ |
| Module       | Authentication     |
| Priority     | Must Have          |
| Trace        | BR-014             |
| UI Reference | `/auth/login` page |

**Description:**
Authenticated users log in with email and password. Returns JWT access token (15-min TTL) + refresh token (30-day TTL).

**Acceptance Criteria:**

- [ ] **Given** valid credentials, **when** user submits login, **then** JWT issued, user redirected to dashboard
- [ ] **Given** invalid credentials, **when** user submits, **then** generic error "Invalid email or password" (no user enumeration)
- [ ] **Given** 5 consecutive failed attempts, **when** user tries again, **then** account locked for 15 minutes
- [ ] **Given** idle session > 30 minutes, **when** user attempts action, **then** redirected to login

---

**FR-003: Invite User to Organization**

| Attribute    | Value                 |
| ------------ | --------------------- |
| Module       | Authentication        |
| Priority     | Must Have             |
| Trace        | BR-007                |
| UI Reference | `/settings/team` page |

**Description:**
Organization Owner or Admin can invite users by email with a specific role (Admin, Accountant, Viewer). Invited user receives email with accept link; on acceptance, they are added to the organization with the assigned role.

**Acceptance Criteria:**

- [ ] **Given** an Owner invites user@email.com as Accountant, **when** invite is sent, **then** invitation email received within 2 minutes with unique accept link
- [ ] **Given** invited user accepts link within 48 hours, **when** they register or log in, **then** added to organization with Accountant role
- [ ] **Given** invite link expires (48h), **when** user clicks link, **then** error shown with option to request new invite

---

### 3.2 Module: Invoicing

#### Module Overview

Core invoicing functionality. Create, edit, preview, send, and track invoices. For Serbia: automatic SEF submission on send. Multi-currency. PDF generation with client/Bilko branding.

---

**FR-010: Create Invoice**

| Attribute    | Value                              |
| ------------ | ---------------------------------- |
| Module       | Invoicing                          |
| Priority     | Must Have                          |
| Trace        | BR-001, BR-002, BR-004, BR-008     |
| UI Reference | `/invoices/create` — 6-step wizard |

**Description:**
User creates a new invoice by selecting a client (Contact), adding line items with quantities and unit prices, selecting currency and PDV rate. System auto-calculates PDV and totals. Preview shows PDF representation before sending.

**Acceptance Criteria:**

- [ ] **Given** an authenticated user, **when** they complete the 6-step invoice wizard with valid data, **then** invoice is created in Draft status with correct PDV calculation
- [ ] **Given** Serbian PDV rate of 20%, **when** line item total is 1000 RSD, **then** PDV = 200 RSD, total = 1200 RSD
- [ ] **Given** multi-currency invoice in EUR, **when** created, **then** exchange rate at transaction date is locked and stored
- [ ] **Given** invoice is in Draft, **when** user sends it, **then** status changes to Sent, PDF emailed to client, SEF submission initiated (Serbia)

**Data Requirements:**

- Input: client (Contact), invoice_date, due_date, currency, line_items (description, qty, unit_price, vat_rate), notes
- Output: Invoice record with auto-generated invoice_number, PDV amounts, total_amount in NUMERIC(19,4)
- Validation: due_date > invoice_date; at least one line item; contact required

**Business Rules:** RUL-01 (NUMERIC), RUL-02 (double-entry on payment), RUL-05 (sequential numbering), RUL-06 (PDV rate selection)

---

**FR-011: SEF E-Invoice Submission (Serbia)**

| Attribute    | Value                                                     |
| ------------ | --------------------------------------------------------- |
| Module       | Invoicing                                                 |
| Priority     | Must Have                                                 |
| Trace        | BR-001                                                    |
| UI Reference | Automatic on invoice send; status shown in invoice detail |

**Description:**
When a user sends an invoice for a Serbian B2B transaction, Bilko automatically submits the invoice to SEF (efaktura.gov.rs) in UBL 2.1 XML format. SEF status (sent, accepted, rejected) is tracked and displayed.

**Acceptance Criteria:**

- [ ] **Given** a Serbian B2B invoice is sent, **when** the send action is triggered, **then** UBL 2.1 XML is generated and submitted to SEF API within 30 seconds
- [ ] **Given** SEF accepts the invoice, **when** success response received, **then** invoice SEF status updated to "Accepted" and SEF invoice ID stored
- [ ] **Given** SEF rejects the invoice, **when** rejection response received, **then** user is notified with the rejection reason from SEF; invoice stays in Sent status pending correction
- [ ] **Given** SEF API is unavailable, **when** submission attempted, **then** invoice queued for retry; user notified; max 3 retries with exponential backoff

**Data Requirements:**

- Input: Invoice record + organization SEF credentials
- Output: SEF invoice ID, submission timestamp, SEF status
- Validation: Required SEF fields present (buyer tax ID, invoice type, issue date)

---

**FR-012: Track Invoice Status**

| Attribute | Value          |
| --------- | -------------- |
| Module    | Invoicing      |
| Priority  | Must Have      |
| Trace     | BR-001, BR-008 |

**Description:**
Invoices progress through status states: Draft → Sent → SEF Accepted → Paid / Overdue. Users can mark invoices as paid, add payment date and amount.

**Acceptance Criteria:**

- [ ] **Given** invoice is Sent, **when** user marks as paid with payment date and amount, **then** status changes to Paid and payment transaction auto-created
- [ ] **Given** invoice is Sent and due_date has passed, **when** system checks daily, **then** status automatically changes to Overdue
- [ ] **Given** a list of invoices, **when** user filters by status, **then** only matching invoices shown

---

### 3.3 Module: Expense Tracking

#### Module Overview

Record business expenses with categorization, multi-currency support, and receipt attachment. Feeds double-entry bookkeeping automatically.

---

**FR-020: Create Expense**

| Attribute    | Value              |
| ------------ | ------------------ |
| Module       | Expenses           |
| Priority     | Must Have          |
| Trace        | BR-009             |
| UI Reference | `/expenses/create` |

**Description:**
User records a business expense with vendor, amount, currency, category, payment method, and optional receipt photo. System auto-creates the double-entry transaction.

**Acceptance Criteria:**

- [ ] **Given** valid expense data, **when** user submits, **then** expense saved with debit to expense account + credit to payment account
- [ ] **Given** a foreign currency expense, **when** created, **then** exchange rate at expense date locked and stored; amount also shown in base currency
- [ ] **Given** receipt image uploaded (JPG/PNG/PDF, max 10MB), **when** expense saved, **then** receipt stored and accessible from expense record

---

### 3.4 Module: Double-Entry Bookkeeping

#### Module Overview

The accounting engine. Every financial event generates balanced debit + credit Transaction entries. Supports Chart of Accounts per Balkan GAAP (Serbian Kontni Okvir 2021).

---

**FR-030: Chart of Accounts**

| Attribute    | Value                |
| ------------ | -------------------- |
| Module       | Bookkeeping          |
| Priority     | Must Have            |
| Trace        | BR-003, BR-010       |
| UI Reference | `/settings/accounts` |

**Description:**
Every organization is seeded with the Serbian Kontni Okvir (Chart of Accounts) per Pravilnik 2021 on creation. Accountants can add custom sub-accounts. Pre-populated accounts cover all 10 account classes (0-9).

**Acceptance Criteria:**

- [ ] **Given** a new Serbian organization is created, **when** setup completes, **then** all standard Kontni Okvir accounts are pre-populated (Classes 0-9)
- [ ] **Given** an accountant adds a custom sub-account under 411, **when** saved, **then** account 411xxx appears in Chart of Accounts and is available in transaction entry
- [ ] **Given** an account has transactions, **when** user attempts to delete it, **then** deletion blocked with explanation

---

**FR-031: Double-Entry Transaction Recording**

| Attribute    | Value                                              |
| ------------ | -------------------------------------------------- |
| Module       | Bookkeeping                                        |
| Priority     | Must Have                                          |
| Trace        | BR-003                                             |
| UI Reference | Auto-generated; viewable in `/bookkeeping/journal` |

**Description:**
Every financial event (invoice paid, expense recorded, bank reconciliation) automatically generates a balanced Transaction record with debitAccountId, creditAccountId, and amount in NUMERIC(19,4).

**Acceptance Criteria:**

- [ ] **Given** an invoice of 1200 RSD (1000 + 200 PDV) is marked paid, **when** payment recorded, **then** Transaction created: Debit 1200 (bank account), Credit 1000 (revenue), Credit 200 (PDV payable)
- [ ] **Given** any transaction is created, **when** saved, **then** sum of all debits = sum of all credits (ACID enforcement)
- [ ] **Given** a transaction is created, **when** user attempts to delete it, **then** soft-delete only — LoggedAction records the deletion; original data preserved

**Business Rules:** RUL-01, RUL-02, RUL-03, RUL-04

---

### 3.5 Module: Bank Reconciliation

#### Module Overview

Import bank statements via CSV upload. Auto-match transactions. Manual reconciliation for unmatched items.

---

**FR-040: Bank Statement CSV Import**

| Attribute    | Value           |
| ------------ | --------------- |
| Module       | Banking         |
| Priority     | Must Have       |
| Trace        | BR-005          |
| UI Reference | `/banking` page |

**Description:**
Users upload bank statement CSV files (Serbian bank format). System parses transactions and attempts to auto-match with existing invoices/expenses by amount and date proximity.

**Acceptance Criteria:**

- [ ] **Given** a valid CSV in supported Serbian bank format, **when** uploaded, **then** all transactions parsed and displayed for review
- [ ] **Given** parsed transaction matches an open invoice by amount ± 5%, **when** suggested, **then** match highlighted for user confirmation
- [ ] **Given** unmatched transaction, **when** user manually matches or categorizes, **then** Transaction and double-entry entry created

---

### 3.6 Module: VAT / PDV Management

#### Module Overview

Auto-calculate, track, and generate PDV reports for monthly filing with Poreska Uprava (Serbia).

---

**FR-050: PDV Report Generation**

| Attribute    | Value          |
| ------------ | -------------- |
| Module       | VAT/PDV        |
| Priority     | Must Have      |
| Trace        | BR-002, BR-006 |
| UI Reference | `/reports/vat` |

**Description:**
System aggregates all VAT-applicable transactions for a period and generates the PDV report in the format required by Poreska Uprava. Export in PDF and XML/JSON formats.

**Acceptance Criteria:**

- [ ] **Given** a reporting period (month), **when** user generates PDV report, **then** all sales PDV and input PDV correctly summed; net PDV payable/refundable calculated
- [ ] **Given** PDV report generated, **when** user exports, **then** PDF and XML export available; XML format compatible with ePorezi portal
- [ ] **Given** zero PDV period, **when** report generated, **then** zero report generated correctly (still required by law)

---

### 3.7 Module: Financial Reports

#### Module Overview

P&L Statement, Balance Sheet, Cash Flow Statement — generated from double-entry transaction data. PDF and Excel export.

---

**FR-060: Profit & Loss Statement**

| Attribute    | Value          |
| ------------ | -------------- |
| Module       | Reports        |
| Priority     | Must Have      |
| Trace        | BR-006         |
| UI Reference | `/reports` hub |

**Acceptance Criteria:**

- [ ] **Given** a date range, **when** P&L generated, **then** all revenue and expense accounts summarized; net profit/loss calculated and matches double-entry totals
- [ ] **Given** multi-currency org, **when** P&L generated, **then** all amounts shown in base currency using locked exchange rates

---

**FR-061: Balance Sheet**

| Attribute | Value     |
| --------- | --------- |
| Module    | Reports   |
| Priority  | Must Have |
| Trace     | BR-006    |

**Acceptance Criteria:**

- [ ] **Given** any date, **when** Balance Sheet generated, **then** Assets = Liabilities + Equity (double-entry balance enforced)
- [ ] **Given** Balance Sheet is unbalanced (should be impossible), **when** detected, **then** alert raised immediately for investigation

---

### 3.8 Module: Multi-Currency

#### Module Overview

Support BAM, RSD, EUR, USD. Exchange rates fetched daily from ECB / fixer.io. Rates locked at transaction date per IFRS requirements.

---

**FR-070: Exchange Rate Management**

| Attribute | Value          |
| --------- | -------------- |
| Module    | Multi-Currency |
| Priority  | Must Have      |
| Trace     | BR-004         |

**Acceptance Criteria:**

- [ ] **Given** a transaction in non-base currency, **when** created, **then** exchange rate at transaction date is fetched, stored, and locked — cannot be edited later
- [ ] **Given** ECB rate API unavailable, **when** transaction attempted, **then** system uses cached rate (max 24h old) or prompts user for manual entry
- [ ] **Given** organization base currency is RSD, **when** EUR invoice created, **then** both EUR amount and RSD equivalent stored; reports show RSD

---

## 4. Use Case Diagrams

### 4.1 Core Workflows

```mermaid
graph LR
    Owner((Owner)) --> UC1[FR-001: Register]
    Owner --> UC2[FR-010: Create Invoice]
    Owner --> UC3[FR-011: Submit to SEF]
    Owner --> UC4[FR-050: Generate PDV Report]
    Owner --> UC5[FR-060: View P&L]
    Accountant((Accountant)) --> UC2
    Accountant --> UC6[FR-030: Manage Chart of Accounts]
    Accountant --> UC7[FR-031: Record Manual Transaction]
    Accountant --> UC4
    Accountant --> UC8[FR-040: Import Bank CSV]
    Viewer((Viewer)) --> UC9[View Reports — Read Only]
    SEF((SEF API)) --> UC3
```

---

## 5. System Behavior Specifications

### 5.1 Error Handling

- All user-facing errors display human-readable Serbian/English message (no stack traces)
- All errors logged with correlation ID, timestamp, user ID (if authenticated), and action
- Validation errors shown inline, adjacent to the invalid field
- SEF API errors: show SEF's rejection reason in user-readable format + link to fix

### 5.2 Data Persistence

- All financial data persisted within 500ms of user action
- Optimistic UI updates rolled back if server confirmation fails
- All mutations (create/update/delete) audited in LoggedAction with user ID and timestamp

### 5.3 Session & State

- Session timeout: 30 minutes of inactivity (JWT expiry)
- Refresh token: 30-day rolling TTL
- Concurrent sessions: allowed (mobile + desktop)
- Browser refresh: state restored from server (no stale data)

### 5.4 Notifications

- Email notifications: invoice sent, invoice paid, SEF acceptance/rejection, account invitation
- In-app notifications: overdue invoices, PDV filing reminder (14th of month), bank import complete
- All marketing emails include unsubscribe link (GDPR)

### 5.5 Accessibility

- WCAG 2.1 Level AA compliance
- Keyboard navigation for all interactive elements
- Screen reader compatibility (Radix UI / shadcn ARIA labels)
- Color contrast ratio ≥ 4.5:1 (Bilko mint green #00E5A0 on dark backgrounds verified)

---

## 6. Requirements Summary Table

| ID     | Feature Name                       | Module         | Priority  | Status                                                             | Trace                          |
| ------ | ---------------------------------- | -------------- | --------- | ------------------------------------------------------------------ | ------------------------------ |
| FR-001 | User Registration                  | Authentication | Must Have | SUPERSEDED — Entra SSO/JIT + FR-003 invite (email/pw retired, 410) | BR-014                         |
| FR-002 | User Login                         | Authentication | Must Have | SUPERSEDED — Entra CIAM SSO only (email/pw retired, 410)           | BR-014                         |
| FR-003 | Invite User to Organization        | Authentication | Must Have | Not Started                                                        | BR-007                         |
| FR-010 | Create Invoice                     | Invoicing      | Must Have | Not Started                                                        | BR-001, BR-002, BR-004, BR-008 |
| FR-011 | SEF E-Invoice Submission           | Invoicing      | Must Have | Not Started                                                        | BR-001                         |
| FR-012 | Track Invoice Status               | Invoicing      | Must Have | Not Started                                                        | BR-001, BR-008                 |
| FR-020 | Create Expense                     | Expenses       | Must Have | Not Started                                                        | BR-009                         |
| FR-030 | Chart of Accounts                  | Bookkeeping    | Must Have | Not Started                                                        | BR-003, BR-010                 |
| FR-031 | Double-Entry Transaction Recording | Bookkeeping    | Must Have | Not Started                                                        | BR-003                         |
| FR-040 | Bank Statement CSV Import          | Banking        | Must Have | Not Started                                                        | BR-005                         |
| FR-050 | PDV Report Generation              | VAT/PDV        | Must Have | Not Started                                                        | BR-002, BR-006                 |
| FR-060 | P&L Statement                      | Reports        | Must Have | Not Started                                                        | BR-006                         |
| FR-061 | Balance Sheet                      | Reports        | Must Have | Not Started                                                        | BR-006                         |
| FR-070 | Exchange Rate Management           | Multi-Currency | Must Have | Not Started                                                        | BR-004                         |

**Requirements Count:**

- Must Have: 14
- Should Have: 0 in this document (Croatian eRačun in Phase 2 FRS)
- Could Have: 0
- Won't Have (Phase 1): Payroll, AI bookkeeping, live bank feeds

---

## 7. Traceability to Business Requirements

| FR ID  | Feature Name            | Business Requirement (BR ID)   | Business Objective (BO ID) |
| ------ | ----------------------- | ------------------------------ | -------------------------- |
| FR-001 | User Registration       | BR-014                         | BO-01                      |
| FR-002 | User Login              | BR-014                         | BO-01                      |
| FR-003 | Invite User             | BR-007                         | BO-02                      |
| FR-010 | Create Invoice          | BR-001, BR-002, BR-004, BR-008 | BO-01, BO-02               |
| FR-011 | SEF Submission          | BR-001                         | BO-01                      |
| FR-012 | Invoice Status Tracking | BR-001, BR-008                 | BO-02                      |
| FR-020 | Create Expense          | BR-009                         | BO-02                      |
| FR-030 | Chart of Accounts       | BR-003, BR-010                 | BO-01                      |
| FR-031 | Double-Entry Recording  | BR-003                         | BO-01                      |
| FR-040 | Bank CSV Import         | BR-005                         | BO-02                      |
| FR-050 | PDV Report              | BR-002, BR-006                 | BO-01, BO-03               |
| FR-060 | P&L Statement           | BR-006                         | BO-03                      |
| FR-061 | Balance Sheet           | BR-006                         | BO-01, BO-03               |
| FR-070 | Exchange Rates          | BR-004                         | BO-01                      |

> Full traceability matrix: [`RTM.md`](RTM.md)

---

## Approval

| Role               | Name               | Date       | Signature |
| ------------------ | ------------------ | ---------- | --------- |
| Author             | John (AI Director) | 2026-02-23 |           |
| Reviewer           |                    |            |           |
| Business Analyst   | John               | 2026-02-23 |           |
| Tech Lead          | John               | 2026-02-23 |           |
| Product Owner      | John               | 2026-02-23 |           |
| AI Director (John) | John               | 2026-02-23 |           |
| CEO (Alem)         | Alem Bašić         |            |           |

# Requirements Traceability Matrix (RTM)

# Requirements Traceability Matrix (RTM): Bilko

> **Project:** Bilko — Balkan Accounting SaaS
> **Version:** 1.0
> **Date:** 2026-02-25
> **Author:** John (AI Director)
> **Status:** Final
> **Reviewers:** Alem Bašić (CEO)

## Document History

| Version | Date       | Author             | Changes                            |
| ------- | ---------- | ------------------ | ---------------------------------- |
| 0.1     | 2026-02-23 | John (AI Director) | Initial draft — Phase 1 Serbia MVP |
| 1.0     | 2026-02-25 | John (AI Director) | Finalized for v1.0 release         |

---

## 1. Purpose of Traceability

The Requirements Traceability Matrix serves four functions for Bilko:

1. **Coverage Assurance** — Every business requirement (BR) has an implementation path (FR, US) and test cases (AC, TC)
2. **Change Impact** — When a regulatory requirement changes (e.g., SEF API update), quickly identify all affected code and tests
3. **Gap Detection** — Identify FRs with no tests (coverage gap) or tests with no requirement (potential scope creep)
4. **Compliance Audit** — Demonstrates to auditors that SEF, PDV, and accounting law requirements are implemented and verified

**Traceability Directions:**

- **Forward Traceability** — BR → FR → Code → Test (did we build what was required by law and stakeholders?)
- **Backward Traceability** — Test → Code → FR → BR (does everything we built have a legal or business justification?)

---

## 2. Document References

| Document                             | Location                                                                                       | Version | Last Updated |
| ------------------------------------ | ---------------------------------------------------------------------------------------------- | ------- | ------------ |
| Business Requirements Document (BRD) | [`BRD.md`](BRD.md)                                                                             | 1.0     | 2026-02-25   |
| Functional Requirements Spec (FRS)   | [`FUNCTIONAL-REQUIREMENTS.md`](FUNCTIONAL-REQUIREMENTS.md)                                     | 1.0     | 2026-02-25   |
| Non-Functional Requirements          | [`NON-FUNCTIONAL-REQUIREMENTS.md`](NON-FUNCTIONAL-REQUIREMENTS.md)                             | 1.0     | 2026-02-25   |
| User Stories                         | [`USER-STORIES.md`](USER-STORIES.md)                                                           | 1.0     | 2026-02-25   |
| Acceptance Criteria                  | [`ACCEPTANCE-CRITERIA.md`](ACCEPTANCE-CRITERIA.md)                                             | 1.0     | 2026-02-25   |
| Risk Register                        | [`../governance/RISK-REGISTER.md`](../governance/RISK-REGISTER.md)                             | 1.0     | 2026-02-25   |
| Test Plan                            | [`../TEST-PLAN.md`](../TEST-PLAN.md)                                                           | 1.0     | 2026-02-25   |
| Database Schema                      | [`../../packages/database/prisma/schema.prisma`](../../packages/database/prisma/schema.prisma) | Current | 2026-02-20   |

---

## 3. Forward Traceability Matrix

### 3.1 Functional Requirements Traceability

| BR ID  | Business Requirement     | FR ID          | Functional Requirement       | US ID          | DB Model                     | Code Module                                   | Unit Test | Integration Test | AC ID             | Status         |
| ------ | ------------------------ | -------------- | ---------------------------- | -------------- | ---------------------------- | --------------------------------------------- | --------- | ---------------- | ----------------- | -------------- |
| BR-001 | SEF e-invoice submission | FR-010         | Create Invoice               | US-010         | Invoice, InvoiceItem         | `apps/api/src/routes/invoices.ts`             | ❌        | ❌               | AC-030            | ❌ Not Started |
| BR-001 | SEF e-invoice submission | FR-011         | SEF Submission               | US-011         | Invoice (sef_status, sef_id) | `apps/api/src/services/sef.service.ts`        | ❌        | ❌               | AC-050            | ❌ Not Started |
| BR-001 | SEF e-invoice submission | FR-012         | Invoice Status Tracking      | US-012         | Invoice (status)             | `apps/api/src/routes/invoices.ts`             | ❌        | ❌               | AC-060            | ❌ Not Started |
| BR-002 | PDV auto-calculation     | FR-010         | Create Invoice (PDV)         | US-010         | InvoiceItem (vat_amount)     | `apps/api/src/services/tax.service.ts`        | ❌        | ❌               | AC-030, AC-038    | ❌ Not Started |
| BR-002 | PDV auto-calculation     | FR-050         | PDV Report                   | US-050         | Invoice, Expense             | `apps/api/src/routes/reports.ts`              | ❌        | ❌               | AC-080, AC-083    | ❌ Not Started |
| BR-003 | Double-entry bookkeeping | FR-031         | Transaction Recording        | US-031         | Transaction                  | `apps/api/src/services/accounting.service.ts` | ❌        | ❌               | NF-AC-030         | ❌ Not Started |
| BR-004 | Multi-currency           | FR-070         | Exchange Rate Management     | US-070         | Currency, ExchangeRate       | `apps/api/src/services/currency.service.ts`   | ❌        | ❌               | AC-032, NF-AC-032 | ❌ Not Started |
| BR-005 | Bank statement import    | FR-040         | CSV Import                   | US-040         | BankTransaction              | `apps/api/src/routes/banking.ts`              | ❌        | ❌               | AC-070 (extended) | ❌ Not Started |
| BR-006 | Financial reports        | FR-060         | P&L Statement                | US-060         | Transaction, Account         | `apps/api/src/routes/reports.ts`              | ❌        | ❌               | —                 | ❌ Not Started |
| BR-006 | Financial reports        | FR-061         | Balance Sheet                | US-061         | Transaction, Account         | `apps/api/src/routes/reports.ts`              | ❌        | ❌               | NF-AC-030         | ❌ Not Started |
| BR-007 | Multi-user RBAC          | FR-003         | Invite User                  | US-003, US-004 | User, Organization (RBAC)    | `apps/api/src/middleware/auth.ts`             | ❌        | ❌               | AC-001 (ext)      | ❌ Not Started |
| BR-008 | PDF invoice + email      | FR-010         | Invoice PDF delivery         | US-010         | Invoice                      | `apps/api/src/services/email.service.ts`      | ❌        | ❌               | INT-004           | ❌ Not Started |
| BR-009 | Expense tracking         | FR-020         | Create Expense               | US-020         | Expense                      | `apps/api/src/routes/expenses.ts`             | ❌        | ❌               | AC-070            | ❌ Not Started |
| BR-010 | Chart of Accounts        | FR-030         | Chart of Accounts            | US-030         | Account, AccountType         | `apps/api/src/services/accounts.service.ts`   | ❌        | ❌               | AC-003, AC-039    | ❌ Not Started |
| BR-011 | Serbian language         | N/A            | i18n / l10n (frontend)       | N/A            | N/A                          | `apps/web/lib/i18n/`                          | ❌        | ❌               | —                 | ❌ Not Started |
| BR-012 | Immutable audit trail    | FR-031         | LoggedAction (all mutations) | US-031         | LoggedAction                 | `apps/api/src/middleware/audit.ts`            | ❌        | ❌               | —                 | ❌ Not Started |
| BR-013 | Data export (GDPR)       | N/A            | Export API endpoint          | N/A            | All models                   | `apps/api/src/routes/export.ts`               | ❌        | ❌               | —                 | ❌ Not Started |
| BR-014 | Secure multi-tenancy     | FR-001, FR-002 | Auth (register/login)        | US-001, US-002 | User, Organization           | `apps/api/src/routes/auth.ts`                 | ✅        | ✅               | AC-001, AC-020    | ✅ Complete    |

> Note: BR-014 Auth endpoints are the only complete items — 4/50 auth endpoints built (2026-02-20).

### 3.2 Non-Functional Requirements Traceability

| NFR ID     | Requirement                 | Target                           | Test Type       | Test Case ID | Status                               |
| ---------- | --------------------------- | -------------------------------- | --------------- | ------------ | ------------------------------------ |
| NFR-P01    | Dashboard load < 3s initial | < 3s (4G)                        | Performance     | PERF-001     | ❌ Not Started                       |
| NFR-P02    | Dashboard < 1s subsequent   | < 1s warm cache                  | Performance     | PERF-002     | ❌ Not Started                       |
| NFR-P04    | API response < 300ms        | p95 < 300ms                      | Performance     | PERF-003     | ❌ Not Started                       |
| NFR-SEC01  | JWT authentication          | 15min access + 30d refresh       | Security        | SEC-001      | ✅ Complete (auth built)             |
| NFR-SEC06  | Input validation (Zod)      | All inputs validated server-side | Security / SAST | SEC-010      | ⏳ In Progress                       |
| NFR-SEC10  | Org data isolation          | No cross-tenant access           | Security        | SEC-020      | ⏳ In Progress (middleware built)    |
| NFR-R02    | ACID compliance             | 100% ACID transactions           | Database        | DB-001       | ⏳ In Progress (PostgreSQL + Prisma) |
| NFR-R03    | Double-entry balance        | Debit = Credit always            | Database / CI   | DB-002       | ❌ Not Started                       |
| NFR-D01    | NUMERIC(19,4) monetary      | No float for money               | Database        | DB-010       | ✅ Complete (schema enforced)        |
| NFR-COMP01 | SEF e-invoicing compliance  | 100% UBL 2.1                     | Compliance      | COMP-001     | ❌ Not Started                       |
| NFR-COMP02 | PDV compliance              | Correct PDV rates                | Compliance      | COMP-002     | ❌ Not Started                       |
| NFR-COMP04 | GDPR compliance             | Right to deletion; export        | Compliance      | COMP-010     | ❌ Not Started                       |
| NFR-U03    | WCAG 2.1 AA                 | Level AA                         | Accessibility   | A11Y-001     | ❌ Not Started                       |
| NFR-A01    | Uptime ≥ 99.9%              | 99.9% monthly                    | Operations      | OPS-001      | N/A (pre-launch)                     |

---

## 4. Backward Traceability Matrix

| Test Case ID | Test Description             | AC ID             | FR ID  | BR ID          | Has Requirement? |
| ------------ | ---------------------------- | ----------------- | ------ | -------------- | ---------------- |
| TC-AUTH-001  | User registration flow       | AC-001            | FR-001 | BR-014         | ✅ Yes           |
| TC-AUTH-002  | Login with JWT               | AC-020            | FR-002 | BR-014         | ✅ Yes           |
| TC-AUTH-003  | Token refresh                | AC-021            | FR-002 | BR-014         | ✅ Yes           |
| TC-AUTH-004  | Account lockout (5 attempts) | AC-024            | FR-002 | BR-014         | ✅ Yes           |
| TC-INV-001   | Invoice PDV 20% calculation  | AC-030            | FR-010 | BR-002         | ✅ Yes           |
| TC-INV-002   | Invoice PDV 10% calculation  | AC-031            | FR-010 | BR-002         | ✅ Yes           |
| TC-INV-003   | NUMERIC precision (no float) | AC-040, NF-AC-031 | FR-010 | BR-002         | ✅ Yes           |
| TC-SEF-001   | SEF UBL 2.1 submission       | AC-050            | FR-011 | BR-001         | ✅ Yes           |
| TC-SEF-002   | SEF rejection handling       | AC-052            | FR-011 | BR-001         | ✅ Yes           |
| TC-SEF-003   | SEF unavailable — queue      | AC-053            | FR-011 | BR-001         | ✅ Yes           |
| TC-ACC-001   | Debit = Credit balance check | NF-AC-030         | FR-031 | BR-003         | ✅ Yes           |
| TC-ACC-002   | Exchange rate immutability   | NF-AC-032         | FR-070 | BR-004         | ✅ Yes           |
| TC-PDV-001   | Monthly PDV report accuracy  | AC-080, AC-083    | FR-050 | BR-002, BR-006 | ✅ Yes           |
| TC-SEC-001   | Cross-tenant data isolation  | NF-AC-020         | N/A    | BR-014         | ✅ Yes           |

---

## 5. Coverage Analysis

### 5.1 Requirement Coverage Summary

| Category                          | Total Count | Fully Covered      | Partially Covered      | Not Covered | Coverage % |
| --------------------------------- | ----------- | ------------------ | ---------------------- | ----------- | ---------- |
| Business Requirements (BR)        | 14          | 1 (BR-014 auth)    | 3 (schema, middleware) | 10          | 7%         |
| Functional Requirements (FR)      | 14          | 2 (FR-001, FR-002) | 2 (FR-003, FR-030)     | 10          | 14%        |
| Non-Functional Requirements (NFR) | 30          | 5                  | 4                      | 21          | 17%        |
| User Stories (US)                 | 15          | 2 (US-001, US-002) | 0                      | 13          | 13%        |
| Acceptance Criteria (AC)          | 40+         | 0 (all Draft)      | 0                      | 40          | 0%         |

**Overall Requirement Coverage:** ~7% (project in early development phase — backend 4/50 endpoints complete)
**Target:** ≥ 95% before UAT (estimated Sprint 4); 100% before production release

> This is expected at current stage. Backend foundation complete (auth, middleware, DB schema). 46 API endpoints remaining.

### 5.2 Test Coverage Summary

| Test Type           | Total Tests         | Passing | Failing | Skipped | Coverage  |
| ------------------- | ------------------- | ------- | ------- | ------- | --------- |
| Unit tests          | 0 (not yet written) | 0       | 0       | 0       | 0%        |
| Integration tests   | 4 (auth endpoints)  | 4       | 0       | 0       | auth only |
| E2E / UAT scenarios | 0                   | 0       | 0       | 0       | 0%        |
| Performance tests   | 0                   | —       | —       | —       | 0%        |
| Security tests      | 0                   | —       | —       | —       | 0%        |

> Test coverage target: ≥ 80% overall, ≥ 95% for financial logic (double-entry, PDV, SEF) before launch.

---

## 6. Gap Identification

### 6.1 Requirements Without Test Coverage (All Phase 1 Non-Auth)

| Requirement ID | Description       | Gap Type                        | Action Required                                                  | Owner         | Target Date                         |
| -------------- | ----------------- | ------------------------------- | ---------------------------------------------------------------- | ------------- | ----------------------------------- |
| BR-001         | SEF e-invoicing   | No tests for SEF integration    | Create TC-SEF-001 through TC-SEF-003                             | John          | 2026-03-21 (SEF integration sprint) |
| BR-002         | PDV calculation   | No tests for PDV accuracy       | Create TC-INV-001 through TC-INV-003; verify against Zakon o PDV | John          | 2026-03-14                          |
| BR-003         | Double-entry      | No tests for accounting balance | Create TC-ACC-001; CI balance check                              | John          | 2026-03-07                          |
| FR-050         | PDV Report        | No implementation yet           | Build + test in Sprint 3                                         | builder agent | 2026-03-21                          |
| FR-060         | P&L Statement     | No implementation yet           | Build + test in Sprint 3                                         | builder agent | 2026-03-21                          |
| NFR-D01        | NUMERIC precision | Schema enforced but no test     | Add TC-INV-003 decimal precision test                            | John          | 2026-03-07                          |

### 6.2 Test Cases Without Requirements (Orphans)

| Test Case ID | Description                     | Status | Action |
| ------------ | ------------------------------- | ------ | ------ |
| —            | No orphaned tests at this stage | N/A    | N/A    |

### 6.3 Requirements Without Design Reference

| Requirement ID | Description                        | Action                                                               |
| -------------- | ---------------------------------- | -------------------------------------------------------------------- |
| FR-011         | SEF Submission UI (status display) | Existing invoice detail page — update to show SEF status field       |
| FR-040         | Bank CSV Import UI                 | New page `/banking` — existing placeholder page needs implementation |
| FR-050         | PDV Report page                    | Existing `/reports/vat` placeholder — needs full implementation      |

---

## 7. Change Impact Tracking

| Change Request ID | Changed Requirement              | Impact on FR | Impact on Code | Impact on Tests | Impact Assessment | CR Status |
| ----------------- | -------------------------------- | ------------ | -------------- | --------------- | ----------------- | --------- |
| —                 | No change requests at this stage | —            | —              | —               | —                 | —         |

**Key anticipated change risk:**
If SEF API changes (Risk R-001 in risk register), the following would need updating:

- FR-011 (SEF submission logic)
- `apps/api/src/services/sef.service.ts`
- TC-SEF-001, TC-SEF-002, TC-SEF-003
- UBL 2.1 XML generation templates
- AC-050, AC-052, AC-054

---

## 8. Traceability Status Dashboard

**Last Updated:** 2026-02-25
**Updated By:** John (AI Director)

| Metric                      | Value             | Target        | Status                    |
| --------------------------- | ----------------- | ------------- | ------------------------- |
| Total Business Requirements | 14                | —             |                           |
| BRs with FR coverage        | 14 / 14           | 100%          | ✅ All mapped             |
| FRs with test coverage      | 2 / 14            | 100%          | ❌ In progress            |
| Test cases passing          | 4 / 4 (auth only) | 100%          | ✅ (auth only)            |
| Open gaps                   | 11 FRs untested   | 0 at launch   | ❌ Expected at this stage |
| Change requests open        | 0                 | ≤ 3 at a time | ✅                        |
| UAT sign-off pending        | 0 (pre-launch)    | 0 at launch   | N/A                       |

**Overall RTM Health:** AMBER — Expected for current development phase. All requirements defined and mapped to code modules. Test coverage to be built alongside each feature in Sprints 2-4.

---

## Approval

| Role               | Name               | Date       | Signature |
| ------------------ | ------------------ | ---------- | --------- |
| Author             | John (AI Director) | 2026-02-23 |           |
| Reviewer           |                    |            |           |
| Business Analyst   | John               | 2026-02-23 |           |
| QA Engineer        | validator agent    |            |           |
| Tech Lead          | John               | 2026-02-23 |           |
| AI Director (John) | John               | 2026-02-23 |           |