Version: 2.0
Last Updated: 2026-01-15
Status: Active
Change Log: v2.0 - Converted to business-focused format with measurable outcomes, success metrics, and standardized structure
Overview
Purpose
The Invoice Management system handles the creation, modification, and tracking of invoices for vehicle rental orders in a multi-tenant environment. It manages invoice numbering, series organization, line items, payment status, discounts, electronic billing integration, and multi-language invoice generation. The system ensures proper financial documentation and supports both regular invoices and proforma invoices across different rental companies.
Problem Statement
Rental companies need a robust invoicing system that can:
- Generate professional invoices with sequential numbering per series
- Track payment status and methods for each invoice
- Support multiple invoice types (invoices, proforma invoices, credit notes)
- Handle complex line items with VAT calculations and discounts
- Integrate with electronic billing systems for regulatory compliance
- Maintain invoice series per company and tenant
- Support multi-language invoice generation
- Connect invoices to customers (clients and partners) and company entities
Key Business Challenges:
| Challenge | Business Impact | Current State |
|---|
| Manual Invoice Creation | 15-30 minutes per invoice, prone to errors | Operators manually create invoices from orders |
| Payment Tracking | Revenue reconciliation delays, cash flow visibility gaps | Payment status tracked separately from invoices |
| Compliance Risk | Regulatory fines for missing or incorrect invoices | No automated electronic billing submission |
| Customer Experience | Delayed invoice delivery, language barriers | Manual PDF generation, single language |
| Financial Reporting | Incomplete revenue visibility, audit trail gaps | Invoices not consistently linked to orders/payments |
Business Value
| Value Area | Measurable Outcome | Target | Measurement Method |
|---|
| Operational Efficiency | Reduce invoice creation time from orders | 80% reduction (15 min → 3 min) | Time tracking: manual vs. automated creation |
| Payment Reconciliation | Improve payment tracking accuracy | 100% invoices linked to payments | Database audit: invoice-payment associations |
| Compliance | Electronic billing submission rate | 95%+ of eligible invoices submitted | Electronic billing status tracking |
| Customer Satisfaction | Multi-language invoice availability | 100% invoices in customer language | Language selection analytics |
| Financial Visibility | Complete invoice-to-order linkage | 100% invoices traceable to orders | Order-invoice association audit |
| Revenue Accuracy | Eliminate calculation errors | Zero manual calculation errors | Invoice total calculation validation |
Success Metrics
| Metric | Definition | Baseline | Target | Measurement Method | Timeframe |
|---|
| Invoice Creation Time | Time from order completion to invoice generation | 15-30 minutes (manual) | < 3 minutes | System timestamps on invoice creation workflow | 3 months |
| Payment Reconciliation Rate | Invoices with linked payment records / Total invoices | Estimate: 70% | 95%+ | Database query: invoice-payment associations | 6 months |
| Electronic Billing Submission | Invoices successfully submitted / Eligible invoices | Estimate: 60% | 95%+ | Electronic billing status tracking | 6 months |
| Multi-Language Usage | Non-default language invoices / Total invoices | Estimate: 20% | > 50% in eligible markets | Language selection tracking | 6 months |
| Calculation Accuracy | Invoices with correct totals / Total invoices | Estimate: 95% | 99.9%+ | Automated calculation validation | Ongoing |
| Invoice Search Performance | Time to retrieve filtered invoice results | N/A | < 500ms (p95) | Application monitoring | Ongoing |
| Customer Invoice Access | Customers viewing/downloading invoices / Total invoices | N/A | > 60% view rate | Customer portal analytics | 6 months |
Baseline Collection: 30-day pre-implementation measurement using current manual process tracking.
Target Users
| User Role | Business Context | Primary Goals |
|---|
| Admin | Financial managers overseeing invoicing operations | Full invoice management, compliance oversight, financial reporting |
| Operator | Frontline staff handling daily invoice operations | Create invoices from orders, update payment status, generate PDFs |
| Client | Rental customers receiving invoices | View and download invoices for their orders, track payment status |
| Partner | Marketplace vehicle owners | View invoices related to their vehicles and marketplace orders |
User Stories
P0 - Critical (Must Have)
US-1: Create Invoice from Order
- As an operator, I want to generate invoices automatically from completed orders so that I can create accurate invoices in under 3 minutes.
- Acceptance Criteria:
- GIVEN a completed order exists
- WHEN operator selects “Create Invoice” from order
- THEN system populates invoice with order line items, customer, and company
- AND invoice number is automatically assigned from series
- AND invoice is indexed for search
- AND invoice creation completes in under 3 minutes
US-2: Manual Invoice Creation
- As an operator, I want to create invoices manually with custom line items so that I can invoice non-order transactions.
- Acceptance Criteria:
- GIVEN operator accesses invoice creation interface
- WHEN operator enters customer, company, line items, and payment details
- THEN system validates customer and company exist
- AND system creates invoice with unique ID
- AND system automatically creates series if new
- AND invoice totals are calculated correctly
US-3: Track Payment Status
- As an operator, I want to mark invoices as paid and record payment details so that payment reconciliation is accurate.
- Acceptance Criteria:
- GIVEN an unpaid invoice exists
- WHEN operator updates payment status with payment date and method
- THEN invoice state.payd flag is set to true
- AND payment date is recorded
- AND payment method is stored
- AND invoice is linked to payment record
US-4: Search and Filter Invoices
- As an admin, I want to search invoices by number, customer, or company and filter by date range so that I can quickly find specific invoices.
- Acceptance Criteria:
- GIVEN invoices exist in the system
- WHEN admin searches by invoice number, customer name, or company name
- THEN system returns matching invoices ranked by relevance
- AND admin can filter by date range using month/year picker
- AND search results include pagination
- AND deleted invoices are excluded by default
US-5: Download Invoice PDF
- As a client, I want to download invoice PDFs in my preferred language so that I have proper documentation for my records.
- Acceptance Criteria:
- GIVEN an invoice exists for the client
- WHEN client requests PDF download
- THEN system generates PDF in client’s preferred language
- AND PDF includes all invoice details, line items, and totals
- AND PDF generation completes in under 10 seconds
P1 - Important (Should Have)
US-6: Electronic Billing Submission
- As an operator, I want to submit invoices to electronic billing systems so that regulatory compliance is automated.
- Acceptance Criteria:
- GIVEN an invoice with electronic billing integration configured
- WHEN operator submits invoice to electronic billing
- THEN system sends invoice data to e-billing API
- AND electronic billing ID is stored
- AND status is updated (CONS, ERRO, INVI, NONC)
- AND operator can track submission status
US-7: Apply Discounts
- As an operator, I want to apply discounts at invoice level (percentage or fixed amount) so that I can offer flexible pricing.
- Acceptance Criteria:
- GIVEN an invoice with line items
- WHEN operator applies discount (PERCENT or AMOUNT)
- THEN system calculates discount amount correctly
- AND invoice total is recalculated with discount
- AND discount cannot exceed subtotal
- AND discount is displayed on invoice
US-8: Invoice Series Management
- As an admin, I want to create and manage invoice series with custom prefixes so that invoices are organized by business unit.
- Acceptance Criteria:
- GIVEN admin needs new invoice series
- WHEN admin creates invoice with new series name
- THEN system automatically creates series if it doesn’t exist
- AND series is unique per tenant
- AND admin can query last invoice number in series
US-9: Soft Delete Invoice
- As an admin, I want to mark invoices as deleted without physical deletion so that audit trails are preserved.
- Acceptance Criteria:
- GIVEN an existing invoice
- WHEN admin marks invoice as deleted
- THEN invoice deleted flag is set to true
- AND invoice is excluded from default queries
- AND invoice data is preserved for audit
- AND invoice remains in database
P2 - Nice to Have
US-10: Send Invoice via Email
- As an operator, I want to send invoices directly to customers via email so that invoice delivery is automated.
- Acceptance Criteria:
- GIVEN an invoice exists
- WHEN operator selects “Send Invoice”
- THEN system sends email with invoice PDF attachment
- AND email is sent in customer’s preferred language
- AND delivery status is tracked
US-11: Invoice Attachments
- As an operator, I want to attach files to invoices so that supporting documents are included.
- Acceptance Criteria:
- GIVEN an invoice exists
- WHEN operator uploads attachment
- THEN file is stored and linked to invoice
- AND file is accessible in invoice view
- AND file appears in Files/Actions column
Functional Requirements
FR-1: Invoice Data Model
| Req ID | Requirement | Business Outcome |
|---|
| FR-01 | Store invoices with fields: id, series, number, date, customerId, companyId, items, state, deleted, discount, discountUnit, electronicBillingId, electronicBillingStatus, type, language, paymentMethod, tenantId | Complete invoice data for financial documentation |
| FR-02 | Support invoice types: Invoice, Credit Note, Proforma | Flexible invoice types for different business scenarios |
| FR-03 | Support discount units: PERCENT, AMOUNT | Flexible discount application methods |
| FR-04 | Support electronic billing statuses: INVI (invalid), ERRO (error), CONS (completed), NONC (not completed) | Track regulatory submission status |
| FR-05 | Store invoice line items as JSON array with fields: number, code, description, quantity, price, netPrice, vat | Detailed line item tracking for audit |
| FR-06 | Store invoice state as JSON with fields: payd (boolean), paymentDate, paymentMethod, status | Complete payment tracking |
| FR-07 | Store payment method details as JSON with fields: method, name, bank, account, cif, iban, swift, address | Complete payment information for reconciliation |
| FR-08 | Support hidden insurance flag and value for special pricing scenarios | Flexible pricing for insurance charges |
FR-2: Invoice Series Management
| Req ID | Requirement | Business Outcome |
|---|
| FR-09 | Maintain separate invoices_series table with fields: id, series, tenantId, createdAt, updatedAt | Organized invoice numbering per business unit |
| FR-10 | Enforce unique series per tenant using compound unique constraint (series, tenantId) | Prevent series conflicts across tenants |
| FR-11 | Automatically create new series when invoice is created with non-existent series | Seamless series creation workflow |
| FR-12 | Provide query for last invoice number in a series for continuity | Maintain sequential numbering |
| FR-13 | Allow multiple companies within same tenant to share or use different series | Flexible series organization |
FR-3: Invoice Creation
| Req ID | Requirement | Business Outcome |
|---|
| FR-14 | Create invoices via GraphQL mutation with input: customer, company, series, number, date, type, language, items, state, paymentMethod, discount, discountUnit | Programmatic invoice creation |
| FR-15 | Validate customer exists (Client or Partner) before creating invoice | Data integrity enforcement |
| FR-16 | Validate company exists before creating invoice | Data integrity enforcement |
| FR-17 | Automatically create invoice series if it doesn’t exist during invoice creation | Seamless workflow |
| FR-18 | Set deleted flag to false by default for new invoices | Proper default state |
| FR-19 | Generate snowflake ID for new invoices | Unique identifier generation |
| FR-20 | Index invoices to search system for quick retrieval by number, customer name, company name | Fast invoice search |
| FR-21 | Support creating invoices from completed orders with automatic line item population | Automated invoice generation |
| FR-22 | Default invoice language to tenant language if not specified | Proper language defaults |
FR-4: Invoice Modification
| Req ID | Requirement | Business Outcome |
|---|
| FR-23 | Update invoices via GraphQL mutation with fields: id, series, number, date, type, language, customer, company, items, state, paymentMethod, discount, discountUnit, deleted | Flexible invoice updates |
| FR-24 | Allow updating invoice series with automatic series creation if new series doesn’t exist | Series flexibility |
| FR-25 | Allow marking invoices as deleted without physical deletion for audit trails | Audit trail preservation |
| FR-26 | Allow updating payment status including payd flag, paymentDate, and paymentMethod | Payment tracking |
| FR-27 | Recalculate invoice totals when items or discount is modified | Accurate calculations |
FR-5: Invoice Retrieval
| Req ID | Requirement | Business Outcome |
|---|
| FR-28 | Retrieve invoices filtered by date range (from/to) | Time-based filtering |
| FR-29 | Exclude deleted invoices from default queries unless explicitly requested | Clean default views |
| FR-30 | Support full-text search on invoice number, customer name, company name | Fast invoice discovery |
| FR-31 | Return invoices with pagination support (first, after cursor) | Scalable query results |
| FR-32 | Retrieve single invoice by ID with all related data | Complete invoice details |
| FR-33 | Support fetching invoices by multiple IDs for batch operations | Efficient batch processing |
| FR-34 | Format invoice dates as ISO strings for GraphQL responses | Standard date formatting |
FR-6: Invoice Calculations
| Req ID | Requirement | Business Outcome |
|---|
| FR-35 | Calculate line item totals: netPrice = price * quantity | Accurate line item totals |
| FR-36 | Calculate VAT amounts per line item: vatAmount = netPrice * (vat / 100) | Accurate VAT calculation |
| FR-37 | Calculate invoice subtotal as sum of all line item netPrices | Accurate subtotal |
| FR-38 | Apply discount to subtotal based on discountUnit (PERCENT or AMOUNT) | Accurate discount application |
| FR-39 | Calculate invoice total with discount: total = subtotal - discountAmount | Accurate final total |
| FR-40 | Calculate total VAT as sum of all line item VAT amounts | Accurate VAT total |
FR-7: Electronic Billing Integration
| Req ID | Requirement | Business Outcome |
|---|
| FR-41 | Store electronic billing ID for invoices submitted to e-billing systems | Track submission status |
| FR-42 | Track electronic billing status: INVI, ERRO, CONS, NONC | Monitor compliance status |
| FR-43 | Provide mutation to submit invoices to electronic billing system | Automated compliance |
| FR-44 | Update electronic billing status based on submission results | Status tracking |
| FR-45 | Allow filtering invoices by electronic billing status | Compliance monitoring |
FR-8: Payment Integration
| Req ID | Requirement | Business Outcome |
|---|
| FR-46 | Link invoices to payment records for reconciliation | Complete financial tracking |
| FR-47 | Track payment status in invoice state (payd flag) | Payment visibility |
| FR-48 | Record payment date when invoice is marked as paid | Payment history |
| FR-49 | Support multiple payment method types in invoice paymentMethod field | Flexible payment methods |
| FR-50 | Collect analytics when invoices are created including amount, payment method, currency | Business intelligence |
FR-9: Access Control
| Req ID | Requirement | Business Outcome |
|---|
| FR-51 | Enforce row-level security (RLS) based on tenantId | Multi-tenant isolation |
| FR-52 | Restrict invoice access to users within same tenant | Security enforcement |
| FR-53 | Allow admins to view all invoices in their tenant | Administrative oversight |
| FR-54 | Allow operators to create and modify invoices | Operational access |
| FR-55 | Allow clients to view only their own invoices | Customer privacy |
| FR-56 | Allow partners to view invoices related to their vehicles | Partner access |
| FR-57 | Restrict Partner/Driver roles to “No access” for invoices | Role-based restrictions |
| FR-58 | Distinguish between “View only” vs “Full access” permissions | Granular permissions |
Acceptance Criteria
AC-01: Create Invoice
- Given valid customer, company, and invoice details
- When createInvoice mutation is called
- Then system creates invoice with unique ID
- And automatically creates series if it doesn’t exist
- And indexes invoice for search
- And returns invoice edge with cursor
- Success: Invoice creation completes in under 3 minutes
AC-02: Update Invoice
- Given existing invoice ID and update fields
- When updateInvoice mutation is called
- Then system updates specified fields
- And preserves unchanged fields
- And returns updated invoice
- And maintains audit trail
- Success: Update completes without errors
AC-03: Query Invoices by Date Range
- Given date range (from/to)
- When invoices query is called with dates parameter
- Then system returns invoices within date range
- And excludes deleted invoices
- And includes pagination metadata
- And formats dates as ISO strings
- Success: Query completes in under 500ms (p95)
AC-04: Search Invoices
- Given search query string
- When invoices query is called with search parameter
- Then system searches invoice number, customer name, company name
- And returns matching invoices ranked by relevance
- And supports partial matches
- Success: Search completes in under 500ms (p95)
AC-05: Invoice Series Auto-Creation
- Given invoice with new series value
- When invoice is created or updated
- Then system checks if series exists
- And creates new series if not found
- And maintains unique constraint per tenant
- Success: Series creation is transparent to user
AC-06: Last Invoice Number Query
- Given series name and tenant
- When lastInvoiceNumber query is called
- Then system returns last used invoice number in series
- And returns null if series has no invoices
- And respects tenant isolation
- Success: Query completes in under 100ms
AC-07: Calculate Invoice Totals
- Given invoice with line items and discount
- When invoice is retrieved or calculated
- Then system calculates subtotal from line items
- And applies discount based on discountUnit
- And calculates total VAT
- And returns invoice total with discount
- Success: 99.9%+ calculation accuracy
AC-08: Mark Invoice as Paid
- Given unpaid invoice
- When invoice state is updated with payd=true and paymentDate
- Then system marks invoice as paid
- And records payment date
- And updates payment method if provided
- And links invoice to payment record
- Success: Payment status update completes successfully
AC-09: Electronic Billing Submission
- Given invoice with electronic billing integration
- When submitToElectronicBilling mutation is called
- Then system submits invoice to e-billing system
- And stores electronicBillingId
- And updates electronicBillingStatus based on result
- Success: 95%+ submission success rate
AC-10: Soft Delete Invoice
- Given existing invoice
- When invoice is updated with deleted=true
- Then system marks invoice as deleted
- And excludes from default queries
- And preserves invoice data for audit
- And maintains in database
- Success: Deleted invoices excluded from default views
Business Rules
| Rule ID | Rule | Rationale |
|---|
| BR-01 | Invoice numbers must be sequential per series | Maintain audit trail and numbering continuity |
| BR-02 | Series and tenant combination must be unique | Prevent conflicts in multi-tenant environment |
| BR-03 | Invoice numbers can contain alphanumeric characters | Support flexible numbering schemes |
| BR-04 | Invoice type determines template and legal requirements | Different types have different compliance needs |
| BR-05 | PERCENT discount: discountAmount = subtotal * (discount / 100) | Standard percentage calculation |
| BR-06 | AMOUNT discount: discountAmount = discount | Fixed amount discount |
| BR-07 | Discount cannot exceed subtotal | Prevent negative totals |
| BR-08 | VAT is calculated per line item based on item vat rate | Accurate tax calculation |
| BR-09 | Total VAT is sum of all line item VAT amounts | Complete VAT reporting |
| BR-10 | All invoices must have tenantId | Multi-tenant isolation requirement |
| BR-11 | Queries filter by tenantId automatically via RLS | Security enforcement |
| BR-12 | Invoices must be linked to either Client or Partner | Customer association requirement |
| BR-13 | Customer can be changed on edit (not fixed after creation) | Flexibility for corrections |
| BR-14 | Deleted invoices remain in database with deleted=true | Audit trail preservation |
| BR-15 | Default queries exclude deleted invoices | Clean default views |
| BR-16 | Invoice language determines PDF template language | Multi-language support |
| BR-17 | Language defaults to customer’s preferred language | Customer experience |
| BR-18 | Electronic billing status: INVI (invalid), ERRO (error), CONS (completed), NONC (not completed) | Compliance tracking |
Dependencies
Upstream Dependencies
| System | Dependency | Impact if Unavailable |
|---|
| Customer Management | Clients and partners tables for customer association | Cannot create invoices without customer |
| Company Management | Companies table for company association | Cannot create invoices without company |
| Order System | Order data for automatic invoice generation | Manual invoice creation only |
| Payment Processing | Payment records for reconciliation | Payment status tracking unavailable |
| PDF Generation | Invoice PDF rendering | Cannot generate invoice PDFs |
| Search System | Invoice indexing for quick retrieval | Search unavailable, manual filtering only |
| Analytics | Invoice creation event tracking | Business intelligence unavailable |
Downstream Dependencies
| Dependent System | Integration Point | Value Delivered |
|---|
| Financial Reporting | Invoice data aggregation | Revenue and payment reporting |
| Customer Portal | Invoice viewing and download | Customer self-service |
| Electronic Billing Systems | Invoice submission API | Regulatory compliance |
| Payment Reconciliation | Invoice-payment linking | Financial accuracy |
External Dependencies
| System | Purpose |
|---|
| Prisma ORM | Data access layer for invoice storage |
| GraphQL | API layer for invoice mutations and queries |
| Fauna/PostgreSQL | Database storage (dual-write during migration) |
| Upstash/Algolia | Search index for invoice queries |
| Electronic Billing APIs | Third-party integrations for regulatory submission |
Non-Functional Requirements
| Category | Requirement | Target |
|---|
| Performance | Invoice creation time | < 3 minutes (from order) |
| Performance | Invoice search response | < 500ms (p95) |
| Performance | PDF generation time | < 10 seconds |
| Availability | Invoice service uptime | 99.5% |
| Scalability | Concurrent invoice operations | 100+ simultaneous users |
| Data Quality | Calculation accuracy | 99.9%+ |
| Security | Tenant isolation | 100% query isolation |
| Compliance | Electronic billing submission rate | 95%+ of eligible invoices |
Glossary
| Term | Definition |
|---|
| Invoice | Legal document recording sale of goods or services, includes line items, customer, company, totals, and payment terms |
| Proforma Invoice | Preliminary invoice or quote sent before goods/services are delivered, not legally binding for accounting purposes |
| Credit Note | Document representing refund or credit adjustment to an original invoice |
| Invoice Series | Named sequence for organizing invoices, typically with prefix like “INV2024-” or “PRO-”, unique per tenant |
| Line Item | Individual entry on invoice representing single good or service, includes description, quantity, price, and VAT rate |
| VAT (Value Added Tax) | Consumption tax added to goods and services, calculated per line item based on applicable rate |
| Discount Unit | Method of discount calculation - PERCENT applies percentage reduction, AMOUNT applies fixed amount reduction |
| Electronic Billing | Automated submission of invoices to government systems for tax compliance and regulatory reporting |
| Soft Delete | Marking records as deleted without physical removal, preserves audit trail and historical data |
| RLS (Row-Level Security) | Database security policy filtering data access based on user context, enforces tenant isolation |
| Snowflake ID | Distributed unique identifier generation algorithm producing time-sortable IDs |
| Net Price | Price excluding VAT |
| Gross Price | Price including VAT |
| Payment State | Current status of invoice payment including payd flag, payment date, and method used |
| Hidden Insurance | Special flag and value for insurance charges not displayed on invoice customer view but included in calculations |
| Multi-Tenant Architecture | System design where single instance serves multiple independent tenants with complete data isolation |
Open Questions
- Baseline metrics for invoice creation time and payment reconciliation rate?
- Integration priority: Electronic billing vs. Payment reconciliation vs. Multi-language?
- Should invoice history be tracked for audit purposes?
- Acceptable fallback UX when electronic billing API unavailable?
- Document retention policy for invoices and related attachments?