feat(loyalty): refactor analytics into shared template and add merchant stats API
Some checks failed
CI / ruff (push) Successful in 11s
CI / validate (push) Has been cancelled
CI / dependency-scanning (push) Has been cancelled
CI / docs (push) Has been cancelled
CI / deploy (push) Has been cancelled
CI / pytest (push) Has been cancelled

Extract analytics stat cards, points activity, and location breakdown
into a shared partial used by admin, merchant, and store dashboards.
Add merchant stats API endpoint and client-side merchant filter on admin
analytics page. Extend stats schema with new_this_month and
estimated_liability_cents fields.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-11 11:08:16 +01:00
parent 8cf5da6914
commit 6acd783754
11 changed files with 630 additions and 375 deletions

View File

@@ -28,6 +28,7 @@ from app.modules.loyalty.schemas import (
ProgramResponse, ProgramResponse,
ProgramUpdate, ProgramUpdate,
) )
from app.modules.loyalty.schemas.program import MerchantStatsResponse
from app.modules.loyalty.services import program_service from app.modules.loyalty.services import program_service
from app.modules.tenancy.models import Merchant from app.modules.tenancy.models import Merchant
@@ -49,6 +50,21 @@ def _build_program_response(program) -> ProgramResponse:
return response return response
# =============================================================================
# Statistics
# =============================================================================
@router.get("/stats", response_model=MerchantStatsResponse)
def get_stats(
merchant: Merchant = Depends(get_merchant_for_current_user),
db: Session = Depends(get_db),
):
"""Get merchant-wide loyalty statistics across all locations."""
stats = program_service.get_merchant_stats(db, merchant.id)
return MerchantStatsResponse(**stats)
# ============================================================================= # =============================================================================
# Program CRUD # Program CRUD
# ============================================================================= # =============================================================================

View File

