Billing & Invoices

1. Real-Time Billing Flow

When each call ends, Wholesale automatically:

Call Ends
  │
  ▼
Calculate Charge (sell price)
  │
  ├── Write to wholesale_cdrs
  ├── Deduct tenant balance (SQL: balance = balance - price)
  ├── Report to circuit breaker (success/failure)
  ├── Record sliding window event (ASR/ACD)
  └── Report Prometheus metrics

1.1 CDR Fields

FieldDescription
call_idSIP Call-ID
tenant_idTenant ID
trunk_idTrunk used
caller / calleeCaller / Callee
call_start / call_endStart/end time
ring_durationRing duration
talk_durationTalk duration
billable_durationBillable duration
sell_rate / sell_priceSell rate / sell price
buy_rate / buy_priceBuy rate / buy price
profitProfit
sip_codeFinal SIP status code
answeredWhether answered

2. CDR Query

Wholesale → CDR Management:

Supported filters:

  • Time range
  • Tenant
  • Trunk
  • Caller / Callee
  • Answered / Unanswered
  • SIP status code

2.1 CDR Export

MethodDescription
Sync ExportInstant CSV download (small datasets)
Async ExportBackground task, generates gzip CSV (large datasets)

Async export flow:

  1. Create an export task (wholesale_export_tasks table)
  2. Background worker streams gzip CSV generation
  3. Download from the Export Tasks list when complete

2.2 CDR Recalculation (Rebill)

CDR Management → Rebill: Recalculate historical CDRs after modifying rates.

  • Filter by time range and tenant
  • Recalculate using current rate decks
  • Update CDRs and tenant balances

3. Billing Cycles

3.1 Configuration

Tenant Details → Billing Settings:

FieldDescription
Cycle TypeWeekly / Monthly
Settlement DateDay of month / day of week
Auto ArchiveWhether to auto-archive settled CDRs

3.2 Invoice Generation

A background task checks hourly:

  1. Finds billing cycles due for settlement
  2. Aggregates CDRs within the cycle
  3. Generates wholesale_bills records:
    • Total amount, call count, ASR, total duration
    • Bill status: draft → confirmed → paid

3.3 Invoice Operations

OperationDescription
ViewInvoice details (aggregated by trunk/date)
PrintGenerate HTML invoice page
DownloadExport CSV
ConfirmMark as confirmed
DeleteDelete draft invoices

4. Top-Up & Balance Management

Tenant Details → Top Up:

  • Amount
  • Payment proof image (uploaded to local server or S3)
  • System logs to rustpbx_recharge_logs

Tenant Details → Generate Invoice:

  • Manually trigger invoice generation for the current period

5. Database Requirements

Wholesale billing involves significant concurrent writes. Database requirements:

ItemMySQLPostgreSQL
Transaction IsolationREAD COMMITTEDREAD COMMITTED
Connection Pool10-20 connections per nodeSame
IndexesAuto-created by migrationsSame
CDR PartitioningRecommended monthly (manual)Recommended monthly (manual)

CDR Data Growth Estimate:

  • 1 CDR per call ≈ 1KB
  • 100K calls/day ≈ 100MB/day ≈ 3GB/month
  • Recommend monthly partitioning or periodic archiving for the wholesale_cdrs table