feat: complete subscription billing system phases 6-10

Phase 6 - Database-driven tiers:
- Update subscription_service to query database first with legacy fallback
- Add get_tier_info() db parameter and _get_tier_from_legacy() method

Phase 7 - Platform health integration:
- Add get_subscription_capacity() for theoretical vs actual capacity
- Include subscription capacity in full health report

Phase 8 - Background subscription tasks:
- Add reset_period_counters() for billing period resets
- Add check_trial_expirations() for trial management
- Add sync_stripe_status() for Stripe synchronization
- Add cleanup_stale_subscriptions() for maintenance
- Add capture_capacity_snapshot() for daily metrics

Phase 10 - Capacity planning & forecasting:
- Add CapacitySnapshot model for historical tracking
- Create capacity_forecast_service with growth trends
- Add /subscription-capacity, /trends, /recommendations endpoints
- Add /snapshot endpoint for manual captures

Also includes billing API enhancements from phase 4:
- Add upcoming-invoice, change-tier, addon purchase/cancel endpoints
- Add UsageSummary schema for billing page
- Enhance billing.js with addon management functions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2025-12-26 20:51:13 +01:00
parent b717c23787
commit c6e7f4087f
20 changed files with 1895 additions and 29 deletions

View File

@@ -17,7 +17,9 @@ function billingData() {
showCancelModal: false,
showSuccessMessage: false,
showCancelMessage: false,
showAddonSuccessMessage: false,
cancelReason: '',
purchasingAddon: null,
// Initialize
async init() {
@@ -25,13 +27,16 @@ function billingData() {
const params = new URLSearchParams(window.location.search);
if (params.get('success') === 'true') {
this.showSuccessMessage = true;
// Clean URL
window.history.replaceState({}, document.title, window.location.pathname);
}
if (params.get('cancelled') === 'true') {
this.showCancelMessage = true;
window.history.replaceState({}, document.title, window.location.pathname);
}
if (params.get('addon_success') === 'true') {
this.showAddonSuccessMessage = true;
window.history.replaceState({}, document.title, window.location.pathname);
}
await this.loadData();
},
@@ -40,16 +45,18 @@ function billingData() {
this.loading = true;
try {
// Load all data in parallel
const [subscriptionRes, tiersRes, addonsRes, invoicesRes] = await Promise.all([
const [subscriptionRes, tiersRes, addonsRes, myAddonsRes, invoicesRes] = await Promise.all([
this.apiGet('/billing/subscription'),
this.apiGet('/billing/tiers'),
this.apiGet('/billing/addons'),
this.apiGet('/billing/my-addons'),
this.apiGet('/billing/invoices?limit=5'),
]);
this.subscription = subscriptionRes;
this.tiers = tiersRes.tiers || [];
this.addons = addonsRes || [];
this.myAddons = myAddonsRes || [];
this.invoices = invoicesRes.invoices || [];
} catch (error) {
@@ -119,6 +126,45 @@ function billingData() {
}
},
async purchaseAddon(addon) {
this.purchasingAddon = addon.code;
try {
const response = await this.apiPost('/billing/addons/purchase', {
addon_code: addon.code,
quantity: 1
});
if (response.checkout_url) {
window.location.href = response.checkout_url;
}
} catch (error) {
console.error('Error purchasing addon:', error);
this.showNotification('Failed to purchase add-on', 'error');
} finally {
this.purchasingAddon = null;
}
},
async cancelAddon(addon) {
if (!confirm(`Are you sure you want to cancel ${addon.addon_name}?`)) {
return;
}
try {
await this.apiDelete(`/billing/addons/${addon.id}`);
this.showNotification('Add-on cancelled successfully', 'success');
await this.loadData();
} catch (error) {
console.error('Error cancelling addon:', error);
this.showNotification('Failed to cancel add-on', 'error');
}
},
// Check if addon is already purchased
isAddonPurchased(addonCode) {
return this.myAddons.some(a => a.addon_code === addonCode && a.status === 'active');
},
// API helpers
async apiGet(endpoint) {
const response = await fetch(`/api/v1/vendor${endpoint}`, {
@@ -153,6 +199,23 @@ function billingData() {
return response.json();
},
async apiDelete(endpoint) {
const response = await fetch(`/api/v1/vendor${endpoint}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include'
});
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(error.detail || `API error: ${response.status}`);
}
return response.json();
},
// Formatters
formatDate(dateString) {
if (!dateString) return '-';