Skip to content

Invoice Management

Document Information

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:

ChallengeBusiness ImpactCurrent State
Manual Invoice Creation15-30 minutes per invoice, prone to errorsOperators manually create invoices from orders
Payment TrackingRevenue reconciliation delays, cash flow visibility gapsPayment status tracked separately from invoices
Compliance RiskRegulatory fines for missing or incorrect invoicesNo automated electronic billing submission
Customer ExperienceDelayed invoice delivery, language barriersManual PDF generation, single language
Financial ReportingIncomplete revenue visibility, audit trail gapsInvoices not consistently linked to orders/payments

Business Value

Value AreaMeasurable OutcomeTargetMeasurement Method
Operational EfficiencyReduce invoice creation time from orders80% reduction (15 min → 3 min)Time tracking: manual vs. automated creation
Payment ReconciliationImprove payment tracking accuracy100% invoices linked to paymentsDatabase audit: invoice-payment associations
ComplianceElectronic billing submission rate95%+ of eligible invoices submittedElectronic billing status tracking
Customer SatisfactionMulti-language invoice availability100% invoices in customer languageLanguage selection analytics
Financial VisibilityComplete invoice-to-order linkage100% invoices traceable to ordersOrder-invoice association audit
Revenue AccuracyEliminate calculation errorsZero manual calculation errorsInvoice total calculation validation

Success Metrics

MetricDefinitionBaselineTargetMeasurement MethodTimeframe
Invoice Creation TimeTime from order completion to invoice generation15-30 minutes (manual)< 3 minutesSystem timestamps on invoice creation workflow3 months
Payment Reconciliation RateInvoices with linked payment records / Total invoicesEstimate: 70%95%+Database query: invoice-payment associations6 months
Electronic Billing SubmissionInvoices successfully submitted / Eligible invoicesEstimate: 60%95%+Electronic billing status tracking6 months
Multi-Language UsageNon-default language invoices / Total invoicesEstimate: 20%> 50% in eligible marketsLanguage selection tracking6 months
Calculation AccuracyInvoices with correct totals / Total invoicesEstimate: 95%99.9%+Automated calculation validationOngoing
Invoice Search PerformanceTime to retrieve filtered invoice resultsN/A< 500ms (p95)Application monitoringOngoing
Customer Invoice AccessCustomers viewing/downloading invoices / Total invoicesN/A> 60% view rateCustomer portal analytics6 months

Baseline Collection: 30-day pre-implementation measurement using current manual process tracking.


Target Users

User RoleBusiness ContextPrimary Goals
AdminFinancial managers overseeing invoicing operationsFull invoice management, compliance oversight, financial reporting
OperatorFrontline staff handling daily invoice operationsCreate invoices from orders, update payment status, generate PDFs
ClientRental customers receiving invoicesView and download invoices for their orders, track payment status
PartnerMarketplace vehicle ownersView 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 IDRequirementBusiness Outcome
FR-01Store invoices with fields: id, series, number, date, customerId, companyId, items, state, deleted, discount, discountUnit, electronicBillingId, electronicBillingStatus, type, language, paymentMethod, tenantIdComplete invoice data for financial documentation
FR-02Support invoice types: Invoice, Credit Note, ProformaFlexible invoice types for different business scenarios
FR-03Support discount units: PERCENT, AMOUNTFlexible discount application methods
FR-04Support electronic billing statuses: INVI (invalid), ERRO (error), CONS (completed), NONC (not completed)Track regulatory submission status
FR-05Store invoice line items as JSON array with fields: number, code, description, quantity, price, netPrice, vatDetailed line item tracking for audit
FR-06Store invoice state as JSON with fields: payd (boolean), paymentDate, paymentMethod, statusComplete payment tracking
FR-07Store payment method details as JSON with fields: method, name, bank, account, cif, iban, swift, addressComplete payment information for reconciliation
FR-08Support hidden insurance flag and value for special pricing scenariosFlexible pricing for insurance charges

FR-2: Invoice Series Management

Req IDRequirementBusiness Outcome
FR-09Maintain separate invoices_series table with fields: id, series, tenantId, createdAt, updatedAtOrganized invoice numbering per business unit
FR-10Enforce unique series per tenant using compound unique constraint (series, tenantId)Prevent series conflicts across tenants
FR-11Automatically create new series when invoice is created with non-existent seriesSeamless series creation workflow
FR-12Provide query for last invoice number in a series for continuityMaintain sequential numbering
FR-13Allow multiple companies within same tenant to share or use different seriesFlexible series organization

