Files
orion/app/modules/loyalty/static/admin/js/loyalty-company-detail.js
Samir Boulahtit d8f3338bc8 feat(loyalty): implement Phase 2 - company-wide points system
Complete implementation of loyalty module Phase 2 features:

Database & Models:
- Add company_id to LoyaltyProgram for chain-wide loyalty
- Add company_id to LoyaltyCard for multi-location support
- Add CompanyLoyaltySettings model for admin-controlled settings
- Add points expiration, welcome bonus, and minimum redemption fields
- Add POINTS_EXPIRED, WELCOME_BONUS transaction types

Services:
- Update program_service for company-based queries
- Update card_service with enrollment and welcome bonus
- Update points_service with void_points for returns
- Update stamp_service for company context
- Update pin_service for company-wide operations

API Endpoints:
- Admin: Program listing with stats, company detail views
- Vendor: Terminal operations, card management, settings
- Storefront: Customer card/transactions, self-enrollment

UI Templates:
- Admin: Programs dashboard, company detail, settings
- Vendor: Terminal, cards list, card detail, settings, stats, enrollment
- Storefront: Dashboard, history, enrollment, success pages

Background Tasks:
- Point expiration task (daily, based on inactivity)
- Wallet sync task (hourly)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 22:10:27 +01:00

209 lines
7.5 KiB
JavaScript

// app/modules/loyalty/static/admin/js/loyalty-company-detail.js
// noqa: js-006 - async init pattern is safe, loadData has try/catch
// Use centralized logger
const loyaltyCompanyDetailLog = window.LogConfig.loggers.loyaltyCompanyDetail || window.LogConfig.createLogger('loyaltyCompanyDetail');
// ============================================
// LOYALTY COMPANY DETAIL FUNCTION
// ============================================
function adminLoyaltyCompanyDetail() {
return {
// Inherit base layout functionality
...data(),
// Page identifier for sidebar active state
currentPage: 'loyalty-programs',
// Company ID from URL
companyId: null,
// Company data
company: null,
program: null,
stats: {
total_cards: 0,
active_cards: 0,
total_points_issued: 0,
total_points_redeemed: 0,
points_issued_30d: 0,
points_redeemed_30d: 0,
transactions_30d: 0
},
settings: null,
locations: [],
// State
loading: false,
error: null,
// Initialize
async init() {
loyaltyCompanyDetailLog.info('=== LOYALTY COMPANY DETAIL PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._loyaltyCompanyDetailInitialized) {
loyaltyCompanyDetailLog.warn('Loyalty company detail page already initialized, skipping...');
return;
}
window._loyaltyCompanyDetailInitialized = true;
// Extract company ID from URL
const pathParts = window.location.pathname.split('/');
const companiesIndex = pathParts.indexOf('companies');
if (companiesIndex !== -1 && pathParts[companiesIndex + 1]) {
this.companyId = parseInt(pathParts[companiesIndex + 1]);
}
if (!this.companyId) {
this.error = 'Invalid company ID';
loyaltyCompanyDetailLog.error('Could not extract company ID from URL');
return;
}
loyaltyCompanyDetailLog.info('Company ID:', this.companyId);
loyaltyCompanyDetailLog.group('Loading company loyalty data');
await this.loadCompanyData();
loyaltyCompanyDetailLog.groupEnd();
loyaltyCompanyDetailLog.info('=== LOYALTY COMPANY DETAIL PAGE INITIALIZATION COMPLETE ===');
},
// Load all company data
async loadCompanyData() {
this.loading = true;
this.error = null;
try {
// Load company info
await this.loadCompany();
// Load loyalty-specific data in parallel
await Promise.all([
this.loadStats(),
this.loadSettings(),
this.loadLocations()
]);
} catch (error) {
loyaltyCompanyDetailLog.error('Failed to load company data:', error);
this.error = error.message || 'Failed to load company loyalty data';
} finally {
this.loading = false;
}
},
// Load company basic info
async loadCompany() {
try {
loyaltyCompanyDetailLog.info('Fetching company info...');
// Get company from tenancy API
const response = await apiClient.get(`/admin/companies/${this.companyId}`);
if (response) {
this.company = response;
loyaltyCompanyDetailLog.info('Company loaded:', this.company.name);
}
} catch (error) {
loyaltyCompanyDetailLog.error('Failed to load company:', error);
throw error;
}
},
// Load company loyalty stats
async loadStats() {
try {
loyaltyCompanyDetailLog.info('Fetching company loyalty stats...');
const response = await apiClient.get(`/admin/loyalty/companies/${this.companyId}/stats`);
if (response) {
this.stats = {
total_cards: response.total_cards || 0,
active_cards: response.active_cards || 0,
total_points_issued: response.total_points_issued || 0,
total_points_redeemed: response.total_points_redeemed || 0,
points_issued_30d: response.points_issued_30d || 0,
points_redeemed_30d: response.points_redeemed_30d || 0,
transactions_30d: response.transactions_30d || 0
};
// Also get program info from stats response
if (response.program) {
this.program = response.program;
}
// Get location breakdown
if (response.locations) {
this.locations = response.locations;
}
loyaltyCompanyDetailLog.info('Stats loaded:', this.stats);
}
} catch (error) {
loyaltyCompanyDetailLog.warn('Failed to load stats (company may not have loyalty program):', error.message);
// Don't throw - stats might fail if no program exists
}
},
// Load company loyalty settings
async loadSettings() {
try {
loyaltyCompanyDetailLog.info('Fetching company loyalty settings...');
const response = await apiClient.get(`/admin/loyalty/companies/${this.companyId}/settings`);
if (response) {
this.settings = response;
loyaltyCompanyDetailLog.info('Settings loaded:', this.settings);
}
} catch (error) {
loyaltyCompanyDetailLog.warn('Failed to load settings:', error.message);
// Don't throw - settings might not exist yet
}
},
// Load location breakdown
async loadLocations() {
try {
loyaltyCompanyDetailLog.info('Fetching location breakdown...');
// This data comes with stats, but could be a separate endpoint
// For now, stats endpoint should return locations array
} catch (error) {
loyaltyCompanyDetailLog.warn('Failed to load locations:', error.message);
}
},
// 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) {
loyaltyCompanyDetailLog.error('Date parsing error:', e);
return dateString;
}
},
// Format number with thousands separator
formatNumber(num) {
if (num === null || num === undefined) return '0';
return new Intl.NumberFormat('en-US').format(num);
}
};
}
// Register logger for configuration
if (!window.LogConfig.loggers.loyaltyCompanyDetail) {
window.LogConfig.loggers.loyaltyCompanyDetail = window.LogConfig.createLogger('loyaltyCompanyDetail');
}
loyaltyCompanyDetailLog.info('Loyalty company detail module loaded');