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>
This commit is contained in:
2026-02-05 22:10:27 +01:00
parent 3bdf1695fd
commit d8f3338bc8
54 changed files with 7252 additions and 186 deletions

View File

@@ -0,0 +1,115 @@
// app/modules/loyalty/static/admin/js/loyalty-analytics.js
// noqa: js-006 - async init pattern is safe, loadData has try/catch
// Use centralized logger
const loyaltyAnalyticsLog = window.LogConfig.loggers.loyaltyAnalytics || window.LogConfig.createLogger('loyaltyAnalytics');
// ============================================
// LOYALTY ANALYTICS FUNCTION
// ============================================
function adminLoyaltyAnalytics() {
return {
// Inherit base layout functionality
...data(),
// Page identifier for sidebar active state
currentPage: 'loyalty-analytics',
// Stats
stats: {
total_programs: 0,
active_programs: 0,
total_cards: 0,
active_cards: 0,
transactions_30d: 0,
points_issued_30d: 0,
points_redeemed_30d: 0,
companies_with_programs: 0
},
// State
loading: false,
error: null,
// Computed: Redemption rate percentage
get redemptionRate() {
if (this.stats.points_issued_30d === 0) return 0;
return Math.round((this.stats.points_redeemed_30d / this.stats.points_issued_30d) * 100);
},
// Computed: Issued percentage for progress bar
get issuedPercentage() {
const total = this.stats.points_issued_30d + this.stats.points_redeemed_30d;
if (total === 0) return 50;
return Math.round((this.stats.points_issued_30d / total) * 100);
},
// Computed: Redeemed percentage for progress bar
get redeemedPercentage() {
return 100 - this.issuedPercentage;
},
// Initialize
async init() {
loyaltyAnalyticsLog.info('=== LOYALTY ANALYTICS PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._loyaltyAnalyticsInitialized) {
loyaltyAnalyticsLog.warn('Loyalty analytics page already initialized, skipping...');
return;
}
window._loyaltyAnalyticsInitialized = true;
loyaltyAnalyticsLog.group('Loading analytics data');
await this.loadStats();
loyaltyAnalyticsLog.groupEnd();
loyaltyAnalyticsLog.info('=== LOYALTY ANALYTICS PAGE INITIALIZATION COMPLETE ===');
},
// Load platform stats
async loadStats() {
this.loading = true;
this.error = null;
try {
loyaltyAnalyticsLog.info('Fetching loyalty analytics...');
const response = await apiClient.get('/admin/loyalty/stats');
if (response) {
this.stats = {
total_programs: response.total_programs || 0,
active_programs: response.active_programs || 0,
total_cards: response.total_cards || 0,
active_cards: response.active_cards || 0,
transactions_30d: response.transactions_30d || 0,
points_issued_30d: response.points_issued_30d || 0,
points_redeemed_30d: response.points_redeemed_30d || 0,
companies_with_programs: response.companies_with_programs || 0
};
loyaltyAnalyticsLog.info('Analytics loaded:', this.stats);
}
} catch (error) {
loyaltyAnalyticsLog.error('Failed to load analytics:', error);
this.error = error.message || 'Failed to load analytics';
} finally {
this.loading = false;
}
},
// 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.loyaltyAnalytics) {
window.LogConfig.loggers.loyaltyAnalytics = window.LogConfig.createLogger('loyaltyAnalytics');
}
loyaltyAnalyticsLog.info('Loyalty analytics module loaded');

View File

@@ -0,0 +1,208 @@
// 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');

View File

@@ -0,0 +1,173 @@
// app/modules/loyalty/static/admin/js/loyalty-company-settings.js
// noqa: js-006 - async init pattern is safe, loadData has try/catch
// Use centralized logger
const loyaltyCompanySettingsLog = window.LogConfig.loggers.loyaltyCompanySettings || window.LogConfig.createLogger('loyaltyCompanySettings');
// ============================================
// LOYALTY COMPANY SETTINGS FUNCTION
// ============================================
function adminLoyaltyCompanySettings() {
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,
// Settings form data
settings: {
staff_pin_policy: 'optional',
staff_pin_lockout_attempts: 5,
staff_pin_lockout_minutes: 30,
allow_self_enrollment: true,
allow_void_transactions: true,
allow_cross_location_redemption: true
},
// State
loading: false,
saving: false,
error: null,
// Back URL
get backUrl() {
return `/admin/loyalty/companies/${this.companyId}`;
},
// Initialize
async init() {
loyaltyCompanySettingsLog.info('=== LOYALTY COMPANY SETTINGS PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._loyaltyCompanySettingsInitialized) {
loyaltyCompanySettingsLog.warn('Loyalty company settings page already initialized, skipping...');
return;
}
window._loyaltyCompanySettingsInitialized = 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';
loyaltyCompanySettingsLog.error('Could not extract company ID from URL');
return;
}
loyaltyCompanySettingsLog.info('Company ID:', this.companyId);
loyaltyCompanySettingsLog.group('Loading company settings data');
await this.loadData();
loyaltyCompanySettingsLog.groupEnd();
loyaltyCompanySettingsLog.info('=== LOYALTY COMPANY SETTINGS PAGE INITIALIZATION COMPLETE ===');
},
// Load all data
async loadData() {
this.loading = true;
this.error = null;
try {
// Load company info and settings in parallel
await Promise.all([
this.loadCompany(),
this.loadSettings()
]);
} catch (error) {
loyaltyCompanySettingsLog.error('Failed to load data:', error);
this.error = error.message || 'Failed to load settings';
} finally {
this.loading = false;
}
},
// Load company basic info
async loadCompany() {
try {
loyaltyCompanySettingsLog.info('Fetching company info...');
const response = await apiClient.get(`/admin/companies/${this.companyId}`);
if (response) {
this.company = response;
loyaltyCompanySettingsLog.info('Company loaded:', this.company.name);
}
} catch (error) {
loyaltyCompanySettingsLog.error('Failed to load company:', error);
throw error;
}
},
// Load settings
async loadSettings() {
try {
loyaltyCompanySettingsLog.info('Fetching company loyalty settings...');
const response = await apiClient.get(`/admin/loyalty/companies/${this.companyId}/settings`);
if (response) {
// Merge with defaults to ensure all fields exist
this.settings = {
staff_pin_policy: response.staff_pin_policy || 'optional',
staff_pin_lockout_attempts: response.staff_pin_lockout_attempts || 5,
staff_pin_lockout_minutes: response.staff_pin_lockout_minutes || 30,
allow_self_enrollment: response.allow_self_enrollment !== false,
allow_void_transactions: response.allow_void_transactions !== false,
allow_cross_location_redemption: response.allow_cross_location_redemption !== false
};
loyaltyCompanySettingsLog.info('Settings loaded:', this.settings);
}
} catch (error) {
loyaltyCompanySettingsLog.warn('Failed to load settings, using defaults:', error.message);
// Keep default settings
}
},
// Save settings
async saveSettings() {
this.saving = true;
try {
loyaltyCompanySettingsLog.info('Saving company loyalty settings...');
const response = await apiClient.patch(
`/admin/loyalty/companies/${this.companyId}/settings`,
this.settings
);
if (response) {
loyaltyCompanySettingsLog.info('Settings saved successfully');
Utils.showToast('Settings saved successfully', 'success');
// Navigate back to company detail
window.location.href = this.backUrl;
}
} catch (error) {
loyaltyCompanySettingsLog.error('Failed to save settings:', error);
Utils.showToast(`Failed to save settings: ${error.message}`, 'error');
} finally {
this.saving = false;
}
}
};
}
// Register logger for configuration
if (!window.LogConfig.loggers.loyaltyCompanySettings) {
window.LogConfig.loggers.loyaltyCompanySettings = window.LogConfig.createLogger('loyaltyCompanySettings');
}
loyaltyCompanySettingsLog.info('Loyalty company settings module loaded');