FR-3: Invoice Creation

Req IDRequirementBusiness Outcome
FR-14Create invoices via GraphQL mutation with input: customer, company, series, number, date, type, language, items, state, paymentMethod, discount, discountUnitProgrammatic invoice creation
FR-15Validate customer exists (Client or Partner) before creating invoiceData integrity enforcement
FR-16Validate company exists before creating invoiceData integrity enforcement
FR-17Automatically create invoice series if it doesn’t exist during invoice creationSeamless workflow
FR-18Set deleted flag to false by default for new invoicesProper default state
FR-19Generate snowflake ID for new invoicesUnique identifier generation
FR-20Index invoices to search system for quick retrieval by number, customer name, company nameFast invoice search
FR-21Support creating invoices from completed orders with automatic line item populationAutomated invoice generation
FR-22Default invoice language to tenant language if not specifiedProper language defaults

FR-4: Invoice Modification

Req IDRequirementBusiness Outcome
FR-23Update invoices via GraphQL mutation with fields: id, series, number, date, type, language, customer, company, items, state, paymentMethod, discount, discountUnit, deletedFlexible invoice updates
FR-24Allow updating invoice series with automatic series creation if new series doesn’t existSeries flexibility
FR-25Allow marking invoices as deleted without physical deletion for audit trailsAudit trail preservation
FR-26Allow updating payment status including payd flag, paymentDate, and paymentMethodPayment tracking
FR-27Recalculate invoice totals when items or discount is modifiedAccurate calculations

FR-5: Invoice Retrieval

Req IDRequirementBusiness Outcome
FR-28Retrieve invoices filtered by date range (from/to)Time-based filtering
FR-29Exclude deleted invoices from default queries unless explicitly requestedClean default views
FR-30Support full-text search on invoice number, customer name, company nameFast invoice discovery
FR-31Return invoices with pagination support (first, after cursor)Scalable query results
FR-32Retrieve single invoice by ID with all related dataComplete invoice details
FR-33Support fetching invoices by multiple IDs for batch operationsEfficient batch processing
FR-34Format invoice dates as ISO strings for GraphQL responsesStandard date formatting

FR-6: Invoice Calculations

Req IDRequirementBusiness Outcome
FR-35Calculate line item totals: netPrice = price * quantityAccurate line item totals
FR-36Calculate VAT amounts per line item: vatAmount = netPrice * (vat / 100)Accurate VAT calculation
FR-37Calculate invoice subtotal as sum of all line item netPricesAccurate subtotal
FR-38Apply discount to subtotal based on discountUnit (PERCENT or AMOUNT)Accurate discount application
FR-39Calculate invoice total with discount: total = subtotal - discountAmountAccurate final total
FR-40Calculate total VAT as sum of all line item VAT amountsAccurate VAT total

FR-7: Electronic Billing Integration

Req IDRequirementBusiness Outcome
FR-41Store electronic billing ID for invoices submitted to e-billing systemsTrack submission status
FR-42Track electronic billing status: INVI, ERRO, CONS, NONCMonitor compliance status
FR-43Provide mutation to submit invoices to electronic billing systemAutomated compliance
FR-44Update electronic billing status based on submission resultsStatus tracking
FR-45Allow filtering invoices by electronic billing statusCompliance monitoring

FR-8: Payment Integration

Req IDRequirementBusiness Outcome
FR-46Link invoices to payment records for reconciliationComplete financial tracking
FR-47Track payment status in invoice state (payd flag)Payment visibility
FR-48Record payment date when invoice is marked as paidPayment history
FR-49Support multiple payment method types in invoice paymentMethod fieldFlexible payment methods
FR-50Collect analytics when invoices are created including amount, payment method, currencyBusiness intelligence

FR-9: Access Control