@@ -145,24 +145,13 @@ async def merchant_loyalty_analytics(
""" """
Render merchant loyalty analytics page. Render merchant loyalty analytics page.
Shows aggregate loyalty program stats across all merchant stores. Stats are loaded client-side via JS fetch.
""" """
merchant_id = merchant.id
stats = {}
try:
stats = program_service.get_merchant_stats(db, merchant_id)
except Exception:
logger.warning(
f"Failed to load loyalty stats for merchant {merchant_id}",
exc_info=True,
)
context = _get_merchant_context( context = _get_merchant_context(
request, request,
db, db,
current_user, current_user,
loyalty_stats=stats, merchant_id=merchant.id,
merchant_id=merchant_id,
) )
return templates.TemplateResponse( return templates.TemplateResponse(
"loyalty/merchant/analytics.html", "loyalty/merchant/analytics.html",

View File

@@ -284,11 +284,17 @@ class MerchantStatsResponse(BaseModel):
total_points_issued: int = 0 total_points_issued: int = 0
total_points_redeemed: int = 0 total_points_redeemed: int = 0
# Members
new_this_month: int = 0
# Points - last 30 days # Points - last 30 days
points_issued_30d: int = 0 points_issued_30d: int = 0
points_redeemed_30d: int = 0 points_redeemed_30d: int = 0
transactions_30d: int = 0 transactions_30d: int = 0
# Value
estimated_liability_cents: int = 0
# Program info (optional) # Program info (optional)
program: dict | None = None program: dict | None = None

View File

@@ -322,6 +322,52 @@ class ProgramService:
db.query(func.count(func.distinct(LoyaltyProgram.merchant_id))).scalar() or 0 db.query(func.count(func.distinct(LoyaltyProgram.merchant_id))).scalar() or 0
) )
# All-time points
total_points_issued = (
db.query(func.sum(LoyaltyTransaction.points_delta))
.filter(LoyaltyTransaction.points_delta > 0)
.scalar()
or 0
)
total_points_redeemed = (
db.query(func.sum(func.abs(LoyaltyTransaction.points_delta)))
.filter(LoyaltyTransaction.points_delta < 0)
.scalar()
or 0
)
# Outstanding points balance
total_points_balance = (
db.query(func.sum(LoyaltyCard.points_balance)).scalar() or 0
)
# New members this month
month_start = datetime.now(UTC).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
new_this_month = (
db.query(func.count(LoyaltyCard.id))
.filter(LoyaltyCard.created_at >= month_start)
.scalar()
or 0
)
# Estimated liability (rough estimate: points / 100 as euros)
points_value_cents = total_points_balance // 100 * 100
# Stamp liability across all programs
stamp_liability = 0
programs = db.query(LoyaltyProgram).all()
for prog in programs:
stamp_value = prog.stamps_reward_value_cents or 0
stamps_target = prog.stamps_target or 1
current_stamps = (
db.query(func.sum(LoyaltyCard.stamp_count))
.filter(LoyaltyCard.program_id == prog.id)
.scalar()
or 0
)
stamp_liability += current_stamps * stamp_value // stamps_target
estimated_liability_cents = stamp_liability + points_value_cents
return { return {
"total_programs": total_programs, "total_programs": total_programs,
"active_programs": active_programs, "active_programs": active_programs,
@@ -331,6 +377,11 @@ class ProgramService:
"transactions_30d": transactions_30d, "transactions_30d": transactions_30d,
"points_issued_30d": points_issued_30d, "points_issued_30d": points_issued_30d,
"points_redeemed_30d": points_redeemed_30d, "points_redeemed_30d": points_redeemed_30d,
"total_points_issued": total_points_issued,
"total_points_redeemed": total_points_redeemed,
"total_points_balance": total_points_balance,
"new_this_month": new_this_month,
"estimated_liability_cents": estimated_liability_cents,
} }
def check_self_enrollment_allowed(self, db: Session, merchant_id: int) -> None: def check_self_enrollment_allowed(self, db: Session, merchant_id: int) -> None:
@@ -843,6 +894,7 @@ class ProgramService:
} }
thirty_days_ago = datetime.now(UTC) - timedelta(days=30) thirty_days_ago = datetime.now(UTC) - timedelta(days=30)
month_start = datetime.now(UTC).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
# Total cards # Total cards
stats["total_cards"] = ( stats["total_cards"] = (
@@ -920,6 +972,37 @@ class ProgramService:
or 0 or 0
) )
# New members this month
stats["new_this_month"] = (
db.query(func.count(LoyaltyCard.id))
.filter(
LoyaltyCard.merchant_id == merchant_id,
LoyaltyCard.created_at >= month_start,
)
.scalar()
or 0
)
# Estimated liability (unredeemed value)
current_stamps = (
db.query(func.sum(LoyaltyCard.stamp_count))
.filter(LoyaltyCard.merchant_id == merchant_id)
.scalar()
or 0
)
stamp_value = program.stamps_reward_value_cents or 0
stamps_target = program.stamps_target or 1
current_points = (
db.query(func.sum(LoyaltyCard.points_balance))
.filter(LoyaltyCard.merchant_id == merchant_id)
.scalar()
or 0
)
points_value_cents = current_points // 100 * 100
stats["estimated_liability_cents"] = (
(current_stamps * stamp_value // stamps_target) + points_value_cents
)
# Get all stores for this merchant for location breakdown # Get all stores for this merchant for location breakdown
stores = store_service.get_stores_by_merchant_id(db, merchant_id) stores = store_service.get_stores_by_merchant_id(db, merchant_id)

View File

@@ -1,21 +1,13 @@
// app/modules/loyalty/static/admin/js/loyalty-analytics.js // app/modules/loyalty/static/admin/js/loyalty-analytics.js
// noqa: js-006 - async init pattern is safe, loadData has try/catch // 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'); const loyaltyAnalyticsLog = window.LogConfig.loggers.loyaltyAnalytics || window.LogConfig.createLogger('loyaltyAnalytics');
// ============================================
// LOYALTY ANALYTICS FUNCTION
// ============================================
function adminLoyaltyAnalytics() { function adminLoyaltyAnalytics() {
return { return {
// Inherit base layout functionality
...data(), ...data(),
// Page identifier for sidebar active state
currentPage: 'loyalty-analytics', currentPage: 'loyalty-analytics',
// Stats
stats: { stats: {
total_programs: 0, total_programs: 0,
active_programs: 0, active_programs: 0,
@@ -24,59 +16,58 @@ function adminLoyaltyAnalytics() {
transactions_30d: 0, transactions_30d: 0,
points_issued_30d: 0, points_issued_30d: 0,
points_redeemed_30d: 0, points_redeemed_30d: 0,
merchants_with_programs: 0 merchants_with_programs: 0,
total_points_issued: 0,
total_points_redeemed: 0,
total_points_balance: 0,
new_this_month: 0,
estimated_liability_cents: 0,
}, },
// State locations: [],
// Merchant filter state
selectedMerchant: null,
merchantSearch: '',
merchantResults: [],
showMerchantDropdown: false,
searchingMerchants: false,
loading: false, loading: false,
error: null, error: null,
// Computed: Redemption rate percentage _searchTimeout: null,
get redemptionRate() { get redemptionRate() {
if (this.stats.points_issued_30d === 0) return 0; if (this.stats.points_issued_30d === 0) return 0;
return Math.round((this.stats.points_redeemed_30d / this.stats.points_issued_30d) * 100); return Math.round((this.stats.points_redeemed_30d / this.stats.points_issued_30d) * 100);
}, },
// Computed: Issued percentage for progress bar
get issuedPercentage() { get issuedPercentage() {
const total = this.stats.points_issued_30d + this.stats.points_redeemed_30d; const total = this.stats.points_issued_30d + this.stats.points_redeemed_30d;
if (total === 0) return 50; if (total === 0) return 50;
return Math.round((this.stats.points_issued_30d / total) * 100); return Math.round((this.stats.points_issued_30d / total) * 100);
}, },
// Computed: Redeemed percentage for progress bar
get redeemedPercentage() { get redeemedPercentage() {
return 100 - this.issuedPercentage; return 100 - this.issuedPercentage;
}, },
// Initialize
async init() { async init() {
loyaltyAnalyticsLog.info('=== LOYALTY ANALYTICS PAGE INITIALIZING ==='); loyaltyAnalyticsLog.info('=== LOYALTY ANALYTICS PAGE INITIALIZING ===');
if (window._loyaltyAnalyticsInitialized) return;
// Prevent multiple initializations
if (window._loyaltyAnalyticsInitialized) {
loyaltyAnalyticsLog.warn('Loyalty analytics page already initialized, skipping...');
return;
}
window._loyaltyAnalyticsInitialized = true; window._loyaltyAnalyticsInitialized = true;
loyaltyAnalyticsLog.group('Loading analytics data');
await this.loadStats(); await this.loadStats();
loyaltyAnalyticsLog.groupEnd();
loyaltyAnalyticsLog.info('=== LOYALTY ANALYTICS PAGE INITIALIZATION COMPLETE ==='); loyaltyAnalyticsLog.info('=== LOYALTY ANALYTICS PAGE INITIALIZATION COMPLETE ===');
}, },
// Load platform stats
async loadStats() { async loadStats() {
this.loading = true; this.loading = true;
this.error = null; this.error = null;
try { try {
loyaltyAnalyticsLog.info('Fetching loyalty analytics...');
const response = await apiClient.get('/admin/loyalty/stats'); const response = await apiClient.get('/admin/loyalty/stats');
if (response) { if (response) {
this.stats = { this.stats = {
total_programs: response.total_programs || 0, total_programs: response.total_programs || 0,
@@ -86,10 +77,15 @@ function adminLoyaltyAnalytics() {
transactions_30d: response.transactions_30d || 0, transactions_30d: response.transactions_30d || 0,
points_issued_30d: response.points_issued_30d || 0, points_issued_30d: response.points_issued_30d || 0,
points_redeemed_30d: response.points_redeemed_30d || 0, points_redeemed_30d: response.points_redeemed_30d || 0,
merchants_with_programs: response.merchants_with_programs || 0 merchants_with_programs: response.merchants_with_programs || 0,
total_points_issued: response.total_points_issued || 0,
total_points_redeemed: response.total_points_redeemed || 0,
total_points_balance: response.total_points_balance || 0,
new_this_month: response.new_this_month || 0,
estimated_liability_cents: response.estimated_liability_cents || 0,
}; };
this.locations = [];
loyaltyAnalyticsLog.info('Analytics loaded:', this.stats); loyaltyAnalyticsLog.info('Platform stats loaded');
} }
} catch (error) { } catch (error) {
loyaltyAnalyticsLog.error('Failed to load analytics:', error); loyaltyAnalyticsLog.error('Failed to load analytics:', error);
@@ -99,7 +95,77 @@ function adminLoyaltyAnalytics() {
} }
}, },
// Format number with thousands separator searchMerchants() {
clearTimeout(this._searchTimeout);
this._searchTimeout = setTimeout(async () => {
if (this.merchantSearch.length < 2) {
this.merchantResults = [];
return;
}
this.searchingMerchants = true;
try {
const response = await apiClient.get(`/admin/loyalty/programs?search=${encodeURIComponent(this.merchantSearch)}&limit=10`);
if (response && response.programs) {
this.merchantResults = response.programs.map(p => ({
id: p.merchant_id,
merchant_name: p.merchant_name || p.display_name || `Program #${p.id}`,
loyalty_type: p.loyalty_type,
}));
}
} catch (error) {
loyaltyAnalyticsLog.error('Merchant search failed:', error);
this.merchantResults = [];
} finally {
this.searchingMerchants = false;
}
}, 300);
},
async selectMerchant(item) {
this.selectedMerchant = item;
this.merchantSearch = '';
this.merchantResults = [];
this.showMerchantDropdown = false;
this.loading = true;
this.error = null;
try {
const response = await apiClient.get(`/admin/loyalty/merchants/${item.id}/stats`);
if (response) {
this.stats = {
total_programs: 1,
active_programs: response.program?.is_active ? 1 : 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,
merchants_with_programs: 1,
total_points_issued: response.total_points_issued || 0,
total_points_redeemed: response.total_points_redeemed || 0,
total_points_balance: (response.total_points_issued || 0) - (response.total_points_redeemed || 0),
new_this_month: response.new_this_month || 0,
estimated_liability_cents: response.estimated_liability_cents || 0,
};
this.locations = response.locations || [];
loyaltyAnalyticsLog.info('Merchant stats loaded for:', item.merchant_name);
}
} catch (error) {
loyaltyAnalyticsLog.error('Failed to load merchant stats:', error);
this.error = error.message || 'Failed to load merchant stats';
} finally {
this.loading = false;
}
},
async clearMerchantFilter() {
this.selectedMerchant = null;
this.merchantSearch = '';
this.merchantResults = [];
await this.loadStats();
},
formatNumber(num) { formatNumber(num) {
if (num === null || num === undefined) return '0'; if (num === null || num === undefined) return '0';
return new Intl.NumberFormat('en-US').format(num); return new Intl.NumberFormat('en-US').format(num);
@@ -107,9 +173,7 @@ function adminLoyaltyAnalytics() {
}; };
} }
// Register logger for configuration
if (!window.LogConfig.loggers.loyaltyAnalytics) { if (!window.LogConfig.loggers.loyaltyAnalytics) {
window.LogConfig.loggers.loyaltyAnalytics = window.LogConfig.createLogger('loyaltyAnalytics'); window.LogConfig.loggers.loyaltyAnalytics = window.LogConfig.createLogger('loyaltyAnalytics');
} }
loyaltyAnalyticsLog.info('Loyalty analytics module loaded'); loyaltyAnalyticsLog.info('Loyalty analytics module loaded');

View File

@@ -0,0 +1,109 @@
// app/modules/loyalty/static/merchant/js/loyalty-analytics.js
// noqa: js-006 - async init pattern is safe, loadData has try/catch
const loyaltyAnalyticsLog = window.LogConfig.loggers.loyaltyAnalytics || window.LogConfig.createLogger('loyaltyAnalytics');
function merchantLoyaltyAnalytics() {
return {
...data(),
currentPage: 'loyalty-analytics',
program: null,
locations: [],
stats: {
total_cards: 0,
active_cards: 0,
new_this_month: 0,
total_points_issued: 0,
total_points_redeemed: 0,
total_points_balance: 0,
points_issued_30d: 0,
points_redeemed_30d: 0,
transactions_30d: 0,
avg_points_per_member: 0,
estimated_liability_cents: 0,
},
loading: false,
error: null,
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);
},
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);
},
get redeemedPercentage() {
return 100 - this.issuedPercentage;
},
async init() {
loyaltyAnalyticsLog.info('=== MERCHANT LOYALTY ANALYTICS PAGE INITIALIZING ===');
if (window._loyaltyAnalyticsInitialized) return;
window._loyaltyAnalyticsInitialized = true;
this.loadMenuConfig();
await this.loadStats();
loyaltyAnalyticsLog.info('=== MERCHANT LOYALTY ANALYTICS PAGE INITIALIZATION COMPLETE ===');
},
async loadStats() {
this.loading = true;
this.error = null;
try {
const response = await apiClient.get('/merchants/loyalty/stats');
if (response) {
this.program = response.program || null;
this.locations = response.locations || [];
const totalBalance = (response.total_points_issued || 0) - (response.total_points_redeemed || 0);
const avgPoints = response.active_cards > 0
? Math.round(totalBalance / response.active_cards * 100) / 100
: 0;
this.stats = {
total_cards: response.total_cards || 0,
active_cards: response.active_cards || 0,
new_this_month: response.new_this_month || 0,
total_points_issued: response.total_points_issued || 0,
total_points_redeemed: response.total_points_redeemed || 0,
total_points_balance: totalBalance,
points_issued_30d: response.points_issued_30d || 0,
points_redeemed_30d: response.points_redeemed_30d || 0,
transactions_30d: response.transactions_30d || 0,
avg_points_per_member: avgPoints,
estimated_liability_cents: response.estimated_liability_cents || 0,
};
loyaltyAnalyticsLog.info('Merchant stats loaded');
}
} catch (error) {
if (error.status === 404) {
loyaltyAnalyticsLog.info('No program found');
this.program = null;
} else {
loyaltyAnalyticsLog.error('Failed to load stats:', error);
this.error = error.message || 'Failed to load analytics';
}
} finally {
this.loading = false;
}
},
formatNumber(num) {
if (num === null || num === undefined) return '0';
return new Intl.NumberFormat('en-US').format(num);
}
};
}
if (!window.LogConfig.loggers.loyaltyAnalytics) {
window.LogConfig.loggers.loyaltyAnalytics = window.LogConfig.createLogger('loyaltyAnalytics');
}
loyaltyAnalyticsLog.info('Merchant loyalty analytics module loaded');

View File

@@ -20,18 +20,34 @@ function storeLoyaltyAnalytics() {
points_issued_30d: 0, points_issued_30d: 0,
points_redeemed_30d: 0, points_redeemed_30d: 0,
transactions_30d: 0, transactions_30d: 0,
avg_points_per_member: 0 avg_points_per_member: 0,
estimated_liability_cents: 0,
}, },
loading: false, loading: false,
error: null, error: null,
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);
},
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);
},
get redeemedPercentage() {
return 100 - this.issuedPercentage;
},
async init() { async init() {
loyaltyAnalyticsLog.info('=== LOYALTY ANALYTICS PAGE INITIALIZING ==='); loyaltyAnalyticsLog.info('=== LOYALTY ANALYTICS PAGE INITIALIZING ===');
if (window._loyaltyAnalyticsInitialized) return; if (window._loyaltyAnalyticsInitialized) return;
window._loyaltyAnalyticsInitialized = true; window._loyaltyAnalyticsInitialized = true;
// IMPORTANT: Call parent init first to set storeCode from URL // Call parent init to set storeCode from URL
const parentInit = data().init; const parentInit = data().init;
if (parentInit) { if (parentInit) {
await parentInit.call(this); await parentInit.call(this);
@@ -70,7 +86,8 @@ function storeLoyaltyAnalytics() {
points_issued_30d: response.points_issued_30d || 0, points_issued_30d: response.points_issued_30d || 0,
points_redeemed_30d: response.points_redeemed_30d || 0, points_redeemed_30d: response.points_redeemed_30d || 0,
transactions_30d: response.transactions_30d || 0, transactions_30d: response.transactions_30d || 0,
avg_points_per_member: response.avg_points_per_member || 0 avg_points_per_member: response.avg_points_per_member || 0,
estimated_liability_cents: response.estimated_liability_cents || 0,
}; };
loyaltyAnalyticsLog.info('Stats loaded'); loyaltyAnalyticsLog.info('Stats loaded');
} }
@@ -83,7 +100,8 @@ function storeLoyaltyAnalytics() {
}, },
formatNumber(num) { formatNumber(num) {
return num == null ? '0' : new Intl.NumberFormat('en-US').format(num); if (num === null || num === undefined) return '0';
return new Intl.NumberFormat('en-US').format(num);
} }
}; };
} }

