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();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user