curl -X GET "https://api.tensorone.ai/v2/billing/credits" \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
-d "status[]=active&status[]=pending" \
-d "includeUsageHistory=true" \
-d "dateRange=current_year"
{
"credits": [
{
"creditId": "cred_promo_001",
"type": "promotional",
"status": "active",
"amount": {
"original": 500.00,
"remaining": 325.50,
"used": 174.50,
"currency": "USD"
},
"source": {
"description": "Welcome Bonus - New Account",
"referenceId": "promo_welcome_2024",
"issuedBy": "marketing_system",
"reason": "New account signup promotion"
},
"dates": {
"issued": "2024-01-15T10:00:00Z",
"activated": "2024-01-15T10:00:00Z",
"expires": "2024-04-15T23:59:59Z",
"lastUsed": "2024-01-20T14:30:00Z"
},
"restrictions": {
"applicableServices": ["clusters", "ai-services"],
"minimumSpend": 0,
"maximumDiscount": null,
"usageLimit": "unlimited",
"accountRestrictions": []
},
"usage": [
{
"appliedAt": "2024-01-20T14:30:00Z",
"amount": 124.50,
"invoiceId": "inv_2024_01_001",
"description": "Applied to GPU cluster usage"
},
{
"appliedAt": "2024-01-18T09:15:00Z",
"amount": 50.00,
"invoiceId": "inv_2024_01_002",
"description": "Applied to AI services"
}
],
"metadata": {
"campaignId": "welcome_2024_q1",
"tags": ["new_customer", "welcome"],
"notes": "Automatically applied welcome bonus",
"transferable": false
}
},
{
"creditId": "cred_refund_002",
"type": "refund",
"status": "active",
"amount": {
"original": 200.00,
"remaining": 200.00,
"used": 0.00,
"currency": "USD"
},
"source": {
"description": "Refund for Service Downtime",
"referenceId": "incident_2024_01_10",
"issuedBy": "support_team",
"reason": "Compensation for service interruption"
},
"dates": {
"issued": "2024-01-12T16:45:00Z",
"activated": "2024-01-12T16:45:00Z",
"expires": null,
"lastUsed": null
},
"restrictions": {
"applicableServices": ["all"],
"minimumSpend": 0,
"maximumDiscount": null,
"usageLimit": "one_time",
"accountRestrictions": []
},
"usage": [],
"metadata": {
"campaignId": null,
"tags": ["refund", "service_credit"],
"notes": "Issued for service downtime on 2024-01-10",
"transferable": false
}
},
{
"creditId": "cred_referral_003",
"type": "referral",
"status": "pending",
"amount": {
"original": 100.00,
"remaining": 100.00,
"used": 0.00,
"currency": "USD"
},
"source": {
"description": "Referral Bonus - Friend Signup",
"referenceId": "ref_user_abc123",
"issuedBy": "referral_system",
"reason": "Friend completed first purchase"
},
"dates": {
"issued": "2024-01-22T12:00:00Z",
"activated": null,
"expires": "2024-07-22T23:59:59Z",
"lastUsed": null
},
"restrictions": {
"applicableServices": ["all"],
"minimumSpend": 50.00,
"maximumDiscount": null,
"usageLimit": "unlimited",
"accountRestrictions": []
},
"usage": [],
"metadata": {
"campaignId": "referral_2024",
"tags": ["referral", "friend_bonus"],
"notes": "Pending activation until minimum spend requirement met",
"transferable": false
}
}
],
"summary": {
"totalCredits": 625.50,
"totalUsed": 174.50,
"byType": {
"promotional": {
"amount": 325.50,
"count": 1
},
"refund": {
"amount": 200.00,
"count": 1
},
"referral": {
"amount": 100.00,
"count": 1
}
},
"byStatus": {
"active": {
"amount": 525.50,
"count": 2
},
"pending": {
"amount": 100.00,
"count": 1
}
},
"expiringWithin30Days": 0.00,
"currency": "USD"
},
"recommendations": [
{
"type": "expiration_warning",
"priority": "medium",
"title": "Use Promotional Credit Before Expiration",
"description": "Your welcome bonus credit of $325.50 will expire on April 15, 2024. Consider using it for upcoming GPU cluster or AI service usage.",
"potentialSavings": 325.50
},
{
"type": "unused_credit",
"priority": "low",
"title": "Apply Refund Credit to Outstanding Invoices",
"description": "You have $200.00 in refund credits that can be applied to any service. Consider applying to reduce your next invoice.",
"potentialSavings": 200.00
}
]
}
Manage account credits, promotional credits, refunds, and credit-based payments for your TensorOne account
curl -X GET "https://api.tensorone.ai/v2/billing/credits" \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
-d "status[]=active&status[]=pending" \
-d "includeUsageHistory=true" \
-d "dateRange=current_year"
{
"credits": [
{
"creditId": "cred_promo_001",
"type": "promotional",
"status": "active",
"amount": {
"original": 500.00,
"remaining": 325.50,
"used": 174.50,
"currency": "USD"
},
"source": {
"description": "Welcome Bonus - New Account",
"referenceId": "promo_welcome_2024",
"issuedBy": "marketing_system",
"reason": "New account signup promotion"
},
"dates": {
"issued": "2024-01-15T10:00:00Z",
"activated": "2024-01-15T10:00:00Z",
"expires": "2024-04-15T23:59:59Z",
"lastUsed": "2024-01-20T14:30:00Z"
},
"restrictions": {
"applicableServices": ["clusters", "ai-services"],
"minimumSpend": 0,
"maximumDiscount": null,
"usageLimit": "unlimited",
"accountRestrictions": []
},
"usage": [
{
"appliedAt": "2024-01-20T14:30:00Z",
"amount": 124.50,
"invoiceId": "inv_2024_01_001",
"description": "Applied to GPU cluster usage"
},
{
"appliedAt": "2024-01-18T09:15:00Z",
"amount": 50.00,
"invoiceId": "inv_2024_01_002",
"description": "Applied to AI services"
}
],
"metadata": {
"campaignId": "welcome_2024_q1",
"tags": ["new_customer", "welcome"],
"notes": "Automatically applied welcome bonus",
"transferable": false
}
},
{
"creditId": "cred_refund_002",
"type": "refund",
"status": "active",
"amount": {
"original": 200.00,
"remaining": 200.00,
"used": 0.00,
"currency": "USD"
},
"source": {
"description": "Refund for Service Downtime",
"referenceId": "incident_2024_01_10",
"issuedBy": "support_team",
"reason": "Compensation for service interruption"
},
"dates": {
"issued": "2024-01-12T16:45:00Z",
"activated": "2024-01-12T16:45:00Z",
"expires": null,
"lastUsed": null
},
"restrictions": {
"applicableServices": ["all"],
"minimumSpend": 0,
"maximumDiscount": null,
"usageLimit": "one_time",
"accountRestrictions": []
},
"usage": [],
"metadata": {
"campaignId": null,
"tags": ["refund", "service_credit"],
"notes": "Issued for service downtime on 2024-01-10",
"transferable": false
}
},
{
"creditId": "cred_referral_003",
"type": "referral",
"status": "pending",
"amount": {
"original": 100.00,
"remaining": 100.00,
"used": 0.00,
"currency": "USD"
},
"source": {
"description": "Referral Bonus - Friend Signup",
"referenceId": "ref_user_abc123",
"issuedBy": "referral_system",
"reason": "Friend completed first purchase"
},
"dates": {
"issued": "2024-01-22T12:00:00Z",
"activated": null,
"expires": "2024-07-22T23:59:59Z",
"lastUsed": null
},
"restrictions": {
"applicableServices": ["all"],
"minimumSpend": 50.00,
"maximumDiscount": null,
"usageLimit": "unlimited",
"accountRestrictions": []
},
"usage": [],
"metadata": {
"campaignId": "referral_2024",
"tags": ["referral", "friend_bonus"],
"notes": "Pending activation until minimum spend requirement met",
"transferable": false
}
}
],
"summary": {
"totalCredits": 625.50,
"totalUsed": 174.50,
"byType": {
"promotional": {
"amount": 325.50,
"count": 1
},
"refund": {
"amount": 200.00,
"count": 1
},
"referral": {
"amount": 100.00,
"count": 1
}
},
"byStatus": {
"active": {
"amount": 525.50,
"count": 2
},
"pending": {
"amount": 100.00,
"count": 1
}
},
"expiringWithin30Days": 0.00,
"currency": "USD"
},
"recommendations": [
{
"type": "expiration_warning",
"priority": "medium",
"title": "Use Promotional Credit Before Expiration",
"description": "Your welcome bonus credit of $325.50 will expire on April 15, 2024. Consider using it for upcoming GPU cluster or AI service usage.",
"potentialSavings": 325.50
},
{
"type": "unused_credit",
"priority": "low",
"title": "Apply Refund Credit to Outstanding Invoices",
"description": "You have $200.00 in refund credits that can be applied to any service. Consider applying to reduce your next invoice.",
"potentialSavings": 200.00
}
]
}
promotional - Marketing and promotional creditsrefund - Credits from refunded paymentsbonus - Bonus credits from programs or achievementspartner - Credits from partner programssupport - Support-issued credits for service issuesreferral - Credits from referral programsmigration - Credits from account migrationsactive - Available for useapplied - Already applied to invoicesexpired - Expired and no longer usablepending - Pending approval or activationreserved - Reserved for specific purposeslast_month - Last 30 dayslast_3_months - Last 3 monthslast_6_months - Last 6 monthscurrent_year - Current calendar yearall - All credit historycustom - Custom date range (requires startDate and endDate)USD, EUR, GBP, JPY, CAD, AUDShow Credit Object
Show Credit Restrictions
curl -X GET "https://api.tensorone.ai/v2/billing/credits" \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
-d "status[]=active&status[]=pending" \
-d "includeUsageHistory=true" \
-d "dateRange=current_year"
{
"credits": [
{
"creditId": "cred_promo_001",
"type": "promotional",
"status": "active",
"amount": {
"original": 500.00,
"remaining": 325.50,
"used": 174.50,
"currency": "USD"
},
"source": {
"description": "Welcome Bonus - New Account",
"referenceId": "promo_welcome_2024",
"issuedBy": "marketing_system",
"reason": "New account signup promotion"
},
"dates": {
"issued": "2024-01-15T10:00:00Z",
"activated": "2024-01-15T10:00:00Z",
"expires": "2024-04-15T23:59:59Z",
"lastUsed": "2024-01-20T14:30:00Z"
},
"restrictions": {
"applicableServices": ["clusters", "ai-services"],
"minimumSpend": 0,
"maximumDiscount": null,
"usageLimit": "unlimited",
"accountRestrictions": []
},
"usage": [
{
"appliedAt": "2024-01-20T14:30:00Z",
"amount": 124.50,
"invoiceId": "inv_2024_01_001",
"description": "Applied to GPU cluster usage"
},
{
"appliedAt": "2024-01-18T09:15:00Z",
"amount": 50.00,
"invoiceId": "inv_2024_01_002",
"description": "Applied to AI services"
}
],
"metadata": {
"campaignId": "welcome_2024_q1",
"tags": ["new_customer", "welcome"],
"notes": "Automatically applied welcome bonus",
"transferable": false
}
},
{
"creditId": "cred_refund_002",
"type": "refund",
"status": "active",
"amount": {
"original": 200.00,
"remaining": 200.00,
"used": 0.00,
"currency": "USD"
},
"source": {
"description": "Refund for Service Downtime",
"referenceId": "incident_2024_01_10",
"issuedBy": "support_team",
"reason": "Compensation for service interruption"
},
"dates": {
"issued": "2024-01-12T16:45:00Z",
"activated": "2024-01-12T16:45:00Z",
"expires": null,
"lastUsed": null
},
"restrictions": {
"applicableServices": ["all"],
"minimumSpend": 0,
"maximumDiscount": null,
"usageLimit": "one_time",
"accountRestrictions": []
},
"usage": [],
"metadata": {
"campaignId": null,
"tags": ["refund", "service_credit"],
"notes": "Issued for service downtime on 2024-01-10",
"transferable": false
}
},
{
"creditId": "cred_referral_003",
"type": "referral",
"status": "pending",
"amount": {
"original": 100.00,
"remaining": 100.00,
"used": 0.00,
"currency": "USD"
},
"source": {
"description": "Referral Bonus - Friend Signup",
"referenceId": "ref_user_abc123",
"issuedBy": "referral_system",
"reason": "Friend completed first purchase"
},
"dates": {
"issued": "2024-01-22T12:00:00Z",
"activated": null,
"expires": "2024-07-22T23:59:59Z",
"lastUsed": null
},
"restrictions": {
"applicableServices": ["all"],
"minimumSpend": 50.00,
"maximumDiscount": null,
"usageLimit": "unlimited",
"accountRestrictions": []
},
"usage": [],
"metadata": {
"campaignId": "referral_2024",
"tags": ["referral", "friend_bonus"],
"notes": "Pending activation until minimum spend requirement met",
"transferable": false
}
}
],
"summary": {
"totalCredits": 625.50,
"totalUsed": 174.50,
"byType": {
"promotional": {
"amount": 325.50,
"count": 1
},
"refund": {
"amount": 200.00,
"count": 1
},
"referral": {
"amount": 100.00,
"count": 1
}
},
"byStatus": {
"active": {
"amount": 525.50,
"count": 2
},
"pending": {
"amount": 100.00,
"count": 1
}
},
"expiringWithin30Days": 0.00,
"currency": "USD"
},
"recommendations": [
{
"type": "expiration_warning",
"priority": "medium",
"title": "Use Promotional Credit Before Expiration",
"description": "Your welcome bonus credit of $325.50 will expire on April 15, 2024. Consider using it for upcoming GPU cluster or AI service usage.",
"potentialSavings": 325.50
},
{
"type": "unused_credit",
"priority": "low",
"title": "Apply Refund Credit to Outstanding Invoices",
"description": "You have $200.00 in refund credits that can be applied to any service. Consider applying to reduce your next invoice.",
"potentialSavings": 200.00
}
]
}
def get_optimal_credit_application(invoice_id):
"""Get optimal credit application strategy for an invoice"""
response = requests.get(
f"https://api.tensorone.ai/v2/billing/credits/optimize/{invoice_id}",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
return response.json()
def bulk_apply_credits():
"""Apply credits optimally to multiple invoices"""
response = requests.post(
"https://api.tensorone.ai/v2/billing/credits/bulk-apply",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json={
"strategy": "minimize_expiration", # or "maximize_savings"
"invoiceTypes": ["pending", "overdue"],
"prioritizeExpiring": True,
"maxAmount": 5000.00
}
)
return response.json()
def apply_credits_with_strategy(strategy="expiring_first"):
"""Apply credits using various strategies"""
print(f"🎯 Applying Credits Strategy: {strategy.replace('_', ' ').title()}")
print("=" * 45)
# Get optimization recommendations
optimization = bulk_apply_credits()
if optimization.get('recommendations'):
total_savings = 0
for rec in optimization['recommendations']:
invoice_id = rec['invoiceId']
credits_to_apply = rec['creditsToApply']
total_credit_amount = sum(c['amount'] for c in credits_to_apply)
print(f"Invoice {rec['invoiceNumber']}: ${rec['invoiceAmount']:,.2f}")
print(f" Recommended credits: ${total_credit_amount:,.2f}")
for credit in credits_to_apply:
credit_desc = credit['description']
credit_amount = credit['amount']
expires = credit.get('expires', 'No expiration')
print(f" • {credit_desc}: ${credit_amount:,.2f} (Expires: {expires})")
total_savings += total_credit_amount
print()
print(f"💰 Total Potential Savings: ${total_savings:,.2f}")
# Apply credits (uncomment to execute)
# for rec in optimization['recommendations']:
# for credit in rec['creditsToApply']:
# result = apply_credit_to_invoice(
# credit['creditId'],
# rec['invoiceId'],
# credit['amount']
# )
# if result.get('success'):
# print(f"✅ Applied {credit['description']} to {rec['invoiceNumber']}")
else:
print("No credit application opportunities found")
apply_credits_with_strategy("expiring_first")
def issue_promotional_credit(recipient_account, amount, campaign_id, expires_days=90):
"""Issue promotional credit to account"""
credit_data = {
"type": "promotional",
"recipientAccountId": recipient_account,
"amount": amount,
"currency": "USD",
"campaignId": campaign_id,
"description": f"Promotional credit from campaign {campaign_id}",
"expirationDays": expires_days,
"restrictions": {
"applicableServices": ["all"],
"minimumSpend": 0,
"usageLimit": "unlimited"
},
"autoActivate": True,
"metadata": {
"tags": ["promotional", "marketing"],
"transferable": False
}
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/credits/issue",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=credit_data
)
return response.json()
def issue_refund_credit(original_invoice_id, refund_amount, reason):
"""Issue refund credit for service issues"""
credit_data = {
"type": "refund",
"amount": refund_amount,
"currency": "USD",
"referenceId": original_invoice_id,
"description": f"Refund credit: {reason}",
"reason": reason,
"restrictions": {
"applicableServices": ["all"],
"usageLimit": "one_time"
},
"autoActivate": True,
"metadata": {
"tags": ["refund", "service_credit"],
"originalInvoice": original_invoice_id
}
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/credits/issue",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=credit_data
)
return response.json()
def issue_support_credit(account_id, amount, reason, restrictions=None):
"""Issue support credit for customer service issues"""
credit_data = {
"type": "support",
"recipientAccountId": account_id,
"amount": amount,
"currency": "USD",
"description": f"Support credit: {reason}",
"reason": reason,
"restrictions": restrictions or {
"applicableServices": ["all"],
"usageLimit": "unlimited"
},
"autoActivate": True,
"metadata": {
"tags": ["support", "customer_service"],
"issuedBy": "support_team"
}
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/credits/issue",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=credit_data
)
return response.json()
# Example credit issuance
def credit_issuance_examples():
"""Examples of different credit issuance scenarios"""
print("💳 Credit Issuance Examples")
print("=" * 30)
# Issue promotional credit
# promo_result = issue_promotional_credit(
# "account_123",
# 250.00,
# "spring_2024_promo",
# expires_days=120
# )
# print(f"Promotional Credit: {promo_result.get('creditId', 'Failed')}")
# Issue refund credit
# refund_result = issue_refund_credit(
# "inv_2024_01_001",
# 150.00,
# "Service downtime compensation"
# )
# print(f"Refund Credit: {refund_result.get('creditId', 'Failed')}")
# Issue support credit with restrictions
# support_result = issue_support_credit(
# "account_456",
# 100.00,
# "Apology for billing error",
# restrictions={
# "applicableServices": ["clusters"],
# "minimumSpend": 25.00,
# "usageLimit": "monthly"
# }
# )
# print(f"Support Credit: {support_result.get('creditId', 'Failed')}")
print("Credit issuance examples completed (uncomment to execute)")
credit_issuance_examples()
def get_expiring_credits(days_ahead=30):
"""Get credits expiring within specified days"""
response = requests.get(
"https://api.tensorone.ai/v2/billing/credits/expiring",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params={
"daysAhead": days_ahead,
"includeUsageHistory": True
}
)
return response.json()
def send_expiration_notifications():
"""Send notifications for expiring credits"""
expiring_credits = get_expiring_credits(30)
print("⏰ Credit Expiration Management")
print("=" * 32)
if expiring_credits.get('credits'):
total_expiring = sum(c['amount']['remaining'] for c in expiring_credits['credits'])
print(f"Credits expiring in 30 days: ${total_expiring:,.2f}")
print()
for credit in expiring_credits['credits']:
credit_id = credit['creditId']
remaining = credit['amount']['remaining']
expires = credit['dates']['expires']
description = credit['source']['description']
expires_date = datetime.fromisoformat(expires.replace('Z', '+00:00'))
days_left = (expires_date - datetime.now(expires_date.tzinfo)).days
urgency_icon = "🔴" if days_left <= 7 else "🟡"
print(f"{urgency_icon} {description}")
print(f" Amount: ${remaining:,.2f}")
print(f" Expires: {expires_date.strftime('%Y-%m-%d')} ({days_left} days)")
# Check if credit has been used
used_amount = credit['amount']['used']
if used_amount == 0:
print(f" ⚠️ Unused credit - consider applying to invoices")
print()
# Send notifications (implementation would vary)
notification_data = {
"type": "credit_expiration_warning",
"totalExpiring": total_expiring,
"creditCount": len(expiring_credits['credits']),
"expiringCredits": expiring_credits['credits']
}
# send_notification(notification_data) # Custom implementation
print("📧 Expiration notifications would be sent")
else:
print("✅ No credits expiring in the next 30 days")
def auto_apply_expiring_credits():
"""Automatically apply credits that are expiring soon"""
expiring_credits = get_expiring_credits(7) # Credits expiring in 7 days
if expiring_credits.get('credits'):
print("🚀 Auto-applying Expiring Credits")
print("-" * 33)
# Get eligible invoices
pending_invoices = get_pending_invoices()
for credit in expiring_credits['credits']:
if credit['amount']['remaining'] > 0:
credit_id = credit['creditId']
remaining = credit['amount']['remaining']
description = credit['source']['description']
print(f"Processing: {description} (${remaining:,.2f})")
# Find best invoice to apply to
if pending_invoices.get('invoices'):
best_invoice = None
best_match_amount = 0
for invoice in pending_invoices['invoices']:
invoice_amount = invoice['amounts']['total']
match_amount = min(remaining, invoice_amount)
if match_amount > best_match_amount:
best_invoice = invoice
best_match_amount = match_amount
if best_invoice and best_match_amount > 0:
# Apply credit to best matching invoice
# result = apply_credit_to_invoice(
# credit_id,
# best_invoice['invoiceId'],
# best_match_amount
# )
print(f" → Applied ${best_match_amount:,.2f} to {best_invoice['invoiceNumber']}")
# if result.get('success'):
# print(f" ✅ Successfully applied")
# else:
# print(f" ❌ Failed to apply")
else:
print(f" ⚠️ No suitable invoice found")
else:
print(f" ℹ️ No pending invoices to apply to")
print()
send_expiration_notifications()
# auto_apply_expiring_credits()
def generate_comprehensive_credit_report(time_period="current_year"):
"""Generate comprehensive credit analytics report"""
all_credits = get_credits(
date_range=time_period,
include_usage=True
)
print("📊 Comprehensive Credit Analytics")
print("=" * 36)
# Credit lifecycle analysis
lifecycle_stats = {
'issued': 0,
'activated': 0,
'partially_used': 0,
'fully_used': 0,
'expired_unused': 0,
'expired_partial': 0
}
total_issued_amount = 0
total_used_amount = 0
total_expired_amount = 0
for credit in all_credits['credits']:
original = credit['amount']['original']
used = credit['amount']['used']
status = credit['status']
total_issued_amount += original
total_used_amount += used
lifecycle_stats['issued'] += 1
if status == 'active' and used > 0:
lifecycle_stats['activated'] += 1
if used < original:
lifecycle_stats['partially_used'] += 1
else:
lifecycle_stats['fully_used'] += 1
elif status == 'expired':
total_expired_amount += (original - used)
if used == 0:
lifecycle_stats['expired_unused'] += 1
else:
lifecycle_stats['expired_partial'] += 1
# Display lifecycle statistics
print(f"Credit Lifecycle Analysis:")
print(f" Total Issued: {lifecycle_stats['issued']} credits (${total_issued_amount:,.2f})")
print(f" Total Used: ${total_used_amount:,.2f}")
print(f" Utilization Rate: {(total_used_amount/total_issued_amount)*100:.1f}%")
print(f" Expired Unused: ${total_expired_amount:,.2f}")
print()
# Credit source effectiveness
source_effectiveness = {}
for credit in all_credits['credits']:
source = credit['source']['issuedBy']
usage_rate = (credit['amount']['used'] / credit['amount']['original']) * 100
if source not in source_effectiveness:
source_effectiveness[source] = {
'count': 0,
'total_issued': 0,
'total_used': 0,
'usage_rates': []
}
source_effectiveness[source]['count'] += 1
source_effectiveness[source]['total_issued'] += credit['amount']['original']
source_effectiveness[source]['total_used'] += credit['amount']['used']
source_effectiveness[source]['usage_rates'].append(usage_rate)
print("Credit Source Effectiveness:")
for source, stats in source_effectiveness.items():
avg_usage = sum(stats['usage_rates']) / len(stats['usage_rates'])
print(f" {source.replace('_', ' ').title()}:")
print(f" Count: {stats['count']}")
print(f" Total Issued: ${stats['total_issued']:,.2f}")
print(f" Average Usage Rate: {avg_usage:.1f}%")
print()
# Monthly credit trends
monthly_trends = {}
for credit in all_credits['credits']:
issued_date = credit['dates']['issued']
month = issued_date[:7] # YYYY-MM
if month not in monthly_trends:
monthly_trends[month] = {
'issued': 0,
'amount': 0,
'used': 0
}
monthly_trends[month]['issued'] += 1
monthly_trends[month]['amount'] += credit['amount']['original']
monthly_trends[month]['used'] += credit['amount']['used']
print("Monthly Credit Trends:")
for month in sorted(monthly_trends.keys()):
trends = monthly_trends[month]
usage_rate = (trends['used'] / trends['amount']) * 100 if trends['amount'] > 0 else 0
print(f" {month}: {trends['issued']} credits, ${trends['amount']:,.2f} issued, {usage_rate:.1f}% used")
return {
'lifecycle_stats': lifecycle_stats,
'source_effectiveness': source_effectiveness,
'monthly_trends': monthly_trends,
'total_issued': total_issued_amount,
'total_used': total_used_amount,
'utilization_rate': (total_used_amount/total_issued_amount)*100
}
def credit_roi_analysis():
"""Analyze return on investment for different credit types"""
print("\n💹 Credit ROI Analysis")
print("=" * 22)
# This would analyze the business impact of different credit types
# For example, promotional credits vs referral credits vs support credits
roi_data = {
'promotional': {
'cost': 15000.00, # Cost of promotional credits
'customer_acquisition': 45, # New customers acquired
'customer_ltv': 2500.00, # Average customer lifetime value
'retention_rate': 0.85
},
'referral': {
'cost': 5000.00,
'customer_acquisition': 25,
'customer_ltv': 3200.00,
'retention_rate': 0.92
},
'support': {
'cost': 3000.00,
'customer_retention': 18, # Customers retained
'avg_customer_value': 1800.00,
'satisfaction_improvement': 0.25
}
}
for credit_type, data in roi_data.items():
print(f"{credit_type.title()} Credits:")
if 'customer_acquisition' in data:
total_value = data['customer_acquisition'] * data['customer_ltv'] * data['retention_rate']
roi = ((total_value - data['cost']) / data['cost']) * 100
print(f" Investment: ${data['cost']:,.2f}")
print(f" Expected Value: ${total_value:,.2f}")
print(f" ROI: {roi:.1f}%")
else:
retention_value = data['customer_retention'] * data['avg_customer_value']
roi = ((retention_value - data['cost']) / data['cost']) * 100
print(f" Investment: ${data['cost']:,.2f}")
print(f" Retention Value: ${retention_value:,.2f}")
print(f" ROI: {roi:.1f}%")
print()
# Generate comprehensive reports
credit_report = generate_comprehensive_credit_report()
credit_roi_analysis()