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

@@ -1,211 +0,0 @@
// 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);
}
};
}

View File

@@ -1,318 +0,0 @@
// static/vendor/js/customers.js
/**
* Vendor customers management page logic
* View and manage customer relationships
*/
const vendorCustomersLog = window.LogConfig.loggers.vendorCustomers ||
window.LogConfig.createLogger('vendorCustomers', false);
vendorCustomersLog.info('Loading...');
function vendorCustomers() {
vendorCustomersLog.info('vendorCustomers() called');
return {
// Inherit base layout state
...data(),
// Set page identifier
currentPage: 'customers',
// Loading states
loading: true,
error: '',
saving: false,
// Customers data
customers: [],
stats: {
total: 0,
active: 0,
new_this_month: 0
},
// Filters
filters: {
search: '',
status: ''
},
// Pagination
pagination: {
page: 1,
per_page: 20,
total: 0,
pages: 0
},
// Modal states
showDetailModal: false,
showOrdersModal: false,
selectedCustomer: null,
customerOrders: [],
// Debounce timer
searchTimeout: 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() {
vendorCustomersLog.info('Customers init() called');
// Guard against multiple initialization
if (window._vendorCustomersInitialized) {
vendorCustomersLog.warn('Already initialized, skipping');
return;
}
window._vendorCustomersInitialized = true;
// IMPORTANT: Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
// Load platform settings for rows per page
if (window.PlatformSettings) {
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
}
try {
await this.loadCustomers();
} catch (error) {
vendorCustomersLog.error('Init failed:', error);
this.error = 'Failed to initialize customers page';
}
vendorCustomersLog.info('Customers initialization complete');
},
/**
* Load customers with filtering and pagination
*/
async loadCustomers() {
this.loading = true;
this.error = '';
try {
const params = new URLSearchParams({
skip: (this.pagination.page - 1) * this.pagination.per_page,
limit: this.pagination.per_page
});
// Add filters
if (this.filters.search) {
params.append('search', this.filters.search);
}
if (this.filters.status) {
params.append('status', this.filters.status);
}
const response = await apiClient.get(`/vendor/customers?${params.toString()}`);
this.customers = response.customers || [];
this.pagination.total = response.total || 0;
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
// Calculate stats
this.stats = {
total: this.pagination.total,
active: this.customers.filter(c => c.is_active !== false).length,
new_this_month: this.customers.filter(c => {
if (!c.created_at) return false;
const created = new Date(c.created_at);
const now = new Date();
return created.getMonth() === now.getMonth() && created.getFullYear() === now.getFullYear();
}).length
};
vendorCustomersLog.info('Loaded customers:', this.customers.length, 'of', this.pagination.total);
} catch (error) {
vendorCustomersLog.error('Failed to load customers:', error);
this.error = error.message || 'Failed to load customers';
} finally {
this.loading = false;
}
},
/**
* Debounced search handler
*/
debouncedSearch() {
clearTimeout(this.searchTimeout);
this.searchTimeout = setTimeout(() => {
this.pagination.page = 1;
this.loadCustomers();
}, 300);
},
/**
* Apply filter and reload
*/
applyFilter() {
this.pagination.page = 1;
this.loadCustomers();
},
/**
* Clear all filters
*/
clearFilters() {
this.filters = {
search: '',
status: ''
};
this.pagination.page = 1;
this.loadCustomers();
},
/**
* View customer details
*/
async viewCustomer(customer) {
this.loading = true;
try {
const response = await apiClient.get(`/vendor/customers/${customer.id}`);
this.selectedCustomer = response;
this.showDetailModal = true;
vendorCustomersLog.info('Loaded customer details:', customer.id);
} catch (error) {
vendorCustomersLog.error('Failed to load customer details:', error);
Utils.showToast(error.message || 'Failed to load customer details', 'error');
} finally {
this.loading = false;
}
},
/**
* View customer orders
*/
async viewCustomerOrders(customer) {
this.loading = true;
try {
const response = await apiClient.get(`/vendor/customers/${customer.id}/orders`);
this.selectedCustomer = customer;
this.customerOrders = response.orders || [];
this.showOrdersModal = true;
vendorCustomersLog.info('Loaded customer orders:', customer.id, this.customerOrders.length);
} catch (error) {
vendorCustomersLog.error('Failed to load customer orders:', error);
Utils.showToast(error.message || 'Failed to load customer orders', 'error');
} finally {
this.loading = false;
}
},
/**
* Send message to customer
*/
messageCustomer(customer) {
window.location.href = `/vendor/${this.vendorCode}/messages?customer=${customer.id}`;
},
/**
* Get customer initials for avatar
*/
getInitials(customer) {
const first = customer.first_name || '';
const last = customer.last_name || '';
return (first.charAt(0) + last.charAt(0)).toUpperCase() || '?';
},
/**
* Format date for display
*/
formatDate(dateStr) {
if (!dateStr) return '-';
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
return new Date(dateStr).toLocaleDateString(locale, {
year: 'numeric',
month: 'short',
day: 'numeric'
});
},
/**
* Format price for display
*/
formatPrice(cents) {
if (!cents && cents !== 0) return '-';
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
const currency = window.VENDOR_CONFIG?.currency || 'EUR';
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency
}).format(cents / 100);
},
/**
* Pagination: Previous page
*/
previousPage() {
if (this.pagination.page > 1) {
this.pagination.page--;
this.loadCustomers();
}
},
/**
* Pagination: Next page
*/
nextPage() {
if (this.pagination.page < this.totalPages) {
this.pagination.page++;
this.loadCustomers();
}
},
/**
* Pagination: Go to specific page
*/
goToPage(pageNum) {
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
this.pagination.page = pageNum;
this.loadCustomers();
}
}
};
}

View File

@@ -1,264 +0,0 @@
/**
* Vendor Email Templates Management Page
*
* Allows vendors to customize email templates sent to their customers.
* Platform-only templates (billing, subscription) cannot be overridden.
*/
const vendorEmailTemplatesLog = window.LogConfig?.loggers?.vendorEmailTemplates ||
window.LogConfig?.createLogger?.('vendorEmailTemplates', false) ||
{ info: () => {}, debug: () => {}, warn: () => {}, error: () => {} };
vendorEmailTemplatesLog.info('Loading...');
function vendorEmailTemplates() {
vendorEmailTemplatesLog.info('vendorEmailTemplates() called');
return {
// Inherit base layout state
...data(),
// Set page identifier
currentPage: 'email-templates',
// Loading states
loading: true,
error: '',
saving: false,
// Data
templates: [],
supportedLanguages: ['en', 'fr', 'de', 'lb'],
// Edit Modal
showEditModal: false,
editingTemplate: null,
editLanguage: 'en',
loadingTemplate: false,
templateSource: 'platform',
editForm: {
subject: '',
body_html: '',
body_text: ''
},
reverting: false,
// Preview Modal
showPreviewModal: false,
previewData: null,
// Test Email Modal
showTestEmailModal: false,
testEmailAddress: '',
sendingTest: false,
// Lifecycle
async init() {
if (window._vendorEmailTemplatesInitialized) return;
window._vendorEmailTemplatesInitialized = true;
vendorEmailTemplatesLog.info('Email templates init() called');
// Call parent init to set vendorCode and other base state
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
await this.loadData();
},
// Data Loading
async loadData() {
this.loading = true;
this.error = '';
try {
const response = await apiClient.get('/vendor/email-templates');
this.templates = response.templates || [];
this.supportedLanguages = response.supported_languages || ['en', 'fr', 'de', 'lb'];
} catch (error) {
vendorEmailTemplatesLog.error('Failed to load templates:', error);
this.error = error.detail || 'Failed to load templates';
} finally {
this.loading = false;
}
},
// Category styling
getCategoryClass(category) {
const classes = {
'AUTH': 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
'ORDERS': 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
'BILLING': 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
'SYSTEM': 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
'MARKETING': 'bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-400',
'TEAM': 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400'
};
return classes[category] || 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300';
},
// Edit Template
async editTemplate(template) {
this.editingTemplate = template;
this.editLanguage = 'en';
this.showEditModal = true;
await this.loadTemplateLanguage();
},
async loadTemplateLanguage() {
if (!this.editingTemplate) return;
this.loadingTemplate = true;
try {
const data = await apiClient.get(
`/vendor/email-templates/${this.editingTemplate.code}/${this.editLanguage}`
);
this.templateSource = data.source;
this.editForm = {
subject: data.subject || '',
body_html: data.body_html || '',
body_text: data.body_text || ''
};
} catch (error) {
if (error.status === 404) {
// No template for this language
this.templateSource = 'none';
this.editForm = {
subject: '',
body_html: '',
body_text: ''
};
Utils.showToast(`No template available for ${this.editLanguage.toUpperCase()}`, 'info');
} else {
vendorEmailTemplatesLog.error('Failed to load template:', error);
Utils.showToast('Failed to load template', 'error');
}
} finally {
this.loadingTemplate = false;
}
},
closeEditModal() {
this.showEditModal = false;
this.editingTemplate = null;
this.editForm = {
subject: '',
body_html: '',
body_text: ''
};
},
async saveTemplate() {
if (!this.editingTemplate) return;
this.saving = true;
try {
await apiClient.put(
`/vendor/email-templates/${this.editingTemplate.code}/${this.editLanguage}`,
{
subject: this.editForm.subject,
body_html: this.editForm.body_html,
body_text: this.editForm.body_text || null
}
);
Utils.showToast('Template saved successfully', 'success');
this.templateSource = 'vendor_override';
// Refresh list to show updated status
await this.loadData();
} catch (error) {
vendorEmailTemplatesLog.error('Failed to save template:', error);
Utils.showToast(error.detail || 'Failed to save template', 'error');
} finally {
this.saving = false;
}
},
async revertToDefault() {
if (!this.editingTemplate) return;
if (!confirm('Are you sure you want to delete your customization and revert to the platform default?')) {
return;
}
this.reverting = true;
try {
await apiClient.delete(
`/vendor/email-templates/${this.editingTemplate.code}/${this.editLanguage}`
);
Utils.showToast('Reverted to platform default', 'success');
// Reload the template to show platform version
await this.loadTemplateLanguage();
// Refresh list
await this.loadData();
} catch (error) {
vendorEmailTemplatesLog.error('Failed to revert template:', error);
Utils.showToast(error.detail || 'Failed to revert', 'error');
} finally {
this.reverting = false;
}
},
// Preview
async previewTemplate() {
if (!this.editingTemplate) return;
try {
const data = await apiClient.post(
`/vendor/email-templates/${this.editingTemplate.code}/preview`,
{
language: this.editLanguage,
variables: {}
}
);
this.previewData = data;
this.showPreviewModal = true;
} catch (error) {
vendorEmailTemplatesLog.error('Failed to preview template:', error);
Utils.showToast('Failed to load preview', 'error');
}
},
// Test Email
sendTestEmail() {
this.showTestEmailModal = true;
},
async confirmSendTestEmail() {
if (!this.testEmailAddress || !this.editingTemplate) return;
this.sendingTest = true;
try {
const result = await apiClient.post(
`/vendor/email-templates/${this.editingTemplate.code}/test`,
{
to_email: this.testEmailAddress,
language: this.editLanguage,
variables: {}
}
);
if (result.success) {
Utils.showToast(`Test email sent to ${this.testEmailAddress}`, 'success');
this.showTestEmailModal = false;
this.testEmailAddress = '';
} else {
Utils.showToast(result.message || 'Failed to send test email', 'error');
}
} catch (error) {
vendorEmailTemplatesLog.error('Failed to send test email:', error);
Utils.showToast('Failed to send test email', 'error');
} finally {
this.sendingTest = false;
}
}
};
}

View File

