// noqa: js-006 - async init pattern is safe, loadData has try/catch // static/admin/js/store-detail.js // ✅ Use centralized logger - ONE LINE! // Create custom logger for store detail const detailLog = window.LogConfig.createLogger('STORE-DETAIL'); function adminStoreDetail() { return { // Inherit base layout functionality from init-alpine.js ...data(), // Store detail page specific state currentPage: 'store-detail', store: null, subscription: null, subscriptionTier: null, usageMetrics: [], loading: false, error: null, storeCode: null, showSubscriptionModal: false, // Initialize async init() { // Load i18n translations await I18n.loadModule('tenancy'); detailLog.info('=== STORE DETAIL PAGE INITIALIZING ==='); // Prevent multiple initializations if (window._storeDetailInitialized) { detailLog.warn('Store detail page already initialized, skipping...'); return; } window._storeDetailInitialized = true; // Get store code from URL const path = window.location.pathname; const match = path.match(/\/admin\/stores\/([^\/]+)$/); if (match) { this.storeCode = match[1]; detailLog.info('Viewing store:', this.storeCode); await this.loadStore(); // Load subscription after store is loaded if (this.store?.id) { await this.loadSubscription(); } } else { detailLog.error('No store code in URL'); this.error = 'Invalid store URL'; Utils.showToast(I18n.t('tenancy.messages.invalid_store_url'), 'error'); } detailLog.info('=== STORE DETAIL PAGE INITIALIZATION COMPLETE ==='); }, // Load store data async loadStore() { detailLog.info('Loading store details...'); this.loading = true; this.error = null; try { const url = `/admin/stores/${this.storeCode}`; 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 Store Details', duration); this.store = response; detailLog.info(`Store loaded in ${duration}ms`, { store_code: this.store.store_code, name: this.store.name, is_verified: this.store.is_verified, is_active: this.store.is_active }); detailLog.debug('Full store data:', this.store); } catch (error) { window.LogConfig.logError(error, 'Load Store Details'); this.error = error.message || 'Failed to load store details'; Utils.showToast(I18n.t('tenancy.messages.failed_to_load_store_details'), 'error'); } finally { this.loading = false; } }, // Format date (matches dashboard pattern) formatDate(dateString) { if (!dateString) { detailLog.debug('formatDate called with empty dateString'); return '-'; } const formatted = Utils.formatDate(dateString); detailLog.debug(`Date formatted: ${dateString} -> ${formatted}`); return formatted; }, // Load subscription data for this store via convenience endpoint async loadSubscription() { if (!this.store?.id) { detailLog.warn('Cannot load subscription: no store ID'); return; } detailLog.info('Loading subscription for store:', this.store.id); try { const url = `/admin/subscriptions/store/${this.store.id}`; window.LogConfig.logApiCall('GET', url, null, 'request'); const response = await apiClient.get(url); window.LogConfig.logApiCall('GET', url, response, 'response'); this.subscription = response.subscription; this.subscriptionTier = response.tier; this.usageMetrics = response.features || []; detailLog.info('Subscription loaded:', { tier: this.subscription?.tier, status: this.subscription?.status, features_count: this.usageMetrics.length }); } catch (error) { // 404 means no subscription exists - that's OK if (error.status === 404) { detailLog.info('No subscription found for store'); this.subscription = null; this.usageMetrics = []; } else { detailLog.warn('Failed to load subscription:', error.message); } } }, // Get usage bar color based on percentage getUsageBarColor(current, limit) { if (!limit || limit === 0) return 'bg-blue-500'; const percent = (current / limit) * 100; if (percent >= 90) return 'bg-red-500'; if (percent >= 75) return 'bg-yellow-500'; return 'bg-green-500'; }, // Create a new subscription for this store async createSubscription() { if (!this.store?.id) { Utils.showToast(I18n.t('tenancy.messages.no_store_loaded'), 'error'); return; } detailLog.info('Creating subscription for store:', this.store.id); try { // Create a trial subscription with default tier const url = `/admin/subscriptions/${this.store.id}`; const data = { tier: 'essential', status: 'trial', trial_days: 14, is_annual: false }; window.LogConfig.logApiCall('POST', url, data, 'request'); const response = await apiClient.post(url, data); window.LogConfig.logApiCall('POST', url, response, 'response'); this.subscription = response; Utils.showToast(I18n.t('tenancy.messages.subscription_created_successfully'), 'success'); detailLog.info('Subscription created:', this.subscription); } catch (error) { window.LogConfig.logError(error, 'Create Subscription'); Utils.showToast(error.message || 'Failed to create subscription', 'error'); } }, // Delete store async deleteStore() { detailLog.info('Delete store requested:', this.storeCode); if (!confirm(`Are you sure you want to delete store "${this.store.name}"?\n\nThis action cannot be undone and will delete:\n- All products\n- All orders\n- All customers\n- All team members`)) { detailLog.info('Delete cancelled by user'); return; } // Second confirmation for safety if (!confirm(`FINAL CONFIRMATION\n\nType the store code to confirm: ${this.store.store_code}\n\nAre you absolutely sure?`)) { detailLog.info('Delete cancelled by user (second confirmation)'); return; } try { const url = `/admin/stores/${this.storeCode}?confirm=true`; window.LogConfig.logApiCall('DELETE', url, null, 'request'); detailLog.info('Deleting store:', this.storeCode); await apiClient.delete(url); window.LogConfig.logApiCall('DELETE', url, null, 'response'); Utils.showToast(I18n.t('tenancy.messages.store_deleted_successfully'), 'success'); detailLog.info('Store deleted successfully'); // Redirect to stores list setTimeout(() => window.location.href = '/admin/stores', 1500); } catch (error) { window.LogConfig.logError(error, 'Delete Store'); Utils.showToast(error.message || 'Failed to delete store', 'error'); } }, // Refresh store data async refresh() { detailLog.info('=== STORE REFRESH TRIGGERED ==='); await this.loadStore(); Utils.showToast(I18n.t('tenancy.messages.store_details_refreshed'), 'success'); detailLog.info('=== STORE REFRESH COMPLETE ==='); } }; } detailLog.info('Store detail module loaded');