BR-001: Multi-Tenant Organization Support
Priority: CRITICAL
Owner: Product Owner
Description
The system shall support multiple independent utility companies (organizations) with complete data isolation at blob storage, processing, and user access levels.
Business Value
- Revenue Model: Enables SaaS subscription model across Nordic markets
- Cost Efficiency: Shared infrastructure reduces per-customer cost by 60-70%
- Market Penetration: Faster onboarding enables rapid customer acquisition
- Scalability: Single platform scales to serve 150+ Swedish utilities alone
Nordic Market Context
- Sweden: ~150 electricity suppliers, ~290 district heating companies
- Norway: ~140 electricity suppliers
- Denmark: ~60 electricity suppliers
- Finland: ~80 electricity suppliers
Total Addressable Market: 700+ potential customers
Acceptance Criteria
| # | Criterion | Measurement Method | Target |
|---|---|---|---|
| 1 | Concurrent organizations supported | Load test with 50 orgs | All batches process successfully |
| 2 | Data isolation enforcement | Cross-org access attempts | 100% blocked (403 Forbidden) |
| 3 | Organization-specific blob containers | Verify storage paths | Pattern: {org-id}-{type}-{year}/ |
| 4 | User organization boundary enforcement | API calls with wrong org context | All rejected |
| 5 | Independent branding per organization | Upload logo, verify rendering | Branding applied correctly |
| 6 | Configurable delivery channels | Set priority [email, postal] | Order respected |
Dependencies
- Azure Blob Storage (container-per-organization strategy)
- PostgreSQL schema with
user_organization_rolestable - Organization context middleware
- Role-based access control (RBAC) implementation
Risks & Mitigation
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Data leakage between orgs | LOW | CRITICAL | Middleware enforcement, automated testing, penetration testing |
| Performance degradation (50+ tenants) | MEDIUM | HIGH | Blob auto-scaling, connection pooling, indexed queries |
| Swedish data residency requirements | LOW | HIGH | West Europe primary, no cross-border transfer |
...
BR-002: Multi-Vendor XML Format Support
Priority: HIGH
Owner: Product Owner
Description
The system shall process invoice batch files from multiple vendor billing systems (GASEL/Telinet, XELLENT/Karlskoga, ZYNERGY/EG Software) with automatic format detection and transformation to canonical JSON.
Business Value
- Market Coverage: Supports 70% of Swedish utilities market
- Zero Custom Development: No per-vendor integration coding required
- Faster Onboarding: 80% reduction in integration time
- Vendor Agnostic: Future-proofs against vendor migrations
Nordic Market Context
Top 3 Billing Systems in Swedish Market:
- Telinet (EDIEL/GASEL format): ~30% market share
- Karlskoga/Xellent (OIOXML format): ~25% market share
- EG Zynergy (proprietary): ~15% market share
Combined Coverage: ~70% of addressable market
Acceptance Criteria
| # | Criterion | Measurement Method | Target |
|---|---|---|---|
| 1 | GASEL format detection | 50 sample files | 100% accuracy |
| 2 | XELLENT format detection | 50 sample files | 100% accuracy |
| 3 | ZYNERGY format detection | 50 sample files | 100% accuracy |
| 4 | Canonical JSON transformation | Schema validation | All fields present |
| 5 | XSD schema validation | Vendor-specific XSD | Pass validation |
| 6 | Unsupported format handling | Unknown XML upload | 415 error with vendor list |
| 7 | Detection performance | 100MB file | < 1 second |
Vendor-Specific Requirements
GASEL (Telinet/EDIEL):
- Namespace:
urn:ediel:se:electricity:invoice:1.0 - Date format: ISO 8601 (YYYY-MM-DD)
- Amount format: Decimal with period separator
- Required elements: InvoiceNumber, PartyName, PayableAmount
XELLENT (Karlskoga/OIOXML):
- Namespace:
http://rep.oio.dk/ubl/xml/schemas/0p71/pie/ - Multiple namespace prefixes:
com:,main:,fsv: - Amount format: "1 245,00" (space separator, comma decimal)
- Must normalize to standard decimal
ZYNERGY (EG Software):
- Namespace:
http://eg.dk/Zynergy/1.0/invoice.xsd - Nested structure: Invoice > Customer, InvoiceData, InvoiceAddress
- Multiple company ID references throughout
- InvoiceAmount vs InvoiceBalance distinction
Dependencies
- Schema registry with field mappings per vendor
- XML parsing library (System.Xml.Linq)
- XSD schema files from vendors
- Canonical JSON schema definition
Risks & Mitigation
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Vendor schema changes without notice | MEDIUM | HIGH | Version all schemas, support multiple versions, 3-month deprecation notice |
| EDIEL standard evolution | MEDIUM | MEDIUM | Monitor Ediel.org, participate in Nordic working groups, backward compatibility |
| Complex namespace handling (OIOXML) | LOW | MEDIUM | XmlNamespaceManager, extensive unit testing per vendor |
| Incomplete field mappings | MEDIUM | MEDIUM | Comprehensive validation, custom fields dictionary, lenient parsing mode |
...
BR-003: Batch Invoice Processing
Priority: HIGH
Owner: Product Owner
Description
The system shall process batch invoice files containing up to 100,000 invoices with parallel processing, retry logic, and granular status tracking.
Business Value
- High-Volume Support: Typical Swedish utility has 50K-200K customers
- Time Efficiency: 95% reduction in manual processing effort
- Customer Satisfaction: Days → hours delivery time
- Predictable SLAs: Enables committed service levels
Nordic Market Context
Monthly Invoice Patterns:
- Peak concentration: First/last week of month
- Heating season (Oct-Mar): 40% higher volumes
- January peak: Coldest month, highest consumption
- Summer (Jun-Aug): 50-60% of winter volumes
Acceptance Criteria
| # | Criterion | Measurement Method | Target |
|---|---|---|---|
| 1 | Single batch capacity | Upload 100K invoices | All processed |
| 2 | Asynchronous processing | API response time | < 500ms (202 Accepted) |
| 3 | Real-time progress tracking | Poll during processing | Updates every 30 seconds |
| 4 | Failed item isolation | 10 errors in 1000-item batch | 990 succeed independently |
| 5 | Retry mechanism | Force temporary failure | 3 retries then poison queue |
| 6 | Processing time SLA | 100K invoice batch | ≤ 120 minutes |
| 7 | Format support (Phase 1) | Upload XML, JSON, CSV | XML fully supported |
Processing Flow
1. API receives batch upload → 201 Created (batch stored)
2. POST /start → 202 Accepted (queued for processing)
3. ParserService picks from batch-upload-queue
4. Parse XML → Individual JSON files (canonical format)
5. Group into 32-item batches → Enqueue to batch-items-queue
6. DocumentGenerator renders 32 items in parallel
7. Generate HTML → PDF → Store in blob
8. Route to delivery queue (email or postal)
9. Update batch statistics in real-time
10. Complete when all items processed
Dependencies
- Azure Storage Queues (message passing)
- Worker auto-scaling (Container Apps + KEDA)
- Blob storage (source files + processed invoices)
- Batch metadata storage (real-time updates)
Risks & Mitigation
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Processing timeout during heating season | MEDIUM | HIGH | Pre-warm workers 1st/last week, priority queue, off-peak scheduling |
| Memory constraints (large XML >50MB) | MEDIUM | MEDIUM | Stream-based parsing, chunk processing, 100MB hard limit |
| Disk space exhaustion | LOW | MEDIUM | Ephemeral storage cleanup, blob-only persistence |
| Queue 64KB message limit | MEDIUM | MEDIUM | Store data in blob, queue references only |
...
BR-004: Template-Based Invoice Rendering
Priority: HIGH
Owner: Product Owner
Description
The system shall generate PDF and HTML invoices using organization-specific Handlebars templates with dynamic data binding and brand customization.
Business Value
- Brand Consistency: Professional appearance across all communications
- Regulatory Compliance: Swedish Energy Markets Inspectorate requirements
- Flexibility: Per-organization customization without code changes
- Future-Proof: Multi-language support foundation (SE, NO, DK, FI)
Swedish Regulatory Requirements
Energimarknadsinspektionen (Swedish Energy Markets Inspectorate) mandates:
- Consumption details (period, kWh)
- Tax breakdown (25% VAT for electricity)
- Grid owner information
- Metering point ID (mätpunkt)
- Price per kWh
- Fixed monthly fee (månadsavgift)
Acceptance Criteria
| # | Criterion | Measurement Method | Target |
|---|---|---|---|
| 1 | Custom template upload | Upload via API/blob | Stored successfully |
| 2 | Dynamic data binding | Test with invoice data | All fields populated |
| 3 | PDF generation | HTML → PDF | A4 format, readable |
| 4 | Template versioning | Create v2.0.0 | Old batches use v1.0.0 |
| 5 | In-flight batch isolation | Update template during processing | In-flight uses old version |
| 6 | Template validation | Missing variable upload | Validation error returned |
| 7 | Organization branding | Logo, colors, fonts | Visible in rendered PDF |
| 8 | Swedish regulatory fields | Verify required elements | All present |
Template Structure
Required Fields (Swedish Regulations):
- Invoice number (Fakturanummer)
- Invoice date (Fakturadatum)
- Due date (Förfallodatum)
- Period (Period)
- Metering point ID (Mätpunkt)
- Grid area (Elområde)
- Grid owner (Nätägare)
- Consumption (Förbrukning)
- Previous/current reading (Mätarställning)
- Unit price (Pris per kWh)
- Monthly fee (Månadsavgift)
- Subtotal (Delsumma)
- VAT 25% (Moms 25%)
- Total amount (Att betala)
- Payment info (Bankgiro, OCR)
Dependencies
- Handlebars.Net template engine
- PDF generation (Playwright + Chromium or IronPDF)
- Blob storage (template files)
- Template metadata storage with versioning
Risks & Mitigation
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| Template rendering bottleneck | HIGH | HIGH | Compiled template caching (24h), parallel rendering (32 items), POC: 10K in <5 min |
| PDF generation quality (Swedish chars) | MEDIUM | MEDIUM | UTF-8 encoding, font embedding (åäö), visual regression testing |
| Swedish regulatory compliance | LOW | CRITICAL | Legal review, required fields checklist, annual update review |
| Template injection attacks | LOW | CRITICAL | Sandboxed execution, no eval/exec helpers, sanitization, security review |
...
BR-005: Multi-Channel Delivery with Nordic Integration
Priority: HIGH
Owner: Product Owner
Description
The system shall deliver invoices through multiple channels (email, postal, future: Kivra, e-Faktura) with configurable priority, automatic fallback, and integration with Nordic delivery partners.
Business Value
- Delivery Success: >98% vs ~92% email-only
- Cost Reduction: Reduced returned mail costs
- Customer Preference: Digital-first with postal backup
- Legal Compliance: Swedish "rätt till pappersfaktura" (right to paper invoice)
- Future-Ready: Digital mailbox mandate preparations
Nordic Market Context
Legal Requirements:
- Sweden: Postal option legally required for all customers
- Kivra Adoption: 4.2M users in Sweden (40% of population)
- E-faktura: Standard for B2B invoicing across Nordics
- Postal Tradition: Especially important for elderly customers
Delivery Statistics (Industry Average):
- Email delivery: 90-95% success
- Email + Postal fallback: 98-99% success
- Pure postal: 97-98% success
Acceptance Criteria
| # | Criterion | Measurement Method | Target |
|---|---|---|---|
| 1 | Email delivery (SendGrid) | 1000 test invoices | >95% delivered |
| 2 | Postal delivery (21G SFTP) | Create ZIP, upload | File accepted by 21G |
| 3 | Channel priority configuration | Set [email, postal] | Email attempted first |
| 4 | Automatic fallback | Force email failure | Postal triggered auto |
| 5 | Delivery status tracking | Check invoice metadata | Status + timestamps recorded |
| 6 | Retry logic (transient failures) | Simulate SendGrid 429 | Retries with backoff |
| 7 | Delivery confirmation logging | Verify audit log | All deliveries logged |
| 8 | 21G bulk processing schedule | Verify postal queue | 12:00 and 20:00 CET |
Channel Specifications
Email (SendGrid):
- Dedicated Nordic IP for sender reputation
- SPF/DKIM/DMARC configuration
- Swedish-localized email templates
- PDF attachment (compressed if >5MB)
- Retry: 2 attempts (1 min, 5 min delays)
- Failure → Postal fallback
Postal (21G Bulk SFTP):
- Scheduled processing: 12:00 and 20:00 CET
- ZIP archive format: PDFs + XML metadata
- SFTP upload to
/incoming/{org-code}/ - SLA: 24-48 hours from upload to print
- Tracking: Email confirmation from 21G
Phase 2 Channels:
- Kivra digital mailbox (4.2M Swedish users)
- e-Faktura/PEPPOL (B2B standard)
- SMS notifications (Wiraya integration)
Dependencies
- SendGrid account (Nordic IP reputation)
- 21G SFTP server access and credentials
- Azure Key Vault (credential storage)
- Postal queue processing service
- ZIP file generation for 21G format
Risks & Mitigation
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| SendGrid Nordic deliverability issues | MEDIUM | HIGH | Dedicated IP, SPF/DKIM/DMARC, sender reputation monitoring, backup: Azure Communication Services |
| 21G SFTP connectivity issues | LOW | HIGH | Retry logic, dual credentials, alert on failure, 21G SLA monitoring, manual upload procedure |
| Postal delivery delays (Swedish postal) | MEDIUM | MEDIUM | Set expectations (5-7 days), track confirmations, escalation for >10 days |
| Email spam filtering (Swedish ISPs) | MEDIUM | MEDIUM | IP warmup, monitor bounce rates, ISP whitelist requests (Telia, Tele2, Telenor) |
...
Non-Functional Requirements
NFR-001: Performance Targets
Priority: HIGH
Owner: Technical Architect
Performance Metrics
| Metric | Target | Measurement | Test Scenario |
|---|---|---|---|
| Monthly throughput | 10M invoices | Application Insights | Production monitoring |
| 100K batch processing | < 2 hours | Timestamp diff | Load test TC-200 |
| API response (p50) | < 200ms | Application Insights | Load test TC-201 |
| API response (p95) | < 500ms | Application Insights | Load test TC-202 |
| API response (p99) | < 1000ms | Application Insights | Load test TC-203 |
| PDF generation (p95) | < 5 seconds/invoice | Custom metric | Render test TC-204 |
| Handlebars render (p95) | < 2 seconds/invoice | Custom metric | Render test TC-205 |
| Queue processing lag | < 5 minutes | Queue depth / throughput | Queue monitoring |
| Database query (p95) | < 100ms | PostgreSQL slow query log | Query analysis |
| ParserService (10K batch) | < 2 minutes | Parse duration | Parser test TC-206 |
Load Testing Scenarios
Scenario 1: Steady State (Normal Month)
- Duration: 24 hours
- Load: 333K invoices evenly distributed
- Concurrent batches: 5-10
- Expected: All targets met, no errors
Scenario 2: Peak Load (Heating Season)
- Duration: 8 hours
- Load: 314K invoices (first week concentration)
- Concurrent batches: 20+
- Expected: 2-hour SLA met, >99% success
Scenario 3: Spike Test
- Duration: 30 minutes
- Load: 10 batches (50K invoices) uploaded simultaneously
- Expected: Auto-scales, processes without degradation
Acceptance Criteria
| # | Criterion | Validation | Target |
|---|---|---|---|
| 1 | 100K batch completion | End-to-end test | ≤ 2 hours |
| 2 | API latency under load | 1000 RPS test | p95 ≤ 500ms |
| 3 | 10M monthly capacity | Production monitoring | ≥ 10M in peak month |
| 4 | 50-org performance | 50 concurrent uploads | All SLAs met |
| 5 | Worker auto-scaling | Monitor queue during peaks | Lag ≤ 5 min |
| 6 | PDF generation performance | 1000 PDFs | p95 ≤ 5 seconds |
...
NFR-002: Scalability & Auto-Scaling
Priority: HIGH
Owner: Technical Architect
Scaling Configuration
| Component | Min | Max | Trigger | Threshold | Scale Up | Scale Down |
|---|---|---|---|---|---|---|
| CoreApiService | 5 | 20 | CPU OR Request Rate | 70% OR 1000 RPS | 2 min | 10 min |
| ParserService | 2 | 10 | Queue Length | >0 | 1 min | 5 min |
| DocumentGenerator | 2 | 100 | Queue Length | >32 | 1 min | 5 min |
| EmailService | 5 | 50 | Queue Length | >50 | 1 min | 5 min |
| PostalService | 1 | 3 | Scheduled | 12:00, 20:00 CET | N/A | After completion |
Peak Load Capacity
Normal Load (non-heating, mid-month):
- 333K invoices/day average
- 5-10 concurrent batches
- Worker instances: 10-20 total
Peak Load (heating season, first/last week):
- 2.2M invoices/week
- 314K invoices/day
- 20+ concurrent batches
- Worker instances: 80-100 total
Pre-Warming Strategy (Heating Season)
Monthly Schedule:
- Day 1-7: Pre-warm to 50 instances at 00:00
- Day 8-23: Scale based on queue (2-20 instances)
- Day 24-31: Pre-warm to 50 instances at 00:00
Heating Season (Oct-Mar): Double levels
- Day 1-7: Pre-warm to 80 instances
- Day 24-31: Pre-warm to 80 instances
...
NFR-003: Availability & Reliability
Priority: HIGH
Owner: Technical Architect
Availability Targets
| Metric | Target | Allowed Downtime | Measurement |
|---|---|---|---|
| System Uptime | 99.9% | 43 min/month | Azure Monitor |
| Batch Success Rate | >99.5% | 50 failures per 10K | Processing logs |
| Delivery Success Rate | >98% | 200 failures per 10K | Delivery tracking |
| API Availability | 99.9% | 43 min/month | Health checks |
| MTTR | <30 minutes | N/A | Incident timestamps |
| MTBF | >720 hours | N/A | Incident tracking |
Multi-Region Deployment
Primary Region: West Europe (Sweden, Denmark)
Secondary Region: North Europe (Norway, Finland)
Traffic Routing:
- Azure Traffic Manager (Performance routing)
- Health check: /health every 30 seconds
- Auto-failover: 3 consecutive failures
- Failover time: <2 minutes
...
NFR-004: Security Requirements
Priority: CRITICAL
Owner: Technical Architect
Authentication & Authorization
OAuth 2.0:
- Grant Type: Client Credentials
- Token Provider: Microsoft Entra ID
- Token Lifetime: 1 hour
- Algorithm: RS256
Roles:
- Super Admin (global)
- Organization Admin (single org)
- Template Admin (single org)
- Batch Operator (single org)
- Read-Only User (single org)
- API Client (single org)
Encryption
In Transit:
- TLS 1.3 minimum
- HSTS enabled
At Rest:
- Blob Storage: AES-256
- PostgreSQL: AES-256
- Backups: AES-256
...
NFR-005: Data Retention
Priority: HIGH
Owner: Legal/Compliance
| Data Type | Retention | Storage Tier Transitions |
|---|---|---|
| Invoices (PDF/HTML/JSON) | 7 years | Day 0-365: Hot Day 366-2555: Cool Day 2556+: Archive |
| Batch Source (XML) | 90 days | Day 0-30: Hot Day 31-90: Cool Day 91+: Delete |
| Audit Logs | 7 years | Year 0-1: PostgreSQL Year 1-7: Blob (compressed) |
| Application Logs | 90 days | Application Insights |
...
Approval Section
Stakeholder Sign-Off
| Stakeholder Role | Name | Signature | Date | Status |
|---|---|---|---|---|
| Product Owner | ☐ PENDING | |||
| Technical Architect | ☐ PENDING |
Approval Criteria
- All CRITICAL requirements reviewed and accepted
- All HIGH requirements reviewed and accepted
- All dependencies identified and acknowledged
- All risks reviewed with mitigation strategies
- All acceptance criteria defined and measurable
- Budget and timeline implications understood
- Resource allocation confirmed
- Compliance requirements validated (GDPR, Bokföringslagen)
Change Control
Any changes to approved CRITICAL or HIGH priority requirements must follow the change control process:
- Document proposed change in Jira (tag with egflow version)
- Impact assessment (scope, timeline, cost)
- Re-approval by Product Owner and Technical Architect
- Update this document with version increment
- Communicate changes to development team
- Update affected Jira issues with new fixVersion
Version History
| Version | Date | Author | Changes | Release Target |
|---|---|---|---|---|
| 1.0 | 2025-11-20 | Product Owner | Initial draft | egflow-1.0.0 |
| 1.1 | 2025-11-21 | Product Owner | Added FR-003 details, updated acceptance criteria | egflow-1.0.0 |
| 1.2 | 2025-11-27 | Product Owner | Updated versioning strategy to match Gasell model | egflow-1.0.0 "Corny Flamingo" |
...
End of Business Requirements Document
2. Business Requirements
2.0 Priority Level Definitions
| Priority | Definition | Go-Live Impact | Stakeholder Approval | Example |
|---|---|---|---|---|
| CRITICAL | Core system functionality, data integrity, legal compliance, security | BLOCKING - Cannot go live without this | All stakeholders required | Authentication, GDPR, data isolation |
| HIGH | Primary business value, significant operational impact | BLOCKING - Should not go live without this | Product Owner + Technical Architect | Batch processing, multi-vendor XML |
| MEDIUM | Important for operations, workarounds exist temporarily | NON-BLOCKING - Can go live with plan to complete | Product Owner approval | Template management UI, postal integration |
| LOW | Nice to have, minimal business impact, future optimization | NON-BLOCKING - Defer to Phase 2 | Product Owner decision | Advanced filtering, custom dashboards |
2.1 BR-001: Multi-Tenant Organization Support
Requirement: The system shall support multiple independent utility companies (organizations) with complete data isolation at the blob storage, processing, and user access levels.
Business Value:
- Enables SaaS business model for Nordic utilities market
- Reduces per-customer infrastructure costs by 60-70%
- Accelerates new customer onboarding (weeks → days)
- Increases addressable market across Sweden, Norway, Denmark, Finland
Priority: CRITICAL
Nordic Market Context: Swedish utilities market has ~150 electricity suppliers, ~290 district heating companies. Multi-tenancy is essential for market penetration.
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| System supports 50+ concurrent organizations | Load test with 50 organizations uploading batches simultaneously | TC-001 | All batches process successfully |
| Each organization has isolated blob storage | Verify container naming: {org-id}-invoices-{year} | TC-002 | No cross-org container access |
| Users cannot access other organizations' data | Attempt API calls to different org-id with valid token | TC-003 | All return 403 Forbidden |
| Each organization configures own branding | Upload logo, colors; verify in rendered PDF | TC-004 | Branding applied correctly |
| Each organization defines delivery channels | Configure email priority; verify email sent first | TC-005 | Channel priority honored |
| Organization data never shared in logs | Review Application Insights logs for data leakage | TC-006 | No PII in logs |
Dependencies:
- Azure Blob Storage with container-per-organization strategy
- PostgreSQL schema with user_organization_roles table
- Middleware for organization context extraction and validation
- Role-based access control implementation
Risks & Mitigation (Nordic Context):
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| Data leakage between organizations | LOW | CRITICAL | - Middleware enforces org boundaries - Automated cross-org access testing - Penetration testing by external auditor - GDPR-compliant architecture review | Security Officer |
| Performance degradation with 50+ tenants | MEDIUM | HIGH | - Blob storage auto-scales - PostgreSQL connection pooling - Indexed queries on organization_id - Load testing with 100 organizations | Technical Architect |
| Swedish data residency requirements | LOW | HIGH | - West Europe primary region - Data residency enforced in org config - No cross-border data transfer | Compliance |
2.2 BR-002: Multi-Vendor XML Format Support
Requirement: The system shall process invoice batch files from multiple vendor billing systems (GASEL/Telinet, XELLENT/Karlskoga, ZYNERGY/EG Software) with automatic format detection and transformation to canonical JSON.
Business Value:
- Eliminates integration barrier for new customers (any billing system supported)
- Reduces onboarding time by 80% (no custom integration development)
- Increases market addressability to all Nordic utilities regardless of billing system
- Enables vendor-agnostic downstream processing
Priority: HIGH
Nordic Market Context: Top 3 billing systems in Swedish utilities market: Telinet (EDIEL format), Karlskoga/Xellent (OIOXML), EG Zynergy (proprietary). Supporting these covers ~70% of market.
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| System auto-detects GASEL format | Test with 50 GASEL XML samples | TC-010 | 100% accuracy |
| System auto-detects XELLENT format | Test with 50 XELLENT XML samples | TC-011 | 100% accuracy |
| System auto-detects ZYNERGY format | Test with 50 ZYNERGY XML samples | TC-012 | 100% accuracy |
| All formats transform to canonical JSON | Parse each format, verify JSON schema | TC-013 | All required fields present |
| XML validation against vendor XSD | Validate sample files against schemas | TC-014 | Schema validation passes |
| Clear error for unsupported formats | Upload unknown format XML | TC-015 | Returns 415 with vendor list |
| Detection within 1 second | Performance test with 100MB files | TC-016 | < 1 second |
Dependencies:
- Schema registry with field mappings for each vendor
- XML parsing library supporting complex namespaces
- XSD schema files from vendors (Telinet, Karlskoga, EG)
- Canonical JSON schema definition
Risks & Mitigation (Nordic Context):
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| Vendor XML schema changes without notice | MEDIUM | HIGH | - Version all schemas (v1.0, v1.1, etc.) - Support multiple versions simultaneously - 3-month deprecation notice in vendor contracts - Automated schema change detection - Direct vendor communication channels | Product Owner |
| EDIEL standard evolution | MEDIUM | MEDIUM | - Monitor Ediel.org for updates - Participate in Nordic Ediel working groups - Backward compatibility for 2 versions - Phased schema migration | Technical Architect |
| Complex namespace handling (OIOXML) | LOW | MEDIUM | - Use System.Xml.Linq for namespace support - XmlNamespaceManager for prefixes - Extensive unit testing per vendor - Schema mapping documentation | Dev Team |
| Incomplete field mappings | MEDIUM | MEDIUM | - Comprehensive mapping validation - Custom fields dictionary for unmapped data - Vendor format validation during onboarding - Optional field graceful degradation | Dev Team |
| Energiforsk format variations | LOW | LOW | - Document accepted variations - Lenient parsing mode option - Warning system for non-critical deviations | Product Owner |
2.3 BR-003: Batch Invoice Processing
Requirement: The system shall process batch invoice files containing up to 100,000 invoices with parallel processing, retry logic, and granular status tracking.
Business Value:
- Enables high-volume monthly invoice runs (typical Swedish utility: 50K-200K customers)
- Reduces manual processing effort by 95%
- Improves time-to-customer (days → hours)
- Enables predictable SLA commitments to customers
Priority: HIGH
Nordic Market Context: Monthly invoice cycles concentrated in first/last week of month. Heating season (Oct-Mar) has 40% higher volumes. System must handle seasonal peaks.
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| Single batch supports 100,000 invoices | Upload 100K batch, verify all processed | TC-020 | All invoices processed |
| Batches processed asynchronously | API returns 202 immediately, processing continues | TC-021 | < 500ms API response |
| Real-time progress tracking | Poll status API during processing | TC-022 | Updates every 30 seconds |
| Failed items don't block batch | Introduce 10 errors in 1000-item batch | TC-023 | 990 succeed, 10 fail independently |
| Retry mechanism (3 attempts) | Force temporary failure, verify retries | TC-024 | 3 retries then poison queue |
| Processing completes within 2 hours (100K) | Load test with 100K invoice batch | TC-025 | <= 120 minutes |
| Supports XML, JSON, CSV formats (Phase 1: XML only) | Upload each format type | TC-026 | XML fully supported |
Dependencies:
- Azure Storage Queues for message passing
- Worker auto-scaling (Container Apps with KEDA)
- Blob storage for batch source files and processed invoices
- Batch metadata storage with real-time updates
Risks & Mitigation (Nordic Context):
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| Processing timeout during heating season peaks (Oct-Mar) | MEDIUM | HIGH | - Pre-warm workers 1st/last week of month - Priority queue for SLA customers - Scheduled off-peak processing windows - Customer communication about peak times | Operations Manager |
| Memory constraints with large XML files (>50MB) | MEDIUM | MEDIUM | - Stream-based XML parsing (XmlReader) - Chunk processing for large batches - File size monitoring and alerts - 100MB hard limit with split guidance | Technical Architect |
| Disk space exhaustion on workers | LOW | MEDIUM | - Ephemeral storage cleanup after processing - Blob storage only for persistence - Worker instance monitoring | Operations Manager |
| Queue message 64KB limit exceeded | MEDIUM | MEDIUM | - Store invoice JSON in blob, queue has reference only - Message payload validation - Compression for large messages | Technical Architect |
2.4 BR-004: Template-Based Invoice Rendering
Requirement: The system shall generate PDF and HTML invoices using organization-specific Handlebars templates with dynamic data binding and brand customization.
Business Value:
- Enables brand consistency across all customer communications
- Supports regulatory requirements (Swedish Energy Markets Inspectorate guidelines)
- Allows per-organization customization without code changes
- Future-proofs for multi-language support (Swedish, Norwegian, Danish, Finnish)
Priority: HIGH
Nordic Market Context: Swedish regulations require specific invoice information (consumption details, tax breakdown, grid owner, metering point). Templates must support regulatory compliance.
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| Organizations upload custom Handlebars templates | Upload HTML template via API (future) or blob | TC-030 | Template stored successfully |
| Templates support dynamic data binding | Render with test invoice data | TC-031 | All fields populated |
| PDF generation from HTML with compliance | Generate PDF, verify format and content | TC-032 | A4, readable, complete |
| Template versioning supported | Create v2.0.0, verify old batches use v1.0.0 | TC-033 | Version isolation working |
| Templates updateable without affecting in-flight batches | Update template while batch processes | TC-034 | In-flight uses old version |
| Template validation before activation | Upload template with missing variable | TC-035 | Validation error returned |
| Organization branding applied | Logo, colors, fonts in rendered PDF | TC-036 | Branding visible |
| Swedish regulatory fields required | Verify mätpunkt, grid owner, consumption present | TC-037 | All required fields shown |
Dependencies:
- Handlebars.Net template engine library
- PDF generation library (Playwright with headless Chromium or IronPDF)
- Blob storage for template files
- Template metadata storage with version tracking
Risks & Mitigation (Nordic Context):
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| Template rendering performance bottleneck | HIGH | HIGH | - Compiled template caching (24-hour TTL) - Parallel rendering within 32-item batches - POC testing: render 10K invoices in < 5 min - Horizontal scaling of BatchItemWorkers | Technical Architect |
| PDF generation quality issues (Swedish characters) | MEDIUM | MEDIUM | - UTF-8 encoding throughout - Font embedding for åäö characters - Visual regression testing - Sample PDF review with Swedish content | QA Team |
| Swedish Energy Markets Inspectorate compliance | LOW | CRITICAL | - Legal review of template requirements - Required fields checklist in template validation - Compliance testing with regulatory samples - Annual regulatory update review | Legal/Compliance |
| Template injection attacks | LOW | CRITICAL | - Sandboxed Handlebars execution - No {{eval}} or {{exec}} helpers - Template sanitization - Security code review | Security Officer |
2.5 BR-005: Multi-Channel Delivery with Nordic Integration
Requirement: The system shall deliver invoices through multiple channels (email, postal, future: Kivra, e-Faktura, SMS) with configurable priority, automatic fallback, and integration with Nordic delivery partners.
Business Value:
- Increases delivery success rate to >98% (vs ~92% email-only)
- Reduces returned mail costs (postal fallback)
- Meets customer preferences (digital-first, postal backup)
- Enables compliance with Swedish "rätt till pappersfaktura" (right to paper invoice)
- Future-proofs for digital mailbox mandate discussions
Priority: HIGH
Nordic Market Context: Swedish law requires postal option for all customers. Kivra has 4.2M users in Sweden (40% population). E-faktura standard for B2B. Multi-channel is regulatory and competitive necessity.
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| Email delivery via SendGrid | Send 1000 test invoices | TC-040 | >95% delivered |
| Postal delivery via 21G bulk SFTP | Create zip, upload to 21G SFTP | TC-041 | File accepted by 21G |
| Channel priority configurable per org | Set priority [email, postal], verify order | TC-042 | Email attempted first |
| Automatic fallback on failure | Force email failure, verify postal attempted | TC-043 | Postal triggered automatically |
| Delivery status tracked per invoice | Check invoice metadata after delivery | TC-044 | Status and timestamps recorded |
| Retry logic for transient failures | Simulate SendGrid 429 rate limit | TC-045 | Retries with backoff |
| Delivery confirmation logged | Verify audit log entries | TC-046 | All deliveries logged |
| 21G bulk processing at scheduled times | Verify postal queue processed 12:00 and 20:00 | TC-047 | Batches sent on schedule |
Dependencies:
- SendGrid account with Nordic sender reputation
- 21G SFTP server access and credentials
- Azure Key Vault for credential storage
- Postal queue processing service (scheduled workers)
- ZIP file generation for 21G format
Risks & Mitigation (Nordic Context):
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| SendGrid Nordic deliverability issues | MEDIUM | HIGH | - Dedicated IP for Nordic sending - SPF/DKIM/DMARC configuration - Sender reputation monitoring - Backup: Azure Communication Services - Gradual ramp-up for new organizations | Operations Manager |
| 21G SFTP connectivity issues | LOW | HIGH | - Retry logic with exponential backoff - Dual SFTP credentials (primary/backup) - Alert on connection failure - 21G SLA monitoring - Manual upload procedure documented | Operations Manager |
| Postal delivery delays (Swedish postal challenges) | MEDIUM | MEDIUM | - Set customer expectations (5-7 business days) - Track 21G processing confirmations - Escalation process for delays>10 days - Alternative print partner identified | Product Owner |
| Email spam filtering (Swedish ISPs) | MEDIUM | MEDIUM | - Warm up sending IP gradually - Monitor bounce rates by ISP - Whitelist requests to major ISPs (Telia, Tele2, Telenor) - Plain text + HTML multi-part emails | Operations Manager |
| Kivra API rate limits (future) | MEDIUM | MEDIUM | - Queue-based sending - Respect Kivra rate limits (documented in API) - Fallback to email if Kivra unavailable | Technical Architect |
2.6 BR-006: Real-Time Batch Status Visibility
Requirement: Users shall view batch processing status, progress statistics, and individual invoice statuses in real-time through the API with granular breakdown by processing stage and delivery channel.
Business Value:
- Reduces support inquiries by 60% (self-service status checking)
- Enables proactive issue resolution before customer complaints
- Improves operational transparency and trust
- Provides audit trail for service level agreement (SLA) tracking
Priority: MEDIUM
Nordic Market Context: Utility operations teams work standard hours (08:00-17:00). Real-time visibility enables remote monitoring and reduces after-hours escalations.
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| Batch status via API (queued/processing/completed/failed) | GET /batches/{id} during processing | TC-050 | Status reflects reality |
| Progress percentage accurate | Compare reported % to actual processed count | TC-051 | Within 1% accuracy |
| Individual invoice status queryable | GET /batches/{id}/items with status filter | TC-052 | Returns correct filtered list |
| Statistics include success/failure counts | Verify statistics.successfulItems matches reality | TC-053 | Exact match |
| Estimated completion time provided | Check estimatedCompletionAt during processing | TC-054 | Within 20% of actual |
| Failed invoices listed with error details | Query items with status=failed | TC-055 | Error messages present |
| Status updates within 30 seconds | Process batch, poll status API | TC-056 | Updates every ≤30 seconds |
| Delivery channel breakdown shown | Verify deliveryChannelBreakdown matches actual | TC-057 | Accurate breakdown |
Dependencies:
- Batch metadata updates from all workers
- Real-time statistics calculation (incremental updates)
- Blob storage access for metadata reads
- API caching strategy for frequently-polled batches
Risks & Mitigation:
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| Performance impact of frequent metadata updates | MEDIUM | MEDIUM | - ETag-based optimistic concurrency - Batch statistics updates (not per-invoice) - Caching layer for status API - Throttle updates to max 1/minute | Technical Architect |
| Stale status data (eventual consistency) | MEDIUM | LOW | - Document 30-second update SLA - Timestamp on status response - Retry-After header for frequent polls - WebSocket push for Phase 2 | Product Owner |
2.7 BR-007: Security & Access Control
Requirement: The system shall implement OAuth 2.0 authentication with Microsoft Entra ID, role-based access control with 6 distinct roles, organization-level data isolation, and comprehensive audit logging compliant with Swedish and EU security standards.
Business Value:
- Ensures GDPR Article 32 compliance (security of processing)
- Prevents unauthorized data access and potential €20M GDPR fines
- Enables customer trust and enterprise sales (security requirements in tenders)
- Supports SOC 2 Type II compliance for future certification
Priority: CRITICAL
Nordic Market Context: Swedish utilities handle sensitive customer data (personnummer, consumption patterns). GDPR fines can reach 4% of annual turnover. Enterprise security is non-negotiable.
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| OAuth 2.0 with Entra ID authentication | Attempt API access with/without token | TC-060 | 401 without token, 200 with valid token |
| 6 roles implemented | Verify all roles in PostgreSQL | TC-061 | All 6 roles present |
| Users access only their organization data | User from Org A attempts Org B access | TC-062 | 403 Forbidden |
| All data access logged to audit trail | Review audit_logs table after operations | TC-063 | All actions logged |
| API authentication required (all endpoints except /health) | Call endpoints without token | TC-064 | 401 on all except /health |
| MFA enforced for admin roles | Admin login without MFA | TC-065 | MFA challenge presented |
| API key rotation every 90 days | Check key age in Key Vault | TC-066 | Alerts at 80 days |
| Failed login lockout (5 attempts = 15 min) | Attempt 6 failed logins | TC-067 | Account locked |
Dependencies:
- Microsoft Entra ID tenant configuration
- PostgreSQL schema for users, roles, user_organization_roles
- Azure Key Vault for secrets management
- Audit logging infrastructure
- MFA provider integration
Risks & Mitigation (Nordic/EU Context):
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| GDPR non-compliance penalty | LOW | CRITICAL | - Annual GDPR compliance audit - Privacy Impact Assessment (PIA) completed - Data Protection Officer (DPO) review - Datainspektionen (Swedish DPA) guidelines followed - EU Standard Contractual Clauses for vendors | Legal/Compliance |
| Unauthorized personnummer access | LOW | CRITICAL | - Personnummer encrypted at rest - Access logging for all PII fields - Role-based field-level access control - Swedish Personal Data Act compliance | Security Officer |
| Authentication complexity delays onboarding | MEDIUM | MEDIUM | - Entra ID B2B invitation flow - Self-service org admin provisioning - Clear onboarding documentation - SSO with customer Entra ID tenants | Product Owner |
| Audit log storage costs (7-year retention) | MEDIUM | LOW | - PostgreSQL for hot logs (1 year) - Archive to blob after 1 year - Compressed JSON format - Query optimization | Technical Architect |
2.8 BR-008: GDPR & Swedish Data Protection Compliance
Requirement: The system shall comply with GDPR and Swedish Data Protection Law including all data subject rights, lawful processing basis, 7-year retention for invoices, data minimization, and Nordic data residency.
Business Value:
- Avoids GDPR fines (up to €20M or 4% of annual turnover)
- Enables enterprise sales (GDPR compliance is tender requirement)
- Builds customer trust and brand reputation
- Supports Swedish utility regulatory requirements (Energimarknadsinspektionen)
Priority: CRITICAL
Nordic Market Context: Swedish Datainspektionen actively enforces GDPR. Recent fines in telecom/energy sector for inadequate security. Data residency within EU required for many public utility contracts.
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| Right to access: Data export API | Request customer data export | TC-070 | JSON export with all customer invoices |
| Right to erasure: Anonymization | Request customer deletion, verify PII removed | TC-071 | Personnummer, name, email redacted |
| 7-year invoice retention | Check lifecycle policy config | TC-072 | Invoices retained 7 years |
| Audit logging for all data access | Query audit_logs for customer data access | TC-073 | All accesses logged |
| Data residency (Nordic countries only) | Verify blob storage regions | TC-074 | West/North Europe only |
| Consent management for digital delivery | Track customer delivery channel consent | TC-075 | Consent recorded |
| Privacy policy compliance | Legal review | TC-076 | Approved by legal |
| Lawful basis documented | Review data processing inventory | TC-077 | Contract basis for invoice data |
Dependencies:
- Legal review of GDPR compliance approach
- Data anonymization procedures and testing
- Azure Blob lifecycle policies for retention
- Data Processing Agreement (DPA) with Azure
- Privacy Impact Assessment (PIA) completion
Risks & Mitigation (Swedish/EU Context):
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| Datainspektionen (Swedish DPA) audit | LOW | CRITICAL | - Annual self-assessment against GDPR - Document all processing activities (ROPA) - DPO appointed and consulted - Privacy by design in architecture - Regular employee training | Legal/Compliance |
| Cross-border data transfer violations | LOW | CRITICAL | - All data stays in EU (Azure West/North Europe) - No backup to non-EU regions - Vendor contracts include EU Standard Clauses - Azure compliance certifications verified | Legal/Compliance |
| Personnummer handling violations | MEDIUM | CRITICAL | - Personnummer only in encrypted fields - Access logging for all reads - Minimal retention (7 years, then deletion) - Swedish Personal Data Act guidelines - No personnummer in URLs or logs | Security Officer |
| Right to erasure vs 7-year retention conflict | MEDIUM | HIGH | - Anonymization instead of deletion (legal basis: accounting law) - Legal opinion obtained - Balance data subject rights with legal obligations - Documented in privacy policy | Legal/Compliance |
| Third-party processor compliance (SendGrid, 21G) | MEDIUM | HIGH | - Data Processing Agreements (DPA) signed - Sub-processor list maintained - Regular compliance audits - EU-based data centers only | Legal/Compliance |
2.9 BR-009: Operational Monitoring & Observability
Requirement: The system shall provide comprehensive monitoring through Application Insights, structured logging with Serilog, real-time dashboards, and automated alerting to enable 24/7 operational visibility and proactive issue resolution.
Business Value:
- Reduces mean time to detection (MTTD) from hours to minutes
- Enables proactive issue resolution before customer impact
- Supports SLA compliance and reporting
- Reduces on-call burden through automated diagnostics
Priority: HIGH
Nordic Market Context: Swedish customers expect high service quality. Many utilities have SLA commitments (99.9% uptime). Winter heating season requires 24/7 monitoring.
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| Application Insights integrated (all services) | Verify telemetry in Azure portal | TC-080 | All services sending data |
| Structured logging with correlation IDs | Trace request across services | TC-081 | Same correlation ID |
| Custom metrics tracked | Verify metrics in dashboard | TC-082 | Batch, delivery, queue metrics present |
| Dashboards refresh every 5 minutes | Check dashboard timestamp | TC-083 | ≤ 5 minutes old |
| Dashboards accessible to authorized users | Login as different roles | TC-084 | Access granted appropriately |
| Critical alerts trigger within 5 minutes | Simulate high error rate | TC-085 | Alert received within 5 min |
| Alert escalation after 15 min unacknowledged | Don't acknowledge alert | TC-086 | Escalation triggered |
| PII masked in logs | Search logs for personnummer | TC-087 | No personnummer found |
Required Dashboards:
- Operations Dashboard: Active batches, queue depths, worker counts, error rate, health status
- Performance Dashboard: API latency, processing times, PDF generation, delivery latency
- Business Dashboard: Invoices processed, delivery breakdown, top organizations
- Vendor Dashboard: Batches by format, parsing success rates
Dependencies:
- Application Insights workspace
- Alert action groups (email, SMS)
- Dashboard configuration and permissions
- On-call rotation schedule
Risks & Mitigation (Nordic Context):
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| Alert fatigue from false positives | HIGH | MEDIUM | - Tuned thresholds based on baseline - 2-week monitoring before alerts live - Weekly alert review meetings - Alert suppression during maintenance | Operations Manager |
| Insufficient monitoring during off-hours | MEDIUM | HIGH | - 24/7 on-call rotation - Automated incident creation in Jira - Runbook for common issues - PagerDuty integration for escalation | Operations Manager |
| Log storage costs exceeding budget | LOW | MEDIUM | - 90-day log retention - Sampling for high-volume logs - Cost alerts at 80% budget - Archive old logs to blob | Technical Architect |
| Missing critical metrics | MEDIUM | MEDIUM | - Monthly metrics review - Stakeholder feedback on dashboard usefulness - Iterate dashboard based on incidents | Operations Manager |
2.10 BR-010: Test Data Strategy (GDPR Compliance)
Requirement: The system shall use only synthetic, non-sensitive test data in all non-production environments, with zero copying of production data to staging, to ensure GDPR compliance and prevent data breaches.
Business Value:
- Ensures GDPR Article 5(1)(b) compliance (purpose limitation)
- Prevents catastrophic data breach from non-production environments
- Reduces storage and transfer costs (no production data duplication)
- Enables offshore development team participation (India)
Priority: CRITICAL
Nordic Market Context: Swedish Datainspektionen prohibits production data in test environments. Indian development team cannot access personnummer data. European team must lead production debugging.
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| Zero production data in staging | Audit staging blob storage | TC-090 | No real personnummer found |
| Synthetic data generator creates realistic batches | Generate 10K synthetic invoices | TC-091 | Valid structure, fake PII |
| European team handles production issues | Production bug workflow documented | TC-092 | No PII sent to offshore team |
| Reproduction scenarios use synthetic data | Create synthetic scenario from production bug | TC-093 | Issue reproducible |
| Staging data clearly marked as test | Visual indicators in UI, filename patterns | TC-094 | Test data obvious |
| Production access restricted (European team only) | Attempt production access from India VPN | TC-095 | Access denied (geo-fenced) |
| Synthetic data follows Swedish patterns | Review generated personnummer, addresses | TC-096 | Realistic but invalid |
Dependencies:
- Synthetic data generation tool (Swedish personnummer, addresses, etc.)
- Staging environment completely isolated from production
- Network policies restricting production access
- Documentation of production issue workflow
Risks & Mitigation (EU/India Context):
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| Accidental production data leak to staging | LOW | CRITICAL | - Automated scanning for real personnummer patterns - No database copying tools - Production data access audit logs - Annual security training | Security Officer |
| Offshore team delays due to data restrictions | MEDIUM | MEDIUM | - European team creates reproduction scenarios - Comprehensive synthetic data sets - Well-documented issue reports - Pair programming for production issues | Product Owner |
| Synthetic data unrealistic (testing gaps) | MEDIUM | MEDIUM | - Generate from real data distributions (anonymized) - Edge cases library (long names, special chars) - Swedish address/personnummer validation - Regular synthetic data quality review | QA Team |
| Production debugging bottleneck (European team only) | MEDIUM | MEDIUM | - European team on-call 24/7 - Comprehensive monitoring reduces debugging needs - Runbooks for common issues - Knowledge transfer to European team | Operations Manager |
2.11 BR-011: Invoice Download API
Requirement: Users shall be able to download generated invoices (PDF and HTML) through authenticated API endpoints with access control and audit logging.
Business Value:
- Enables customer service to retrieve invoices for disputes
- Supports reprint requests without reprocessing
- Facilitates regulatory compliance (invoice provision upon request)
- Enables future customer portal integration
Priority: HIGH
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| API endpoint to download PDF by invoice ID | GET /invoices/{id}/pdf | TC-100 | PDF file returned |
| API endpoint to download HTML by invoice ID | GET /invoices/{id}/html | TC-101 | HTML returned |
| Download links in batch item response | GET /batches/{id}/items/{itemId} | TC-102 | pdfUrl and htmlUrl present |
| Access control: org users only | User from Org A downloads Org B invoice | TC-103 | 403 Forbidden |
| Download generates audit log entry | Download invoice, check audit_logs | TC-104 | Entry created |
| Content-Disposition header for PDF | Check HTTP response headers | TC-105 | Filename in header |
| Rate limiting on downloads | Download 1000 invoices rapidly | TC-106 | Rate limit applied |
Dependencies:
- Blob storage SAS token generation
- Access control middleware
- Audit logging service
Risks & Mitigation:
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| Unauthorized invoice access | LOW | HIGH | - Organization boundary checks - Audit all downloads - Rate limiting - Anomaly detection | Security Officer |
| Bandwidth costs for large volumes | MEDIUM | LOW | - CDN for frequently accessed invoices - Compression - Monitoring | Technical Architect |
2.12 BR-012: Batch History & Search
Requirement: Users shall be able to search, filter, and list historical batches for their organization with support for date ranges, status filters, and vendor format filtering.
Business Value:
- Enables troubleshooting and root cause analysis
- Supports operational reporting and SLA tracking
- Facilitates audit compliance
- Improves user experience with search capabilities
Priority: MEDIUM
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| List batches with pagination | GET /batches?page=1&pageSize=50 | TC-110 | Paginated list returned |
| Filter by date range | GET /batches?from=2025-11-01&to=2025-11-30 | TC-111 | Only Nov batches returned |
| Filter by status | GET /batches?status=completed | TC-112 | Only completed batches |
| Filter by vendor format | GET /batches?vendorCode=GASEL | TC-113 | Only GASEL batches |
| Search by batch name | GET /batches?search=November | TC-114 | Name contains "November" |
| Sort by upload/completion date | GET /batches?sortBy=uploadedAt&order=desc | TC-115 | Newest first |
| Returns last 90 days by default | GET /batches (no filters) | TC-116 | Last 90 days only |
| Access restricted to organization | User queries batches from other org | TC-117 | Empty results |
Dependencies:
- Batch metadata indexing strategy
- Query performance optimization
- Blob storage metadata queries or search index
Risks & Mitigation:
| Risk | Likelihood | Impact | Mitigation Strategy | Owner |
|---|---|---|---|---|
| Slow queries with large batch history | MEDIUM | MEDIUM | - Index on organization_id, date - Pagination required - Consider Azure Cognitive Search for Phase 2 | Technical Architect |
2.13 BR-013: Notification System
Requirement: The system shall send email notifications to designated organization contacts when batch processing completes successfully or fails, including summary statistics and error reports.
Business Value:
- Reduces manual status checking effort by 80%
- Enables proactive issue resolution
- Improves customer satisfaction with timely updates
- Supports SLA monitoring and reporting
Priority: MEDIUM
Acceptance Criteria:
| Criterion | Measurement Method | Test Case | Target |
|---|---|---|---|
| Email sent on batch completion | Complete batch, verify email received | TC-120 | Email received within 5 min |
| Email sent on batch failure | Force batch failure, verify email | TC-121 | Email received within 5 min |
| Email includes summary statistics | Review email content | TC-122 | Total, success, failed counts present |
| Email includes error report for failures | Review failure email | TC-123 | Failed items listed with reasons |
| Recipients configurable per organization | Update org config, verify new recipient | TC-124 | Email to correct recipients |
| Email template professional and branded | Review email design | TC-125 | EG branding applied |
| Links to batch status in email | Click link in email | TC-126 | Opens to batch detail |
Dependencies:
- Email service (SendGrid or Azure Communication Services)
- Email templates (HTML)
- Organization configuration for recipients
Risks & Mitigation:
...