feat(billing): migrate frontend templates to feature provider system
Replace hardcoded subscription fields (orders_limit, products_limit,
team_members_limit) across 5 frontend pages with dynamic feature
provider APIs. Add admin convenience endpoint for store subscription
lookup. Remove legacy stubs (StoreSubscription, FeatureCode, Feature,
TIER_LIMITS, FeatureInfo, FeatureUpgradeInfo) and schema aliases.
Pages updated:
- Admin subscriptions: dynamic feature overrides editor
- Admin tiers: correct feature catalog/limits API URLs
- Store billing: usage metrics from /store/billing/usage
- Merchant subscription detail: tier.feature_limits rendering
- Admin store detail: new GET /admin/subscriptions/store/{id} endpoint
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -28,6 +28,7 @@ function adminSubscriptionTiers() {
|
||||
categories: [],
|
||||
featuresGrouped: {},
|
||||
selectedFeatures: [],
|
||||
featureLimits: {}, // { feature_code: limit_value }
|
||||
selectedTierForFeatures: null,
|
||||
showFeaturePanel: false,
|
||||
loadingFeatures: false,
|
||||
@@ -46,13 +47,9 @@ function adminSubscriptionTiers() {
|
||||
description: '',
|
||||
price_monthly_cents: 0,
|
||||
price_annual_cents: null,
|
||||
orders_per_month: null,
|
||||
products_limit: null,
|
||||
team_members: null,
|
||||
display_order: 0,
|
||||
stripe_product_id: '',
|
||||
stripe_price_monthly_id: '',
|
||||
features: [],
|
||||
is_active: true,
|
||||
is_public: true
|
||||
},
|
||||
@@ -70,8 +67,7 @@ function adminSubscriptionTiers() {
|
||||
await Promise.all([
|
||||
this.loadTiers(),
|
||||
this.loadStats(),
|
||||
this.loadFeatures(),
|
||||
this.loadCategories()
|
||||
this.loadFeatures()
|
||||
]);
|
||||
tiersLog.info('=== SUBSCRIPTION TIERS PAGE INITIALIZED ===');
|
||||
} catch (error) {
|
||||
@@ -137,13 +133,9 @@ function adminSubscriptionTiers() {
|
||||
description: '',
|
||||
price_monthly_cents: 0,
|
||||
price_annual_cents: null,
|
||||
orders_per_month: null,
|
||||
products_limit: null,
|
||||
team_members: null,
|
||||
display_order: this.tiers.length,
|
||||
stripe_product_id: '',
|
||||
stripe_price_monthly_id: '',
|
||||
features: [],
|
||||
is_active: true,
|
||||
is_public: true
|
||||
};
|
||||
@@ -158,13 +150,9 @@ function adminSubscriptionTiers() {
|
||||
description: tier.description || '',
|
||||
price_monthly_cents: tier.price_monthly_cents,
|
||||
price_annual_cents: tier.price_annual_cents,
|
||||
orders_per_month: tier.orders_per_month,
|
||||
products_limit: tier.products_limit,
|
||||
team_members: tier.team_members,
|
||||
display_order: tier.display_order,
|
||||
stripe_product_id: tier.stripe_product_id || '',
|
||||
stripe_price_monthly_id: tier.stripe_price_monthly_id || '',
|
||||
features: tier.features || [],
|
||||
is_active: tier.is_active,
|
||||
is_public: tier.is_public
|
||||
};
|
||||
@@ -184,9 +172,6 @@ function adminSubscriptionTiers() {
|
||||
// Clean up null values for empty strings
|
||||
const payload = { ...this.formData };
|
||||
if (payload.price_annual_cents === '') payload.price_annual_cents = null;
|
||||
if (payload.orders_per_month === '') payload.orders_per_month = null;
|
||||
if (payload.products_limit === '') payload.products_limit = null;
|
||||
if (payload.team_members === '') payload.team_members = null;
|
||||
|
||||
if (this.editingTier) {
|
||||
// Update existing tier
|
||||
@@ -233,24 +218,22 @@ function adminSubscriptionTiers() {
|
||||
|
||||
async loadFeatures() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/features');
|
||||
this.features = data.features || [];
|
||||
tiersLog.info(`Loaded ${this.features.length} features`);
|
||||
const data = await apiClient.get('/admin/subscriptions/features/catalog');
|
||||
// Parse grouped response: { features: { category: [FeatureDeclaration, ...] } }
|
||||
this.features = [];
|
||||
this.categories = [];
|
||||
for (const [category, featureList] of Object.entries(data.features || {})) {
|
||||
this.categories.push(category);
|
||||
for (const f of featureList) {
|
||||
this.features.push({ ...f, category });
|
||||
}
|
||||
}
|
||||
tiersLog.info(`Loaded ${this.features.length} features in ${this.categories.length} categories`);
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load features:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async loadCategories() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/features/categories');
|
||||
this.categories = data.categories || [];
|
||||
tiersLog.info(`Loaded ${this.categories.length} categories`);
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load categories:', error);
|
||||
}
|
||||
},
|
||||
|
||||
groupFeaturesByCategory() {
|
||||
this.featuresGrouped = {};
|
||||
for (const category of this.categories) {
|
||||
@@ -263,18 +246,22 @@ function adminSubscriptionTiers() {
|
||||
this.selectedTierForFeatures = tier;
|
||||
this.loadingFeatures = true;
|
||||
this.showFeaturePanel = true;
|
||||
this.featureLimits = {};
|
||||
|
||||
try {
|
||||
// Load tier's current features
|
||||
const data = await apiClient.get(`/admin/features/tiers/${tier.code}/features`);
|
||||
if (data.features) {
|
||||
this.selectedFeatures = data.features.map(f => f.code);
|
||||
} else {
|
||||
this.selectedFeatures = tier.features || [];
|
||||
// Load tier's current feature limits
|
||||
const data = await apiClient.get(`/admin/subscriptions/features/tiers/${tier.code}/limits`);
|
||||
// data is TierFeatureLimitEntry[]: [{feature_code, limit_value, enabled}]
|
||||
this.selectedFeatures = [];
|
||||
for (const entry of (data || [])) {
|
||||
this.selectedFeatures.push(entry.feature_code);
|
||||
if (entry.limit_value !== null && entry.limit_value !== undefined) {
|
||||
this.featureLimits[entry.feature_code] = entry.limit_value;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load tier features:', error);
|
||||
this.selectedFeatures = tier.features || [];
|
||||
this.selectedFeatures = tier.feature_codes || tier.features || [];
|
||||
} finally {
|
||||
this.groupFeaturesByCategory();
|
||||
this.loadingFeatures = false;
|
||||
@@ -285,6 +272,7 @@ function adminSubscriptionTiers() {
|
||||
this.showFeaturePanel = false;
|
||||
this.selectedTierForFeatures = null;
|
||||
this.selectedFeatures = [];
|
||||
this.featureLimits = {};
|
||||
this.featuresGrouped = {};
|
||||
},
|
||||
|
||||
@@ -308,9 +296,16 @@ function adminSubscriptionTiers() {
|
||||
this.savingFeatures = true;
|
||||
|
||||
try {
|
||||
// Build TierFeatureLimitEntry[] payload
|
||||
const entries = this.selectedFeatures.map(code => ({
|
||||
feature_code: code,
|
||||
limit_value: this.featureLimits[code] ?? null,
|
||||
enabled: true
|
||||
}));
|
||||
|
||||
await apiClient.put(
|
||||
`/admin/features/tiers/${this.selectedTierForFeatures.code}/features`,
|
||||
{ feature_codes: this.selectedFeatures }
|
||||
`/admin/subscriptions/features/tiers/${this.selectedTierForFeatures.code}/limits`,
|
||||
entries
|
||||
);
|
||||
|
||||
this.successMessage = `Features updated for ${this.selectedTierForFeatures.name}`;
|
||||
@@ -345,6 +340,18 @@ function adminSubscriptionTiers() {
|
||||
return categoryFeatures.every(f => this.selectedFeatures.includes(f.code));
|
||||
},
|
||||
|
||||
getFeatureLimitValue(featureCode) {
|
||||
return this.featureLimits[featureCode] ?? '';
|
||||
},
|
||||
|
||||
setFeatureLimitValue(featureCode, value) {
|
||||
if (value === '' || value === null || value === undefined) {
|
||||
delete this.featureLimits[featureCode];
|
||||
} else {
|
||||
this.featureLimits[featureCode] = parseInt(value, 10);
|
||||
}
|
||||
},
|
||||
|
||||
formatCategoryName(category) {
|
||||
return category
|
||||
.split('_')
|
||||
|
||||
@@ -39,7 +39,7 @@ function adminSubscriptions() {
|
||||
},
|
||||
|
||||
// Sorting
|
||||
sortBy: 'vendor_name',
|
||||
sortBy: 'store_name',
|
||||
sortOrder: 'asc',
|
||||
|
||||
// Modal state
|
||||
@@ -47,12 +47,14 @@ function adminSubscriptions() {
|
||||
editingSub: null,
|
||||
formData: {
|
||||
tier: '',
|
||||
status: '',
|
||||
custom_orders_limit: null,
|
||||
custom_products_limit: null,
|
||||
custom_team_limit: null
|
||||
status: ''
|
||||
},
|
||||
|
||||
// Feature overrides
|
||||
featureOverrides: [],
|
||||
quantitativeFeatures: [],
|
||||
loadingOverrides: false,
|
||||
|
||||
// Computed: Total pages
|
||||
get totalPages() {
|
||||
return this.pagination.pages;
|
||||
@@ -203,16 +205,18 @@ function adminSubscriptions() {
|
||||
}
|
||||
},
|
||||
|
||||
openEditModal(sub) {
|
||||
async openEditModal(sub) {
|
||||
this.editingSub = sub;
|
||||
this.formData = {
|
||||
tier: sub.tier,
|
||||
status: sub.status,
|
||||
custom_orders_limit: sub.custom_orders_limit,
|
||||
custom_products_limit: sub.custom_products_limit,
|
||||
custom_team_limit: sub.custom_team_limit
|
||||
status: sub.status
|
||||
};
|
||||
this.featureOverrides = [];
|
||||
this.quantitativeFeatures = [];
|
||||
this.showModal = true;
|
||||
|
||||
// Load feature catalog and merchant overrides
|
||||
await this.loadFeatureOverrides(sub.merchant_id);
|
||||
},
|
||||
|
||||
closeModal() {
|
||||
@@ -220,6 +224,77 @@ function adminSubscriptions() {
|
||||
this.editingSub = null;
|
||||
},
|
||||
|
||||
async loadFeatureOverrides(merchantId) {
|
||||
this.loadingOverrides = true;
|
||||
try {
|
||||
const [catalogData, overridesData] = await Promise.all([
|
||||
apiClient.get('/admin/subscriptions/features/catalog'),
|
||||
apiClient.get(`/admin/subscriptions/features/merchants/${merchantId}/overrides`),
|
||||
]);
|
||||
|
||||
// Extract quantitative features from catalog
|
||||
const allFeatures = [];
|
||||
for (const [, features] of Object.entries(catalogData.features || {})) {
|
||||
for (const f of features) {
|
||||
if (f.feature_type === 'quantitative') {
|
||||
allFeatures.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.quantitativeFeatures = allFeatures;
|
||||
|
||||
// Map overrides by feature_code
|
||||
this.featureOverrides = (overridesData || []).map(o => ({
|
||||
feature_code: o.feature_code,
|
||||
limit_value: o.limit_value,
|
||||
is_enabled: o.is_enabled
|
||||
}));
|
||||
|
||||
subsLog.info(`Loaded ${allFeatures.length} quantitative features and ${this.featureOverrides.length} overrides`);
|
||||
} catch (error) {
|
||||
subsLog.error('Failed to load feature overrides:', error);
|
||||
} finally {
|
||||
this.loadingOverrides = false;
|
||||
}
|
||||
},
|
||||
|
||||
getOverrideValue(featureCode) {
|
||||
const override = this.featureOverrides.find(o => o.feature_code === featureCode);
|
||||
return override?.limit_value ?? '';
|
||||
},
|
||||
|
||||
setOverrideValue(featureCode, value) {
|
||||
const numValue = value === '' ? null : parseInt(value, 10);
|
||||
const existing = this.featureOverrides.find(o => o.feature_code === featureCode);
|
||||
if (existing) {
|
||||
existing.limit_value = numValue;
|
||||
} else if (numValue !== null) {
|
||||
this.featureOverrides.push({
|
||||
feature_code: featureCode,
|
||||
limit_value: numValue,
|
||||
is_enabled: true
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
async saveFeatureOverrides(merchantId) {
|
||||
// Only send overrides that have a limit_value set
|
||||
const entries = this.featureOverrides
|
||||
.filter(o => o.limit_value !== null && o.limit_value !== undefined)
|
||||
.map(o => ({
|
||||
feature_code: o.feature_code,
|
||||
limit_value: o.limit_value,
|
||||
is_enabled: true
|
||||
}));
|
||||
|
||||
if (entries.length > 0) {
|
||||
await apiClient.put(
|
||||
`/admin/subscriptions/features/merchants/${merchantId}/overrides`,
|
||||
entries
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
async saveSubscription() {
|
||||
if (!this.editingSub) return;
|
||||
|
||||
@@ -227,14 +302,17 @@ function adminSubscriptions() {
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
// Clean up null values for empty strings
|
||||
const payload = { ...this.formData };
|
||||
if (payload.custom_orders_limit === '') payload.custom_orders_limit = null;
|
||||
if (payload.custom_products_limit === '') payload.custom_products_limit = null;
|
||||
if (payload.custom_team_limit === '') payload.custom_team_limit = null;
|
||||
|
||||
await apiClient.patch(`/admin/subscriptions/${this.editingSub.vendor_id}`, payload);
|
||||
this.successMessage = `Subscription for "${this.editingSub.vendor_name}" updated`;
|
||||
await apiClient.patch(
|
||||
`/admin/subscriptions/merchants/${this.editingSub.merchant_id}/platforms/${this.editingSub.platform_id}`,
|
||||
payload
|
||||
);
|
||||
|
||||
// Save feature overrides
|
||||
await this.saveFeatureOverrides(this.editingSub.merchant_id);
|
||||
|
||||
this.successMessage = `Subscription for "${this.editingSub.store_name || this.editingSub.merchant_name}" updated`;
|
||||
|
||||
this.closeModal();
|
||||
await this.loadSubscriptions();
|
||||
|
||||
217
app/modules/billing/static/store/js/billing.js
Normal file
217
app/modules/billing/static/store/js/billing.js
Normal file
@@ -0,0 +1,217 @@
|
||||
// app/modules/billing/static/store/js/billing.js
|
||||
// Store billing and subscription management
|
||||
|
||||
const billingLog = window.LogConfig?.createLogger('BILLING') || console;
|
||||
|
||||
function storeBilling() {
|
||||
return {
|
||||
// Inherit base data (dark mode, sidebar, store info, etc.)
|
||||
...data(),
|
||||
currentPage: 'billing',
|
||||
|
||||
// State
|
||||
loading: true,
|
||||
subscription: null,
|
||||
tiers: [],
|
||||
addons: [],
|
||||
myAddons: [],
|
||||
invoices: [],
|
||||
usageMetrics: [],
|
||||
|
||||
// UI state
|
||||
showTiersModal: false,
|
||||
showAddonsModal: false,
|
||||
showCancelModal: false,
|
||||
showSuccessMessage: false,
|
||||
showCancelMessage: false,
|
||||
showAddonSuccessMessage: false,
|
||||
cancelReason: '',
|
||||
purchasingAddon: null,
|
||||
|
||||
// Initialize
|
||||
async init() {
|
||||
// Load i18n translations
|
||||
await I18n.loadModule('billing');
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._storeBillingInitialized) return;
|
||||
window._storeBillingInitialized = true;
|
||||
|
||||
// IMPORTANT: Call parent init first to set storeCode from URL
|
||||
const parentInit = data().init;
|
||||
if (parentInit) {
|
||||
await parentInit.call(this);
|
||||
}
|
||||
|
||||
try {
|
||||
// Check URL params for success/cancel
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (params.get('success') === 'true') {
|
||||
this.showSuccessMessage = true;
|
||||
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();
|
||||
} catch (error) {
|
||||
billingLog.error('Failed to initialize billing page:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async loadData() {
|
||||
this.loading = true;
|
||||
try {
|
||||
// Load all data in parallel
|
||||
const [subscriptionRes, tiersRes, addonsRes, myAddonsRes, invoicesRes, usageRes] = await Promise.all([
|
||||
apiClient.get('/store/billing/subscription'),
|
||||
apiClient.get('/store/billing/tiers'),
|
||||
apiClient.get('/store/billing/addons'),
|
||||
apiClient.get('/store/billing/my-addons'),
|
||||
apiClient.get('/store/billing/invoices?limit=5'),
|
||||
apiClient.get('/store/billing/usage').catch(() => ({ usage: [] })),
|
||||
]);
|
||||
|
||||
this.subscription = subscriptionRes;
|
||||
this.tiers = tiersRes.tiers || [];
|
||||
this.addons = addonsRes || [];
|
||||
this.myAddons = myAddonsRes || [];
|
||||
this.invoices = invoicesRes.invoices || [];
|
||||
this.usageMetrics = usageRes.usage || usageRes || [];
|
||||
|
||||
} catch (error) {
|
||||
billingLog.error('Error loading billing data:', error);
|
||||
Utils.showToast(I18n.t('billing.messages.failed_to_load_billing_data'), 'error');
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async selectTier(tier) {
|
||||
if (tier.is_current) return;
|
||||
|
||||
try {
|
||||
const response = await apiClient.post('/store/billing/checkout', {
|
||||
tier_code: tier.code,
|
||||
is_annual: false
|
||||
});
|
||||
|
||||
if (response.checkout_url) {
|
||||
window.location.href = response.checkout_url;
|
||||
}
|
||||
} catch (error) {
|
||||
billingLog.error('Error creating checkout:', error);
|
||||
Utils.showToast(I18n.t('billing.messages.failed_to_create_checkout_session'), 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async openPortal() {
|
||||
try {
|
||||
const response = await apiClient.post('/store/billing/portal', {});
|
||||
if (response.portal_url) {
|
||||
window.location.href = response.portal_url;
|
||||
}
|
||||
} catch (error) {
|
||||
billingLog.error('Error opening portal:', error);
|
||||
Utils.showToast(I18n.t('billing.messages.failed_to_open_payment_portal'), 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async cancelSubscription() {
|
||||
try {
|
||||
await apiClient.post('/store/billing/cancel', {
|
||||
reason: this.cancelReason,
|
||||
immediately: false
|
||||
});
|
||||
|
||||
this.showCancelModal = false;
|
||||
Utils.showToast(I18n.t('billing.messages.subscription_cancelled_you_have_access_u'), 'success');
|
||||
await this.loadData();
|
||||
|
||||
} catch (error) {
|
||||
billingLog.error('Error cancelling subscription:', error);
|
||||
Utils.showToast(I18n.t('billing.messages.failed_to_cancel_subscription'), 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async reactivate() {
|
||||
try {
|
||||
await apiClient.post('/store/billing/reactivate', {});
|
||||
Utils.showToast(I18n.t('billing.messages.subscription_reactivated'), 'success');
|
||||
await this.loadData();
|
||||
|
||||
} catch (error) {
|
||||
billingLog.error('Error reactivating subscription:', error);
|
||||
Utils.showToast(I18n.t('billing.messages.failed_to_reactivate_subscription'), 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async purchaseAddon(addon) {
|
||||
this.purchasingAddon = addon.code;
|
||||
try {
|
||||
const response = await apiClient.post('/store/billing/addons/purchase', {
|
||||
addon_code: addon.code,
|
||||
quantity: 1
|
||||
});
|
||||
|
||||
if (response.checkout_url) {
|
||||
window.location.href = response.checkout_url;
|
||||
}
|
||||
} catch (error) {
|
||||
billingLog.error('Error purchasing addon:', error);
|
||||
Utils.showToast(I18n.t('billing.messages.failed_to_purchase_addon'), 'error');
|
||||
} finally {
|
||||
this.purchasingAddon = null;
|
||||
}
|
||||
},
|
||||
|
||||
async cancelAddon(addon) {
|
||||
if (!confirm(`Are you sure you want to cancel ${addon.addon_name}?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await apiClient.delete(`/store/billing/addons/${addon.id}`);
|
||||
Utils.showToast(I18n.t('billing.messages.addon_cancelled_successfully'), 'success');
|
||||
await this.loadData();
|
||||
} catch (error) {
|
||||
billingLog.error('Error cancelling addon:', error);
|
||||
Utils.showToast(I18n.t('billing.messages.failed_to_cancel_addon'), 'error');
|
||||
}
|
||||
},
|
||||
|
||||
// Check if addon is already purchased
|
||||
isAddonPurchased(addonCode) {
|
||||
return this.myAddons.some(a => a.addon_code === addonCode && a.status === 'active');
|
||||
},
|
||||
|
||||
// Formatters
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return '-';
|
||||
const date = new Date(dateString);
|
||||
const locale = window.STORE_CONFIG?.locale || 'en-GB';
|
||||
return date.toLocaleDateString(locale, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
},
|
||||
|
||||
formatCurrency(cents, currency = 'EUR') {
|
||||
if (cents === null || cents === undefined) return '-';
|
||||
const amount = cents / 100;
|
||||
const locale = window.STORE_CONFIG?.locale || 'en-GB';
|
||||
const currencyCode = window.STORE_CONFIG?.currency || currency;
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency: currencyCode
|
||||
}).format(amount);
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user