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:
2026-01-30 22:08:20 +01:00
parent 434db1560a
commit 0b4291d893
86 changed files with 63 additions and 63 deletions

View 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');

View 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');

View 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');