Cost Model Documentation
Overview​
The Cost model provides dynamic pricing management and billing report generation for the CODITECT platform. It supports tiered pricing structures, multi-currency billing, and comprehensive cost breakdowns. The model enables accurate cost calculation based on usage volumes and generates detailed billing reports for transparency and financial planning.
Model Structure​
CostModel - Pricing Configuration​
Core Fields​
| Field | Type | Description | Constraints |
|---|---|---|---|
cost_model_id | UUID | Unique pricing model identifier | Primary key, auto-generated |
provider | String | Service provider name | Required (e.g., "anthropic", "google") |
resource_type | ResourceType | Type of resource being priced | Foreign key to Usage |
pricing_tiers | Vec | Volume-based pricing tiers | Required, at least one tier |
effective_date | DateTime | When pricing takes effect | Required, auto-set to now |
expires_date | DateTime | When pricing expires | For limited-time pricing |
PricingTier Structure​
| Field | Type | Description | Example |
|---|---|---|---|
min_quantity | f64 | Minimum quantity for tier | 0.0 |
max_quantity | f64 (Optional) | Maximum quantity for tier | 1,000,000.0 |
price_per_unit | f64 | Unit price in this tier | 0.000008 |
currency | String | Currency code | "USD" |
BillingReport - Monthly Billing​
Core Fields​
| Field | Type | Description | Constraints |
|---|---|---|---|
report_id | UUID | Unique report identifier | Primary key, auto-generated |
tenant_id | UUID | Tenant being billed | Foreign key to Tenant |
start_date | DateTime | Billing period start | Required |
end_date | DateTime | Billing period end | Required |
total_cost | f64 | Total amount due | Auto-calculated |
currency | String | Billing currency | Required |
cost_breakdown | Vec | Detailed line items | Auto-populated |
generated_at | DateTime | Report generation time | Auto-set |
CostBreakdown Structure​
| Field | Type | Description |
|---|---|---|
service_type | String | Category of service |
resource_type | String | Specific resource |
quantity | f64 | Amount consumed |
unit | String | Unit of measurement |
unit_cost | f64 | Price per unit |
total_cost | f64 | Line item total |
percentage_of_total | f64 | % of total bill |
AggregationLevel Enum​
enum AggregationLevel {
Service, // By service type
Resource, // By resource type
User, // By user
Day, // Daily aggregation
Hour // Hourly aggregation
}
Pricing Examples​
Tiered AI Token Pricing​
{
"cost_model_id": "550e8400-e29b-41d4-a716-446655440000",
"provider": "anthropic",
"resource_type": "ClaudeInputTokens",
"pricing_tiers": [
{
"min_quantity": 0.0,
"max_quantity": 1000000.0,
"price_per_unit": 0.000015,
"currency": "USD"
},
{
"min_quantity": 1000000.0,
"max_quantity": 10000000.0,
"price_per_unit": 0.000012,
"currency": "USD"
},
{
"min_quantity": 10000000.0,
"max_quantity": null,
"price_per_unit": 0.00001,
"currency": "USD"
}
],
"effective_date": "2025-08-01T00:00:00Z",
"expires_date": null
}
Compute Pricing Model​
{
"cost_model_id": "660e8400-e29b-41d4-a716-446655440000",
"provider": "gcp",
"resource_type": "CloudRunCpu",
"pricing_tiers": [
{
"min_quantity": 0.0,
"max_quantity": 1000.0,
"price_per_unit": 0.024,
"currency": "USD"
},
{
"min_quantity": 1000.0,
"max_quantity": null,
"price_per_unit": 0.020,
"currency": "USD"
}
],
"effective_date": "2025-08-01T00:00:00Z",
"expires_date": null
}
Billing Report Example​
Monthly Report​
{
"report_id": "770e8400-e29b-41d4-a716-446655440000",
"tenant_id": "123e4567-e89b-12d3-a456-426614174000",
"start_date": "2025-08-01T00:00:00Z",
"end_date": "2025-08-31T23:59:59Z",
"total_cost": 1247.85,
"currency": "USD",
"cost_breakdown": [
{
"service_type": "AI",
"resource_type": "ClaudeInputTokens",
"quantity": 45000000.0,
"unit": "tokens",
"unit_cost": 0.00001,
"total_cost": 450.00,
"percentage_of_total": 36.05
},
{
"service_type": "AI",
"resource_type": "ClaudeOutputTokens",
"quantity": 15000000.0,
"unit": "tokens",
"unit_cost": 0.00005,
"total_cost": 750.00,
"percentage_of_total": 60.12
},
{
"service_type": "Compute",
"resource_type": "CloudRunCpu",
"quantity": 1500.0,
"unit": "vCPU-hours",
"unit_cost": 0.020,
"total_cost": 30.00,
"percentage_of_total": 2.40
},
{
"service_type": "Storage",
"resource_type": "GcsStorage",
"quantity": 892.5,
"unit": "GB-months",
"unit_cost": 0.02,
"total_cost": 17.85,
"percentage_of_total": 1.43
}
],
"generated_at": "2025-09-01T00:05:00Z"
}
Database Schema​
Primary Storage Patterns​
# Cost models by provider and resource
Key: /cost_models/{provider}/{resource_type}/{effective_date}
Value: JSON serialized CostModel
# Active cost models
Key: /active_cost_models/{provider}/{resource_type}
Value: cost_model_id
# Billing reports
Key: /{tenant_id}/billing_reports/{YYYY-MM}/{report_id}
Value: JSON serialized BillingReport
# Historical pricing
Key: /cost_model_history/{provider}/{resource_type}/{effective_date}
Value: JSON serialized CostModel
Secondary Indexes​
# Reports by status
/billing_reports_by_status/{status} -> [report_ids]
# Reports by amount
/billing_reports_by_amount/{YYYY}/{amount_range} -> [report_ids]
# Overdue reports
/overdue_billing_reports -> [report_ids]
Cost Calculation​
Tiered Pricing Logic​
impl CostModel {
pub fn calculate_cost(&self, quantity: f64) -> Option<f64> {
// For simple tiered pricing (entire quantity at tier rate)
for tier in &self.pricing_tiers {
if quantity >= tier.min_quantity &&
tier.max_quantity.map_or(true, |max| quantity <= max) {
return Some(quantity * tier.price_per_unit);
}
}
None
}
pub fn calculate_cost_graduated(&self, quantity: f64) -> f64 {
// For graduated pricing (each tier gets its rate)
let mut total_cost = 0.0;
let mut remaining = quantity;
for tier in &self.pricing_tiers {
let tier_max = tier.max_quantity.unwrap_or(f64::MAX);
let tier_quantity = (tier_max - tier.min_quantity).min(remaining);
if tier_quantity > 0.0 {
total_cost += tier_quantity * tier.price_per_unit;
remaining -= tier_quantity;
}
if remaining <= 0.0 {
break;
}
}
total_cost
}
}
Volume Discounts​
struct VolumeDiscount {
threshold: f64,
discount_percent: f64,
applicable_to: Vec<ResourceType>
}
// Apply volume discount
let base_cost = cost_model.calculate_cost(quantity)?;
let discount = get_applicable_discount(resource_type, quantity);
let final_cost = base_cost * (1.0 - discount.discount_percent / 100.0);
Related Code​
Source Files​
- Models:
/src/models/cost.rs- Cost model definitions/src/models/usage.rs- ResourceType enum
- Services:
/src/services/pricing_service.rs- Pricing calculations/src/services/billing_service.rs- Report generation
- Repositories:
/src/db/repositories/cost_repository.rs/src/db/repositories/billing_repository.rs
- API Handlers:
/src/api/handlers/billing_handlers.rs
- Tests:
/src/models/tests/cost_tests.rs
Key Methods​
impl CostModel {
fn new(provider: String, resource_type: ResourceType, pricing_tiers: Vec<PricingTier>) -> Self
fn calculate_cost(&self, quantity: f64) -> Option<f64>
fn get_unit_price(&self, quantity: f64) -> Option<f64>
fn is_active(&self) -> bool
}
impl BillingReport {
fn new(tenant_id: Uuid, start_date: DateTime<Utc>, end_date: DateTime<Utc>, currency: String) -> Self
fn add_cost_item(&mut self, breakdown: CostBreakdown)
fn recalculate_percentages(&mut self)
fn apply_credits(&mut self, credits: Vec<Credit>)
fn finalize(&mut self) -> Result<()>
}
API Endpoints​
Pricing Management​
- GET
/api/pricing- Get current pricing - GET
/api/pricing/{provider}/{resource}- Get specific pricing - POST
/api/admin/pricing- Create new pricing model - PUT
/api/admin/pricing/{cost_model_id}- Update pricing
Billing Reports​
- GET
/api/billing/current- Current month's usage - GET
/api/billing/reports- List billing reports - GET
/api/billing/reports/{report_id}- Get specific report - POST
/api/billing/reports/generate- Generate ad-hoc report
Cost Estimation​
- POST
/api/billing/estimate- Estimate costs - GET
/api/billing/calculator- Interactive calculator - GET
/api/billing/forecast- Cost forecasting
Pricing Strategies​
Standard Pricing Tiers​
- Free Tier: First N units free
- Standard Tier: Regular pricing
- Volume Tier: Discounted bulk rates
- Enterprise Tier: Negotiated rates
Special Pricing Models​
- Committed Use: Pre-purchase discounts
- Spot Pricing: Variable market rates
- Reserved Capacity: Guaranteed availability
- Pay-as-you-go: Standard on-demand
Billing Workflows​
Monthly Billing Cycle​
Day 1-25: Usage accumulation
Day 26: Usage forecast email
Day 28: Final usage warning
Day 30: Generate billing report
Day 31: Send invoice
Day 1 (next): Payment processing
Day 5: Late payment reminder
Day 10: Service suspension warning
Report Generation Process​
- Aggregate usage data by service/resource
- Apply current pricing models
- Calculate tiered pricing
- Apply discounts/credits
- Generate line items
- Calculate taxes if applicable
- Create PDF invoice
- Send notifications
Cost Optimization​
Recommendations Engine​
struct CostOptimization {
resource_type: ResourceType,
current_usage: f64,
current_cost: f64,
recommended_action: String,
potential_savings: f64
}
// Example recommendations
- Switch to volume pricing tier
- Use reserved capacity
- Optimize resource usage patterns
- Consolidate similar workloads
Budget Alerts​
struct BudgetAlert {
tenant_id: Uuid,
budget_amount: f64,
period: BudgetPeriod,
alert_thresholds: Vec<f64>, // e.g., [50.0, 80.0, 100.0]
notification_channels: Vec<NotificationChannel>
}
Financial Integration​
Invoice Structure​
struct Invoice {
invoice_number: String,
billing_report: BillingReport,
tax_details: Option<TaxDetails>,
payment_terms: PaymentTerms,
due_date: DateTime<Utc>,
status: InvoiceStatus
}
enum InvoiceStatus {
Draft,
Sent,
Paid,
Overdue,
Disputed,
Cancelled
}
Payment Processing​
- Credit card auto-charge
- ACH bank transfers
- Wire transfers
- Purchase orders
- Credits and adjustments
Compliance & Audit​
Audit Requirements​
- Immutable billing records
- Complete pricing history
- Usage-to-cost traceability
- Adjustment audit trail
Data Retention​
- Cost models: Permanent
- Billing reports: 7 years
- Usage data: 90 days detailed, 7 years aggregated
- Payment records: 7 years
Performance Considerations​
Caching Strategy​
- Cache active pricing models
- Pre-calculate common quantities
- Store monthly aggregates
- Materialized report views
Optimization​
- Batch cost calculations
- Async report generation
- Compress historical data
- Archive old reports
Future Enhancements​
Advanced Features​
- Multi-currency Support: Real-time exchange rates
- Tax Integration: Automated tax calculation
- Cost Allocation: Department/project charging
- Marketplace Billing: Third-party service integration
Analytics Improvements​
- Cost Trends: Historical analysis
- Anomaly Detection: Unusual spending alerts
- What-if Analysis: Pricing scenario modeling
- ROI Calculations: Value metrics
Automation​
- Auto-scaling Budgets: Dynamic budget adjustment
- Smart Credits: Automatic credit application
- Dispute Resolution: Automated handling
- Collection Automation: Dunning management
Last Updated: 2025-08-29 Version: 1.0