View File

@@ -1,14 +1,43 @@
{# app/modules/loyalty/templates/loyalty/admin/analytics.html #} {# app/modules/loyalty/templates/loyalty/admin/analytics.html #}
{% extends "admin/base.html" %} {% extends "admin/base.html" %}
{% from 'shared/macros/headers.html' import page_header %} {% from 'shared/macros/headers.html' import page_header_flex, refresh_button %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %} {% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/inputs.html' import search_autocomplete, selected_item_display %}
{% block title %}Loyalty Analytics{% endblock %} {% block title %}Loyalty Analytics{% endblock %}
{% block alpine_data %}adminLoyaltyAnalytics(){% endblock %} {% block alpine_data %}adminLoyaltyAnalytics(){% endblock %}
{% block content %} {% block content %}
{{ page_header('Loyalty Analytics') }} {% call page_header_flex(title='Loyalty Analytics', subtitle='Platform-wide loyalty program statistics') %}
<div class="flex items-center gap-3">
{{ refresh_button(loading_var='loading', onclick='loadStats()', variant='secondary') }}
</div>
{% endcall %}
<!-- Merchant Filter -->
<div class="mb-6 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">Filter by Merchant</label>
<div x-show="!selectedMerchant">
{{ search_autocomplete(
search_var='merchantSearch',
results_var='merchantResults',
show_dropdown_var='showMerchantDropdown',
loading_var='searchingMerchants',
search_action='searchMerchants()',
select_action='selectMerchant(item)',
display_field='merchant_name',
secondary_field='loyalty_type',
placeholder='Search merchants by name...',
) }}
</div>
{{ selected_item_display(
selected_var='selectedMerchant',
display_field='merchant_name',
clear_action='clearMerchantFilter()',
label='Showing stats for:'
) }}
</div>
{{ loading_state('Loading analytics...') }} {{ loading_state('Loading analytics...') }}
@@ -16,131 +45,14 @@
<!-- Analytics Dashboard --> <!-- Analytics Dashboard -->
<div x-show="!loading"> <div x-show="!loading">
<!-- Summary Stats --> {% set show_programs_card = true %}
<div class="grid gap-6 mb-8 md:grid-cols-2 xl:grid-cols-4"> {% set show_locations = true %}
<!-- Total Programs --> {% set show_merchants_metric = true %}
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800"> {% include "loyalty/shared/analytics-stats.html" %}
<div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
<span x-html="$icon('gift', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Total Programs
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.total_programs)">
0
</p>
<p class="text-xs text-gray-500 dark:text-gray-400">
<span x-text="stats.active_programs"></span> active
</p>
</div>
</div>
<!-- Total Members --> <!-- Quick Actions -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
<span x-html="$icon('users', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Total Members
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.total_cards)">
0
</p>
<p class="text-xs text-gray-500 dark:text-gray-400">
<span x-text="formatNumber(stats.active_cards)"></span> active
</p>
</div>
</div>
<!-- Points Issued (30d) -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
<span x-html="$icon('trending-up', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Points Issued (30d)
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.points_issued_30d)">
0
</p>
</div>
</div>
<!-- Points Redeemed (30d) -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
<span x-html="$icon('shopping-cart', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Points Redeemed (30d)
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.points_redeemed_30d)">
0
</p>
</div>
</div>
</div>
<!-- Activity Metrics -->
<div class="grid gap-6 mb-8 md:grid-cols-2">
<!-- Transactions Overview -->
<div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800"> <div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200"> <h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">Quick Actions</h3>
<span x-html="$icon('chart-bar', 'inline w-5 h-5 mr-2')"></span>
Transaction Activity (30 Days)
</h3>
<div class="space-y-4">
<div class="flex items-center justify-between">
<span class="text-sm text-gray-600 dark:text-gray-400">Total Transactions</span>
<span class="font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.transactions_30d)">0</span>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-gray-600 dark:text-gray-400">Merchants with Programs</span>
<span class="font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.merchants_with_programs)">0</span>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-gray-600 dark:text-gray-400">Redemption Rate</span>
<span class="font-semibold text-gray-700 dark:text-gray-200" x-text="redemptionRate + '%'">0%</span>
</div>
</div>
</div>
<!-- Points Balance Overview -->
<div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
<span x-html="$icon('currency-dollar', 'inline w-5 h-5 mr-2')"></span>
Points Overview
</h3>
<div class="space-y-4">
<div>
<div class="flex items-center justify-between mb-1">
<span class="text-sm text-gray-600 dark:text-gray-400">Points Issued vs Redeemed (30d)</span>
</div>
<div class="w-full bg-gray-200 rounded-full h-4 dark:bg-gray-700">
<div class="h-4 rounded-full flex">
<div class="bg-green-500 rounded-l-full" :style="'width: ' + issuedPercentage + '%'"></div>
<div class="bg-orange-500 rounded-r-full" :style="'width: ' + redeemedPercentage + '%'"></div>
</div>
</div>
<div class="flex justify-between mt-2 text-xs text-gray-500 dark:text-gray-400">
<span><span class="inline-block w-3 h-3 bg-green-500 rounded-full mr-1"></span>Issued: <span x-text="formatNumber(stats.points_issued_30d)"></span></span>
<span><span class="inline-block w-3 h-3 bg-orange-500 rounded-full mr-1"></span>Redeemed: <span x-text="formatNumber(stats.points_redeemed_30d)"></span></span>
</div>
</div>
</div>
</div>
</div>
<!-- Quick Links -->
<div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
<span x-html="$icon('link', 'inline w-5 h-5 mr-2')"></span>
Quick Links
</h3>
<div class="flex flex-wrap gap-3"> <div class="flex flex-wrap gap-3">
<a href="/admin/loyalty/programs" <a href="/admin/loyalty/programs"
class="inline-flex items-center px-4 py-2 text-sm font-medium text-purple-600 bg-purple-100 rounded-lg hover:bg-purple-200 dark:text-purple-300 dark:bg-purple-900/30 dark:hover:bg-purple-900/50"> class="inline-flex items-center px-4 py-2 text-sm font-medium text-purple-600 bg-purple-100 rounded-lg hover:bg-purple-200 dark:text-purple-300 dark:bg-purple-900/30 dark:hover:bg-purple-900/50">

