// static/admin/js/companies.js // ✅ Use centralized logger const companiesLog = window.LogConfig.loggers.companies || window.LogConfig.createLogger('companies'); // ============================================ // COMPANY LIST FUNCTION // ============================================ function adminCompanies() { return { // Inherit base layout functionality ...data(), // ✅ Page identifier for sidebar active state currentPage: 'companies', // Companies page specific state companies: [], stats: { total: 0, verified: 0, active: 0, totalVendors: 0 }, loading: false, error: null, // Pagination state page: 1, itemsPerPage: 10, // Initialize async init() { companiesLog.info('=== COMPANIES PAGE INITIALIZING ==='); // Prevent multiple initializations if (window._companiesInitialized) { companiesLog.warn('Companies page already initialized, skipping...'); return; } window._companiesInitialized = true; companiesLog.group('Loading companies data'); await this.loadCompanies(); await this.loadStats(); companiesLog.groupEnd(); companiesLog.info('=== COMPANIES PAGE INITIALIZATION COMPLETE ==='); }, // Computed: Get paginated companies for current page get paginatedCompanies() { const start = (this.page - 1) * this.itemsPerPage; const end = start + this.itemsPerPage; return this.companies.slice(start, end); }, // Computed: Total number of pages get totalPages() { return Math.ceil(this.companies.length / this.itemsPerPage); }, // Computed: Start index for pagination display get startIndex() { if (this.companies.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.companies.length ? this.companies.length : end; }, // Computed: Generate page numbers array with ellipsis get pageNumbers() { const pages = []; const totalPages = this.totalPages; const current = this.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; }, // Load all companies async loadCompanies() { this.loading = true; this.error = null; try { companiesLog.info('Fetching companies from API...'); const response = await apiClient.get('/admin/companies'); if (response.companies) { this.companies = response.companies; companiesLog.info(`Loaded ${this.companies.length} companies`); } else { companiesLog.warn('No companies in response'); this.companies = []; } } catch (error) { companiesLog.error('Failed to load companies:', error); this.error = error.message || 'Failed to load companies'; this.companies = []; } finally { this.loading = false; } }, // Load statistics async loadStats() { try { companiesLog.info('Calculating stats from companies...'); this.stats.total = this.companies.length; this.stats.verified = this.companies.filter(c => c.is_verified).length; this.stats.active = this.companies.filter(c => c.is_active).length; this.stats.totalVendors = this.companies.reduce((sum, c) => sum + (c.vendor_count || 0), 0); companiesLog.info('Stats calculated:', this.stats); } catch (error) { companiesLog.error('Failed to calculate stats:', error); } }, // Edit company editCompany(companyId) { companiesLog.info('Edit company:', companyId); // TODO: Navigate to edit page window.location.href = `/admin/companies/${companyId}/edit`; }, // Delete company async deleteCompany(company) { if (company.vendor_count > 0) { companiesLog.warn('Cannot delete company with vendors'); alert(`Cannot delete "${company.name}" because it has ${company.vendor_count} vendor(s). Please delete or reassign the vendors first.`); return; } const confirmed = confirm( `Are you sure you want to delete "${company.name}"?\n\nThis action cannot be undone.` ); if (!confirmed) { companiesLog.info('Delete cancelled by user'); return; } try { companiesLog.info('Deleting company:', company.id); await apiClient.delete(`/admin/companies/${company.id}?confirm=true`); companiesLog.info('Company deleted successfully'); // Reload companies await this.loadCompanies(); await this.loadStats(); alert(`Company "${company.name}" deleted successfully`); } catch (error) { companiesLog.error('Failed to delete company:', error); alert(`Failed to delete company: ${error.message}`); } }, // Pagination methods previousPage() { if (this.page > 1) { this.page--; companiesLog.info('Previous page:', this.page); } }, nextPage() { if (this.page < this.totalPages) { this.page++; companiesLog.info('Next page:', this.page); } }, goToPage(pageNum) { if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) { this.page = pageNum; companiesLog.info('Go to page:', this.page); } }, // Format date for display formatDate(dateString) { if (!dateString) return 'N/A'; try { const date = new Date(dateString); return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }); } catch (e) { companiesLog.error('Date parsing error:', e); return dateString; } } }; } // Register logger for configuration if (!window.LogConfig.loggers.companies) { window.LogConfig.loggers.companies = window.LogConfig.createLogger('companies'); } companiesLog.info('✅ Companies module loaded');