@@ -1,514 +0,0 @@
// static/vendor/js/inventory.js
/**
* Vendor inventory management page logic
* View and manage stock levels
*/
const vendorInventoryLog = window.LogConfig.loggers.vendorInventory ||
window.LogConfig.createLogger('vendorInventory', false);
vendorInventoryLog.info('Loading...');
function vendorInventory() {
vendorInventoryLog.info('vendorInventory() called');
return {
// Inherit base layout state
...data(),
// Set page identifier
currentPage: 'inventory',
// Loading states
loading: true,
error: '',
saving: false,
// Inventory data
inventory: [],
stats: {
total_entries: 0,
total_quantity: 0,
low_stock_count: 0,
out_of_stock_count: 0
},
// Filters
filters: {
search: '',
location: '',
low_stock: ''
},
// Available locations for filter dropdown
locations: [],
// Pagination
pagination: {
page: 1,
per_page: 20,
total: 0,
pages: 0
},
// Modal states
showAdjustModal: false,
showSetModal: false,
selectedItem: null,
// Form data
adjustForm: {
quantity: 0,
reason: ''
},
setForm: {
quantity: 0
},
// Bulk operations
selectedItems: [],
showBulkAdjustModal: false,
bulkAdjustForm: {
quantity: 0,
reason: ''
},
// Debounce timer
searchTimeout: 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;
},
// Computed: Check if all visible items are selected
get allSelected() {
return this.inventory.length > 0 && this.selectedItems.length === this.inventory.length;
},
// Computed: Check if some but not all items are selected
get someSelected() {
return this.selectedItems.length > 0 && this.selectedItems.length < this.inventory.length;
},
async init() {
vendorInventoryLog.info('Inventory init() called');
// Guard against multiple initialization
if (window._vendorInventoryInitialized) {
vendorInventoryLog.warn('Already initialized, skipping');
return;
}
window._vendorInventoryInitialized = true;
// IMPORTANT: Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
// Load platform settings for rows per page
if (window.PlatformSettings) {
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
}
try {
await this.loadInventory();
} catch (error) {
vendorInventoryLog.error('Init failed:', error);
this.error = 'Failed to initialize inventory page';
}
vendorInventoryLog.info('Inventory initialization complete');
},
/**
* Load inventory with filtering and pagination
*/
async loadInventory() {
this.loading = true;
this.error = '';
try {
const params = new URLSearchParams({
skip: (this.pagination.page - 1) * this.pagination.per_page,
limit: this.pagination.per_page
});
// Add filters
if (this.filters.search) {
params.append('search', this.filters.search);
}
if (this.filters.location) {
params.append('location', this.filters.location);
}
if (this.filters.low_stock) {
params.append('low_stock', this.filters.low_stock);
}
const response = await apiClient.get(`/vendor/inventory?${params.toString()}`);
this.inventory = response.items || [];
this.pagination.total = response.total || 0;
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
// Extract unique locations
this.extractLocations();
// Calculate stats
this.calculateStats();
vendorInventoryLog.info('Loaded inventory:', this.inventory.length, 'of', this.pagination.total);
} catch (error) {
vendorInventoryLog.error('Failed to load inventory:', error);
this.error = error.message || 'Failed to load inventory';
} finally {
this.loading = false;
}
},
/**
* Extract unique locations from inventory
*/
extractLocations() {
const locationSet = new Set(this.inventory.map(i => i.location).filter(Boolean));
this.locations = Array.from(locationSet).sort();
},
/**
* Calculate inventory statistics
*/
calculateStats() {
this.stats = {
total_entries: this.pagination.total,
total_quantity: this.inventory.reduce((sum, i) => sum + (i.quantity || 0), 0),
low_stock_count: this.inventory.filter(i => i.quantity > 0 && i.quantity <= (i.low_stock_threshold || 5)).length,
out_of_stock_count: this.inventory.filter(i => i.quantity <= 0).length
};
},
/**
* Debounced search handler
*/
debouncedSearch() {
clearTimeout(this.searchTimeout);
this.searchTimeout = setTimeout(() => {
this.pagination.page = 1;
this.loadInventory();
}, 300);
},
/**
* Apply filter and reload
*/
applyFilter() {
this.pagination.page = 1;
this.loadInventory();
},
/**
* Clear all filters
*/
clearFilters() {
this.filters = {
search: '',
location: '',
low_stock: ''
};
this.pagination.page = 1;
this.loadInventory();
},
/**
* Open adjust stock modal
*/
openAdjustModal(item) {
this.selectedItem = item;
this.adjustForm = {
quantity: 0,
reason: ''
};
this.showAdjustModal = true;
},
/**
* Open set quantity modal
*/
openSetModal(item) {
this.selectedItem = item;
this.setForm = {
quantity: item.quantity || 0
};
this.showSetModal = true;
},
/**
* Execute stock adjustment
*/
async executeAdjust() {
if (!this.selectedItem || this.adjustForm.quantity === 0) return;
this.saving = true;
try {
await apiClient.post(`/vendor/inventory/adjust`, {
product_id: this.selectedItem.product_id,
location: this.selectedItem.location,
quantity: this.adjustForm.quantity,
reason: this.adjustForm.reason || null
});
vendorInventoryLog.info('Adjusted inventory:', this.selectedItem.id);
this.showAdjustModal = false;
this.selectedItem = null;
Utils.showToast('Stock adjusted successfully', 'success');
await this.loadInventory();
} catch (error) {
vendorInventoryLog.error('Failed to adjust inventory:', error);
Utils.showToast(error.message || 'Failed to adjust stock', 'error');
} finally {
this.saving = false;
}
},
/**
* Execute set quantity
*/
async executeSet() {
if (!this.selectedItem || this.setForm.quantity < 0) return;
this.saving = true;
try {
await apiClient.post(`/vendor/inventory/set`, {
product_id: this.selectedItem.product_id,
location: this.selectedItem.location,
quantity: this.setForm.quantity
});
vendorInventoryLog.info('Set inventory quantity:', this.selectedItem.id);
this.showSetModal = false;
this.selectedItem = null;
Utils.showToast('Quantity set successfully', 'success');
await this.loadInventory();
} catch (error) {
vendorInventoryLog.error('Failed to set inventory:', error);
Utils.showToast(error.message || 'Failed to set quantity', 'error');
} finally {
this.saving = false;
}
},
/**
* Get stock status class
*/
getStockStatus(item) {
if (item.quantity <= 0) return 'out';
if (item.quantity <= (item.low_stock_threshold || 5)) return 'low';
return 'ok';
},
/**
* Format number with locale
*/
formatNumber(num) {
if (num === null || num === undefined) return '0';
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
return new Intl.NumberFormat(locale).format(num);
},
/**
* Pagination: Previous page
*/
previousPage() {
if (this.pagination.page > 1) {
this.pagination.page--;
this.loadInventory();
}
},
/**
* Pagination: Next page
*/
nextPage() {
if (this.pagination.page < this.totalPages) {
this.pagination.page++;
this.loadInventory();
}
},
/**
* Pagination: Go to specific page
*/
goToPage(pageNum) {
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
this.pagination.page = pageNum;
this.loadInventory();
}
},
// ============================================================================
// BULK OPERATIONS
// ============================================================================
/**
* Toggle select all items on current page
*/
toggleSelectAll() {
if (this.allSelected) {
this.selectedItems = [];
} else {
this.selectedItems = this.inventory.map(i => i.id);
}
},
/**
* Toggle selection of a single item
*/
toggleSelect(itemId) {
const index = this.selectedItems.indexOf(itemId);
if (index === -1) {
this.selectedItems.push(itemId);
} else {
this.selectedItems.splice(index, 1);
}
},
/**
* Check if item is selected
*/
isSelected(itemId) {
return this.selectedItems.includes(itemId);
},
/**
* Clear all selections
*/
clearSelection() {
this.selectedItems = [];
},
/**
* Open bulk adjust modal
*/
openBulkAdjustModal() {
if (this.selectedItems.length === 0) return;
this.bulkAdjustForm = {
quantity: 0,
reason: ''
};
this.showBulkAdjustModal = true;
},
/**
* Execute bulk stock adjustment
*/
async bulkAdjust() {
if (this.selectedItems.length === 0 || this.bulkAdjustForm.quantity === 0) return;
this.saving = true;
try {
let successCount = 0;
for (const itemId of this.selectedItems) {
const item = this.inventory.find(i => i.id === itemId);
if (item) {
try {
await apiClient.post(`/vendor/inventory/adjust`, {
product_id: item.product_id,
location: item.location,
quantity: this.bulkAdjustForm.quantity,
reason: this.bulkAdjustForm.reason || 'Bulk adjustment'
});
successCount++;
} catch (error) {
vendorInventoryLog.warn(`Failed to adjust item ${itemId}:`, error);
}
}
}
Utils.showToast(`${successCount} item(s) adjusted by ${this.bulkAdjustForm.quantity > 0 ? '+' : ''}${this.bulkAdjustForm.quantity}`, 'success');
this.showBulkAdjustModal = false;
this.clearSelection();
await this.loadInventory();
} catch (error) {
vendorInventoryLog.error('Bulk adjust failed:', error);
Utils.showToast(error.message || 'Failed to adjust inventory', 'error');
} finally {
this.saving = false;
}
},
/**
* Export selected items as CSV
*/
exportSelectedItems() {
if (this.selectedItems.length === 0) return;
const selectedData = this.inventory.filter(i => this.selectedItems.includes(i.id));
// Build CSV content
const headers = ['Product', 'SKU', 'Location', 'Quantity', 'Low Stock Threshold', 'Status'];
const rows = selectedData.map(i => [
i.product_name || '-',
i.sku || '-',
i.location || 'Default',
i.quantity || 0,
i.low_stock_threshold || 5,
this.getStockStatus(i)
]);
const csvContent = [
headers.join(','),
...rows.map(row => row.map(cell => `"${cell}"`).join(','))
].join('\n');
// Download
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `inventory_export_${new Date().toISOString().split('T')[0]}.csv`;
link.click();
Utils.showToast(`Exported ${selectedData.length} item(s)`, 'success');
}
};
}

View File

@@ -1,404 +0,0 @@
// 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);
}
};
}

View File

