refactor(js): migrate JavaScript files to module directories
Move 47 JS files from static/{admin,vendor,shared}/js/ to their
respective module directories app/modules/*/static/*/js/:
- Orders: orders.js, order-detail.js
- Catalog: products.js (renamed from vendor-products.js), product-*.js
- Inventory: inventory.js (admin & vendor)
- Customers: customers.js, users.js, user-*.js
- Billing: billing-history.js, subscriptions.js, subscription-tiers.js,
billing.js, invoices.js, feature-store.js, upgrade-prompts.js
- Messaging: messages.js, notifications.js, email-templates.js
- Marketplace: marketplace*.js, letzshop*.js, onboarding.js
- Monitoring: monitoring.js, background-tasks.js, imports.js, logs.js
- Dev Tools: testing-*.js, code-quality-*.js
Update 39 templates to reference new module static paths using
url_for('{module}_static', path='...') pattern.
Files staying in static/ (platform core):
- admin: dashboard, login, platforms, vendors, companies, admin-users,
settings, components, init-alpine, module-config
- vendor: dashboard, login, profile, settings, team, media, init-alpine
- shared: api-client, utils, money, icons, log-config, vendor-selector,
media-picker
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
238
app/modules/billing/static/admin/js/billing-history.js
Normal file
238
app/modules/billing/static/admin/js/billing-history.js
Normal file
@@ -0,0 +1,238 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/billing-history.js
|
||||
// noqa: JS-003 - Uses ...baseData which is data() with safety check
|
||||
|
||||
const billingLog = window.LogConfig?.loggers?.billingHistory || console;
|
||||
|
||||
function adminBillingHistory() {
|
||||
// Get base data with safety check for standalone usage
|
||||
const baseData = typeof data === 'function' ? data() : {};
|
||||
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...baseData,
|
||||
|
||||
// Page-specific state
|
||||
currentPage: 'billing-history',
|
||||
loading: true,
|
||||
error: null,
|
||||
successMessage: null,
|
||||
|
||||
// Data
|
||||
invoices: [],
|
||||
vendors: [],
|
||||
statusCounts: {
|
||||
paid: 0,
|
||||
open: 0,
|
||||
draft: 0,
|
||||
uncollectible: 0,
|
||||
void: 0
|
||||
},
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
vendor_id: '',
|
||||
status: ''
|
||||
},
|
||||
|
||||
// Pagination
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Sorting
|
||||
sortBy: 'invoice_date',
|
||||
sortOrder: 'desc',
|
||||
|
||||
// Computed: Total pages
|
||||
get totalPages() {
|
||||
return this.pagination.pages;
|
||||
},
|
||||
|
||||
// Computed: Start index for pagination display
|
||||
get startIndex() {
|
||||
if (this.pagination.total === 0) return 0;
|
||||
return (this.pagination.page - 1) * this.pagination.per_page + 1;
|
||||
},
|
||||
|
||||
// Computed: End index for pagination display
|
||||
get endIndex() {
|
||||
const end = this.pagination.page * this.pagination.per_page;
|
||||
return end > this.pagination.total ? this.pagination.total : end;
|
||||
},
|
||||
|
||||
// Computed: Page numbers for pagination
|
||||
get pageNumbers() {
|
||||
const pages = [];
|
||||
const totalPages = this.totalPages;
|
||||
const current = this.pagination.page;
|
||||
|
||||
if (totalPages <= 7) {
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
pages.push(1);
|
||||
if (current > 3) {
|
||||
pages.push('...');
|
||||
}
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(totalPages - 1, current + 1);
|
||||
for (let i = start; i <= end; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
if (current < totalPages - 2) {
|
||||
pages.push('...');
|
||||
}
|
||||
pages.push(totalPages);
|
||||
}
|
||||
return pages;
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminBillingHistoryInitialized) {
|
||||
billingLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminBillingHistoryInitialized = true;
|
||||
|
||||
billingLog.info('=== BILLING HISTORY PAGE INITIALIZING ===');
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
await this.loadVendors();
|
||||
await this.loadInvoices();
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
this.error = null;
|
||||
this.successMessage = null;
|
||||
await this.loadInvoices();
|
||||
},
|
||||
|
||||
async loadVendors() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/vendors?limit=1000');
|
||||
this.vendors = data.vendors || [];
|
||||
billingLog.info(`Loaded ${this.vendors.length} vendors for filter`);
|
||||
} catch (error) {
|
||||
billingLog.error('Failed to load vendors:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async loadInvoices() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', this.pagination.page);
|
||||
params.append('per_page', this.pagination.per_page);
|
||||
if (this.filters.vendor_id) params.append('vendor_id', this.filters.vendor_id);
|
||||
if (this.filters.status) params.append('status', this.filters.status);
|
||||
if (this.sortBy) params.append('sort_by', this.sortBy);
|
||||
if (this.sortOrder) params.append('sort_order', this.sortOrder);
|
||||
|
||||
const data = await apiClient.get(`/admin/subscriptions/billing/history?${params}`);
|
||||
this.invoices = data.invoices || [];
|
||||
this.pagination.total = data.total;
|
||||
this.pagination.pages = data.pages;
|
||||
|
||||
// Count by status (from loaded data for approximation)
|
||||
this.updateStatusCounts();
|
||||
|
||||
billingLog.info(`Loaded ${this.invoices.length} invoices (total: ${this.pagination.total})`);
|
||||
} catch (error) {
|
||||
billingLog.error('Failed to load invoices:', error);
|
||||
this.error = error.message || 'Failed to load billing history';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
handleSort(key) {
|
||||
if (this.sortBy === key) {
|
||||
this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
this.sortBy = key;
|
||||
this.sortOrder = 'asc';
|
||||
}
|
||||
this.pagination.page = 1;
|
||||
this.loadInvoices();
|
||||
},
|
||||
|
||||
updateStatusCounts() {
|
||||
// Reset counts
|
||||
this.statusCounts = {
|
||||
paid: 0,
|
||||
open: 0,
|
||||
draft: 0,
|
||||
uncollectible: 0,
|
||||
void: 0
|
||||
};
|
||||
|
||||
// Count from current page (approximation)
|
||||
for (const invoice of this.invoices) {
|
||||
if (this.statusCounts[invoice.status] !== undefined) {
|
||||
this.statusCounts[invoice.status]++;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
resetFilters() {
|
||||
this.filters = {
|
||||
vendor_id: '',
|
||||
status: ''
|
||||
};
|
||||
this.pagination.page = 1;
|
||||
this.loadInvoices();
|
||||
},
|
||||
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
this.loadInvoices();
|
||||
}
|
||||
},
|
||||
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.totalPages) {
|
||||
this.pagination.page++;
|
||||
this.loadInvoices();
|
||||
}
|
||||
},
|
||||
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadInvoices();
|
||||
}
|
||||
},
|
||||
|
||||
formatDate(dateStr) {
|
||||
if (!dateStr) return '-';
|
||||
return new Date(dateStr).toLocaleDateString('de-LU', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
},
|
||||
|
||||
formatCurrency(cents) {
|
||||
if (cents === null || cents === undefined) return '-';
|
||||
return new Intl.NumberFormat('de-LU', {
|
||||
style: 'currency',
|
||||
currency: 'EUR'
|
||||
}).format(cents / 100);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
billingLog.info('Billing history module loaded');
|
||||
357
app/modules/billing/static/admin/js/subscription-tiers.js
Normal file
357
app/modules/billing/static/admin/js/subscription-tiers.js
Normal file
@@ -0,0 +1,357 @@
|
||||
// app/modules/billing/static/admin/js/subscription-tiers.js
|
||||
// noqa: JS-003 - Uses ...baseData which is data() with safety check
|
||||
|
||||
const tiersLog = window.LogConfig?.loggers?.subscriptionTiers || window.LogConfig?.createLogger?.('subscriptionTiers') || console;
|
||||
|
||||
function adminSubscriptionTiers() {
|
||||
// Get base data with safety check for standalone usage
|
||||
const baseData = typeof data === 'function' ? data() : {};
|
||||
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...baseData,
|
||||
|
||||
// Page-specific state
|
||||
currentPage: 'subscription-tiers',
|
||||
loading: true,
|
||||
error: null,
|
||||
successMessage: null,
|
||||
saving: false,
|
||||
|
||||
// Data
|
||||
tiers: [],
|
||||
stats: null,
|
||||
includeInactive: false,
|
||||
|
||||
// Feature management
|
||||
features: [],
|
||||
categories: [],
|
||||
featuresGrouped: {},
|
||||
selectedFeatures: [],
|
||||
selectedTierForFeatures: null,
|
||||
showFeaturePanel: false,
|
||||
loadingFeatures: false,
|
||||
savingFeatures: false,
|
||||
|
||||
// Sorting
|
||||
sortBy: 'display_order',
|
||||
sortOrder: 'asc',
|
||||
|
||||
// Modal state
|
||||
showModal: false,
|
||||
editingTier: null,
|
||||
formData: {
|
||||
code: '',
|
||||
name: '',
|
||||
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
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminSubscriptionTiersInitialized) {
|
||||
tiersLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminSubscriptionTiersInitialized = true;
|
||||
|
||||
tiersLog.info('=== SUBSCRIPTION TIERS PAGE INITIALIZING ===');
|
||||
try {
|
||||
await Promise.all([
|
||||
this.loadTiers(),
|
||||
this.loadStats(),
|
||||
this.loadFeatures(),
|
||||
this.loadCategories()
|
||||
]);
|
||||
tiersLog.info('=== SUBSCRIPTION TIERS PAGE INITIALIZED ===');
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to initialize subscription tiers page:', error);
|
||||
this.error = 'Failed to load page data. Please refresh.';
|
||||
}
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
this.error = null;
|
||||
this.successMessage = null;
|
||||
await this.loadTiers();
|
||||
await this.loadStats();
|
||||
},
|
||||
|
||||
async loadTiers() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.append('include_inactive', this.includeInactive);
|
||||
if (this.sortBy) params.append('sort_by', this.sortBy);
|
||||
if (this.sortOrder) params.append('sort_order', this.sortOrder);
|
||||
|
||||
const data = await apiClient.get(`/admin/subscriptions/tiers?${params}`);
|
||||
this.tiers = data.tiers || [];
|
||||
tiersLog.info(`Loaded ${this.tiers.length} tiers`);
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load tiers:', error);
|
||||
this.error = error.message || 'Failed to load subscription tiers';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
handleSort(key) {
|
||||
if (this.sortBy === key) {
|
||||
this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
this.sortBy = key;
|
||||
this.sortOrder = 'asc';
|
||||
}
|
||||
this.loadTiers();
|
||||
},
|
||||
|
||||
async loadStats() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/subscriptions/stats');
|
||||
this.stats = data;
|
||||
tiersLog.info('Loaded subscription stats');
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load stats:', error);
|
||||
// Non-critical, don't show error
|
||||
}
|
||||
},
|
||||
|
||||
openCreateModal() {
|
||||
this.editingTier = null;
|
||||
this.formData = {
|
||||
code: '',
|
||||
name: '',
|
||||
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
|
||||
};
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
openEditModal(tier) {
|
||||
this.editingTier = tier;
|
||||
this.formData = {
|
||||
code: tier.code,
|
||||
name: tier.name,
|
||||
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
|
||||
};
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
closeModal() {
|
||||
this.showModal = false;
|
||||
this.editingTier = null;
|
||||
},
|
||||
|
||||
async saveTier() {
|
||||
this.saving = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
// 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
|
||||
await apiClient.patch(`/admin/subscriptions/tiers/${this.editingTier.code}`, payload);
|
||||
this.successMessage = `Tier "${payload.name}" updated successfully`;
|
||||
} else {
|
||||
// Create new tier
|
||||
await apiClient.post('/admin/subscriptions/tiers', payload);
|
||||
this.successMessage = `Tier "${payload.name}" created successfully`;
|
||||
}
|
||||
|
||||
this.closeModal();
|
||||
await this.loadTiers();
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to save tier:', error);
|
||||
this.error = error.message || 'Failed to save tier';
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
async toggleTierStatus(tier, activate) {
|
||||
try {
|
||||
await apiClient.patch(`/admin/subscriptions/tiers/${tier.code}`, {
|
||||
is_active: activate
|
||||
});
|
||||
this.successMessage = `Tier "${tier.name}" ${activate ? 'activated' : 'deactivated'}`;
|
||||
await this.loadTiers();
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to toggle tier status:', error);
|
||||
this.error = error.message || 'Failed to update tier';
|
||||
}
|
||||
},
|
||||
|
||||
formatCurrency(cents) {
|
||||
if (cents === null || cents === undefined) return '-';
|
||||
return new Intl.NumberFormat('de-LU', {
|
||||
style: 'currency',
|
||||
currency: 'EUR'
|
||||
}).format(cents / 100);
|
||||
},
|
||||
|
||||
// ==================== FEATURE MANAGEMENT ====================
|
||||
|
||||
async loadFeatures() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/features');
|
||||
this.features = data.features || [];
|
||||
tiersLog.info(`Loaded ${this.features.length} features`);
|
||||
} 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) {
|
||||
this.featuresGrouped[category] = this.features.filter(f => f.category === category);
|
||||
}
|
||||
},
|
||||
|
||||
async openFeaturePanel(tier) {
|
||||
tiersLog.info('Opening feature panel for tier:', tier.code);
|
||||
this.selectedTierForFeatures = tier;
|
||||
this.loadingFeatures = true;
|
||||
this.showFeaturePanel = true;
|
||||
|
||||
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 || [];
|
||||
}
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load tier features:', error);
|
||||
this.selectedFeatures = tier.features || [];
|
||||
} finally {
|
||||
this.groupFeaturesByCategory();
|
||||
this.loadingFeatures = false;
|
||||
}
|
||||
},
|
||||
|
||||
closeFeaturePanel() {
|
||||
this.showFeaturePanel = false;
|
||||
this.selectedTierForFeatures = null;
|
||||
this.selectedFeatures = [];
|
||||
this.featuresGrouped = {};
|
||||
},
|
||||
|
||||
toggleFeature(featureCode) {
|
||||
const index = this.selectedFeatures.indexOf(featureCode);
|
||||
if (index === -1) {
|
||||
this.selectedFeatures.push(featureCode);
|
||||
} else {
|
||||
this.selectedFeatures.splice(index, 1);
|
||||
}
|
||||
},
|
||||
|
||||
isFeatureSelected(featureCode) {
|
||||
return this.selectedFeatures.includes(featureCode);
|
||||
},
|
||||
|
||||
async saveFeatures() {
|
||||
if (!this.selectedTierForFeatures) return;
|
||||
|
||||
tiersLog.info('Saving features for tier:', this.selectedTierForFeatures.code);
|
||||
this.savingFeatures = true;
|
||||
|
||||
try {
|
||||
await apiClient.put(
|
||||
`/admin/features/tiers/${this.selectedTierForFeatures.code}/features`,
|
||||
{ feature_codes: this.selectedFeatures }
|
||||
);
|
||||
|
||||
this.successMessage = `Features updated for ${this.selectedTierForFeatures.name}`;
|
||||
this.closeFeaturePanel();
|
||||
await this.loadTiers();
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to save features:', error);
|
||||
this.error = error.message || 'Failed to save features';
|
||||
} finally {
|
||||
this.savingFeatures = false;
|
||||
}
|
||||
},
|
||||
|
||||
selectAllInCategory(category) {
|
||||
const categoryFeatures = this.featuresGrouped[category] || [];
|
||||
for (const feature of categoryFeatures) {
|
||||
if (!this.selectedFeatures.includes(feature.code)) {
|
||||
this.selectedFeatures.push(feature.code);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
deselectAllInCategory(category) {
|
||||
const categoryFeatures = this.featuresGrouped[category] || [];
|
||||
const codes = categoryFeatures.map(f => f.code);
|
||||
this.selectedFeatures = this.selectedFeatures.filter(c => !codes.includes(c));
|
||||
},
|
||||
|
||||
allSelectedInCategory(category) {
|
||||
const categoryFeatures = this.featuresGrouped[category] || [];
|
||||
if (categoryFeatures.length === 0) return false;
|
||||
return categoryFeatures.every(f => this.selectedFeatures.includes(f.code));
|
||||
},
|
||||
|
||||
formatCategoryName(category) {
|
||||
return category
|
||||
.split('_')
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
tiersLog.info('Subscription tiers module loaded');
|
||||
269
app/modules/billing/static/admin/js/subscriptions.js
Normal file
269
app/modules/billing/static/admin/js/subscriptions.js
Normal file
@@ -0,0 +1,269 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/subscriptions.js
|
||||
// noqa: JS-003 - Uses ...baseData which is data() with safety check
|
||||
|
||||
const subsLog = window.LogConfig?.loggers?.subscriptions || console;
|
||||
|
||||
function adminSubscriptions() {
|
||||
// Get base data with safety check for standalone usage
|
||||
const baseData = typeof data === 'function' ? data() : {};
|
||||
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...baseData,
|
||||
|
||||
// Page-specific state
|
||||
currentPage: 'subscriptions',
|
||||
loading: true,
|
||||
error: null,
|
||||
successMessage: null,
|
||||
saving: false,
|
||||
|
||||
// Data
|
||||
subscriptions: [],
|
||||
stats: null,
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
search: '',
|
||||
status: '',
|
||||
tier: ''
|
||||
},
|
||||
|
||||
// Pagination
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Sorting
|
||||
sortBy: 'vendor_name',
|
||||
sortOrder: 'asc',
|
||||
|
||||
// Modal state
|
||||
showModal: false,
|
||||
editingSub: null,
|
||||
formData: {
|
||||
tier: '',
|
||||
status: '',
|
||||
custom_orders_limit: null,
|
||||
custom_products_limit: null,
|
||||
custom_team_limit: null
|
||||
},
|
||||
|
||||
// Computed: Total pages
|
||||
get totalPages() {
|
||||
return this.pagination.pages;
|
||||
},
|
||||
|
||||
// Computed: Start index for pagination display
|
||||
get startIndex() {
|
||||
if (this.pagination.total === 0) return 0;
|
||||
return (this.pagination.page - 1) * this.pagination.per_page + 1;
|
||||
},
|
||||
|
||||
// Computed: End index for pagination display
|
||||
get endIndex() {
|
||||
const end = this.pagination.page * this.pagination.per_page;
|
||||
return end > this.pagination.total ? this.pagination.total : end;
|
||||
},
|
||||
|
||||
// Computed: Page numbers for pagination
|
||||
get pageNumbers() {
|
||||
const pages = [];
|
||||
const totalPages = this.totalPages;
|
||||
const current = this.pagination.page;
|
||||
|
||||
if (totalPages <= 7) {
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
pages.push(1);
|
||||
if (current > 3) {
|
||||
pages.push('...');
|
||||
}
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(totalPages - 1, current + 1);
|
||||
for (let i = start; i <= end; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
if (current < totalPages - 2) {
|
||||
pages.push('...');
|
||||
}
|
||||
pages.push(totalPages);
|
||||
}
|
||||
return pages;
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminSubscriptionsInitialized) {
|
||||
subsLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminSubscriptionsInitialized = true;
|
||||
|
||||
subsLog.info('=== SUBSCRIPTIONS PAGE INITIALIZING ===');
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
await this.loadStats();
|
||||
await this.loadSubscriptions();
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
this.error = null;
|
||||
this.successMessage = null;
|
||||
await this.loadStats();
|
||||
await this.loadSubscriptions();
|
||||
},
|
||||
|
||||
async loadStats() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/subscriptions/stats');
|
||||
this.stats = data;
|
||||
subsLog.info('Loaded subscription stats');
|
||||
} catch (error) {
|
||||
subsLog.error('Failed to load stats:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async loadSubscriptions() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', this.pagination.page);
|
||||
params.append('per_page', this.pagination.per_page);
|
||||
if (this.filters.status) params.append('status', this.filters.status);
|
||||
if (this.filters.tier) params.append('tier', this.filters.tier);
|
||||
if (this.filters.search) params.append('search', this.filters.search);
|
||||
if (this.sortBy) params.append('sort_by', this.sortBy);
|
||||
if (this.sortOrder) params.append('sort_order', this.sortOrder);
|
||||
|
||||
const data = await apiClient.get(`/admin/subscriptions?${params}`);
|
||||
this.subscriptions = data.subscriptions || [];
|
||||
this.pagination.total = data.total;
|
||||
this.pagination.pages = data.pages;
|
||||
subsLog.info(`Loaded ${this.subscriptions.length} subscriptions (total: ${this.pagination.total})`);
|
||||
} catch (error) {
|
||||
subsLog.error('Failed to load subscriptions:', error);
|
||||
this.error = error.message || 'Failed to load subscriptions';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
resetFilters() {
|
||||
this.filters = {
|
||||
search: '',
|
||||
status: '',
|
||||
tier: ''
|
||||
};
|
||||
this.pagination.page = 1;
|
||||
this.loadSubscriptions();
|
||||
},
|
||||
|
||||
handleSort(key) {
|
||||
if (this.sortBy === key) {
|
||||
this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
this.sortBy = key;
|
||||
this.sortOrder = 'asc';
|
||||
}
|
||||
this.pagination.page = 1;
|
||||
this.loadSubscriptions();
|
||||
},
|
||||
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
this.loadSubscriptions();
|
||||
}
|
||||
},
|
||||
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.totalPages) {
|
||||
this.pagination.page++;
|
||||
this.loadSubscriptions();
|
||||
}
|
||||
},
|
||||
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadSubscriptions();
|
||||
}
|
||||
},
|
||||
|
||||
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
|
||||
};
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
closeModal() {
|
||||
this.showModal = false;
|
||||
this.editingSub = null;
|
||||
},
|
||||
|
||||
async saveSubscription() {
|
||||
if (!this.editingSub) return;
|
||||
|
||||
this.saving = true;
|
||||
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`;
|
||||
|
||||
this.closeModal();
|
||||
await this.loadSubscriptions();
|
||||
await this.loadStats();
|
||||
} catch (error) {
|
||||
subsLog.error('Failed to save subscription:', error);
|
||||
this.error = error.message || 'Failed to update subscription';
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
formatDate(dateStr) {
|
||||
if (!dateStr) return '-';
|
||||
return new Date(dateStr).toLocaleDateString('de-LU', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
},
|
||||
|
||||
formatCurrency(cents) {
|
||||
if (cents === null || cents === undefined) return '-';
|
||||
return new Intl.NumberFormat('de-LU', {
|
||||
style: 'currency',
|
||||
currency: 'EUR'
|
||||
}).format(cents / 100);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
subsLog.info('Subscriptions module loaded');
|
||||
217
app/modules/billing/static/shared/js/feature-store.js
Normal file
217
app/modules/billing/static/shared/js/feature-store.js
Normal file
@@ -0,0 +1,217 @@
|
||||
// app/modules/billing/static/shared/js/feature-store.js
|
||||
/**
|
||||
* Feature Store for Alpine.js
|
||||
*
|
||||
* Provides feature availability checking for tier-based access control.
|
||||
* Loads features from the API on init and caches them for the session.
|
||||
*
|
||||
* Usage in templates:
|
||||
*
|
||||
* 1. Check if feature is available:
|
||||
* <div x-show="$store.features.has('analytics_dashboard')">
|
||||
* Analytics content here
|
||||
* </div>
|
||||
*
|
||||
* 2. Show upgrade prompt if not available:
|
||||
* <div x-show="!$store.features.has('analytics_dashboard')">
|
||||
* <p>Upgrade to access Analytics</p>
|
||||
* </div>
|
||||
*
|
||||
* 3. Conditionally render with x-if:
|
||||
* <template x-if="$store.features.has('api_access')">
|
||||
* <a href="/settings/api">API Settings</a>
|
||||
* </template>
|
||||
*
|
||||
* 4. Use feature data for upgrade prompts:
|
||||
* <p x-text="$store.features.getUpgradeTier('analytics_dashboard')"></p>
|
||||
*
|
||||
* 5. Get current tier info:
|
||||
* <span x-text="$store.features.tierName"></span>
|
||||
*/
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// Use centralized logger if available
|
||||
const log = window.LogConfig?.log || console;
|
||||
|
||||
/**
|
||||
* Feature Store
|
||||
*/
|
||||
const featureStore = {
|
||||
// State
|
||||
features: [], // Array of feature codes available to vendor
|
||||
featuresMap: {}, // Full feature info keyed by code
|
||||
tierCode: null, // Current tier code
|
||||
tierName: null, // Current tier name
|
||||
loading: true, // Loading state
|
||||
loaded: false, // Whether features have been loaded
|
||||
error: null, // Error message if load failed
|
||||
|
||||
/**
|
||||
* Initialize the feature store
|
||||
* Called automatically when Alpine starts
|
||||
*/
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._featureStoreInitialized) return;
|
||||
window._featureStoreInitialized = true;
|
||||
|
||||
try {
|
||||
log.debug('[FeatureStore] Initializing...');
|
||||
await this.loadFeatures();
|
||||
} catch (error) {
|
||||
log.error('[FeatureStore] Failed to initialize:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load features from API
|
||||
*/
|
||||
async loadFeatures() {
|
||||
// Don't reload if already loaded
|
||||
if (this.loaded) {
|
||||
log.debug('[FeatureStore] Already loaded, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get vendor code from URL
|
||||
const vendorCode = this.getVendorCode();
|
||||
if (!vendorCode) {
|
||||
log.warn('[FeatureStore] No vendor code found in URL');
|
||||
this.loading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
// Fetch available features (lightweight endpoint)
|
||||
const response = await apiClient.get('/vendor/features/available');
|
||||
|
||||
this.features = response.features || [];
|
||||
this.tierCode = response.tier_code;
|
||||
this.tierName = response.tier_name;
|
||||
this.loaded = true;
|
||||
|
||||
log.debug(`[FeatureStore] Loaded ${this.features.length} features for ${this.tierName} tier`);
|
||||
|
||||
} catch (error) {
|
||||
log.error('[FeatureStore] Failed to load features:', error);
|
||||
this.error = error.message || 'Failed to load features';
|
||||
// Set empty array so checks don't fail
|
||||
this.features = [];
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load full feature details (with metadata)
|
||||
* Use this when you need upgrade info
|
||||
*/
|
||||
async loadFullFeatures() {
|
||||
const vendorCode = this.getVendorCode();
|
||||
if (!vendorCode) return;
|
||||
|
||||
try {
|
||||
const response = await apiClient.get('/vendor/features');
|
||||
|
||||
// Build map for quick lookup
|
||||
this.featuresMap = {};
|
||||
for (const feature of response.features) {
|
||||
this.featuresMap[feature.code] = feature;
|
||||
}
|
||||
|
||||
log.debug(`[FeatureStore] Loaded full details for ${response.features.length} features`);
|
||||
|
||||
} catch (error) {
|
||||
log.error('[FeatureStore] Failed to load full features:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if vendor has access to a feature
|
||||
* @param {string} featureCode - The feature code to check
|
||||
* @returns {boolean} - Whether the feature is available
|
||||
*/
|
||||
has(featureCode) {
|
||||
return this.features.includes(featureCode);
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if vendor has access to ANY of the given features
|
||||
* @param {...string} featureCodes - Feature codes to check
|
||||
* @returns {boolean} - Whether any feature is available
|
||||
*/
|
||||
hasAny(...featureCodes) {
|
||||
return featureCodes.some(code => this.has(code));
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if vendor has access to ALL of the given features
|
||||
* @param {...string} featureCodes - Feature codes to check
|
||||
* @returns {boolean} - Whether all features are available
|
||||
*/
|
||||
hasAll(...featureCodes) {
|
||||
return featureCodes.every(code => this.has(code));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get feature info (requires loadFullFeatures first)
|
||||
* @param {string} featureCode - The feature code
|
||||
* @returns {object|null} - Feature info or null
|
||||
*/
|
||||
getFeature(featureCode) {
|
||||
return this.featuresMap[featureCode] || null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the tier name required for a feature
|
||||
* @param {string} featureCode - The feature code
|
||||
* @returns {string|null} - Tier name or null
|
||||
*/
|
||||
getUpgradeTier(featureCode) {
|
||||
const feature = this.getFeature(featureCode);
|
||||
return feature?.minimum_tier_name || null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get vendor code from URL
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getVendorCode() {
|
||||
const path = window.location.pathname;
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
if (segments[0] === 'vendor' && segments[1]) {
|
||||
return segments[1];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Reload features (e.g., after tier change)
|
||||
*/
|
||||
async reload() {
|
||||
try {
|
||||
this.loaded = false;
|
||||
this.features = [];
|
||||
this.featuresMap = {};
|
||||
await this.loadFeatures();
|
||||
} catch (error) {
|
||||
log.error('[FeatureStore] Failed to reload:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Register Alpine store when Alpine is available
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.store('features', featureStore);
|
||||
log.debug('[FeatureStore] Registered as Alpine store');
|
||||
});
|
||||
|
||||
// Also expose globally for non-Alpine usage
|
||||
window.FeatureStore = featureStore;
|
||||
|
||||
})();
|
||||
365
app/modules/billing/static/shared/js/upgrade-prompts.js
Normal file
365
app/modules/billing/static/shared/js/upgrade-prompts.js
Normal file
@@ -0,0 +1,365 @@
|
||||
// app/modules/billing/static/shared/js/upgrade-prompts.js
|
||||
/**
|
||||
* Upgrade Prompts System
|
||||
*
|
||||
* Provides contextual upgrade prompts based on:
|
||||
* - Usage limits approaching/reached
|
||||
* - Locked features
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* 1. Initialize the store (auto-loads usage on init):
|
||||
* <div x-data x-init="$store.upgrade.loadUsage()">
|
||||
*
|
||||
* 2. Show limit warning banner:
|
||||
* <template x-if="$store.upgrade.shouldShowLimitWarning('orders')">
|
||||
* <div x-html="$store.upgrade.getLimitWarningHTML('orders')"></div>
|
||||
* </template>
|
||||
*
|
||||
* 3. Check before action:
|
||||
* <button @click="$store.upgrade.checkLimitAndProceed('products', () => createProduct())">
|
||||
* Add Product
|
||||
* </button>
|
||||
*
|
||||
* 4. Show upgrade CTA on dashboard:
|
||||
* <template x-if="$store.upgrade.hasUpgradeRecommendation">
|
||||
* <div x-html="$store.upgrade.getUpgradeCardHTML()"></div>
|
||||
* </template>
|
||||
*/
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const log = window.LogConfig?.log || console;
|
||||
|
||||
/**
|
||||
* Upgrade Prompts Store
|
||||
*/
|
||||
const upgradeStore = {
|
||||
// State
|
||||
usage: null,
|
||||
loading: false,
|
||||
loaded: false,
|
||||
error: null,
|
||||
|
||||
// Computed-like getters
|
||||
get hasLimitsApproaching() {
|
||||
return this.usage?.has_limits_approaching || false;
|
||||
},
|
||||
|
||||
get hasLimitsReached() {
|
||||
return this.usage?.has_limits_reached || false;
|
||||
},
|
||||
|
||||
get hasUpgradeRecommendation() {
|
||||
return this.usage?.upgrade_available && (this.hasLimitsApproaching || this.hasLimitsReached);
|
||||
},
|
||||
|
||||
get upgradeReasons() {
|
||||
return this.usage?.upgrade_reasons || [];
|
||||
},
|
||||
|
||||
get currentTier() {
|
||||
return this.usage?.tier || null;
|
||||
},
|
||||
|
||||
get nextTier() {
|
||||
return this.usage?.upgrade_tier || null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Load usage data from API
|
||||
*/
|
||||
async loadUsage() {
|
||||
if (this.loaded || this.loading) return;
|
||||
|
||||
try {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
const response = await apiClient.get('/vendor/usage');
|
||||
this.usage = response;
|
||||
this.loaded = true;
|
||||
|
||||
log.debug('[UpgradePrompts] Loaded usage data', this.usage);
|
||||
|
||||
} catch (error) {
|
||||
log.error('[UpgradePrompts] Failed to load usage:', error);
|
||||
this.error = error.message;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get usage metric by name
|
||||
*/
|
||||
getMetric(name) {
|
||||
if (!this.usage?.usage) return null;
|
||||
return this.usage.usage.find(m => m.name === name);
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if should show limit warning for a metric
|
||||
*/
|
||||
shouldShowLimitWarning(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
return metric && (metric.is_approaching_limit || metric.is_at_limit);
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if at limit for a metric
|
||||
*/
|
||||
isAtLimit(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
return metric?.is_at_limit || false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get percentage used for a metric
|
||||
*/
|
||||
getPercentage(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
return metric?.percentage || 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get formatted usage string (e.g., "85/100")
|
||||
*/
|
||||
getUsageString(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
if (!metric) return '';
|
||||
if (metric.is_unlimited) return `${metric.current} (unlimited)`;
|
||||
return `${metric.current}/${metric.limit}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get vendor code from URL
|
||||
*/
|
||||
getVendorCode() {
|
||||
const path = window.location.pathname;
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
if (segments[0] === 'vendor' && segments[1]) {
|
||||
return segments[1];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get billing URL
|
||||
*/
|
||||
getBillingUrl() {
|
||||
const vendorCode = this.getVendorCode();
|
||||
return vendorCode ? `/vendor/${vendorCode}/billing` : '#';
|
||||
},
|
||||
|
||||
/**
|
||||
* Check limit before action, show modal if at limit
|
||||
*/
|
||||
async checkLimitAndProceed(limitType, onSuccess) {
|
||||
try {
|
||||
const response = await apiClient.get(`/vendor/usage/check/${limitType}`);
|
||||
|
||||
if (response.can_proceed) {
|
||||
if (typeof onSuccess === 'function') {
|
||||
onSuccess();
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
// Show upgrade modal
|
||||
this.showLimitReachedModal(limitType, response);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
log.error('[UpgradePrompts] Failed to check limit:', error);
|
||||
// Proceed anyway on error (fail open)
|
||||
if (typeof onSuccess === 'function') {
|
||||
onSuccess();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Show limit reached modal
|
||||
*/
|
||||
showLimitReachedModal(limitType, response) {
|
||||
const limitNames = {
|
||||
'orders': 'monthly orders',
|
||||
'products': 'products',
|
||||
'team_members': 'team members'
|
||||
};
|
||||
|
||||
const limitName = limitNames[limitType] || limitType;
|
||||
const message = response.message || `You've reached your ${limitName} limit.`;
|
||||
|
||||
// Use browser confirm for simplicity - could be replaced with custom modal
|
||||
const shouldUpgrade = confirm(
|
||||
`${message}\n\n` +
|
||||
`Current: ${response.current}/${response.limit}\n\n` +
|
||||
(response.upgrade_tier_name
|
||||
? `Upgrade to ${response.upgrade_tier_name} to get more ${limitName}.\n\nGo to billing page?`
|
||||
: 'Contact support for more capacity.')
|
||||
);
|
||||
|
||||
if (shouldUpgrade && response.upgrade_tier_code) {
|
||||
window.location.href = this.getBillingUrl();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get limit warning banner HTML
|
||||
*/
|
||||
getLimitWarningHTML(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
if (!metric) return '';
|
||||
|
||||
const names = {
|
||||
'orders': 'monthly orders',
|
||||
'products': 'products',
|
||||
'team_members': 'team members'
|
||||
};
|
||||
const name = names[metricName] || metricName;
|
||||
|
||||
if (metric.is_at_limit) {
|
||||
return `
|
||||
<div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-4">
|
||||
<div class="flex items-center">
|
||||
<svg class="w-5 h-5 text-red-500 mr-3" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
<div class="flex-1">
|
||||
<p class="text-sm font-medium text-red-800 dark:text-red-200">
|
||||
You've reached your ${name} limit (${metric.current}/${metric.limit})
|
||||
</p>
|
||||
</div>
|
||||
<a href="${this.getBillingUrl()}"
|
||||
class="ml-4 px-3 py-1 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded">
|
||||
Upgrade
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (metric.is_approaching_limit) {
|
||||
return `
|
||||
<div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-4">
|
||||
<div class="flex items-center">
|
||||
<svg class="w-5 h-5 text-yellow-500 mr-3" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
<div class="flex-1">
|
||||
<p class="text-sm font-medium text-yellow-800 dark:text-yellow-200">
|
||||
You're approaching your ${name} limit (${metric.current}/${metric.limit} - ${Math.round(metric.percentage)}%)
|
||||
</p>
|
||||
</div>
|
||||
<a href="${this.getBillingUrl()}"
|
||||
class="ml-4 px-3 py-1 text-sm font-medium text-yellow-800 bg-yellow-200 hover:bg-yellow-300 dark:bg-yellow-800 dark:text-yellow-200 dark:hover:bg-yellow-700 rounded">
|
||||
Upgrade
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return '';
|
||||
},
|
||||
|
||||
/**
|
||||
* Get upgrade card HTML for dashboard
|
||||
*/
|
||||
getUpgradeCardHTML() {
|
||||
if (!this.usage?.upgrade_tier) return '';
|
||||
|
||||
const tier = this.usage.upgrade_tier;
|
||||
const reasons = this.usage.upgrade_reasons || [];
|
||||
|
||||
return `
|
||||
<div class="bg-gradient-to-r from-purple-500 to-indigo-600 rounded-lg p-6 text-white">
|
||||
<div class="flex items-start justify-between">
|
||||
<div>
|
||||
<h3 class="text-lg font-semibold mb-2">Upgrade to ${tier.name}</h3>
|
||||
${reasons.length > 0 ? `
|
||||
<ul class="text-sm opacity-90 mb-4 space-y-1">
|
||||
${reasons.map(r => `<li>• ${r}</li>`).join('')}
|
||||
</ul>
|
||||
` : ''}
|
||||
${tier.benefits.length > 0 ? `
|
||||
<p class="text-sm opacity-80 mb-2">Get access to:</p>
|
||||
<ul class="text-sm space-y-1 mb-4">
|
||||
${tier.benefits.slice(0, 4).map(b => `
|
||||
<li class="flex items-center">
|
||||
<svg class="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
${b}
|
||||
</li>
|
||||
`).join('')}
|
||||
</ul>
|
||||
` : ''}
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<p class="text-2xl font-bold">€${(tier.price_monthly_cents / 100).toFixed(0)}</p>
|
||||
<p class="text-sm opacity-80">/month</p>
|
||||
</div>
|
||||
</div>
|
||||
<a href="${this.getBillingUrl()}"
|
||||
class="mt-4 inline-flex items-center px-4 py-2 bg-white text-purple-600 font-medium rounded-lg hover:bg-gray-100 transition-colors">
|
||||
Upgrade Now
|
||||
<svg class="w-4 h-4 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6"/>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get compact usage bar HTML
|
||||
*/
|
||||
getUsageBarHTML(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
if (!metric || metric.is_unlimited) return '';
|
||||
|
||||
const percentage = Math.min(metric.percentage, 100);
|
||||
const colorClass = metric.is_at_limit
|
||||
? 'bg-red-500'
|
||||
: metric.is_approaching_limit
|
||||
? 'bg-yellow-500'
|
||||
: 'bg-green-500';
|
||||
|
||||
return `
|
||||
<div class="w-full">
|
||||
<div class="flex justify-between text-xs text-gray-500 dark:text-gray-400 mb-1">
|
||||
<span>${metric.current} / ${metric.limit}</span>
|
||||
<span>${Math.round(percentage)}%</span>
|
||||
</div>
|
||||
<div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
|
||||
<div class="${colorClass} h-2 rounded-full transition-all" style="width: ${percentage}%"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Reload usage data
|
||||
*/
|
||||
async reload() {
|
||||
try {
|
||||
this.loaded = false;
|
||||
await this.loadUsage();
|
||||
} catch (error) {
|
||||
log.error('[UpgradePrompts] Failed to reload:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Register Alpine store when Alpine is available
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.store('upgrade', upgradeStore);
|
||||
log.debug('[UpgradePrompts] Registered as Alpine store');
|
||||
});
|
||||
|
||||
// Also expose globally
|
||||
window.UpgradePrompts = upgradeStore;
|
||||
|
||||
})();
|
||||
211
app/modules/billing/static/vendor/js/billing.js
vendored
Normal file
211
app/modules/billing/static/vendor/js/billing.js
vendored
Normal file
@@ -0,0 +1,211 @@
|
||||
// app/modules/billing/static/vendor/js/billing.js
|
||||
// Vendor billing and subscription management
|
||||
|
||||
const billingLog = window.LogConfig?.createLogger('BILLING') || console;
|
||||
|
||||
function vendorBilling() {
|
||||
return {
|
||||
// Inherit base data (dark mode, sidebar, vendor info, etc.)
|
||||
...data(),
|
||||
currentPage: 'billing',
|
||||
|
||||
// State
|
||||
loading: true,
|
||||
subscription: null,
|
||||
tiers: [],
|
||||
addons: [],
|
||||
myAddons: [],
|
||||
invoices: [],
|
||||
|
||||
// UI state
|
||||
showTiersModal: false,
|
||||
showAddonsModal: false,
|
||||
showCancelModal: false,
|
||||
showSuccessMessage: false,
|
||||
showCancelMessage: false,
|
||||
showAddonSuccessMessage: false,
|
||||
cancelReason: '',
|
||||
purchasingAddon: null,
|
||||
|
||||
// Initialize
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._vendorBillingInitialized) return;
|
||||
window._vendorBillingInitialized = true;
|
||||
|
||||
// IMPORTANT: Call parent init first to set vendorCode 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] = await Promise.all([
|
||||
apiClient.get('/vendor/billing/subscription'),
|
||||
apiClient.get('/vendor/billing/tiers'),
|
||||
apiClient.get('/vendor/billing/addons'),
|
||||
apiClient.get('/vendor/billing/my-addons'),
|
||||
apiClient.get('/vendor/billing/invoices?limit=5'),
|
||||
]);
|
||||
|
||||
this.subscription = subscriptionRes;
|
||||
this.tiers = tiersRes.tiers || [];
|
||||
this.addons = addonsRes || [];
|
||||
this.myAddons = myAddonsRes || [];
|
||||
this.invoices = invoicesRes.invoices || [];
|
||||
|
||||
} catch (error) {
|
||||
billingLog.error('Error loading billing data:', error);
|
||||
Utils.showToast('Failed to load billing data', 'error');
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async selectTier(tier) {
|
||||
if (tier.is_current) return;
|
||||
|
||||
try {
|
||||
const response = await apiClient.post('/vendor/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('Failed to create checkout session', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async openPortal() {
|
||||
try {
|
||||
const response = await apiClient.post('/vendor/billing/portal', {});
|
||||
if (response.portal_url) {
|
||||
window.location.href = response.portal_url;
|
||||
}
|
||||
} catch (error) {
|
||||
billingLog.error('Error opening portal:', error);
|
||||
Utils.showToast('Failed to open payment portal', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async cancelSubscription() {
|
||||
try {
|
||||
await apiClient.post('/vendor/billing/cancel', {
|
||||
reason: this.cancelReason,
|
||||
immediately: false
|
||||
});
|
||||
|
||||
this.showCancelModal = false;
|
||||
Utils.showToast('Subscription cancelled. You have access until the end of your billing period.', 'success');
|
||||
await this.loadData();
|
||||
|
||||
} catch (error) {
|
||||
billingLog.error('Error cancelling subscription:', error);
|
||||
Utils.showToast('Failed to cancel subscription', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async reactivate() {
|
||||
try {
|
||||
await apiClient.post('/vendor/billing/reactivate', {});
|
||||
Utils.showToast('Subscription reactivated!', 'success');
|
||||
await this.loadData();
|
||||
|
||||
} catch (error) {
|
||||
billingLog.error('Error reactivating subscription:', error);
|
||||
Utils.showToast('Failed to reactivate subscription', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async purchaseAddon(addon) {
|
||||
this.purchasingAddon = addon.code;
|
||||
try {
|
||||
const response = await apiClient.post('/vendor/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('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 apiClient.delete(`/vendor/billing/addons/${addon.id}`);
|
||||
Utils.showToast('Add-on cancelled successfully', 'success');
|
||||
await this.loadData();
|
||||
} catch (error) {
|
||||
billingLog.error('Error cancelling addon:', error);
|
||||
Utils.showToast('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');
|
||||
},
|
||||
|
||||
// Formatters
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return '-';
|
||||
const date = new Date(dateString);
|
||||
const locale = window.VENDOR_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.VENDOR_CONFIG?.locale || 'en-GB';
|
||||
const currencyCode = window.VENDOR_CONFIG?.currency || currency;
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency: currencyCode
|
||||
}).format(amount);
|
||||
}
|
||||
};
|
||||
}
|
||||
404
app/modules/billing/static/vendor/js/invoices.js
vendored
Normal file
404
app/modules/billing/static/vendor/js/invoices.js
vendored
Normal file
@@ -0,0 +1,404 @@
|
||||
// app/modules/billing/static/vendor/js/invoices.js
|
||||
/**
|
||||
* Vendor invoice management page logic
|
||||
*/
|
||||
|
||||
const invoicesLog = window.LogConfig?.createLogger('INVOICES') || console;
|
||||
|
||||
invoicesLog.info('[VENDOR INVOICES] Loading...');
|
||||
|
||||
function vendorInvoices() {
|
||||
invoicesLog.info('[VENDOR INVOICES] vendorInvoices() called');
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'invoices',
|
||||
|
||||
// Tab state
|
||||
activeTab: 'invoices',
|
||||
|
||||
// Loading states
|
||||
loading: false,
|
||||
savingSettings: false,
|
||||
creatingInvoice: false,
|
||||
downloadingPdf: false,
|
||||
|
||||
// Messages
|
||||
error: '',
|
||||
successMessage: '',
|
||||
|
||||
// Settings
|
||||
hasSettings: false,
|
||||
settings: null,
|
||||
settingsForm: {
|
||||
company_name: '',
|
||||
company_address: '',
|
||||
company_city: '',
|
||||
company_postal_code: '',
|
||||
company_country: 'LU',
|
||||
vat_number: '',
|
||||
invoice_prefix: 'INV',
|
||||
default_vat_rate: '17.00',
|
||||
bank_name: '',
|
||||
bank_iban: '',
|
||||
bank_bic: '',
|
||||
payment_terms: 'Net 30 days',
|
||||
footer_text: ''
|
||||
},
|
||||
|
||||
// Stats
|
||||
stats: {
|
||||
total_invoices: 0,
|
||||
total_revenue_cents: 0,
|
||||
draft_count: 0,
|
||||
issued_count: 0,
|
||||
paid_count: 0,
|
||||
cancelled_count: 0
|
||||
},
|
||||
|
||||
// Invoices list
|
||||
invoices: [],
|
||||
totalInvoices: 0,
|
||||
page: 1,
|
||||
perPage: 20,
|
||||
filters: {
|
||||
status: ''
|
||||
},
|
||||
|
||||
// Create invoice modal
|
||||
showCreateModal: false,
|
||||
createForm: {
|
||||
order_id: '',
|
||||
notes: ''
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._vendorInvoicesInitialized) {
|
||||
return;
|
||||
}
|
||||
window._vendorInvoicesInitialized = true;
|
||||
|
||||
// Call parent init first to set vendorCode from URL
|
||||
const parentInit = data().init;
|
||||
if (parentInit) {
|
||||
await parentInit.call(this);
|
||||
}
|
||||
|
||||
await this.loadSettings();
|
||||
await this.loadStats();
|
||||
await this.loadInvoices();
|
||||
},
|
||||
|
||||
/**
|
||||
* Load invoice settings
|
||||
*/
|
||||
async loadSettings() {
|
||||
try {
|
||||
const response = await apiClient.get('/vendor/invoices/settings');
|
||||
if (response) {
|
||||
this.settings = response;
|
||||
this.hasSettings = true;
|
||||
// Populate form with existing settings
|
||||
this.settingsForm = {
|
||||
company_name: response.company_name || '',
|
||||
company_address: response.company_address || '',
|
||||
company_city: response.company_city || '',
|
||||
company_postal_code: response.company_postal_code || '',
|
||||
company_country: response.company_country || 'LU',
|
||||
vat_number: response.vat_number || '',
|
||||
invoice_prefix: response.invoice_prefix || 'INV',
|
||||
default_vat_rate: response.default_vat_rate?.toString() || '17.00',
|
||||
bank_name: response.bank_name || '',
|
||||
bank_iban: response.bank_iban || '',
|
||||
bank_bic: response.bank_bic || '',
|
||||
payment_terms: response.payment_terms || 'Net 30 days',
|
||||
footer_text: response.footer_text || ''
|
||||
};
|
||||
} else {
|
||||
this.hasSettings = false;
|
||||
}
|
||||
} catch (error) {
|
||||
// 404 means not configured yet, which is fine
|
||||
if (error.status !== 404) {
|
||||
invoicesLog.error('[VENDOR INVOICES] Failed to load settings:', error);
|
||||
}
|
||||
this.hasSettings = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load invoice statistics
|
||||
*/
|
||||
async loadStats() {
|
||||
try {
|
||||
const response = await apiClient.get('/vendor/invoices/stats');
|
||||
this.stats = {
|
||||
total_invoices: response.total_invoices || 0,
|
||||
total_revenue_cents: response.total_revenue_cents || 0,
|
||||
draft_count: response.draft_count || 0,
|
||||
issued_count: response.issued_count || 0,
|
||||
paid_count: response.paid_count || 0,
|
||||
cancelled_count: response.cancelled_count || 0
|
||||
};
|
||||
} catch (error) {
|
||||
invoicesLog.error('[VENDOR INVOICES] Failed to load stats:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load invoices list
|
||||
*/
|
||||
async loadInvoices() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
page: this.page.toString(),
|
||||
per_page: this.perPage.toString()
|
||||
});
|
||||
|
||||
if (this.filters.status) {
|
||||
params.append('status', this.filters.status);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(`/vendor/invoices?${params}`);
|
||||
this.invoices = response.items || [];
|
||||
this.totalInvoices = response.total || 0;
|
||||
} catch (error) {
|
||||
invoicesLog.error('[VENDOR INVOICES] Failed to load invoices:', error);
|
||||
this.error = error.message || 'Failed to load invoices';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh all data
|
||||
*/
|
||||
async refreshData() {
|
||||
await this.loadSettings();
|
||||
await this.loadStats();
|
||||
await this.loadInvoices();
|
||||
this.successMessage = 'Data refreshed';
|
||||
setTimeout(() => this.successMessage = '', 3000);
|
||||
},
|
||||
|
||||
/**
|
||||
* Save invoice settings
|
||||
*/
|
||||
async saveSettings() {
|
||||
if (!this.settingsForm.company_name) {
|
||||
this.error = 'Company name is required';
|
||||
return;
|
||||
}
|
||||
|
||||
this.savingSettings = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
company_name: this.settingsForm.company_name,
|
||||
company_address: this.settingsForm.company_address || null,
|
||||
company_city: this.settingsForm.company_city || null,
|
||||
company_postal_code: this.settingsForm.company_postal_code || null,
|
||||
company_country: this.settingsForm.company_country || 'LU',
|
||||
vat_number: this.settingsForm.vat_number || null,
|
||||
invoice_prefix: this.settingsForm.invoice_prefix || 'INV',
|
||||
default_vat_rate: parseFloat(this.settingsForm.default_vat_rate) || 17.0,
|
||||
bank_name: this.settingsForm.bank_name || null,
|
||||
bank_iban: this.settingsForm.bank_iban || null,
|
||||
bank_bic: this.settingsForm.bank_bic || null,
|
||||
payment_terms: this.settingsForm.payment_terms || null,
|
||||
footer_text: this.settingsForm.footer_text || null
|
||||
};
|
||||
|
||||
let response;
|
||||
if (this.hasSettings) {
|
||||
// Update existing settings
|
||||
response = await apiClient.put('/vendor/invoices/settings', payload);
|
||||
} else {
|
||||
// Create new settings
|
||||
response = await apiClient.post('/vendor/invoices/settings', payload);
|
||||
}
|
||||
|
||||
this.settings = response;
|
||||
this.hasSettings = true;
|
||||
this.successMessage = 'Settings saved successfully';
|
||||
} catch (error) {
|
||||
invoicesLog.error('[VENDOR INVOICES] Failed to save settings:', error);
|
||||
this.error = error.message || 'Failed to save settings';
|
||||
} finally {
|
||||
this.savingSettings = false;
|
||||
setTimeout(() => this.successMessage = '', 5000);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Open create invoice modal
|
||||
*/
|
||||
openCreateModal() {
|
||||
if (!this.hasSettings) {
|
||||
this.error = 'Please configure invoice settings first';
|
||||
this.activeTab = 'settings';
|
||||
return;
|
||||
}
|
||||
this.createForm = {
|
||||
order_id: '',
|
||||
notes: ''
|
||||
};
|
||||
this.showCreateModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Create invoice from order
|
||||
*/
|
||||
async createInvoice() {
|
||||
if (!this.createForm.order_id) {
|
||||
this.error = 'Please enter an order ID';
|
||||
return;
|
||||
}
|
||||
|
||||
this.creatingInvoice = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
order_id: parseInt(this.createForm.order_id),
|
||||
notes: this.createForm.notes || null
|
||||
};
|
||||
|
||||
const response = await apiClient.post('/vendor/invoices', payload);
|
||||
|
||||
this.showCreateModal = false;
|
||||
this.successMessage = `Invoice ${response.invoice_number} created successfully`;
|
||||
await this.loadStats();
|
||||
await this.loadInvoices();
|
||||
} catch (error) {
|
||||
invoicesLog.error('[VENDOR INVOICES] Failed to create invoice:', error);
|
||||
this.error = error.message || 'Failed to create invoice';
|
||||
} finally {
|
||||
this.creatingInvoice = false;
|
||||
setTimeout(() => this.successMessage = '', 5000);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Update invoice status
|
||||
*/
|
||||
async updateStatus(invoice, newStatus) {
|
||||
const statusLabels = {
|
||||
'issued': 'mark as issued',
|
||||
'paid': 'mark as paid',
|
||||
'cancelled': 'cancel'
|
||||
};
|
||||
|
||||
if (!confirm(`Are you sure you want to ${statusLabels[newStatus] || newStatus} this invoice?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await apiClient.put(`/vendor/invoices/${invoice.id}/status`, {
|
||||
status: newStatus
|
||||
});
|
||||
|
||||
this.successMessage = `Invoice ${invoice.invoice_number} status updated to ${newStatus}`;
|
||||
await this.loadStats();
|
||||
await this.loadInvoices();
|
||||
} catch (error) {
|
||||
invoicesLog.error('[VENDOR INVOICES] Failed to update status:', error);
|
||||
this.error = error.message || 'Failed to update invoice status';
|
||||
}
|
||||
setTimeout(() => this.successMessage = '', 5000);
|
||||
},
|
||||
|
||||
/**
|
||||
* Download invoice PDF
|
||||
*/
|
||||
async downloadPDF(invoice) {
|
||||
this.downloadingPdf = true;
|
||||
|
||||
try {
|
||||
// Get the token for authentication
|
||||
const token = localStorage.getItem('wizamart_token') || localStorage.getItem('vendor_token');
|
||||
if (!token) {
|
||||
throw new Error('Not authenticated');
|
||||
}
|
||||
|
||||
// noqa: js-008 - File download needs response headers for filename
|
||||
const response = await fetch(`/api/v1/vendor/invoices/${invoice.id}/pdf`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.detail || 'Failed to download PDF');
|
||||
}
|
||||
|
||||
// Get filename from Content-Disposition header
|
||||
const contentDisposition = response.headers.get('Content-Disposition');
|
||||
let filename = `invoice-${invoice.invoice_number}.pdf`;
|
||||
if (contentDisposition) {
|
||||
const match = contentDisposition.match(/filename="(.+)"/);
|
||||
if (match) {
|
||||
filename = match[1];
|
||||
}
|
||||
}
|
||||
|
||||
// Download the file
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(url);
|
||||
|
||||
this.successMessage = `Downloaded: ${filename}`;
|
||||
} catch (error) {
|
||||
invoicesLog.error('[VENDOR INVOICES] Failed to download PDF:', error);
|
||||
this.error = error.message || 'Failed to download PDF';
|
||||
} finally {
|
||||
this.downloadingPdf = false;
|
||||
setTimeout(() => this.successMessage = '', 5000);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date for display
|
||||
*/
|
||||
formatDate(dateStr) {
|
||||
if (!dateStr) return 'N/A';
|
||||
const date = new Date(dateStr);
|
||||
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
|
||||
return date.toLocaleDateString(locale, {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
year: 'numeric'
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Format currency for display
|
||||
*/
|
||||
formatCurrency(cents, currency = 'EUR') {
|
||||
if (cents === null || cents === undefined) return 'N/A';
|
||||
const amount = cents / 100;
|
||||
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
|
||||
const currencyCode = window.VENDOR_CONFIG?.currency || currency;
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency: currencyCode
|
||||
}).format(amount);
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user