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:
@@ -12,9 +12,11 @@ function adminVendorDetail() {
|
||||
// Vendor detail page specific state
|
||||
currentPage: 'vendor-detail',
|
||||
vendor: null,
|
||||
subscription: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
vendorCode: null,
|
||||
showSubscriptionModal: false,
|
||||
|
||||
// Initialize
|
||||
async init() {
|
||||
@@ -35,6 +37,10 @@ function adminVendorDetail() {
|
||||
this.vendorCode = match[1];
|
||||
detailLog.info('Viewing vendor:', this.vendorCode);
|
||||
await this.loadVendor();
|
||||
// Load subscription after vendor is loaded
|
||||
if (this.vendor?.id) {
|
||||
await this.loadSubscription();
|
||||
}
|
||||
} else {
|
||||
detailLog.error('No vendor code in URL');
|
||||
this.error = 'Invalid vendor URL';
|
||||
@@ -91,6 +97,82 @@ function adminVendorDetail() {
|
||||
return formatted;
|
||||
},
|
||||
|
||||
// Load subscription data for this vendor
|
||||
async loadSubscription() {
|
||||
if (!this.vendor?.id) {
|
||||
detailLog.warn('Cannot load subscription: no vendor ID');
|
||||
return;
|
||||
}
|
||||
|
||||
detailLog.info('Loading subscription for vendor:', this.vendor.id);
|
||||
|
||||
try {
|
||||
const url = `/admin/subscriptions/${this.vendor.id}`;
|
||||
window.LogConfig.logApiCall('GET', url, null, 'request');
|
||||
|
||||
const response = await apiClient.get(url);
|
||||
window.LogConfig.logApiCall('GET', url, response, 'response');
|
||||
|
||||
this.subscription = response;
|
||||
detailLog.info('Subscription loaded:', {
|
||||
tier: this.subscription?.tier,
|
||||
status: this.subscription?.status,
|
||||
orders_this_period: this.subscription?.orders_this_period
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
// 404 means no subscription exists - that's OK
|
||||
if (error.status === 404) {
|
||||
detailLog.info('No subscription found for vendor');
|
||||
this.subscription = null;
|
||||
} else {
|
||||
detailLog.warn('Failed to load subscription:', error.message);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Get usage bar color based on percentage
|
||||
getUsageBarColor(current, limit) {
|
||||
if (!limit || limit === 0) return 'bg-blue-500';
|
||||
const percent = (current / limit) * 100;
|
||||
if (percent >= 90) return 'bg-red-500';
|
||||
if (percent >= 75) return 'bg-yellow-500';
|
||||
return 'bg-green-500';
|
||||
},
|
||||
|
||||
// Create a new subscription for this vendor
|
||||
async createSubscription() {
|
||||
if (!this.vendor?.id) {
|
||||
Utils.showToast('No vendor loaded', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
detailLog.info('Creating subscription for vendor:', this.vendor.id);
|
||||
|
||||
try {
|
||||
// Create a trial subscription with default tier
|
||||
const url = `/admin/subscriptions/${this.vendor.id}`;
|
||||
const data = {
|
||||
tier: 'essential',
|
||||
status: 'trial',
|
||||
trial_days: 14,
|
||||
is_annual: false
|
||||
};
|
||||
|
||||
window.LogConfig.logApiCall('POST', url, data, 'request');
|
||||
const response = await apiClient.post(url, data);
|
||||
window.LogConfig.logApiCall('POST', url, response, 'response');
|
||||
|
||||
this.subscription = response;
|
||||
Utils.showToast('Subscription created successfully', 'success');
|
||||
detailLog.info('Subscription created:', this.subscription);
|
||||
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'Create Subscription');
|
||||
Utils.showToast(error.message || 'Failed to create subscription', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
// Delete vendor
|
||||
async deleteVendor() {
|
||||
detailLog.info('Delete vendor requested:', this.vendorCode);
|
||||
|
||||
67
static/vendor/js/billing.js
vendored
67
static/vendor/js/billing.js
vendored
@@ -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 '-';
|
||||
|
||||
Reference in New Issue
Block a user