balls :D
All checks were successful
Build Frontend / build (push) Successful in 1m6s

This commit is contained in:
g
2026-01-12 02:32:23 +00:00
parent b10e8f8939
commit 624bfa5485
3 changed files with 89 additions and 30 deletions

View File

@@ -30,6 +30,7 @@ import {
Layers, Layers,
Zap, Zap,
Info, Info,
Download,
} from "lucide-react"; } from "lucide-react";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
@@ -83,13 +84,16 @@ export default function PredictionsChart({
const [daysAhead, setDaysAhead] = useState(7); const [daysAhead, setDaysAhead] = useState(7);
const [activeTab, setActiveTab] = useState<"overview" | "stock">("overview"); const [activeTab, setActiveTab] = useState<"overview" | "stock">("overview");
const [simulationFactor, setSimulationFactor] = useState(0); const [simulationFactor, setSimulationFactor] = useState(0);
const [committedSimulationFactor, setCommittedSimulationFactor] = useState(0);
const { toast } = useToast(); const { toast } = useToast();
const fetchPredictions = async () => { const fetchPredictions = async () => {
try { try {
setLoading(true); setLoading(true);
// Convert percentage (e.g. 50) to factor (e.g. 0.5)
const factor = committedSimulationFactor / 100;
const [overview, stock] = await Promise.all([ const [overview, stock] = await Promise.all([
getPredictionsOverviewWithStore(daysAhead, timeRange), getPredictionsOverviewWithStore(daysAhead, timeRange, factor),
getStockPredictionsWithStore(timeRange), getStockPredictionsWithStore(timeRange),
]); ]);
setPredictions(overview); setPredictions(overview);
@@ -108,7 +112,7 @@ export default function PredictionsChart({
useEffect(() => { useEffect(() => {
fetchPredictions(); fetchPredictions();
}, [daysAhead, timeRange]); }, [daysAhead, timeRange, committedSimulationFactor]);
const getConfidenceColor = (confidence: string) => { const getConfidenceColor = (confidence: string) => {
switch (confidence) { switch (confidence) {
@@ -145,10 +149,41 @@ export default function PredictionsChart({
return predictions.sales.dailyPredictions.map((d) => ({ return predictions.sales.dailyPredictions.map((d) => ({
...d, ...d,
formattedDate: format(new Date(d.date), "MMM d"), formattedDate: format(new Date(d.date), "MMM d"),
value: d.predicted * (1 + simulationFactor / 100), value: d.predicted,
originalValue: d.predicted,
})); }));
}, [predictions, simulationFactor]); }, [predictions]);
const handleExportCSV = () => {
if (!simulatedData.length) return;
// Create CSV headers
const headers = ["Date", "Predicted Revenue", "Orders", "Confidence"];
// Create CSV rows
const rows = simulatedData.map(d => [
format(new Date(d.date), "yyyy-MM-dd"),
d.predicted.toFixed(2),
d.orders || "", // Provide fallback if orders is undefined
predictions?.sales?.confidence || "unknown"
]);
// Combine headers and rows
const csvContent = [
headers.join(","),
...rows.map(row => row.join(","))
].join("\n");
// Create download link
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", `predictions_export_${format(new Date(), "yyyyMMdd")}.csv`);
link.style.visibility = "hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
if (loading) { if (loading) {
return ( return (
@@ -462,8 +497,9 @@ export default function PredictionsChart({
value={[simulationFactor]} value={[simulationFactor]}
min={-50} min={-50}
max={50} max={50}
step={5} step={10}
onValueChange={(val) => setSimulationFactor(val[0])} onValueChange={(val) => setSimulationFactor(val[0])}
onValueCommit={(val) => setCommittedSimulationFactor(val[0])}
className="w-[150px] mt-1.5" className="w-[150px] mt-1.5"
/> />
</div> </div>
@@ -472,13 +508,20 @@ export default function PredictionsChart({
variant="ghost" variant="ghost"
size="icon" size="icon"
className="h-6 w-6" className="h-6 w-6"
onClick={() => setSimulationFactor(0)} onClick={() => {
setSimulationFactor(0);
setCommittedSimulationFactor(0);
}}
title="Reset simulation" title="Reset simulation"
> >
<RefreshCw className="h-3 w-3" /> <RefreshCw className="h-3 w-3" />
</Button> </Button>
)} )}
</div> </div>
<Button variant="outline" size="sm" onClick={handleExportCSV} title="Export to CSV">
<Download className="mr-2 h-4 w-4" />
Export
</Button>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="h-[300px] w-full mt-4"> <div className="h-[300px] w-full mt-4">

View File

@@ -7,7 +7,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { TrendingUp, DollarSign } from "lucide-react"; import { TrendingUp, DollarSign } from "lucide-react";
import { getRevenueTrendsWithStore, type RevenueData } from "@/lib/services/analytics-service"; import { getRevenueTrendsWithStore, type RevenueData } from "@/lib/services/analytics-service";
import { formatGBP } from "@/utils/format"; import { formatGBP } from "@/utils/format";
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar } from 'recharts'; import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, AreaChart, Area } from 'recharts';
import { ChartSkeleton } from './SkeletonLoaders'; import { ChartSkeleton } from './SkeletonLoaders';
interface RevenueChartProps { interface RevenueChartProps {
@@ -176,28 +176,40 @@ export default function RevenueChart({ timeRange, hideNumbers = false }: Revenue
{/* Chart */} {/* Chart */}
<div className="h-64"> <div className="h-64">
<ResponsiveContainer width="100%" height="100%"> <ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}> <AreaChart data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" /> <defs>
<linearGradient id="colorRevenue" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#2563eb" stopOpacity={0.8} />
<stop offset="95%" stopColor="#2563eb" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
<XAxis <XAxis
dataKey="formattedDate" dataKey="formattedDate"
tick={{ fontSize: 12 }} tick={{ fontSize: 12, fill: "hsl(var(--muted-foreground))" }}
axisLine={false}
tickLine={false}
angle={-45} angle={-45}
textAnchor="end" textAnchor="end"
height={60} height={60}
minTickGap={30}
/> />
<YAxis <YAxis
tick={{ fontSize: 12 }} tick={{ fontSize: 12, fill: "hsl(var(--muted-foreground))" }}
axisLine={false}
tickLine={false}
tickFormatter={(value) => hideNumbers ? '***' : `£${(value / 1000).toFixed(0)}k`} tickFormatter={(value) => hideNumbers ? '***' : `£${(value / 1000).toFixed(0)}k`}
/> />
<Tooltip content={<CustomTooltip />} /> <Tooltip content={<CustomTooltip />} cursor={{ fill: "transparent", stroke: "hsl(var(--muted-foreground))", strokeDasharray: "3 3" }} />
<Bar <Area
type="monotone"
dataKey="revenue" dataKey="revenue"
fill="#2563eb" stroke="#2563eb"
stroke="#1d4ed8" fillOpacity={1}
strokeWidth={1} fill="url(#colorRevenue)"
radius={[2, 2, 0, 0]} strokeWidth={2}
/> />
</BarChart> </AreaChart>
</ResponsiveContainer> </ResponsiveContainer>
</div> </div>

View File

@@ -494,15 +494,18 @@ export const getStockPredictions = async (
* @param daysAhead Number of days to predict ahead (default: 7) * @param daysAhead Number of days to predict ahead (default: 7)
* @param period Historical period in days (default: 30) * @param period Historical period in days (default: 30)
* @param storeId Optional storeId for staff users * @param storeId Optional storeId for staff users
* @param simulation Simulation factor (e.g. 0.1 for +10%)
*/ */
export const getPredictionsOverview = async ( export const getPredictionsOverview = async (
daysAhead: number = 7, daysAhead: number = 7,
period: number = 30, period: number = 30,
storeId?: string, storeId?: string,
simulation: number = 0,
): Promise<PredictionsOverview> => { ): Promise<PredictionsOverview> => {
const params = new URLSearchParams({ const params = new URLSearchParams({
daysAhead: daysAhead.toString(), daysAhead: daysAhead.toString(),
period: period.toString(), period: period.toString(),
simulation: simulation.toString(),
}); });
if (storeId) params.append("storeId", storeId); if (storeId) params.append("storeId", storeId);
@@ -538,7 +541,8 @@ export const getStockPredictionsWithStore = async (
export const getPredictionsOverviewWithStore = async ( export const getPredictionsOverviewWithStore = async (
daysAhead: number = 7, daysAhead: number = 7,
period: number = 30, period: number = 30,
simulation: number = 0,
): Promise<PredictionsOverview> => { ): Promise<PredictionsOverview> => {
const storeId = getStoreIdForUser(); const storeId = getStoreIdForUser();
return getPredictionsOverview(daysAhead, period, storeId); return getPredictionsOverview(daysAhead, period, storeId, simulation);
}; };