View File

@@ -0,0 +1,264 @@
// app/modules/loyalty/static/admin/js/loyalty-programs.js
// noqa: js-006 - async init pattern is safe, loadData has try/catch
// Use centralized logger
const loyaltyProgramsLog = window.LogConfig.loggers.loyaltyPrograms || window.LogConfig.createLogger('loyaltyPrograms');
// ============================================
// LOYALTY PROGRAMS LIST FUNCTION
// ============================================
function adminLoyaltyPrograms() {
return {
// Inherit base layout functionality
...data(),
// Page identifier for sidebar active state
currentPage: 'loyalty-programs',
// Programs page specific state
programs: [],
stats: {
total_programs: 0,
active_programs: 0,
total_cards: 0,
transactions_30d: 0,
points_issued_30d: 0,
points_redeemed_30d: 0,
companies_with_programs: 0
},
loading: false,
error: null,
// Search and filters
filters: {
search: '',
is_active: ''
},
// Pagination state
pagination: {
page: 1,
per_page: 20,
total: 0,
pages: 0
},
// Initialize
async init() {
loyaltyProgramsLog.info('=== LOYALTY PROGRAMS PAGE INITIALIZING ===');
// Prevent multiple initializations
if (window._loyaltyProgramsInitialized) {
loyaltyProgramsLog.warn('Loyalty programs page already initialized, skipping...');
return;
}
window._loyaltyProgramsInitialized = true;
// Load platform settings for rows per page
if (window.PlatformSettings) {
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
}
loyaltyProgramsLog.group('Loading loyalty programs data');
await Promise.all([
this.loadPrograms(),
this.loadStats()
]);
loyaltyProgramsLog.groupEnd();
loyaltyProgramsLog.info('=== LOYALTY PROGRAMS PAGE INITIALIZATION COMPLETE ===');
},
// Debounced search
debouncedSearch() {
if (this._searchTimeout) {
clearTimeout(this._searchTimeout);
}
this._searchTimeout = setTimeout(() => {
loyaltyProgramsLog.info('Search triggered:', this.filters.search);
this.pagination.page = 1;
this.loadPrograms();
}, 300);
},
// Computed: Get programs for current page (already paginated from server)
get paginatedPrograms() {
return this.programs;
},
// 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 programs with search and pagination
async loadPrograms() {
this.loading = true;
this.error = null;
try {
loyaltyProgramsLog.info('Fetching loyalty programs from API...');
const params = new URLSearchParams();
params.append('skip', (this.pagination.page - 1) * this.pagination.per_page);
params.append('limit', this.pagination.per_page);
if (this.filters.search) {
params.append('search', this.filters.search);
}
if (this.filters.is_active !== '') {
params.append('is_active', this.filters.is_active);
}
const response = await apiClient.get(`/admin/loyalty/programs?${params}`);
if (response.programs) {
this.programs = response.programs;
this.pagination.total = response.total;
this.pagination.pages = Math.ceil(response.total / this.pagination.per_page);
loyaltyProgramsLog.info(`Loaded ${this.programs.length} programs (total: ${response.total})`);
} else {
loyaltyProgramsLog.warn('No programs in response');
this.programs = [];
}
} catch (error) {
loyaltyProgramsLog.error('Failed to load programs:', error);
this.error = error.message || 'Failed to load loyalty programs';
this.programs = [];
} finally {
this.loading = false;
}
},
// Load platform stats
async loadStats() {
try {
loyaltyProgramsLog.info('Fetching loyalty stats from API...');
const response = await apiClient.get('/admin/loyalty/stats');
if (response) {
this.stats = {
total_programs: response.total_programs || 0,
active_programs: response.active_programs || 0,
total_cards: response.total_cards || 0,
transactions_30d: response.transactions_30d || 0,
points_issued_30d: response.points_issued_30d || 0,
points_redeemed_30d: response.points_redeemed_30d || 0,
companies_with_programs: response.companies_with_programs || 0
};
loyaltyProgramsLog.info('Stats loaded:', this.stats);
}
} catch (error) {
loyaltyProgramsLog.error('Failed to load stats:', error);
// Don't set error state for stats failure
}
},
// Pagination methods
previousPage() {
if (this.pagination.page > 1) {
this.pagination.page--;
loyaltyProgramsLog.info('Previous page:', this.pagination.page);
this.loadPrograms();
}
},
nextPage() {
if (this.pagination.page < this.totalPages) {
this.pagination.page++;
loyaltyProgramsLog.info('Next page:', this.pagination.page);
this.loadPrograms();
}
},
goToPage(pageNum) {
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
this.pagination.page = pageNum;
loyaltyProgramsLog.info('Go to page:', this.pagination.page);
this.loadPrograms();
}
},
// 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) {
loyaltyProgramsLog.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.loyaltyPrograms) {
window.LogConfig.loggers.loyaltyPrograms = window.LogConfig.createLogger('loyaltyPrograms');
}
loyaltyProgramsLog.info('Loyalty programs module loaded');