View File

@@ -1,129 +1,65 @@
{# app/modules/loyalty/templates/loyalty/merchant/analytics.html #} {# app/modules/loyalty/templates/loyalty/merchant/analytics.html #}
{% extends "merchant/base.html" %} {% extends "merchant/base.html" %}
{% from 'shared/macros/headers.html' import page_header_flex, refresh_button %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% block title %}Loyalty Analytics{% endblock %} {% block title %}Loyalty Analytics{% endblock %}
{% block content %} {% block alpine_data %}merchantLoyaltyAnalytics(){% endblock %}
<div x-data="merchantLoyaltyAnalytics()">
<!-- Page Header --> {% block content %}
<div class="mb-8 mt-6 flex items-center justify-between"> {% call page_header_flex(title='Loyalty Analytics', subtitle='Loyalty program statistics across all your stores') %}
<div> <div class="flex items-center gap-3">
<h2 class="text-2xl font-bold text-gray-900 dark:text-gray-100">Loyalty Analytics</h2> {{ refresh_button(loading_var='loading', onclick='loadStats()', variant='secondary') }}
<p class="mt-1 text-gray-500 dark:text-gray-400">Loyalty program statistics across all your stores.</p>
</div>
</div> </div>
{% endcall %}
{{ loading_state('Loading analytics...') }}
{{ error_state('Error loading analytics') }}
<!-- No Program State --> <!-- No Program State -->
<template x-if="!stats.program_id && !loading"> <div x-show="!loading && !program" class="mb-6 px-4 py-5 bg-yellow-50 border border-yellow-200 rounded-lg dark:bg-yellow-900/20 dark:border-yellow-800">
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-12 text-center"> <div class="flex items-start">
<span x-html="$icon('gift', 'w-12 h-12 mx-auto text-gray-400')"></span> <span x-html="$icon('gift', 'w-6 h-6 text-yellow-500 mr-3 flex-shrink-0')"></span>
<h3 class="mt-4 text-lg font-medium text-gray-900 dark:text-white">No Loyalty Program</h3> <div>
<p class="mt-2 text-gray-500 dark:text-gray-400"> <h3 class="text-sm font-semibold text-yellow-800 dark:text-yellow-200">No Loyalty Program</h3>
Set up a loyalty program to see analytics here. <p class="mt-1 text-sm text-yellow-700 dark:text-yellow-300">Set up a loyalty program to see analytics here.</p>
</p>
<a href="/merchants/loyalty/program/edit" <a href="/merchants/loyalty/program/edit"
class="inline-flex items-center mt-4 px-6 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700"> class="mt-3 inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-yellow-600 rounded-lg hover:bg-yellow-700">
<span x-html="$icon('plus', 'w-4 h-4 mr-2')"></span> <span x-html="$icon('plus', 'w-4 h-4 mr-2')"></span>
Create Program Create Program
</a> </a>
</div> </div>
</template>
<!-- Stats Cards -->
<template x-if="stats.program_id || loading">
<div>
<div class="grid gap-6 mb-8 md:grid-cols-2 xl:grid-cols-4">
<!-- Total Cards -->
<div class="flex items-center p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
<div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
<span x-html="$icon('identification', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Total Cards</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.total_cards || 0"></p>
</div> </div>
</div> </div>
<!-- Active Cards --> <!-- Analytics Dashboard -->
<div class="flex items-center p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700"> <div x-show="!loading && program">
<div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500"> {% set show_programs_card = false %}
<span x-html="$icon('check-circle', 'w-5 h-5')"></span> {% set show_locations = true %}
</div> {% set show_merchants_metric = false %}
<div> {% include "loyalty/shared/analytics-stats.html" %}
<p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Active Cards</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.active_cards || 0"></p>
</div>
</div>
<!-- Points Issued (30d) --> <!-- Quick Actions -->
<div class="flex items-center p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700"> <div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800">
<div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500"> <h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">Quick Actions</h3>
<span x-html="$icon('arrow-trending-up', 'w-5 h-5')"></span> <div class="flex flex-wrap gap-3">
</div> <a href="/merchants/loyalty/program"
<div> class="inline-flex items-center px-4 py-2 text-sm font-medium text-purple-600 bg-purple-100 rounded-lg hover:bg-purple-200 dark:text-purple-300 dark:bg-purple-900/30 dark:hover:bg-purple-900/50">
<p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Points Issued (30d)</p> <span x-html="$icon('eye', 'w-4 h-4 mr-2')"></span>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="(stats.points_issued_30d || 0).toLocaleString()"></p> View Program
</a>
<a href="/merchants/loyalty/program/edit"
class="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 bg-blue-100 rounded-lg hover:bg-blue-200 dark:text-blue-300 dark:bg-blue-900/30 dark:hover:bg-blue-900/50">
<span x-html="$icon('pencil', 'w-4 h-4 mr-2')"></span>
Edit Program
</a>
</div> </div>
</div> </div>
<!-- Transactions (30d) -->
<div class="flex items-center p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
<div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
<span x-html="$icon('receipt-percent', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-1 text-sm font-medium text-gray-600 dark:text-gray-400">Transactions (30d)</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.transactions_30d || 0"></p>
</div>
</div>
</div>
<!-- All Time Stats -->
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
<div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">All-Time Statistics</h3>
</div>
<div class="p-6">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div>
<p class="text-sm text-gray-500 dark:text-gray-400">Total Points Issued</p>
<p class="text-xl font-bold text-gray-900 dark:text-white" x-text="(stats.total_points_issued || 0).toLocaleString()"></p>
</div>
<div>
<p class="text-sm text-gray-500 dark:text-gray-400">Total Points Redeemed</p>
<p class="text-xl font-bold text-gray-900 dark:text-white" x-text="(stats.total_points_redeemed || 0).toLocaleString()"></p>
</div>
<div>
<p class="text-sm text-gray-500 dark:text-gray-400">Points Redeemed (30d)</p>
<p class="text-xl font-bold text-gray-900 dark:text-white" x-text="(stats.points_redeemed_30d || 0).toLocaleString()"></p>
</div>
<div>
<p class="text-sm text-gray-500 dark:text-gray-400">Outstanding Liability</p>
<p class="text-xl font-bold text-gray-900 dark:text-white"
x-text="'€' + ((stats.estimated_liability_cents || 0) / 100).toFixed(2)"></p>
</div>
</div>
</div>
</div>
</div>
</template>
</div> </div>
{% endblock %} {% endblock %}
{% block extra_scripts %} {% block extra_scripts %}
<script> <script defer src="{{ url_for('loyalty_static', path='merchant/js/loyalty-analytics.js') }}"></script>
function merchantLoyaltyAnalytics() {
return {
...data(),
currentPage: 'loyalty-analytics',
loading: false,
stats: {{ loyalty_stats | tojson }},
init() {
this.loadMenuConfig();
},
};
}
</script>
{% endblock %} {% endblock %}

View File

@@ -0,0 +1,203 @@
{# app/modules/loyalty/templates/loyalty/shared/analytics-stats.html #}
{#
Shared analytics stats partial. Set these variables before including:
- show_programs_card (bool): Show "Total Programs" instead of "Total Members" in first card
- show_locations (bool): Show location breakdown table
- show_merchants_metric (bool): Show "Merchants with Programs" in Member Activity
#}
<!-- Summary Stats Cards -->
<div class="grid gap-6 mb-8 md:grid-cols-2 xl:grid-cols-4">
{% if show_programs_card %}
<!-- Total Programs (admin) -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
<span x-html="$icon('gift', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Total Programs</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.total_programs)">0</p>
<p class="text-xs text-gray-500 dark:text-gray-400">
<span x-text="stats.active_programs"></span> active
</p>
</div>
</div>
{% else %}
<!-- Total Members -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
<span x-html="$icon('users', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Total Members</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.total_cards)">0</p>
<p class="text-xs text-gray-500 dark:text-gray-400">
<span x-text="formatNumber(stats.active_cards)"></span> active
</p>
</div>
</div>
{% endif %}
<!-- Active Members -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
<span x-html="$icon('check-circle', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
{% if show_programs_card %}Total Members{% else %}Active Members{% endif %}
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200"
x-text="formatNumber({% if show_programs_card %}stats.total_cards{% else %}stats.active_cards{% endif %})">0</p>
</div>
</div>
<!-- Points Issued (30d) -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
<span x-html="$icon('trending-up', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Points Issued (30d)</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.points_issued_30d)">0</p>
</div>
</div>
<!-- Transactions (30d) -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
<span x-html="$icon('chart-bar', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Transactions (30d)</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.transactions_30d)">0</p>
</div>
</div>
</div>
<!-- Activity Metrics (2-col) -->
<div class="grid gap-6 mb-8 md:grid-cols-2">
<!-- Points Overview -->
<div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
<span x-html="$icon('currency-dollar', 'inline w-5 h-5 mr-2')"></span>
Points Overview
</h3>
<div class="space-y-4">
<!-- Progress bar: Issued vs Redeemed (30d) -->
<div>
<div class="flex items-center justify-between mb-1">
<span class="text-sm text-gray-600 dark:text-gray-400">Points Issued vs Redeemed (30d)</span>
</div>
<div class="w-full bg-gray-200 rounded-full h-4 dark:bg-gray-700">
<div class="h-4 rounded-full flex">
<div class="bg-green-500 rounded-l-full" :style="'width: ' + issuedPercentage + '%'"></div>
<div class="bg-orange-500 rounded-r-full" :style="'width: ' + redeemedPercentage + '%'"></div>
</div>
</div>
<div class="flex justify-between mt-2 text-xs text-gray-500 dark:text-gray-400">
<span><span class="inline-block w-3 h-3 bg-green-500 rounded-full mr-1"></span>Issued: <span x-text="formatNumber(stats.points_issued_30d)"></span></span>
<span><span class="inline-block w-3 h-3 bg-orange-500 rounded-full mr-1"></span>Redeemed: <span x-text="formatNumber(stats.points_redeemed_30d)"></span></span>
</div>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-gray-600 dark:text-gray-400">Redemption Rate</span>
<span class="font-semibold text-gray-700 dark:text-gray-200" x-text="redemptionRate + '%'">0%</span>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-gray-600 dark:text-gray-400">Outstanding Balance</span>
<span class="font-semibold text-purple-600 dark:text-purple-400" x-text="formatNumber(stats.total_points_balance || 0)">0</span>
</div>
</div>
</div>
<!-- Member Activity -->
<div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
<span x-html="$icon('users', 'inline w-5 h-5 mr-2')"></span>
Member Activity
</h3>
<div class="space-y-4">
<div class="flex items-center justify-between">
<span class="text-sm text-gray-600 dark:text-gray-400">Active Members (30d)</span>
<span class="font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.active_cards)">0</span>
</div>
<div class="flex items-center justify-between">
<span class="text-sm text-gray-600 dark:text-gray-400">New This Month</span>
<span class="font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.new_this_month || 0)">0</span>
</div>
{% if show_merchants_metric %}
<div class="flex items-center justify-between">
<span class="text-sm text-gray-600 dark:text-gray-400">Merchants with Programs</span>
<span class="font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.merchants_with_programs || 0)">0</span>
</div>
{% else %}
<div class="flex items-center justify-between">
<span class="text-sm text-gray-600 dark:text-gray-400">Avg Points Per Member</span>
<span class="font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.avg_points_per_member || 0)">0</span>
</div>
{% endif %}
</div>
</div>
</div>
<!-- All-Time Statistics -->
<div class="mb-8 bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden">
<div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">All-Time Statistics</h3>
</div>
<div class="p-6">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div>
<p class="text-sm text-gray-500 dark:text-gray-400">Total Points Issued</p>
<p class="text-xl font-bold text-gray-900 dark:text-white" x-text="formatNumber(stats.total_points_issued || 0)">0</p>
</div>
<div>
<p class="text-sm text-gray-500 dark:text-gray-400">Total Points Redeemed</p>
<p class="text-xl font-bold text-gray-900 dark:text-white" x-text="formatNumber(stats.total_points_redeemed || 0)">0</p>
</div>
<div>
<p class="text-sm text-gray-500 dark:text-gray-400">Points Redeemed (30d)</p>
<p class="text-xl font-bold text-gray-900 dark:text-white" x-text="formatNumber(stats.points_redeemed_30d || 0)">0</p>
</div>
<div>
<p class="text-sm text-gray-500 dark:text-gray-400">Outstanding Liability</p>
<p class="text-xl font-bold text-gray-900 dark:text-white"
x-text="'&euro;' + ((stats.estimated_liability_cents || 0) / 100).toFixed(2)">0</p>
</div>
</div>
</div>
</div>
<!-- Location Breakdown -->
{% if show_locations %}
<div x-show="locations && locations.length > 0" class="mb-8 bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden">
<div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Location Breakdown</h3>
</div>
<div class="overflow-x-auto">
<table class="w-full whitespace-nowrap">
<thead>
<tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
<th class="px-4 py-3">Store</th>
<th class="px-4 py-3">Enrolled</th>
<th class="px-4 py-3">Points Earned</th>
<th class="px-4 py-3">Points Redeemed</th>
<th class="px-4 py-3">Transactions (30d)</th>
</tr>
</thead>
<tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
<template x-for="loc in locations" :key="loc.store_id">
<tr class="text-gray-700 dark:text-gray-400">
<td class="px-4 py-3 text-sm font-medium" x-text="loc.store_name"></td>
<td class="px-4 py-3 text-sm" x-text="formatNumber(loc.enrolled_count)"></td>
<td class="px-4 py-3 text-sm" x-text="formatNumber(loc.points_earned)"></td>
<td class="px-4 py-3 text-sm" x-text="formatNumber(loc.points_redeemed)"></td>
<td class="px-4 py-3 text-sm" x-text="formatNumber(loc.transactions_30d)"></td>
</tr>
</template>
</tbody>
</table>
</div>
</div>
{% endif %}

View File

@@ -37,112 +37,31 @@
</div> </div>
</div> </div>
<!-- Analytics Dashboard -->
<div x-show="!loading && program"> <div x-show="!loading && program">
<!-- Summary Stats --> {% set show_programs_card = false %}
<div class="grid gap-6 mb-8 md:grid-cols-2 xl:grid-cols-4"> {% set show_locations = false %}
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800"> {% set show_merchants_metric = false %}
<div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500"> {% include "loyalty/shared/analytics-stats.html" %}
<span x-html="$icon('users', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Total Members</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.total_cards)">0</p>
</div>
</div>
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
<span x-html="$icon('trending-up', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Points Issued (30d)</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.points_issued_30d)">0</p>
</div>
</div>
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
<span x-html="$icon('gift', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Points Redeemed (30d)</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.points_redeemed_30d)">0</p>
</div>
</div>
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
<span x-html="$icon('chart-bar', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Transactions (30d)</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.transactions_30d)">0</p>
</div>
</div>
</div>
<!-- Detailed Metrics --> <!-- Quick Actions -->
<div class="grid gap-6 mb-8 md:grid-cols-2">
<!-- Points Overview -->
<div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
<span x-html="$icon('currency-dollar', 'inline w-5 h-5 mr-2')"></span>
Points Overview
</h3>
<div class="space-y-4">
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Total Points Issued (All Time)</span>
<span class="font-semibold" x-text="formatNumber(stats.total_points_issued)">0</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Total Points Redeemed</span>
<span class="font-semibold" x-text="formatNumber(stats.total_points_redeemed)">0</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Outstanding Balance</span>
<span class="font-semibold text-purple-600" x-text="formatNumber(stats.total_points_balance)">0</span>
</div>
</div>
</div>
<!-- Member Activity -->
<div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
<span x-html="$icon('users', 'inline w-5 h-5 mr-2')"></span>
Member Activity
</h3>
<div class="space-y-4">
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Active Members (30d)</span>
<span class="font-semibold" x-text="formatNumber(stats.active_cards)">0</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">New This Month</span>
<span class="font-semibold" x-text="formatNumber(stats.new_this_month)">0</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Avg Points Per Member</span>
<span class="font-semibold" x-text="formatNumber(stats.avg_points_per_member)">0</span>
</div>
</div>
</div>
</div>
<!-- Quick Links -->
<div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800"> <div class="px-4 py-5 bg-white rounded-lg shadow-md dark:bg-gray-800">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">Quick Actions</h3> <h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">Quick Actions</h3>
<div class="flex flex-wrap gap-3"> <div class="flex flex-wrap gap-3">
<a href="/store/{{ store_code }}/loyalty/terminal" <a href="/store/{{ store_code }}/loyalty/terminal"
class="flex items-center px-4 py-2 text-sm font-medium text-purple-600 bg-purple-50 rounded-lg hover:bg-purple-100 dark:bg-purple-900/20 dark:text-purple-400"> class="inline-flex items-center px-4 py-2 text-sm font-medium text-purple-600 bg-purple-100 rounded-lg hover:bg-purple-200 dark:text-purple-300 dark:bg-purple-900/30 dark:hover:bg-purple-900/50">
<span x-html="$icon('device-tablet', 'w-4 h-4 mr-2')"></span> <span x-html="$icon('device-tablet', 'w-4 h-4 mr-2')"></span>
Open Terminal Open Terminal
</a> </a>
<a href="/store/{{ store_code }}/loyalty/cards" <a href="/store/{{ store_code }}/loyalty/cards"
class="flex items-center px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 dark:bg-blue-900/20 dark:text-blue-400"> class="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 bg-blue-100 rounded-lg hover:bg-blue-200 dark:text-blue-300 dark:bg-blue-900/30 dark:hover:bg-blue-900/50">
<span x-html="$icon('users', 'w-4 h-4 mr-2')"></span> <span x-html="$icon('users', 'w-4 h-4 mr-2')"></span>
View Members View Members
</a> </a>
<a href="/store/{{ store_code }}/loyalty/program" <a href="/store/{{ store_code }}/loyalty/program"
class="flex items-center px-4 py-2 text-sm font-medium text-gray-600 bg-gray-50 rounded-lg hover:bg-gray-100 dark:bg-gray-700 dark:text-gray-400"> class="inline-flex items-center px-4 py-2 text-sm font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 dark:text-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600">
<span x-html="$icon('cog', 'w-4 h-4 mr-2')"></span> <span x-html="$icon('eye', 'w-4 h-4 mr-2')"></span>
Program View Program
</a> </a>
</div> </div>
</div> </div>