Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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

  1. Revenue Model: Enables SaaS subscription model across Nordic markets
  2. Cost Efficiency: Shared infrastructure reduces per-customer cost by 60-70%
  3. Market Penetration: Faster onboarding enables rapid customer acquisition
  4. 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

#CriterionMeasurement MethodTarget
1Concurrent organizations supportedLoad test with 50 orgsAll batches process successfully
2Data isolation enforcementCross-org access attempts100% blocked (403 Forbidden)
3Organization-specific blob containersVerify storage pathsPattern: {org-id}-{type}-{year}/
4User organization boundary enforcementAPI calls with wrong org contextAll rejected
5Independent branding per organizationUpload logo, verify renderingBranding applied correctly
6Configurable delivery channelsSet priority [email, postal]Order respected

Dependencies

  • Azure Blob Storage (container-per-organization strategy)
  • PostgreSQL schema with user_organization_roles table
  • Organization context middleware
  • Role-based access control (RBAC) implementation

Risks & Mitigation

RiskLikelihoodImpactMitigation
Data leakage between orgsLOWCRITICALMiddleware enforcement, automated testing, penetration testing
Performance degradation (50+ tenants)MEDIUMHIGHBlob auto-scaling, connection pooling, indexed queries
Swedish data residency requirementsLOWHIGHWest 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

  1. Market Coverage: Supports 70% of Swedish utilities market
  2. Zero Custom Development: No per-vendor integration coding required
  3. Faster Onboarding: 80% reduction in integration time
  4. 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

#CriterionMeasurement MethodTarget
1GASEL format detection50 sample files100% accuracy
2XELLENT format detection50 sample files100% accuracy
3ZYNERGY format detection50 sample files100% accuracy
4Canonical JSON transformationSchema validationAll fields present
5XSD schema validationVendor-specific XSDPass validation
6Unsupported format handlingUnknown XML upload415 error with vendor list
7Detection performance100MB 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):

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

RiskLikelihoodImpactMitigation
Vendor schema changes without noticeMEDIUMHIGHVersion all schemas, support multiple versions, 3-month deprecation notice
EDIEL standard evolutionMEDIUMMEDIUMMonitor Ediel.org, participate in Nordic working groups, backward compatibility
Complex namespace handling (OIOXML)LOWMEDIUMXmlNamespaceManager, extensive unit testing per vendor
Incomplete field mappingsMEDIUMMEDIUMComprehensive 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

  1. High-Volume Support: Typical Swedish utility has 50K-200K customers
  2. Time Efficiency: 95% reduction in manual processing effort
  3. Customer Satisfaction: Days → hours delivery time
  4. 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

#CriterionMeasurement MethodTarget
1Single batch capacityUpload 100K invoicesAll processed
2Asynchronous processingAPI response time< 500ms (202 Accepted)
3Real-time progress trackingPoll during processingUpdates every 30 seconds
4Failed item isolation10 errors in 1000-item batch990 succeed independently
5Retry mechanismForce temporary failure3 retries then poison queue
6Processing time SLA100K invoice batch≤ 120 minutes
7Format support (Phase 1)Upload XML, JSON, CSVXML 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

RiskLikelihoodImpactMitigation
Processing timeout during heating seasonMEDIUMHIGHPre-warm workers 1st/last week, priority queue, off-peak scheduling
Memory constraints (large XML >50MB)MEDIUMMEDIUMStream-based parsing, chunk processing, 100MB hard limit
Disk space exhaustionLOWMEDIUMEphemeral storage cleanup, blob-only persistence
Queue 64KB message limitMEDIUMMEDIUMStore 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

  1. Brand Consistency: Professional appearance across all communications
  2. Regulatory Compliance: Swedish Energy Markets Inspectorate requirements
  3. Flexibility: Per-organization customization without code changes
  4. 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

#CriterionMeasurement MethodTarget
1Custom template uploadUpload via API/blobStored successfully
2Dynamic data bindingTest with invoice dataAll fields populated
3PDF generationHTML → PDFA4 format, readable
4Template versioningCreate v2.0.0Old batches use v1.0.0
5In-flight batch isolationUpdate template during processingIn-flight uses old version
6Template validationMissing variable uploadValidation error returned
7Organization brandingLogo, colors, fontsVisible in rendered PDF
8Swedish regulatory fieldsVerify required elementsAll 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

RiskLikelihoodImpactMitigation
Template rendering bottleneckHIGHHIGHCompiled template caching (24h), parallel rendering (32 items), POC: 10K in <5 min
PDF generation quality (Swedish chars)MEDIUMMEDIUMUTF-8 encoding, font embedding (åäö), visual regression testing
Swedish regulatory complianceLOWCRITICALLegal review, required fields checklist, annual update review
Template injection attacksLOWCRITICALSandboxed 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

  1. Delivery Success: >98% vs ~92% email-only
  2. Cost Reduction: Reduced returned mail costs
  3. Customer Preference: Digital-first with postal backup
  4. Legal Compliance: Swedish "rätt till pappersfaktura" (right to paper invoice)
  5. 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

