Skip to main content

Credits

The credit system allows adding balance to a customer's account that is automatically applied to future invoices.

Credit Types

TypeDescription
promotionalPromotional credits (may expire)
adjustmentAdministrative balance adjustments
refundCredit generated from a refund
manualManual credit addition

Credit Fields

FieldDescription
Billing accountCustomer receiving the credit
CompanyIssuing company (for application scoping)
TypeCredit type
Amount (cents)Total credit amount
Amount remainingUnused balance
DescriptionReason or description of the credit
Expires atExpiration date (null = never expires)

Automatic Credit Application

When an invoice is finalized, the system automatically applies credits using the FIFO strategy:

Application Order

  1. Credits expiring soonest (priority to avoid loss)
  2. Oldest credits (when expiration dates are equal)

Company Scoping Rules

  • If the invoice has a company: applies credits from the same company and credits without a company
  • If the invoice has no company: applies only credits without a company

Process (in atomic transaction)

  1. Fetches unexpired credits with available balance
  2. For each credit: applies the minimum of (credit balance, invoice remaining amount)
  3. Creates a CreditApplication record for traceability
  4. Updates the credit and invoice balances
  5. If the invoice is fully paid: marks it as paid
  6. Updates the billing account's balanceCents

Credit Restoration

When an invoice is voided, all applied credits are restored:

  • Each credit has its remaining balance increased
  • The CreditApplication records are removed
  • The invoice returns to open status
  • The billing account balance is updated

Credit Expiration

Credits with an expiration date are automatically zeroed out when the date passes:

  • The amountRemaining is set to 0
  • The billing account balance is reduced

Operations

  • Add credit: Creates a credit and increments the account balance
  • Adjust balance: Adds or subtracts credits
  • Refund credit: Creates a credit of type refund
  • Promotional credit: Creates a credit with optional expiration
  • Delete credit: Only if never used (remaining balance = total amount)
  • Check available balance: Returns total available, active credits, and expiring credits