curl -X GET "https://api.tensorone.ai/v2/billing/invoices" \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
-d "status[]=pending&status[]=overdue" \
-d "includeLineItems=true" \
-d "dateRange=last_6_months"
{
"invoices": [
{
"invoiceId": "inv_2024_01_001",
"invoiceNumber": "INV-2024-001",
"status": "paid",
"billingPeriod": {
"startDate": "2024-01-01",
"endDate": "2024-01-31",
"description": "January 2024"
},
"amounts": {
"subtotal": 1247.83,
"taxAmount": 124.78,
"discountAmount": 0.00,
"creditAmount": 50.00,
"total": 1322.61,
"currency": "USD"
},
"dates": {
"issued": "2024-02-01",
"dueDate": "2024-02-15",
"paidDate": "2024-02-10",
"createdAt": "2024-02-01T08:00:00Z"
},
"customer": {
"name": "Acme Corporation",
"email": "billing@acme.com",
"billingAddress": {
"street": "123 Business Ave",
"city": "San Francisco",
"state": "CA",
"postalCode": "94105",
"country": "US"
},
"taxId": "12-3456789"
},
"lineItems": [
{
"description": "GPU Cluster A100 - Compute Hours",
"resourceType": "clusters",
"quantity": 156.7,
"unit": "gpu_hours",
"unitPrice": 5.00,
"totalAmount": 783.50,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
},
{
"description": "AI Services - Text-to-Image Generation",
"resourceType": "ai-services",
"quantity": 34562,
"unit": "requests",
"unitPrice": 0.003,
"totalAmount": 103.69,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
},
{
"description": "Data Storage - Standard Tier",
"resourceType": "storage",
"quantity": 2847.3,
"unit": "gb_hours",
"unitPrice": 0.05,
"totalAmount": 142.37,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
},
{
"description": "Data Transfer - Outbound",
"resourceType": "bandwidth",
"quantity": 1256.8,
"unit": "gb",
"unitPrice": 0.09,
"totalAmount": 113.11,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
}
],
"payment": {
"paymentMethod": "Credit Card (****4242)",
"transactionId": "txn_1234567890",
"paidAmount": 1322.61,
"paymentDate": "2024-02-10T14:32:15Z"
},
"documents": {
"pdf": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_001/download/pdf",
"html": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_001/view",
"csv": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_001/export/csv"
}
},
{
"invoiceId": "inv_2024_01_002",
"invoiceNumber": "INV-2024-002",
"status": "overdue",
"billingPeriod": {
"startDate": "2024-02-01",
"endDate": "2024-02-29",
"description": "February 2024"
},
"amounts": {
"subtotal": 2156.45,
"taxAmount": 215.65,
"discountAmount": 100.00,
"creditAmount": 0.00,
"total": 2272.10,
"currency": "USD"
},
"dates": {
"issued": "2024-03-01",
"dueDate": "2024-03-15",
"paidDate": null,
"createdAt": "2024-03-01T08:00:00Z"
},
"customer": {
"name": "Acme Corporation",
"email": "billing@acme.com",
"billingAddress": {
"street": "123 Business Ave",
"city": "San Francisco",
"state": "CA",
"postalCode": "94105",
"country": "US"
},
"taxId": "12-3456789"
},
"lineItems": [],
"payment": null,
"documents": {
"pdf": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_002/download/pdf",
"html": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_002/view",
"csv": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_002/export/csv"
}
}
],
"summary": {
"totalCount": 12,
"totalAmount": 18456.78,
"byStatus": {
"paid": {
"count": 8,
"amount": 12834.56
},
"pending": {
"count": 2,
"amount": 3350.12
},
"overdue": {
"count": 1,
"amount": 2272.10
},
"draft": {
"count": 1,
"amount": 0.00
}
},
"averageAmount": 1537.23,
"currency": "USD"
},
"pagination": {
"limit": 25,
"offset": 0,
"total": 12,
"hasMore": false
}
}
Retrieve, manage, and download invoices for your TensorOne account billing and payment history
curl -X GET "https://api.tensorone.ai/v2/billing/invoices" \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
-d "status[]=pending&status[]=overdue" \
-d "includeLineItems=true" \
-d "dateRange=last_6_months"
{
"invoices": [
{
"invoiceId": "inv_2024_01_001",
"invoiceNumber": "INV-2024-001",
"status": "paid",
"billingPeriod": {
"startDate": "2024-01-01",
"endDate": "2024-01-31",
"description": "January 2024"
},
"amounts": {
"subtotal": 1247.83,
"taxAmount": 124.78,
"discountAmount": 0.00,
"creditAmount": 50.00,
"total": 1322.61,
"currency": "USD"
},
"dates": {
"issued": "2024-02-01",
"dueDate": "2024-02-15",
"paidDate": "2024-02-10",
"createdAt": "2024-02-01T08:00:00Z"
},
"customer": {
"name": "Acme Corporation",
"email": "billing@acme.com",
"billingAddress": {
"street": "123 Business Ave",
"city": "San Francisco",
"state": "CA",
"postalCode": "94105",
"country": "US"
},
"taxId": "12-3456789"
},
"lineItems": [
{
"description": "GPU Cluster A100 - Compute Hours",
"resourceType": "clusters",
"quantity": 156.7,
"unit": "gpu_hours",
"unitPrice": 5.00,
"totalAmount": 783.50,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
},
{
"description": "AI Services - Text-to-Image Generation",
"resourceType": "ai-services",
"quantity": 34562,
"unit": "requests",
"unitPrice": 0.003,
"totalAmount": 103.69,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
},
{
"description": "Data Storage - Standard Tier",
"resourceType": "storage",
"quantity": 2847.3,
"unit": "gb_hours",
"unitPrice": 0.05,
"totalAmount": 142.37,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
},
{
"description": "Data Transfer - Outbound",
"resourceType": "bandwidth",
"quantity": 1256.8,
"unit": "gb",
"unitPrice": 0.09,
"totalAmount": 113.11,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
}
],
"payment": {
"paymentMethod": "Credit Card (****4242)",
"transactionId": "txn_1234567890",
"paidAmount": 1322.61,
"paymentDate": "2024-02-10T14:32:15Z"
},
"documents": {
"pdf": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_001/download/pdf",
"html": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_001/view",
"csv": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_001/export/csv"
}
},
{
"invoiceId": "inv_2024_01_002",
"invoiceNumber": "INV-2024-002",
"status": "overdue",
"billingPeriod": {
"startDate": "2024-02-01",
"endDate": "2024-02-29",
"description": "February 2024"
},
"amounts": {
"subtotal": 2156.45,
"taxAmount": 215.65,
"discountAmount": 100.00,
"creditAmount": 0.00,
"total": 2272.10,
"currency": "USD"
},
"dates": {
"issued": "2024-03-01",
"dueDate": "2024-03-15",
"paidDate": null,
"createdAt": "2024-03-01T08:00:00Z"
},
"customer": {
"name": "Acme Corporation",
"email": "billing@acme.com",
"billingAddress": {
"street": "123 Business Ave",
"city": "San Francisco",
"state": "CA",
"postalCode": "94105",
"country": "US"
},
"taxId": "12-3456789"
},
"lineItems": [],
"payment": null,
"documents": {
"pdf": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_002/download/pdf",
"html": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_002/view",
"csv": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_002/export/csv"
}
}
],
"summary": {
"totalCount": 12,
"totalAmount": 18456.78,
"byStatus": {
"paid": {
"count": 8,
"amount": 12834.56
},
"pending": {
"count": 2,
"amount": 3350.12
},
"overdue": {
"count": 1,
"amount": 2272.10
},
"draft": {
"count": 1,
"amount": 0.00
}
},
"averageAmount": 1537.23,
"currency": "USD"
},
"pagination": {
"limit": 25,
"offset": 0,
"total": 12,
"hasMore": false
}
}
draft - Draft invoices not yet finalizedpending - Pending paymentpaid - Successfully paidoverdue - Past due datecancelled - Cancelled invoicesrefunded - Refunded invoiceslast_month - Previous monthlast_3_months - Last 3 monthslast_6_months - Last 6 monthslast_year - Previous 12 monthscurrent_year - Current calendar yearcustom - Custom date range (requires startDate and endDate)USD, EUR, GBP, JPY, CAD, AUDShow Invoice Object
curl -X GET "https://api.tensorone.ai/v2/billing/invoices" \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
-d "status[]=pending&status[]=overdue" \
-d "includeLineItems=true" \
-d "dateRange=last_6_months"
{
"invoices": [
{
"invoiceId": "inv_2024_01_001",
"invoiceNumber": "INV-2024-001",
"status": "paid",
"billingPeriod": {
"startDate": "2024-01-01",
"endDate": "2024-01-31",
"description": "January 2024"
},
"amounts": {
"subtotal": 1247.83,
"taxAmount": 124.78,
"discountAmount": 0.00,
"creditAmount": 50.00,
"total": 1322.61,
"currency": "USD"
},
"dates": {
"issued": "2024-02-01",
"dueDate": "2024-02-15",
"paidDate": "2024-02-10",
"createdAt": "2024-02-01T08:00:00Z"
},
"customer": {
"name": "Acme Corporation",
"email": "billing@acme.com",
"billingAddress": {
"street": "123 Business Ave",
"city": "San Francisco",
"state": "CA",
"postalCode": "94105",
"country": "US"
},
"taxId": "12-3456789"
},
"lineItems": [
{
"description": "GPU Cluster A100 - Compute Hours",
"resourceType": "clusters",
"quantity": 156.7,
"unit": "gpu_hours",
"unitPrice": 5.00,
"totalAmount": 783.50,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
},
{
"description": "AI Services - Text-to-Image Generation",
"resourceType": "ai-services",
"quantity": 34562,
"unit": "requests",
"unitPrice": 0.003,
"totalAmount": 103.69,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
},
{
"description": "Data Storage - Standard Tier",
"resourceType": "storage",
"quantity": 2847.3,
"unit": "gb_hours",
"unitPrice": 0.05,
"totalAmount": 142.37,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
},
{
"description": "Data Transfer - Outbound",
"resourceType": "bandwidth",
"quantity": 1256.8,
"unit": "gb",
"unitPrice": 0.09,
"totalAmount": 113.11,
"period": {
"start": "2024-01-01",
"end": "2024-01-31"
}
}
],
"payment": {
"paymentMethod": "Credit Card (****4242)",
"transactionId": "txn_1234567890",
"paidAmount": 1322.61,
"paymentDate": "2024-02-10T14:32:15Z"
},
"documents": {
"pdf": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_001/download/pdf",
"html": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_001/view",
"csv": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_001/export/csv"
}
},
{
"invoiceId": "inv_2024_01_002",
"invoiceNumber": "INV-2024-002",
"status": "overdue",
"billingPeriod": {
"startDate": "2024-02-01",
"endDate": "2024-02-29",
"description": "February 2024"
},
"amounts": {
"subtotal": 2156.45,
"taxAmount": 215.65,
"discountAmount": 100.00,
"creditAmount": 0.00,
"total": 2272.10,
"currency": "USD"
},
"dates": {
"issued": "2024-03-01",
"dueDate": "2024-03-15",
"paidDate": null,
"createdAt": "2024-03-01T08:00:00Z"
},
"customer": {
"name": "Acme Corporation",
"email": "billing@acme.com",
"billingAddress": {
"street": "123 Business Ave",
"city": "San Francisco",
"state": "CA",
"postalCode": "94105",
"country": "US"
},
"taxId": "12-3456789"
},
"lineItems": [],
"payment": null,
"documents": {
"pdf": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_002/download/pdf",
"html": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_002/view",
"csv": "https://api.tensorone.ai/v2/billing/invoices/inv_2024_01_002/export/csv"
}
}
],
"summary": {
"totalCount": 12,
"totalAmount": 18456.78,
"byStatus": {
"paid": {
"count": 8,
"amount": 12834.56
},
"pending": {
"count": 2,
"amount": 3350.12
},
"overdue": {
"count": 1,
"amount": 2272.10
},
"draft": {
"count": 1,
"amount": 0.00
}
},
"averageAmount": 1537.23,
"currency": "USD"
},
"pagination": {
"limit": 25,
"offset": 0,
"total": 12,
"hasMore": false
}
}
def download_invoice(invoice_id, format_type="pdf"):
"""Download invoice in specified format"""
response = requests.get(
f"https://api.tensorone.ai/v2/billing/invoices/{invoice_id}/download/{format_type}",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
if response.status_code == 200:
filename = f"invoice_{invoice_id}.{format_type}"
with open(filename, 'wb') as f:
f.write(response.content)
print(f"Downloaded: {filename}")
return filename
else:
print(f"Failed to download invoice: {response.status_code}")
return None
def bulk_download_invoices(invoice_ids, format_type="pdf"):
"""Download multiple invoices"""
downloaded_files = []
for invoice_id in invoice_ids:
filename = download_invoice(invoice_id, format_type)
if filename:
downloaded_files.append(filename)
return downloaded_files
# Download specific invoice
invoice_file = download_invoice("inv_2024_01_001", "pdf")
# Bulk download recent invoices
recent_invoices = get_invoices(status=["paid"], date_range="last_month")
invoice_ids = [inv['invoiceId'] for inv in recent_invoices['invoices']]
downloaded_files = bulk_download_invoices(invoice_ids[:5])
print(f"Downloaded {len(downloaded_files)} invoice files")
def send_invoice_reminder(invoice_id, reminder_type="standard"):
"""Send payment reminder for overdue invoice"""
reminder_data = {
"reminderType": reminder_type, # standard, urgent, final
"customMessage": None,
"includeLateFee": True,
"notificationChannels": ["email"]
}
response = requests.post(
f"https://api.tensorone.ai/v2/billing/invoices/{invoice_id}/remind",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=reminder_data
)
return response.json()
def automated_reminder_system():
"""Automated system to send reminders for overdue invoices"""
overdue_invoices = get_invoices(status=["overdue"])
for invoice in overdue_invoices['invoices']:
invoice_id = invoice['invoiceId']
due_date = datetime.fromisoformat(invoice['dates']['dueDate'].replace('Z', '+00:00'))
days_overdue = (datetime.now(due_date.tzinfo) - due_date).days
# Determine reminder type based on days overdue
if days_overdue <= 7:
reminder_type = "standard"
elif days_overdue <= 21:
reminder_type = "urgent"
else:
reminder_type = "final"
print(f"Sending {reminder_type} reminder for {invoice['invoiceNumber']} ({days_overdue} days overdue)")
result = send_invoice_reminder(invoice_id, reminder_type)
if result.get('success'):
print(f" ✅ Reminder sent successfully")
else:
print(f" ❌ Failed to send reminder: {result.get('error', 'Unknown error')}")
# Run automated reminder system
# automated_reminder_system()
def generate_invoice_analytics(time_period="current_year"):
"""Generate comprehensive invoice analytics"""
invoices_data = get_invoices(date_range=time_period, include_details=True)
analytics = {
'revenue_trends': {},
'payment_patterns': {},
'resource_breakdown': {},
'customer_insights': {}
}
invoices = invoices_data['invoices']
# Revenue trends by month
monthly_revenue = {}
for invoice in invoices:
if invoice['status'] == 'paid':
month = invoice['dates']['paidDate'][:7] # YYYY-MM
monthly_revenue[month] = monthly_revenue.get(month, 0) + invoice['amounts']['total']
analytics['revenue_trends'] = monthly_revenue
# Payment timing analysis
payment_days = []
for invoice in invoices:
if invoice['status'] == 'paid' and invoice['dates']['paidDate']:
issued = datetime.fromisoformat(invoice['dates']['issued'])
paid = datetime.fromisoformat(invoice['dates']['paidDate'].replace('Z', '+00:00'))
days_to_pay = (paid - issued).days
payment_days.append(days_to_pay)
if payment_days:
analytics['payment_patterns'] = {
'average_days_to_pay': sum(payment_days) / len(payment_days),
'fastest_payment': min(payment_days),
'slowest_payment': max(payment_days)
}
# Resource type breakdown
resource_totals = {}
for invoice in invoices:
if invoice.get('lineItems'):
for item in invoice['lineItems']:
resource_type = item['resourceType']
resource_totals[resource_type] = resource_totals.get(resource_type, 0) + item['totalAmount']
analytics['resource_breakdown'] = resource_totals
return analytics
def print_invoice_analytics():
"""Print formatted invoice analytics"""
analytics = generate_invoice_analytics()
print("📊 Invoice Analytics Report")
print("=" * 30)
# Revenue trends
if analytics['revenue_trends']:
print("\n💰 Monthly Revenue Trends:")
for month, revenue in sorted(analytics['revenue_trends'].items()):
print(f" {month}: ${revenue:,.2f}")
# Payment patterns
if analytics['payment_patterns']:
patterns = analytics['payment_patterns']
print(f"\n⏱️ Payment Patterns:")
print(f" Average Days to Pay: {patterns['average_days_to_pay']:.1f}")
print(f" Fastest Payment: {patterns['fastest_payment']} days")
print(f" Slowest Payment: {patterns['slowest_payment']} days")
# Resource breakdown
if analytics['resource_breakdown']:
print(f"\n🔧 Revenue by Resource Type:")
sorted_resources = sorted(analytics['resource_breakdown'].items(),
key=lambda x: x[1], reverse=True)
total_resource_revenue = sum(analytics['resource_breakdown'].values())
for resource, revenue in sorted_resources:
percentage = (revenue / total_resource_revenue) * 100
print(f" {resource.title()}: ${revenue:,.2f} ({percentage:.1f}%)")
print_invoice_analytics()
def create_invoice_dispute(invoice_id, dispute_reason, amount=None, description=None):
"""Create a dispute for an invoice"""
dispute_data = {
"invoiceId": invoice_id,
"disputeReason": dispute_reason, # billing_error, duplicate_charge, service_issue, etc.
"disputedAmount": amount, # None for full invoice dispute
"description": description,
"supportingDocuments": []
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/disputes",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=dispute_data
)
return response.json()
def get_invoice_disputes(status=None):
"""Get list of invoice disputes"""
params = {}
if status:
params['status'] = status
response = requests.get(
"https://api.tensorone.ai/v2/billing/disputes",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params=params
)
return response.json()
def resolve_dispute(dispute_id, resolution, adjustment_amount=None):
"""Resolve an invoice dispute"""
resolution_data = {
"resolution": resolution, # accepted, rejected, partial
"adjustmentAmount": adjustment_amount,
"resolutionNotes": "Dispute resolved after review"
}
response = requests.post(
f"https://api.tensorone.ai/v2/billing/disputes/{dispute_id}/resolve",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=resolution_data
)
return response.json()
# Example dispute workflow
def handle_billing_dispute_workflow():
"""Example dispute handling workflow"""
print("🎯 Dispute Management Workflow")
print("=" * 32)
# Get active disputes
disputes = get_invoice_disputes(status="pending")
if disputes.get('disputes'):
for dispute in disputes['disputes']:
dispute_id = dispute['disputeId']
invoice_num = dispute['invoiceNumber']
reason = dispute['disputeReason']
amount = dispute['disputedAmount']
print(f"\n📋 Dispute: {dispute_id}")
print(f"Invoice: {invoice_num}")
print(f"Reason: {reason}")
print(f"Amount: ${amount:,.2f}")
print(f"Description: {dispute['description']}")
# Simulate dispute resolution
# resolution = resolve_dispute(dispute_id, "partial", amount * 0.5)
# print(f"Resolution: {resolution['status']}")
else:
print("No pending disputes found")
# Run dispute workflow
handle_billing_dispute_workflow()
def setup_automated_invoice_processing():
"""Configure automated invoice processing rules"""
automation_config = {
"autoSendInvoices": True,
"sendDelay": "24h", # Wait 24h after period ends
"reminderSchedule": {
"firstReminder": "3d", # 3 days after due date
"secondReminder": "10d", # 10 days after due date
"finalReminder": "20d" # 20 days after due date
},
"lateFeeSettings": {
"enabled": True,
"amount": 25.00,
"type": "fixed", # fixed or percentage
"gracePeriod": "5d"
},
"autoRetryPayments": {
"enabled": True,
"maxRetries": 3,
"retryInterval": "3d"
}
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/automation/invoice-processing",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=automation_config
)
return response.json()
# Configure automated processing
automation_result = setup_automated_invoice_processing()
print(f"Automation configured: {automation_result.get('success', False)}")
def customize_invoice_template(template_settings):
"""Customize invoice template and branding"""
response = requests.post(
"https://api.tensorone.ai/v2/billing/invoice-templates",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=template_settings
)
return response.json()
# Customize invoice appearance
template_customization = {
"companyLogo": "https://yourcompany.com/logo.png",
"primaryColor": "#1a365d",
"fontFamily": "Arial",
"customFields": [
{
"name": "Purchase Order",
"required": False,
"position": "header"
},
{
"name": "Project Code",
"required": True,
"position": "line_item"
}
],
"footerText": "Thank you for your business!",
"paymentInstructions": "Payment is due within 15 days of invoice date.",
"includeTaxSummary": True,
"showResourceUsageDetails": True
}
template_result = customize_invoice_template(template_customization)
print(f"Template updated: {template_result.get('templateId', 'N/A')}")