#CriterionMeasurement MethodTarget
1Email delivery (SendGrid)1000 test invoices>95% delivered
2Postal delivery (21G SFTP)Create ZIP, uploadFile accepted by 21G
3Channel priority configurationSet [email, postal]Email attempted first
4Automatic fallbackForce email failurePostal triggered auto
5Delivery status trackingCheck invoice metadataStatus + timestamps recorded
6Retry logic (transient failures)Simulate SendGrid 429Retries with backoff
7Delivery confirmation loggingVerify audit logAll deliveries logged
821G bulk processing scheduleVerify postal queue12: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

RiskLikelihoodImpactMitigation
SendGrid Nordic deliverability issuesMEDIUMHIGHDedicated IP, SPF/DKIM/DMARC, sender reputation monitoring, backup: Azure Communication Services
21G SFTP connectivity issuesLOWHIGHRetry logic, dual credentials, alert on failure, 21G SLA monitoring, manual upload procedure
Postal delivery delays (Swedish postal)MEDIUMMEDIUMSet expectations (5-7 days), track confirmations, escalation for >10 days
Email spam filtering (Swedish ISPs)MEDIUMMEDIUMIP warmup, monitor bounce rates, ISP whitelist requests (Telia, Tele2, Telenor)

Non-Functional Requirements

NFR-001: Performance Targets

Priority: HIGH
Owner: Technical Architect

Performance Metrics

MetricTargetMeasurementTest Scenario
Monthly throughput10M invoicesApplication InsightsProduction monitoring
100K batch processing< 2 hoursTimestamp diffLoad test TC-200
API response (p50)< 200msApplication InsightsLoad test TC-201
API response (p95)< 500msApplication InsightsLoad test TC-202
API response (p99)< 1000msApplication InsightsLoad test TC-203
PDF generation (p95)< 5 seconds/invoiceCustom metricRender test TC-204
Handlebars render (p95)< 2 seconds/invoiceCustom metricRender test TC-205
Queue processing lag< 5 minutesQueue depth / throughputQueue monitoring
Database query (p95)< 100msPostgreSQL slow query logQuery analysis
ParserService (10K batch)< 2 minutesParse durationParser 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

#CriterionValidationTarget
1100K batch completionEnd-to-end test≤ 2 hours
2API latency under load1000 RPS testp95 ≤ 500ms
310M monthly capacityProduction monitoring≥ 10M in peak month
450-org performance50 concurrent uploadsAll SLAs met
5Worker auto-scalingMonitor queue during peaksLag ≤ 5 min
6PDF generation performance1000 PDFsp95 ≤ 5 seconds

NFR-002: Scalability & Auto-Scaling

Priority: HIGH
Owner: Technical Architect

Scaling Configuration

ComponentMinMaxTriggerThresholdScale UpScale Down
CoreApiService520CPU OR Request Rate70% OR 1000 RPS2 min10 min
ParserService210Queue Length>01 min5 min
DocumentGenerator2100Queue Length>321 min5 min
EmailService550Queue Length>501 min5 min
PostalService13Scheduled12:00, 20:00 CETN/AAfter 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

MetricTargetAllowed DowntimeMeasurement
System Uptime99.9%43 min/monthAzure Monitor
Batch Success Rate>99.5%50 failures per 10KProcessing logs
Delivery Success Rate>98%200 failures per 10KDelivery tracking
API Availability99.9%43 min/monthHealth checks
MTTR<30 minutesN/AIncident timestamps
MTBF>720 hoursN/AIncident 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:

  1. Super Admin (global)
  2. Organization Admin (single org)
  3. Template Admin (single org)
  4. Batch Operator (single org)
  5. Read-Only User (single org)
  6. 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 TypeRetentionStorage Tier Transitions
Invoices (PDF/HTML/JSON)7 yearsDay 0-365: Hot
Day 366-2555: Cool
Day 2556+: Archive
Batch Source (XML)90 daysDay 0-30: Hot
Day 31-90: Cool
Day 91+: Delete
Audit Logs7 yearsYear 0-1: PostgreSQL
Year 1-7: Blob (compressed)
Application Logs90 daysApplication Insights

Approval Section

Stakeholder Sign-Off

...

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:

  1. Document proposed change in Jira (tag with egflow version)
  2. Impact assessment (scope, timeline, cost)
  3. Re-approval by Product Owner and Technical Architect
  4. Update this document with version increment
  5. Communicate changes to development team
  6. Update affected Jira issues with new fixVersion

Version History

VersionDateAuthorChangesRelease Target
1.02025-11-20Product OwnerInitial draftegflow-1.0.0
1.12025-11-21Product OwnerAdded FR-003 details, updated acceptance criteriaegflow-1.0.0
1.22025-11-27Product OwnerUpdated versioning strategy to match Gasell modelegflow-1.0.0 "Corny Flamingo"

End of Business Requirements Document

...