Req IDRequirementBusiness Outcome
FR-51Enforce row-level security (RLS) based on tenantIdMulti-tenant isolation
FR-52Restrict invoice access to users within same tenantSecurity enforcement
FR-53Allow admins to view all invoices in their tenantAdministrative oversight
FR-54Allow operators to create and modify invoicesOperational access
FR-55Allow clients to view only their own invoicesCustomer privacy
FR-56Allow partners to view invoices related to their vehiclesPartner access
FR-57Restrict Partner/Driver roles to “No access” for invoicesRole-based restrictions
FR-58Distinguish between “View only” vs “Full access” permissionsGranular 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 IDRuleRationale
BR-01Invoice numbers must be sequential per seriesMaintain audit trail and numbering continuity
BR-02Series and tenant combination must be uniquePrevent conflicts in multi-tenant environment
BR-03Invoice numbers can contain alphanumeric charactersSupport flexible numbering schemes
BR-04Invoice type determines template and legal requirementsDifferent types have different compliance needs
BR-05PERCENT discount: discountAmount = subtotal * (discount / 100)Standard percentage calculation
BR-06AMOUNT discount: discountAmount = discountFixed amount discount
BR-07Discount cannot exceed subtotalPrevent negative totals
BR-08VAT is calculated per line item based on item vat rateAccurate tax calculation
BR-09Total VAT is sum of all line item VAT amountsComplete VAT reporting
BR-10All invoices must have tenantIdMulti-tenant isolation requirement
BR-11Queries filter by tenantId automatically via RLSSecurity enforcement
BR-12Invoices must be linked to either Client or PartnerCustomer association requirement
BR-13Customer can be changed on edit (not fixed after creation)Flexibility for corrections
BR-14Deleted invoices remain in database with deleted=trueAudit trail preservation
BR-15Default queries exclude deleted invoicesClean default views
BR-16Invoice language determines PDF template languageMulti-language support
BR-17Language defaults to customer’s preferred languageCustomer experience
BR-18Electronic billing status: INVI (invalid), ERRO (error), CONS (completed), NONC (not completed)Compliance tracking

Dependencies

Upstream Dependencies

SystemDependencyImpact if Unavailable
Customer ManagementClients and partners tables for customer associationCannot create invoices without customer
Company ManagementCompanies table for company associationCannot create invoices without company
Order SystemOrder data for automatic invoice generationManual invoice creation only
Payment ProcessingPayment records for reconciliationPayment status tracking unavailable
PDF GenerationInvoice PDF renderingCannot generate invoice PDFs
Search SystemInvoice indexing for quick retrievalSearch unavailable, manual filtering only
AnalyticsInvoice creation event trackingBusiness intelligence unavailable

Downstream Dependencies

Dependent SystemIntegration PointValue Delivered
Financial ReportingInvoice data aggregationRevenue and payment reporting
Customer PortalInvoice viewing and downloadCustomer self-service
Electronic Billing SystemsInvoice submission APIRegulatory compliance
Payment ReconciliationInvoice-payment linkingFinancial accuracy

External Dependencies

SystemPurpose
Prisma ORMData access layer for invoice storage
GraphQLAPI layer for invoice mutations and queries
Fauna/PostgreSQLDatabase storage (dual-write during migration)
Upstash/AlgoliaSearch index for invoice queries
Electronic Billing APIsThird-party integrations for regulatory submission

Non-Functional Requirements

CategoryRequirementTarget
PerformanceInvoice creation time< 3 minutes (from order)
PerformanceInvoice search response< 500ms (p95)
PerformancePDF generation time< 10 seconds
AvailabilityInvoice service uptime99.5%
ScalabilityConcurrent invoice operations100+ simultaneous users
Data QualityCalculation accuracy99.9%+
SecurityTenant isolation100% query isolation
ComplianceElectronic billing submission rate95%+ of eligible invoices

Glossary

TermDefinition
InvoiceLegal document recording sale of goods or services, includes line items, customer, company, totals, and payment terms
Proforma InvoicePreliminary invoice or quote sent before goods/services are delivered, not legally binding for accounting purposes
Credit NoteDocument representing refund or credit adjustment to an original invoice
Invoice SeriesNamed sequence for organizing invoices, typically with prefix like “INV2024-” or “PRO-”, unique per tenant
Line ItemIndividual 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 UnitMethod of discount calculation - PERCENT applies percentage reduction, AMOUNT applies fixed amount reduction
Electronic BillingAutomated submission of invoices to government systems for tax compliance and regulatory reporting
Soft DeleteMarking 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 IDDistributed unique identifier generation algorithm producing time-sortable IDs
Net PricePrice excluding VAT
Gross PricePrice including VAT
Payment StateCurrent status of invoice payment including payd flag, payment date, and method used
Hidden InsuranceSpecial flag and value for insurance charges not displayed on invoice customer view but included in calculations
Multi-Tenant ArchitectureSystem design where single instance serves multiple independent tenants with complete data isolation

Open Questions

  1. Baseline metrics for invoice creation time and payment reconciliation rate?
  2. Integration priority: Electronic billing vs. Payment reconciliation vs. Multi-language?
  3. Should invoice history be tracked for audit purposes?
  4. Acceptable fallback UX when electronic billing API unavailable?
  5. Document retention policy for invoices and related attachments?