Add pagination to Customer Insights top customers list

Implemented pagination controls and page size selection for the top customers section in CustomerInsightsChart. Updated analytics-service to support paginated customer insights API calls and handle pagination metadata. Improves usability for stores with large customer bases.
This commit is contained in:
NotII
2025-08-30 21:07:00 +01:00
parent 57502d09bc
commit fabc8f2d71
4 changed files with 119 additions and 28 deletions

View File

@@ -3,9 +3,11 @@
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { Skeleton } from "@/components/ui/skeleton";
import { Users, Crown, UserPlus, UserCheck, Star } from "lucide-react";
import { Users, Crown, UserPlus, UserCheck, Star, ChevronLeft, ChevronRight } from "lucide-react";
import { getCustomerInsightsWithStore, type CustomerInsights } from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format";
import { CustomerInsightsSkeleton } from './SkeletonLoaders';
@@ -14,6 +16,8 @@ export default function CustomerInsightsChart() {
const [data, setData] = useState<CustomerInsights | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const { toast } = useToast();
useEffect(() => {
@@ -21,7 +25,7 @@ export default function CustomerInsightsChart() {
try {
setIsLoading(true);
setError(null);
const response = await getCustomerInsightsWithStore();
const response = await getCustomerInsightsWithStore(currentPage, pageSize);
setData(response);
} catch (err) {
console.error('Error fetching customer insights:', err);
@@ -37,7 +41,7 @@ export default function CustomerInsightsChart() {
};
fetchCustomerData();
}, [toast]);
}, [toast, currentPage, pageSize]);
const getSegmentColor = (segment: string) => {
switch (segment) {
@@ -116,6 +120,15 @@ export default function CustomerInsightsChart() {
const segments = Object.entries(data.segments);
const totalCustomers = data.totalCustomers;
const handlePageChange = (newPage: number) => {
setCurrentPage(newPage);
};
const handlePageSizeChange = (newPageSize: string) => {
setPageSize(parseInt(newPageSize));
setCurrentPage(1); // Reset to first page when changing page size
};
return (
<div className="space-y-6">
{/* Customer Overview */}
@@ -194,6 +207,11 @@ export default function CustomerInsightsChart() {
</CardTitle>
<CardDescription>
Your highest-spending customers
{data.pagination && (
<span className="ml-2 text-sm">
(Showing {data.pagination.startIndex}-{data.pagination.endIndex} of {data.pagination.totalCustomers})
</span>
)}
</CardDescription>
</CardHeader>
<CardContent>
@@ -203,12 +221,15 @@ export default function CustomerInsightsChart() {
<p className="text-muted-foreground">No customer data available</p>
</div>
) : (
<>
<div className="space-y-4">
{data.topCustomers.map((customer, index) => (
{data.topCustomers.map((customer, index) => {
const globalRank = data.pagination ? (data.pagination.currentPage - 1) * data.pagination.limit + index + 1 : index + 1;
return (
<div key={customer._id} className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<div className="flex items-center justify-center w-8 h-8 bg-primary text-primary-foreground rounded-full text-sm font-bold">
{index + 1}
{globalRank}
</div>
<div>
<div className="font-medium">{customer.displayName || `Customer #${customer._id.slice(-6)}`}</div>
@@ -226,8 +247,59 @@ export default function CustomerInsightsChart() {
</div>
</div>
</div>
))}
);
})}
</div>
{/* Pagination Controls */}
{data.pagination && data.pagination.totalPages > 1 && (
<div className="mt-6 flex items-center justify-between">
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">Show</span>
<Select value={pageSize.toString()} onValueChange={handlePageSizeChange}>
<SelectTrigger className="w-20">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="20">20</SelectItem>
<SelectItem value="50">50</SelectItem>
</SelectContent>
</Select>
<span className="text-sm text-muted-foreground">customers per page</span>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => handlePageChange(currentPage - 1)}
disabled={!data.pagination.hasPrevPage || isLoading}
>
<ChevronLeft className="h-4 w-4" />
Previous
</Button>
<div className="flex items-center gap-1">
<span className="text-sm text-muted-foreground">
Page {data.pagination.currentPage} of {data.pagination.totalPages}
</span>
</div>
<Button
variant="outline"
size="sm"
onClick={() => handlePageChange(currentPage + 1)}
disabled={!data.pagination.hasNextPage || isLoading}
>
Next
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
</>
)}
</CardContent>
</Card>

View File

@@ -67,6 +67,16 @@ export interface CustomerInsights {
username?: string;
}>;
averageOrdersPerCustomer: string;
pagination?: {
currentPage: number;
totalPages: number;
totalCustomers: number;
limit: number;
hasNextPage: boolean;
hasPrevPage: boolean;
startIndex: number;
endIndex: number;
};
}
export interface OrderAnalytics {
@@ -112,9 +122,17 @@ export const getProductPerformance = async (storeId?: string): Promise<ProductPe
/**
* Get customer insights data
* @param storeId Optional storeId for staff users
* @param page Page number (default: 1)
* @param limit Number of customers per page (default: 10)
*/
export const getCustomerInsights = async (storeId?: string): Promise<CustomerInsights> => {
const url = storeId ? `/analytics/customer-insights?storeId=${storeId}` : '/analytics/customer-insights';
export const getCustomerInsights = async (storeId?: string, page: number = 1, limit: number = 10): Promise<CustomerInsights> => {
const params = new URLSearchParams({
page: page.toString(),
limit: limit.toString()
});
if (storeId) params.append('storeId', storeId);
const url = `/analytics/customer-insights?${params.toString()}`;
return clientFetch<CustomerInsights>(url);
};
@@ -162,9 +180,9 @@ export const getProductPerformanceWithStore = async (): Promise<ProductPerforman
return getProductPerformance(storeId);
};
export const getCustomerInsightsWithStore = async (): Promise<CustomerInsights> => {
export const getCustomerInsightsWithStore = async (page: number = 1, limit: number = 10): Promise<CustomerInsights> => {
const storeId = getStoreIdForUser();
return getCustomerInsights(storeId);
return getCustomerInsights(storeId, page, limit);
};
export const getOrderAnalyticsWithStore = async (period: string = '30'): Promise<OrderAnalytics> => {

View File

@@ -1,4 +1,4 @@
{
"commitHash": "6a2cd9a",
"buildTime": "2025-08-26T20:09:00.025Z"
"commitHash": "57502d0",
"buildTime": "2025-08-30T20:06:32.862Z"
}

View File

@@ -1 +1,2 @@
loaderio-4f43d28a66724ee6c044221219487237