@@ -1,486 +0,0 @@
// static/vendor/js/letzshop.js
/**
* Vendor Letzshop orders management page logic
*/
const letzshopLog = window.LogConfig?.createLogger('LETZSHOP') || console;
letzshopLog.info('[VENDOR LETZSHOP] Loading...');
function vendorLetzshop() {
letzshopLog.info('[VENDOR LETZSHOP] vendorLetzshop() called');
return {
// Inherit base layout state
...data(),
// Set page identifier
currentPage: 'letzshop',
// Tab state
activeTab: 'orders',
// Loading states
loading: false,
importing: false,
saving: false,
testing: false,
submittingTracking: false,
// Messages
error: '',
successMessage: '',
// Integration status
status: {
is_configured: false,
is_connected: false,
auto_sync_enabled: false,
last_sync_at: null,
last_sync_status: null
},
// Credentials
credentials: null,
credentialsForm: {
api_key: '',
auto_sync_enabled: false,
sync_interval_minutes: 15
},
showApiKey: false,
// Orders
orders: [],
totalOrders: 0,
page: 1,
limit: 20,
filters: {
sync_status: ''
},
// Order stats
orderStats: {
pending: 0,
confirmed: 0,
rejected: 0,
shipped: 0
},
// Modals
showTrackingModal: false,
showOrderModal: false,
selectedOrder: null,
trackingForm: {
tracking_number: '',
tracking_carrier: ''
},
// Export
exportLanguage: 'fr',
exportIncludeInactive: false,
exporting: false,
async init() {
// Guard against multiple initialization
if (window._vendorLetzshopInitialized) {
return;
}
window._vendorLetzshopInitialized = true;
// Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
await this.loadStatus();
await this.loadOrders();
},
/**
* Load integration status
*/
async loadStatus() {
try {
const response = await apiClient.get('/vendor/letzshop/status');
this.status = response;
if (this.status.is_configured) {
await this.loadCredentials();
}
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Failed to load status:', error);
}
},
/**
* Load credentials (masked)
*/
async loadCredentials() {
try {
const response = await apiClient.get('/vendor/letzshop/credentials');
this.credentials = response;
this.credentialsForm.auto_sync_enabled = response.auto_sync_enabled;
this.credentialsForm.sync_interval_minutes = response.sync_interval_minutes;
} catch (error) {
// 404 means not configured, which is fine
if (error.status !== 404) {
letzshopLog.error('[VENDOR LETZSHOP] Failed to load credentials:', error);
}
}
},
/**
* Load orders
*/
async loadOrders() {
this.loading = true;
this.error = '';
try {
const params = new URLSearchParams({
skip: ((this.page - 1) * this.limit).toString(),
limit: this.limit.toString()
});
if (this.filters.sync_status) {
params.append('sync_status', this.filters.sync_status);
}
const response = await apiClient.get(`/vendor/letzshop/orders?${params}`);
this.orders = response.orders;
this.totalOrders = response.total;
// Calculate stats
await this.loadOrderStats();
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Failed to load orders:', error);
this.error = error.message || 'Failed to load orders';
} finally {
this.loading = false;
}
},
/**
* Load order stats by fetching counts for each status
*/
async loadOrderStats() {
try {
// Get all orders without filter to calculate stats
const allResponse = await apiClient.get('/vendor/letzshop/orders?limit=1000');
const allOrders = allResponse.orders || [];
this.orderStats = {
pending: allOrders.filter(o => o.sync_status === 'pending').length,
confirmed: allOrders.filter(o => o.sync_status === 'confirmed').length,
rejected: allOrders.filter(o => o.sync_status === 'rejected').length,
shipped: allOrders.filter(o => o.sync_status === 'shipped').length
};
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Failed to load order stats:', error);
}
},
/**
* Refresh all data
*/
async refreshData() {
await this.loadStatus();
await this.loadOrders();
this.successMessage = 'Data refreshed';
setTimeout(() => this.successMessage = '', 3000);
},
/**
* Import orders from Letzshop
*/
async importOrders() {
if (!this.status.is_configured) {
this.error = 'Please configure your API key first';
this.activeTab = 'settings';
return;
}
this.importing = true;
this.error = '';
try {
const response = await apiClient.post('/vendor/letzshop/orders/import', {
operation: 'order_import'
});
if (response.success) {
this.successMessage = response.message;
await this.loadOrders();
} else {
this.error = response.message || 'Import failed';
}
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Import failed:', error);
this.error = error.message || 'Failed to import orders';
} finally {
this.importing = false;
setTimeout(() => this.successMessage = '', 5000);
}
},
/**
* Save credentials
*/
async saveCredentials() {
if (!this.credentialsForm.api_key && !this.credentials) {
this.error = 'Please enter an API key';
return;
}
this.saving = true;
this.error = '';
try {
const payload = {
auto_sync_enabled: this.credentialsForm.auto_sync_enabled,
sync_interval_minutes: parseInt(this.credentialsForm.sync_interval_minutes)
};
if (this.credentialsForm.api_key) {
payload.api_key = this.credentialsForm.api_key;
}
const response = await apiClient.post('/vendor/letzshop/credentials', payload);
this.credentials = response;
this.credentialsForm.api_key = '';
this.status.is_configured = true;
this.successMessage = 'Credentials saved successfully';
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Failed to save credentials:', error);
this.error = error.message || 'Failed to save credentials';
} finally {
this.saving = false;
setTimeout(() => this.successMessage = '', 5000);
}
},
/**
* Test connection
*/
async testConnection() {
this.testing = true;
this.error = '';
try {
const response = await apiClient.post('/vendor/letzshop/test');
if (response.success) {
this.successMessage = `Connection successful (${response.response_time_ms?.toFixed(0)}ms)`;
} else {
this.error = response.error_details || 'Connection failed';
}
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Connection test failed:', error);
this.error = error.message || 'Connection test failed';
} finally {
this.testing = false;
setTimeout(() => this.successMessage = '', 5000);
}
},
/**
* Delete credentials
*/
async deleteCredentials() {
if (!confirm('Are you sure you want to remove your Letzshop credentials?')) {
return;
}
try {
await apiClient.delete('/vendor/letzshop/credentials');
this.credentials = null;
this.status.is_configured = false;
this.credentialsForm = {
api_key: '',
auto_sync_enabled: false,
sync_interval_minutes: 15
};
this.successMessage = 'Credentials removed';
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Failed to delete credentials:', error);
this.error = error.message || 'Failed to remove credentials';
}
setTimeout(() => this.successMessage = '', 5000);
},
/**
* Confirm order
*/
async confirmOrder(order) {
if (!confirm('Confirm this order?')) {
return;
}
try {
const response = await apiClient.post(`/vendor/letzshop/orders/${order.id}/confirm`);
if (response.success) {
this.successMessage = 'Order confirmed';
await this.loadOrders();
} else {
this.error = response.message || 'Failed to confirm order';
}
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Failed to confirm order:', error);
this.error = error.message || 'Failed to confirm order';
}
setTimeout(() => this.successMessage = '', 5000);
},
/**
* Reject order
*/
async rejectOrder(order) {
if (!confirm('Reject this order? This action cannot be undone.')) {
return;
}
try {
const response = await apiClient.post(`/vendor/letzshop/orders/${order.id}/reject`);
if (response.success) {
this.successMessage = 'Order rejected';
await this.loadOrders();
} else {
this.error = response.message || 'Failed to reject order';
}
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Failed to reject order:', error);
this.error = error.message || 'Failed to reject order';
}
setTimeout(() => this.successMessage = '', 5000);
},
/**
* Open tracking modal
*/
openTrackingModal(order) {
this.selectedOrder = order;
this.trackingForm = {
tracking_number: order.tracking_number || '',
tracking_carrier: order.tracking_carrier || ''
};
this.showTrackingModal = true;
},
/**
* Submit tracking
*/
async submitTracking() {
if (!this.trackingForm.tracking_number || !this.trackingForm.tracking_carrier) {
this.error = 'Please fill in all fields';
return;
}
this.submittingTracking = true;
try {
const response = await apiClient.post(
`/vendor/letzshop/orders/${this.selectedOrder.id}/tracking`,
this.trackingForm
);
if (response.success) {
this.showTrackingModal = false;
this.successMessage = 'Tracking information saved';
await this.loadOrders();
} else {
this.error = response.message || 'Failed to save tracking';
}
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Failed to set tracking:', error);
this.error = error.message || 'Failed to save tracking';
} finally {
this.submittingTracking = false;
}
setTimeout(() => this.successMessage = '', 5000);
},
/**
* View order details
*/
viewOrderDetails(order) {
this.selectedOrder = order;
this.showOrderModal = true;
},
/**
* 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) + ' ' + date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' });
},
/**
* Download product export CSV
*/
async downloadExport() {
this.exporting = true;
this.error = '';
try {
const params = new URLSearchParams({
language: this.exportLanguage,
include_inactive: this.exportIncludeInactive.toString()
});
// Get the token for authentication
const token = localStorage.getItem('wizamart_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/letzshop/export?${params}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || 'Export failed');
}
// Get filename from Content-Disposition header
const contentDisposition = response.headers.get('Content-Disposition');
let filename = `letzshop_export_${this.exportLanguage}.csv`;
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 = `Export downloaded: ${filename}`;
} catch (error) {
letzshopLog.error('[VENDOR LETZSHOP] Export failed:', error);
this.error = error.message || 'Failed to export products';
} finally {
this.exporting = false;
setTimeout(() => this.successMessage = '', 5000);
}
}
};
}

View File

