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:
@@ -1,137 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
/**
|
||||
* Background Tasks Monitoring Component
|
||||
* Manages the background tasks monitoring page
|
||||
*/
|
||||
|
||||
// Use centralized logger
|
||||
const backgroundTasksLog = window.LogConfig.createLogger('BACKGROUND-TASKS');
|
||||
|
||||
function backgroundTasks() {
|
||||
return {
|
||||
// Extend base data
|
||||
...data(),
|
||||
|
||||
// Set current page for navigation
|
||||
currentPage: 'background-tasks',
|
||||
|
||||
// Page-specific data
|
||||
loading: false,
|
||||
error: null,
|
||||
filterType: null,
|
||||
pollInterval: null,
|
||||
|
||||
// Statistics
|
||||
stats: {
|
||||
total_tasks: 0,
|
||||
running: 0,
|
||||
completed: 0,
|
||||
failed: 0,
|
||||
tasks_today: 0,
|
||||
avg_duration_seconds: null,
|
||||
import_jobs: {},
|
||||
test_runs: {}
|
||||
},
|
||||
|
||||
// Tasks
|
||||
tasks: [],
|
||||
runningTasks: [],
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminBackgroundTasksInitialized) return;
|
||||
window._adminBackgroundTasksInitialized = true;
|
||||
|
||||
try {
|
||||
backgroundTasksLog.info('Initializing background tasks monitor');
|
||||
await this.loadStats();
|
||||
await this.loadTasks();
|
||||
await this.loadRunningTasks();
|
||||
|
||||
// Poll for updates every 5 seconds
|
||||
this.pollInterval = setInterval(() => {
|
||||
this.loadRunningTasks();
|
||||
if (this.runningTasks.length > 0) {
|
||||
this.loadStats();
|
||||
}
|
||||
}, 5000);
|
||||
} catch (error) {
|
||||
backgroundTasksLog.error('Failed to initialize background tasks:', error);
|
||||
}
|
||||
},
|
||||
|
||||
destroy() {
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval);
|
||||
}
|
||||
},
|
||||
|
||||
async loadStats() {
|
||||
try {
|
||||
const stats = await apiClient.get('/admin/background-tasks/tasks/stats');
|
||||
this.stats = stats;
|
||||
backgroundTasksLog.info('Stats loaded:', stats);
|
||||
} catch (err) {
|
||||
backgroundTasksLog.error('Failed to load stats:', err);
|
||||
}
|
||||
},
|
||||
|
||||
async loadTasks() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
let url = '/admin/background-tasks/tasks?limit=50';
|
||||
if (this.filterType) {
|
||||
url += `&task_type=${this.filterType}`;
|
||||
}
|
||||
|
||||
const tasks = await apiClient.get(url);
|
||||
this.tasks = tasks;
|
||||
backgroundTasksLog.info('Tasks loaded:', tasks.length);
|
||||
} catch (err) {
|
||||
backgroundTasksLog.error('Failed to load tasks:', err);
|
||||
this.error = err.message;
|
||||
|
||||
if (err.message.includes('Unauthorized')) {
|
||||
window.location.href = '/admin/login';
|
||||
}
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async loadRunningTasks() {
|
||||
try {
|
||||
const running = await apiClient.get('/admin/background-tasks/tasks/running');
|
||||
this.runningTasks = running;
|
||||
|
||||
// Update elapsed time for running tasks
|
||||
const now = new Date();
|
||||
this.runningTasks.forEach(task => {
|
||||
if (task.started_at) {
|
||||
const started = new Date(task.started_at);
|
||||
task.duration_seconds = (now - started) / 1000;
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
backgroundTasksLog.error('Failed to load running tasks:', err);
|
||||
}
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
await this.loadStats();
|
||||
await this.loadTasks();
|
||||
await this.loadRunningTasks();
|
||||
},
|
||||
|
||||
formatDuration(seconds) {
|
||||
if (seconds === null || seconds === undefined) return 'N/A';
|
||||
if (seconds < 1) return `${Math.round(seconds * 1000)}ms`;
|
||||
if (seconds < 60) return `${Math.round(seconds)}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const secs = Math.round(seconds % 60);
|
||||
return `${minutes}m ${secs}s`;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/billing-history.js
|
||||
// noqa: JS-003 - Uses ...baseData which is data() with safety check
|
||||
|
||||
const billingLog = window.LogConfig?.loggers?.billingHistory || console;
|
||||
|
||||
function adminBillingHistory() {
|
||||
// Get base data with safety check for standalone usage
|
||||
const baseData = typeof data === 'function' ? data() : {};
|
||||
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...baseData,
|
||||
|
||||
// Page-specific state
|
||||
currentPage: 'billing-history',
|
||||
loading: true,
|
||||
error: null,
|
||||
successMessage: null,
|
||||
|
||||
// Data
|
||||
invoices: [],
|
||||
vendors: [],
|
||||
statusCounts: {
|
||||
paid: 0,
|
||||
open: 0,
|
||||
draft: 0,
|
||||
uncollectible: 0,
|
||||
void: 0
|
||||
},
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
vendor_id: '',
|
||||
status: ''
|
||||
},
|
||||
|
||||
// Pagination
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Sorting
|
||||
sortBy: 'invoice_date',
|
||||
sortOrder: 'desc',
|
||||
|
||||
// Computed: Total pages
|
||||
get totalPages() {
|
||||
return this.pagination.pages;
|
||||
},
|
||||
|
||||
// Computed: Start index for pagination display
|
||||
get startIndex() {
|
||||
if (this.pagination.total === 0) return 0;
|
||||
return (this.pagination.page - 1) * this.pagination.per_page + 1;
|
||||
},
|
||||
|
||||
// Computed: End index for pagination display
|
||||
get endIndex() {
|
||||
const end = this.pagination.page * this.pagination.per_page;
|
||||
return end > this.pagination.total ? this.pagination.total : end;
|
||||
},
|
||||
|
||||
// Computed: Page numbers for pagination
|
||||
get pageNumbers() {
|
||||
const pages = [];
|
||||
const totalPages = this.totalPages;
|
||||
const current = this.pagination.page;
|
||||
|
||||
if (totalPages <= 7) {
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
pages.push(1);
|
||||
if (current > 3) {
|
||||
pages.push('...');
|
||||
}
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(totalPages - 1, current + 1);
|
||||
for (let i = start; i <= end; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
if (current < totalPages - 2) {
|
||||
pages.push('...');
|
||||
}
|
||||
pages.push(totalPages);
|
||||
}
|
||||
return pages;
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminBillingHistoryInitialized) {
|
||||
billingLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminBillingHistoryInitialized = true;
|
||||
|
||||
billingLog.info('=== BILLING HISTORY PAGE INITIALIZING ===');
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
await this.loadVendors();
|
||||
await this.loadInvoices();
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
this.error = null;
|
||||
this.successMessage = null;
|
||||
await this.loadInvoices();
|
||||
},
|
||||
|
||||
async loadVendors() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/vendors?limit=1000');
|
||||
this.vendors = data.vendors || [];
|
||||
billingLog.info(`Loaded ${this.vendors.length} vendors for filter`);
|
||||
} catch (error) {
|
||||
billingLog.error('Failed to load vendors:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async loadInvoices() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', this.pagination.page);
|
||||
params.append('per_page', this.pagination.per_page);
|
||||
if (this.filters.vendor_id) params.append('vendor_id', this.filters.vendor_id);
|
||||
if (this.filters.status) params.append('status', this.filters.status);
|
||||
if (this.sortBy) params.append('sort_by', this.sortBy);
|
||||
if (this.sortOrder) params.append('sort_order', this.sortOrder);
|
||||
|
||||
const data = await apiClient.get(`/admin/subscriptions/billing/history?${params}`);
|
||||
this.invoices = data.invoices || [];
|
||||
this.pagination.total = data.total;
|
||||
this.pagination.pages = data.pages;
|
||||
|
||||
// Count by status (from loaded data for approximation)
|
||||
this.updateStatusCounts();
|
||||
|
||||
billingLog.info(`Loaded ${this.invoices.length} invoices (total: ${this.pagination.total})`);
|
||||
} catch (error) {
|
||||
billingLog.error('Failed to load invoices:', error);
|
||||
this.error = error.message || 'Failed to load billing history';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
handleSort(key) {
|
||||
if (this.sortBy === key) {
|
||||
this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
this.sortBy = key;
|
||||
this.sortOrder = 'asc';
|
||||
}
|
||||
this.pagination.page = 1;
|
||||
this.loadInvoices();
|
||||
},
|
||||
|
||||
updateStatusCounts() {
|
||||
// Reset counts
|
||||
this.statusCounts = {
|
||||
paid: 0,
|
||||
open: 0,
|
||||
draft: 0,
|
||||
uncollectible: 0,
|
||||
void: 0
|
||||
};
|
||||
|
||||
// Count from current page (approximation)
|
||||
for (const invoice of this.invoices) {
|
||||
if (this.statusCounts[invoice.status] !== undefined) {
|
||||
this.statusCounts[invoice.status]++;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
resetFilters() {
|
||||
this.filters = {
|
||||
vendor_id: '',
|
||||
status: ''
|
||||
};
|
||||
this.pagination.page = 1;
|
||||
this.loadInvoices();
|
||||
},
|
||||
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
this.loadInvoices();
|
||||
}
|
||||
},
|
||||
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.totalPages) {
|
||||
this.pagination.page++;
|
||||
this.loadInvoices();
|
||||
}
|
||||
},
|
||||
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadInvoices();
|
||||
}
|
||||
},
|
||||
|
||||
formatDate(dateStr) {
|
||||
if (!dateStr) return '-';
|
||||
return new Date(dateStr).toLocaleDateString('de-LU', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
},
|
||||
|
||||
formatCurrency(cents) {
|
||||
if (cents === null || cents === undefined) return '-';
|
||||
return new Intl.NumberFormat('de-LU', {
|
||||
style: 'currency',
|
||||
currency: 'EUR'
|
||||
}).format(cents / 100);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
billingLog.info('Billing history module loaded');
|
||||
@@ -1,292 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
/**
|
||||
* Code Quality Dashboard Component
|
||||
* Manages the unified code quality dashboard page
|
||||
* Supports multiple validator types: architecture, security, performance
|
||||
*/
|
||||
|
||||
// Use centralized logger
|
||||
const codeQualityLog = window.LogConfig.createLogger('CODE-QUALITY');
|
||||
|
||||
function codeQualityDashboard() {
|
||||
return {
|
||||
// Extend base data
|
||||
...data(),
|
||||
|
||||
// Set current page for navigation
|
||||
currentPage: 'code-quality',
|
||||
|
||||
// Validator type selection
|
||||
selectedValidator: 'all', // 'all', 'architecture', 'security', 'performance'
|
||||
validatorTypes: ['architecture', 'security', 'performance'],
|
||||
|
||||
// Dashboard-specific data
|
||||
loading: false,
|
||||
scanning: false,
|
||||
scanDropdownOpen: false,
|
||||
error: null,
|
||||
successMessage: null,
|
||||
scanProgress: null, // Progress message during scan
|
||||
runningScans: [], // Track running scan IDs
|
||||
pollInterval: null, // Polling interval ID
|
||||
stats: {
|
||||
total_violations: 0,
|
||||
errors: 0,
|
||||
warnings: 0,
|
||||
info: 0,
|
||||
open: 0,
|
||||
assigned: 0,
|
||||
resolved: 0,
|
||||
ignored: 0,
|
||||
technical_debt_score: 100,
|
||||
trend: [],
|
||||
by_severity: {},
|
||||
by_rule: {},
|
||||
by_module: {},
|
||||
top_files: [],
|
||||
last_scan: null,
|
||||
validator_type: null,
|
||||
by_validator: {}
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminCodeQualityDashboardInitialized) return;
|
||||
window._adminCodeQualityDashboardInitialized = true;
|
||||
|
||||
try {
|
||||
// Check URL for validator_type parameter
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const urlValidator = urlParams.get('validator_type');
|
||||
if (urlValidator && this.validatorTypes.includes(urlValidator)) {
|
||||
this.selectedValidator = urlValidator;
|
||||
} else {
|
||||
// Ensure 'all' is explicitly set as default
|
||||
this.selectedValidator = 'all';
|
||||
}
|
||||
|
||||
await this.loadStats();
|
||||
|
||||
// Check for any running scans on page load
|
||||
await this.checkRunningScans();
|
||||
} catch (error) {
|
||||
codeQualityLog.error('Failed to initialize code quality dashboard:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async checkRunningScans() {
|
||||
try {
|
||||
const runningScans = await apiClient.get('/admin/code-quality/scans/running');
|
||||
if (runningScans && runningScans.length > 0) {
|
||||
this.scanning = true;
|
||||
this.runningScans = runningScans.map(s => s.id);
|
||||
this.updateProgressMessage(runningScans);
|
||||
this.startPolling();
|
||||
}
|
||||
} catch (err) {
|
||||
codeQualityLog.error('Failed to check running scans:', err);
|
||||
}
|
||||
},
|
||||
|
||||
updateProgressMessage(scans) {
|
||||
const runningScans = scans.filter(s => s.status === 'running' || s.status === 'pending');
|
||||
if (runningScans.length === 0) {
|
||||
this.scanProgress = null;
|
||||
return;
|
||||
}
|
||||
|
||||
// Show progress from the first running scan
|
||||
const firstRunning = runningScans.find(s => s.status === 'running');
|
||||
if (firstRunning && firstRunning.progress_message) {
|
||||
this.scanProgress = firstRunning.progress_message;
|
||||
} else {
|
||||
const validatorNames = runningScans.map(s => this.capitalizeFirst(s.validator_type));
|
||||
this.scanProgress = `Running ${validatorNames.join(', ')} scan${runningScans.length > 1 ? 's' : ''}...`;
|
||||
}
|
||||
},
|
||||
|
||||
async loadStats() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
// Build URL with validator_type filter if not 'all'
|
||||
let url = '/admin/code-quality/stats';
|
||||
if (this.selectedValidator !== 'all') {
|
||||
url += `?validator_type=${this.selectedValidator}`;
|
||||
}
|
||||
|
||||
const stats = await apiClient.get(url);
|
||||
this.stats = stats;
|
||||
} catch (err) {
|
||||
codeQualityLog.error('Failed to load stats:', err);
|
||||
this.error = err.message;
|
||||
|
||||
// Redirect to login if unauthorized
|
||||
if (err.message.includes('Unauthorized')) {
|
||||
window.location.href = '/admin/login';
|
||||
}
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async selectValidator(validatorType) {
|
||||
if (this.selectedValidator !== validatorType) {
|
||||
this.selectedValidator = validatorType;
|
||||
await this.loadStats();
|
||||
|
||||
// Update URL without reload
|
||||
const url = new URL(window.location);
|
||||
if (validatorType === 'all') {
|
||||
url.searchParams.delete('validator_type');
|
||||
} else {
|
||||
url.searchParams.set('validator_type', validatorType);
|
||||
}
|
||||
window.history.pushState({}, '', url);
|
||||
}
|
||||
},
|
||||
|
||||
async runScan(validatorType = 'all') {
|
||||
this.scanning = true;
|
||||
this.error = null;
|
||||
this.successMessage = null;
|
||||
this.scanProgress = 'Queuing scan...';
|
||||
|
||||
try {
|
||||
// Determine which validators to run
|
||||
const validatorTypesToRun = validatorType === 'all'
|
||||
? this.validatorTypes
|
||||
: [validatorType];
|
||||
|
||||
const result = await apiClient.post('/admin/code-quality/scan', {
|
||||
validator_types: validatorTypesToRun
|
||||
});
|
||||
|
||||
// Store running scan IDs for polling
|
||||
this.runningScans = result.scans.map(s => s.id);
|
||||
|
||||
// Show initial status message
|
||||
const validatorNames = validatorTypesToRun.map(v => this.capitalizeFirst(v));
|
||||
this.scanProgress = `Running ${validatorNames.join(', ')} scan${validatorNames.length > 1 ? 's' : ''}...`;
|
||||
|
||||
// Start polling for completion
|
||||
this.startPolling();
|
||||
|
||||
} catch (err) {
|
||||
codeQualityLog.error('Failed to run scan:', err);
|
||||
this.error = err.message;
|
||||
this.scanning = false;
|
||||
this.scanProgress = null;
|
||||
|
||||
// Redirect to login if unauthorized
|
||||
if (err.message.includes('Unauthorized')) {
|
||||
window.location.href = '/admin/login';
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
startPolling() {
|
||||
// Clear any existing polling
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval);
|
||||
}
|
||||
|
||||
// Poll every 3 seconds
|
||||
this.pollInterval = setInterval(async () => {
|
||||
await this.pollScanStatus();
|
||||
}, 3000);
|
||||
},
|
||||
|
||||
stopPolling() {
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval);
|
||||
this.pollInterval = null;
|
||||
}
|
||||
},
|
||||
|
||||
async pollScanStatus() {
|
||||
if (this.runningScans.length === 0) {
|
||||
this.stopPolling();
|
||||
this.scanning = false;
|
||||
this.scanProgress = null;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const runningScans = await apiClient.get('/admin/code-quality/scans/running');
|
||||
|
||||
// Update progress message from running scans
|
||||
this.updateProgressMessage(runningScans);
|
||||
|
||||
// Check if our scans have completed
|
||||
const stillRunning = this.runningScans.filter(id =>
|
||||
runningScans.some(s => s.id === id)
|
||||
);
|
||||
|
||||
if (stillRunning.length === 0) {
|
||||
// All scans completed - get final results
|
||||
await this.handleScanCompletion();
|
||||
} else {
|
||||
// Update running scans list
|
||||
this.runningScans = stillRunning;
|
||||
}
|
||||
} catch (err) {
|
||||
codeQualityLog.error('Failed to poll scan status:', err);
|
||||
}
|
||||
},
|
||||
|
||||
async handleScanCompletion() {
|
||||
this.stopPolling();
|
||||
|
||||
// Get results for all completed scans
|
||||
let totalViolations = 0;
|
||||
let totalErrors = 0;
|
||||
let totalWarnings = 0;
|
||||
const completedScans = [];
|
||||
|
||||
for (const scanId of this.runningScans) {
|
||||
try {
|
||||
const scan = await apiClient.get(`/admin/code-quality/scans/${scanId}/status`);
|
||||
completedScans.push(scan);
|
||||
totalViolations += scan.total_violations || 0;
|
||||
totalErrors += scan.errors || 0;
|
||||
totalWarnings += scan.warnings || 0;
|
||||
} catch (err) {
|
||||
codeQualityLog.error(`Failed to get scan ${scanId} results:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
// Format success message based on number of validators run
|
||||
if (completedScans.length > 1) {
|
||||
this.successMessage = `Scan completed: ${totalViolations} total violations found (${totalErrors} errors, ${totalWarnings} warnings) across ${completedScans.length} validators`;
|
||||
} else if (completedScans.length === 1) {
|
||||
const scan = completedScans[0];
|
||||
this.successMessage = `${this.capitalizeFirst(scan.validator_type)} scan completed: ${scan.total_violations} violations found (${scan.errors} errors, ${scan.warnings} warnings)`;
|
||||
} else {
|
||||
this.successMessage = 'Scan completed';
|
||||
}
|
||||
|
||||
// Reload stats after scan
|
||||
await this.loadStats();
|
||||
|
||||
// Reset scanning state
|
||||
this.scanning = false;
|
||||
this.scanProgress = null;
|
||||
this.runningScans = [];
|
||||
|
||||
// Clear success message after 5 seconds
|
||||
setTimeout(() => {
|
||||
this.successMessage = null;
|
||||
}, 5000);
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
await this.loadStats();
|
||||
},
|
||||
|
||||
capitalizeFirst(str) {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
/**
|
||||
* Code Quality Violations List Component
|
||||
* Manages the violations list page with filtering and pagination
|
||||
*/
|
||||
|
||||
// ✅ Use centralized logger
|
||||
const codeQualityViolationsLog = window.LogConfig.createLogger('CODE-QUALITY');
|
||||
|
||||
function codeQualityViolations() {
|
||||
return {
|
||||
// Extend base data
|
||||
...data(),
|
||||
|
||||
// Set current page for navigation
|
||||
currentPage: 'code-quality',
|
||||
|
||||
// Violations-specific data
|
||||
loading: false,
|
||||
error: null,
|
||||
violations: [],
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
filters: {
|
||||
validator_type: '',
|
||||
severity: '',
|
||||
status: '',
|
||||
rule_id: '',
|
||||
file_path: ''
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._codeQualityViolationsInitialized) {
|
||||
codeQualityViolationsLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._codeQualityViolationsInitialized = true;
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
// Load filters from URL params
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
this.filters.validator_type = params.get('validator_type') || '';
|
||||
this.filters.severity = params.get('severity') || '';
|
||||
this.filters.status = params.get('status') || '';
|
||||
this.filters.rule_id = params.get('rule_id') || '';
|
||||
this.filters.file_path = params.get('file_path') || '';
|
||||
|
||||
await this.loadViolations();
|
||||
},
|
||||
|
||||
async loadViolations() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
// Build query params
|
||||
const params = {
|
||||
page: this.pagination.page.toString(),
|
||||
page_size: this.pagination.per_page.toString()
|
||||
};
|
||||
|
||||
if (this.filters.validator_type) params.validator_type = this.filters.validator_type;
|
||||
if (this.filters.severity) params.severity = this.filters.severity;
|
||||
if (this.filters.status) params.status = this.filters.status;
|
||||
if (this.filters.rule_id) params.rule_id = this.filters.rule_id;
|
||||
if (this.filters.file_path) params.file_path = this.filters.file_path;
|
||||
|
||||
const data = await apiClient.get('/admin/code-quality/violations', params);
|
||||
|
||||
this.violations = data.violations;
|
||||
this.pagination.total = data.total;
|
||||
this.pagination.pages = data.total_pages;
|
||||
|
||||
// Update URL with current filters (without reloading)
|
||||
this.updateURL();
|
||||
} catch (err) {
|
||||
codeQualityViolationsLog.error('Failed to load violations:', err);
|
||||
this.error = err.message;
|
||||
|
||||
// Redirect to login if unauthorized
|
||||
if (err.message.includes('Unauthorized')) {
|
||||
window.location.href = '/admin/login';
|
||||
}
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
applyFilters() {
|
||||
// Reset to page 1 when filters change
|
||||
this.pagination.page = 1;
|
||||
this.loadViolations();
|
||||
},
|
||||
|
||||
async nextPage() {
|
||||
if (this.pagination.page < this.pagination.pages) {
|
||||
this.pagination.page++;
|
||||
await this.loadViolations();
|
||||
}
|
||||
},
|
||||
|
||||
// Computed: Total number of 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: Generate page numbers array with ellipsis
|
||||
get pageNumbers() {
|
||||
const pages = [];
|
||||
const totalPages = this.totalPages;
|
||||
const current = this.pagination.page;
|
||||
|
||||
if (totalPages <= 7) {
|
||||
// Show all pages if 7 or fewer
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
// Always show first page
|
||||
pages.push(1);
|
||||
|
||||
if (current > 3) {
|
||||
pages.push('...');
|
||||
}
|
||||
|
||||
// Show pages around current page
|
||||
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('...');
|
||||
}
|
||||
|
||||
// Always show last page
|
||||
pages.push(totalPages);
|
||||
}
|
||||
|
||||
return pages;
|
||||
},
|
||||
|
||||
async previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
await this.loadViolations();
|
||||
}
|
||||
},
|
||||
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadViolations();
|
||||
}
|
||||
},
|
||||
|
||||
updateURL() {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (this.filters.validator_type) params.set('validator_type', this.filters.validator_type);
|
||||
if (this.filters.severity) params.set('severity', this.filters.severity);
|
||||
if (this.filters.status) params.set('status', this.filters.status);
|
||||
if (this.filters.rule_id) params.set('rule_id', this.filters.rule_id);
|
||||
if (this.filters.file_path) params.set('file_path', this.filters.file_path);
|
||||
|
||||
const newURL = params.toString()
|
||||
? `${window.location.pathname}?${params.toString()}`
|
||||
: window.location.pathname;
|
||||
|
||||
window.history.replaceState({}, '', newURL);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,404 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/customers.js
|
||||
/**
|
||||
* Admin customer management page logic
|
||||
*/
|
||||
|
||||
// Create logger for this module
|
||||
const customersLog = window.LogConfig?.createLogger('CUSTOMERS') || console;
|
||||
|
||||
function adminCustomers() {
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Page identifier
|
||||
currentPage: 'customers',
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
loadingCustomers: false,
|
||||
|
||||
// Error state
|
||||
error: '',
|
||||
|
||||
// Data
|
||||
customers: [],
|
||||
stats: {
|
||||
total: 0,
|
||||
active: 0,
|
||||
inactive: 0,
|
||||
with_orders: 0,
|
||||
total_spent: 0,
|
||||
total_orders: 0,
|
||||
avg_order_value: 0
|
||||
},
|
||||
|
||||
// Pagination (standard structure matching pagination macro)
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
search: '',
|
||||
is_active: '',
|
||||
vendor_id: ''
|
||||
},
|
||||
|
||||
// Selected vendor (for prominent display and filtering)
|
||||
selectedVendor: null,
|
||||
|
||||
// Tom Select instance
|
||||
vendorSelectInstance: 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() {
|
||||
customersLog.debug('Customers page initialized');
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
// Initialize Tom Select for vendor filter
|
||||
this.initVendorSelect();
|
||||
|
||||
// Check localStorage for saved vendor
|
||||
const savedVendorId = localStorage.getItem('customers_selected_vendor_id');
|
||||
if (savedVendorId) {
|
||||
customersLog.debug('Restoring saved vendor:', savedVendorId);
|
||||
// Restore vendor after a short delay to ensure TomSelect is ready
|
||||
setTimeout(async () => {
|
||||
await this.restoreSavedVendor(parseInt(savedVendorId));
|
||||
}, 200);
|
||||
// Load stats but not customers (restoreSavedVendor will do that)
|
||||
await this.loadStats();
|
||||
} else {
|
||||
// No saved vendor - load all data
|
||||
await Promise.all([
|
||||
this.loadCustomers(),
|
||||
this.loadStats()
|
||||
]);
|
||||
}
|
||||
|
||||
this.loading = false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Restore saved vendor from localStorage
|
||||
*/
|
||||
async restoreSavedVendor(vendorId) {
|
||||
try {
|
||||
const vendor = await apiClient.get(`/admin/vendors/${vendorId}`);
|
||||
if (this.vendorSelectInstance && vendor) {
|
||||
// Add the vendor as an option and select it
|
||||
this.vendorSelectInstance.addOption({
|
||||
id: vendor.id,
|
||||
name: vendor.name,
|
||||
vendor_code: vendor.vendor_code
|
||||
});
|
||||
this.vendorSelectInstance.setValue(vendor.id, true);
|
||||
|
||||
// Set the filter state
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_id = vendor.id;
|
||||
|
||||
customersLog.debug('Restored vendor:', vendor.name);
|
||||
|
||||
// Load customers with the vendor filter applied
|
||||
await this.loadCustomers();
|
||||
}
|
||||
} catch (error) {
|
||||
customersLog.error('Failed to restore saved vendor, clearing localStorage:', error);
|
||||
localStorage.removeItem('customers_selected_vendor_id');
|
||||
// Load unfiltered customers as fallback
|
||||
await this.loadCustomers();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize Tom Select for vendor autocomplete
|
||||
*/
|
||||
initVendorSelect() {
|
||||
const selectEl = this.$refs.vendorSelect;
|
||||
if (!selectEl) {
|
||||
customersLog.warn('Vendor select element not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for Tom Select to be available
|
||||
if (typeof TomSelect === 'undefined') {
|
||||
customersLog.warn('TomSelect not loaded, retrying in 100ms');
|
||||
setTimeout(() => this.initVendorSelect(), 100);
|
||||
return;
|
||||
}
|
||||
|
||||
this.vendorSelectInstance = new TomSelect(selectEl, {
|
||||
valueField: 'id',
|
||||
labelField: 'name',
|
||||
searchField: ['name', 'vendor_code'],
|
||||
placeholder: 'Filter by vendor...',
|
||||
allowEmptyOption: true,
|
||||
load: async (query, callback) => {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors', {
|
||||
search: query,
|
||||
limit: 50
|
||||
});
|
||||
callback(response.vendors || []);
|
||||
} catch (error) {
|
||||
customersLog.error('Failed to search vendors:', error);
|
||||
callback([]);
|
||||
}
|
||||
},
|
||||
render: {
|
||||
option: (data, escape) => {
|
||||
return `<div class="flex items-center justify-between py-1">
|
||||
<span>${escape(data.name)}</span>
|
||||
<span class="text-xs text-gray-400 font-mono">${escape(data.vendor_code || '')}</span>
|
||||
</div>`;
|
||||
},
|
||||
item: (data, escape) => {
|
||||
return `<div>${escape(data.name)}</div>`;
|
||||
}
|
||||
},
|
||||
onChange: (value) => {
|
||||
if (value) {
|
||||
const vendor = this.vendorSelectInstance.options[value];
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_id = value;
|
||||
// Save to localStorage
|
||||
localStorage.setItem('customers_selected_vendor_id', value.toString());
|
||||
} else {
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_id = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('customers_selected_vendor_id');
|
||||
}
|
||||
this.pagination.page = 1;
|
||||
this.loadCustomers();
|
||||
this.loadStats();
|
||||
}
|
||||
});
|
||||
|
||||
customersLog.debug('Vendor select initialized');
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear vendor filter
|
||||
*/
|
||||
clearVendorFilter() {
|
||||
if (this.vendorSelectInstance) {
|
||||
this.vendorSelectInstance.clear();
|
||||
}
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_id = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('customers_selected_vendor_id');
|
||||
this.pagination.page = 1;
|
||||
this.loadCustomers();
|
||||
this.loadStats();
|
||||
},
|
||||
|
||||
/**
|
||||
* Load customers with current filters
|
||||
*/
|
||||
async loadCustomers() {
|
||||
this.loadingCustomers = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
skip: ((this.pagination.page - 1) * this.pagination.per_page).toString(),
|
||||
limit: this.pagination.per_page.toString()
|
||||
});
|
||||
|
||||
if (this.filters.search) {
|
||||
params.append('search', this.filters.search);
|
||||
}
|
||||
|
||||
if (this.filters.is_active !== '') {
|
||||
params.append('is_active', this.filters.is_active);
|
||||
}
|
||||
|
||||
if (this.filters.vendor_id) {
|
||||
params.append('vendor_id', this.filters.vendor_id);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(`/admin/customers?${params}`);
|
||||
this.customers = response.customers || [];
|
||||
this.pagination.total = response.total || 0;
|
||||
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
|
||||
} catch (error) {
|
||||
customersLog.error('Failed to load customers:', error);
|
||||
this.error = error.message || 'Failed to load customers';
|
||||
this.customers = [];
|
||||
} finally {
|
||||
this.loadingCustomers = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load customer statistics
|
||||
*/
|
||||
async loadStats() {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (this.filters.vendor_id) {
|
||||
params.append('vendor_id', this.filters.vendor_id);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(`/admin/customers/stats?${params}`);
|
||||
this.stats = response;
|
||||
} catch (error) {
|
||||
customersLog.error('Failed to load stats:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset pagination and reload
|
||||
*/
|
||||
async resetAndLoad() {
|
||||
this.pagination.page = 1;
|
||||
await Promise.all([
|
||||
this.loadCustomers(),
|
||||
this.loadStats()
|
||||
]);
|
||||
},
|
||||
|
||||
/**
|
||||
* Go to previous page
|
||||
*/
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
this.loadCustomers();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Go to next page
|
||||
*/
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.totalPages) {
|
||||
this.pagination.page++;
|
||||
this.loadCustomers();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Go to specific page
|
||||
*/
|
||||
goToPage(pageNum) {
|
||||
if (typeof pageNum === 'number' && pageNum !== this.pagination.page) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadCustomers();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Toggle customer active status
|
||||
*/
|
||||
async toggleStatus(customer) {
|
||||
const action = customer.is_active ? 'deactivate' : 'activate';
|
||||
if (!confirm(`Are you sure you want to ${action} this customer?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await apiClient.patch(`/admin/customers/${customer.id}/toggle-status`);
|
||||
customer.is_active = response.is_active;
|
||||
|
||||
// Update stats
|
||||
if (response.is_active) {
|
||||
this.stats.active++;
|
||||
this.stats.inactive--;
|
||||
} else {
|
||||
this.stats.active--;
|
||||
this.stats.inactive++;
|
||||
}
|
||||
|
||||
customersLog.info(response.message);
|
||||
} catch (error) {
|
||||
customersLog.error('Failed to toggle status:', error);
|
||||
Utils.showToast(error.message || 'Failed to toggle customer status', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format currency for display
|
||||
*/
|
||||
formatCurrency(amount) {
|
||||
if (amount == null) return '-';
|
||||
return new Intl.NumberFormat('de-DE', {
|
||||
style: 'currency',
|
||||
currency: 'EUR'
|
||||
}).format(amount);
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date for display
|
||||
*/
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return '-';
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('en-GB', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
} catch {
|
||||
return dateString;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,267 +0,0 @@
|
||||
/**
|
||||
* Email Templates Management Page
|
||||
*
|
||||
* Handles:
|
||||
* - Listing all platform email templates
|
||||
* - Editing template content (all languages)
|
||||
* - Preview and test email sending
|
||||
*/
|
||||
|
||||
const emailTemplatesLog = window.LogConfig?.createLogger?.('emailTemplates') ||
|
||||
{ info: () => {}, debug: () => {}, warn: () => {}, error: () => {} };
|
||||
|
||||
function emailTemplatesPage() {
|
||||
return {
|
||||
// Data
|
||||
loading: true,
|
||||
templates: [],
|
||||
categories: [],
|
||||
selectedCategory: null,
|
||||
|
||||
// Edit Modal
|
||||
showEditModal: false,
|
||||
editingTemplate: null,
|
||||
editLanguage: 'en',
|
||||
loadingTemplate: false,
|
||||
editForm: {
|
||||
subject: '',
|
||||
body_html: '',
|
||||
body_text: '',
|
||||
variables: [],
|
||||
required_variables: []
|
||||
},
|
||||
saving: false,
|
||||
|
||||
// Preview Modal
|
||||
showPreviewModal: false,
|
||||
previewData: null,
|
||||
|
||||
// Test Email Modal
|
||||
showTestEmailModal: false,
|
||||
testEmailAddress: '',
|
||||
sendingTest: false,
|
||||
|
||||
// Computed
|
||||
get filteredTemplates() {
|
||||
if (!this.selectedCategory) {
|
||||
return this.templates;
|
||||
}
|
||||
return this.templates.filter(t => t.category === this.selectedCategory);
|
||||
},
|
||||
|
||||
// Lifecycle
|
||||
async init() {
|
||||
if (window._adminEmailTemplatesInitialized) return;
|
||||
window._adminEmailTemplatesInitialized = true;
|
||||
|
||||
await this.loadData();
|
||||
},
|
||||
|
||||
// Data Loading
|
||||
async loadData() {
|
||||
this.loading = true;
|
||||
try {
|
||||
const [templatesData, categoriesData] = await Promise.all([
|
||||
apiClient.get('/admin/email-templates'),
|
||||
apiClient.get('/admin/email-templates/categories')
|
||||
]);
|
||||
|
||||
this.templates = templatesData.templates || [];
|
||||
this.categories = categoriesData.categories || [];
|
||||
} catch (error) {
|
||||
emailTemplatesLog.error('Failed to load email templates:', error);
|
||||
Utils.showToast('Failed to load templates', 'error');
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Category styling
|
||||
getCategoryClass(category) {
|
||||
const classes = {
|
||||
'auth': 'bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200',
|
||||
'orders': 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200',
|
||||
'billing': 'bg-orange-100 dark:bg-orange-900 text-orange-800 dark:text-orange-200',
|
||||
'system': 'bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-200',
|
||||
'marketing': 'bg-pink-100 dark:bg-pink-900 text-pink-800 dark:text-pink-200'
|
||||
};
|
||||
return classes[category] || 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200';
|
||||
},
|
||||
|
||||
// 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(
|
||||
`/admin/email-templates/${this.editingTemplate.code}/${this.editLanguage}`
|
||||
);
|
||||
|
||||
this.editForm = {
|
||||
subject: data.subject || '',
|
||||
body_html: data.body_html || '',
|
||||
body_text: data.body_text || '',
|
||||
variables: data.variables || [],
|
||||
required_variables: data.required_variables || []
|
||||
};
|
||||
} catch (error) {
|
||||
if (error.status === 404) {
|
||||
// Template doesn't exist for this language yet
|
||||
this.editForm = {
|
||||
subject: '',
|
||||
body_html: '',
|
||||
body_text: '',
|
||||
variables: [],
|
||||
required_variables: []
|
||||
};
|
||||
Utils.showToast(`No template for ${this.editLanguage.toUpperCase()} - create one by saving`, 'info');
|
||||
} else {
|
||||
emailTemplatesLog.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: '',
|
||||
variables: [],
|
||||
required_variables: []
|
||||
};
|
||||
},
|
||||
|
||||
async saveTemplate() {
|
||||
if (!this.editingTemplate) return;
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
await apiClient.put(
|
||||
`/admin/email-templates/${this.editingTemplate.code}/${this.editLanguage}`,
|
||||
{
|
||||
subject: this.editForm.subject,
|
||||
body_html: this.editForm.body_html,
|
||||
body_text: this.editForm.body_text
|
||||
}
|
||||
);
|
||||
|
||||
Utils.showToast('Template saved successfully', 'success');
|
||||
// Refresh templates list
|
||||
await this.loadData();
|
||||
} catch (error) {
|
||||
emailTemplatesLog.error('Failed to save template:', error);
|
||||
Utils.showToast(error.detail || 'Failed to save template', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Preview
|
||||
async previewTemplate(template) {
|
||||
try {
|
||||
// Use sample variables for preview
|
||||
const sampleVariables = this.getSampleVariables(template.code);
|
||||
|
||||
const data = await apiClient.post(
|
||||
`/admin/email-templates/${template.code}/preview`,
|
||||
{
|
||||
template_code: template.code,
|
||||
language: 'en',
|
||||
variables: sampleVariables
|
||||
}
|
||||
);
|
||||
|
||||
this.previewData = data;
|
||||
this.showPreviewModal = true;
|
||||
} catch (error) {
|
||||
emailTemplatesLog.error('Failed to preview template:', error);
|
||||
Utils.showToast('Failed to load preview', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
getSampleVariables(templateCode) {
|
||||
// Sample variables for common templates
|
||||
const samples = {
|
||||
'signup_welcome': {
|
||||
first_name: 'John',
|
||||
company_name: 'Acme Corp',
|
||||
email: 'john@example.com',
|
||||
vendor_code: 'acme',
|
||||
login_url: 'https://example.com/login',
|
||||
trial_days: '14',
|
||||
tier_name: 'Business'
|
||||
},
|
||||
'order_confirmation': {
|
||||
customer_name: 'Jane Doe',
|
||||
order_number: 'ORD-12345',
|
||||
order_total: '99.99',
|
||||
order_items_count: '3',
|
||||
order_date: '2024-01-15',
|
||||
shipping_address: '123 Main St, Luxembourg City, L-1234'
|
||||
},
|
||||
'password_reset': {
|
||||
customer_name: 'John Doe',
|
||||
reset_link: 'https://example.com/reset?token=abc123',
|
||||
expiry_hours: '1'
|
||||
},
|
||||
'team_invite': {
|
||||
invitee_name: 'Jane',
|
||||
inviter_name: 'John',
|
||||
vendor_name: 'Acme Corp',
|
||||
role: 'Admin',
|
||||
accept_url: 'https://example.com/accept',
|
||||
expires_in_days: '7'
|
||||
}
|
||||
};
|
||||
return samples[templateCode] || { platform_name: 'Wizamart' };
|
||||
},
|
||||
|
||||
// Test Email
|
||||
sendTestEmail() {
|
||||
this.showTestEmailModal = true;
|
||||
},
|
||||
|
||||
async confirmSendTestEmail() {
|
||||
if (!this.testEmailAddress || !this.editingTemplate) return;
|
||||
|
||||
this.sendingTest = true;
|
||||
try {
|
||||
const result = await apiClient.post(
|
||||
`/admin/email-templates/${this.editingTemplate.code}/test`,
|
||||
{
|
||||
template_code: this.editingTemplate.code,
|
||||
language: this.editLanguage,
|
||||
to_email: this.testEmailAddress,
|
||||
variables: this.getSampleVariables(this.editingTemplate.code)
|
||||
}
|
||||
);
|
||||
|
||||
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) {
|
||||
emailTemplatesLog.error('Failed to send test email:', error);
|
||||
Utils.showToast('Failed to send test email', 'error');
|
||||
} finally {
|
||||
this.sendingTest = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,468 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/imports.js
|
||||
/**
|
||||
* Admin platform monitoring - all import jobs
|
||||
*/
|
||||
|
||||
// ✅ Use centralized logger
|
||||
const adminImportsLog = window.LogConfig.loggers.imports;
|
||||
|
||||
adminImportsLog.info('Loading...');
|
||||
|
||||
function adminImports() {
|
||||
adminImportsLog.debug('adminImports() called');
|
||||
|
||||
return {
|
||||
// ✅ Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// ✅ Set page identifier
|
||||
currentPage: 'imports',
|
||||
|
||||
// Loading states
|
||||
loading: false,
|
||||
error: '',
|
||||
|
||||
// Vendors list
|
||||
vendors: [],
|
||||
|
||||
// Stats
|
||||
stats: {
|
||||
total: 0,
|
||||
active: 0,
|
||||
completed: 0,
|
||||
failed: 0
|
||||
},
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
vendor_id: '',
|
||||
status: '',
|
||||
marketplace: '',
|
||||
created_by: '' // 'me' or empty
|
||||
},
|
||||
|
||||
// Import jobs
|
||||
jobs: [],
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Modal state
|
||||
showJobModal: false,
|
||||
selectedJob: null,
|
||||
|
||||
// Job errors state
|
||||
jobErrors: [],
|
||||
jobErrorsTotal: 0,
|
||||
jobErrorsPage: 1,
|
||||
loadingErrors: false,
|
||||
|
||||
// Auto-refresh for active jobs
|
||||
autoRefreshInterval: null,
|
||||
|
||||
// Computed: Total pages
|
||||
get totalPages() {
|
||||
return this.pagination.pages;
|
||||
},
|
||||
|
||||
// Computed: Start index for pagination display
|
||||
get startIndex() {
|
||||
if (this.pagination.total === 0) return 0;
|
||||
return (this.pagination.page - 1) * this.pagination.per_page + 1;
|
||||
},
|
||||
|
||||
// Computed: End index for pagination display
|
||||
get endIndex() {
|
||||
const end = this.pagination.page * this.pagination.per_page;
|
||||
return end > this.pagination.total ? this.pagination.total : end;
|
||||
},
|
||||
|
||||
// Computed: Page numbers for pagination
|
||||
get pageNumbers() {
|
||||
const pages = [];
|
||||
const totalPages = this.totalPages;
|
||||
const current = this.pagination.page;
|
||||
|
||||
if (totalPages <= 7) {
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
pages.push(1);
|
||||
if (current > 3) {
|
||||
pages.push('...');
|
||||
}
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(totalPages - 1, current + 1);
|
||||
for (let i = start; i <= end; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
if (current < totalPages - 2) {
|
||||
pages.push('...');
|
||||
}
|
||||
pages.push(totalPages);
|
||||
}
|
||||
return pages;
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminImportsInitialized) {
|
||||
return;
|
||||
}
|
||||
window._adminImportsInitialized = true;
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
// IMPORTANT: Call parent init first
|
||||
const parentInit = data().init;
|
||||
if (parentInit) {
|
||||
await parentInit.call(this);
|
||||
}
|
||||
|
||||
await this.loadVendors();
|
||||
await this.loadJobs();
|
||||
await this.loadStats();
|
||||
|
||||
// Auto-refresh active jobs every 15 seconds
|
||||
this.startAutoRefresh();
|
||||
},
|
||||
|
||||
/**
|
||||
* Load all vendors for filtering
|
||||
*/
|
||||
async loadVendors() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors?limit=1000');
|
||||
this.vendors = response.vendors || [];
|
||||
adminImportsLog.debug('Loaded vendors:', this.vendors.length);
|
||||
} catch (error) {
|
||||
adminImportsLog.error('Failed to load vendors:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load statistics
|
||||
*/
|
||||
async loadStats() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/marketplace-import-jobs/stats');
|
||||
this.stats = {
|
||||
total: response.total || 0,
|
||||
active: (response.pending || 0) + (response.processing || 0),
|
||||
completed: response.completed || 0,
|
||||
failed: response.failed || 0
|
||||
};
|
||||
adminImportsLog.debug('Loaded stats:', this.stats);
|
||||
} catch (error) {
|
||||
adminImportsLog.error('Failed to load stats:', error);
|
||||
// Non-critical, don't show error
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load ALL import jobs (with filters)
|
||||
*/
|
||||
async loadJobs() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
// Build query params
|
||||
const params = new URLSearchParams({
|
||||
skip: (this.pagination.page - 1) * this.pagination.per_page,
|
||||
limit: this.pagination.per_page
|
||||
});
|
||||
|
||||
// Add filters
|
||||
if (this.filters.vendor_id) {
|
||||
params.append('vendor_id', this.filters.vendor_id);
|
||||
}
|
||||
if (this.filters.status) {
|
||||
params.append('status', this.filters.status);
|
||||
}
|
||||
if (this.filters.marketplace) {
|
||||
params.append('marketplace', this.filters.marketplace);
|
||||
}
|
||||
if (this.filters.created_by === 'me') {
|
||||
params.append('created_by_me', 'true');
|
||||
}
|
||||
|
||||
const response = await apiClient.get(
|
||||
`/admin/marketplace-import-jobs?${params.toString()}`
|
||||
);
|
||||
|
||||
this.jobs = response.items || [];
|
||||
this.pagination.total = response.total || 0;
|
||||
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
|
||||
|
||||
adminImportsLog.debug('Loaded all jobs:', this.jobs.length);
|
||||
} catch (error) {
|
||||
adminImportsLog.error('Failed to load jobs:', error);
|
||||
this.error = error.message || 'Failed to load import jobs';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Apply filters and reload
|
||||
*/
|
||||
async applyFilters() {
|
||||
this.pagination.page = 1; // Reset to first page when filtering
|
||||
await this.loadJobs();
|
||||
await this.loadStats(); // Update stats based on filters
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear all filters and reload
|
||||
*/
|
||||
async clearFilters() {
|
||||
this.filters.vendor_id = '';
|
||||
this.filters.status = '';
|
||||
this.filters.marketplace = '';
|
||||
this.filters.created_by = '';
|
||||
this.pagination.page = 1;
|
||||
await this.loadJobs();
|
||||
await this.loadStats();
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh jobs list
|
||||
*/
|
||||
async refreshJobs() {
|
||||
await this.loadJobs();
|
||||
await this.loadStats();
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh single job status
|
||||
*/
|
||||
async refreshJobStatus(jobId) {
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/marketplace-import-jobs/${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;
|
||||
}
|
||||
|
||||
adminImportsLog.debug('Refreshed job:', jobId);
|
||||
} catch (error) {
|
||||
adminImportsLog.error('Failed to refresh job:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* View job details in modal
|
||||
*/
|
||||
async viewJobDetails(jobId) {
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/marketplace-import-jobs/${jobId}`);
|
||||
this.selectedJob = response;
|
||||
this.showJobModal = true;
|
||||
adminImportsLog.debug('Viewing job details:', jobId);
|
||||
} catch (error) {
|
||||
adminImportsLog.error('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;
|
||||
// Clear errors state
|
||||
this.jobErrors = [];
|
||||
this.jobErrorsTotal = 0;
|
||||
this.jobErrorsPage = 1;
|
||||
},
|
||||
|
||||
/**
|
||||
* Load errors for a specific job
|
||||
*/
|
||||
async loadJobErrors(jobId) {
|
||||
if (!jobId) return;
|
||||
|
||||
this.loadingErrors = true;
|
||||
this.jobErrorsPage = 1;
|
||||
|
||||
try {
|
||||
const response = await apiClient.get(
|
||||
`/admin/marketplace-import-jobs/${jobId}/errors?page=1&limit=20`
|
||||
);
|
||||
this.jobErrors = response.errors || [];
|
||||
this.jobErrorsTotal = response.total || 0;
|
||||
adminImportsLog.debug('Loaded job errors:', this.jobErrors.length);
|
||||
} catch (error) {
|
||||
adminImportsLog.error('Failed to load job errors:', error);
|
||||
this.error = error.message || 'Failed to load import errors';
|
||||
} finally {
|
||||
this.loadingErrors = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load more errors (pagination)
|
||||
*/
|
||||
async loadMoreJobErrors(jobId) {
|
||||
if (!jobId || this.loadingErrors) return;
|
||||
|
||||
this.loadingErrors = true;
|
||||
this.jobErrorsPage++;
|
||||
|
||||
try {
|
||||
const response = await apiClient.get(
|
||||
`/admin/marketplace-import-jobs/${jobId}/errors?page=${this.jobErrorsPage}&limit=20`
|
||||
);
|
||||
const newErrors = response.errors || [];
|
||||
this.jobErrors = [...this.jobErrors, ...newErrors];
|
||||
adminImportsLog.debug('Loaded more job errors:', newErrors.length);
|
||||
} catch (error) {
|
||||
adminImportsLog.error('Failed to load more job errors:', error);
|
||||
this.jobErrorsPage--; // Revert page on failure
|
||||
} finally {
|
||||
this.loadingErrors = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get vendor name by ID
|
||||
*/
|
||||
getVendorName(vendorId) {
|
||||
const vendor = this.vendors.find(v => v.id === vendorId);
|
||||
return vendor ? `${vendor.name} (${vendor.vendor_code})` : `Vendor #${vendorId}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Previous page
|
||||
*/
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
this.loadJobs();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Next page
|
||||
*/
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.totalPages) {
|
||||
this.pagination.page++;
|
||||
this.loadJobs();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Go to specific page
|
||||
*/
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadJobs();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date for display
|
||||
*/
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return 'N/A';
|
||||
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleString('en-US', {
|
||||
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 15 seconds if there are active jobs
|
||||
this.autoRefreshInterval = setInterval(async () => {
|
||||
const hasActiveJobs = this.jobs.some(job =>
|
||||
job.status === 'pending' || job.status === 'processing'
|
||||
);
|
||||
|
||||
if (hasActiveJobs) {
|
||||
adminImportsLog.debug('Auto-refreshing active jobs...');
|
||||
await this.loadJobs();
|
||||
await this.loadStats();
|
||||
}
|
||||
}, 15000); // 15 seconds
|
||||
},
|
||||
|
||||
/**
|
||||
* Stop auto-refresh (cleanup)
|
||||
*/
|
||||
stopAutoRefresh() {
|
||||
if (this.autoRefreshInterval) {
|
||||
clearInterval(this.autoRefreshInterval);
|
||||
this.autoRefreshInterval = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Cleanup on page unload
|
||||
window.addEventListener('beforeunload', () => {
|
||||
if (window._adminImportsInstance && window._adminImportsInstance.stopAutoRefresh) {
|
||||
window._adminImportsInstance.stopAutoRefresh();
|
||||
}
|
||||
});
|
||||
@@ -1,596 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/inventory.js
|
||||
/**
|
||||
* Admin inventory management page logic
|
||||
* View and manage stock levels across all vendors
|
||||
*/
|
||||
|
||||
const adminInventoryLog = window.LogConfig.loggers.adminInventory ||
|
||||
window.LogConfig.createLogger('adminInventory', false);
|
||||
|
||||
adminInventoryLog.info('Loading...');
|
||||
|
||||
function adminInventory() {
|
||||
adminInventoryLog.info('adminInventory() 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,
|
||||
total_reserved: 0,
|
||||
total_available: 0,
|
||||
low_stock_count: 0,
|
||||
vendors_with_inventory: 0,
|
||||
unique_locations: 0
|
||||
},
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
search: '',
|
||||
vendor_id: '',
|
||||
location: '',
|
||||
low_stock: ''
|
||||
},
|
||||
|
||||
// Available locations for filter dropdown
|
||||
locations: [],
|
||||
|
||||
// Selected vendor (for prominent display and filtering)
|
||||
selectedVendor: null,
|
||||
|
||||
// Vendor selector controller (Tom Select)
|
||||
vendorSelector: null,
|
||||
|
||||
// Pagination
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Modal states
|
||||
showAdjustModal: false,
|
||||
showSetModal: false,
|
||||
showDeleteModal: false,
|
||||
showImportModal: false,
|
||||
selectedItem: null,
|
||||
|
||||
// Form data
|
||||
adjustForm: {
|
||||
quantity: 0,
|
||||
reason: ''
|
||||
},
|
||||
setForm: {
|
||||
quantity: 0
|
||||
},
|
||||
|
||||
// Import form
|
||||
importForm: {
|
||||
vendor_id: '',
|
||||
warehouse: 'strassen',
|
||||
file: null,
|
||||
clear_existing: false
|
||||
},
|
||||
importing: false,
|
||||
importResult: null,
|
||||
vendorsList: [],
|
||||
|
||||
// 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() {
|
||||
adminInventoryLog.info('Inventory init() called');
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._adminInventoryInitialized) {
|
||||
adminInventoryLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminInventoryInitialized = true;
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
// Initialize vendor selector (Tom Select)
|
||||
this.$nextTick(() => {
|
||||
this.initVendorSelector();
|
||||
});
|
||||
|
||||
// Load vendors list for import modal
|
||||
await this.loadVendorsList();
|
||||
|
||||
// Check localStorage for saved vendor
|
||||
const savedVendorId = localStorage.getItem('inventory_selected_vendor_id');
|
||||
if (savedVendorId) {
|
||||
adminInventoryLog.info('Restoring saved vendor:', savedVendorId);
|
||||
// Restore vendor after a short delay to ensure TomSelect is ready
|
||||
setTimeout(async () => {
|
||||
await this.restoreSavedVendor(parseInt(savedVendorId));
|
||||
}, 200);
|
||||
// Load stats and locations but not inventory (restoreSavedVendor will do that)
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadLocations()
|
||||
]);
|
||||
} else {
|
||||
// No saved vendor - load all data
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadLocations(),
|
||||
this.loadInventory()
|
||||
]);
|
||||
}
|
||||
|
||||
adminInventoryLog.info('Inventory initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Restore saved vendor from localStorage
|
||||
*/
|
||||
async restoreSavedVendor(vendorId) {
|
||||
try {
|
||||
const vendor = await apiClient.get(`/admin/vendors/${vendorId}`);
|
||||
if (this.vendorSelector && vendor) {
|
||||
// Use the vendor selector's setValue method
|
||||
this.vendorSelector.setValue(vendor.id, vendor);
|
||||
|
||||
// Set the filter state
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_id = vendor.id;
|
||||
|
||||
adminInventoryLog.info('Restored vendor:', vendor.name);
|
||||
|
||||
// Load inventory with the vendor filter applied
|
||||
await this.loadInventory();
|
||||
}
|
||||
} catch (error) {
|
||||
adminInventoryLog.warn('Failed to restore saved vendor, clearing localStorage:', error);
|
||||
localStorage.removeItem('inventory_selected_vendor_id');
|
||||
// Load unfiltered inventory as fallback
|
||||
await this.loadInventory();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize vendor selector with Tom Select
|
||||
*/
|
||||
initVendorSelector() {
|
||||
if (!this.$refs.vendorSelect) {
|
||||
adminInventoryLog.warn('Vendor select element not found');
|
||||
return;
|
||||
}
|
||||
|
||||
this.vendorSelector = initVendorSelector(this.$refs.vendorSelect, {
|
||||
placeholder: 'Filter by vendor...',
|
||||
onSelect: (vendor) => {
|
||||
adminInventoryLog.info('Vendor selected:', vendor);
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_id = vendor.id;
|
||||
// Save to localStorage
|
||||
localStorage.setItem('inventory_selected_vendor_id', vendor.id.toString());
|
||||
this.pagination.page = 1;
|
||||
this.loadLocations();
|
||||
this.loadInventory();
|
||||
this.loadStats();
|
||||
},
|
||||
onClear: () => {
|
||||
adminInventoryLog.info('Vendor filter cleared');
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_id = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('inventory_selected_vendor_id');
|
||||
this.pagination.page = 1;
|
||||
this.loadLocations();
|
||||
this.loadInventory();
|
||||
this.loadStats();
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear vendor filter
|
||||
*/
|
||||
clearVendorFilter() {
|
||||
if (this.vendorSelector) {
|
||||
this.vendorSelector.clear();
|
||||
}
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_id = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('inventory_selected_vendor_id');
|
||||
this.pagination.page = 1;
|
||||
this.loadLocations();
|
||||
this.loadInventory();
|
||||
this.loadStats();
|
||||
},
|
||||
|
||||
/**
|
||||
* Load inventory statistics
|
||||
*/
|
||||
async loadStats() {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (this.filters.vendor_id) {
|
||||
params.append('vendor_id', this.filters.vendor_id);
|
||||
}
|
||||
const url = params.toString() ? `/admin/inventory/stats?${params}` : '/admin/inventory/stats';
|
||||
const response = await apiClient.get(url);
|
||||
this.stats = response;
|
||||
adminInventoryLog.info('Loaded stats:', this.stats);
|
||||
} catch (error) {
|
||||
adminInventoryLog.error('Failed to load stats:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load available locations for filter
|
||||
*/
|
||||
async loadLocations() {
|
||||
try {
|
||||
const params = this.filters.vendor_id ? `?vendor_id=${this.filters.vendor_id}` : '';
|
||||
const response = await apiClient.get(`/admin/inventory/locations${params}`);
|
||||
this.locations = response.locations || [];
|
||||
adminInventoryLog.info('Loaded locations:', this.locations.length);
|
||||
} catch (error) {
|
||||
adminInventoryLog.error('Failed to load locations:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 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.vendor_id) {
|
||||
params.append('vendor_id', this.filters.vendor_id);
|
||||
}
|
||||
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(`/admin/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);
|
||||
|
||||
adminInventoryLog.info('Loaded inventory:', this.inventory.length, 'of', this.pagination.total);
|
||||
} catch (error) {
|
||||
adminInventoryLog.error('Failed to load inventory:', error);
|
||||
this.error = error.message || 'Failed to load inventory';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Debounced search handler
|
||||
*/
|
||||
debouncedSearch() {
|
||||
clearTimeout(this.searchTimeout);
|
||||
this.searchTimeout = setTimeout(() => {
|
||||
this.pagination.page = 1;
|
||||
this.loadInventory();
|
||||
}, 300);
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh inventory list
|
||||
*/
|
||||
async refresh() {
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadLocations(),
|
||||
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
|
||||
};
|
||||
this.showSetModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Confirm delete
|
||||
*/
|
||||
confirmDelete(item) {
|
||||
this.selectedItem = item;
|
||||
this.showDeleteModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Execute stock adjustment
|
||||
*/
|
||||
async executeAdjust() {
|
||||
if (!this.selectedItem || this.adjustForm.quantity === 0) return;
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
await apiClient.post('/admin/inventory/adjust', {
|
||||
vendor_id: this.selectedItem.vendor_id,
|
||||
product_id: this.selectedItem.product_id,
|
||||
location: this.selectedItem.location,
|
||||
quantity: this.adjustForm.quantity,
|
||||
reason: this.adjustForm.reason || null
|
||||
});
|
||||
|
||||
adminInventoryLog.info('Adjusted inventory:', this.selectedItem.id);
|
||||
|
||||
this.showAdjustModal = false;
|
||||
this.selectedItem = null;
|
||||
|
||||
Utils.showToast('Stock adjusted successfully.', 'success');
|
||||
|
||||
await this.refresh();
|
||||
} catch (error) {
|
||||
adminInventoryLog.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('/admin/inventory/set', {
|
||||
vendor_id: this.selectedItem.vendor_id,
|
||||
product_id: this.selectedItem.product_id,
|
||||
location: this.selectedItem.location,
|
||||
quantity: this.setForm.quantity
|
||||
});
|
||||
|
||||
adminInventoryLog.info('Set inventory quantity:', this.selectedItem.id);
|
||||
|
||||
this.showSetModal = false;
|
||||
this.selectedItem = null;
|
||||
|
||||
Utils.showToast('Quantity set successfully.', 'success');
|
||||
|
||||
await this.refresh();
|
||||
} catch (error) {
|
||||
adminInventoryLog.error('Failed to set inventory:', error);
|
||||
Utils.showToast(error.message || 'Failed to set quantity.', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Execute delete
|
||||
*/
|
||||
async executeDelete() {
|
||||
if (!this.selectedItem) return;
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
await apiClient.delete(`/admin/inventory/${this.selectedItem.id}`);
|
||||
|
||||
adminInventoryLog.info('Deleted inventory:', this.selectedItem.id);
|
||||
|
||||
this.showDeleteModal = false;
|
||||
this.selectedItem = null;
|
||||
|
||||
Utils.showToast('Inventory entry deleted.', 'success');
|
||||
|
||||
await this.refresh();
|
||||
} catch (error) {
|
||||
adminInventoryLog.error('Failed to delete inventory:', error);
|
||||
Utils.showToast(error.message || 'Failed to delete entry.', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format number with locale
|
||||
*/
|
||||
formatNumber(num) {
|
||||
if (num === null || num === undefined) return '0';
|
||||
return new Intl.NumberFormat('en-US').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();
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================
|
||||
// Import Methods
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* Load vendors list for import modal
|
||||
*/
|
||||
async loadVendorsList() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors', { limit: 100 });
|
||||
this.vendorsList = response.vendors || [];
|
||||
} catch (error) {
|
||||
adminInventoryLog.error('Failed to load vendors:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Execute inventory import
|
||||
*/
|
||||
async executeImport() {
|
||||
if (!this.importForm.vendor_id || !this.importForm.file) {
|
||||
Utils.showToast('Please select a vendor and file', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
this.importing = true;
|
||||
this.importResult = null;
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', this.importForm.file);
|
||||
formData.append('vendor_id', this.importForm.vendor_id);
|
||||
formData.append('warehouse', this.importForm.warehouse || 'strassen');
|
||||
formData.append('clear_existing', this.importForm.clear_existing);
|
||||
|
||||
this.importResult = await apiClient.postFormData('/admin/inventory/import', formData);
|
||||
|
||||
if (this.importResult.success) {
|
||||
adminInventoryLog.info('Import successful:', this.importResult);
|
||||
Utils.showToast(
|
||||
`Imported ${this.importResult.quantity_imported} units (${this.importResult.entries_created} new, ${this.importResult.entries_updated} updated)`,
|
||||
'success'
|
||||
);
|
||||
// Refresh inventory list
|
||||
await this.refresh();
|
||||
} else {
|
||||
Utils.showToast('Import completed with errors', 'warning');
|
||||
}
|
||||
} catch (error) {
|
||||
adminInventoryLog.error('Import failed:', error);
|
||||
this.importResult = {
|
||||
success: false,
|
||||
errors: [error.message || 'Import failed']
|
||||
};
|
||||
Utils.showToast(error.message || 'Import failed', 'error');
|
||||
} finally {
|
||||
this.importing = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Close import modal and reset form
|
||||
*/
|
||||
closeImportModal() {
|
||||
this.showImportModal = false;
|
||||
this.importResult = null;
|
||||
this.importForm = {
|
||||
vendor_id: '',
|
||||
warehouse: 'strassen',
|
||||
file: null,
|
||||
clear_existing: false
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,204 +0,0 @@
|
||||
// static/admin/js/letzshop-vendor-directory.js
|
||||
/**
|
||||
* Admin Letzshop Vendor Directory page logic
|
||||
* Browse and import vendors from Letzshop marketplace
|
||||
*/
|
||||
|
||||
const letzshopVendorDirectoryLog = window.LogConfig.loggers.letzshopVendorDirectory ||
|
||||
window.LogConfig.createLogger('letzshopVendorDirectory', false);
|
||||
|
||||
letzshopVendorDirectoryLog.info('Loading...');
|
||||
|
||||
function letzshopVendorDirectory() {
|
||||
letzshopVendorDirectoryLog.info('letzshopVendorDirectory() called');
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier for sidebar highlighting
|
||||
currentPage: 'letzshop-vendor-directory',
|
||||
|
||||
// Data
|
||||
vendors: [],
|
||||
stats: {},
|
||||
companies: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
limit: 20,
|
||||
hasMore: false,
|
||||
|
||||
// State
|
||||
loading: true,
|
||||
syncing: false,
|
||||
creating: false,
|
||||
error: '',
|
||||
successMessage: '',
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
search: '',
|
||||
city: '',
|
||||
category: '',
|
||||
only_unclaimed: false,
|
||||
},
|
||||
|
||||
// Modals
|
||||
showDetailModal: false,
|
||||
showCreateModal: false,
|
||||
selectedVendor: null,
|
||||
createVendorData: {
|
||||
slug: '',
|
||||
name: '',
|
||||
company_id: '',
|
||||
},
|
||||
createError: '',
|
||||
|
||||
// Init
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._letzshopVendorDirectoryInitialized) return;
|
||||
window._letzshopVendorDirectoryInitialized = true;
|
||||
|
||||
letzshopVendorDirectoryLog.info('init() called');
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadVendors(),
|
||||
this.loadCompanies(),
|
||||
]);
|
||||
},
|
||||
|
||||
// API calls
|
||||
async loadStats() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/letzshop/vendor-directory/stats');
|
||||
if (data.success) {
|
||||
this.stats = data.stats;
|
||||
}
|
||||
} catch (e) {
|
||||
letzshopVendorDirectoryLog.error('Failed to load stats:', e);
|
||||
}
|
||||
},
|
||||
|
||||
async loadVendors() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
page: this.page,
|
||||
limit: this.limit,
|
||||
});
|
||||
|
||||
if (this.filters.search) params.append('search', this.filters.search);
|
||||
if (this.filters.city) params.append('city', this.filters.city);
|
||||
if (this.filters.category) params.append('category', this.filters.category);
|
||||
if (this.filters.only_unclaimed) params.append('only_unclaimed', 'true');
|
||||
|
||||
const data = await apiClient.get(`/admin/letzshop/vendor-directory/vendors?${params}`);
|
||||
|
||||
if (data.success) {
|
||||
this.vendors = data.vendors;
|
||||
this.total = data.total;
|
||||
this.hasMore = data.has_more;
|
||||
} else {
|
||||
this.error = data.detail || 'Failed to load vendors';
|
||||
}
|
||||
} catch (e) {
|
||||
this.error = 'Failed to load vendors';
|
||||
letzshopVendorDirectoryLog.error('Failed to load vendors:', e);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async loadCompanies() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/companies?limit=100');
|
||||
if (data.companies) {
|
||||
this.companies = data.companies;
|
||||
}
|
||||
} catch (e) {
|
||||
letzshopVendorDirectoryLog.error('Failed to load companies:', e);
|
||||
}
|
||||
},
|
||||
|
||||
async triggerSync() {
|
||||
this.syncing = true;
|
||||
this.error = '';
|
||||
this.successMessage = '';
|
||||
|
||||
try {
|
||||
const data = await apiClient.post('/admin/letzshop/vendor-directory/sync');
|
||||
|
||||
if (data.success) {
|
||||
this.successMessage = data.message + (data.mode === 'celery' ? ` (Task ID: ${data.task_id})` : '');
|
||||
// Reload data after a delay to allow sync to complete
|
||||
setTimeout(() => {
|
||||
this.loadStats();
|
||||
this.loadVendors();
|
||||
}, 3000);
|
||||
} else {
|
||||
this.error = data.detail || 'Failed to trigger sync';
|
||||
}
|
||||
} catch (e) {
|
||||
this.error = 'Failed to trigger sync';
|
||||
letzshopVendorDirectoryLog.error('Failed to trigger sync:', e);
|
||||
} finally {
|
||||
this.syncing = false;
|
||||
}
|
||||
},
|
||||
|
||||
async createVendor() {
|
||||
if (!this.createVendorData.company_id || !this.createVendorData.slug) return;
|
||||
|
||||
this.creating = true;
|
||||
this.createError = '';
|
||||
|
||||
try {
|
||||
const data = await apiClient.post(
|
||||
`/admin/letzshop/vendor-directory/vendors/${this.createVendorData.slug}/create-vendor?company_id=${this.createVendorData.company_id}`
|
||||
);
|
||||
|
||||
if (data.success) {
|
||||
this.showCreateModal = false;
|
||||
this.successMessage = data.message;
|
||||
this.loadVendors();
|
||||
this.loadStats();
|
||||
} else {
|
||||
this.createError = data.detail || 'Failed to create vendor';
|
||||
}
|
||||
} catch (e) {
|
||||
this.createError = 'Failed to create vendor';
|
||||
letzshopVendorDirectoryLog.error('Failed to create vendor:', e);
|
||||
} finally {
|
||||
this.creating = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Modal handlers
|
||||
showVendorDetail(vendor) {
|
||||
this.selectedVendor = vendor;
|
||||
this.showDetailModal = true;
|
||||
},
|
||||
|
||||
openCreateVendorModal(vendor) {
|
||||
this.createVendorData = {
|
||||
slug: vendor.slug,
|
||||
name: vendor.name,
|
||||
company_id: '',
|
||||
};
|
||||
this.createError = '';
|
||||
this.showCreateModal = true;
|
||||
},
|
||||
|
||||
// Utilities
|
||||
formatDate(dateStr) {
|
||||
if (!dateStr) return '-';
|
||||
const date = new Date(dateStr);
|
||||
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
letzshopVendorDirectoryLog.info('Loaded');
|
||||
@@ -1,281 +0,0 @@
|
||||
// static/admin/js/letzshop.js
|
||||
/**
|
||||
* Admin Letzshop management page logic
|
||||
*/
|
||||
|
||||
// Use centralized logger (with fallback)
|
||||
const letzshopLog = window.LogConfig?.createLogger?.('letzshop') ||
|
||||
window.LogConfig?.loggers?.letzshop ||
|
||||
{ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} };
|
||||
|
||||
letzshopLog.info('Loading...');
|
||||
|
||||
function adminLetzshop() {
|
||||
letzshopLog.info('adminLetzshop() called');
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'letzshop',
|
||||
|
||||
// Loading states
|
||||
loading: false,
|
||||
savingConfig: false,
|
||||
loadingOrders: false,
|
||||
|
||||
// Messages
|
||||
error: '',
|
||||
successMessage: '',
|
||||
|
||||
// Vendors data
|
||||
vendors: [],
|
||||
totalVendors: 0,
|
||||
page: 1,
|
||||
limit: 50,
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
configuredOnly: false
|
||||
},
|
||||
|
||||
// Stats
|
||||
stats: {
|
||||
total: 0,
|
||||
configured: 0,
|
||||
autoSync: 0,
|
||||
pendingOrders: 0
|
||||
},
|
||||
|
||||
// Configuration modal
|
||||
showConfigModal: false,
|
||||
selectedVendor: null,
|
||||
vendorCredentials: null,
|
||||
configForm: {
|
||||
api_key: '',
|
||||
auto_sync_enabled: false,
|
||||
sync_interval_minutes: 15
|
||||
},
|
||||
showApiKey: false,
|
||||
|
||||
// Orders modal
|
||||
showOrdersModal: false,
|
||||
vendorOrders: [],
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminLetzshopInitialized) {
|
||||
return;
|
||||
}
|
||||
window._adminLetzshopInitialized = true;
|
||||
|
||||
letzshopLog.info('Initializing...');
|
||||
await this.loadVendors();
|
||||
},
|
||||
|
||||
/**
|
||||
* Load vendors with Letzshop status
|
||||
*/
|
||||
async loadVendors() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
skip: ((this.page - 1) * this.limit).toString(),
|
||||
limit: this.limit.toString(),
|
||||
configured_only: this.filters.configuredOnly.toString()
|
||||
});
|
||||
|
||||
const response = await apiClient.get(`/admin/letzshop/vendors?${params}`);
|
||||
this.vendors = response.vendors || [];
|
||||
this.totalVendors = response.total || 0;
|
||||
|
||||
// Calculate stats
|
||||
this.stats.total = this.totalVendors;
|
||||
this.stats.configured = this.vendors.filter(v => v.is_configured).length;
|
||||
this.stats.autoSync = this.vendors.filter(v => v.auto_sync_enabled).length;
|
||||
this.stats.pendingOrders = this.vendors.reduce((sum, v) => sum + (v.pending_orders || 0), 0);
|
||||
|
||||
letzshopLog.info('Loaded vendors:', this.vendors.length);
|
||||
} catch (error) {
|
||||
letzshopLog.error('Failed to load vendors:', error);
|
||||
this.error = error.message || 'Failed to load vendors';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh all data
|
||||
*/
|
||||
async refreshData() {
|
||||
await this.loadVendors();
|
||||
this.successMessage = 'Data refreshed';
|
||||
setTimeout(() => this.successMessage = '', 3000);
|
||||
},
|
||||
|
||||
/**
|
||||
* Open configuration modal for a vendor
|
||||
*/
|
||||
async openConfigModal(vendor) {
|
||||
this.selectedVendor = vendor;
|
||||
this.vendorCredentials = null;
|
||||
this.configForm = {
|
||||
api_key: '',
|
||||
auto_sync_enabled: vendor.auto_sync_enabled || false,
|
||||
sync_interval_minutes: 15
|
||||
};
|
||||
this.showApiKey = false;
|
||||
this.showConfigModal = true;
|
||||
|
||||
// Load existing credentials if configured
|
||||
if (vendor.is_configured) {
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/letzshop/vendors/${vendor.vendor_id}/credentials`);
|
||||
this.vendorCredentials = response;
|
||||
this.configForm.auto_sync_enabled = response.auto_sync_enabled;
|
||||
this.configForm.sync_interval_minutes = response.sync_interval_minutes || 15;
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
letzshopLog.error('Failed to load credentials:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Save vendor configuration
|
||||
*/
|
||||
async saveVendorConfig() {
|
||||
if (!this.configForm.api_key && !this.vendorCredentials) {
|
||||
this.error = 'Please enter an API key';
|
||||
return;
|
||||
}
|
||||
|
||||
this.savingConfig = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
auto_sync_enabled: this.configForm.auto_sync_enabled,
|
||||
sync_interval_minutes: parseInt(this.configForm.sync_interval_minutes)
|
||||
};
|
||||
|
||||
if (this.configForm.api_key) {
|
||||
payload.api_key = this.configForm.api_key;
|
||||
}
|
||||
|
||||
await apiClient.post(
|
||||
`/admin/letzshop/vendors/${this.selectedVendor.vendor_id}/credentials`,
|
||||
payload
|
||||
);
|
||||
|
||||
this.showConfigModal = false;
|
||||
this.successMessage = 'Configuration saved successfully';
|
||||
await this.loadVendors();
|
||||
} catch (error) {
|
||||
letzshopLog.error('Failed to save config:', error);
|
||||
this.error = error.message || 'Failed to save configuration';
|
||||
} finally {
|
||||
this.savingConfig = false;
|
||||
setTimeout(() => this.successMessage = '', 5000);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Delete vendor configuration
|
||||
*/
|
||||
async deleteVendorConfig() {
|
||||
if (!confirm('Are you sure you want to remove Letzshop configuration for this vendor?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await apiClient.delete(`/admin/letzshop/vendors/${this.selectedVendor.vendor_id}/credentials`);
|
||||
this.showConfigModal = false;
|
||||
this.successMessage = 'Configuration removed';
|
||||
await this.loadVendors();
|
||||
} catch (error) {
|
||||
letzshopLog.error('Failed to delete config:', error);
|
||||
this.error = error.message || 'Failed to remove configuration';
|
||||
}
|
||||
setTimeout(() => this.successMessage = '', 5000);
|
||||
},
|
||||
|
||||
/**
|
||||
* Test connection for a vendor
|
||||
*/
|
||||
async testConnection(vendor) {
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const response = await apiClient.post(`/admin/letzshop/vendors/${vendor.vendor_id}/test`);
|
||||
|
||||
if (response.success) {
|
||||
this.successMessage = `Connection successful for ${vendor.vendor_name} (${response.response_time_ms?.toFixed(0)}ms)`;
|
||||
} else {
|
||||
this.error = response.error_details || 'Connection failed';
|
||||
}
|
||||
} catch (error) {
|
||||
letzshopLog.error('Connection test failed:', error);
|
||||
this.error = error.message || 'Connection test failed';
|
||||
}
|
||||
setTimeout(() => this.successMessage = '', 5000);
|
||||
},
|
||||
|
||||
/**
|
||||
* Trigger sync for a vendor
|
||||
*/
|
||||
async triggerSync(vendor) {
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const response = await apiClient.post(`/admin/letzshop/vendors/${vendor.vendor_id}/sync`);
|
||||
|
||||
if (response.success) {
|
||||
this.successMessage = response.message || 'Sync completed';
|
||||
await this.loadVendors();
|
||||
} else {
|
||||
this.error = response.message || 'Sync failed';
|
||||
}
|
||||
} catch (error) {
|
||||
letzshopLog.error('Sync failed:', error);
|
||||
this.error = error.message || 'Sync failed';
|
||||
}
|
||||
setTimeout(() => this.successMessage = '', 5000);
|
||||
},
|
||||
|
||||
/**
|
||||
* View orders for a vendor
|
||||
*/
|
||||
async viewOrders(vendor) {
|
||||
this.selectedVendor = vendor;
|
||||
this.vendorOrders = [];
|
||||
this.loadingOrders = true;
|
||||
this.showOrdersModal = true;
|
||||
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/letzshop/vendors/${vendor.vendor_id}/orders?limit=100`);
|
||||
this.vendorOrders = response.orders || [];
|
||||
} catch (error) {
|
||||
letzshopLog.error('Failed to load orders:', error);
|
||||
this.error = error.message || 'Failed to load orders';
|
||||
} finally {
|
||||
this.loadingOrders = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date for display
|
||||
*/
|
||||
formatDate(dateStr) {
|
||||
if (!dateStr) return 'N/A';
|
||||
const date = new Date(dateStr);
|
||||
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
letzshopLog.info('Module loaded');
|
||||
@@ -1,248 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/logs.js
|
||||
// noqa: JS-003 - Uses ...baseData which is data() with safety check
|
||||
|
||||
const logsLog = window.LogConfig?.loggers?.logs || console;
|
||||
|
||||
function adminLogs() {
|
||||
// Get base data with safety check for standalone usage
|
||||
const baseData = typeof data === 'function' ? data() : {};
|
||||
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...baseData,
|
||||
|
||||
// Logs-specific state
|
||||
currentPage: 'logs',
|
||||
loading: true,
|
||||
error: null,
|
||||
successMessage: null,
|
||||
logSource: 'database',
|
||||
logs: [],
|
||||
stats: {
|
||||
total_count: 0,
|
||||
warning_count: 0,
|
||||
error_count: 0,
|
||||
critical_count: 0
|
||||
},
|
||||
selectedLog: null,
|
||||
filters: {
|
||||
level: '',
|
||||
module: '',
|
||||
search: ''
|
||||
},
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
logFiles: [],
|
||||
selectedFile: '',
|
||||
fileContent: null,
|
||||
|
||||
// Computed: Total pages
|
||||
get totalPages() {
|
||||
return this.pagination.pages;
|
||||
},
|
||||
|
||||
// Computed: Start index for pagination display
|
||||
get startIndex() {
|
||||
if (this.pagination.total === 0) return 0;
|
||||
return (this.pagination.page - 1) * this.pagination.per_page + 1;
|
||||
},
|
||||
|
||||
// Computed: End index for pagination display
|
||||
get endIndex() {
|
||||
const end = this.pagination.page * this.pagination.per_page;
|
||||
return end > this.pagination.total ? this.pagination.total : end;
|
||||
},
|
||||
|
||||
// Computed: Page numbers for pagination
|
||||
get pageNumbers() {
|
||||
const pages = [];
|
||||
const totalPages = this.totalPages;
|
||||
const current = this.pagination.page;
|
||||
|
||||
if (totalPages <= 7) {
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
pages.push(1);
|
||||
if (current > 3) {
|
||||
pages.push('...');
|
||||
}
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(totalPages - 1, current + 1);
|
||||
for (let i = start; i <= end; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
if (current < totalPages - 2) {
|
||||
pages.push('...');
|
||||
}
|
||||
pages.push(totalPages);
|
||||
}
|
||||
return pages;
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminLogsInitialized) {
|
||||
logsLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminLogsInitialized = true;
|
||||
|
||||
logsLog.info('=== LOGS PAGE INITIALIZING ===');
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
await this.loadStats();
|
||||
await this.loadLogs();
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
this.error = null;
|
||||
this.successMessage = null;
|
||||
await this.loadStats();
|
||||
if (this.logSource === 'database') {
|
||||
await this.loadLogs();
|
||||
} else {
|
||||
await this.loadFileLogs();
|
||||
}
|
||||
},
|
||||
|
||||
async loadStats() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/logs/statistics?days=7');
|
||||
this.stats = data;
|
||||
logsLog.info('Log statistics loaded:', this.stats);
|
||||
} catch (error) {
|
||||
logsLog.error('Failed to load log statistics:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async loadLogs() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (this.filters.level) params.append('level', this.filters.level);
|
||||
if (this.filters.module) params.append('module', this.filters.module);
|
||||
if (this.filters.search) params.append('search', this.filters.search);
|
||||
params.append('skip', (this.pagination.page - 1) * this.pagination.per_page);
|
||||
params.append('limit', this.pagination.per_page);
|
||||
|
||||
const data = await apiClient.get(`/admin/logs/database?${params}`);
|
||||
this.logs = data.logs;
|
||||
this.pagination.total = data.total;
|
||||
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
|
||||
logsLog.info(`Loaded ${this.logs.length} logs (total: ${this.pagination.total})`);
|
||||
} catch (error) {
|
||||
logsLog.error('Failed to load logs:', error);
|
||||
this.error = error.response?.data?.detail || 'Failed to load logs';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async loadFileLogs() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const data = await apiClient.get('/admin/logs/files');
|
||||
this.logFiles = data.files;
|
||||
|
||||
if (this.logFiles.length > 0 && !this.selectedFile) {
|
||||
this.selectedFile = this.logFiles[0].filename;
|
||||
await this.loadFileContent();
|
||||
}
|
||||
logsLog.info(`Loaded ${this.logFiles.length} log files`);
|
||||
} catch (error) {
|
||||
logsLog.error('Failed to load log files:', error);
|
||||
this.error = error.response?.data?.detail || 'Failed to load log files';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async loadFileContent() {
|
||||
if (!this.selectedFile) return;
|
||||
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const data = await apiClient.get(`/admin/logs/files/${this.selectedFile}?lines=500`);
|
||||
this.fileContent = data;
|
||||
logsLog.info(`Loaded file content for ${this.selectedFile}`);
|
||||
} catch (error) {
|
||||
logsLog.error('Failed to load file content:', error);
|
||||
this.error = error.response?.data?.detail || 'Failed to load file content';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async downloadLogFile() {
|
||||
if (!this.selectedFile) return;
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('admin_token');
|
||||
// Note: window.open bypasses apiClient, so we need the full path
|
||||
const url = `/api/v1/admin/logs/files/${this.selectedFile}/download`;
|
||||
window.open(`${url}?token=${token}`, '_blank'); // noqa: sec-022
|
||||
} catch (error) {
|
||||
logsLog.error('Failed to download log file:', error);
|
||||
this.error = 'Failed to download log file';
|
||||
}
|
||||
},
|
||||
|
||||
resetFilters() {
|
||||
this.filters = {
|
||||
level: '',
|
||||
module: '',
|
||||
search: ''
|
||||
};
|
||||
this.pagination.page = 1;
|
||||
this.loadLogs();
|
||||
},
|
||||
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
this.loadLogs();
|
||||
}
|
||||
},
|
||||
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.totalPages) {
|
||||
this.pagination.page++;
|
||||
this.loadLogs();
|
||||
}
|
||||
},
|
||||
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadLogs();
|
||||
}
|
||||
},
|
||||
|
||||
showLogDetail(log) {
|
||||
this.selectedLog = log;
|
||||
},
|
||||
|
||||
formatTimestamp(timestamp) {
|
||||
return new Date(timestamp).toLocaleString();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
logsLog.info('Logs module loaded');
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,229 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/marketplace-product-detail.js
|
||||
/**
|
||||
* Admin marketplace product detail page logic
|
||||
* View and manage individual marketplace products
|
||||
*/
|
||||
|
||||
const adminMarketplaceProductDetailLog = window.LogConfig.loggers.adminMarketplaceProductDetail ||
|
||||
window.LogConfig.createLogger('adminMarketplaceProductDetail', false);
|
||||
|
||||
adminMarketplaceProductDetailLog.info('Loading...');
|
||||
|
||||
function adminMarketplaceProductDetail() {
|
||||
adminMarketplaceProductDetailLog.info('adminMarketplaceProductDetail() called');
|
||||
|
||||
// Extract product ID from URL
|
||||
const pathParts = window.location.pathname.split('/');
|
||||
const productId = parseInt(pathParts[pathParts.length - 1]);
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'marketplace-products',
|
||||
|
||||
// Product ID from URL
|
||||
productId: productId,
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
error: '',
|
||||
|
||||
// Product data
|
||||
product: null,
|
||||
|
||||
// Copy to vendor modal state
|
||||
showCopyModal: false,
|
||||
copying: false,
|
||||
copyForm: {
|
||||
vendor_id: '',
|
||||
skip_existing: true
|
||||
},
|
||||
targetVendors: [],
|
||||
|
||||
async init() {
|
||||
adminMarketplaceProductDetailLog.info('Marketplace Product Detail init() called, ID:', this.productId);
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._adminMarketplaceProductDetailInitialized) {
|
||||
adminMarketplaceProductDetailLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminMarketplaceProductDetailInitialized = true;
|
||||
|
||||
// Load data in parallel
|
||||
await Promise.all([
|
||||
this.loadProduct(),
|
||||
this.loadTargetVendors()
|
||||
]);
|
||||
|
||||
adminMarketplaceProductDetailLog.info('Marketplace Product Detail initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Load product details
|
||||
*/
|
||||
async loadProduct() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/products/${this.productId}`);
|
||||
this.product = response;
|
||||
adminMarketplaceProductDetailLog.info('Loaded product:', this.product.marketplace_product_id);
|
||||
} catch (error) {
|
||||
adminMarketplaceProductDetailLog.error('Failed to load product:', error);
|
||||
this.error = error.message || 'Failed to load product details';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load target vendors for copy functionality
|
||||
*/
|
||||
async loadTargetVendors() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors?is_active=true&limit=500');
|
||||
this.targetVendors = response.vendors || [];
|
||||
adminMarketplaceProductDetailLog.info('Loaded target vendors:', this.targetVendors.length);
|
||||
} catch (error) {
|
||||
adminMarketplaceProductDetailLog.error('Failed to load target vendors:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Open copy modal
|
||||
*/
|
||||
openCopyModal() {
|
||||
this.copyForm.vendor_id = '';
|
||||
this.showCopyModal = true;
|
||||
adminMarketplaceProductDetailLog.info('Opening copy modal for product:', this.productId);
|
||||
},
|
||||
|
||||
/**
|
||||
* Execute copy to vendor catalog
|
||||
*/
|
||||
async executeCopyToVendor() {
|
||||
if (!this.copyForm.vendor_id) {
|
||||
this.error = 'Please select a target vendor';
|
||||
return;
|
||||
}
|
||||
|
||||
this.copying = true;
|
||||
try {
|
||||
const response = await apiClient.post('/admin/products/copy-to-vendor', {
|
||||
marketplace_product_ids: [this.productId],
|
||||
vendor_id: parseInt(this.copyForm.vendor_id),
|
||||
skip_existing: this.copyForm.skip_existing
|
||||
});
|
||||
|
||||
adminMarketplaceProductDetailLog.info('Copy result:', response);
|
||||
|
||||
// Show success message
|
||||
const copied = response.copied || 0;
|
||||
const skipped = response.skipped || 0;
|
||||
const failed = response.failed || 0;
|
||||
|
||||
let message;
|
||||
if (copied > 0) {
|
||||
message = 'Product successfully copied to vendor catalog.';
|
||||
} else if (skipped > 0) {
|
||||
message = 'Product already exists in the vendor catalog.';
|
||||
} else {
|
||||
message = 'Failed to copy product.';
|
||||
}
|
||||
|
||||
// Close modal
|
||||
this.showCopyModal = false;
|
||||
|
||||
// Show notification
|
||||
Utils.showToast(message, copied > 0 ? 'success' : 'warning');
|
||||
} catch (error) {
|
||||
adminMarketplaceProductDetailLog.error('Failed to copy product:', error);
|
||||
this.error = error.message || 'Failed to copy product to vendor catalog';
|
||||
} finally {
|
||||
this.copying = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format price for display
|
||||
*/
|
||||
formatPrice(price, currency = 'EUR') {
|
||||
if (price === null || price === undefined) return '-';
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: currency || 'EUR'
|
||||
}).format(price);
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date for display
|
||||
*/
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return '-';
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
} catch (e) {
|
||||
return dateString;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get full language name from ISO code (native names for Luxembourg languages)
|
||||
*/
|
||||
getLanguageName(code) {
|
||||
const languages = {
|
||||
'en': 'English',
|
||||
'de': 'Deutsch',
|
||||
'fr': 'Français',
|
||||
'lb': 'Lëtzebuergesch',
|
||||
'es': 'Español',
|
||||
'it': 'Italiano',
|
||||
'nl': 'Nederlands',
|
||||
'pt': 'Português',
|
||||
'pl': 'Polski',
|
||||
'cs': 'Čeština',
|
||||
'da': 'Dansk',
|
||||
'sv': 'Svenska',
|
||||
'fi': 'Suomi',
|
||||
'no': 'Norsk',
|
||||
'hu': 'Hungarian',
|
||||
'ro': 'Romanian',
|
||||
'bg': 'Bulgarian',
|
||||
'el': 'Greek',
|
||||
'sk': 'Slovak',
|
||||
'sl': 'Slovenian',
|
||||
'hr': 'Croatian',
|
||||
'lt': 'Lithuanian',
|
||||
'lv': 'Latvian',
|
||||
'et': 'Estonian'
|
||||
};
|
||||
return languages[code?.toLowerCase()] || '';
|
||||
},
|
||||
|
||||
/**
|
||||
* Copy text to clipboard
|
||||
*/
|
||||
async copyToClipboard(text) {
|
||||
if (!text) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
Utils.showToast('Copied to clipboard', 'success');
|
||||
} catch (err) {
|
||||
adminMarketplaceProductDetailLog.error('Failed to copy to clipboard:', err);
|
||||
Utils.showToast('Failed to copy to clipboard', 'error');
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,554 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/marketplace-products.js
|
||||
/**
|
||||
* Admin marketplace products page logic
|
||||
* Browse the master product repository (imported from external sources)
|
||||
*/
|
||||
|
||||
const adminMarketplaceProductsLog = window.LogConfig.loggers.adminMarketplaceProducts ||
|
||||
window.LogConfig.createLogger('adminMarketplaceProducts', false);
|
||||
|
||||
adminMarketplaceProductsLog.info('Loading...');
|
||||
|
||||
function adminMarketplaceProducts() {
|
||||
adminMarketplaceProductsLog.info('adminMarketplaceProducts() called');
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'marketplace-products',
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
error: '',
|
||||
|
||||
// Products data
|
||||
products: [],
|
||||
stats: {
|
||||
total: 0,
|
||||
active: 0,
|
||||
inactive: 0,
|
||||
digital: 0,
|
||||
physical: 0,
|
||||
by_marketplace: {}
|
||||
},
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
search: '',
|
||||
marketplace: '',
|
||||
vendor_name: '',
|
||||
is_active: '',
|
||||
is_digital: ''
|
||||
},
|
||||
|
||||
// Selected vendor (for prominent display and filtering)
|
||||
selectedVendor: null,
|
||||
|
||||
// Tom Select instance
|
||||
vendorSelectInstance: null,
|
||||
|
||||
// Available marketplaces for filter dropdown
|
||||
marketplaces: [],
|
||||
|
||||
// Pagination
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Selection state
|
||||
selectedProducts: [],
|
||||
|
||||
// Copy to vendor modal state
|
||||
showCopyModal: false,
|
||||
copying: false,
|
||||
copyForm: {
|
||||
vendor_id: '',
|
||||
skip_existing: true
|
||||
},
|
||||
targetVendors: [],
|
||||
|
||||
// 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() {
|
||||
adminMarketplaceProductsLog.info('Marketplace Products init() called');
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._adminMarketplaceProductsInitialized) {
|
||||
adminMarketplaceProductsLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminMarketplaceProductsInitialized = true;
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
// Initialize Tom Select for vendor filter
|
||||
this.initVendorSelect();
|
||||
|
||||
// Check localStorage for saved vendor
|
||||
const savedVendorId = localStorage.getItem('marketplace_products_selected_vendor_id');
|
||||
if (savedVendorId) {
|
||||
adminMarketplaceProductsLog.info('Restoring saved vendor:', savedVendorId);
|
||||
// Restore vendor after a short delay to ensure TomSelect is ready
|
||||
setTimeout(async () => {
|
||||
await this.restoreSavedVendor(parseInt(savedVendorId));
|
||||
}, 200);
|
||||
// Load other data but not products (restoreSavedVendor will do that)
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadMarketplaces(),
|
||||
this.loadTargetVendors()
|
||||
]);
|
||||
} else {
|
||||
// No saved vendor - load all data including unfiltered products
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadMarketplaces(),
|
||||
this.loadTargetVendors(),
|
||||
this.loadProducts()
|
||||
]);
|
||||
}
|
||||
|
||||
adminMarketplaceProductsLog.info('Marketplace Products initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Restore saved vendor from localStorage
|
||||
*/
|
||||
async restoreSavedVendor(vendorId) {
|
||||
try {
|
||||
const vendor = await apiClient.get(`/admin/vendors/${vendorId}`);
|
||||
if (this.vendorSelectInstance && vendor) {
|
||||
// Add the vendor as an option and select it
|
||||
this.vendorSelectInstance.addOption({
|
||||
id: vendor.id,
|
||||
name: vendor.name,
|
||||
vendor_code: vendor.vendor_code
|
||||
});
|
||||
this.vendorSelectInstance.setValue(vendor.id, true);
|
||||
|
||||
// Set the filter state
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_name = vendor.name;
|
||||
|
||||
adminMarketplaceProductsLog.info('Restored vendor:', vendor.name);
|
||||
|
||||
// Load products with the vendor filter applied
|
||||
await this.loadProducts();
|
||||
}
|
||||
} catch (error) {
|
||||
adminMarketplaceProductsLog.warn('Failed to restore saved vendor, clearing localStorage:', error);
|
||||
localStorage.removeItem('marketplace_products_selected_vendor_id');
|
||||
// Load unfiltered products as fallback
|
||||
await this.loadProducts();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize Tom Select for vendor autocomplete
|
||||
*/
|
||||
initVendorSelect() {
|
||||
const selectEl = this.$refs.vendorSelect;
|
||||
if (!selectEl) {
|
||||
adminMarketplaceProductsLog.warn('Vendor select element not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for Tom Select to be available
|
||||
if (typeof TomSelect === 'undefined') {
|
||||
adminMarketplaceProductsLog.warn('TomSelect not loaded, retrying in 100ms');
|
||||
setTimeout(() => this.initVendorSelect(), 100);
|
||||
return;
|
||||
}
|
||||
|
||||
this.vendorSelectInstance = new TomSelect(selectEl, {
|
||||
valueField: 'id',
|
||||
labelField: 'name',
|
||||
searchField: ['name', 'vendor_code'],
|
||||
placeholder: 'Filter by vendor...',
|
||||
allowEmptyOption: true,
|
||||
load: async (query, callback) => {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors', {
|
||||
search: query,
|
||||
limit: 50
|
||||
});
|
||||
callback(response.vendors || []);
|
||||
} catch (error) {
|
||||
adminMarketplaceProductsLog.error('Failed to search vendors:', error);
|
||||
callback([]);
|
||||
}
|
||||
},
|
||||
render: {
|
||||
option: (data, escape) => {
|
||||
return `<div class="flex items-center justify-between py-1">
|
||||
<span>${escape(data.name)}</span>
|
||||
<span class="text-xs text-gray-400 font-mono">${escape(data.vendor_code || '')}</span>
|
||||
</div>`;
|
||||
},
|
||||
item: (data, escape) => {
|
||||
return `<div>${escape(data.name)}</div>`;
|
||||
}
|
||||
},
|
||||
onChange: (value) => {
|
||||
if (value) {
|
||||
const vendor = this.vendorSelectInstance.options[value];
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_name = vendor.name;
|
||||
// Save to localStorage
|
||||
localStorage.setItem('marketplace_products_selected_vendor_id', value.toString());
|
||||
} else {
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_name = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('marketplace_products_selected_vendor_id');
|
||||
}
|
||||
this.pagination.page = 1;
|
||||
this.loadProducts();
|
||||
this.loadStats();
|
||||
}
|
||||
});
|
||||
|
||||
adminMarketplaceProductsLog.info('Vendor select initialized');
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear vendor filter
|
||||
*/
|
||||
clearVendorFilter() {
|
||||
if (this.vendorSelectInstance) {
|
||||
this.vendorSelectInstance.clear();
|
||||
}
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_name = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('marketplace_products_selected_vendor_id');
|
||||
this.pagination.page = 1;
|
||||
this.loadProducts();
|
||||
this.loadStats();
|
||||
},
|
||||
|
||||
/**
|
||||
* Load product statistics
|
||||
*/
|
||||
async loadStats() {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (this.filters.marketplace) {
|
||||
params.append('marketplace', this.filters.marketplace);
|
||||
}
|
||||
if (this.filters.vendor_name) {
|
||||
params.append('vendor_name', this.filters.vendor_name);
|
||||
}
|
||||
const url = params.toString() ? `/admin/products/stats?${params}` : '/admin/products/stats';
|
||||
const response = await apiClient.get(url);
|
||||
this.stats = response;
|
||||
adminMarketplaceProductsLog.info('Loaded stats:', this.stats);
|
||||
} catch (error) {
|
||||
adminMarketplaceProductsLog.error('Failed to load stats:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load available marketplaces for filter
|
||||
*/
|
||||
async loadMarketplaces() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/products/marketplaces');
|
||||
this.marketplaces = response.marketplaces || [];
|
||||
adminMarketplaceProductsLog.info('Loaded marketplaces:', this.marketplaces);
|
||||
} catch (error) {
|
||||
adminMarketplaceProductsLog.error('Failed to load marketplaces:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load target vendors for copy functionality (actual vendor accounts)
|
||||
*/
|
||||
async loadTargetVendors() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors?is_active=true&limit=500');
|
||||
this.targetVendors = response.vendors || [];
|
||||
adminMarketplaceProductsLog.info('Loaded target vendors:', this.targetVendors.length);
|
||||
} catch (error) {
|
||||
adminMarketplaceProductsLog.error('Failed to load target vendors:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 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.marketplace) {
|
||||
params.append('marketplace', this.filters.marketplace);
|
||||
}
|
||||
if (this.filters.vendor_name) {
|
||||
params.append('vendor_name', this.filters.vendor_name);
|
||||
}
|
||||
if (this.filters.is_active !== '') {
|
||||
params.append('is_active', this.filters.is_active);
|
||||
}
|
||||
if (this.filters.is_digital !== '') {
|
||||
params.append('is_digital', this.filters.is_digital);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(`/admin/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);
|
||||
|
||||
adminMarketplaceProductsLog.info('Loaded products:', this.products.length, 'of', this.pagination.total);
|
||||
} catch (error) {
|
||||
adminMarketplaceProductsLog.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);
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh products list
|
||||
*/
|
||||
async refresh() {
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadProducts()
|
||||
]);
|
||||
},
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
// Selection Management
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Check if a product is selected
|
||||
*/
|
||||
isSelected(productId) {
|
||||
return this.selectedProducts.includes(productId);
|
||||
},
|
||||
|
||||
/**
|
||||
* Toggle selection for a single product
|
||||
*/
|
||||
toggleSelection(productId) {
|
||||
const index = this.selectedProducts.indexOf(productId);
|
||||
if (index === -1) {
|
||||
this.selectedProducts.push(productId);
|
||||
} else {
|
||||
this.selectedProducts.splice(index, 1);
|
||||
}
|
||||
adminMarketplaceProductsLog.info('Selection changed:', this.selectedProducts.length, 'selected');
|
||||
},
|
||||
|
||||
/**
|
||||
* Toggle select all products on current page
|
||||
*/
|
||||
toggleSelectAll(event) {
|
||||
if (event.target.checked) {
|
||||
// Select all on current page
|
||||
this.selectedProducts = this.products.map(p => p.id);
|
||||
} else {
|
||||
// Deselect all
|
||||
this.selectedProducts = [];
|
||||
}
|
||||
adminMarketplaceProductsLog.info('Select all toggled:', this.selectedProducts.length, 'selected');
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear all selections
|
||||
*/
|
||||
clearSelection() {
|
||||
this.selectedProducts = [];
|
||||
adminMarketplaceProductsLog.info('Selection cleared');
|
||||
},
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
// Copy to Vendor Catalog
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Open copy modal for selected products
|
||||
*/
|
||||
openCopyToVendorModal() {
|
||||
if (this.selectedProducts.length === 0) {
|
||||
this.error = 'Please select at least one product to copy';
|
||||
return;
|
||||
}
|
||||
this.copyForm.vendor_id = '';
|
||||
this.showCopyModal = true;
|
||||
adminMarketplaceProductsLog.info('Opening copy modal for', this.selectedProducts.length, 'products');
|
||||
},
|
||||
|
||||
/**
|
||||
* Copy single product - convenience method for action button
|
||||
*/
|
||||
copySingleProduct(productId) {
|
||||
this.selectedProducts = [productId];
|
||||
this.openCopyToVendorModal();
|
||||
},
|
||||
|
||||
/**
|
||||
* Execute copy to vendor catalog
|
||||
*/
|
||||
async executeCopyToVendor() {
|
||||
if (!this.copyForm.vendor_id) {
|
||||
this.error = 'Please select a target vendor';
|
||||
return;
|
||||
}
|
||||
|
||||
this.copying = true;
|
||||
try {
|
||||
const response = await apiClient.post('/admin/products/copy-to-vendor', {
|
||||
marketplace_product_ids: this.selectedProducts,
|
||||
vendor_id: parseInt(this.copyForm.vendor_id),
|
||||
skip_existing: this.copyForm.skip_existing
|
||||
});
|
||||
|
||||
adminMarketplaceProductsLog.info('Copy result:', response);
|
||||
|
||||
// Show success message
|
||||
const copied = response.copied || 0;
|
||||
const skipped = response.skipped || 0;
|
||||
const failed = response.failed || 0;
|
||||
|
||||
let message = `Successfully copied ${copied} product(s) to vendor catalog.`;
|
||||
if (skipped > 0) message += ` ${skipped} already existed.`;
|
||||
if (failed > 0) message += ` ${failed} failed.`;
|
||||
|
||||
// Close modal and clear selection
|
||||
this.showCopyModal = false;
|
||||
this.clearSelection();
|
||||
|
||||
// Show success notification
|
||||
Utils.showToast(message, 'success');
|
||||
} catch (error) {
|
||||
adminMarketplaceProductsLog.error('Failed to copy products:', error);
|
||||
const errorMsg = error.message || 'Failed to copy products to vendor catalog';
|
||||
this.error = errorMsg;
|
||||
Utils.showToast(errorMsg, 'error');
|
||||
} finally {
|
||||
this.copying = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format price for display
|
||||
*/
|
||||
formatPrice(price, currency = 'EUR') {
|
||||
if (price === null || price === undefined) return '-';
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: currency || 'EUR'
|
||||
}).format(price);
|
||||
},
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,533 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/marketplace.js
|
||||
/**
|
||||
* Admin marketplace import page logic
|
||||
*/
|
||||
|
||||
// ✅ Use centralized logger
|
||||
const adminMarketplaceLog = window.LogConfig.loggers.marketplace;
|
||||
|
||||
adminMarketplaceLog.info('Loading...');
|
||||
|
||||
function adminMarketplace() {
|
||||
adminMarketplaceLog.info('adminMarketplace() called');
|
||||
|
||||
return {
|
||||
// ✅ Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// ✅ Set page identifier
|
||||
currentPage: 'marketplace',
|
||||
|
||||
// Loading states
|
||||
loading: false,
|
||||
importing: false,
|
||||
error: '',
|
||||
successMessage: '',
|
||||
|
||||
// Active import tab (marketplace selector)
|
||||
activeImportTab: 'letzshop',
|
||||
|
||||
// Vendors list
|
||||
vendors: [],
|
||||
selectedVendor: null,
|
||||
|
||||
// Import form
|
||||
importForm: {
|
||||
vendor_id: '',
|
||||
csv_url: '',
|
||||
marketplace: 'Letzshop',
|
||||
language: 'fr',
|
||||
batch_size: 1000
|
||||
},
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
vendor_id: '',
|
||||
status: '',
|
||||
marketplace: ''
|
||||
},
|
||||
|
||||
// Import jobs
|
||||
jobs: [],
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Modal state
|
||||
showJobModal: false,
|
||||
selectedJob: null,
|
||||
|
||||
// Auto-refresh for active jobs
|
||||
autoRefreshInterval: 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() {
|
||||
adminMarketplaceLog.info('Marketplace init() called');
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._adminMarketplaceInitialized) {
|
||||
adminMarketplaceLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminMarketplaceInitialized = true;
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
// Ensure form defaults are set (in case spread didn't work)
|
||||
if (!this.importForm.marketplace) {
|
||||
this.importForm.marketplace = 'Letzshop';
|
||||
}
|
||||
if (!this.importForm.batch_size) {
|
||||
this.importForm.batch_size = 1000;
|
||||
}
|
||||
if (!this.importForm.language) {
|
||||
this.importForm.language = 'fr';
|
||||
}
|
||||
|
||||
adminMarketplaceLog.info('Form defaults:', this.importForm);
|
||||
|
||||
await this.loadVendors();
|
||||
await this.loadJobs();
|
||||
|
||||
// Auto-refresh active jobs every 10 seconds
|
||||
this.startAutoRefresh();
|
||||
|
||||
adminMarketplaceLog.info('Marketplace initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Load all vendors for dropdown
|
||||
*/
|
||||
async loadVendors() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors?limit=1000');
|
||||
this.vendors = response.vendors || [];
|
||||
adminMarketplaceLog.info('Loaded vendors:', this.vendors.length);
|
||||
} catch (error) {
|
||||
adminMarketplaceLog.error('Failed to load vendors:', error);
|
||||
this.error = 'Failed to load vendors: ' + (error.message || 'Unknown error');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle vendor selection change
|
||||
*/
|
||||
onVendorChange() {
|
||||
const vendorId = parseInt(this.importForm.vendor_id);
|
||||
this.selectedVendor = this.vendors.find(v => v.id === vendorId) || null;
|
||||
adminMarketplaceLog.info('Selected vendor:', this.selectedVendor);
|
||||
|
||||
// Auto-populate CSV URL if marketplace is Letzshop
|
||||
this.autoPopulateCSV();
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle language selection change
|
||||
*/
|
||||
onLanguageChange() {
|
||||
// Auto-populate CSV URL if marketplace is Letzshop
|
||||
this.autoPopulateCSV();
|
||||
},
|
||||
|
||||
/**
|
||||
* Auto-populate CSV URL based on selected vendor and language
|
||||
*/
|
||||
autoPopulateCSV() {
|
||||
// Only auto-populate for Letzshop marketplace
|
||||
if (this.importForm.marketplace !== 'Letzshop') return;
|
||||
if (!this.selectedVendor) return;
|
||||
|
||||
const urlMap = {
|
||||
'fr': this.selectedVendor.letzshop_csv_url_fr,
|
||||
'en': this.selectedVendor.letzshop_csv_url_en,
|
||||
'de': this.selectedVendor.letzshop_csv_url_de
|
||||
};
|
||||
|
||||
const url = urlMap[this.importForm.language];
|
||||
if (url) {
|
||||
this.importForm.csv_url = url;
|
||||
adminMarketplaceLog.info('Auto-populated CSV URL:', this.importForm.language, url);
|
||||
} else {
|
||||
adminMarketplaceLog.info('No CSV URL configured for language:', this.importForm.language);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load import jobs (only jobs triggered by current admin user)
|
||||
*/
|
||||
async loadJobs() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
// Build query params
|
||||
const params = new URLSearchParams({
|
||||
skip: (this.pagination.page - 1) * this.pagination.per_page,
|
||||
limit: this.pagination.per_page,
|
||||
created_by_me: 'true' // ✅ Only show jobs I triggered
|
||||
});
|
||||
|
||||
// Add filters (keep for consistency, though less needed here)
|
||||
if (this.filters.vendor_id) {
|
||||
params.append('vendor_id', this.filters.vendor_id);
|
||||
}
|
||||
if (this.filters.status) {
|
||||
params.append('status', this.filters.status);
|
||||
}
|
||||
if (this.filters.marketplace) {
|
||||
params.append('marketplace', this.filters.marketplace);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(
|
||||
`/admin/marketplace-import-jobs?${params.toString()}`
|
||||
);
|
||||
|
||||
this.jobs = response.items || [];
|
||||
this.pagination.total = response.total || 0;
|
||||
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
|
||||
|
||||
adminMarketplaceLog.info('Loaded my jobs:', this.jobs.length);
|
||||
} catch (error) {
|
||||
adminMarketplaceLog.error('Failed to load jobs:', error);
|
||||
this.error = error.message || 'Failed to load import jobs';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Start new import for selected vendor
|
||||
*/
|
||||
async startImport() {
|
||||
if (!this.importForm.csv_url || !this.importForm.vendor_id) {
|
||||
this.error = 'Please select a vendor and enter a CSV URL';
|
||||
return;
|
||||
}
|
||||
|
||||
this.importing = true;
|
||||
this.error = '';
|
||||
this.successMessage = '';
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
vendor_id: parseInt(this.importForm.vendor_id),
|
||||
source_url: this.importForm.csv_url,
|
||||
marketplace: this.importForm.marketplace,
|
||||
batch_size: this.importForm.batch_size,
|
||||
language: this.importForm.language // Include selected language
|
||||
};
|
||||
|
||||
adminMarketplaceLog.info('Starting import:', payload);
|
||||
|
||||
const response = await apiClient.post('/admin/marketplace-import-jobs', payload);
|
||||
|
||||
adminMarketplaceLog.info('Import started:', response);
|
||||
|
||||
const vendorName = this.selectedVendor?.name || 'vendor';
|
||||
this.successMessage = `Import job #${response.job_id || response.id} started successfully for ${vendorName}!`;
|
||||
|
||||
// Clear form
|
||||
this.importForm.vendor_id = '';
|
||||
this.importForm.csv_url = '';
|
||||
this.importForm.language = 'fr';
|
||||
this.importForm.batch_size = 1000;
|
||||
this.selectedVendor = null;
|
||||
|
||||
// Reload jobs to show the new import
|
||||
await this.loadJobs();
|
||||
|
||||
// Clear success message after 5 seconds
|
||||
setTimeout(() => {
|
||||
this.successMessage = '';
|
||||
}, 5000);
|
||||
} catch (error) {
|
||||
adminMarketplaceLog.error('Failed to start import:', error);
|
||||
this.error = error.message || 'Failed to start import';
|
||||
} finally {
|
||||
this.importing = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Switch marketplace tab and update form accordingly
|
||||
*/
|
||||
switchMarketplace(marketplace) {
|
||||
this.activeImportTab = marketplace;
|
||||
|
||||
// Update marketplace in form
|
||||
const marketplaceMap = {
|
||||
'letzshop': 'Letzshop',
|
||||
'codeswholesale': 'CodesWholesale'
|
||||
};
|
||||
this.importForm.marketplace = marketplaceMap[marketplace] || 'Letzshop';
|
||||
|
||||
// Reset form fields when switching tabs
|
||||
this.importForm.vendor_id = '';
|
||||
this.importForm.csv_url = '';
|
||||
this.importForm.language = 'fr';
|
||||
this.importForm.batch_size = 1000;
|
||||
this.selectedVendor = null;
|
||||
|
||||
adminMarketplaceLog.info('Switched to marketplace:', this.importForm.marketplace);
|
||||
},
|
||||
|
||||
/**
|
||||
* Quick fill form with saved CSV URL from vendor settings
|
||||
*/
|
||||
quickFill(language) {
|
||||
if (!this.selectedVendor) return;
|
||||
|
||||
const urlMap = {
|
||||
'fr': this.selectedVendor.letzshop_csv_url_fr,
|
||||
'en': this.selectedVendor.letzshop_csv_url_en,
|
||||
'de': this.selectedVendor.letzshop_csv_url_de
|
||||
};
|
||||
|
||||
const url = urlMap[language];
|
||||
if (url) {
|
||||
this.importForm.csv_url = url;
|
||||
this.importForm.language = language;
|
||||
adminMarketplaceLog.info('Quick filled:', language, url);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear all filters and reload
|
||||
*/
|
||||
clearFilters() {
|
||||
this.filters.vendor_id = '';
|
||||
this.filters.status = '';
|
||||
this.filters.marketplace = '';
|
||||
this.pagination.page = 1;
|
||||
this.loadJobs();
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh jobs list
|
||||
*/
|
||||
async refreshJobs() {
|
||||
await this.loadJobs();
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh single job status
|
||||
*/
|
||||
async refreshJobStatus(jobId) {
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/marketplace-import-jobs/${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;
|
||||
}
|
||||
|
||||
adminMarketplaceLog.info('Refreshed job:', jobId);
|
||||
} catch (error) {
|
||||
adminMarketplaceLog.error('Failed to refresh job:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* View job details in modal
|
||||
*/
|
||||
async viewJobDetails(jobId) {
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/marketplace-import-jobs/${jobId}`);
|
||||
this.selectedJob = response;
|
||||
this.showJobModal = true;
|
||||
adminMarketplaceLog.info('Viewing job details:', jobId);
|
||||
} catch (error) {
|
||||
adminMarketplaceLog.error('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;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get vendor name by ID
|
||||
*/
|
||||
getVendorName(vendorId) {
|
||||
const vendor = this.vendors.find(v => v.id === vendorId);
|
||||
return vendor ? `${vendor.name} (${vendor.vendor_code})` : `Vendor #${vendorId}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Previous page
|
||||
*/
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
this.loadJobs();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Next page
|
||||
*/
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.totalPages) {
|
||||
this.pagination.page++;
|
||||
this.loadJobs();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Go to specific page
|
||||
*/
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadJobs();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date for display
|
||||
*/
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return 'N/A';
|
||||
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleString('en-US', {
|
||||
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) {
|
||||
adminMarketplaceLog.info('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._adminMarketplaceInstance && window._adminMarketplaceInstance.stopAutoRefresh) {
|
||||
window._adminMarketplaceInstance.stopAutoRefresh();
|
||||
}
|
||||
});
|
||||
@@ -1,489 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
/**
|
||||
* Admin Messages Page
|
||||
*
|
||||
* Handles the messaging interface including:
|
||||
* - Conversation list with filtering and pagination
|
||||
* - Message thread display
|
||||
* - Sending messages with attachments
|
||||
* - Creating new conversations
|
||||
*/
|
||||
|
||||
const messagesLog = window.LogConfig?.createLogger('MESSAGES') || console;
|
||||
|
||||
/**
|
||||
* Admin Messages Component
|
||||
*/
|
||||
function adminMessages(initialConversationId = null) {
|
||||
return {
|
||||
...data(),
|
||||
currentPage: 'messages',
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
error: null,
|
||||
loadingConversations: false,
|
||||
loadingMessages: false,
|
||||
sendingMessage: false,
|
||||
creatingConversation: false,
|
||||
|
||||
// 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: '',
|
||||
attachedFiles: [],
|
||||
|
||||
// Compose modal
|
||||
showComposeModal: false,
|
||||
compose: {
|
||||
recipientType: '',
|
||||
recipientId: null,
|
||||
subject: '',
|
||||
message: ''
|
||||
},
|
||||
recipients: [],
|
||||
loadingRecipients: false,
|
||||
|
||||
// Polling
|
||||
pollInterval: null,
|
||||
|
||||
/**
|
||||
* Initialize component
|
||||
*/
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminMessagesInitialized) return;
|
||||
window._adminMessagesInitialized = true;
|
||||
|
||||
try {
|
||||
messagesLog.debug('Initializing messages page');
|
||||
await this.loadConversations();
|
||||
|
||||
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 () => {
|
||||
// Only poll if we have a selected conversation
|
||||
if (this.selectedConversationId && !document.hidden) {
|
||||
await this.refreshCurrentConversation();
|
||||
}
|
||||
// Update unread count
|
||||
await this.updateUnreadCount();
|
||||
}, 30000); // 30 seconds
|
||||
},
|
||||
|
||||
/**
|
||||
* 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(`/admin/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('/admin/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);
|
||||
|
||||
// Update URL without reload
|
||||
const url = new URL(window.location);
|
||||
url.pathname = `/admin/messages/${conversationId}`;
|
||||
window.history.pushState({}, '', url);
|
||||
},
|
||||
|
||||
/**
|
||||
* Load conversation detail
|
||||
*/
|
||||
async loadConversation(conversationId) {
|
||||
this.loadingMessages = true;
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/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;
|
||||
}
|
||||
|
||||
messagesLog.debug(`Loaded conversation ${conversationId} with ${response.messages?.length || 0} messages`);
|
||||
|
||||
// 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(`/admin/messages/${this.selectedConversationId}?mark_read=true`);
|
||||
const oldCount = this.selectedConversation?.messages?.length || 0;
|
||||
const newCount = response.messages?.length || 0;
|
||||
|
||||
this.selectedConversation = response;
|
||||
|
||||
// If new messages, scroll to bottom
|
||||
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
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Handle file selection
|
||||
*/
|
||||
handleFileSelect(event) {
|
||||
const files = Array.from(event.target.files);
|
||||
this.attachedFiles = files;
|
||||
messagesLog.debug(`Selected ${files.length} files`);
|
||||
},
|
||||
|
||||
/**
|
||||
* Send a message
|
||||
*/
|
||||
async sendMessage() {
|
||||
if (!this.replyContent.trim() && this.attachedFiles.length === 0) return;
|
||||
if (!this.selectedConversationId) return;
|
||||
|
||||
this.sendingMessage = true;
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('content', this.replyContent);
|
||||
|
||||
for (const file of this.attachedFiles) {
|
||||
formData.append('files', file);
|
||||
}
|
||||
|
||||
const message = await apiClient.postFormData(`/admin/messages/${this.selectedConversationId}/messages`, formData);
|
||||
|
||||
// Add to messages
|
||||
if (this.selectedConversation) {
|
||||
this.selectedConversation.messages.push(message);
|
||||
this.selectedConversation.message_count++;
|
||||
}
|
||||
|
||||
// Clear form
|
||||
this.replyContent = '';
|
||||
this.attachedFiles = [];
|
||||
if (this.$refs.fileInput) {
|
||||
this.$refs.fileInput.value = '';
|
||||
}
|
||||
|
||||
// Scroll to bottom
|
||||
await this.$nextTick();
|
||||
this.scrollToBottom();
|
||||
|
||||
messagesLog.debug(`Sent message ${message.id}`);
|
||||
} 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('Are you sure you want to close this conversation?')) return;
|
||||
|
||||
try {
|
||||
await apiClient.post(`/admin/messages/${this.selectedConversationId}/close`);
|
||||
|
||||
if (this.selectedConversation) {
|
||||
this.selectedConversation.is_closed = true;
|
||||
}
|
||||
|
||||
// Update in list
|
||||
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(`/admin/messages/${this.selectedConversationId}/reopen`);
|
||||
|
||||
if (this.selectedConversation) {
|
||||
this.selectedConversation.is_closed = false;
|
||||
}
|
||||
|
||||
// Update in list
|
||||
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 for compose modal
|
||||
*/
|
||||
async loadRecipients() {
|
||||
if (!this.compose.recipientType) {
|
||||
this.recipients = [];
|
||||
return;
|
||||
}
|
||||
|
||||
this.loadingRecipients = true;
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/messages/recipients?recipient_type=${this.compose.recipientType}&limit=100`);
|
||||
this.recipients = response.recipients || [];
|
||||
messagesLog.debug(`Loaded ${this.recipients.length} recipients`);
|
||||
} catch (error) {
|
||||
messagesLog.error('Failed to load recipients:', error);
|
||||
Utils.showToast('Failed to load recipients', 'error');
|
||||
} finally {
|
||||
this.loadingRecipients = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Create new conversation
|
||||
*/
|
||||
async createConversation() {
|
||||
if (!this.compose.recipientId || !this.compose.subject.trim()) return;
|
||||
|
||||
this.creatingConversation = true;
|
||||
try {
|
||||
// Determine conversation type
|
||||
const conversationType = this.compose.recipientType === 'vendor'
|
||||
? 'admin_vendor'
|
||||
: 'admin_customer';
|
||||
|
||||
// Get vendor_id if customer
|
||||
let vendorId = null;
|
||||
if (this.compose.recipientType === 'customer') {
|
||||
const recipient = this.recipients.find(r => r.id === parseInt(this.compose.recipientId));
|
||||
vendorId = recipient?.vendor_id;
|
||||
}
|
||||
|
||||
const response = await apiClient.post('/admin/messages', {
|
||||
conversation_type: conversationType,
|
||||
subject: this.compose.subject,
|
||||
recipient_type: this.compose.recipientType,
|
||||
recipient_id: parseInt(this.compose.recipientId),
|
||||
vendor_id: vendorId,
|
||||
initial_message: this.compose.message || null
|
||||
});
|
||||
|
||||
// Close modal and reset
|
||||
this.showComposeModal = false;
|
||||
this.compose = {
|
||||
recipientType: '',
|
||||
recipientId: null,
|
||||
subject: '',
|
||||
message: ''
|
||||
};
|
||||
this.recipients = [];
|
||||
|
||||
// Reload conversations and select new one
|
||||
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
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Get other participant name
|
||||
*/
|
||||
getOtherParticipantName() {
|
||||
if (!this.selectedConversation?.participants) return 'Unknown';
|
||||
|
||||
const other = this.selectedConversation.participants.find(
|
||||
p => p.participant_type !== 'admin'
|
||||
);
|
||||
|
||||
return other?.participant_info?.name || 'Unknown';
|
||||
},
|
||||
|
||||
/**
|
||||
* Format relative time
|
||||
*/
|
||||
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';
|
||||
if (diff < 604800) return `${Math.floor(diff / 86400)}d`;
|
||||
|
||||
return date.toLocaleDateString();
|
||||
},
|
||||
|
||||
/**
|
||||
* Format time for messages
|
||||
*/
|
||||
formatTime(dateString) {
|
||||
if (!dateString) return '';
|
||||
|
||||
const date = new Date(dateString);
|
||||
const now = new Date();
|
||||
const isToday = date.toDateString() === now.toDateString();
|
||||
|
||||
if (isToday) {
|
||||
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
return date.toLocaleString([], {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Make available globally
|
||||
window.adminMessages = adminMessages;
|
||||
@@ -1 +0,0 @@
|
||||
// System monitoring
|
||||
@@ -1,308 +0,0 @@
|
||||
/**
|
||||
* Admin Notifications Page
|
||||
*
|
||||
* Handles the notifications management interface including:
|
||||
* - Notifications list with filtering and pagination
|
||||
* - Platform alerts management
|
||||
* - Mark as read, delete, and bulk operations
|
||||
*/
|
||||
|
||||
const notificationsLog = window.LogConfig?.createLogger('NOTIFICATIONS') || console;
|
||||
|
||||
/**
|
||||
* Admin Notifications Component
|
||||
*/
|
||||
function adminNotifications() {
|
||||
return {
|
||||
...data(),
|
||||
currentPage: 'notifications',
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
error: null,
|
||||
loadingNotifications: false,
|
||||
loadingAlerts: false,
|
||||
|
||||
// Tab state
|
||||
activeTab: 'notifications',
|
||||
|
||||
// Notifications state
|
||||
notifications: [],
|
||||
page: 1,
|
||||
skip: 0,
|
||||
limit: 10,
|
||||
stats: {
|
||||
total: 0,
|
||||
unread_count: 0
|
||||
},
|
||||
|
||||
// Notifications filters
|
||||
filters: {
|
||||
priority: '',
|
||||
is_read: ''
|
||||
},
|
||||
|
||||
// Alerts state
|
||||
alerts: [],
|
||||
alertPage: 1,
|
||||
alertSkip: 0,
|
||||
alertLimit: 10,
|
||||
alertStats: {
|
||||
total: 0,
|
||||
active_alerts: 0,
|
||||
critical_alerts: 0,
|
||||
resolved_today: 0,
|
||||
by_type: {},
|
||||
by_severity: {}
|
||||
},
|
||||
|
||||
// Alerts filters
|
||||
alertFilters: {
|
||||
severity: '',
|
||||
is_resolved: ''
|
||||
},
|
||||
|
||||
// Resolve modal state
|
||||
showResolveModal: false,
|
||||
resolvingAlert: null,
|
||||
resolutionNotes: '',
|
||||
|
||||
/**
|
||||
* Initialize component
|
||||
*/
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminNotificationsInitialized) return;
|
||||
window._adminNotificationsInitialized = true;
|
||||
|
||||
try {
|
||||
notificationsLog.debug('Initializing notifications page');
|
||||
await Promise.all([
|
||||
this.loadNotifications(),
|
||||
this.loadAlertStats()
|
||||
]);
|
||||
} catch (error) {
|
||||
notificationsLog.error('Failed to initialize notifications page:', error);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// NOTIFICATIONS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Load notifications with current filters
|
||||
*/
|
||||
async loadNotifications() {
|
||||
this.loadingNotifications = 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.priority) params.append('priority', this.filters.priority);
|
||||
if (this.filters.is_read !== '') params.append('is_read', this.filters.is_read);
|
||||
|
||||
const response = await apiClient.get(`/admin/notifications?${params}`);
|
||||
this.notifications = response.notifications || [];
|
||||
this.stats.total = response.total || 0;
|
||||
this.stats.unread_count = response.unread_count || 0;
|
||||
|
||||
notificationsLog.debug(`Loaded ${this.notifications.length} notifications`);
|
||||
} catch (error) {
|
||||
notificationsLog.error('Failed to load notifications:', error);
|
||||
Utils.showToast('Failed to load notifications', 'error');
|
||||
} finally {
|
||||
this.loadingNotifications = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Mark notification as read
|
||||
*/
|
||||
async markAsRead(notification) {
|
||||
try {
|
||||
await apiClient.put(`/admin/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) {
|
||||
notificationsLog.error('Failed to mark as read:', error);
|
||||
Utils.showToast('Failed to mark notification as read', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Mark all notifications as read
|
||||
*/
|
||||
async markAllAsRead() {
|
||||
try {
|
||||
await apiClient.put('/admin/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) {
|
||||
notificationsLog.error('Failed to mark all as read:', error);
|
||||
Utils.showToast('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(`/admin/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) {
|
||||
notificationsLog.error('Failed to delete notification:', error);
|
||||
Utils.showToast('Failed to delete notification', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get notification icon based on type
|
||||
*/
|
||||
getNotificationIcon(type) {
|
||||
const icons = {
|
||||
'import_failure': window.$icon?.('x-circle', 'w-5 h-5') || '❌',
|
||||
'sync_issue': window.$icon?.('refresh', 'w-5 h-5') || '🔄',
|
||||
'vendor_alert': window.$icon?.('exclamation-triangle', 'w-5 h-5') || '⚠️',
|
||||
'system_health': window.$icon?.('heart', 'w-5 h-5') || '💓',
|
||||
'security': window.$icon?.('shield-exclamation', 'w-5 h-5') || '🛡️',
|
||||
'performance': window.$icon?.('chart-bar', 'w-5 h-5') || '📊',
|
||||
'info': window.$icon?.('information-circle', 'w-5 h-5') || 'ℹ️'
|
||||
};
|
||||
return icons[type] || window.$icon?.('bell', 'w-5 h-5') || '🔔';
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// PLATFORM ALERTS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Load platform alerts
|
||||
*/
|
||||
async loadAlerts() {
|
||||
this.loadingAlerts = true;
|
||||
try {
|
||||
this.alertSkip = (this.alertPage - 1) * this.alertLimit;
|
||||
const params = new URLSearchParams();
|
||||
params.append('skip', this.alertSkip);
|
||||
params.append('limit', this.alertLimit);
|
||||
|
||||
if (this.alertFilters.severity) params.append('severity', this.alertFilters.severity);
|
||||
if (this.alertFilters.is_resolved !== '') params.append('is_resolved', this.alertFilters.is_resolved);
|
||||
|
||||
const response = await apiClient.get(`/admin/notifications/alerts?${params}`);
|
||||
this.alerts = response.alerts || [];
|
||||
this.alertStats.total = response.total || 0;
|
||||
this.alertStats.active_alerts = response.active_count || 0;
|
||||
this.alertStats.critical_alerts = response.critical_count || 0;
|
||||
|
||||
notificationsLog.debug(`Loaded ${this.alerts.length} alerts`);
|
||||
} catch (error) {
|
||||
notificationsLog.error('Failed to load alerts:', error);
|
||||
Utils.showToast('Failed to load alerts', 'error');
|
||||
} finally {
|
||||
this.loadingAlerts = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load alert statistics
|
||||
*/
|
||||
async loadAlertStats() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/notifications/alerts/stats');
|
||||
this.alertStats = {
|
||||
...this.alertStats,
|
||||
total: response.total || 0,
|
||||
active_alerts: response.active || 0,
|
||||
critical_alerts: response.critical || 0,
|
||||
resolved_today: response.resolved_today || 0,
|
||||
by_type: response.by_type || {},
|
||||
by_severity: response.by_severity || {}
|
||||
};
|
||||
} catch (error) {
|
||||
notificationsLog.error('Failed to load alert stats:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Resolve alert
|
||||
*/
|
||||
async resolveAlert(alert) {
|
||||
const notes = prompt('Resolution notes (optional):');
|
||||
if (notes === null) return; // User cancelled
|
||||
|
||||
try {
|
||||
await apiClient.put(`/admin/notifications/alerts/${alert.id}/resolve`, {
|
||||
resolution_notes: notes
|
||||
});
|
||||
|
||||
// Update local state
|
||||
alert.is_resolved = true;
|
||||
alert.resolution_notes = notes;
|
||||
this.alertStats.active_alerts = Math.max(0, this.alertStats.active_alerts - 1);
|
||||
if (alert.severity === 'critical') {
|
||||
this.alertStats.critical_alerts = Math.max(0, this.alertStats.critical_alerts - 1);
|
||||
}
|
||||
this.alertStats.resolved_today++;
|
||||
|
||||
Utils.showToast('Alert resolved successfully', 'success');
|
||||
} catch (error) {
|
||||
notificationsLog.error('Failed to resolve alert:', error);
|
||||
Utils.showToast('Failed to resolve alert', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// HELPERS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 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
|
||||
return date.toLocaleString();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Make available globally
|
||||
window.adminNotifications = adminNotifications;
|
||||
@@ -1,616 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/orders.js
|
||||
/**
|
||||
* Admin orders management page logic
|
||||
* View and manage orders across all vendors
|
||||
*/
|
||||
|
||||
const adminOrdersLog = window.LogConfig.loggers.adminOrders ||
|
||||
window.LogConfig.createLogger('adminOrders', false);
|
||||
|
||||
adminOrdersLog.info('Loading...');
|
||||
|
||||
function adminOrders() {
|
||||
adminOrdersLog.info('adminOrders() called');
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'orders',
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
error: '',
|
||||
saving: false,
|
||||
|
||||
// Orders data
|
||||
orders: [],
|
||||
stats: {
|
||||
total_orders: 0,
|
||||
pending_orders: 0,
|
||||
processing_orders: 0,
|
||||
shipped_orders: 0,
|
||||
delivered_orders: 0,
|
||||
cancelled_orders: 0,
|
||||
refunded_orders: 0,
|
||||
total_revenue: 0,
|
||||
vendors_with_orders: 0
|
||||
},
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
search: '',
|
||||
vendor_id: '',
|
||||
status: '',
|
||||
channel: ''
|
||||
},
|
||||
|
||||
// Available vendors for filter dropdown
|
||||
vendors: [],
|
||||
|
||||
// Selected vendor (for prominent display)
|
||||
selectedVendor: null,
|
||||
|
||||
// Tom Select instance
|
||||
vendorSelectInstance: null,
|
||||
|
||||
// Pagination
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Modal states
|
||||
showStatusModal: false,
|
||||
showDetailModal: false,
|
||||
selectedOrder: null,
|
||||
selectedOrderDetail: null,
|
||||
|
||||
// Status update form
|
||||
statusForm: {
|
||||
status: '',
|
||||
tracking_number: '',
|
||||
reason: ''
|
||||
},
|
||||
|
||||
// Mark as shipped modal
|
||||
showMarkAsShippedModal: false,
|
||||
markingAsShipped: false,
|
||||
shipForm: {
|
||||
tracking_number: '',
|
||||
tracking_url: '',
|
||||
shipping_carrier: ''
|
||||
},
|
||||
|
||||
// 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() {
|
||||
adminOrdersLog.info('Orders init() called');
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._adminOrdersInitialized) {
|
||||
adminOrdersLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminOrdersInitialized = true;
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
// Initialize Tom Select for vendor filter
|
||||
this.initVendorSelect();
|
||||
|
||||
// Check localStorage for saved vendor
|
||||
const savedVendorId = localStorage.getItem('orders_selected_vendor_id');
|
||||
if (savedVendorId) {
|
||||
adminOrdersLog.info('Restoring saved vendor:', savedVendorId);
|
||||
// Restore vendor after a short delay to ensure TomSelect is ready
|
||||
// restoreSavedVendor will call loadOrders() after setting the filter
|
||||
setTimeout(async () => {
|
||||
await this.restoreSavedVendor(parseInt(savedVendorId));
|
||||
}, 200);
|
||||
// Load stats and vendors, but not orders (restoreSavedVendor will do that)
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadVendors()
|
||||
]);
|
||||
} else {
|
||||
// No saved vendor - load all data including unfiltered orders
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadVendors(),
|
||||
this.loadOrders()
|
||||
]);
|
||||
}
|
||||
|
||||
adminOrdersLog.info('Orders initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Restore saved vendor from localStorage
|
||||
*/
|
||||
async restoreSavedVendor(vendorId) {
|
||||
try {
|
||||
const vendor = await apiClient.get(`/admin/vendors/${vendorId}`);
|
||||
if (this.vendorSelectInstance && vendor) {
|
||||
// Add the vendor as an option and select it
|
||||
this.vendorSelectInstance.addOption({
|
||||
id: vendor.id,
|
||||
name: vendor.name,
|
||||
vendor_code: vendor.vendor_code
|
||||
});
|
||||
this.vendorSelectInstance.setValue(vendor.id, true);
|
||||
|
||||
// Set the filter state (this is the key fix!)
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_id = vendor.id;
|
||||
|
||||
adminOrdersLog.info('Restored vendor:', vendor.name);
|
||||
|
||||
// Load orders with the vendor filter applied
|
||||
await this.loadOrders();
|
||||
}
|
||||
} catch (error) {
|
||||
adminOrdersLog.warn('Failed to restore saved vendor, clearing localStorage:', error);
|
||||
localStorage.removeItem('orders_selected_vendor_id');
|
||||
// Load unfiltered orders as fallback
|
||||
await this.loadOrders();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize Tom Select for vendor autocomplete
|
||||
*/
|
||||
initVendorSelect() {
|
||||
const selectEl = this.$refs.vendorSelect;
|
||||
if (!selectEl) {
|
||||
adminOrdersLog.warn('Vendor select element not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for Tom Select to be available
|
||||
if (typeof TomSelect === 'undefined') {
|
||||
adminOrdersLog.warn('TomSelect not loaded, retrying in 100ms');
|
||||
setTimeout(() => this.initVendorSelect(), 100);
|
||||
return;
|
||||
}
|
||||
|
||||
this.vendorSelectInstance = new TomSelect(selectEl, {
|
||||
valueField: 'id',
|
||||
labelField: 'name',
|
||||
searchField: ['name', 'vendor_code'],
|
||||
placeholder: 'Search vendor by name or code...',
|
||||
allowEmptyOption: true,
|
||||
load: async (query, callback) => {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors', {
|
||||
search: query,
|
||||
limit: 50
|
||||
});
|
||||
callback(response.vendors || []);
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to search vendors:', error);
|
||||
callback([]);
|
||||
}
|
||||
},
|
||||
render: {
|
||||
option: (data, escape) => {
|
||||
return `<div class="flex items-center justify-between py-1">
|
||||
<span>${escape(data.name)}</span>
|
||||
<span class="text-xs text-gray-400 font-mono">${escape(data.vendor_code || '')}</span>
|
||||
</div>`;
|
||||
},
|
||||
item: (data, escape) => {
|
||||
return `<div>${escape(data.name)}</div>`;
|
||||
}
|
||||
},
|
||||
onChange: (value) => {
|
||||
if (value) {
|
||||
const vendor = this.vendorSelectInstance.options[value];
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_id = value;
|
||||
// Save to localStorage
|
||||
localStorage.setItem('orders_selected_vendor_id', value.toString());
|
||||
} else {
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_id = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('orders_selected_vendor_id');
|
||||
}
|
||||
this.pagination.page = 1;
|
||||
this.loadOrders();
|
||||
}
|
||||
});
|
||||
|
||||
adminOrdersLog.info('Vendor select initialized');
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear vendor filter
|
||||
*/
|
||||
clearVendorFilter() {
|
||||
if (this.vendorSelectInstance) {
|
||||
this.vendorSelectInstance.clear();
|
||||
}
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_id = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('orders_selected_vendor_id');
|
||||
this.pagination.page = 1;
|
||||
this.loadOrders();
|
||||
},
|
||||
|
||||
/**
|
||||
* Load order statistics
|
||||
*/
|
||||
async loadStats() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/orders/stats');
|
||||
this.stats = response;
|
||||
adminOrdersLog.info('Loaded stats:', this.stats);
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to load stats:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load available vendors for filter
|
||||
*/
|
||||
async loadVendors() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/orders/vendors');
|
||||
this.vendors = response.vendors || [];
|
||||
adminOrdersLog.info('Loaded vendors:', this.vendors.length);
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to load vendors:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 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.vendor_id) {
|
||||
params.append('vendor_id', this.filters.vendor_id);
|
||||
}
|
||||
if (this.filters.status) {
|
||||
params.append('status', this.filters.status);
|
||||
}
|
||||
if (this.filters.channel) {
|
||||
params.append('channel', this.filters.channel);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(`/admin/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);
|
||||
|
||||
adminOrdersLog.info('Loaded orders:', this.orders.length, 'of', this.pagination.total);
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to load orders:', error);
|
||||
this.error = error.message || 'Failed to load orders';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Debounced search handler
|
||||
*/
|
||||
debouncedSearch() {
|
||||
clearTimeout(this.searchTimeout);
|
||||
this.searchTimeout = setTimeout(() => {
|
||||
this.pagination.page = 1;
|
||||
this.loadOrders();
|
||||
}, 300);
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh orders list
|
||||
*/
|
||||
async refresh() {
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadVendors(),
|
||||
this.loadOrders()
|
||||
]);
|
||||
},
|
||||
|
||||
/**
|
||||
* View order details
|
||||
*/
|
||||
async viewOrder(order) {
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/orders/${order.id}`);
|
||||
this.selectedOrderDetail = response;
|
||||
this.showDetailModal = true;
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to load order details:', error);
|
||||
Utils.showToast('Failed to load order details.', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Open status update modal
|
||||
*/
|
||||
openStatusModal(order) {
|
||||
this.selectedOrder = order;
|
||||
this.statusForm = {
|
||||
status: order.status,
|
||||
tracking_number: order.tracking_number || '',
|
||||
reason: ''
|
||||
};
|
||||
this.showStatusModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Update order status
|
||||
*/
|
||||
async updateStatus() {
|
||||
if (!this.selectedOrder || this.statusForm.status === this.selectedOrder.status) return;
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
const payload = {
|
||||
status: this.statusForm.status
|
||||
};
|
||||
|
||||
if (this.statusForm.tracking_number) {
|
||||
payload.tracking_number = this.statusForm.tracking_number;
|
||||
}
|
||||
|
||||
if (this.statusForm.reason) {
|
||||
payload.reason = this.statusForm.reason;
|
||||
}
|
||||
|
||||
await apiClient.patch(`/admin/orders/${this.selectedOrder.id}/status`, payload);
|
||||
|
||||
adminOrdersLog.info('Updated order status:', this.selectedOrder.id);
|
||||
|
||||
this.showStatusModal = false;
|
||||
this.selectedOrder = null;
|
||||
|
||||
Utils.showToast('Order status updated successfully.', 'success');
|
||||
|
||||
await this.refresh();
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to update order status:', error);
|
||||
Utils.showToast(error.message || 'Failed to update status.', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Open mark as shipped modal
|
||||
*/
|
||||
openMarkAsShippedModal(order) {
|
||||
this.selectedOrder = order;
|
||||
this.shipForm = {
|
||||
tracking_number: order.tracking_number || '',
|
||||
tracking_url: order.tracking_url || '',
|
||||
shipping_carrier: order.shipping_carrier || ''
|
||||
};
|
||||
this.showMarkAsShippedModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Mark order as shipped
|
||||
*/
|
||||
async markAsShipped() {
|
||||
if (!this.selectedOrder) return;
|
||||
|
||||
this.markingAsShipped = true;
|
||||
try {
|
||||
const payload = {};
|
||||
|
||||
if (this.shipForm.tracking_number) {
|
||||
payload.tracking_number = this.shipForm.tracking_number;
|
||||
}
|
||||
if (this.shipForm.tracking_url) {
|
||||
payload.tracking_url = this.shipForm.tracking_url;
|
||||
}
|
||||
if (this.shipForm.shipping_carrier) {
|
||||
payload.shipping_carrier = this.shipForm.shipping_carrier;
|
||||
}
|
||||
|
||||
await apiClient.post(`/admin/orders/${this.selectedOrder.id}/ship`, payload);
|
||||
|
||||
adminOrdersLog.info('Marked order as shipped:', this.selectedOrder.id);
|
||||
|
||||
this.showMarkAsShippedModal = false;
|
||||
this.selectedOrder = null;
|
||||
|
||||
Utils.showToast('Order marked as shipped successfully.', 'success');
|
||||
|
||||
await this.refresh();
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to mark order as shipped:', error);
|
||||
Utils.showToast(error.message || 'Failed to mark as shipped.', 'error');
|
||||
} finally {
|
||||
this.markingAsShipped = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Download shipping label for an order
|
||||
*/
|
||||
async downloadShippingLabel(order) {
|
||||
try {
|
||||
const labelInfo = await apiClient.get(`/admin/orders/${order.id}/shipping-label`);
|
||||
|
||||
if (labelInfo.label_url) {
|
||||
// Open label URL in new tab
|
||||
window.open(labelInfo.label_url, '_blank');
|
||||
} else {
|
||||
Utils.showToast('No shipping label URL available for this order.', 'warning');
|
||||
}
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to get shipping label:', error);
|
||||
Utils.showToast(error.message || 'Failed to get shipping label.', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get CSS class for status badge
|
||||
*/
|
||||
getStatusClass(status) {
|
||||
const classes = {
|
||||
pending: 'text-orange-700 bg-orange-100 dark:bg-orange-700 dark:text-orange-100',
|
||||
processing: 'text-blue-700 bg-blue-100 dark:bg-blue-700 dark:text-blue-100',
|
||||
shipped: 'text-purple-700 bg-purple-100 dark:bg-purple-700 dark:text-purple-100',
|
||||
delivered: 'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100',
|
||||
cancelled: 'text-red-700 bg-red-100 dark:bg-red-700 dark:text-red-100',
|
||||
refunded: 'text-gray-700 bg-gray-100 dark:bg-gray-700 dark:text-gray-100'
|
||||
};
|
||||
return classes[status] || 'text-gray-700 bg-gray-100 dark:bg-gray-700 dark:text-gray-100';
|
||||
},
|
||||
|
||||
/**
|
||||
* Format price for display
|
||||
*/
|
||||
formatPrice(price, currency = 'EUR') {
|
||||
if (price === null || price === undefined) return '-';
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: currency || 'EUR'
|
||||
}).format(price);
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date for display
|
||||
*/
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return '-';
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('en-GB', {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
year: 'numeric'
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Format time for display
|
||||
*/
|
||||
formatTime(dateString) {
|
||||
if (!dateString) return '';
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleTimeString('en-GB', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Format full date and time
|
||||
*/
|
||||
formatDateTime(dateString) {
|
||||
if (!dateString) return '-';
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleString('en-GB', {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
year: '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();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,357 +0,0 @@
|
||||
// static/admin/js/subscription-tiers.js
|
||||
// noqa: JS-003 - Uses ...baseData which is data() with safety check
|
||||
|
||||
const tiersLog = window.LogConfig?.loggers?.subscriptionTiers || window.LogConfig?.createLogger?.('subscriptionTiers') || console;
|
||||
|
||||
function adminSubscriptionTiers() {
|
||||
// Get base data with safety check for standalone usage
|
||||
const baseData = typeof data === 'function' ? data() : {};
|
||||
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...baseData,
|
||||
|
||||
// Page-specific state
|
||||
currentPage: 'subscription-tiers',
|
||||
loading: true,
|
||||
error: null,
|
||||
successMessage: null,
|
||||
saving: false,
|
||||
|
||||
// Data
|
||||
tiers: [],
|
||||
stats: null,
|
||||
includeInactive: false,
|
||||
|
||||
// Feature management
|
||||
features: [],
|
||||
categories: [],
|
||||
featuresGrouped: {},
|
||||
selectedFeatures: [],
|
||||
selectedTierForFeatures: null,
|
||||
showFeaturePanel: false,
|
||||
loadingFeatures: false,
|
||||
savingFeatures: false,
|
||||
|
||||
// Sorting
|
||||
sortBy: 'display_order',
|
||||
sortOrder: 'asc',
|
||||
|
||||
// Modal state
|
||||
showModal: false,
|
||||
editingTier: null,
|
||||
formData: {
|
||||
code: '',
|
||||
name: '',
|
||||
description: '',
|
||||
price_monthly_cents: 0,
|
||||
price_annual_cents: null,
|
||||
orders_per_month: null,
|
||||
products_limit: null,
|
||||
team_members: null,
|
||||
display_order: 0,
|
||||
stripe_product_id: '',
|
||||
stripe_price_monthly_id: '',
|
||||
features: [],
|
||||
is_active: true,
|
||||
is_public: true
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminSubscriptionTiersInitialized) {
|
||||
tiersLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminSubscriptionTiersInitialized = true;
|
||||
|
||||
tiersLog.info('=== SUBSCRIPTION TIERS PAGE INITIALIZING ===');
|
||||
try {
|
||||
await Promise.all([
|
||||
this.loadTiers(),
|
||||
this.loadStats(),
|
||||
this.loadFeatures(),
|
||||
this.loadCategories()
|
||||
]);
|
||||
tiersLog.info('=== SUBSCRIPTION TIERS PAGE INITIALIZED ===');
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to initialize subscription tiers page:', error);
|
||||
this.error = 'Failed to load page data. Please refresh.';
|
||||
}
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
this.error = null;
|
||||
this.successMessage = null;
|
||||
await this.loadTiers();
|
||||
await this.loadStats();
|
||||
},
|
||||
|
||||
async loadTiers() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.append('include_inactive', this.includeInactive);
|
||||
if (this.sortBy) params.append('sort_by', this.sortBy);
|
||||
if (this.sortOrder) params.append('sort_order', this.sortOrder);
|
||||
|
||||
const data = await apiClient.get(`/admin/subscriptions/tiers?${params}`);
|
||||
this.tiers = data.tiers || [];
|
||||
tiersLog.info(`Loaded ${this.tiers.length} tiers`);
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load tiers:', error);
|
||||
this.error = error.message || 'Failed to load subscription tiers';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
handleSort(key) {
|
||||
if (this.sortBy === key) {
|
||||
this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
this.sortBy = key;
|
||||
this.sortOrder = 'asc';
|
||||
}
|
||||
this.loadTiers();
|
||||
},
|
||||
|
||||
async loadStats() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/subscriptions/stats');
|
||||
this.stats = data;
|
||||
tiersLog.info('Loaded subscription stats');
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load stats:', error);
|
||||
// Non-critical, don't show error
|
||||
}
|
||||
},
|
||||
|
||||
openCreateModal() {
|
||||
this.editingTier = null;
|
||||
this.formData = {
|
||||
code: '',
|
||||
name: '',
|
||||
description: '',
|
||||
price_monthly_cents: 0,
|
||||
price_annual_cents: null,
|
||||
orders_per_month: null,
|
||||
products_limit: null,
|
||||
team_members: null,
|
||||
display_order: this.tiers.length,
|
||||
stripe_product_id: '',
|
||||
stripe_price_monthly_id: '',
|
||||
features: [],
|
||||
is_active: true,
|
||||
is_public: true
|
||||
};
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
openEditModal(tier) {
|
||||
this.editingTier = tier;
|
||||
this.formData = {
|
||||
code: tier.code,
|
||||
name: tier.name,
|
||||
description: tier.description || '',
|
||||
price_monthly_cents: tier.price_monthly_cents,
|
||||
price_annual_cents: tier.price_annual_cents,
|
||||
orders_per_month: tier.orders_per_month,
|
||||
products_limit: tier.products_limit,
|
||||
team_members: tier.team_members,
|
||||
display_order: tier.display_order,
|
||||
stripe_product_id: tier.stripe_product_id || '',
|
||||
stripe_price_monthly_id: tier.stripe_price_monthly_id || '',
|
||||
features: tier.features || [],
|
||||
is_active: tier.is_active,
|
||||
is_public: tier.is_public
|
||||
};
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
closeModal() {
|
||||
this.showModal = false;
|
||||
this.editingTier = null;
|
||||
},
|
||||
|
||||
async saveTier() {
|
||||
this.saving = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
// Clean up null values for empty strings
|
||||
const payload = { ...this.formData };
|
||||
if (payload.price_annual_cents === '') payload.price_annual_cents = null;
|
||||
if (payload.orders_per_month === '') payload.orders_per_month = null;
|
||||
if (payload.products_limit === '') payload.products_limit = null;
|
||||
if (payload.team_members === '') payload.team_members = null;
|
||||
|
||||
if (this.editingTier) {
|
||||
// Update existing tier
|
||||
await apiClient.patch(`/admin/subscriptions/tiers/${this.editingTier.code}`, payload);
|
||||
this.successMessage = `Tier "${payload.name}" updated successfully`;
|
||||
} else {
|
||||
// Create new tier
|
||||
await apiClient.post('/admin/subscriptions/tiers', payload);
|
||||
this.successMessage = `Tier "${payload.name}" created successfully`;
|
||||
}
|
||||
|
||||
this.closeModal();
|
||||
await this.loadTiers();
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to save tier:', error);
|
||||
this.error = error.message || 'Failed to save tier';
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
async toggleTierStatus(tier, activate) {
|
||||
try {
|
||||
await apiClient.patch(`/admin/subscriptions/tiers/${tier.code}`, {
|
||||
is_active: activate
|
||||
});
|
||||
this.successMessage = `Tier "${tier.name}" ${activate ? 'activated' : 'deactivated'}`;
|
||||
await this.loadTiers();
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to toggle tier status:', error);
|
||||
this.error = error.message || 'Failed to update tier';
|
||||
}
|
||||
},
|
||||
|
||||
formatCurrency(cents) {
|
||||
if (cents === null || cents === undefined) return '-';
|
||||
return new Intl.NumberFormat('de-LU', {
|
||||
style: 'currency',
|
||||
currency: 'EUR'
|
||||
}).format(cents / 100);
|
||||
},
|
||||
|
||||
// ==================== FEATURE MANAGEMENT ====================
|
||||
|
||||
async loadFeatures() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/features');
|
||||
this.features = data.features || [];
|
||||
tiersLog.info(`Loaded ${this.features.length} features`);
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load features:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async loadCategories() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/features/categories');
|
||||
this.categories = data.categories || [];
|
||||
tiersLog.info(`Loaded ${this.categories.length} categories`);
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load categories:', error);
|
||||
}
|
||||
},
|
||||
|
||||
groupFeaturesByCategory() {
|
||||
this.featuresGrouped = {};
|
||||
for (const category of this.categories) {
|
||||
this.featuresGrouped[category] = this.features.filter(f => f.category === category);
|
||||
}
|
||||
},
|
||||
|
||||
async openFeaturePanel(tier) {
|
||||
tiersLog.info('Opening feature panel for tier:', tier.code);
|
||||
this.selectedTierForFeatures = tier;
|
||||
this.loadingFeatures = true;
|
||||
this.showFeaturePanel = true;
|
||||
|
||||
try {
|
||||
// Load tier's current features
|
||||
const data = await apiClient.get(`/admin/features/tiers/${tier.code}/features`);
|
||||
if (data.features) {
|
||||
this.selectedFeatures = data.features.map(f => f.code);
|
||||
} else {
|
||||
this.selectedFeatures = tier.features || [];
|
||||
}
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to load tier features:', error);
|
||||
this.selectedFeatures = tier.features || [];
|
||||
} finally {
|
||||
this.groupFeaturesByCategory();
|
||||
this.loadingFeatures = false;
|
||||
}
|
||||
},
|
||||
|
||||
closeFeaturePanel() {
|
||||
this.showFeaturePanel = false;
|
||||
this.selectedTierForFeatures = null;
|
||||
this.selectedFeatures = [];
|
||||
this.featuresGrouped = {};
|
||||
},
|
||||
|
||||
toggleFeature(featureCode) {
|
||||
const index = this.selectedFeatures.indexOf(featureCode);
|
||||
if (index === -1) {
|
||||
this.selectedFeatures.push(featureCode);
|
||||
} else {
|
||||
this.selectedFeatures.splice(index, 1);
|
||||
}
|
||||
},
|
||||
|
||||
isFeatureSelected(featureCode) {
|
||||
return this.selectedFeatures.includes(featureCode);
|
||||
},
|
||||
|
||||
async saveFeatures() {
|
||||
if (!this.selectedTierForFeatures) return;
|
||||
|
||||
tiersLog.info('Saving features for tier:', this.selectedTierForFeatures.code);
|
||||
this.savingFeatures = true;
|
||||
|
||||
try {
|
||||
await apiClient.put(
|
||||
`/admin/features/tiers/${this.selectedTierForFeatures.code}/features`,
|
||||
{ feature_codes: this.selectedFeatures }
|
||||
);
|
||||
|
||||
this.successMessage = `Features updated for ${this.selectedTierForFeatures.name}`;
|
||||
this.closeFeaturePanel();
|
||||
await this.loadTiers();
|
||||
} catch (error) {
|
||||
tiersLog.error('Failed to save features:', error);
|
||||
this.error = error.message || 'Failed to save features';
|
||||
} finally {
|
||||
this.savingFeatures = false;
|
||||
}
|
||||
},
|
||||
|
||||
selectAllInCategory(category) {
|
||||
const categoryFeatures = this.featuresGrouped[category] || [];
|
||||
for (const feature of categoryFeatures) {
|
||||
if (!this.selectedFeatures.includes(feature.code)) {
|
||||
this.selectedFeatures.push(feature.code);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
deselectAllInCategory(category) {
|
||||
const categoryFeatures = this.featuresGrouped[category] || [];
|
||||
const codes = categoryFeatures.map(f => f.code);
|
||||
this.selectedFeatures = this.selectedFeatures.filter(c => !codes.includes(c));
|
||||
},
|
||||
|
||||
allSelectedInCategory(category) {
|
||||
const categoryFeatures = this.featuresGrouped[category] || [];
|
||||
if (categoryFeatures.length === 0) return false;
|
||||
return categoryFeatures.every(f => this.selectedFeatures.includes(f.code));
|
||||
},
|
||||
|
||||
formatCategoryName(category) {
|
||||
return category
|
||||
.split('_')
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
tiersLog.info('Subscription tiers module loaded');
|
||||
@@ -1,269 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/subscriptions.js
|
||||
// noqa: JS-003 - Uses ...baseData which is data() with safety check
|
||||
|
||||
const subsLog = window.LogConfig?.loggers?.subscriptions || console;
|
||||
|
||||
function adminSubscriptions() {
|
||||
// Get base data with safety check for standalone usage
|
||||
const baseData = typeof data === 'function' ? data() : {};
|
||||
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...baseData,
|
||||
|
||||
// Page-specific state
|
||||
currentPage: 'subscriptions',
|
||||
loading: true,
|
||||
error: null,
|
||||
successMessage: null,
|
||||
saving: false,
|
||||
|
||||
// Data
|
||||
subscriptions: [],
|
||||
stats: null,
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
search: '',
|
||||
status: '',
|
||||
tier: ''
|
||||
},
|
||||
|
||||
// Pagination
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Sorting
|
||||
sortBy: 'vendor_name',
|
||||
sortOrder: 'asc',
|
||||
|
||||
// Modal state
|
||||
showModal: false,
|
||||
editingSub: null,
|
||||
formData: {
|
||||
tier: '',
|
||||
status: '',
|
||||
custom_orders_limit: null,
|
||||
custom_products_limit: null,
|
||||
custom_team_limit: null
|
||||
},
|
||||
|
||||
// Computed: Total pages
|
||||
get totalPages() {
|
||||
return this.pagination.pages;
|
||||
},
|
||||
|
||||
// Computed: Start index for pagination display
|
||||
get startIndex() {
|
||||
if (this.pagination.total === 0) return 0;
|
||||
return (this.pagination.page - 1) * this.pagination.per_page + 1;
|
||||
},
|
||||
|
||||
// Computed: End index for pagination display
|
||||
get endIndex() {
|
||||
const end = this.pagination.page * this.pagination.per_page;
|
||||
return end > this.pagination.total ? this.pagination.total : end;
|
||||
},
|
||||
|
||||
// Computed: Page numbers for pagination
|
||||
get pageNumbers() {
|
||||
const pages = [];
|
||||
const totalPages = this.totalPages;
|
||||
const current = this.pagination.page;
|
||||
|
||||
if (totalPages <= 7) {
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
pages.push(1);
|
||||
if (current > 3) {
|
||||
pages.push('...');
|
||||
}
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(totalPages - 1, current + 1);
|
||||
for (let i = start; i <= end; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
if (current < totalPages - 2) {
|
||||
pages.push('...');
|
||||
}
|
||||
pages.push(totalPages);
|
||||
}
|
||||
return pages;
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminSubscriptionsInitialized) {
|
||||
subsLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminSubscriptionsInitialized = true;
|
||||
|
||||
subsLog.info('=== SUBSCRIPTIONS PAGE INITIALIZING ===');
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
await this.loadStats();
|
||||
await this.loadSubscriptions();
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
this.error = null;
|
||||
this.successMessage = null;
|
||||
await this.loadStats();
|
||||
await this.loadSubscriptions();
|
||||
},
|
||||
|
||||
async loadStats() {
|
||||
try {
|
||||
const data = await apiClient.get('/admin/subscriptions/stats');
|
||||
this.stats = data;
|
||||
subsLog.info('Loaded subscription stats');
|
||||
} catch (error) {
|
||||
subsLog.error('Failed to load stats:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async loadSubscriptions() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', this.pagination.page);
|
||||
params.append('per_page', this.pagination.per_page);
|
||||
if (this.filters.status) params.append('status', this.filters.status);
|
||||
if (this.filters.tier) params.append('tier', this.filters.tier);
|
||||
if (this.filters.search) params.append('search', this.filters.search);
|
||||
if (this.sortBy) params.append('sort_by', this.sortBy);
|
||||
if (this.sortOrder) params.append('sort_order', this.sortOrder);
|
||||
|
||||
const data = await apiClient.get(`/admin/subscriptions?${params}`);
|
||||
this.subscriptions = data.subscriptions || [];
|
||||
this.pagination.total = data.total;
|
||||
this.pagination.pages = data.pages;
|
||||
subsLog.info(`Loaded ${this.subscriptions.length} subscriptions (total: ${this.pagination.total})`);
|
||||
} catch (error) {
|
||||
subsLog.error('Failed to load subscriptions:', error);
|
||||
this.error = error.message || 'Failed to load subscriptions';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
resetFilters() {
|
||||
this.filters = {
|
||||
search: '',
|
||||
status: '',
|
||||
tier: ''
|
||||
};
|
||||
this.pagination.page = 1;
|
||||
this.loadSubscriptions();
|
||||
},
|
||||
|
||||
handleSort(key) {
|
||||
if (this.sortBy === key) {
|
||||
this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
this.sortBy = key;
|
||||
this.sortOrder = 'asc';
|
||||
}
|
||||
this.pagination.page = 1;
|
||||
this.loadSubscriptions();
|
||||
},
|
||||
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
this.loadSubscriptions();
|
||||
}
|
||||
},
|
||||
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.totalPages) {
|
||||
this.pagination.page++;
|
||||
this.loadSubscriptions();
|
||||
}
|
||||
},
|
||||
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadSubscriptions();
|
||||
}
|
||||
},
|
||||
|
||||
openEditModal(sub) {
|
||||
this.editingSub = sub;
|
||||
this.formData = {
|
||||
tier: sub.tier,
|
||||
status: sub.status,
|
||||
custom_orders_limit: sub.custom_orders_limit,
|
||||
custom_products_limit: sub.custom_products_limit,
|
||||
custom_team_limit: sub.custom_team_limit
|
||||
};
|
||||
this.showModal = true;
|
||||
},
|
||||
|
||||
closeModal() {
|
||||
this.showModal = false;
|
||||
this.editingSub = null;
|
||||
},
|
||||
|
||||
async saveSubscription() {
|
||||
if (!this.editingSub) return;
|
||||
|
||||
this.saving = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
// Clean up null values for empty strings
|
||||
const payload = { ...this.formData };
|
||||
if (payload.custom_orders_limit === '') payload.custom_orders_limit = null;
|
||||
if (payload.custom_products_limit === '') payload.custom_products_limit = null;
|
||||
if (payload.custom_team_limit === '') payload.custom_team_limit = null;
|
||||
|
||||
await apiClient.patch(`/admin/subscriptions/${this.editingSub.vendor_id}`, payload);
|
||||
this.successMessage = `Subscription for "${this.editingSub.vendor_name}" updated`;
|
||||
|
||||
this.closeModal();
|
||||
await this.loadSubscriptions();
|
||||
await this.loadStats();
|
||||
} catch (error) {
|
||||
subsLog.error('Failed to save subscription:', error);
|
||||
this.error = error.message || 'Failed to update subscription';
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
formatDate(dateStr) {
|
||||
if (!dateStr) return '-';
|
||||
return new Date(dateStr).toLocaleDateString('de-LU', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
});
|
||||
},
|
||||
|
||||
formatCurrency(cents) {
|
||||
if (cents === null || cents === undefined) return '-';
|
||||
return new Intl.NumberFormat('de-LU', {
|
||||
style: 'currency',
|
||||
currency: 'EUR'
|
||||
}).format(cents / 100);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
subsLog.info('Subscriptions module loaded');
|
||||
@@ -1,249 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
/**
|
||||
* Testing Dashboard Component
|
||||
* Manages the pytest testing dashboard page
|
||||
*/
|
||||
|
||||
// Use centralized logger
|
||||
const testingDashboardLog = window.LogConfig.createLogger('TESTING-DASHBOARD');
|
||||
|
||||
function testingDashboard() {
|
||||
return {
|
||||
// Extend base data
|
||||
...data(),
|
||||
|
||||
// Set current page for navigation
|
||||
currentPage: 'testing',
|
||||
|
||||
// Dashboard-specific data
|
||||
loading: false,
|
||||
running: false,
|
||||
collecting: false,
|
||||
error: null,
|
||||
successMessage: null,
|
||||
activeRunId: null,
|
||||
pollInterval: null,
|
||||
elapsedTime: 0,
|
||||
elapsedTimer: null,
|
||||
|
||||
// Statistics
|
||||
stats: {
|
||||
total_tests: 0,
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
errors: 0,
|
||||
skipped: 0,
|
||||
pass_rate: 0,
|
||||
duration_seconds: 0,
|
||||
coverage_percent: null,
|
||||
last_run: null,
|
||||
last_run_status: null,
|
||||
total_test_files: 0,
|
||||
collected_tests: 0,
|
||||
unit_tests: 0,
|
||||
integration_tests: 0,
|
||||
performance_tests: 0,
|
||||
system_tests: 0,
|
||||
last_collected: null,
|
||||
trend: [],
|
||||
by_category: {},
|
||||
top_failing: []
|
||||
},
|
||||
|
||||
// Recent runs
|
||||
runs: [],
|
||||
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._adminTestingDashboardInitialized) return;
|
||||
window._adminTestingDashboardInitialized = true;
|
||||
|
||||
try {
|
||||
testingDashboardLog.info('Initializing testing dashboard');
|
||||
await this.loadStats();
|
||||
await this.loadRuns();
|
||||
// Check if there's a running test and resume polling
|
||||
await this.checkForRunningTests();
|
||||
} catch (error) {
|
||||
testingDashboardLog.error('Failed to initialize testing dashboard:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async checkForRunningTests() {
|
||||
// Check if there's already a test running
|
||||
const runningRun = this.runs.find(r => r.status === 'running');
|
||||
if (runningRun) {
|
||||
testingDashboardLog.info('Found running test:', runningRun.id);
|
||||
this.running = true;
|
||||
this.activeRunId = runningRun.id;
|
||||
|
||||
// Calculate elapsed time from when the run started
|
||||
const startTime = new Date(runningRun.timestamp);
|
||||
this.elapsedTime = Math.floor((Date.now() - startTime.getTime()) / 1000);
|
||||
|
||||
// Start elapsed time counter
|
||||
this.elapsedTimer = setInterval(() => {
|
||||
this.elapsedTime++;
|
||||
}, 1000);
|
||||
|
||||
// Start polling for status
|
||||
this.pollInterval = setInterval(() => this.pollRunStatus(), 2000);
|
||||
}
|
||||
},
|
||||
|
||||
async loadStats() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const stats = await apiClient.get('/admin/tests/stats');
|
||||
this.stats = stats;
|
||||
testingDashboardLog.info('Stats loaded:', stats);
|
||||
} catch (err) {
|
||||
testingDashboardLog.error('Failed to load stats:', err);
|
||||
this.error = err.message;
|
||||
|
||||
// Redirect to login if unauthorized
|
||||
if (err.message.includes('Unauthorized')) {
|
||||
window.location.href = '/admin/login';
|
||||
}
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async loadRuns() {
|
||||
try {
|
||||
const runs = await apiClient.get('/admin/tests/runs?limit=10');
|
||||
this.runs = runs;
|
||||
testingDashboardLog.info('Runs loaded:', runs.length);
|
||||
} catch (err) {
|
||||
testingDashboardLog.error('Failed to load runs:', err);
|
||||
// Don't set error - stats are more important
|
||||
}
|
||||
},
|
||||
|
||||
async runTests(testPath = 'tests') {
|
||||
this.running = true;
|
||||
this.error = null;
|
||||
this.successMessage = null;
|
||||
this.elapsedTime = 0;
|
||||
|
||||
testingDashboardLog.info('Starting tests:', testPath);
|
||||
|
||||
try {
|
||||
// Start the test run (returns immediately)
|
||||
const result = await apiClient.post('/admin/tests/run', {
|
||||
test_path: testPath
|
||||
});
|
||||
|
||||
testingDashboardLog.info('Test run started:', result);
|
||||
this.activeRunId = result.id;
|
||||
|
||||
// Start elapsed time counter
|
||||
this.elapsedTimer = setInterval(() => {
|
||||
this.elapsedTime++;
|
||||
}, 1000);
|
||||
|
||||
// Start polling for status
|
||||
this.pollInterval = setInterval(() => this.pollRunStatus(), 2000);
|
||||
|
||||
Utils.showToast('Test run started...', 'info');
|
||||
|
||||
} catch (err) {
|
||||
testingDashboardLog.error('Failed to start tests:', err);
|
||||
this.error = err.message;
|
||||
this.running = false;
|
||||
Utils.showToast('Failed to start tests: ' + err.message, 'error');
|
||||
|
||||
// Redirect to login if unauthorized
|
||||
if (err.message.includes('Unauthorized')) {
|
||||
window.location.href = '/admin/login';
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async pollRunStatus() {
|
||||
if (!this.activeRunId) return;
|
||||
|
||||
try {
|
||||
const run = await apiClient.get(`/admin/tests/runs/${this.activeRunId}`);
|
||||
|
||||
if (run.status !== 'running') {
|
||||
// Test run completed
|
||||
this.stopPolling();
|
||||
|
||||
testingDashboardLog.info('Test run completed:', run);
|
||||
|
||||
// Format success message
|
||||
const status = run.status === 'passed' ? 'All tests passed!' : 'Tests completed with failures.';
|
||||
this.successMessage = `${status} ${run.passed}/${run.total_tests} passed (${run.pass_rate.toFixed(1)}%) in ${this.formatDuration(run.duration_seconds)}`;
|
||||
|
||||
// Reload stats and runs
|
||||
await this.loadStats();
|
||||
await this.loadRuns();
|
||||
|
||||
// Show toast notification
|
||||
Utils.showToast(this.successMessage, run.status === 'passed' ? 'success' : 'warning');
|
||||
|
||||
// Clear success message after 10 seconds
|
||||
setTimeout(() => {
|
||||
this.successMessage = null;
|
||||
}, 10000);
|
||||
}
|
||||
} catch (err) {
|
||||
testingDashboardLog.error('Failed to poll run status:', err);
|
||||
// Don't stop polling on error, might be transient
|
||||
}
|
||||
},
|
||||
|
||||
stopPolling() {
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval);
|
||||
this.pollInterval = null;
|
||||
}
|
||||
if (this.elapsedTimer) {
|
||||
clearInterval(this.elapsedTimer);
|
||||
this.elapsedTimer = null;
|
||||
}
|
||||
this.running = false;
|
||||
this.activeRunId = null;
|
||||
},
|
||||
|
||||
async collectTests() {
|
||||
this.collecting = true;
|
||||
this.error = null;
|
||||
|
||||
testingDashboardLog.info('Collecting tests');
|
||||
|
||||
try {
|
||||
const result = await apiClient.post('/admin/tests/collect');
|
||||
testingDashboardLog.info('Collection completed:', result);
|
||||
|
||||
Utils.showToast(`Collected ${result.total_tests} tests from ${result.total_files} files`, 'success');
|
||||
|
||||
// Reload stats
|
||||
await this.loadStats();
|
||||
} catch (err) {
|
||||
testingDashboardLog.error('Failed to collect tests:', err);
|
||||
Utils.showToast('Failed to collect tests: ' + err.message, 'error');
|
||||
} finally {
|
||||
this.collecting = false;
|
||||
}
|
||||
},
|
||||
|
||||
async refresh() {
|
||||
await this.loadStats();
|
||||
await this.loadRuns();
|
||||
},
|
||||
|
||||
formatDuration(seconds) {
|
||||
if (seconds === null || seconds === undefined) return 'N/A';
|
||||
if (seconds < 1) return `${Math.round(seconds * 1000)}ms`;
|
||||
if (seconds < 60) return `${seconds.toFixed(1)}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const secs = Math.round(seconds % 60);
|
||||
return `${minutes}m ${secs}s`;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
// static/admin/js/testing-hub.js
|
||||
|
||||
// ✅ Use centralized logger - ONE LINE!
|
||||
// Create custom logger for testing hub
|
||||
const testingLog = window.LogConfig.createLogger('TESTING-HUB');
|
||||
|
||||
/**
|
||||
* Testing Hub Alpine.js Component
|
||||
* Central hub for all test suites and QA tools
|
||||
*/
|
||||
function adminTestingHub() {
|
||||
return {
|
||||
// ✅ CRITICAL: Inherit base layout functionality
|
||||
...data(),
|
||||
|
||||
// ✅ CRITICAL: Set page identifier
|
||||
currentPage: 'testing',
|
||||
|
||||
// Test suites data
|
||||
testSuites: [
|
||||
{
|
||||
id: 'auth-flow',
|
||||
name: 'Authentication Flow',
|
||||
description: 'Test login, logout, token expiration, redirects, and protected route access.',
|
||||
url: '/admin/test/auth-flow',
|
||||
icon: 'lock-closed',
|
||||
color: 'blue',
|
||||
testCount: 6,
|
||||
features: [
|
||||
'Login with valid/invalid credentials',
|
||||
'Token expiration handling',
|
||||
'Protected route access & redirects',
|
||||
'localStorage state monitoring'
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'vendors-users',
|
||||
name: 'Data Migration & CRUD',
|
||||
description: 'Test vendor and user creation, listing, editing, deletion, and data migration scenarios.',
|
||||
url: '/admin/test/vendors-users-migration',
|
||||
icon: 'database',
|
||||
color: 'orange',
|
||||
testCount: 10,
|
||||
features: [
|
||||
'Vendor CRUD operations',
|
||||
'User management & roles',
|
||||
'Data migration validation',
|
||||
'Form validation & error handling'
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
// Stats
|
||||
stats: {
|
||||
totalSuites: 2,
|
||||
totalTests: 16,
|
||||
coverage: 'Auth, CRUD',
|
||||
avgDuration: '< 5 min'
|
||||
},
|
||||
|
||||
// Loading state
|
||||
loading: false,
|
||||
|
||||
// ✅ CRITICAL: Proper initialization with guard
|
||||
async init() {
|
||||
testingLog.info('=== TESTING HUB INITIALIZING ===');
|
||||
|
||||
// Prevent multiple initializations
|
||||
if (window._testingHubInitialized) {
|
||||
testingLog.warn('Testing hub already initialized, skipping...');
|
||||
return;
|
||||
}
|
||||
window._testingHubInitialized = true;
|
||||
|
||||
// Calculate stats
|
||||
this.calculateStats();
|
||||
|
||||
testingLog.info('=== TESTING HUB INITIALIZATION COMPLETE ===');
|
||||
},
|
||||
|
||||
/**
|
||||
* Calculate test statistics
|
||||
*/
|
||||
calculateStats() {
|
||||
this.stats.totalSuites = this.testSuites.length;
|
||||
this.stats.totalTests = this.testSuites.reduce((sum, suite) => sum + suite.testCount, 0);
|
||||
testingLog.debug('Stats calculated:', this.stats);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get color classes for test suite cards
|
||||
*/
|
||||
getColorClasses(color) {
|
||||
const colorMap = {
|
||||
blue: {
|
||||
gradient: 'from-blue-500 to-blue-600',
|
||||
button: 'bg-blue-600 hover:bg-blue-700'
|
||||
},
|
||||
orange: {
|
||||
gradient: 'from-orange-500 to-orange-600',
|
||||
button: 'bg-orange-600 hover:bg-orange-700'
|
||||
},
|
||||
green: {
|
||||
gradient: 'from-green-500 to-green-600',
|
||||
button: 'bg-green-600 hover:bg-green-700'
|
||||
},
|
||||
purple: {
|
||||
gradient: 'from-purple-500 to-purple-600',
|
||||
button: 'bg-purple-600 hover:bg-purple-700'
|
||||
}
|
||||
};
|
||||
return colorMap[color] || colorMap.blue;
|
||||
},
|
||||
|
||||
/**
|
||||
* Navigate to test suite
|
||||
*/
|
||||
goToTest(url) {
|
||||
testingLog.info('Navigating to test suite:', url);
|
||||
window.location.href = url;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
testingLog.info('Testing hub module loaded');
|
||||
@@ -1,157 +0,0 @@
|
||||
// static/admin/js/user-create.js
|
||||
|
||||
// Create custom logger for admin user create
|
||||
const userCreateLog = window.LogConfig.createLogger('ADMIN-USER-CREATE');
|
||||
|
||||
function adminUserCreate() {
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...data(),
|
||||
|
||||
// Admin user create page specific state
|
||||
currentPage: 'admin-users',
|
||||
loading: false,
|
||||
formData: {
|
||||
username: '',
|
||||
email: '',
|
||||
password: '',
|
||||
first_name: '',
|
||||
last_name: '',
|
||||
is_super_admin: false,
|
||||
platform_ids: []
|
||||
},
|
||||
platforms: [],
|
||||
errors: {},
|
||||
saving: false,
|
||||
|
||||
// Initialize
|
||||
async init() {
|
||||
userCreateLog.info('=== ADMIN USER CREATE PAGE INITIALIZING ===');
|
||||
|
||||
// Prevent multiple initializations
|
||||
if (window._userCreateInitialized) {
|
||||
userCreateLog.warn('Admin user create page already initialized, skipping...');
|
||||
return;
|
||||
}
|
||||
window._userCreateInitialized = true;
|
||||
|
||||
// Load platforms for admin assignment
|
||||
await this.loadPlatforms();
|
||||
|
||||
userCreateLog.info('=== ADMIN USER CREATE PAGE INITIALIZATION COMPLETE ===');
|
||||
},
|
||||
|
||||
// Load available platforms
|
||||
async loadPlatforms() {
|
||||
try {
|
||||
userCreateLog.debug('Loading platforms...');
|
||||
const response = await apiClient.get('/admin/platforms');
|
||||
this.platforms = response.platforms || response.items || [];
|
||||
userCreateLog.debug(`Loaded ${this.platforms.length} platforms`);
|
||||
} catch (error) {
|
||||
userCreateLog.error('Failed to load platforms:', error);
|
||||
this.platforms = [];
|
||||
}
|
||||
},
|
||||
|
||||
// Validate form
|
||||
validateForm() {
|
||||
this.errors = {};
|
||||
|
||||
if (!this.formData.username.trim()) {
|
||||
this.errors.username = 'Username is required';
|
||||
}
|
||||
if (!this.formData.email.trim()) {
|
||||
this.errors.email = 'Email is required';
|
||||
}
|
||||
if (!this.formData.password || this.formData.password.length < 6) {
|
||||
this.errors.password = 'Password must be at least 6 characters';
|
||||
}
|
||||
|
||||
// Platform admin validation: must have at least one platform
|
||||
if (!this.formData.is_super_admin) {
|
||||
if (!this.formData.platform_ids || this.formData.platform_ids.length === 0) {
|
||||
this.errors.platform_ids = 'Platform admins must be assigned to at least one platform';
|
||||
}
|
||||
}
|
||||
|
||||
return Object.keys(this.errors).length === 0;
|
||||
},
|
||||
|
||||
// Submit form
|
||||
async handleSubmit() {
|
||||
userCreateLog.info('=== CREATING ADMIN USER ===');
|
||||
userCreateLog.debug('Form data:', { ...this.formData, password: '[REDACTED]' });
|
||||
|
||||
if (!this.validateForm()) {
|
||||
userCreateLog.warn('Validation failed:', this.errors);
|
||||
Utils.showToast('Please fix the errors before submitting', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
this.saving = true;
|
||||
|
||||
try {
|
||||
// Use admin-users endpoint for creating admin users
|
||||
const url = '/admin/admin-users';
|
||||
const payload = {
|
||||
email: this.formData.email,
|
||||
username: this.formData.username,
|
||||
password: this.formData.password,
|
||||
first_name: this.formData.first_name || null,
|
||||
last_name: this.formData.last_name || null,
|
||||
is_super_admin: this.formData.is_super_admin,
|
||||
platform_ids: this.formData.is_super_admin ? [] : this.formData.platform_ids.map(id => parseInt(id))
|
||||
};
|
||||
|
||||
window.LogConfig.logApiCall('POST', url, { ...payload, password: '[REDACTED]' }, 'request');
|
||||
|
||||
const startTime = performance.now();
|
||||
const response = await apiClient.post(url, payload);
|
||||
const duration = performance.now() - startTime;
|
||||
|
||||
window.LogConfig.logApiCall('POST', url, response, 'response');
|
||||
window.LogConfig.logPerformance('Create Admin User', duration);
|
||||
|
||||
const userType = this.formData.is_super_admin ? 'Super admin' : 'Platform admin';
|
||||
Utils.showToast(`${userType} created successfully`, 'success');
|
||||
userCreateLog.info(`${userType} created successfully in ${duration}ms`, response);
|
||||
|
||||
// Redirect to the admin users list
|
||||
setTimeout(() => {
|
||||
window.location.href = `/admin/admin-users/${response.id}`;
|
||||
}, 1500);
|
||||
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'Create Admin User');
|
||||
|
||||
// Handle validation errors
|
||||
if (error.details && error.details.validation_errors) {
|
||||
error.details.validation_errors.forEach(err => {
|
||||
const field = err.loc?.[1] || err.loc?.[0];
|
||||
if (field) {
|
||||
this.errors[field] = err.msg;
|
||||
}
|
||||
});
|
||||
userCreateLog.debug('Validation errors:', this.errors);
|
||||
}
|
||||
|
||||
// Handle specific errors
|
||||
if (error.message) {
|
||||
if (error.message.includes('Email already')) {
|
||||
this.errors.email = 'This email is already registered';
|
||||
} else if (error.message.includes('Username already')) {
|
||||
this.errors.username = 'This username is already taken';
|
||||
}
|
||||
}
|
||||
|
||||
Utils.showToast(error.message || 'Failed to create admin user', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
userCreateLog.info('=== ADMIN USER CREATION COMPLETE ===');
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
userCreateLog.info('Admin user create module loaded');
|
||||
@@ -1,176 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/user-detail.js
|
||||
|
||||
// Create custom logger for user detail
|
||||
const userDetailLog = window.LogConfig.createLogger('USER-DETAIL');
|
||||
|
||||
function adminUserDetail() {
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...data(),
|
||||
|
||||
// User detail page specific state
|
||||
currentPage: 'user-detail',
|
||||
user: null,
|
||||
loading: false,
|
||||
saving: false,
|
||||
error: null,
|
||||
userId: null,
|
||||
|
||||
// Initialize
|
||||
async init() {
|
||||
userDetailLog.info('=== USER DETAIL PAGE INITIALIZING ===');
|
||||
|
||||
// Prevent multiple initializations
|
||||
if (window._userDetailInitialized) {
|
||||
userDetailLog.warn('User detail page already initialized, skipping...');
|
||||
return;
|
||||
}
|
||||
window._userDetailInitialized = true;
|
||||
|
||||
// Get user ID from URL
|
||||
const path = window.location.pathname;
|
||||
const match = path.match(/\/admin\/users\/(\d+)$/);
|
||||
|
||||
if (match) {
|
||||
this.userId = match[1];
|
||||
userDetailLog.info('Viewing user:', this.userId);
|
||||
await this.loadUser();
|
||||
} else {
|
||||
userDetailLog.error('No user ID in URL');
|
||||
this.error = 'Invalid user URL';
|
||||
Utils.showToast('Invalid user URL', 'error');
|
||||
}
|
||||
|
||||
userDetailLog.info('=== USER DETAIL PAGE INITIALIZATION COMPLETE ===');
|
||||
},
|
||||
|
||||
// Load user data
|
||||
async loadUser() {
|
||||
userDetailLog.info('Loading user details...');
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const url = `/admin/users/${this.userId}`;
|
||||
window.LogConfig.logApiCall('GET', url, null, 'request');
|
||||
|
||||
const startTime = performance.now();
|
||||
const response = await apiClient.get(url);
|
||||
const duration = performance.now() - startTime;
|
||||
|
||||
window.LogConfig.logApiCall('GET', url, response, 'response');
|
||||
window.LogConfig.logPerformance('Load User Details', duration);
|
||||
|
||||
this.user = response;
|
||||
|
||||
userDetailLog.info(`User loaded in ${duration}ms`, {
|
||||
id: this.user.id,
|
||||
username: this.user.username,
|
||||
role: this.user.role,
|
||||
is_active: this.user.is_active
|
||||
});
|
||||
userDetailLog.debug('Full user data:', this.user);
|
||||
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'Load User Details');
|
||||
this.error = error.message || 'Failed to load user details';
|
||||
Utils.showToast('Failed to load user details', 'error');
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Format date
|
||||
formatDate(dateString) {
|
||||
if (!dateString) {
|
||||
return '-';
|
||||
}
|
||||
return Utils.formatDate(dateString);
|
||||
},
|
||||
|
||||
// Toggle user status
|
||||
async toggleStatus() {
|
||||
const action = this.user.is_active ? 'deactivate' : 'activate';
|
||||
userDetailLog.info(`Toggle status: ${action}`);
|
||||
|
||||
if (!confirm(`Are you sure you want to ${action} ${this.user.username}?`)) {
|
||||
userDetailLog.info('Status toggle cancelled by user');
|
||||
return;
|
||||
}
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
const url = `/admin/users/${this.userId}/status`;
|
||||
window.LogConfig.logApiCall('PUT', url, null, 'request');
|
||||
|
||||
const response = await apiClient.put(url);
|
||||
|
||||
window.LogConfig.logApiCall('PUT', url, response, 'response');
|
||||
|
||||
this.user.is_active = response.is_active;
|
||||
Utils.showToast(`User ${action}d successfully`, 'success');
|
||||
userDetailLog.info(`User ${action}d successfully`);
|
||||
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, `Toggle Status (${action})`);
|
||||
Utils.showToast(error.message || `Failed to ${action} user`, 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Delete user
|
||||
async deleteUser() {
|
||||
userDetailLog.info('Delete user requested:', this.userId);
|
||||
|
||||
if (this.user?.owned_companies_count > 0) {
|
||||
Utils.showToast(`Cannot delete user who owns ${this.user.owned_companies_count} company(ies). Transfer ownership first.`, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm(`Are you sure you want to delete "${this.user.username}"?\n\nThis action cannot be undone.`)) {
|
||||
userDetailLog.info('Delete cancelled by user');
|
||||
return;
|
||||
}
|
||||
|
||||
// Second confirmation for safety
|
||||
if (!confirm(`FINAL CONFIRMATION\n\nAre you absolutely sure you want to delete "${this.user.username}"?`)) {
|
||||
userDetailLog.info('Delete cancelled by user (second confirmation)');
|
||||
return;
|
||||
}
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
const url = `/admin/users/${this.userId}`;
|
||||
window.LogConfig.logApiCall('DELETE', url, null, 'request');
|
||||
|
||||
await apiClient.delete(url);
|
||||
|
||||
window.LogConfig.logApiCall('DELETE', url, null, 'response');
|
||||
|
||||
Utils.showToast('User deleted successfully', 'success');
|
||||
userDetailLog.info('User deleted successfully');
|
||||
|
||||
// Redirect to users list
|
||||
setTimeout(() => window.location.href = '/admin/users', 1500);
|
||||
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'Delete User');
|
||||
Utils.showToast(error.message || 'Failed to delete user', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Refresh user data
|
||||
async refresh() {
|
||||
userDetailLog.info('=== USER REFRESH TRIGGERED ===');
|
||||
await this.loadUser();
|
||||
Utils.showToast('User details refreshed', 'success');
|
||||
userDetailLog.info('=== USER REFRESH COMPLETE ===');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
userDetailLog.info('User detail module loaded');
|
||||
@@ -1,229 +0,0 @@
|
||||
// static/admin/js/user-edit.js
|
||||
|
||||
// Create custom logger for user edit
|
||||
const userEditLog = window.LogConfig.createLogger('USER-EDIT');
|
||||
|
||||
function adminUserEdit() {
|
||||
return {
|
||||
// Inherit base layout functionality from init-alpine.js
|
||||
...data(),
|
||||
|
||||
// User edit page specific state
|
||||
currentPage: 'user-edit',
|
||||
loading: false,
|
||||
user: null,
|
||||
formData: {},
|
||||
errors: {},
|
||||
loadingUser: false,
|
||||
saving: false,
|
||||
userId: null,
|
||||
|
||||
// Initialize
|
||||
async init() {
|
||||
userEditLog.info('=== USER EDIT PAGE INITIALIZING ===');
|
||||
|
||||
// Prevent multiple initializations
|
||||
if (window._userEditInitialized) {
|
||||
userEditLog.warn('User edit page already initialized, skipping...');
|
||||
return;
|
||||
}
|
||||
window._userEditInitialized = true;
|
||||
|
||||
try {
|
||||
// Get user ID from URL
|
||||
const path = window.location.pathname;
|
||||
const match = path.match(/\/admin\/users\/(\d+)\/edit/);
|
||||
|
||||
if (match) {
|
||||
this.userId = parseInt(match[1], 10);
|
||||
userEditLog.info('Editing user:', this.userId);
|
||||
await this.loadUser();
|
||||
} else {
|
||||
userEditLog.error('No user ID in URL');
|
||||
Utils.showToast('Invalid user URL', 'error');
|
||||
setTimeout(() => window.location.href = '/admin/users', 2000);
|
||||
}
|
||||
|
||||
userEditLog.info('=== USER EDIT PAGE INITIALIZATION COMPLETE ===');
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'User Edit Init');
|
||||
Utils.showToast('Failed to initialize page', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
// Load user data
|
||||
async loadUser() {
|
||||
userEditLog.info('Loading user data...');
|
||||
this.loadingUser = true;
|
||||
|
||||
try {
|
||||
const url = `/admin/users/${this.userId}`;
|
||||
window.LogConfig.logApiCall('GET', url, null, 'request');
|
||||
|
||||
const startTime = performance.now();
|
||||
const response = await apiClient.get(url);
|
||||
const duration = performance.now() - startTime;
|
||||
|
||||
window.LogConfig.logApiCall('GET', url, response, 'response');
|
||||
window.LogConfig.logPerformance('Load User', duration);
|
||||
|
||||
this.user = response;
|
||||
|
||||
// Initialize form data
|
||||
this.formData = {
|
||||
username: response.username || '',
|
||||
email: response.email || '',
|
||||
first_name: response.first_name || '',
|
||||
last_name: response.last_name || '',
|
||||
role: response.role || 'vendor',
|
||||
is_email_verified: response.is_email_verified || false
|
||||
};
|
||||
|
||||
userEditLog.info(`User loaded in ${duration}ms`, {
|
||||
user_id: this.user.id,
|
||||
username: this.user.username
|
||||
});
|
||||
userEditLog.debug('Form data initialized:', this.formData);
|
||||
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'Load User');
|
||||
Utils.showToast('Failed to load user', 'error');
|
||||
setTimeout(() => window.location.href = '/admin/users', 2000);
|
||||
} finally {
|
||||
this.loadingUser = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Format date
|
||||
formatDate(dateString) {
|
||||
if (!dateString) {
|
||||
return '-';
|
||||
}
|
||||
return Utils.formatDate(dateString);
|
||||
},
|
||||
|
||||
// Submit form
|
||||
async handleSubmit() {
|
||||
userEditLog.info('=== SUBMITTING USER UPDATE ===');
|
||||
userEditLog.debug('Form data:', this.formData);
|
||||
|
||||
this.errors = {};
|
||||
this.saving = true;
|
||||
|
||||
try {
|
||||
const url = `/admin/users/${this.userId}`;
|
||||
window.LogConfig.logApiCall('PUT', url, this.formData, 'request');
|
||||
|
||||
const startTime = performance.now();
|
||||
const response = await apiClient.put(url, this.formData);
|
||||
const duration = performance.now() - startTime;
|
||||
|
||||
window.LogConfig.logApiCall('PUT', url, response, 'response');
|
||||
window.LogConfig.logPerformance('Update User', duration);
|
||||
|
||||
this.user = response;
|
||||
Utils.showToast('User updated successfully', 'success');
|
||||
userEditLog.info(`User updated successfully in ${duration}ms`, response);
|
||||
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'Update User');
|
||||
|
||||
// Handle validation errors
|
||||
if (error.details && error.details.validation_errors) {
|
||||
error.details.validation_errors.forEach(err => {
|
||||
const field = err.loc?.[1] || err.loc?.[0];
|
||||
if (field) {
|
||||
this.errors[field] = err.msg;
|
||||
}
|
||||
});
|
||||
userEditLog.debug('Validation errors:', this.errors);
|
||||
}
|
||||
|
||||
Utils.showToast(error.message || 'Failed to update user', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
userEditLog.info('=== USER UPDATE COMPLETE ===');
|
||||
}
|
||||
},
|
||||
|
||||
// Toggle user status
|
||||
async toggleStatus() {
|
||||
const action = this.user.is_active ? 'deactivate' : 'activate';
|
||||
userEditLog.info(`Toggle status: ${action}`);
|
||||
|
||||
if (!confirm(`Are you sure you want to ${action} ${this.user.username}?`)) {
|
||||
userEditLog.info('Status toggle cancelled by user');
|
||||
return;
|
||||
}
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
const url = `/admin/users/${this.userId}/status`;
|
||||
window.LogConfig.logApiCall('PUT', url, null, 'request');
|
||||
|
||||
const response = await apiClient.put(url);
|
||||
|
||||
window.LogConfig.logApiCall('PUT', url, response, 'response');
|
||||
|
||||
this.user.is_active = response.is_active;
|
||||
Utils.showToast(`User ${action}d successfully`, 'success');
|
||||
userEditLog.info(`User ${action}d successfully`);
|
||||
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, `Toggle Status (${action})`);
|
||||
Utils.showToast(error.message || `Failed to ${action} user`, 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Delete user
|
||||
async deleteUser() {
|
||||
userEditLog.info('=== DELETING USER ===');
|
||||
|
||||
if (this.user.owned_companies_count > 0) {
|
||||
Utils.showToast(`Cannot delete user who owns ${this.user.owned_companies_count} company(ies). Transfer ownership first.`, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm(`Are you sure you want to delete user "${this.user.username}"?\n\nThis action cannot be undone.`)) {
|
||||
userEditLog.info('User deletion cancelled by user');
|
||||
return;
|
||||
}
|
||||
|
||||
// Double confirmation for critical action
|
||||
if (!confirm(`FINAL CONFIRMATION: Delete "${this.user.username}"?\n\nThis will permanently delete the user.`)) {
|
||||
userEditLog.info('User deletion cancelled at final confirmation');
|
||||
return;
|
||||
}
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
const url = `/admin/users/${this.userId}`;
|
||||
|
||||
window.LogConfig.logApiCall('DELETE', url, null, 'request');
|
||||
|
||||
await apiClient.delete(url);
|
||||
|
||||
window.LogConfig.logApiCall('DELETE', url, null, 'response');
|
||||
|
||||
Utils.showToast('User deleted successfully', 'success');
|
||||
userEditLog.info('User deleted successfully');
|
||||
|
||||
// Redirect to users list
|
||||
setTimeout(() => {
|
||||
window.location.href = '/admin/users';
|
||||
}, 1500);
|
||||
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'Delete User');
|
||||
Utils.showToast(error.message || 'Failed to delete user', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
userEditLog.info('=== USER DELETION COMPLETE ===');
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
userEditLog.info('User edit module loaded');
|
||||
@@ -1,299 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/users.js
|
||||
|
||||
// ✅ Use centralized logger - ONE LINE!
|
||||
const usersLog = window.LogConfig.loggers.users;
|
||||
|
||||
function adminUsers() {
|
||||
return {
|
||||
// Inherit base layout functionality
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'users',
|
||||
|
||||
// State
|
||||
users: [],
|
||||
loading: false,
|
||||
error: null,
|
||||
filters: {
|
||||
search: '',
|
||||
role: '',
|
||||
is_active: ''
|
||||
},
|
||||
stats: {
|
||||
total_users: 0,
|
||||
active_users: 0,
|
||||
inactive_users: 0,
|
||||
admin_users: 0
|
||||
},
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Initialization
|
||||
async init() {
|
||||
usersLog.info('=== USERS PAGE INITIALIZING ===');
|
||||
|
||||
// Prevent multiple initializations
|
||||
if (window._usersInitialized) {
|
||||
usersLog.warn('Users page already initialized, skipping...');
|
||||
return;
|
||||
}
|
||||
window._usersInitialized = true;
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
await this.loadUsers();
|
||||
await this.loadStats();
|
||||
|
||||
usersLog.info('=== USERS PAGE INITIALIZATION COMPLETE ===');
|
||||
},
|
||||
|
||||
// Format date helper
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return '-';
|
||||
return Utils.formatDate(dateString);
|
||||
},
|
||||
|
||||
// Computed: Total number of 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: Generate page numbers array with ellipsis
|
||||
get pageNumbers() {
|
||||
const pages = [];
|
||||
const totalPages = this.totalPages;
|
||||
const current = this.pagination.page;
|
||||
|
||||
if (totalPages <= 7) {
|
||||
// Show all pages if 7 or fewer
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
// Always show first page
|
||||
pages.push(1);
|
||||
|
||||
if (current > 3) {
|
||||
pages.push('...');
|
||||
}
|
||||
|
||||
// Show pages around current page
|
||||
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('...');
|
||||
}
|
||||
|
||||
// Always show last page
|
||||
pages.push(totalPages);
|
||||
}
|
||||
|
||||
return pages;
|
||||
},
|
||||
|
||||
// Load users from API
|
||||
async loadUsers() {
|
||||
usersLog.info('Loading users...');
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', this.pagination.page);
|
||||
params.append('per_page', this.pagination.per_page);
|
||||
|
||||
if (this.filters.search) {
|
||||
params.append('search', this.filters.search);
|
||||
}
|
||||
if (this.filters.role) {
|
||||
params.append('role', this.filters.role);
|
||||
}
|
||||
if (this.filters.is_active) {
|
||||
params.append('is_active', this.filters.is_active);
|
||||
}
|
||||
|
||||
const url = `/admin/users?${params}`;
|
||||
window.LogConfig.logApiCall('GET', url, null, 'request');
|
||||
|
||||
const startTime = performance.now();
|
||||
const response = await apiClient.get(url);
|
||||
const duration = performance.now() - startTime;
|
||||
|
||||
window.LogConfig.logApiCall('GET', url, response, 'response');
|
||||
window.LogConfig.logPerformance('Load Users', duration);
|
||||
|
||||
if (response.items) {
|
||||
this.users = response.items;
|
||||
this.pagination.total = response.total;
|
||||
this.pagination.pages = response.pages;
|
||||
this.pagination.page = response.page;
|
||||
this.pagination.per_page = response.per_page;
|
||||
usersLog.info(`Loaded ${this.users.length} users`);
|
||||
}
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'Load Users');
|
||||
this.error = error.message || 'Failed to load users';
|
||||
Utils.showToast('Failed to load users', 'error');
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
// Load statistics
|
||||
async loadStats() {
|
||||
usersLog.info('Loading user statistics...');
|
||||
|
||||
try {
|
||||
const url = '/admin/users/stats';
|
||||
window.LogConfig.logApiCall('GET', url, null, 'request');
|
||||
|
||||
const response = await apiClient.get(url); // ✅ Fixed: lowercase apiClient
|
||||
|
||||
window.LogConfig.logApiCall('GET', url, response, 'response');
|
||||
|
||||
if (response) {
|
||||
this.stats = response;
|
||||
usersLog.debug('Stats loaded:', this.stats);
|
||||
}
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'Load Stats');
|
||||
}
|
||||
},
|
||||
|
||||
// Search with debounce
|
||||
debouncedSearch() {
|
||||
// Clear existing timeout
|
||||
if (this._searchTimeout) {
|
||||
clearTimeout(this._searchTimeout);
|
||||
}
|
||||
// Set new timeout
|
||||
this._searchTimeout = setTimeout(() => {
|
||||
usersLog.info('Search triggered:', this.filters.search);
|
||||
this.pagination.page = 1;
|
||||
this.loadUsers();
|
||||
}, 300);
|
||||
},
|
||||
|
||||
// Pagination
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.pagination.pages) {
|
||||
this.pagination.page++;
|
||||
usersLog.info('Next page:', this.pagination.page);
|
||||
this.loadUsers();
|
||||
}
|
||||
},
|
||||
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
usersLog.info('Previous page:', this.pagination.page);
|
||||
this.loadUsers();
|
||||
}
|
||||
},
|
||||
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
usersLog.info('Go to page:', this.pagination.page);
|
||||
this.loadUsers();
|
||||
}
|
||||
},
|
||||
|
||||
// Actions
|
||||
viewUser(user) {
|
||||
usersLog.info('View user:', user.username);
|
||||
window.location.href = `/admin/users/${user.id}`;
|
||||
},
|
||||
|
||||
editUser(user) {
|
||||
usersLog.info('Edit user:', user.username);
|
||||
window.location.href = `/admin/users/${user.id}/edit`;
|
||||
},
|
||||
|
||||
async toggleUserStatus(user) {
|
||||
const action = user.is_active ? 'deactivate' : 'activate';
|
||||
usersLog.info(`Toggle user status: ${action}`, user.username);
|
||||
|
||||
if (!confirm(`Are you sure you want to ${action} ${user.username}?`)) {
|
||||
usersLog.info('Status toggle cancelled by user');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `/admin/users/${user.id}/status`;
|
||||
window.LogConfig.logApiCall('PUT', url, { is_active: !user.is_active }, 'request');
|
||||
|
||||
await apiClient.put(url, { // ✅ Fixed: lowercase apiClient
|
||||
is_active: !user.is_active
|
||||
});
|
||||
|
||||
Utils.showToast(`User ${action}d successfully`, 'success');
|
||||
usersLog.info(`User ${action}d successfully`);
|
||||
|
||||
await this.loadUsers();
|
||||
await this.loadStats();
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, `Toggle User Status (${action})`);
|
||||
Utils.showToast(`Failed to ${action} user`, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async deleteUser(user) {
|
||||
usersLog.warn('Delete user requested:', user.username);
|
||||
|
||||
if (!confirm(`Are you sure you want to delete ${user.username}? This action cannot be undone.`)) {
|
||||
usersLog.info('Delete cancelled by user');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `/admin/users/${user.id}`;
|
||||
window.LogConfig.logApiCall('DELETE', url, null, 'request');
|
||||
|
||||
await apiClient.delete(url); // ✅ Fixed: lowercase apiClient
|
||||
|
||||
Utils.showToast('User deleted successfully', 'success');
|
||||
usersLog.info('User deleted successfully');
|
||||
|
||||
await this.loadUsers();
|
||||
await this.loadStats();
|
||||
} catch (error) {
|
||||
window.LogConfig.logError(error, 'Delete User');
|
||||
Utils.showToast('Failed to delete user', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
openCreateModal() {
|
||||
usersLog.info('Open create user modal');
|
||||
window.location.href = '/admin/users/create';
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
usersLog.info('Users module loaded');
|
||||
@@ -1,403 +0,0 @@
|
||||
// static/admin/js/vendor-product-create.js
|
||||
/**
|
||||
* Admin vendor product create page logic
|
||||
* Create new vendor product entries with translations
|
||||
*/
|
||||
|
||||
const adminVendorProductCreateLog = window.LogConfig.loggers.adminVendorProductCreate ||
|
||||
window.LogConfig.createLogger('adminVendorProductCreate', false);
|
||||
|
||||
adminVendorProductCreateLog.info('Loading...');
|
||||
|
||||
function adminVendorProductCreate() {
|
||||
adminVendorProductCreateLog.info('adminVendorProductCreate() called');
|
||||
|
||||
// Default translations structure
|
||||
const defaultTranslations = () => ({
|
||||
en: { title: '', description: '' },
|
||||
fr: { title: '', description: '' },
|
||||
de: { title: '', description: '' },
|
||||
lu: { title: '', description: '' }
|
||||
});
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Include media picker functionality (vendor ID getter will be bound via loadMediaLibrary override)
|
||||
...mediaPickerMixin(() => null, false),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'vendor-products',
|
||||
|
||||
// Loading states
|
||||
loading: false,
|
||||
saving: false,
|
||||
|
||||
// Tom Select instance
|
||||
vendorSelectInstance: null,
|
||||
|
||||
// Active language tab
|
||||
activeLanguage: 'en',
|
||||
|
||||
// Form data
|
||||
form: {
|
||||
vendor_id: null,
|
||||
// Translations by language
|
||||
translations: defaultTranslations(),
|
||||
// Product identifiers
|
||||
vendor_sku: '',
|
||||
brand: '',
|
||||
gtin: '',
|
||||
gtin_type: '',
|
||||
// Pricing
|
||||
price: null,
|
||||
sale_price: null,
|
||||
currency: 'EUR',
|
||||
tax_rate_percent: 17,
|
||||
availability: '',
|
||||
// Images
|
||||
primary_image_url: '',
|
||||
additional_images: [],
|
||||
// Status
|
||||
is_active: true,
|
||||
is_featured: false,
|
||||
is_digital: false
|
||||
},
|
||||
|
||||
async init() {
|
||||
adminVendorProductCreateLog.info('Vendor Product Create init() called');
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._adminVendorProductCreateInitialized) {
|
||||
adminVendorProductCreateLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminVendorProductCreateInitialized = true;
|
||||
|
||||
// Initialize Tom Select
|
||||
this.initVendorSelect();
|
||||
|
||||
adminVendorProductCreateLog.info('Vendor Product Create initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize Tom Select for vendor autocomplete
|
||||
*/
|
||||
initVendorSelect() {
|
||||
const selectEl = this.$refs.vendorSelect;
|
||||
if (!selectEl) {
|
||||
adminVendorProductCreateLog.warn('Vendor select element not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for Tom Select to be available
|
||||
if (typeof TomSelect === 'undefined') {
|
||||
adminVendorProductCreateLog.warn('TomSelect not loaded, retrying in 100ms');
|
||||
setTimeout(() => this.initVendorSelect(), 100);
|
||||
return;
|
||||
}
|
||||
|
||||
this.vendorSelectInstance = new TomSelect(selectEl, {
|
||||
valueField: 'id',
|
||||
labelField: 'name',
|
||||
searchField: ['name', 'vendor_code'],
|
||||
placeholder: 'Search vendor...',
|
||||
load: async (query, callback) => {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors', {
|
||||
search: query,
|
||||
limit: 50
|
||||
});
|
||||
callback(response.vendors || []);
|
||||
} catch (error) {
|
||||
adminVendorProductCreateLog.error('Failed to search vendors:', error);
|
||||
callback([]);
|
||||
}
|
||||
},
|
||||
render: {
|
||||
option: (data, escape) => {
|
||||
return `<div class="flex items-center justify-between py-1">
|
||||
<span>${escape(data.name)}</span>
|
||||
<span class="text-xs text-gray-400 font-mono">${escape(data.vendor_code || '')}</span>
|
||||
</div>`;
|
||||
},
|
||||
item: (data, escape) => {
|
||||
return `<div>${escape(data.name)}</div>`;
|
||||
}
|
||||
},
|
||||
onChange: (value) => {
|
||||
this.form.vendor_id = value ? parseInt(value) : null;
|
||||
}
|
||||
});
|
||||
|
||||
adminVendorProductCreateLog.info('Vendor select initialized');
|
||||
},
|
||||
|
||||
/**
|
||||
* Generate a unique vendor SKU
|
||||
* Format: XXXX_XXXX_XXXX (includes vendor_id for uniqueness)
|
||||
*/
|
||||
generateSku() {
|
||||
const vendorId = this.form.vendor_id || 0;
|
||||
|
||||
// Generate random alphanumeric segments
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
||||
const generateSegment = (length) => {
|
||||
let result = '';
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// First segment includes vendor ID (padded)
|
||||
const vendorSegment = vendorId.toString().padStart(4, '0').slice(-4);
|
||||
|
||||
// Generate SKU: VID + random + random
|
||||
const sku = `${vendorSegment}_${generateSegment(4)}_${generateSegment(4)}`;
|
||||
this.form.vendor_sku = sku;
|
||||
|
||||
adminVendorProductCreateLog.info('Generated SKU:', sku);
|
||||
},
|
||||
|
||||
/**
|
||||
* Create the product
|
||||
*/
|
||||
async createProduct() {
|
||||
if (!this.form.vendor_id) {
|
||||
Utils.showToast('Please select a vendor', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.form.translations.en.title?.trim()) {
|
||||
Utils.showToast('Please enter a product title (English)', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
this.saving = true;
|
||||
|
||||
try {
|
||||
// Build translations object for API (only include non-empty)
|
||||
const translations = {};
|
||||
for (const lang of ['en', 'fr', 'de', 'lu']) {
|
||||
const t = this.form.translations[lang];
|
||||
if (t.title?.trim() || t.description?.trim()) {
|
||||
translations[lang] = {
|
||||
title: t.title?.trim() || null,
|
||||
description: t.description?.trim() || null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Build create payload
|
||||
const payload = {
|
||||
vendor_id: this.form.vendor_id,
|
||||
translations: Object.keys(translations).length > 0 ? translations : null,
|
||||
// Product identifiers
|
||||
brand: this.form.brand?.trim() || null,
|
||||
vendor_sku: this.form.vendor_sku?.trim() || null,
|
||||
gtin: this.form.gtin?.trim() || null,
|
||||
gtin_type: this.form.gtin_type || null,
|
||||
// Pricing
|
||||
price: this.form.price !== null && this.form.price !== ''
|
||||
? parseFloat(this.form.price) : null,
|
||||
sale_price: this.form.sale_price !== null && this.form.sale_price !== ''
|
||||
? parseFloat(this.form.sale_price) : null,
|
||||
currency: this.form.currency || 'EUR',
|
||||
tax_rate_percent: this.form.tax_rate_percent !== null
|
||||
? parseInt(this.form.tax_rate_percent) : 17,
|
||||
availability: this.form.availability || null,
|
||||
// Images
|
||||
primary_image_url: this.form.primary_image_url?.trim() || null,
|
||||
additional_images: this.form.additional_images?.length > 0
|
||||
? this.form.additional_images : null,
|
||||
// Status
|
||||
is_active: this.form.is_active,
|
||||
is_featured: this.form.is_featured,
|
||||
is_digital: this.form.is_digital
|
||||
};
|
||||
|
||||
adminVendorProductCreateLog.info('Creating product with payload:', payload);
|
||||
|
||||
const response = await apiClient.post('/admin/vendor-products', payload);
|
||||
|
||||
adminVendorProductCreateLog.info('Product created:', response.id);
|
||||
|
||||
Utils.showToast('Product created successfully', 'success');
|
||||
|
||||
// Redirect to the new product's detail page
|
||||
setTimeout(() => {
|
||||
window.location.href = `/admin/vendor-products/${response.id}`;
|
||||
}, 1000);
|
||||
} catch (error) {
|
||||
adminVendorProductCreateLog.error('Failed to create product:', error);
|
||||
Utils.showToast(error.message || 'Failed to create product', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
// === Media Picker Overrides ===
|
||||
// These override the mixin methods to use proper form context
|
||||
|
||||
/**
|
||||
* Load media library for the selected vendor
|
||||
*/
|
||||
async loadMediaLibrary() {
|
||||
const vendorId = this.form?.vendor_id;
|
||||
|
||||
if (!vendorId) {
|
||||
adminVendorProductCreateLog.warn('Media picker: No vendor ID selected');
|
||||
return;
|
||||
}
|
||||
|
||||
this.mediaPickerState.loading = true;
|
||||
this.mediaPickerState.skip = 0;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
skip: '0',
|
||||
limit: this.mediaPickerState.limit.toString(),
|
||||
media_type: 'image',
|
||||
});
|
||||
|
||||
if (this.mediaPickerState.search) {
|
||||
params.append('search', this.mediaPickerState.search);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(
|
||||
`/admin/media/vendors/${vendorId}?${params.toString()}`
|
||||
);
|
||||
|
||||
this.mediaPickerState.media = response.media || [];
|
||||
this.mediaPickerState.total = response.total || 0;
|
||||
} catch (error) {
|
||||
adminVendorProductCreateLog.error('Failed to load media library:', error);
|
||||
Utils.showToast('Failed to load media library', 'error');
|
||||
} finally {
|
||||
this.mediaPickerState.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load more media (pagination)
|
||||
*/
|
||||
async loadMoreMedia() {
|
||||
const vendorId = this.form?.vendor_id;
|
||||
if (!vendorId) return;
|
||||
|
||||
this.mediaPickerState.loading = true;
|
||||
this.mediaPickerState.skip += this.mediaPickerState.limit;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
skip: this.mediaPickerState.skip.toString(),
|
||||
limit: this.mediaPickerState.limit.toString(),
|
||||
media_type: 'image',
|
||||
});
|
||||
|
||||
if (this.mediaPickerState.search) {
|
||||
params.append('search', this.mediaPickerState.search);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(
|
||||
`/admin/media/vendors/${vendorId}?${params.toString()}`
|
||||
);
|
||||
|
||||
this.mediaPickerState.media = [
|
||||
...this.mediaPickerState.media,
|
||||
...(response.media || [])
|
||||
];
|
||||
} catch (error) {
|
||||
adminVendorProductCreateLog.error('Failed to load more media:', error);
|
||||
} finally {
|
||||
this.mediaPickerState.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Upload a new media file
|
||||
*/
|
||||
async uploadMediaFile(event) {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
const vendorId = this.form?.vendor_id;
|
||||
|
||||
if (!vendorId) {
|
||||
Utils.showToast('Please select a vendor first', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!file.type.startsWith('image/')) {
|
||||
Utils.showToast('Please select an image file', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
Utils.showToast('Image must be less than 10MB', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
this.mediaPickerState.uploading = true;
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const response = await apiClient.postFormData(
|
||||
`/admin/media/vendors/${vendorId}/upload?folder=products`,
|
||||
formData
|
||||
);
|
||||
|
||||
if (response.success && response.media) {
|
||||
this.mediaPickerState.media.unshift(response.media);
|
||||
this.mediaPickerState.total++;
|
||||
this.toggleMediaSelection(response.media);
|
||||
Utils.showToast('Image uploaded successfully', 'success');
|
||||
}
|
||||
} catch (error) {
|
||||
adminVendorProductCreateLog.error('Failed to upload image:', error);
|
||||
Utils.showToast(error.message || 'Failed to upload image', 'error');
|
||||
} finally {
|
||||
this.mediaPickerState.uploading = false;
|
||||
event.target.value = '';
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Set main image from media picker
|
||||
*/
|
||||
setMainImage(media) {
|
||||
this.form.primary_image_url = media.url;
|
||||
adminVendorProductCreateLog.info('Main image set:', media.url);
|
||||
},
|
||||
|
||||
/**
|
||||
* Add additional images from media picker
|
||||
*/
|
||||
addAdditionalImages(mediaList) {
|
||||
const newUrls = mediaList.map(m => m.url);
|
||||
this.form.additional_images = [
|
||||
...this.form.additional_images,
|
||||
...newUrls
|
||||
];
|
||||
adminVendorProductCreateLog.info('Additional images added:', newUrls);
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove an additional image by index
|
||||
*/
|
||||
removeAdditionalImage(index) {
|
||||
this.form.additional_images.splice(index, 1);
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear the main image
|
||||
*/
|
||||
clearMainImage() {
|
||||
this.form.primary_image_url = '';
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
// static/admin/js/vendor-product-detail.js
|
||||
/**
|
||||
* Admin vendor product detail page logic
|
||||
* View and manage individual vendor catalog products
|
||||
*/
|
||||
|
||||
const adminVendorProductDetailLog = window.LogConfig.loggers.adminVendorProductDetail ||
|
||||
window.LogConfig.createLogger('adminVendorProductDetail', false);
|
||||
|
||||
adminVendorProductDetailLog.info('Loading...');
|
||||
|
||||
function adminVendorProductDetail() {
|
||||
adminVendorProductDetailLog.info('adminVendorProductDetail() called');
|
||||
|
||||
// Extract product ID from URL
|
||||
const pathParts = window.location.pathname.split('/');
|
||||
const productId = parseInt(pathParts[pathParts.length - 1]);
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'vendor-products',
|
||||
|
||||
// Product ID from URL
|
||||
productId: productId,
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
error: '',
|
||||
|
||||
// Product data
|
||||
product: null,
|
||||
|
||||
// Modals
|
||||
showRemoveModal: false,
|
||||
removing: false,
|
||||
|
||||
async init() {
|
||||
adminVendorProductDetailLog.info('Vendor Product Detail init() called, ID:', this.productId);
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._adminVendorProductDetailInitialized) {
|
||||
adminVendorProductDetailLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminVendorProductDetailInitialized = true;
|
||||
|
||||
// Load product data
|
||||
await this.loadProduct();
|
||||
|
||||
adminVendorProductDetailLog.info('Vendor Product Detail initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Load product details
|
||||
*/
|
||||
async loadProduct() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/vendor-products/${this.productId}`);
|
||||
this.product = response;
|
||||
adminVendorProductDetailLog.info('Loaded product:', this.product.id);
|
||||
} catch (error) {
|
||||
adminVendorProductDetailLog.error('Failed to load product:', error);
|
||||
this.error = error.message || 'Failed to load product details';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Open edit modal (placeholder for future implementation)
|
||||
*/
|
||||
openEditModal() {
|
||||
window.dispatchEvent(new CustomEvent('toast', {
|
||||
detail: { message: 'Edit functionality coming soon', type: 'info' }
|
||||
}));
|
||||
},
|
||||
|
||||
/**
|
||||
* Toggle active status
|
||||
*/
|
||||
async toggleActive() {
|
||||
// TODO: Implement PATCH endpoint for status update
|
||||
window.dispatchEvent(new CustomEvent('toast', {
|
||||
detail: {
|
||||
message: 'Status toggle functionality coming soon',
|
||||
type: 'info'
|
||||
}
|
||||
}));
|
||||
},
|
||||
|
||||
/**
|
||||
* Confirm remove
|
||||
*/
|
||||
confirmRemove() {
|
||||
this.showRemoveModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Execute remove
|
||||
*/
|
||||
async executeRemove() {
|
||||
this.removing = true;
|
||||
|
||||
try {
|
||||
await apiClient.delete(`/admin/vendor-products/${this.productId}`);
|
||||
|
||||
adminVendorProductDetailLog.info('Product removed:', this.productId);
|
||||
|
||||
window.dispatchEvent(new CustomEvent('toast', {
|
||||
detail: {
|
||||
message: 'Product removed from catalog successfully',
|
||||
type: 'success'
|
||||
}
|
||||
}));
|
||||
|
||||
// Redirect to vendor products list
|
||||
setTimeout(() => {
|
||||
window.location.href = '/admin/vendor-products';
|
||||
}, 1000);
|
||||
} catch (error) {
|
||||
adminVendorProductDetailLog.error('Failed to remove product:', error);
|
||||
window.dispatchEvent(new CustomEvent('toast', {
|
||||
detail: { message: error.message || 'Failed to remove product', type: 'error' }
|
||||
}));
|
||||
} finally {
|
||||
this.removing = false;
|
||||
this.showRemoveModal = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format price for display
|
||||
*/
|
||||
formatPrice(price, currency = 'EUR') {
|
||||
if (price === null || price === undefined) return '-';
|
||||
const numPrice = typeof price === 'string' ? parseFloat(price) : price;
|
||||
if (isNaN(numPrice)) return price;
|
||||
|
||||
return new Intl.NumberFormat('de-DE', {
|
||||
style: 'currency',
|
||||
currency: currency || 'EUR'
|
||||
}).format(numPrice);
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date for display
|
||||
*/
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return '-';
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('en-GB', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
} catch (e) {
|
||||
return dateString;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,445 +0,0 @@
|
||||
// static/admin/js/vendor-product-edit.js
|
||||
/**
|
||||
* Admin vendor product edit page logic
|
||||
* Edit vendor product information with translations
|
||||
*/
|
||||
|
||||
const adminVendorProductEditLog = window.LogConfig.loggers.adminVendorProductEdit ||
|
||||
window.LogConfig.createLogger('adminVendorProductEdit', false);
|
||||
|
||||
adminVendorProductEditLog.info('Loading...');
|
||||
|
||||
function adminVendorProductEdit() {
|
||||
adminVendorProductEditLog.info('adminVendorProductEdit() called');
|
||||
|
||||
// Extract product ID from URL
|
||||
const pathParts = window.location.pathname.split('/');
|
||||
const productId = parseInt(pathParts[pathParts.length - 2]); // /vendor-products/{id}/edit
|
||||
|
||||
// Default translations structure
|
||||
const defaultTranslations = () => ({
|
||||
en: { title: '', description: '' },
|
||||
fr: { title: '', description: '' },
|
||||
de: { title: '', description: '' },
|
||||
lu: { title: '', description: '' }
|
||||
});
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Include media picker functionality (vendor ID comes from loaded product)
|
||||
...mediaPickerMixin(() => null, false),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'vendor-products',
|
||||
|
||||
// Product ID from URL
|
||||
productId: productId,
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
saving: false,
|
||||
error: '',
|
||||
|
||||
// Product data from API
|
||||
product: null,
|
||||
|
||||
// Active language tab
|
||||
activeLanguage: 'en',
|
||||
|
||||
// Form data
|
||||
form: {
|
||||
// Translations by language
|
||||
translations: defaultTranslations(),
|
||||
// Product identifiers
|
||||
vendor_sku: '',
|
||||
brand: '',
|
||||
gtin: '',
|
||||
gtin_type: 'ean13',
|
||||
// Pricing
|
||||
price: null,
|
||||
sale_price: null,
|
||||
currency: 'EUR',
|
||||
tax_rate_percent: 17,
|
||||
availability: '',
|
||||
// Images
|
||||
primary_image_url: '',
|
||||
additional_images: [],
|
||||
// Product type & status
|
||||
is_digital: false,
|
||||
is_active: true,
|
||||
is_featured: false,
|
||||
// Optional supplier info
|
||||
supplier: '',
|
||||
cost: null
|
||||
},
|
||||
|
||||
async init() {
|
||||
adminVendorProductEditLog.info('Vendor Product Edit init() called, ID:', this.productId);
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._adminVendorProductEditInitialized) {
|
||||
adminVendorProductEditLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminVendorProductEditInitialized = true;
|
||||
|
||||
// Load product data
|
||||
await this.loadProduct();
|
||||
|
||||
adminVendorProductEditLog.info('Vendor Product Edit initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Load product details and populate form
|
||||
*/
|
||||
async loadProduct() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/vendor-products/${this.productId}`);
|
||||
this.product = response;
|
||||
|
||||
adminVendorProductEditLog.info('Loaded product:', response);
|
||||
|
||||
// Populate translations from vendor_translations
|
||||
const translations = defaultTranslations();
|
||||
if (response.vendor_translations) {
|
||||
for (const lang of ['en', 'fr', 'de', 'lu']) {
|
||||
if (response.vendor_translations[lang]) {
|
||||
translations[lang] = {
|
||||
title: response.vendor_translations[lang].title || '',
|
||||
description: response.vendor_translations[lang].description || ''
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Populate form with current values
|
||||
this.form = {
|
||||
translations: translations,
|
||||
// Product identifiers
|
||||
vendor_sku: response.vendor_sku || '',
|
||||
brand: response.brand || '',
|
||||
gtin: response.gtin || '',
|
||||
gtin_type: response.gtin_type || 'ean13',
|
||||
// Pricing (convert cents to euros if stored as cents)
|
||||
price: response.price || null,
|
||||
sale_price: response.sale_price || null,
|
||||
currency: response.currency || 'EUR',
|
||||
tax_rate_percent: response.tax_rate_percent ?? 17,
|
||||
availability: response.availability || '',
|
||||
// Images
|
||||
primary_image_url: response.primary_image_url || '',
|
||||
additional_images: response.additional_images || [],
|
||||
// Product type & status
|
||||
is_digital: response.is_digital ?? false,
|
||||
is_active: response.is_active ?? true,
|
||||
is_featured: response.is_featured ?? false,
|
||||
// Optional supplier info
|
||||
supplier: response.supplier || '',
|
||||
cost: response.cost || null
|
||||
};
|
||||
|
||||
adminVendorProductEditLog.info('Form initialized:', this.form);
|
||||
} catch (error) {
|
||||
adminVendorProductEditLog.error('Failed to load product:', error);
|
||||
this.error = error.message || 'Failed to load product details';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if form is valid (all mandatory fields filled)
|
||||
*/
|
||||
isFormValid() {
|
||||
// English title and description are required
|
||||
if (!this.form.translations.en.title?.trim()) return false;
|
||||
if (!this.form.translations.en.description?.trim()) return false;
|
||||
|
||||
// Product identifiers
|
||||
if (!this.form.vendor_sku?.trim()) return false;
|
||||
if (!this.form.brand?.trim()) return false;
|
||||
if (!this.form.gtin?.trim()) return false;
|
||||
if (!this.form.gtin_type) return false;
|
||||
|
||||
// Pricing
|
||||
if (this.form.price === null || this.form.price === '' || this.form.price < 0) return false;
|
||||
if (!this.form.currency) return false;
|
||||
if (this.form.tax_rate_percent === null || this.form.tax_rate_percent === '') return false;
|
||||
|
||||
// Image
|
||||
if (!this.form.primary_image_url?.trim()) return false;
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Generate a unique vendor SKU
|
||||
* Format: XXXX_XXXX_XXXX (includes vendor_id for uniqueness)
|
||||
*/
|
||||
generateSku() {
|
||||
const vendorId = this.product?.vendor_id || 0;
|
||||
|
||||
// Generate random alphanumeric segments
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
||||
const generateSegment = (length) => {
|
||||
let result = '';
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// First segment includes vendor ID (padded)
|
||||
const vendorSegment = vendorId.toString().padStart(4, '0').slice(-4);
|
||||
|
||||
// Generate SKU: VID + random + random
|
||||
const sku = `${vendorSegment}_${generateSegment(4)}_${generateSegment(4)}`;
|
||||
this.form.vendor_sku = sku;
|
||||
|
||||
adminVendorProductEditLog.info('Generated SKU:', sku);
|
||||
},
|
||||
|
||||
/**
|
||||
* Save product changes
|
||||
*/
|
||||
async saveProduct() {
|
||||
if (!this.isFormValid()) {
|
||||
Utils.showToast('Please fill in all required fields', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
this.saving = true;
|
||||
|
||||
try {
|
||||
// Build translations object for API
|
||||
const translations = {};
|
||||
for (const lang of ['en', 'fr', 'de', 'lu']) {
|
||||
const t = this.form.translations[lang];
|
||||
// Only include if there's actual content
|
||||
if (t.title?.trim() || t.description?.trim()) {
|
||||
translations[lang] = {
|
||||
title: t.title?.trim() || null,
|
||||
description: t.description?.trim() || null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Build update payload
|
||||
const payload = {
|
||||
translations: Object.keys(translations).length > 0 ? translations : null,
|
||||
// Product identifiers
|
||||
vendor_sku: this.form.vendor_sku?.trim() || null,
|
||||
brand: this.form.brand?.trim() || null,
|
||||
gtin: this.form.gtin?.trim() || null,
|
||||
gtin_type: this.form.gtin_type || null,
|
||||
// Pricing
|
||||
price: this.form.price !== null && this.form.price !== ''
|
||||
? parseFloat(this.form.price) : null,
|
||||
sale_price: this.form.sale_price !== null && this.form.sale_price !== ''
|
||||
? parseFloat(this.form.sale_price) : null,
|
||||
currency: this.form.currency || null,
|
||||
tax_rate_percent: this.form.tax_rate_percent !== null && this.form.tax_rate_percent !== ''
|
||||
? parseInt(this.form.tax_rate_percent) : null,
|
||||
availability: this.form.availability || null,
|
||||
// Images
|
||||
primary_image_url: this.form.primary_image_url?.trim() || null,
|
||||
additional_images: this.form.additional_images?.length > 0
|
||||
? this.form.additional_images : null,
|
||||
// Status
|
||||
is_digital: this.form.is_digital,
|
||||
is_active: this.form.is_active,
|
||||
is_featured: this.form.is_featured,
|
||||
// Optional supplier info
|
||||
supplier: this.form.supplier?.trim() || null,
|
||||
cost: this.form.cost !== null && this.form.cost !== ''
|
||||
? parseFloat(this.form.cost) : null
|
||||
};
|
||||
|
||||
adminVendorProductEditLog.info('Saving payload:', payload);
|
||||
|
||||
await apiClient.patch(`/admin/vendor-products/${this.productId}`, payload);
|
||||
|
||||
adminVendorProductEditLog.info('Product saved:', this.productId);
|
||||
|
||||
Utils.showToast('Product updated successfully', 'success');
|
||||
|
||||
// Redirect to detail page
|
||||
setTimeout(() => {
|
||||
window.location.href = `/admin/vendor-products/${this.productId}`;
|
||||
}, 1000);
|
||||
} catch (error) {
|
||||
adminVendorProductEditLog.error('Failed to save product:', error);
|
||||
Utils.showToast(error.message || 'Failed to save product', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
// === Media Picker Overrides ===
|
||||
// These override the mixin methods to use proper form/product context
|
||||
|
||||
/**
|
||||
* Load media library for the product's vendor
|
||||
*/
|
||||
async loadMediaLibrary() {
|
||||
const vendorId = this.product?.vendor_id;
|
||||
|
||||
if (!vendorId) {
|
||||
adminVendorProductEditLog.warn('Media picker: No vendor ID available');
|
||||
return;
|
||||
}
|
||||
|
||||
this.mediaPickerState.loading = true;
|
||||
this.mediaPickerState.skip = 0;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
skip: '0',
|
||||
limit: this.mediaPickerState.limit.toString(),
|
||||
media_type: 'image',
|
||||
});
|
||||
|
||||
if (this.mediaPickerState.search) {
|
||||
params.append('search', this.mediaPickerState.search);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(
|
||||
`/admin/media/vendors/${vendorId}?${params.toString()}`
|
||||
);
|
||||
|
||||
this.mediaPickerState.media = response.media || [];
|
||||
this.mediaPickerState.total = response.total || 0;
|
||||
} catch (error) {
|
||||
adminVendorProductEditLog.error('Failed to load media library:', error);
|
||||
Utils.showToast('Failed to load media library', 'error');
|
||||
} finally {
|
||||
this.mediaPickerState.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load more media (pagination)
|
||||
*/
|
||||
async loadMoreMedia() {
|
||||
const vendorId = this.product?.vendor_id;
|
||||
if (!vendorId) return;
|
||||
|
||||
this.mediaPickerState.loading = true;
|
||||
this.mediaPickerState.skip += this.mediaPickerState.limit;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
skip: this.mediaPickerState.skip.toString(),
|
||||
limit: this.mediaPickerState.limit.toString(),
|
||||
media_type: 'image',
|
||||
});
|
||||
|
||||
if (this.mediaPickerState.search) {
|
||||
params.append('search', this.mediaPickerState.search);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(
|
||||
`/admin/media/vendors/${vendorId}?${params.toString()}`
|
||||
);
|
||||
|
||||
this.mediaPickerState.media = [
|
||||
...this.mediaPickerState.media,
|
||||
...(response.media || [])
|
||||
];
|
||||
} catch (error) {
|
||||
adminVendorProductEditLog.error('Failed to load more media:', error);
|
||||
} finally {
|
||||
this.mediaPickerState.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Upload a new media file
|
||||
*/
|
||||
async uploadMediaFile(event) {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
const vendorId = this.product?.vendor_id;
|
||||
|
||||
if (!vendorId) {
|
||||
Utils.showToast('No vendor associated with this product', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!file.type.startsWith('image/')) {
|
||||
Utils.showToast('Please select an image file', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
Utils.showToast('Image must be less than 10MB', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
this.mediaPickerState.uploading = true;
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const response = await apiClient.postFormData(
|
||||
`/admin/media/vendors/${vendorId}/upload?folder=products`,
|
||||
formData
|
||||
);
|
||||
|
||||
if (response.success && response.media) {
|
||||
this.mediaPickerState.media.unshift(response.media);
|
||||
this.mediaPickerState.total++;
|
||||
this.toggleMediaSelection(response.media);
|
||||
Utils.showToast('Image uploaded successfully', 'success');
|
||||
}
|
||||
} catch (error) {
|
||||
adminVendorProductEditLog.error('Failed to upload image:', error);
|
||||
Utils.showToast(error.message || 'Failed to upload image', 'error');
|
||||
} finally {
|
||||
this.mediaPickerState.uploading = false;
|
||||
event.target.value = '';
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Set main image from media picker
|
||||
*/
|
||||
setMainImage(media) {
|
||||
this.form.primary_image_url = media.url;
|
||||
adminVendorProductEditLog.info('Main image set:', media.url);
|
||||
},
|
||||
|
||||
/**
|
||||
* Add additional images from media picker
|
||||
*/
|
||||
addAdditionalImages(mediaList) {
|
||||
const newUrls = mediaList.map(m => m.url);
|
||||
this.form.additional_images = [
|
||||
...this.form.additional_images,
|
||||
...newUrls
|
||||
];
|
||||
adminVendorProductEditLog.info('Additional images added:', newUrls);
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove an additional image by index
|
||||
*/
|
||||
removeAdditionalImage(index) {
|
||||
this.form.additional_images.splice(index, 1);
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear the main image
|
||||
*/
|
||||
clearMainImage() {
|
||||
this.form.primary_image_url = '';
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,441 +0,0 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/vendor-products.js
|
||||
/**
|
||||
* Admin vendor products page logic
|
||||
* Browse vendor-specific product catalogs with override capability
|
||||
*/
|
||||
|
||||
const adminVendorProductsLog = window.LogConfig.loggers.adminVendorProducts ||
|
||||
window.LogConfig.createLogger('adminVendorProducts', false);
|
||||
|
||||
adminVendorProductsLog.info('Loading...');
|
||||
|
||||
function adminVendorProducts() {
|
||||
adminVendorProductsLog.info('adminVendorProducts() called');
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'vendor-products',
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
error: '',
|
||||
|
||||
// Products data
|
||||
products: [],
|
||||
stats: {
|
||||
total: 0,
|
||||
active: 0,
|
||||
inactive: 0,
|
||||
featured: 0,
|
||||
digital: 0,
|
||||
physical: 0,
|
||||
by_vendor: {}
|
||||
},
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
search: '',
|
||||
vendor_id: '',
|
||||
is_active: '',
|
||||
is_featured: ''
|
||||
},
|
||||
|
||||
// Selected vendor (for prominent display and filtering)
|
||||
selectedVendor: null,
|
||||
|
||||
// Tom Select instance
|
||||
vendorSelectInstance: null,
|
||||
|
||||
// Pagination
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Product detail modal state
|
||||
showProductModal: false,
|
||||
selectedProduct: null,
|
||||
|
||||
// Remove confirmation modal state
|
||||
showRemoveModal: false,
|
||||
productToRemove: null,
|
||||
removing: false,
|
||||
|
||||
// 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() {
|
||||
adminVendorProductsLog.info('Vendor Products init() called');
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._adminVendorProductsInitialized) {
|
||||
adminVendorProductsLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminVendorProductsInitialized = true;
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
// Initialize Tom Select for vendor filter
|
||||
this.initVendorSelect();
|
||||
|
||||
// Check localStorage for saved vendor
|
||||
const savedVendorId = localStorage.getItem('vendor_products_selected_vendor_id');
|
||||
if (savedVendorId) {
|
||||
adminVendorProductsLog.info('Restoring saved vendor:', savedVendorId);
|
||||
// Restore vendor after a short delay to ensure TomSelect is ready
|
||||
setTimeout(async () => {
|
||||
await this.restoreSavedVendor(parseInt(savedVendorId));
|
||||
}, 200);
|
||||
// Load stats but not products (restoreSavedVendor will do that)
|
||||
await this.loadStats();
|
||||
} else {
|
||||
// No saved vendor - load all data including unfiltered products
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadProducts()
|
||||
]);
|
||||
}
|
||||
|
||||
adminVendorProductsLog.info('Vendor Products initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Restore saved vendor from localStorage
|
||||
*/
|
||||
async restoreSavedVendor(vendorId) {
|
||||
try {
|
||||
const vendor = await apiClient.get(`/admin/vendors/${vendorId}`);
|
||||
if (this.vendorSelectInstance && vendor) {
|
||||
// Add the vendor as an option and select it
|
||||
this.vendorSelectInstance.addOption({
|
||||
id: vendor.id,
|
||||
name: vendor.name,
|
||||
vendor_code: vendor.vendor_code
|
||||
});
|
||||
this.vendorSelectInstance.setValue(vendor.id, true);
|
||||
|
||||
// Set the filter state
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_id = vendor.id;
|
||||
|
||||
adminVendorProductsLog.info('Restored vendor:', vendor.name);
|
||||
|
||||
// Load products with the vendor filter applied
|
||||
await this.loadProducts();
|
||||
}
|
||||
} catch (error) {
|
||||
adminVendorProductsLog.warn('Failed to restore saved vendor, clearing localStorage:', error);
|
||||
localStorage.removeItem('vendor_products_selected_vendor_id');
|
||||
// Load unfiltered products as fallback
|
||||
await this.loadProducts();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize Tom Select for vendor autocomplete
|
||||
*/
|
||||
initVendorSelect() {
|
||||
const selectEl = this.$refs.vendorSelect;
|
||||
if (!selectEl) {
|
||||
adminVendorProductsLog.warn('Vendor select element not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for Tom Select to be available
|
||||
if (typeof TomSelect === 'undefined') {
|
||||
adminVendorProductsLog.warn('TomSelect not loaded, retrying in 100ms');
|
||||
setTimeout(() => this.initVendorSelect(), 100);
|
||||
return;
|
||||
}
|
||||
|
||||
this.vendorSelectInstance = new TomSelect(selectEl, {
|
||||
valueField: 'id',
|
||||
labelField: 'name',
|
||||
searchField: ['name', 'vendor_code'],
|
||||
placeholder: 'Filter by vendor...',
|
||||
allowEmptyOption: true,
|
||||
load: async (query, callback) => {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors', {
|
||||
search: query,
|
||||
limit: 50
|
||||
});
|
||||
callback(response.vendors || []);
|
||||
} catch (error) {
|
||||
adminVendorProductsLog.error('Failed to search vendors:', error);
|
||||
callback([]);
|
||||
}
|
||||
},
|
||||
render: {
|
||||
option: (data, escape) => {
|
||||
return `<div class="flex items-center justify-between py-1">
|
||||
<span>${escape(data.name)}</span>
|
||||
<span class="text-xs text-gray-400 font-mono">${escape(data.vendor_code || '')}</span>
|
||||
</div>`;
|
||||
},
|
||||
item: (data, escape) => {
|
||||
return `<div>${escape(data.name)}</div>`;
|
||||
}
|
||||
},
|
||||
onChange: (value) => {
|
||||
if (value) {
|
||||
const vendor = this.vendorSelectInstance.options[value];
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_id = value;
|
||||
// Save to localStorage
|
||||
localStorage.setItem('vendor_products_selected_vendor_id', value.toString());
|
||||
} else {
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_id = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('vendor_products_selected_vendor_id');
|
||||
}
|
||||
this.pagination.page = 1;
|
||||
this.loadProducts();
|
||||
this.loadStats();
|
||||
}
|
||||
});
|
||||
|
||||
adminVendorProductsLog.info('Vendor select initialized');
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear vendor filter
|
||||
*/
|
||||
clearVendorFilter() {
|
||||
if (this.vendorSelectInstance) {
|
||||
this.vendorSelectInstance.clear();
|
||||
}
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_id = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('vendor_products_selected_vendor_id');
|
||||
this.pagination.page = 1;
|
||||
this.loadProducts();
|
||||
this.loadStats();
|
||||
},
|
||||
|
||||
/**
|
||||
* Load product statistics
|
||||
*/
|
||||
async loadStats() {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (this.filters.vendor_id) {
|
||||
params.append('vendor_id', this.filters.vendor_id);
|
||||
}
|
||||
const url = params.toString() ? `/admin/vendor-products/stats?${params}` : '/admin/vendor-products/stats';
|
||||
const response = await apiClient.get(url);
|
||||
this.stats = response;
|
||||
adminVendorProductsLog.info('Loaded stats:', this.stats);
|
||||
} catch (error) {
|
||||
adminVendorProductsLog.error('Failed to load stats:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 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.vendor_id) {
|
||||
params.append('vendor_id', this.filters.vendor_id);
|
||||
}
|
||||
if (this.filters.is_active !== '') {
|
||||
params.append('is_active', this.filters.is_active);
|
||||
}
|
||||
if (this.filters.is_featured !== '') {
|
||||
params.append('is_featured', this.filters.is_featured);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(`/admin/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);
|
||||
|
||||
adminVendorProductsLog.info('Loaded products:', this.products.length, 'of', this.pagination.total);
|
||||
} catch (error) {
|
||||
adminVendorProductsLog.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);
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh products list
|
||||
*/
|
||||
async refresh() {
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadVendors(),
|
||||
this.loadProducts()
|
||||
]);
|
||||
},
|
||||
|
||||
/**
|
||||
* View product details - navigate to detail page
|
||||
*/
|
||||
viewProduct(productId) {
|
||||
adminVendorProductsLog.info('Navigating to product detail:', productId);
|
||||
window.location.href = `/admin/vendor-products/${productId}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Show remove confirmation modal
|
||||
*/
|
||||
confirmRemove(product) {
|
||||
this.productToRemove = product;
|
||||
this.showRemoveModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Execute product removal from catalog
|
||||
*/
|
||||
async executeRemove() {
|
||||
if (!this.productToRemove) return;
|
||||
|
||||
this.removing = true;
|
||||
try {
|
||||
await apiClient.delete(`/admin/vendor-products/${this.productToRemove.id}`);
|
||||
|
||||
adminVendorProductsLog.info('Removed product:', this.productToRemove.id);
|
||||
|
||||
// Close modal and refresh
|
||||
this.showRemoveModal = false;
|
||||
this.productToRemove = null;
|
||||
|
||||
// Show success notification
|
||||
Utils.showToast('Product removed from vendor catalog.', 'success');
|
||||
|
||||
// Refresh the list
|
||||
await this.refresh();
|
||||
} catch (error) {
|
||||
adminVendorProductsLog.error('Failed to remove product:', error);
|
||||
this.error = error.message || 'Failed to remove product';
|
||||
} finally {
|
||||
this.removing = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format price for display
|
||||
*/
|
||||
formatPrice(price, currency = 'EUR') {
|
||||
if (price === null || price === undefined) return '-';
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: currency || 'EUR'
|
||||
}).format(price);
|
||||
},
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
// static/shared/js/feature-store.js
|
||||
/**
|
||||
* Feature Store for Alpine.js
|
||||
*
|
||||
* Provides feature availability checking for tier-based access control.
|
||||
* Loads features from the API on init and caches them for the session.
|
||||
*
|
||||
* Usage in templates:
|
||||
*
|
||||
* 1. Check if feature is available:
|
||||
* <div x-show="$store.features.has('analytics_dashboard')">
|
||||
* Analytics content here
|
||||
* </div>
|
||||
*
|
||||
* 2. Show upgrade prompt if not available:
|
||||
* <div x-show="!$store.features.has('analytics_dashboard')">
|
||||
* <p>Upgrade to access Analytics</p>
|
||||
* </div>
|
||||
*
|
||||
* 3. Conditionally render with x-if:
|
||||
* <template x-if="$store.features.has('api_access')">
|
||||
* <a href="/settings/api">API Settings</a>
|
||||
* </template>
|
||||
*
|
||||
* 4. Use feature data for upgrade prompts:
|
||||
* <p x-text="$store.features.getUpgradeTier('analytics_dashboard')"></p>
|
||||
*
|
||||
* 5. Get current tier info:
|
||||
* <span x-text="$store.features.tierName"></span>
|
||||
*/
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// Use centralized logger if available
|
||||
const log = window.LogConfig?.log || console;
|
||||
|
||||
/**
|
||||
* Feature Store
|
||||
*/
|
||||
const featureStore = {
|
||||
// State
|
||||
features: [], // Array of feature codes available to vendor
|
||||
featuresMap: {}, // Full feature info keyed by code
|
||||
tierCode: null, // Current tier code
|
||||
tierName: null, // Current tier name
|
||||
loading: true, // Loading state
|
||||
loaded: false, // Whether features have been loaded
|
||||
error: null, // Error message if load failed
|
||||
|
||||
/**
|
||||
* Initialize the feature store
|
||||
* Called automatically when Alpine starts
|
||||
*/
|
||||
async init() {
|
||||
// Guard against multiple initialization
|
||||
if (window._featureStoreInitialized) return;
|
||||
window._featureStoreInitialized = true;
|
||||
|
||||
try {
|
||||
log.debug('[FeatureStore] Initializing...');
|
||||
await this.loadFeatures();
|
||||
} catch (error) {
|
||||
log.error('[FeatureStore] Failed to initialize:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load features from API
|
||||
*/
|
||||
async loadFeatures() {
|
||||
// Don't reload if already loaded
|
||||
if (this.loaded) {
|
||||
log.debug('[FeatureStore] Already loaded, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get vendor code from URL
|
||||
const vendorCode = this.getVendorCode();
|
||||
if (!vendorCode) {
|
||||
log.warn('[FeatureStore] No vendor code found in URL');
|
||||
this.loading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
// Fetch available features (lightweight endpoint)
|
||||
const response = await apiClient.get('/vendor/features/available');
|
||||
|
||||
this.features = response.features || [];
|
||||
this.tierCode = response.tier_code;
|
||||
this.tierName = response.tier_name;
|
||||
this.loaded = true;
|
||||
|
||||
log.debug(`[FeatureStore] Loaded ${this.features.length} features for ${this.tierName} tier`);
|
||||
|
||||
} catch (error) {
|
||||
log.error('[FeatureStore] Failed to load features:', error);
|
||||
this.error = error.message || 'Failed to load features';
|
||||
// Set empty array so checks don't fail
|
||||
this.features = [];
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load full feature details (with metadata)
|
||||
* Use this when you need upgrade info
|
||||
*/
|
||||
async loadFullFeatures() {
|
||||
const vendorCode = this.getVendorCode();
|
||||
if (!vendorCode) return;
|
||||
|
||||
try {
|
||||
const response = await apiClient.get('/vendor/features');
|
||||
|
||||
// Build map for quick lookup
|
||||
this.featuresMap = {};
|
||||
for (const feature of response.features) {
|
||||
this.featuresMap[feature.code] = feature;
|
||||
}
|
||||
|
||||
log.debug(`[FeatureStore] Loaded full details for ${response.features.length} features`);
|
||||
|
||||
} catch (error) {
|
||||
log.error('[FeatureStore] Failed to load full features:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if vendor has access to a feature
|
||||
* @param {string} featureCode - The feature code to check
|
||||
* @returns {boolean} - Whether the feature is available
|
||||
*/
|
||||
has(featureCode) {
|
||||
return this.features.includes(featureCode);
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if vendor has access to ANY of the given features
|
||||
* @param {...string} featureCodes - Feature codes to check
|
||||
* @returns {boolean} - Whether any feature is available
|
||||
*/
|
||||
hasAny(...featureCodes) {
|
||||
return featureCodes.some(code => this.has(code));
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if vendor has access to ALL of the given features
|
||||
* @param {...string} featureCodes - Feature codes to check
|
||||
* @returns {boolean} - Whether all features are available
|
||||
*/
|
||||
hasAll(...featureCodes) {
|
||||
return featureCodes.every(code => this.has(code));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get feature info (requires loadFullFeatures first)
|
||||
* @param {string} featureCode - The feature code
|
||||
* @returns {object|null} - Feature info or null
|
||||
*/
|
||||
getFeature(featureCode) {
|
||||
return this.featuresMap[featureCode] || null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the tier name required for a feature
|
||||
* @param {string} featureCode - The feature code
|
||||
* @returns {string|null} - Tier name or null
|
||||
*/
|
||||
getUpgradeTier(featureCode) {
|
||||
const feature = this.getFeature(featureCode);
|
||||
return feature?.minimum_tier_name || null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get vendor code from URL
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getVendorCode() {
|
||||
const path = window.location.pathname;
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
if (segments[0] === 'vendor' && segments[1]) {
|
||||
return segments[1];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Reload features (e.g., after tier change)
|
||||
*/
|
||||
async reload() {
|
||||
try {
|
||||
this.loaded = false;
|
||||
this.features = [];
|
||||
this.featuresMap = {};
|
||||
await this.loadFeatures();
|
||||
} catch (error) {
|
||||
log.error('[FeatureStore] Failed to reload:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Register Alpine store when Alpine is available
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.store('features', featureStore);
|
||||
log.debug('[FeatureStore] Registered as Alpine store');
|
||||
});
|
||||
|
||||
// Also expose globally for non-Alpine usage
|
||||
window.FeatureStore = featureStore;
|
||||
|
||||
})();
|
||||
@@ -1,365 +0,0 @@
|
||||
// static/shared/js/upgrade-prompts.js
|
||||
/**
|
||||
* Upgrade Prompts System
|
||||
*
|
||||
* Provides contextual upgrade prompts based on:
|
||||
* - Usage limits approaching/reached
|
||||
* - Locked features
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* 1. Initialize the store (auto-loads usage on init):
|
||||
* <div x-data x-init="$store.upgrade.loadUsage()">
|
||||
*
|
||||
* 2. Show limit warning banner:
|
||||
* <template x-if="$store.upgrade.shouldShowLimitWarning('orders')">
|
||||
* <div x-html="$store.upgrade.getLimitWarningHTML('orders')"></div>
|
||||
* </template>
|
||||
*
|
||||
* 3. Check before action:
|
||||
* <button @click="$store.upgrade.checkLimitAndProceed('products', () => createProduct())">
|
||||
* Add Product
|
||||
* </button>
|
||||
*
|
||||
* 4. Show upgrade CTA on dashboard:
|
||||
* <template x-if="$store.upgrade.hasUpgradeRecommendation">
|
||||
* <div x-html="$store.upgrade.getUpgradeCardHTML()"></div>
|
||||
* </template>
|
||||
*/
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const log = window.LogConfig?.log || console;
|
||||
|
||||
/**
|
||||
* Upgrade Prompts Store
|
||||
*/
|
||||
const upgradeStore = {
|
||||
// State
|
||||
usage: null,
|
||||
loading: false,
|
||||
loaded: false,
|
||||
error: null,
|
||||
|
||||
// Computed-like getters
|
||||
get hasLimitsApproaching() {
|
||||
return this.usage?.has_limits_approaching || false;
|
||||
},
|
||||
|
||||
get hasLimitsReached() {
|
||||
return this.usage?.has_limits_reached || false;
|
||||
},
|
||||
|
||||
get hasUpgradeRecommendation() {
|
||||
return this.usage?.upgrade_available && (this.hasLimitsApproaching || this.hasLimitsReached);
|
||||
},
|
||||
|
||||
get upgradeReasons() {
|
||||
return this.usage?.upgrade_reasons || [];
|
||||
},
|
||||
|
||||
get currentTier() {
|
||||
return this.usage?.tier || null;
|
||||
},
|
||||
|
||||
get nextTier() {
|
||||
return this.usage?.upgrade_tier || null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Load usage data from API
|
||||
*/
|
||||
async loadUsage() {
|
||||
if (this.loaded || this.loading) return;
|
||||
|
||||
try {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
const response = await apiClient.get('/vendor/usage');
|
||||
this.usage = response;
|
||||
this.loaded = true;
|
||||
|
||||
log.debug('[UpgradePrompts] Loaded usage data', this.usage);
|
||||
|
||||
} catch (error) {
|
||||
log.error('[UpgradePrompts] Failed to load usage:', error);
|
||||
this.error = error.message;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get usage metric by name
|
||||
*/
|
||||
getMetric(name) {
|
||||
if (!this.usage?.usage) return null;
|
||||
return this.usage.usage.find(m => m.name === name);
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if should show limit warning for a metric
|
||||
*/
|
||||
shouldShowLimitWarning(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
return metric && (metric.is_approaching_limit || metric.is_at_limit);
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if at limit for a metric
|
||||
*/
|
||||
isAtLimit(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
return metric?.is_at_limit || false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get percentage used for a metric
|
||||
*/
|
||||
getPercentage(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
return metric?.percentage || 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get formatted usage string (e.g., "85/100")
|
||||
*/
|
||||
getUsageString(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
if (!metric) return '';
|
||||
if (metric.is_unlimited) return `${metric.current} (unlimited)`;
|
||||
return `${metric.current}/${metric.limit}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get vendor code from URL
|
||||
*/
|
||||
getVendorCode() {
|
||||
const path = window.location.pathname;
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
if (segments[0] === 'vendor' && segments[1]) {
|
||||
return segments[1];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get billing URL
|
||||
*/
|
||||
getBillingUrl() {
|
||||
const vendorCode = this.getVendorCode();
|
||||
return vendorCode ? `/vendor/${vendorCode}/billing` : '#';
|
||||
},
|
||||
|
||||
/**
|
||||
* Check limit before action, show modal if at limit
|
||||
*/
|
||||
async checkLimitAndProceed(limitType, onSuccess) {
|
||||
try {
|
||||
const response = await apiClient.get(`/vendor/usage/check/${limitType}`);
|
||||
|
||||
if (response.can_proceed) {
|
||||
if (typeof onSuccess === 'function') {
|
||||
onSuccess();
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
// Show upgrade modal
|
||||
this.showLimitReachedModal(limitType, response);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
log.error('[UpgradePrompts] Failed to check limit:', error);
|
||||
// Proceed anyway on error (fail open)
|
||||
if (typeof onSuccess === 'function') {
|
||||
onSuccess();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Show limit reached modal
|
||||
*/
|
||||
showLimitReachedModal(limitType, response) {
|
||||
const limitNames = {
|
||||
'orders': 'monthly orders',
|
||||
'products': 'products',
|
||||
'team_members': 'team members'
|
||||
};
|
||||
|
||||
const limitName = limitNames[limitType] || limitType;
|
||||
const message = response.message || `You've reached your ${limitName} limit.`;
|
||||
|
||||
// Use browser confirm for simplicity - could be replaced with custom modal
|
||||
const shouldUpgrade = confirm(
|
||||
`${message}\n\n` +
|
||||
`Current: ${response.current}/${response.limit}\n\n` +
|
||||
(response.upgrade_tier_name
|
||||
? `Upgrade to ${response.upgrade_tier_name} to get more ${limitName}.\n\nGo to billing page?`
|
||||
: 'Contact support for more capacity.')
|
||||
);
|
||||
|
||||
if (shouldUpgrade && response.upgrade_tier_code) {
|
||||
window.location.href = this.getBillingUrl();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get limit warning banner HTML
|
||||
*/
|
||||
getLimitWarningHTML(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
if (!metric) return '';
|
||||
|
||||
const names = {
|
||||
'orders': 'monthly orders',
|
||||
'products': 'products',
|
||||
'team_members': 'team members'
|
||||
};
|
||||
const name = names[metricName] || metricName;
|
||||
|
||||
if (metric.is_at_limit) {
|
||||
return `
|
||||
<div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-4">
|
||||
<div class="flex items-center">
|
||||
<svg class="w-5 h-5 text-red-500 mr-3" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
<div class="flex-1">
|
||||
<p class="text-sm font-medium text-red-800 dark:text-red-200">
|
||||
You've reached your ${name} limit (${metric.current}/${metric.limit})
|
||||
</p>
|
||||
</div>
|
||||
<a href="${this.getBillingUrl()}"
|
||||
class="ml-4 px-3 py-1 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded">
|
||||
Upgrade
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (metric.is_approaching_limit) {
|
||||
return `
|
||||
<div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-4">
|
||||
<div class="flex items-center">
|
||||
<svg class="w-5 h-5 text-yellow-500 mr-3" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
<div class="flex-1">
|
||||
<p class="text-sm font-medium text-yellow-800 dark:text-yellow-200">
|
||||
You're approaching your ${name} limit (${metric.current}/${metric.limit} - ${Math.round(metric.percentage)}%)
|
||||
</p>
|
||||
</div>
|
||||
<a href="${this.getBillingUrl()}"
|
||||
class="ml-4 px-3 py-1 text-sm font-medium text-yellow-800 bg-yellow-200 hover:bg-yellow-300 dark:bg-yellow-800 dark:text-yellow-200 dark:hover:bg-yellow-700 rounded">
|
||||
Upgrade
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return '';
|
||||
},
|
||||
|
||||
/**
|
||||
* Get upgrade card HTML for dashboard
|
||||
*/
|
||||
getUpgradeCardHTML() {
|
||||
if (!this.usage?.upgrade_tier) return '';
|
||||
|
||||
const tier = this.usage.upgrade_tier;
|
||||
const reasons = this.usage.upgrade_reasons || [];
|
||||
|
||||
return `
|
||||
<div class="bg-gradient-to-r from-purple-500 to-indigo-600 rounded-lg p-6 text-white">
|
||||
<div class="flex items-start justify-between">
|
||||
<div>
|
||||
<h3 class="text-lg font-semibold mb-2">Upgrade to ${tier.name}</h3>
|
||||
${reasons.length > 0 ? `
|
||||
<ul class="text-sm opacity-90 mb-4 space-y-1">
|
||||
${reasons.map(r => `<li>• ${r}</li>`).join('')}
|
||||
</ul>
|
||||
` : ''}
|
||||
${tier.benefits.length > 0 ? `
|
||||
<p class="text-sm opacity-80 mb-2">Get access to:</p>
|
||||
<ul class="text-sm space-y-1 mb-4">
|
||||
${tier.benefits.slice(0, 4).map(b => `
|
||||
<li class="flex items-center">
|
||||
<svg class="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
${b}
|
||||
</li>
|
||||
`).join('')}
|
||||
</ul>
|
||||
` : ''}
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<p class="text-2xl font-bold">€${(tier.price_monthly_cents / 100).toFixed(0)}</p>
|
||||
<p class="text-sm opacity-80">/month</p>
|
||||
</div>
|
||||
</div>
|
||||
<a href="${this.getBillingUrl()}"
|
||||
class="mt-4 inline-flex items-center px-4 py-2 bg-white text-purple-600 font-medium rounded-lg hover:bg-gray-100 transition-colors">
|
||||
Upgrade Now
|
||||
<svg class="w-4 h-4 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6"/>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get compact usage bar HTML
|
||||
*/
|
||||
getUsageBarHTML(metricName) {
|
||||
const metric = this.getMetric(metricName);
|
||||
if (!metric || metric.is_unlimited) return '';
|
||||
|
||||
const percentage = Math.min(metric.percentage, 100);
|
||||
const colorClass = metric.is_at_limit
|
||||
? 'bg-red-500'
|
||||
: metric.is_approaching_limit
|
||||
? 'bg-yellow-500'
|
||||
: 'bg-green-500';
|
||||
|
||||
return `
|
||||
<div class="w-full">
|
||||
<div class="flex justify-between text-xs text-gray-500 dark:text-gray-400 mb-1">
|
||||
<span>${metric.current} / ${metric.limit}</span>
|
||||
<span>${Math.round(percentage)}%</span>
|
||||
</div>
|
||||
<div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
|
||||
<div class="${colorClass} h-2 rounded-full transition-all" style="width: ${percentage}%"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Reload usage data
|
||||
*/
|
||||
async reload() {
|
||||
try {
|
||||
this.loaded = false;
|
||||
await this.loadUsage();
|
||||
} catch (error) {
|
||||
log.error('[UpgradePrompts] Failed to reload:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Register Alpine store when Alpine is available
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.store('upgrade', upgradeStore);
|
||||
log.debug('[UpgradePrompts] Registered as Alpine store');
|
||||
});
|
||||
|
||||
// Also expose globally
|
||||
window.UpgradePrompts = upgradeStore;
|
||||
|
||||
})();
|
||||
211
static/vendor/js/billing.js
vendored
211
static/vendor/js/billing.js
vendored
@@ -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);
|
||||
}
|
||||
};
|
||||
}
|
||||
318
static/vendor/js/customers.js
vendored
318
static/vendor/js/customers.js
vendored
@@ -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();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
264
static/vendor/js/email-templates.js
vendored
264
static/vendor/js/email-templates.js
vendored
@@ -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;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
514
static/vendor/js/inventory.js
vendored
514
static/vendor/js/inventory.js
vendored
@@ -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');
|
||||
}
|
||||
};
|
||||
}
|
||||
404
static/vendor/js/invoices.js
vendored
404
static/vendor/js/invoices.js
vendored
@@ -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);
|
||||
}
|
||||
};
|
||||
}
|
||||
486
static/vendor/js/letzshop.js
vendored
486
static/vendor/js/letzshop.js
vendored
@@ -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);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
343
static/vendor/js/marketplace.js
vendored
343
static/vendor/js/marketplace.js
vendored
@@ -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();
|
||||
}
|
||||
});
|
||||
408
static/vendor/js/messages.js
vendored
408
static/vendor/js/messages.js
vendored
@@ -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;
|
||||
281
static/vendor/js/notifications.js
vendored
281
static/vendor/js/notifications.js
vendored
@@ -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();
|
||||
}
|
||||
};
|
||||
}
|
||||
649
static/vendor/js/onboarding.js
vendored
649
static/vendor/js/onboarding.js
vendored
@@ -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);
|
||||
},
|
||||
};
|
||||
}
|
||||
381
static/vendor/js/order-detail.js
vendored
381
static/vendor/js/order-detail.js
vendored
@@ -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;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
482
static/vendor/js/orders.js
vendored
482
static/vendor/js/orders.js
vendored
@@ -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');
|
||||
}
|
||||
};
|
||||
}
|
||||
114
static/vendor/js/product-create.js
vendored
114
static/vendor/js/product-create.js
vendored
@@ -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');
|
||||
548
static/vendor/js/products.js
vendored
548
static/vendor/js/products.js
vendored
@@ -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;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user