Add custom date range support to profit analytics

Introduces a date range picker to the profit analytics dashboard, allowing users to select custom date ranges for profit calculations. Updates ProfitAnalyticsChart and profit-analytics-service to handle both period and date range queries, improving flexibility and user experience.
This commit is contained in:
g
2025-11-28 18:32:38 +00:00
parent 28e292abb3
commit b10b2f2701
5 changed files with 98 additions and 14 deletions

View File

@@ -1,3 +1,4 @@
# Disable telemetry for faster builds # Disable telemetry for faster builds
NEXT_TELEMETRY_DISABLED=1 NEXT_TELEMETRY_DISABLED=1
@@ -11,4 +12,4 @@ NEXT_LOG_LEVEL=error
GENERATE_SOURCEMAP=false GENERATE_SOURCEMAP=false
# API configuration # API configuration
SERVER_API_URL=https://internal-api.inboxi.ng/api SERVER_API_URL=https://internal-api.inboxi.ng/api

View File

@@ -27,6 +27,10 @@ import { formatGBP } from "@/utils/format";
import { MetricsCardSkeleton } from './SkeletonLoaders'; import { MetricsCardSkeleton } from './SkeletonLoaders';
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
import { DateRangePicker } from "@/components/ui/date-picker";
import { DateRange } from "react-day-picker";
import { addDays, startOfDay, endOfDay } from "date-fns";
import type { DateRange as ProfitDateRange } from "@/lib/services/profit-analytics-service";
// Lazy load chart components // Lazy load chart components
const RevenueChart = dynamic(() => import('./RevenueChart'), { const RevenueChart = dynamic(() => import('./RevenueChart'), {
@@ -78,6 +82,10 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [timeRange, setTimeRange] = useState('30'); const [timeRange, setTimeRange] = useState('30');
const [hideNumbers, setHideNumbers] = useState(false); const [hideNumbers, setHideNumbers] = useState(false);
const [profitDateRange, setProfitDateRange] = useState<DateRange | undefined>({
from: startOfDay(addDays(new Date(), -29)),
to: endOfDay(new Date())
});
const { toast } = useToast(); const { toast } = useToast();
// Function to mask sensitive numbers // Function to mask sensitive numbers
@@ -302,8 +310,41 @@ export default function AnalyticsDashboard({ initialData }: AnalyticsDashboardPr
</TabsContent> </TabsContent>
<TabsContent value="profit" className="space-y-6"> <TabsContent value="profit" className="space-y-6">
{/* Date Range Selector for Profit Calculator */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Date Range</CardTitle>
<CardDescription>
Select a custom date range for profit calculations
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-col sm:flex-row gap-4 sm:items-center">
<DateRangePicker
dateRange={profitDateRange}
onDateRangeChange={setProfitDateRange}
placeholder="Select date range"
showPresets={true}
className="w-full sm:w-auto"
/>
{profitDateRange?.from && profitDateRange?.to && (
<div className="text-sm text-muted-foreground flex items-center">
<span>
{profitDateRange.from.toLocaleDateString()} - {profitDateRange.to.toLocaleDateString()}
</span>
</div>
)}
</div>
</CardContent>
</Card>
<Suspense fallback={<ChartSkeleton />}> <Suspense fallback={<ChartSkeleton />}>
<ProfitAnalyticsChart timeRange={timeRange} hideNumbers={hideNumbers} /> <ProfitAnalyticsChart
dateRange={profitDateRange?.from && profitDateRange?.to ? {
from: profitDateRange.from,
to: profitDateRange.to
} : undefined}
hideNumbers={hideNumbers}
/>
</Suspense> </Suspense>
</TabsContent> </TabsContent>

View File

@@ -15,15 +15,16 @@ import {
} from "lucide-react"; } from "lucide-react";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { formatGBP } from "@/utils/format"; import { formatGBP } from "@/utils/format";
import { getProfitOverview, type ProfitOverview } from "@/lib/services/profit-analytics-service"; import { getProfitOverview, type ProfitOverview, type DateRange } from "@/lib/services/profit-analytics-service";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
interface ProfitAnalyticsChartProps { interface ProfitAnalyticsChartProps {
timeRange: string; timeRange?: string;
dateRange?: DateRange;
hideNumbers?: boolean; hideNumbers?: boolean;
} }
export default function ProfitAnalyticsChart({ timeRange, hideNumbers = false }: ProfitAnalyticsChartProps) { export default function ProfitAnalyticsChart({ timeRange, dateRange, hideNumbers = false }: ProfitAnalyticsChartProps) {
const [data, setData] = useState<ProfitOverview | null>(null); const [data, setData] = useState<ProfitOverview | null>(null);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -44,7 +45,8 @@ export default function ProfitAnalyticsChart({ timeRange, hideNumbers = false }:
try { try {
setIsLoading(true); setIsLoading(true);
setError(null); setError(null);
const response = await getProfitOverview(timeRange); // Use dateRange if provided, otherwise fall back to timeRange
const response = await getProfitOverview(dateRange || timeRange || '30');
setData(response); setData(response);
} catch (error) { } catch (error) {
console.error('Error fetching profit data:', error); console.error('Error fetching profit data:', error);
@@ -60,7 +62,7 @@ export default function ProfitAnalyticsChart({ timeRange, hideNumbers = false }:
}; };
fetchData(); fetchData();
}, [timeRange, toast]); }, [timeRange, dateRange, toast]);
if (isLoading) { if (isLoading) {
return ( return (
@@ -304,7 +306,10 @@ export default function ProfitAnalyticsChart({ timeRange, hideNumbers = false }:
Most Profitable Products Most Profitable Products
</CardTitle> </CardTitle>
<CardDescription> <CardDescription>
Products generating the highest total profit (last {timeRange} days) {dateRange
? `Products generating the highest total profit (${new Date(dateRange.from).toLocaleDateString()} - ${new Date(dateRange.to).toLocaleDateString()})`
: `Products generating the highest total profit (last ${timeRange || '30'} days)`
}
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>

View File

@@ -2,6 +2,8 @@ import { apiRequest } from '../api';
export interface ProfitOverview { export interface ProfitOverview {
period: string; period: string;
startDate?: string;
endDate?: string;
summary: { summary: {
totalRevenue: number; totalRevenue: number;
revenueFromTrackedProducts: number; revenueFromTrackedProducts: number;
@@ -40,10 +42,45 @@ export interface ProfitTrend {
profitMargin: number; profitMargin: number;
} }
export const getProfitOverview = async (period: string = '30'): Promise<ProfitOverview> => { export interface DateRange {
return apiRequest(`/analytics/profit-overview?period=${period}`); from: Date;
to: Date;
}
export const getProfitOverview = async (
periodOrRange?: string | DateRange
): Promise<ProfitOverview> => {
let url = '/analytics/profit-overview';
if (periodOrRange && typeof periodOrRange !== 'string') {
// Date range provided
const startDate = periodOrRange.from.toISOString().split('T')[0];
const endDate = periodOrRange.to.toISOString().split('T')[0];
url += `?startDate=${startDate}&endDate=${endDate}`;
} else {
// Period provided (backward compatibility)
const period = periodOrRange || '30';
url += `?period=${period}`;
}
return apiRequest(url);
}; };
export const getProfitTrends = async (period: string = '30'): Promise<ProfitTrend[]> => { export const getProfitTrends = async (
return apiRequest(`/analytics/profit-trends?period=${period}`); periodOrRange?: string | DateRange
): Promise<ProfitTrend[]> => {
let url = '/analytics/profit-trends';
if (periodOrRange && typeof periodOrRange !== 'string') {
// Date range provided
const startDate = periodOrRange.from.toISOString().split('T')[0];
const endDate = periodOrRange.to.toISOString().split('T')[0];
url += `?startDate=${startDate}&endDate=${endDate}`;
} else {
// Period provided (backward compatibility)
const period = periodOrRange || '30';
url += `?period=${period}`;
}
return apiRequest(url);
}; };

View File

@@ -1,4 +1,4 @@
{ {
"commitHash": "928d94c", "commitHash": "28e292a",
"buildTime": "2025-10-31T00:03:09.717Z" "buildTime": "2025-11-28T18:29:50.128Z"
} }