@@ -1,343 +0,0 @@
// static/vendor/js/marketplace.js
/**
* Vendor marketplace import page logic
*/
// ✅ Use centralized logger (with safe fallback)
const vendorMarketplaceLog = window.LogConfig.loggers.marketplace ||
window.LogConfig.createLogger('marketplace', false);
vendorMarketplaceLog.info('Loading...');
function vendorMarketplace() {
vendorMarketplaceLog.info('[VENDOR MARKETPLACE] vendorMarketplace() called');
return {
// ✅ Inherit base layout state
...data(),
// ✅ Set page identifier
currentPage: 'marketplace',
// Loading states
loading: false,
importing: false,
error: '',
successMessage: '',
// Import form
importForm: {
csv_url: '',
marketplace: 'Letzshop',
language: 'fr',
batch_size: 1000
},
// Vendor settings (for quick fill)
vendorSettings: {
letzshop_csv_url_fr: '',
letzshop_csv_url_en: '',
letzshop_csv_url_de: ''
},
// Import jobs
jobs: [],
totalJobs: 0,
page: 1,
limit: 10,
// Modal state
showJobModal: false,
selectedJob: null,
// Auto-refresh for active jobs
autoRefreshInterval: null,
async init() {
// Guard against multiple initialization
if (window._vendorMarketplaceInitialized) {
return;
}
window._vendorMarketplaceInitialized = true;
// IMPORTANT: Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
await this.loadVendorSettings();
await this.loadJobs();
// Auto-refresh active jobs every 10 seconds
this.startAutoRefresh();
},
/**
* Load vendor settings (for quick fill)
*/
async loadVendorSettings() {
try {
const response = await apiClient.get('/vendor/settings');
this.vendorSettings = {
letzshop_csv_url_fr: response.letzshop_csv_url_fr || '',
letzshop_csv_url_en: response.letzshop_csv_url_en || '',
letzshop_csv_url_de: response.letzshop_csv_url_de || ''
};
} catch (error) {
vendorMarketplaceLog.error('[VENDOR MARKETPLACE] Failed to load vendor settings:', error);
// Non-critical, don't show error to user
}
},
/**
* Load import jobs
*/
async loadJobs() {
this.loading = true;
this.error = '';
try {
const response = await apiClient.get(
`/vendor/marketplace/imports?page=${this.page}&limit=${this.limit}`
);
this.jobs = response.items || [];
this.totalJobs = response.total || 0;
vendorMarketplaceLog.info('[VENDOR MARKETPLACE] Loaded jobs:', this.jobs.length);
} catch (error) {
vendorMarketplaceLog.error('[VENDOR MARKETPLACE] Failed to load jobs:', error);
this.error = error.message || 'Failed to load import jobs';
} finally {
this.loading = false;
}
},
/**
* Start new import
*/
async startImport() {
if (!this.importForm.csv_url) {
this.error = 'Please enter a CSV URL';
return;
}
this.importing = true;
this.error = '';
this.successMessage = '';
try {
const payload = {
source_url: this.importForm.csv_url,
marketplace: this.importForm.marketplace,
batch_size: this.importForm.batch_size
};
vendorMarketplaceLog.info('[VENDOR MARKETPLACE] Starting import:', payload);
const response = await apiClient.post('/vendor/marketplace/import', payload);
vendorMarketplaceLog.info('[VENDOR MARKETPLACE] Import started:', response);
this.successMessage = `Import job #${response.job_id} started successfully!`;
// Clear form
this.importForm.csv_url = '';
this.importForm.language = 'fr';
this.importForm.batch_size = 1000;
// Reload jobs to show the new import
await this.loadJobs();
// Clear success message after 5 seconds
setTimeout(() => {
this.successMessage = '';
}, 5000);
} catch (error) {
vendorMarketplaceLog.error('[VENDOR MARKETPLACE] Failed to start import:', error);
this.error = error.message || 'Failed to start import';
} finally {
this.importing = false;
}
},
/**
* Quick fill form with saved CSV URL
*/
quickFill(language) {
const urlMap = {
'fr': this.vendorSettings.letzshop_csv_url_fr,
'en': this.vendorSettings.letzshop_csv_url_en,
'de': this.vendorSettings.letzshop_csv_url_de
};
const url = urlMap[language];
if (url) {
this.importForm.csv_url = url;
this.importForm.language = language;
vendorMarketplaceLog.info('[VENDOR MARKETPLACE] Quick filled:', language, url);
}
},
/**
* Refresh jobs list
*/
async refreshJobs() {
await this.loadJobs();
},
/**
* Refresh single job status
*/
async refreshJobStatus(jobId) {
try {
const response = await apiClient.get(`/vendor/marketplace/imports/${jobId}`);
// Update job in list
const index = this.jobs.findIndex(j => j.id === jobId);
if (index !== -1) {
this.jobs[index] = response;
}
// Update selected job if modal is open
if (this.selectedJob && this.selectedJob.id === jobId) {
this.selectedJob = response;
}
vendorMarketplaceLog.info('[VENDOR MARKETPLACE] Refreshed job:', jobId);
} catch (error) {
vendorMarketplaceLog.error('[VENDOR MARKETPLACE] Failed to refresh job:', error);
}
},
/**
* View job details in modal
*/
async viewJobDetails(jobId) {
try {
const response = await apiClient.get(`/vendor/marketplace/imports/${jobId}`);
this.selectedJob = response;
this.showJobModal = true;
vendorMarketplaceLog.info('[VENDOR MARKETPLACE] Viewing job details:', jobId);
} catch (error) {
vendorMarketplaceLog.error('[VENDOR MARKETPLACE] Failed to load job details:', error);
this.error = error.message || 'Failed to load job details';
}
},
/**
* Close job details modal
*/
closeJobModal() {
this.showJobModal = false;
this.selectedJob = null;
},
/**
* Pagination: Previous page
*/
async previousPage() {
if (this.page > 1) {
this.page--;
await this.loadJobs();
}
},
/**
* Pagination: Next page
*/
async nextPage() {
if (this.page * this.limit < this.totalJobs) {
this.page++;
await this.loadJobs();
}
},
/**
* Format date for display
*/
formatDate(dateString) {
if (!dateString) return 'N/A';
try {
const date = new Date(dateString);
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
return date.toLocaleString(locale, {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
} catch (error) {
return dateString;
}
},
/**
* Calculate duration between start and end
*/
calculateDuration(job) {
if (!job.started_at) {
return 'Not started';
}
const start = new Date(job.started_at);
const end = job.completed_at ? new Date(job.completed_at) : new Date();
const durationMs = end - start;
// Convert to human-readable format
const seconds = Math.floor(durationMs / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
return `${hours}h ${minutes % 60}m`;
} else if (minutes > 0) {
return `${minutes}m ${seconds % 60}s`;
} else {
return `${seconds}s`;
}
},
/**
* Start auto-refresh for active jobs
*/
startAutoRefresh() {
// Clear any existing interval
if (this.autoRefreshInterval) {
clearInterval(this.autoRefreshInterval);
}
// Refresh every 10 seconds if there are active jobs
this.autoRefreshInterval = setInterval(async () => {
const hasActiveJobs = this.jobs.some(job =>
job.status === 'pending' || job.status === 'processing'
);
if (hasActiveJobs) {
vendorMarketplaceLog.info('[VENDOR MARKETPLACE] Auto-refreshing active jobs...');
await this.loadJobs();
}
}, 10000); // 10 seconds
},
/**
* Stop auto-refresh (cleanup)
*/
stopAutoRefresh() {
if (this.autoRefreshInterval) {
clearInterval(this.autoRefreshInterval);
this.autoRefreshInterval = null;
}
}
};
}
// Cleanup on page unload
window.addEventListener('beforeunload', () => {
if (window._vendorMarketplaceInstance && window._vendorMarketplaceInstance.stopAutoRefresh) {
window._vendorMarketplaceInstance.stopAutoRefresh();
}
});

View File

@@ -1,408 +0,0 @@
/**
* Vendor Messages Page
*
* Handles the messaging interface for vendors including:
* - Conversation list with filtering
* - Message thread display
* - Sending messages
* - Creating new conversations with customers
*/
const messagesLog = window.LogConfig?.createLogger('VENDOR-MESSAGES') || console;
/**
* Vendor Messages Component
*/
function vendorMessages(initialConversationId = null) {
return {
...data(),
// Loading states
loading: true,
loadingConversations: false,
loadingMessages: false,
sendingMessage: false,
creatingConversation: false,
error: '',
// Conversations state
conversations: [],
page: 1,
skip: 0,
limit: 20,
totalConversations: 0,
totalUnread: 0,
// Filters
filters: {
conversation_type: '',
is_closed: ''
},
// Selected conversation
selectedConversationId: initialConversationId,
selectedConversation: null,
// Reply form
replyContent: '',
// Compose modal
showComposeModal: false,
compose: {
recipientId: null,
subject: '',
message: ''
},
recipients: [],
// Polling
pollInterval: null,
/**
* Initialize component
*/
async init() {
// Guard against multiple initialization
if (window._vendorMessagesInitialized) return;
window._vendorMessagesInitialized = true;
// IMPORTANT: Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
try {
messagesLog.debug('Initializing vendor messages page');
await Promise.all([
this.loadConversations(),
this.loadRecipients()
]);
if (this.selectedConversationId) {
await this.loadConversation(this.selectedConversationId);
}
// Start polling for new messages
this.startPolling();
} catch (error) {
messagesLog.error('Failed to initialize messages page:', error);
} finally {
this.loading = false;
}
},
/**
* Start polling for updates
*/
startPolling() {
this.pollInterval = setInterval(async () => {
if (this.selectedConversationId && !document.hidden) {
await this.refreshCurrentConversation();
}
await this.updateUnreadCount();
}, 30000);
},
/**
* Stop polling
*/
destroy() {
if (this.pollInterval) {
clearInterval(this.pollInterval);
}
},
// ============================================================================
// CONVERSATIONS LIST
// ============================================================================
/**
* Load conversations with current filters
*/
async loadConversations() {
this.loadingConversations = true;
try {
this.skip = (this.page - 1) * this.limit;
const params = new URLSearchParams();
params.append('skip', this.skip);
params.append('limit', this.limit);
if (this.filters.conversation_type) {
params.append('conversation_type', this.filters.conversation_type);
}
if (this.filters.is_closed !== '') {
params.append('is_closed', this.filters.is_closed);
}
const response = await apiClient.get(`/vendor/messages?${params}`);
this.conversations = response.conversations || [];
this.totalConversations = response.total || 0;
this.totalUnread = response.total_unread || 0;
messagesLog.debug(`Loaded ${this.conversations.length} conversations`);
} catch (error) {
messagesLog.error('Failed to load conversations:', error);
Utils.showToast('Failed to load conversations', 'error');
} finally {
this.loadingConversations = false;
}
},
/**
* Update unread count
*/
async updateUnreadCount() {
try {
const response = await apiClient.get('/vendor/messages/unread-count');
this.totalUnread = response.total_unread || 0;
} catch (error) {
messagesLog.error('Failed to update unread count:', error);
}
},
/**
* Select a conversation
*/
async selectConversation(conversationId) {
if (this.selectedConversationId === conversationId) return;
this.selectedConversationId = conversationId;
await this.loadConversation(conversationId);
},
/**
* Load conversation detail
*/
async loadConversation(conversationId) {
this.loadingMessages = true;
try {
const response = await apiClient.get(`/vendor/messages/${conversationId}?mark_read=true`);
this.selectedConversation = response;
// Update unread count in list
const conv = this.conversations.find(c => c.id === conversationId);
if (conv) {
this.totalUnread = Math.max(0, this.totalUnread - conv.unread_count);
conv.unread_count = 0;
}
// Scroll to bottom
await this.$nextTick();
this.scrollToBottom();
} catch (error) {
messagesLog.error('Failed to load conversation:', error);
Utils.showToast('Failed to load conversation', 'error');
} finally {
this.loadingMessages = false;
}
},
/**
* Refresh current conversation
*/
async refreshCurrentConversation() {
if (!this.selectedConversationId) return;
try {
const response = await apiClient.get(`/vendor/messages/${this.selectedConversationId}?mark_read=true`);
const oldCount = this.selectedConversation?.messages?.length || 0;
const newCount = response.messages?.length || 0;
this.selectedConversation = response;
if (newCount > oldCount) {
await this.$nextTick();
this.scrollToBottom();
}
} catch (error) {
messagesLog.error('Failed to refresh conversation:', error);
}
},
/**
* Scroll messages to bottom
*/
scrollToBottom() {
const container = this.$refs.messagesContainer;
if (container) {
container.scrollTop = container.scrollHeight;
}
},
// ============================================================================
// SENDING MESSAGES
// ============================================================================
/**
* Send a message
*/
async sendMessage() {
if (!this.replyContent.trim()) return;
if (!this.selectedConversationId) return;
this.sendingMessage = true;
try {
const formData = new FormData();
formData.append('content', this.replyContent);
const message = await apiClient.postFormData(`/vendor/messages/${this.selectedConversationId}/messages`, formData);
// Add to messages
if (this.selectedConversation) {
this.selectedConversation.messages.push(message);
this.selectedConversation.message_count++;
}
// Clear form
this.replyContent = '';
// Scroll to bottom
await this.$nextTick();
this.scrollToBottom();
} catch (error) {
messagesLog.error('Failed to send message:', error);
Utils.showToast(error.message || 'Failed to send message', 'error');
} finally {
this.sendingMessage = false;
}
},
// ============================================================================
// CONVERSATION ACTIONS
// ============================================================================
/**
* Close conversation
*/
async closeConversation() {
if (!confirm('Close this conversation?')) return;
try {
await apiClient.post(`/vendor/messages/${this.selectedConversationId}/close`);
if (this.selectedConversation) {
this.selectedConversation.is_closed = true;
}
const conv = this.conversations.find(c => c.id === this.selectedConversationId);
if (conv) conv.is_closed = true;
Utils.showToast('Conversation closed', 'success');
} catch (error) {
messagesLog.error('Failed to close conversation:', error);
Utils.showToast('Failed to close conversation', 'error');
}
},
/**
* Reopen conversation
*/
async reopenConversation() {
try {
await apiClient.post(`/vendor/messages/${this.selectedConversationId}/reopen`);
if (this.selectedConversation) {
this.selectedConversation.is_closed = false;
}
const conv = this.conversations.find(c => c.id === this.selectedConversationId);
if (conv) conv.is_closed = false;
Utils.showToast('Conversation reopened', 'success');
} catch (error) {
messagesLog.error('Failed to reopen conversation:', error);
Utils.showToast('Failed to reopen conversation', 'error');
}
},
// ============================================================================
// CREATE CONVERSATION
// ============================================================================
/**
* Load recipients (customers)
*/
async loadRecipients() {
try {
const response = await apiClient.get('/vendor/messages/recipients?recipient_type=customer&limit=100');
this.recipients = response.recipients || [];
} catch (error) {
messagesLog.error('Failed to load recipients:', error);
}
},
/**
* Create new conversation
*/
async createConversation() {
if (!this.compose.recipientId || !this.compose.subject.trim()) return;
this.creatingConversation = true;
try {
const response = await apiClient.post('/vendor/messages', {
conversation_type: 'vendor_customer',
subject: this.compose.subject,
recipient_type: 'customer',
recipient_id: parseInt(this.compose.recipientId),
initial_message: this.compose.message || null
});
// Close modal and reset
this.showComposeModal = false;
this.compose = { recipientId: null, subject: '', message: '' };
// Reload and select
await this.loadConversations();
await this.selectConversation(response.id);
Utils.showToast('Conversation created', 'success');
} catch (error) {
messagesLog.error('Failed to create conversation:', error);
Utils.showToast(error.message || 'Failed to create conversation', 'error');
} finally {
this.creatingConversation = false;
}
},
// ============================================================================
// HELPERS
// ============================================================================
getOtherParticipantName() {
if (!this.selectedConversation?.participants) return 'Unknown';
const other = this.selectedConversation.participants.find(p => p.participant_type !== 'vendor');
return other?.participant_info?.name || 'Unknown';
},
formatRelativeTime(dateString) {
if (!dateString) return '';
const date = new Date(dateString);
const now = new Date();
const diff = Math.floor((now - date) / 1000);
if (diff < 60) return 'Now';
if (diff < 3600) return `${Math.floor(diff / 60)}m`;
if (diff < 86400) return `${Math.floor(diff / 3600)}h`;
if (diff < 172800) return 'Yesterday';
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
return date.toLocaleDateString(locale);
},
formatTime(dateString) {
if (!dateString) return '';
const date = new Date(dateString);
const now = new Date();
const isToday = date.toDateString() === now.toDateString();
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
if (isToday) {
return date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' });
}
return date.toLocaleString(locale, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
}
};
}
// Make available globally
window.vendorMessages = vendorMessages;

View File

@@ -1,281 +0,0 @@
// static/vendor/js/notifications.js
/**
* Vendor notifications center page logic
* View and manage notifications
*/
const vendorNotificationsLog = window.LogConfig.loggers.vendorNotifications ||
window.LogConfig.createLogger('vendorNotifications', false);
vendorNotificationsLog.info('Loading...');
function vendorNotifications() {
vendorNotificationsLog.info('vendorNotifications() called');
return {
// Inherit base layout state
...data(),
// Set page identifier
currentPage: 'notifications',
// Loading states
loading: true,
error: '',
loadingNotifications: false,
// Notifications data
notifications: [],
stats: {
total: 0,
unread_count: 0
},
// Pagination
page: 1,
limit: 20,
skip: 0,
// Filters
filters: {
priority: '',
is_read: ''
},
// Settings
settings: null,
showSettingsModal: false,
settingsForm: {
email_notifications: true,
in_app_notifications: true
},
async init() {
vendorNotificationsLog.info('Notifications init() called');
// Guard against multiple initialization
if (window._vendorNotificationsInitialized) {
vendorNotificationsLog.warn('Already initialized, skipping');
return;
}
window._vendorNotificationsInitialized = true;
// IMPORTANT: Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
try {
await this.loadNotifications();
} catch (error) {
vendorNotificationsLog.error('Init failed:', error);
this.error = 'Failed to initialize notifications page';
} finally {
this.loading = false;
}
vendorNotificationsLog.info('Notifications initialization complete');
},
/**
* Load notifications with current filters
*/
async loadNotifications() {
this.loadingNotifications = true;
this.error = '';
try {
this.skip = (this.page - 1) * this.limit;
const params = new URLSearchParams();
params.append('skip', this.skip);
params.append('limit', this.limit);
if (this.filters.is_read === 'false') {
params.append('unread_only', 'true');
}
const response = await apiClient.get(`/vendor/notifications?${params}`);
this.notifications = response.notifications || [];
this.stats.total = response.total || 0;
this.stats.unread_count = response.unread_count || 0;
vendorNotificationsLog.info(`Loaded ${this.notifications.length} notifications`);
} catch (error) {
vendorNotificationsLog.error('Failed to load notifications:', error);
this.error = error.message || 'Failed to load notifications';
} finally {
this.loadingNotifications = false;
}
},
/**
* Mark notification as read
*/
async markAsRead(notification) {
try {
await apiClient.put(`/vendor/notifications/${notification.id}/read`);
// Update local state
notification.is_read = true;
this.stats.unread_count = Math.max(0, this.stats.unread_count - 1);
Utils.showToast('Notification marked as read', 'success');
} catch (error) {
vendorNotificationsLog.error('Failed to mark as read:', error);
Utils.showToast(error.message || 'Failed to mark notification as read', 'error');
}
},
/**
* Mark all notifications as read
*/
async markAllAsRead() {
try {
await apiClient.put(`/vendor/notifications/mark-all-read`);
// Update local state
this.notifications.forEach(n => n.is_read = true);
this.stats.unread_count = 0;
Utils.showToast('All notifications marked as read', 'success');
} catch (error) {
vendorNotificationsLog.error('Failed to mark all as read:', error);
Utils.showToast(error.message || 'Failed to mark all as read', 'error');
}
},
/**
* Delete notification
*/
async deleteNotification(notificationId) {
if (!confirm('Are you sure you want to delete this notification?')) {
return;
}
try {
await apiClient.delete(`/vendor/notifications/${notificationId}`);
// Remove from local state
const wasUnread = this.notifications.find(n => n.id === notificationId && !n.is_read);
this.notifications = this.notifications.filter(n => n.id !== notificationId);
this.stats.total = Math.max(0, this.stats.total - 1);
if (wasUnread) {
this.stats.unread_count = Math.max(0, this.stats.unread_count - 1);
}
Utils.showToast('Notification deleted', 'success');
} catch (error) {
vendorNotificationsLog.error('Failed to delete notification:', error);
Utils.showToast(error.message || 'Failed to delete notification', 'error');
}
},
/**
* Open settings modal
*/
async openSettingsModal() {
try {
const response = await apiClient.get(`/vendor/notifications/settings`);
this.settingsForm = {
email_notifications: response.email_notifications !== false,
in_app_notifications: response.in_app_notifications !== false
};
this.showSettingsModal = true;
} catch (error) {
vendorNotificationsLog.error('Failed to load settings:', error);
Utils.showToast(error.message || 'Failed to load notification settings', 'error');
}
},
/**
* Save notification settings
*/
async saveSettings() {
try {
await apiClient.put(`/vendor/notifications/settings`, this.settingsForm);
Utils.showToast('Notification settings saved', 'success');
this.showSettingsModal = false;
} catch (error) {
vendorNotificationsLog.error('Failed to save settings:', error);
Utils.showToast(error.message || 'Failed to save settings', 'error');
}
},
/**
* Get notification icon based on type
*/
getNotificationIcon(type) {
const icons = {
'order_received': 'shopping-cart',
'order_shipped': 'truck',
'order_delivered': 'check-circle',
'low_stock': 'exclamation-triangle',
'import_complete': 'cloud-download',
'import_failed': 'x-circle',
'team_invite': 'user-plus',
'payment_received': 'credit-card',
'system': 'cog'
};
return icons[type] || 'bell';
},
/**
* Get priority color class
*/
getPriorityClass(priority) {
const classes = {
'critical': 'bg-red-100 text-red-600 dark:bg-red-900 dark:text-red-300',
'high': 'bg-orange-100 text-orange-600 dark:bg-orange-900 dark:text-orange-300',
'normal': 'bg-blue-100 text-blue-600 dark:bg-blue-900 dark:text-blue-300',
'low': 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300'
};
return classes[priority] || classes['normal'];
},
/**
* Format date for display
*/
formatDate(dateString) {
if (!dateString) return '-';
const date = new Date(dateString);
const now = new Date();
const diff = Math.floor((now - date) / 1000);
// Show relative time for recent dates
if (diff < 60) return 'Just now';
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
if (diff < 172800) return 'Yesterday';
// Show full date for older dates
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
return date.toLocaleDateString(locale);
},
// Pagination methods
get totalPages() {
return Math.ceil(this.stats.total / this.limit);
},
prevPage() {
if (this.page > 1) {
this.page--;
this.loadNotifications();
}
},
nextPage() {
if (this.page < this.totalPages) {
this.page++;
this.loadNotifications();
}
},
goToPage(pageNum) {
this.page = pageNum;
this.loadNotifications();
}
};
}

View File

@@ -1,649 +0,0 @@
// static/vendor/js/onboarding.js
// noqa: js-003 - Standalone page without vendor layout (no base.html extends)
// noqa: js-004 - Standalone page has no currentPage sidebar highlight
/**
* Vendor Onboarding Wizard
*
* Handles the 4-step mandatory onboarding flow:
* 1. Company Profile Setup
* 2. Letzshop API Configuration
* 3. Product & Order Import Configuration
* 4. Order Sync (historical import)
*/
const onboardingLog = window.LogConfig?.createLogger('ONBOARDING') || console;
// Onboarding translations
const onboardingTranslations = {
en: {
title: 'Welcome to Wizamart',
subtitle: 'Complete these steps to set up your store',
steps: {
company_profile: 'Company Profile',
letzshop_api: 'Letzshop API',
product_import: 'Product Import',
order_sync: 'Order Sync',
},
step1: {
title: 'Company Profile Setup',
description: 'Tell us about your business. This information will be used for invoices and your store profile.',
company_name: 'Company Name',
brand_name: 'Brand Name',
brand_name_help: 'The name customers will see',
description_label: 'Description',
description_placeholder: 'Brief description of your business',
contact_email: 'Contact Email',
contact_phone: 'Contact Phone',
website: 'Website',
business_address: 'Business Address',
tax_number: 'Tax Number (VAT)',
tax_number_placeholder: 'e.g., LU12345678',
default_language: 'Default Shop Language',
dashboard_language: 'Dashboard Language',
},
step2: {
title: 'Letzshop API Configuration',
description: 'Connect your Letzshop marketplace account to sync orders automatically.',
api_key: 'Letzshop API Key',
api_key_placeholder: 'Enter your API key',
api_key_help: 'Get your API key from Letzshop Support team',
shop_slug: 'Shop Slug',
shop_slug_help: 'Enter the last part of your Letzshop vendor URL',
test_connection: 'Test Connection',
testing: 'Testing...',
connection_success: 'Connection successful',
connection_failed: 'Connection failed',
},
step3: {
title: 'Product Import Configuration',
description: 'Configure how products are imported from your CSV feeds.',
csv_urls: 'CSV Feed URLs',
csv_url_fr: 'French CSV URL',
csv_url_en: 'English CSV URL',
csv_url_de: 'German CSV URL',
csv_url_help: 'Find your CSV URL in Letzshop Admin Panel > API > Export Products',
default_tax_rate: 'Default Tax Rate (%)',
delivery_method: 'Delivery Method',
delivery_package: 'Package Delivery',
delivery_pickup: 'Store Pickup',
preorder_days: 'Preorder Days',
preorder_days_help: 'Days before product is available after order',
},
step4: {
title: 'Historical Order Import',
description: 'Import your existing orders from Letzshop to start managing them in Wizamart.',
days_back: 'Import orders from last',
days: 'days',
start_import: 'Start Import',
importing: 'Importing...',
import_complete: 'Import Complete!',
orders_imported: 'orders imported',
skip_step: 'Skip this step',
},
buttons: {
save_continue: 'Save & Continue',
saving: 'Saving...',
back: 'Back',
complete: 'Complete Setup',
retry: 'Retry',
},
loading: 'Loading your setup...',
errors: {
load_failed: 'Failed to load onboarding status',
save_failed: 'Failed to save. Please try again.',
},
},
fr: {
title: 'Bienvenue sur Wizamart',
subtitle: 'Complétez ces étapes pour configurer votre boutique',
steps: {
company_profile: 'Profil Entreprise',
letzshop_api: 'API Letzshop',
product_import: 'Import Produits',
order_sync: 'Sync Commandes',
},
step1: {
title: 'Configuration du Profil Entreprise',
description: 'Parlez-nous de votre entreprise. Ces informations seront utilisées pour les factures et le profil de votre boutique.',
company_name: 'Nom de l\'Entreprise',
brand_name: 'Nom de la Marque',
brand_name_help: 'Le nom que les clients verront',
description_label: 'Description',
description_placeholder: 'Brève description de votre activité',
contact_email: 'Email de Contact',
contact_phone: 'Téléphone de Contact',
website: 'Site Web',
business_address: 'Adresse Professionnelle',
tax_number: 'Numéro de TVA',
tax_number_placeholder: 'ex: LU12345678',
default_language: 'Langue par Défaut de la Boutique',
dashboard_language: 'Langue du Tableau de Bord',
},
step2: {
title: 'Configuration de l\'API Letzshop',
description: 'Connectez votre compte Letzshop pour synchroniser automatiquement les commandes.',
api_key: 'Clé API Letzshop',
api_key_placeholder: 'Entrez votre clé API',
api_key_help: 'Obtenez votre clé API auprès de l\'équipe Support Letzshop',
shop_slug: 'Identifiant Boutique',
shop_slug_help: 'Entrez la dernière partie de votre URL vendeur Letzshop',
test_connection: 'Tester la Connexion',
testing: 'Test en cours...',
connection_success: 'Connexion réussie',
connection_failed: 'Échec de la connexion',
},
step3: {
title: 'Configuration Import Produits',
description: 'Configurez comment les produits sont importés depuis vos flux CSV.',
csv_urls: 'URLs des Flux CSV',
csv_url_fr: 'URL CSV Français',
csv_url_en: 'URL CSV Anglais',
csv_url_de: 'URL CSV Allemand',
csv_url_help: 'Trouvez votre URL CSV dans Letzshop Admin > API > Exporter Produits',
default_tax_rate: 'Taux de TVA par Défaut (%)',
delivery_method: 'Méthode de Livraison',
delivery_package: 'Livraison Colis',
delivery_pickup: 'Retrait en Magasin',
preorder_days: 'Jours de Précommande',
preorder_days_help: 'Jours avant disponibilité du produit après commande',
},
step4: {
title: 'Import Historique des Commandes',
description: 'Importez vos commandes existantes de Letzshop pour commencer à les gérer dans Wizamart.',
days_back: 'Importer les commandes des derniers',
days: 'jours',
start_import: 'Démarrer l\'Import',
importing: 'Import en cours...',
import_complete: 'Import Terminé !',
orders_imported: 'commandes importées',
skip_step: 'Passer cette étape',
},
buttons: {
save_continue: 'Enregistrer & Continuer',
saving: 'Enregistrement...',
back: 'Retour',
complete: 'Terminer la Configuration',
retry: 'Réessayer',
},
loading: 'Chargement de votre configuration...',
errors: {
load_failed: 'Échec du chargement du statut d\'onboarding',
save_failed: 'Échec de l\'enregistrement. Veuillez réessayer.',
},
},
de: {
title: 'Willkommen bei Wizamart',
subtitle: 'Führen Sie diese Schritte aus, um Ihren Shop einzurichten',
steps: {
company_profile: 'Firmenprofil',
letzshop_api: 'Letzshop API',
product_import: 'Produktimport',
order_sync: 'Bestellsync',
},
step1: {
title: 'Firmenprofil Einrichten',
description: 'Erzählen Sie uns von Ihrem Unternehmen. Diese Informationen werden für Rechnungen und Ihr Shop-Profil verwendet.',
company_name: 'Firmenname',
brand_name: 'Markenname',
brand_name_help: 'Der Name, den Kunden sehen werden',
description_label: 'Beschreibung',
description_placeholder: 'Kurze Beschreibung Ihres Unternehmens',
contact_email: 'Kontakt-E-Mail',
contact_phone: 'Kontakttelefon',
website: 'Website',
business_address: 'Geschäftsadresse',
tax_number: 'Steuernummer (USt-IdNr.)',
tax_number_placeholder: 'z.B. LU12345678',
default_language: 'Standard-Shop-Sprache',
dashboard_language: 'Dashboard-Sprache',
},
step2: {
title: 'Letzshop API Konfiguration',
description: 'Verbinden Sie Ihr Letzshop-Konto, um Bestellungen automatisch zu synchronisieren.',
api_key: 'Letzshop API-Schlüssel',
api_key_placeholder: 'Geben Sie Ihren API-Schlüssel ein',
api_key_help: 'Erhalten Sie Ihren API-Schlüssel vom Letzshop Support-Team',
shop_slug: 'Shop-Slug',
shop_slug_help: 'Geben Sie den letzten Teil Ihrer Letzshop-Verkäufer-URL ein',
test_connection: 'Verbindung Testen',
testing: 'Teste...',
connection_success: 'Verbindung erfolgreich',
connection_failed: 'Verbindung fehlgeschlagen',
},
step3: {
title: 'Produktimport Konfiguration',
description: 'Konfigurieren Sie, wie Produkte aus Ihren CSV-Feeds importiert werden.',
csv_urls: 'CSV-Feed-URLs',
csv_url_fr: 'Französische CSV-URL',
csv_url_en: 'Englische CSV-URL',
csv_url_de: 'Deutsche CSV-URL',
csv_url_help: 'Finden Sie Ihre CSV-URL im Letzshop Admin-Panel > API > Produkte exportieren',
default_tax_rate: 'Standard-Steuersatz (%)',
delivery_method: 'Liefermethode',
delivery_package: 'Paketlieferung',
delivery_pickup: 'Abholung im Geschäft',
preorder_days: 'Vorbestelltage',
preorder_days_help: 'Tage bis zur Verfügbarkeit nach Bestellung',
},
step4: {
title: 'Historischer Bestellimport',
description: 'Importieren Sie Ihre bestehenden Bestellungen von Letzshop, um sie in Wizamart zu verwalten.',
days_back: 'Bestellungen der letzten importieren',
days: 'Tage',
start_import: 'Import Starten',
importing: 'Importiere...',
import_complete: 'Import Abgeschlossen!',
orders_imported: 'Bestellungen importiert',
skip_step: 'Diesen Schritt überspringen',
},
buttons: {
save_continue: 'Speichern & Fortfahren',
saving: 'Speichern...',
back: 'Zurück',
complete: 'Einrichtung Abschließen',
retry: 'Erneut versuchen',
},
loading: 'Ihre Einrichtung wird geladen...',
errors: {
load_failed: 'Onboarding-Status konnte nicht geladen werden',
save_failed: 'Speichern fehlgeschlagen. Bitte versuchen Sie es erneut.',
},
},
};
function vendorOnboarding(initialLang = 'en') {
return {
// Language
lang: initialLang || localStorage.getItem('onboarding_lang') || 'en',
availableLanguages: ['en', 'fr', 'de'],
languageNames: { en: 'English', fr: 'Français', de: 'Deutsch' },
languageFlags: { en: '🇬🇧', fr: '🇫🇷', de: '🇩🇪' },
// Translation helper
t(key) {
const keys = key.split('.');
let value = onboardingTranslations[this.lang];
for (const k of keys) {
value = value?.[k];
}
return value || key;
},
// Change language
setLang(newLang) {
this.lang = newLang;
localStorage.setItem('onboarding_lang', newLang);
},
// State
loading: true,
saving: false,
testing: false,
error: null,
// Steps configuration (will be populated with translated titles)
get steps() {
return [
{ id: 'company_profile', title: this.t('steps.company_profile') },
{ id: 'letzshop_api', title: this.t('steps.letzshop_api') },
{ id: 'product_import', title: this.t('steps.product_import') },
{ id: 'order_sync', title: this.t('steps.order_sync') },
];
},
// Current state
currentStep: 'company_profile',
completedSteps: 0,
status: null,
// Form data
formData: {
// Step 1: Company Profile
company_name: '',
brand_name: '',
description: '',
contact_email: '',
contact_phone: '',
website: '',
business_address: '',
tax_number: '',
default_language: 'fr',
dashboard_language: 'fr',
// Step 2: Letzshop API
api_key: '',
shop_slug: '',
// Step 3: Product Import
csv_url_fr: '',
csv_url_en: '',
csv_url_de: '',
default_tax_rate: 17,
delivery_method: 'package_delivery',
preorder_days: 1,
// Step 4: Order Sync
days_back: 90,
},
// Letzshop connection test state
connectionStatus: null, // null, 'success', 'failed'
connectionError: null,
// Order sync state
syncJobId: null,
syncProgress: 0,
syncPhase: '',
ordersImported: 0,
syncComplete: false,
syncPollInterval: null,
// Computed
get currentStepIndex() {
return this.steps.findIndex(s => s.id === this.currentStep);
},
// Initialize
async init() {
// Guard against multiple initialization
if (window._vendorOnboardingInitialized) return;
window._vendorOnboardingInitialized = true;
try {
await this.loadStatus();
} catch (error) {
onboardingLog.error('Failed to initialize onboarding:', error);
}
},
// Load current onboarding status
async loadStatus() {
this.loading = true;
this.error = null;
try {
const response = await apiClient.get('/vendor/onboarding/status');
this.status = response;
this.currentStep = response.current_step;
this.completedSteps = response.completed_steps_count;
// Pre-populate form data from status if available
if (response.company_profile?.data) {
Object.assign(this.formData, response.company_profile.data);
}
// Check if we were in the middle of an order sync
if (response.order_sync?.job_id && this.currentStep === 'order_sync') {
this.syncJobId = response.order_sync.job_id;
this.startSyncPolling();
}
// Load step-specific data
await this.loadStepData();
} catch (err) {
onboardingLog.error('Failed to load onboarding status:', err);
this.error = err.message || 'Failed to load onboarding status';
} finally {
this.loading = false;
}
},
// Load data for current step
async loadStepData() {
try {
if (this.currentStep === 'company_profile') {
const data = await apiClient.get('/vendor/onboarding/step/company-profile');
if (data) {
Object.assign(this.formData, data);
}
} else if (this.currentStep === 'product_import') {
const data = await apiClient.get('/vendor/onboarding/step/product-import');
if (data) {
Object.assign(this.formData, {
csv_url_fr: data.csv_url_fr || '',
csv_url_en: data.csv_url_en || '',
csv_url_de: data.csv_url_de || '',
default_tax_rate: data.default_tax_rate || 17,
delivery_method: data.delivery_method || 'package_delivery',
preorder_days: data.preorder_days || 1,
});
}
}
} catch (err) {
onboardingLog.warn('Failed to load step data:', err);
}
},
// Check if a step is completed
isStepCompleted(stepId) {
if (!this.status) return false;
const stepData = this.status[stepId];
return stepData?.completed === true;
},
// Go to previous step
goToPreviousStep() {
const prevIndex = this.currentStepIndex - 1;
if (prevIndex >= 0) {
this.currentStep = this.steps[prevIndex].id;
this.loadStepData();
}
},
// Test Letzshop API connection
async testLetzshopApi() {
this.testing = true;
this.connectionStatus = null;
this.connectionError = null;
try {
const response = await apiClient.post('/vendor/onboarding/step/letzshop-api/test', {
api_key: this.formData.api_key,
shop_slug: this.formData.shop_slug,
});
if (response.success) {
this.connectionStatus = 'success';
} else {
this.connectionStatus = 'failed';
this.connectionError = response.message;
}
} catch (err) {
this.connectionStatus = 'failed';
this.connectionError = err.message || 'Connection test failed';
} finally {
this.testing = false;
}
},
// Start order sync
async startOrderSync() {
this.saving = true;
try {
const response = await apiClient.post('/vendor/onboarding/step/order-sync/trigger', {
days_back: parseInt(this.formData.days_back),
include_products: true,
});
if (response.success && response.job_id) {
this.syncJobId = response.job_id;
this.startSyncPolling();
} else {
throw new Error(response.message || 'Failed to start import');
}
} catch (err) {
onboardingLog.error('Failed to start order sync:', err);
this.error = err.message || 'Failed to start import';
} finally {
this.saving = false;
}
},
// Start polling for sync progress
startSyncPolling() {
this.syncPollInterval = setInterval(async () => {
await this.pollSyncProgress();
}, 2000);
},
// Poll sync progress
async pollSyncProgress() {
try {
const response = await apiClient.get(
`/vendor/onboarding/step/order-sync/progress/${this.syncJobId}`
);
this.syncProgress = response.progress_percentage || 0;
this.syncPhase = this.formatPhase(response.current_phase);
this.ordersImported = response.orders_imported || 0;
if (response.status === 'completed' || response.status === 'failed') {
this.stopSyncPolling();
this.syncComplete = true;
this.syncProgress = response.status === 'completed' ? 100 : this.syncProgress;
}
} catch (err) {
onboardingLog.error('Failed to poll sync progress:', err);
}
},
// Stop sync polling
stopSyncPolling() {
if (this.syncPollInterval) {
clearInterval(this.syncPollInterval);
this.syncPollInterval = null;
}
},
// Format phase for display
formatPhase(phase) {
const phases = {
fetching: 'Fetching orders from Letzshop...',
orders: 'Processing orders...',
products: 'Importing products...',
finalizing: 'Finalizing import...',
complete: 'Import complete!',
};
return phases[phase] || 'Processing...';
},
// Save current step and continue
async saveAndContinue() {
this.saving = true;
this.error = null;
try {
let endpoint = '';
let payload = {};
switch (this.currentStep) {
case 'company_profile':
endpoint = '/vendor/onboarding/step/company-profile';
payload = {
company_name: this.formData.company_name,
brand_name: this.formData.brand_name,
description: this.formData.description,
contact_email: this.formData.contact_email,
contact_phone: this.formData.contact_phone,
website: this.formData.website,
business_address: this.formData.business_address,
tax_number: this.formData.tax_number,
default_language: this.formData.default_language,
dashboard_language: this.formData.dashboard_language,
};
break;
case 'letzshop_api':
endpoint = '/vendor/onboarding/step/letzshop-api';
payload = {
api_key: this.formData.api_key,
shop_slug: this.formData.shop_slug,
};
break;
case 'product_import':
endpoint = '/vendor/onboarding/step/product-import';
payload = {
csv_url_fr: this.formData.csv_url_fr || null,
csv_url_en: this.formData.csv_url_en || null,
csv_url_de: this.formData.csv_url_de || null,
default_tax_rate: parseInt(this.formData.default_tax_rate),
delivery_method: this.formData.delivery_method,
preorder_days: parseInt(this.formData.preorder_days),
};
break;
case 'order_sync':
// Complete onboarding
endpoint = '/vendor/onboarding/step/order-sync/complete';
payload = {
job_id: this.syncJobId,
};
break;
}
const response = await apiClient.post(endpoint, payload);
if (!response.success) {
throw new Error(response.message || 'Save failed');
}
// Handle completion
if (response.onboarding_completed || response.redirect_url) {
// Redirect to dashboard
window.location.href = response.redirect_url || window.location.pathname.replace('/onboarding', '/dashboard');
return;
}
// Move to next step
if (response.next_step) {
this.currentStep = response.next_step;
this.completedSteps++;
await this.loadStepData();
}
} catch (err) {
onboardingLog.error('Failed to save step:', err);
this.error = err.message || 'Failed to save. Please try again.';
} finally {
this.saving = false;
}
},
// Logout handler
async handleLogout() {
onboardingLog.info('Logging out from onboarding...');
// Get vendor code from URL
const path = window.location.pathname;
const segments = path.split('/').filter(Boolean);
const vendorCode = segments[0] === 'vendor' && segments[1] ? segments[1] : '';
try {
// Call logout API
await apiClient.post('/vendor/auth/logout');
onboardingLog.info('Logout API called successfully');
} catch (error) {
onboardingLog.warn('Logout API error (continuing anyway):', error);
} finally {
// Clear vendor tokens only (not admin or customer tokens)
onboardingLog.info('Clearing vendor tokens...');
localStorage.removeItem('vendor_token');
localStorage.removeItem('vendor_user');
localStorage.removeItem('currentUser');
localStorage.removeItem('vendorCode');
// Note: Do NOT use localStorage.clear() - it would clear admin/customer tokens too
onboardingLog.info('Redirecting to login...');
window.location.href = `/vendor/${vendorCode}/login`;
}
},
// Dark mode
get dark() {
return localStorage.getItem('dark') === 'true' ||
(!localStorage.getItem('dark') && window.matchMedia('(prefers-color-scheme: dark)').matches);
},
};
}

View File

@@ -1,381 +0,0 @@
// static/vendor/js/order-detail.js
/**
* Vendor order detail page logic
* View order details, manage status, handle shipments, and invoice integration
*/
const orderDetailLog = window.LogConfig.loggers.orderDetail ||
window.LogConfig.createLogger('orderDetail', false);
orderDetailLog.info('Loading...');
function vendorOrderDetail() {
orderDetailLog.info('vendorOrderDetail() called');
return {
// Inherit base layout state
...data(),
// Set page identifier
currentPage: 'orders',
// Order ID from URL
orderId: window.orderDetailData?.orderId || null,
// Loading states
loading: true,
error: '',
saving: false,
creatingInvoice: false,
downloadingPdf: false,
// Order data
order: null,
shipmentStatus: null,
invoice: null,
// Modal states
showStatusModal: false,
showShipAllModal: false,
newStatus: '',
trackingNumber: '',
trackingProvider: '',
// Order statuses
statuses: [
{ value: 'pending', label: 'Pending', color: 'yellow' },
{ value: 'processing', label: 'Processing', color: 'blue' },
{ value: 'partially_shipped', label: 'Partially Shipped', color: 'orange' },
{ value: 'shipped', label: 'Shipped', color: 'indigo' },
{ value: 'delivered', label: 'Delivered', color: 'green' },
{ value: 'cancelled', label: 'Cancelled', color: 'red' },
{ value: 'refunded', label: 'Refunded', color: 'gray' }
],
async init() {
orderDetailLog.info('Order detail init() called, orderId:', this.orderId);
// Guard against multiple initialization
if (window._orderDetailInitialized) {
orderDetailLog.warn('Already initialized, skipping');
return;
}
window._orderDetailInitialized = true;
// IMPORTANT: Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
if (!this.orderId) {
this.error = 'Order ID not provided';
this.loading = false;
return;
}
try {
await this.loadOrderDetails();
} catch (error) {
orderDetailLog.error('Init failed:', error);
this.error = 'Failed to load order details';
}
orderDetailLog.info('Order detail initialization complete');
},
/**
* Load order details from API
*/
async loadOrderDetails() {
this.loading = true;
this.error = '';
try {
// Load order details
const orderResponse = await apiClient.get(
`/vendor/orders/${this.orderId}`
);
this.order = orderResponse;
this.newStatus = this.order.status;
orderDetailLog.info('Loaded order:', this.order.order_number);
// Load shipment status
await this.loadShipmentStatus();
// Load invoice if exists
await this.loadInvoice();
} catch (error) {
orderDetailLog.error('Failed to load order details:', error);
this.error = error.message || 'Failed to load order details';
} finally {
this.loading = false;
}
},
/**
* Load shipment status for partial shipment tracking
*/
async loadShipmentStatus() {
try {
const response = await apiClient.get(
`/vendor/orders/${this.orderId}/shipment-status`
);
this.shipmentStatus = response;
orderDetailLog.info('Loaded shipment status:', response);
} catch (error) {
orderDetailLog.warn('Failed to load shipment status:', error);
// Not critical - continue without shipment status
}
},
/**
* Load invoice for this order
*/
async loadInvoice() {
try {
// Search for invoices linked to this order
const response = await apiClient.get(
`/vendor/invoices?order_id=${this.orderId}&limit=1`
);
if (response.invoices && response.invoices.length > 0) {
this.invoice = response.invoices[0];
orderDetailLog.info('Loaded invoice:', this.invoice.invoice_number);
}
} catch (error) {
orderDetailLog.warn('Failed to load invoice:', error);
// Not critical - continue without invoice
}
},
/**
* Get status color class
*/
getStatusColor(status) {
const statusObj = this.statuses.find(s => s.value === status);
return statusObj ? statusObj.color : 'gray';
},
/**
* Get status label
*/
getStatusLabel(status) {
const statusObj = this.statuses.find(s => s.value === status);
return statusObj ? statusObj.label : status;
},
/**
* Get item shipment status
*/
getItemShipmentStatus(itemId) {
if (!this.shipmentStatus?.items) return null;
return this.shipmentStatus.items.find(i => i.item_id === itemId);
},
/**
* Check if item can be shipped
*/
canShipItem(itemId) {
const status = this.getItemShipmentStatus(itemId);
if (!status) return true; // Assume can ship if no status
return !status.is_fully_shipped;
},
/**
* Format price for display
*/
formatPrice(cents) {
if (cents === null || cents === undefined) return '-';
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
const currency = window.VENDOR_CONFIG?.currency || 'EUR';
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency
}).format(cents / 100);
},
/**
* Format date/time for display
*/
formatDateTime(dateStr) {
if (!dateStr) return '-';
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
return new Date(dateStr).toLocaleDateString(locale, {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
},
/**
* Update order status
*/
async updateOrderStatus(status) {
this.saving = true;
try {
const payload = { status };
// Add tracking info if shipping
if (status === 'shipped' && this.trackingNumber) {
payload.tracking_number = this.trackingNumber;
payload.tracking_provider = this.trackingProvider;
}
await apiClient.put(
`/vendor/orders/${this.orderId}/status`,
payload
);
Utils.showToast(`Order status updated to ${this.getStatusLabel(status)}`, 'success');
await this.loadOrderDetails();
} catch (error) {
orderDetailLog.error('Failed to update status:', error);
Utils.showToast(error.message || 'Failed to update status', 'error');
} finally {
this.saving = false;
}
},
/**
* Confirm status update from modal
*/
async confirmStatusUpdate() {
await this.updateOrderStatus(this.newStatus);
this.showStatusModal = false;
this.trackingNumber = '';
this.trackingProvider = '';
},
/**
* Ship a single item
*/
async shipItem(itemId) {
this.saving = true;
try {
await apiClient.post(
`/vendor/orders/${this.orderId}/items/${itemId}/ship`,
{}
);
Utils.showToast('Item shipped successfully', 'success');
await this.loadOrderDetails();
} catch (error) {
orderDetailLog.error('Failed to ship item:', error);
Utils.showToast(error.message || 'Failed to ship item', 'error');
} finally {
this.saving = false;
}
},
/**
* Ship all remaining items
*/
async shipAllItems() {
this.saving = true;
try {
// Ship each unshipped item
const unshippedItems = this.shipmentStatus?.items?.filter(i => !i.is_fully_shipped) || [];
for (const item of unshippedItems) {
await apiClient.post(
`/vendor/orders/${this.orderId}/items/${item.item_id}/ship`,
{}
);
}
// Update order status to shipped with tracking
const payload = { status: 'shipped' };
if (this.trackingNumber) {
payload.tracking_number = this.trackingNumber;
payload.tracking_provider = this.trackingProvider;
}
await apiClient.put(
`/vendor/orders/${this.orderId}/status`,
payload
);
Utils.showToast('All items shipped', 'success');
this.showShipAllModal = false;
this.trackingNumber = '';
this.trackingProvider = '';
await this.loadOrderDetails();
} catch (error) {
orderDetailLog.error('Failed to ship all items:', error);
Utils.showToast(error.message || 'Failed to ship items', 'error');
} finally {
this.saving = false;
}
},
/**
* Create invoice for this order
*/
async createInvoice() {
this.creatingInvoice = true;
try {
const response = await apiClient.post(
`/vendor/invoices`,
{ order_id: this.orderId }
);
this.invoice = response;
Utils.showToast(`Invoice ${response.invoice_number} created`, 'success');
} catch (error) {
orderDetailLog.error('Failed to create invoice:', error);
Utils.showToast(error.message || 'Failed to create invoice', 'error');
} finally {
this.creatingInvoice = false;
}
},
/**
* Download invoice PDF
*/
async downloadInvoicePdf() {
if (!this.invoice) return;
this.downloadingPdf = true;
try {
const response = await fetch(
`/api/v1/vendor/${this.vendorCode}/invoices/${this.invoice.id}/pdf`,
{
headers: {
'Authorization': `Bearer ${window.Auth?.getToken()}`
}
}
);
if (!response.ok) {
throw new Error('Failed to download PDF');
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${this.invoice.invoice_number}.pdf`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();
Utils.showToast('Invoice downloaded', 'success');
} catch (error) {
orderDetailLog.error('Failed to download invoice PDF:', error);
Utils.showToast(error.message || 'Failed to download PDF', 'error');
} finally {
this.downloadingPdf = false;
}
}
};
}

View File

@@ -1,482 +0,0 @@
// static/vendor/js/orders.js
/**
* Vendor orders management page logic
* View and manage vendor's orders
*/
const vendorOrdersLog = window.LogConfig.loggers.vendorOrders ||
window.LogConfig.createLogger('vendorOrders', false);
vendorOrdersLog.info('Loading...');
function vendorOrders() {
vendorOrdersLog.info('vendorOrders() called');
return {
// Inherit base layout state
...data(),
// Set page identifier
currentPage: 'orders',
// Loading states
loading: true,
error: '',
saving: false,
// Orders data
orders: [],
stats: {
total: 0,
pending: 0,
processing: 0,
completed: 0,
cancelled: 0
},
// Order statuses for filter and display
statuses: [
{ value: 'pending', label: 'Pending', color: 'yellow' },
{ value: 'processing', label: 'Processing', color: 'blue' },
{ value: 'partially_shipped', label: 'Partially Shipped', color: 'orange' },
{ value: 'shipped', label: 'Shipped', color: 'indigo' },
{ value: 'delivered', label: 'Delivered', color: 'green' },
{ value: 'completed', label: 'Completed', color: 'green' },
{ value: 'cancelled', label: 'Cancelled', color: 'red' },
{ value: 'refunded', label: 'Refunded', color: 'gray' }
],
// Filters
filters: {
search: '',
status: '',
date_from: '',
date_to: ''
},
// Pagination
pagination: {
page: 1,
per_page: 20,
total: 0,
pages: 0
},
// Modal states
showDetailModal: false,
showStatusModal: false,
showBulkStatusModal: false,
selectedOrder: null,
newStatus: '',
bulkStatus: '',
// Bulk selection
selectedOrders: [],
// Debounce timer
searchTimeout: 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;
},
// Computed: Check if all visible orders are selected
get allSelected() {
return this.orders.length > 0 && this.selectedOrders.length === this.orders.length;
},
// Computed: Check if some but not all orders are selected
get someSelected() {
return this.selectedOrders.length > 0 && this.selectedOrders.length < this.orders.length;
},
async init() {
vendorOrdersLog.info('Orders init() called');
// Guard against multiple initialization
if (window._vendorOrdersInitialized) {
vendorOrdersLog.warn('Already initialized, skipping');
return;
}
window._vendorOrdersInitialized = true;
// IMPORTANT: Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
// Load platform settings for rows per page
if (window.PlatformSettings) {
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
}
try {
await this.loadOrders();
} catch (error) {
vendorOrdersLog.error('Init failed:', error);
this.error = 'Failed to initialize orders page';
}
vendorOrdersLog.info('Orders initialization complete');
},
/**
* Load orders with filtering and pagination
*/
async loadOrders() {
this.loading = true;
this.error = '';
try {
const params = new URLSearchParams({
skip: (this.pagination.page - 1) * this.pagination.per_page,
limit: this.pagination.per_page
});
// Add filters
if (this.filters.search) {
params.append('search', this.filters.search);
}
if (this.filters.status) {
params.append('status', this.filters.status);
}
if (this.filters.date_from) {
params.append('date_from', this.filters.date_from);
}
if (this.filters.date_to) {
params.append('date_to', this.filters.date_to);
}
const response = await apiClient.get(`/vendor/orders?${params.toString()}`);
this.orders = response.orders || [];
this.pagination.total = response.total || 0;
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
// Calculate stats
this.calculateStats();
vendorOrdersLog.info('Loaded orders:', this.orders.length, 'of', this.pagination.total);
} catch (error) {
vendorOrdersLog.error('Failed to load orders:', error);
this.error = error.message || 'Failed to load orders';
} finally {
this.loading = false;
}
},
/**
* Calculate order statistics
*/
calculateStats() {
this.stats = {
total: this.pagination.total,
pending: this.orders.filter(o => o.status === 'pending').length,
processing: this.orders.filter(o => o.status === 'processing').length,
completed: this.orders.filter(o => ['completed', 'delivered'].includes(o.status)).length,
cancelled: this.orders.filter(o => o.status === 'cancelled').length
};
},
/**
* Debounced search handler
*/
debouncedSearch() {
clearTimeout(this.searchTimeout);
this.searchTimeout = setTimeout(() => {
this.pagination.page = 1;
this.loadOrders();
}, 300);
},
/**
* Apply filter and reload
*/
applyFilter() {
this.pagination.page = 1;
this.loadOrders();
},
/**
* Clear all filters
*/
clearFilters() {
this.filters = {
search: '',
status: '',
date_from: '',
date_to: ''
};
this.pagination.page = 1;
this.loadOrders();
},
/**
* View order details - navigates to detail page
*/
viewOrder(order) {
window.location.href = `/vendor/${this.vendorCode}/orders/${order.id}`;
},
/**
* Open status change modal
*/
openStatusModal(order) {
this.selectedOrder = order;
this.newStatus = order.status;
this.showStatusModal = true;
},
/**
* Update order status
*/
async updateStatus() {
if (!this.selectedOrder || !this.newStatus) return;
this.saving = true;
try {
await apiClient.put(`/vendor/orders/${this.selectedOrder.id}/status`, {
status: this.newStatus
});
Utils.showToast('Order status updated', 'success');
vendorOrdersLog.info('Updated order status:', this.selectedOrder.id, this.newStatus);
this.showStatusModal = false;
this.selectedOrder = null;
await this.loadOrders();
} catch (error) {
vendorOrdersLog.error('Failed to update status:', error);
Utils.showToast(error.message || 'Failed to update status', 'error');
} finally {
this.saving = false;
}
},
/**
* Get status color class
*/
getStatusColor(status) {
const statusObj = this.statuses.find(s => s.value === status);
return statusObj ? statusObj.color : 'gray';
},
/**
* Get status label
*/
getStatusLabel(status) {
const statusObj = this.statuses.find(s => s.value === status);
return statusObj ? statusObj.label : status;
},
/**
* Format price for display
*/
formatPrice(cents) {
if (!cents && cents !== 0) return '-';
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
const currency = window.VENDOR_CONFIG?.currency || 'EUR';
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency
}).format(cents / 100);
},
/**
* Format date for display
*/
formatDate(dateStr) {
if (!dateStr) return '-';
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
return new Date(dateStr).toLocaleDateString(locale, {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
},
/**
* Pagination: Previous page
*/
previousPage() {
if (this.pagination.page > 1) {
this.pagination.page--;
this.loadOrders();
}
},
/**
* Pagination: Next page
*/
nextPage() {
if (this.pagination.page < this.totalPages) {
this.pagination.page++;
this.loadOrders();
}
},
/**
* Pagination: Go to specific page
*/
goToPage(pageNum) {
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
this.pagination.page = pageNum;
this.loadOrders();
}
},
// ============================================================================
// BULK OPERATIONS
// ============================================================================
/**
* Toggle select all orders on current page
*/
toggleSelectAll() {
if (this.allSelected) {
this.selectedOrders = [];
} else {
this.selectedOrders = this.orders.map(o => o.id);
}
},
/**
* Toggle selection of a single order
*/
toggleSelect(orderId) {
const index = this.selectedOrders.indexOf(orderId);
if (index === -1) {
this.selectedOrders.push(orderId);
} else {
this.selectedOrders.splice(index, 1);
}
},
/**
* Check if order is selected
*/
isSelected(orderId) {
return this.selectedOrders.includes(orderId);
},
/**
* Clear all selections
*/
clearSelection() {
this.selectedOrders = [];
},
/**
* Open bulk status change modal
*/
openBulkStatusModal() {
if (this.selectedOrders.length === 0) return;
this.bulkStatus = '';
this.showBulkStatusModal = true;
},
/**
* Execute bulk status update
*/
async bulkUpdateStatus() {
if (this.selectedOrders.length === 0 || !this.bulkStatus) return;
this.saving = true;
try {
let successCount = 0;
for (const orderId of this.selectedOrders) {
try {
await apiClient.put(`/vendor/orders/${orderId}/status`, {
status: this.bulkStatus
});
successCount++;
} catch (error) {
vendorOrdersLog.warn(`Failed to update order ${orderId}:`, error);
}
}
Utils.showToast(`${successCount} order(s) updated to ${this.getStatusLabel(this.bulkStatus)}`, 'success');
this.showBulkStatusModal = false;
this.clearSelection();
await this.loadOrders();
} catch (error) {
vendorOrdersLog.error('Bulk status update failed:', error);
Utils.showToast(error.message || 'Failed to update orders', 'error');
} finally {
this.saving = false;
}
},
/**
* Export selected orders as CSV
*/
exportSelectedOrders() {
if (this.selectedOrders.length === 0) return;
const selectedOrderData = this.orders.filter(o => this.selectedOrders.includes(o.id));
// Build CSV content
const headers = ['Order ID', 'Date', 'Customer', 'Status', 'Total'];
const rows = selectedOrderData.map(o => [
o.order_number || o.id,
this.formatDate(o.created_at),
o.customer_name || o.customer_email || '-',
this.getStatusLabel(o.status),
this.formatPrice(o.total)
]);
const csvContent = [
headers.join(','),
...rows.map(row => row.map(cell => `"${cell}"`).join(','))
].join('\n');
// Download
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `orders_export_${new Date().toISOString().split('T')[0]}.csv`;
link.click();
Utils.showToast(`Exported ${selectedOrderData.length} order(s)`, 'success');
}
};
}

View File

@@ -1,114 +0,0 @@
// static/vendor/js/product-create.js
/**
* Vendor product creation page logic
*/
const vendorProductCreateLog = window.LogConfig.loggers.vendorProductCreate ||
window.LogConfig.createLogger('vendorProductCreate', false);
vendorProductCreateLog.info('Loading...');
function vendorProductCreate() {
vendorProductCreateLog.info('vendorProductCreate() called');
return {
// Inherit base layout state
...data(),
// Set page identifier
currentPage: 'products',
// Back URL
get backUrl() {
return `/vendor/${this.vendorCode}/products`;
},
// Loading states
loading: false,
saving: false,
error: '',
// Form data
form: {
title: '',
brand: '',
vendor_sku: '',
gtin: '',
price: '',
currency: 'EUR',
availability: 'in_stock',
is_active: true,
is_featured: false,
is_digital: false,
description: ''
},
async init() {
// Guard against duplicate initialization
if (window._vendorProductCreateInitialized) return;
window._vendorProductCreateInitialized = true;
vendorProductCreateLog.info('Initializing product create page...');
try {
// IMPORTANT: Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
vendorProductCreateLog.info('Product create page initialized');
} catch (err) {
vendorProductCreateLog.error('Failed to initialize:', err);
this.error = err.message || 'Failed to initialize';
}
},
async createProduct() {
if (!this.form.title || !this.form.price) {
this.showToast('Title and price are required', 'error');
return;
}
this.saving = true;
this.error = '';
try {
// Create product directly (vendor_id from JWT token)
const response = await apiClient.post('/vendor/products/create', {
title: this.form.title,
brand: this.form.brand || null,
vendor_sku: this.form.vendor_sku || null,
gtin: this.form.gtin || null,
price: parseFloat(this.form.price),
currency: this.form.currency,
availability: this.form.availability,
is_active: this.form.is_active,
is_featured: this.form.is_featured,
description: this.form.description || null
});
if (!response.ok) {
throw new Error(response.message || 'Failed to create product');
}
vendorProductCreateLog.info('Product created:', response.data);
this.showToast('Product created successfully', 'success');
// Navigate back to products list
setTimeout(() => {
window.location.href = this.backUrl;
}, 1000);
} catch (err) {
vendorProductCreateLog.error('Failed to create product:', err);
this.error = err.message || 'Failed to create product';
this.showToast(this.error, 'error');
} finally {
this.saving = false;
}
}
};
}
vendorProductCreateLog.info('Loaded successfully');

View File

@@ -1,548 +0,0 @@
// static/vendor/js/products.js
/**
* Vendor products management page logic
* View, edit, and manage vendor's product catalog
*/
const vendorProductsLog = window.LogConfig.loggers.vendorProducts ||
window.LogConfig.createLogger('vendorProducts', false);
vendorProductsLog.info('Loading...');
function vendorProducts() {
vendorProductsLog.info('vendorProducts() called');
return {
// Inherit base layout state
...data(),
// Set page identifier
currentPage: 'products',
// Loading states
loading: true,
error: '',
saving: false,
// Products data
products: [],
stats: {
total: 0,
active: 0,
inactive: 0,
featured: 0
},
// Filters
filters: {
search: '',
status: '', // 'active', 'inactive', ''
featured: '' // 'true', 'false', ''
},
// Pagination
pagination: {
page: 1,
per_page: 20,
total: 0,
pages: 0
},
// Modal states
showDeleteModal: false,
showDetailModal: false,
showBulkDeleteModal: false,
selectedProduct: null,
// Bulk selection
selectedProducts: [],
// Debounce timer
searchTimeout: 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;
},
// Computed: Check if all visible products are selected
get allSelected() {
return this.products.length > 0 && this.selectedProducts.length === this.products.length;
},
// Computed: Check if some but not all products are selected
get someSelected() {
return this.selectedProducts.length > 0 && this.selectedProducts.length < this.products.length;
},
async init() {
vendorProductsLog.info('Products init() called');
// Guard against multiple initialization
if (window._vendorProductsInitialized) {
vendorProductsLog.warn('Already initialized, skipping');
return;
}
window._vendorProductsInitialized = true;
// IMPORTANT: Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
// Load platform settings for rows per page
if (window.PlatformSettings) {
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
}
try {
await this.loadProducts();
} catch (error) {
vendorProductsLog.error('Init failed:', error);
this.error = 'Failed to initialize products page';
}
vendorProductsLog.info('Products initialization complete');
},
/**
* Load products with filtering and pagination
*/
async loadProducts() {
this.loading = true;
this.error = '';
try {
const params = new URLSearchParams({
skip: (this.pagination.page - 1) * this.pagination.per_page,
limit: this.pagination.per_page
});
// Add filters
if (this.filters.search) {
params.append('search', this.filters.search);
}
if (this.filters.status) {
params.append('is_active', this.filters.status === 'active');
}
if (this.filters.featured) {
params.append('is_featured', this.filters.featured === 'true');
}
const response = await apiClient.get(`/vendor/products?${params.toString()}`);
this.products = response.products || [];
this.pagination.total = response.total || 0;
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
// Calculate stats from response or products
this.stats = {
total: response.total || this.products.length,
active: this.products.filter(p => p.is_active).length,
inactive: this.products.filter(p => !p.is_active).length,
featured: this.products.filter(p => p.is_featured).length
};
vendorProductsLog.info('Loaded products:', this.products.length, 'of', this.pagination.total);
} catch (error) {
vendorProductsLog.error('Failed to load products:', error);
this.error = error.message || 'Failed to load products';
} finally {
this.loading = false;
}
},
/**
* Debounced search handler
*/
debouncedSearch() {
clearTimeout(this.searchTimeout);
this.searchTimeout = setTimeout(() => {
this.pagination.page = 1;
this.loadProducts();
}, 300);
},
/**
* Apply filter and reload
*/
applyFilter() {
this.pagination.page = 1;
this.loadProducts();
},
/**
* Clear all filters
*/
clearFilters() {
this.filters = {
search: '',
status: '',
featured: ''
};
this.pagination.page = 1;
this.loadProducts();
},
/**
* Toggle product active status
*/
async toggleActive(product) {
this.saving = true;
try {
await apiClient.put(`/vendor/products/${product.id}/toggle-active`);
product.is_active = !product.is_active;
Utils.showToast(
product.is_active ? 'Product activated' : 'Product deactivated',
'success'
);
vendorProductsLog.info('Toggled product active:', product.id, product.is_active);
} catch (error) {
vendorProductsLog.error('Failed to toggle active:', error);
Utils.showToast(error.message || 'Failed to update product', 'error');
} finally {
this.saving = false;
}
},
/**
* Toggle product featured status
*/
async toggleFeatured(product) {
this.saving = true;
try {
await apiClient.put(`/vendor/products/${product.id}/toggle-featured`);
product.is_featured = !product.is_featured;
Utils.showToast(
product.is_featured ? 'Product marked as featured' : 'Product unmarked as featured',
'success'
);
vendorProductsLog.info('Toggled product featured:', product.id, product.is_featured);
} catch (error) {
vendorProductsLog.error('Failed to toggle featured:', error);
Utils.showToast(error.message || 'Failed to update product', 'error');
} finally {
this.saving = false;
}
},
/**
* View product details
*/
viewProduct(product) {
this.selectedProduct = product;
this.showDetailModal = true;
},
/**
* Confirm delete product
*/
confirmDelete(product) {
this.selectedProduct = product;
this.showDeleteModal = true;
},
/**
* Execute delete product
*/
async deleteProduct() {
if (!this.selectedProduct) return;
this.saving = true;
try {
await apiClient.delete(`/vendor/products/${this.selectedProduct.id}`);
Utils.showToast('Product deleted successfully', 'success');
vendorProductsLog.info('Deleted product:', this.selectedProduct.id);
this.showDeleteModal = false;
this.selectedProduct = null;
await this.loadProducts();
} catch (error) {
vendorProductsLog.error('Failed to delete product:', error);
Utils.showToast(error.message || 'Failed to delete product', 'error');
} finally {
this.saving = false;
}
},
/**
* Navigate to edit product page
*/
editProduct(product) {
window.location.href = `/vendor/${this.vendorCode}/products/${product.id}/edit`;
},
/**
* Navigate to create product page
*/
createProduct() {
window.location.href = `/vendor/${this.vendorCode}/products/create`;
},
/**
* Format price for display
*/
formatPrice(cents) {
if (!cents && cents !== 0) return '-';
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
const currency = window.VENDOR_CONFIG?.currency || 'EUR';
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency
}).format(cents / 100);
},
/**
* Pagination: Previous page
*/
previousPage() {
if (this.pagination.page > 1) {
this.pagination.page--;
this.loadProducts();
}
},
/**
* Pagination: Next page
*/
nextPage() {
if (this.pagination.page < this.totalPages) {
this.pagination.page++;
this.loadProducts();
}
},
/**
* Pagination: Go to specific page
*/
goToPage(pageNum) {
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
this.pagination.page = pageNum;
this.loadProducts();
}
},
// ============================================================================
// BULK OPERATIONS
// ============================================================================
/**
* Toggle select all products on current page
*/
toggleSelectAll() {
if (this.allSelected) {
this.selectedProducts = [];
} else {
this.selectedProducts = this.products.map(p => p.id);
}
},
/**
* Toggle selection of a single product
*/
toggleSelect(productId) {
const index = this.selectedProducts.indexOf(productId);
if (index === -1) {
this.selectedProducts.push(productId);
} else {
this.selectedProducts.splice(index, 1);
}
},
/**
* Check if product is selected
*/
isSelected(productId) {
return this.selectedProducts.includes(productId);
},
/**
* Clear all selections
*/
clearSelection() {
this.selectedProducts = [];
},
/**
* Bulk activate selected products
*/
async bulkActivate() {
if (this.selectedProducts.length === 0) return;
this.saving = true;
try {
let successCount = 0;
for (const productId of this.selectedProducts) {
const product = this.products.find(p => p.id === productId);
if (product && !product.is_active) {
await apiClient.put(`/vendor/products/${productId}/toggle-active`);
product.is_active = true;
successCount++;
}
}
Utils.showToast(`${successCount} product(s) activated`, 'success');
this.clearSelection();
await this.loadProducts();
} catch (error) {
vendorProductsLog.error('Bulk activate failed:', error);
Utils.showToast(error.message || 'Failed to activate products', 'error');
} finally {
this.saving = false;
}
},
/**
* Bulk deactivate selected products
*/
async bulkDeactivate() {
if (this.selectedProducts.length === 0) return;
this.saving = true;
try {
let successCount = 0;
for (const productId of this.selectedProducts) {
const product = this.products.find(p => p.id === productId);
if (product && product.is_active) {
await apiClient.put(`/vendor/products/${productId}/toggle-active`);
product.is_active = false;
successCount++;
}
}
Utils.showToast(`${successCount} product(s) deactivated`, 'success');
this.clearSelection();
await this.loadProducts();
} catch (error) {
vendorProductsLog.error('Bulk deactivate failed:', error);
Utils.showToast(error.message || 'Failed to deactivate products', 'error');
} finally {
this.saving = false;
}
},
/**
* Bulk set featured on selected products
*/
async bulkSetFeatured() {
if (this.selectedProducts.length === 0) return;
this.saving = true;
try {
let successCount = 0;
for (const productId of this.selectedProducts) {
const product = this.products.find(p => p.id === productId);
if (product && !product.is_featured) {
await apiClient.put(`/vendor/products/${productId}/toggle-featured`);
product.is_featured = true;
successCount++;
}
}
Utils.showToast(`${successCount} product(s) marked as featured`, 'success');
this.clearSelection();
await this.loadProducts();
} catch (error) {
vendorProductsLog.error('Bulk set featured failed:', error);
Utils.showToast(error.message || 'Failed to update products', 'error');
} finally {
this.saving = false;
}
},
/**
* Bulk remove featured from selected products
*/
async bulkRemoveFeatured() {
if (this.selectedProducts.length === 0) return;
this.saving = true;
try {
let successCount = 0;
for (const productId of this.selectedProducts) {
const product = this.products.find(p => p.id === productId);
if (product && product.is_featured) {
await apiClient.put(`/vendor/products/${productId}/toggle-featured`);
product.is_featured = false;
successCount++;
}
}
Utils.showToast(`${successCount} product(s) unmarked as featured`, 'success');
this.clearSelection();
await this.loadProducts();
} catch (error) {
vendorProductsLog.error('Bulk remove featured failed:', error);
Utils.showToast(error.message || 'Failed to update products', 'error');
} finally {
this.saving = false;
}
},
/**
* Confirm bulk delete
*/
confirmBulkDelete() {
if (this.selectedProducts.length === 0) return;
this.showBulkDeleteModal = true;
},
/**
* Execute bulk delete
*/
async bulkDelete() {
if (this.selectedProducts.length === 0) return;
this.saving = true;
try {
let successCount = 0;
for (const productId of this.selectedProducts) {
await apiClient.delete(`/vendor/products/${productId}`);
successCount++;
}
Utils.showToast(`${successCount} product(s) deleted`, 'success');
this.showBulkDeleteModal = false;
this.clearSelection();
await this.loadProducts();
} catch (error) {
vendorProductsLog.error('Bulk delete failed:', error);
Utils.showToast(error.message || 'Failed to delete products', 'error');
} finally {
this.saving = false;
}
}
};
}