Files
orion/static/admin/js/vendors.js

260 lines
8.6 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// static/admin/js/vendors.js
// Log levels: 0 = None, 1 = Error, 2 = Warning, 3 = Info, 4 = Debug
const VENDORS_LOG_LEVEL = 3;
const vendorsLog = {
error: (...args) => VENDORS_LOG_LEVEL >= 1 && console.error('❌ [VENDORS ERROR]', ...args),
warn: (...args) => VENDORS_LOG_LEVEL >= 2 && console.warn('⚠️ [VENDORS WARN]', ...args),
info: (...args) => VENDORS_LOG_LEVEL >= 3 && console.info(' [VENDORS INFO]', ...args),
debug: (...args) => VENDORS_LOG_LEVEL >= 4 && console.log('🔍 [VENDORS DEBUG]', ...args)
};
// ============================================
// VENDOR LIST FUNCTION
// ============================================
function adminVendors() {
return {
// Inherit base layout functionality from init-alpine.js
...data(),
// ✅ CRITICAL: Page identifier for sidebar active state
currentPage: 'vendors',
// Vendors page specific state
vendors: [],
stats: {
total: 0,
verified: 0,
pending: 0,
inactive: 0
},
loading: false,
error: null,
// Pagination state (renamed from currentPage to avoid conflict)
page: 1, // ✅ FIXED: Was 'currentPage' which conflicted with sidebar
itemsPerPage: 10,
// Initialize
async init() {
vendorsLog.info('=== VENDORS PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._vendorsInitialized) {
vendorsLog.warn('Vendors page already initialized, skipping...');
return;
}
window._vendorsInitialized = true;
await this.loadVendors();
await this.loadStats();
vendorsLog.info('=== VENDORS PAGE INITIALIZATION COMPLETE ===');
},
// Computed: Get paginated vendors for current page
get paginatedVendors() {
const start = (this.page - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.vendors.slice(start, end);
},
// Computed: Total number of pages
get totalPages() {
return Math.ceil(this.vendors.length / this.itemsPerPage);
},
// Computed: Start index for pagination display
get startIndex() {
if (this.vendors.length === 0) return 0;
return (this.page - 1) * this.itemsPerPage + 1;
},
// Computed: End index for pagination display
get endIndex() {
const end = this.page * this.itemsPerPage;
return end > this.vendors.length ? this.vendors.length : end;
},
// Computed: Generate page numbers array with ellipsis
get pageNumbers() {
const pages = [];
const totalPages = this.totalPages;
const current = this.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 vendors list
async loadVendors() {
vendorsLog.info('Loading vendors list...');
this.loading = true;
this.error = null;
try {
const startTime = Date.now();
const response = await apiClient.get('/admin/vendors');
const duration = Date.now() - startTime;
// Handle different response structures
this.vendors = response.vendors || response.items || response || [];
vendorsLog.info(`Vendors loaded in ${duration}ms`, {
count: this.vendors.length,
hasVendors: this.vendors.length > 0
});
if (this.vendors.length > 0) {
vendorsLog.debug('First vendor:', this.vendors[0]);
}
// Reset to first page when data is loaded
this.page = 1;
} catch (error) {
vendorsLog.error('Failed to load vendors:', error);
this.error = error.message || 'Failed to load vendors';
Utils.showToast('Failed to load vendors', 'error');
} finally {
this.loading = false;
}
},
// Load statistics
async loadStats() {
vendorsLog.info('Loading vendor statistics...');
try {
const startTime = Date.now();
const response = await apiClient.get('/admin/vendors/stats');
const duration = Date.now() - startTime;
this.stats = response;
vendorsLog.info(`Stats loaded in ${duration}ms`, this.stats);
} catch (error) {
vendorsLog.error('Failed to load stats:', error);
// Don't show error toast for stats, just log it
}
},
// Pagination: Go to specific page
goToPage(pageNum) {
if (pageNum === '...' || pageNum < 1 || pageNum > this.totalPages) {
return;
}
vendorsLog.info('Going to page:', pageNum);
this.page = pageNum;
},
// Pagination: Go to next page
nextPage() {
if (this.page < this.totalPages) {
vendorsLog.info('Going to next page');
this.page++;
}
},
// Pagination: Go to previous page
previousPage() {
if (this.page > 1) {
vendorsLog.info('Going to previous page');
this.page--;
}
},
// Format date (matches dashboard pattern)
formatDate(dateString) {
if (!dateString) {
vendorsLog.debug('formatDate called with empty dateString');
return '-';
}
const formatted = Utils.formatDate(dateString);
vendorsLog.debug(`Date formatted: ${dateString} -> ${formatted}`);
return formatted;
},
// View vendor details
viewVendor(vendorCode) {
vendorsLog.info('Navigating to vendor details:', vendorCode);
const url = `/admin/vendors/${vendorCode}`;
vendorsLog.debug('Navigation URL:', url);
window.location.href = url;
},
// Edit vendor
editVendor(vendorCode) {
vendorsLog.info('Navigating to vendor edit:', vendorCode);
const url = `/admin/vendors/${vendorCode}/edit`;
vendorsLog.debug('Navigation URL:', url);
window.location.href = url;
},
// Delete vendor
async deleteVendor(vendor) {
vendorsLog.info('Delete vendor requested:', vendor.vendor_code);
if (!confirm(`Are you sure you want to delete vendor "${vendor.name}"?\n\nThis action cannot be undone.`)) {
vendorsLog.info('Delete cancelled by user');
return;
}
try {
vendorsLog.info('Deleting vendor:', vendor.vendor_code);
await apiClient.delete(`/admin/vendors/${vendor.vendor_code}`);
Utils.showToast('Vendor deleted successfully', 'success');
vendorsLog.info('Vendor deleted successfully');
// Reload data
await this.loadVendors();
await this.loadStats();
} catch (error) {
vendorsLog.error('Failed to delete vendor:', error);
Utils.showToast(error.message || 'Failed to delete vendor', 'error');
}
},
// Refresh vendors list
async refresh() {
vendorsLog.info('=== VENDORS REFRESH TRIGGERED ===');
await this.loadVendors();
await this.loadStats();
Utils.showToast('Vendors list refreshed', 'success');
vendorsLog.info('=== VENDORS REFRESH COMPLETE ===');
}
};
}
vendorsLog.info('Vendors module loaded');