mirror of
https://github.com/R0m1k3/LogiFlow.git
synced 2026-10-11 17:27:31 +02:00
8 files changed
+1740
-234
No files matched your search
@@ -15,10 +15,6 @@ run = ["npm", "run", "start"]
|
||||
localPort = 5000
|
||||
externalPort = 80
|
||||
|
||||
[[ports]]
|
||||
localPort = 37321
|
||||
externalPort = 3003
|
||||
|
||||
[[ports]]
|
||||
localPort = 38343
|
||||
externalPort = 3000
|
||||
|
||||
+491
-230
File diff suppressed because it is too large.
Load diff
@@ -23,6 +23,7 @@ import Tasks from "@/pages/Tasks";
|
||||
import SavTickets from "@/pages/SavTickets";
|
||||
import Avoirs from "@/pages/Avoirs";
|
||||
import WeatherSettings from "@/pages/WeatherSettings";
|
||||
import Analytics from "@/pages/Analytics";
|
||||
import Layout from "@/components/Layout";
|
||||
|
||||
function RouterProduction() {
|
||||
@@ -102,6 +103,7 @@ function RouterProduction() {
|
||||
<Route path="/tasks" component={Tasks} />
|
||||
<Route path="/sav" component={SavTickets} />
|
||||
<Route path="/avoirs" component={Avoirs} />
|
||||
<Route path="/analytics" component={Analytics} />
|
||||
|
||||
{/* Routes de compatibilité - redirection vers utilities */}
|
||||
<Route path="/backup" component={Utilities} />
|
||||
|
||||
@@ -257,6 +257,12 @@ export default function Sidebar() {
|
||||
icon: FileText,
|
||||
roles: ["admin", "directeur"]
|
||||
},
|
||||
{
|
||||
path: "/analytics",
|
||||
label: "Statistiques",
|
||||
icon: BarChart3,
|
||||
roles: ["admin", "directeur", "manager"]
|
||||
},
|
||||
{
|
||||
path: "/avoirs",
|
||||
label: "Avoirs",
|
||||
|
||||
@@ -0,0 +1,526 @@
|
||||
import { useState, useMemo } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Calendar } from "@/components/ui/calendar";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { useAuthUnified } from "@/hooks/useAuthUnified";
|
||||
import { useStore } from "@/contexts/StoreContext";
|
||||
import { CalendarIcon, Download, RefreshCw, TrendingUp, Package, Clock, Euro, Store, Truck, BarChart3, PieChart, Activity, FileDown } from "lucide-react";
|
||||
import { addDays, format, startOfMonth, endOfMonth, startOfWeek, endOfWeek, startOfYear, endOfYear } from "date-fns";
|
||||
import { fr } from "date-fns/locale";
|
||||
import { LineChart, Line, BarChart, Bar, PieChart as RechartsChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from "recharts";
|
||||
|
||||
// Couleurs pour les graphiques
|
||||
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8', '#82CA9D', '#FFC658', '#8DD1E1', '#D084D0', '#FFB3BA'];
|
||||
|
||||
export default function Analytics() {
|
||||
const { user } = useAuthUnified();
|
||||
const { selectedStoreId } = useStore();
|
||||
|
||||
// États des filtres
|
||||
const [dateRange, setDateRange] = useState({
|
||||
from: startOfMonth(new Date()),
|
||||
to: endOfMonth(new Date())
|
||||
});
|
||||
const [selectedSuppliers, setSelectedSuppliers] = useState<number[]>([]);
|
||||
const [selectedStores, setSelectedStores] = useState<number[]>([]);
|
||||
const [selectedStatus, setSelectedStatus] = useState<string[]>([]);
|
||||
const [granularity, setGranularity] = useState<'day' | 'week' | 'month'>('day');
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
|
||||
// Périodes rapides
|
||||
const quickPeriods = [
|
||||
{ label: "Aujourd'hui", value: () => ({ from: new Date(), to: new Date() }) },
|
||||
{ label: "Cette semaine", value: () => ({ from: startOfWeek(new Date(), { locale: fr }), to: endOfWeek(new Date(), { locale: fr }) }) },
|
||||
{ label: "Ce mois", value: () => ({ from: startOfMonth(new Date()), to: endOfMonth(new Date()) }) },
|
||||
{ label: "Cette année", value: () => ({ from: startOfYear(new Date()), to: endOfYear(new Date()) }) },
|
||||
{ label: "30 derniers jours", value: () => ({ from: addDays(new Date(), -30), to: new Date() }) },
|
||||
{ label: "90 derniers jours", value: () => ({ from: addDays(new Date(), -90), to: new Date() }) }
|
||||
];
|
||||
|
||||
// Construction des paramètres de requête
|
||||
const queryParams = useMemo(() => {
|
||||
const params = new URLSearchParams();
|
||||
if (dateRange.from) params.append('startDate', dateRange.from.toISOString());
|
||||
if (dateRange.to) params.append('endDate', dateRange.to.toISOString());
|
||||
if (selectedSuppliers.length) params.append('supplierIds', selectedSuppliers.join(','));
|
||||
if (selectedStores.length) params.append('groupIds', selectedStores.join(','));
|
||||
if (selectedStatus.length) params.append('status', selectedStatus.join(','));
|
||||
return params.toString();
|
||||
}, [dateRange, selectedSuppliers, selectedStores, selectedStatus]);
|
||||
|
||||
// Récupération des données
|
||||
const { data: summary, isLoading: summaryLoading } = useQuery({
|
||||
queryKey: ['/api/analytics/summary', queryParams],
|
||||
queryFn: async () => {
|
||||
const response = await fetch(`/api/analytics/summary?${queryParams}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to fetch summary');
|
||||
return response.json();
|
||||
},
|
||||
refetchInterval: isRefreshing ? 30000 : false
|
||||
});
|
||||
|
||||
const { data: timeseries } = useQuery({
|
||||
queryKey: ['/api/analytics/timeseries', queryParams, granularity],
|
||||
queryFn: async () => {
|
||||
const response = await fetch(`/api/analytics/timeseries?${queryParams}&granularity=${granularity}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to fetch timeseries');
|
||||
return response.json();
|
||||
}
|
||||
});
|
||||
|
||||
const { data: bySupplier } = useQuery({
|
||||
queryKey: ['/api/analytics/by-supplier', queryParams],
|
||||
queryFn: async () => {
|
||||
const response = await fetch(`/api/analytics/by-supplier?${queryParams}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to fetch by supplier');
|
||||
return response.json();
|
||||
}
|
||||
});
|
||||
|
||||
const { data: byStore } = useQuery({
|
||||
queryKey: ['/api/analytics/by-store', queryParams],
|
||||
queryFn: async () => {
|
||||
const response = await fetch(`/api/analytics/by-store?${queryParams}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to fetch by store');
|
||||
return response.json();
|
||||
}
|
||||
});
|
||||
|
||||
const { data: suppliers } = useQuery({
|
||||
queryKey: ['/api/suppliers'],
|
||||
});
|
||||
|
||||
const { data: stores } = useQuery({
|
||||
queryKey: ['/api/groups'],
|
||||
});
|
||||
|
||||
// Fonction d'export
|
||||
const handleExport = async (type: string) => {
|
||||
const response = await fetch(`/api/analytics/export?${queryParams}&type=${type}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
if (response.ok) {
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `analytics_${type}_${format(new Date(), 'yyyy-MM-dd')}.csv`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
window.URL.revokeObjectURL(url);
|
||||
}
|
||||
};
|
||||
|
||||
if (summaryLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
|
||||
<p className="text-gray-600">Chargement des statistiques...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{/* Header */}
|
||||
<div className="bg-white border-b p-6 -m-6 mb-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold flex items-center gap-2">
|
||||
<BarChart3 className="h-6 w-6 text-primary" />
|
||||
Tableau de bord Analytics
|
||||
</h1>
|
||||
<p className="text-gray-600 mt-1">Analysez vos performances logistiques</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setIsRefreshing(!isRefreshing)}
|
||||
className={isRefreshing ? "animate-pulse" : ""}
|
||||
>
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
{isRefreshing ? "Actualisé" : "Temps réel"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleExport('summary')}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Export CSV
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filtres */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<CalendarIcon className="h-5 w-5" />
|
||||
Filtres
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Périodes rapides */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{quickPeriods.map(period => (
|
||||
<Button
|
||||
key={period.label}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setDateRange(period.value())}
|
||||
>
|
||||
{period.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Sélecteur de dates */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
<div className="md:col-span-1">
|
||||
<label className="text-sm font-medium mb-1 block">Période</label>
|
||||
<div className="flex gap-2">
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="justify-start text-left font-normal">
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{dateRange.from ? format(dateRange.from, 'dd/MM/yyyy', { locale: fr }) : 'Date début'}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={dateRange.from}
|
||||
onSelect={(date) => date && setDateRange(prev => ({ ...prev, from: date }))}
|
||||
initialFocus
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<span className="text-gray-500 self-center">→</span>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="justify-start text-left font-normal">
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{dateRange.to ? format(dateRange.to, 'dd/MM/yyyy', { locale: fr }) : 'Date fin'}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={dateRange.to}
|
||||
onSelect={(date) => date && setDateRange(prev => ({ ...prev, to: date }))}
|
||||
initialFocus
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-1 block">Granularité</label>
|
||||
<Select value={granularity} onValueChange={(value: any) => setGranularity(value)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="day">Jour</SelectItem>
|
||||
<SelectItem value="week">Semaine</SelectItem>
|
||||
<SelectItem value="month">Mois</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-1 block">Fournisseurs</label>
|
||||
<Select
|
||||
value={selectedSuppliers.length === 0 ? "all" :
|
||||
selectedSuppliers.length === 1 ? selectedSuppliers[0].toString() : "multiple"}
|
||||
onValueChange={(value) => {
|
||||
if (value === "all") {
|
||||
setSelectedSuppliers([]);
|
||||
} else if (value !== "multiple") {
|
||||
// Basculer entre sélection unique ou multiple
|
||||
const supplierId = parseInt(value);
|
||||
if (selectedSuppliers.includes(supplierId)) {
|
||||
setSelectedSuppliers(selectedSuppliers.filter(id => id !== supplierId));
|
||||
} else {
|
||||
setSelectedSuppliers([supplierId]);
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Tous les fournisseurs" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Tous les fournisseurs</SelectItem>
|
||||
{suppliers?.map((supplier: any) => (
|
||||
<SelectItem key={supplier.id} value={supplier.id.toString()}>
|
||||
{selectedSuppliers.includes(supplier.id) ? "✓ " : ""}{supplier.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-1 block">Magasins</label>
|
||||
<Select
|
||||
value={selectedStores.length === 0 ? "all" :
|
||||
selectedStores.length === 1 ? selectedStores[0].toString() : "multiple"}
|
||||
onValueChange={(value) => {
|
||||
if (value === "all") {
|
||||
setSelectedStores([]);
|
||||
} else if (value !== "multiple") {
|
||||
// Basculer entre sélection unique ou multiple
|
||||
const storeId = parseInt(value);
|
||||
if (selectedStores.includes(storeId)) {
|
||||
setSelectedStores(selectedStores.filter(id => id !== storeId));
|
||||
} else {
|
||||
setSelectedStores([storeId]);
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Tous les magasins" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Tous les magasins</SelectItem>
|
||||
{stores?.map((store: any) => (
|
||||
<SelectItem key={store.id} value={store.id.toString()}>
|
||||
{selectedStores.includes(store.id) ? "✓ " : ""}{store.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* KPIs */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-medium text-gray-600">
|
||||
Commandes totales
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-2xl font-bold">{summary?.totalOrders || 0}</div>
|
||||
<Package className="h-8 w-8 text-blue-500 opacity-50" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-medium text-gray-600">
|
||||
Livraisons totales
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-2xl font-bold">{summary?.totalDeliveries || 0}</div>
|
||||
<Truck className="h-8 w-8 text-green-500 opacity-50" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-medium text-gray-600">
|
||||
Taux de ponctualité
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-2xl font-bold">
|
||||
{summary?.onTimeRate ? `${summary.onTimeRate.toFixed(1)}%` : '0%'}
|
||||
</div>
|
||||
<Clock className="h-8 w-8 text-orange-500 opacity-50" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-medium text-gray-600">
|
||||
Montant total
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-2xl font-bold">
|
||||
{summary?.totalAmount ? `${summary.totalAmount.toFixed(2)}€` : '0€'}
|
||||
</div>
|
||||
<Euro className="h-8 w-8 text-purple-500 opacity-50" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Graphiques */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Évolution temporelle */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Activity className="h-5 w-5" />
|
||||
Évolution temporelle
|
||||
</CardTitle>
|
||||
<CardDescription>Commandes vs Livraisons</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<LineChart data={timeseries || []}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="date" />
|
||||
<YAxis />
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
<Line type="monotone" dataKey="orders" stroke="#8884d8" name="Commandes" />
|
||||
<Line type="monotone" dataKey="deliveries" stroke="#82ca9d" name="Livraisons" />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Répartition par fournisseur */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<PieChart className="h-5 w-5" />
|
||||
Répartition par fournisseur
|
||||
</CardTitle>
|
||||
<CardDescription>Top 5 fournisseurs</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<RechartsChart>
|
||||
<Pie
|
||||
data={bySupplier?.slice(0, 5) || []}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
labelLine={false}
|
||||
label={(entry) => entry.supplierName}
|
||||
outerRadius={80}
|
||||
fill="#8884d8"
|
||||
dataKey="deliveries"
|
||||
>
|
||||
{bySupplier?.slice(0, 5).map((entry: any, index: number) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
</RechartsChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Performance par magasin */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Store className="h-5 w-5" />
|
||||
Performance par magasin
|
||||
</CardTitle>
|
||||
<CardDescription>Commandes et livraisons</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<BarChart data={byStore?.slice(0, 5) || []} layout="horizontal">
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis type="number" />
|
||||
<YAxis dataKey="storeName" type="category" />
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
<Bar dataKey="orders" fill="#8884d8" name="Commandes" />
|
||||
<Bar dataKey="deliveries" fill="#82ca9d" name="Livraisons" />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Top fournisseurs */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<TrendingUp className="h-5 w-5" />
|
||||
Top 5 Fournisseurs
|
||||
</CardTitle>
|
||||
<CardDescription>Par volume et montant</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
{summary?.topSuppliers?.map((supplier: any, index: number) => (
|
||||
<div key={supplier.id} className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline" className="w-8 h-8 rounded-full p-0 flex items-center justify-center">
|
||||
{index + 1}
|
||||
</Badge>
|
||||
<div>
|
||||
<p className="font-medium">{supplier.name}</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{supplier.count} livraisons • {supplier.amount.toFixed(2)}€
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-sm font-medium">{supplier.count}</div>
|
||||
<div className="text-xs text-gray-600">livraisons</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Actions d'export */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<FileDown className="h-5 w-5" />
|
||||
Export des données
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => handleExport('summary')}>
|
||||
Export Résumé
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => handleExport('timeseries')}>
|
||||
Export Évolution
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => handleExport('suppliers')}>
|
||||
Export Fournisseurs
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => handleExport('stores')}>
|
||||
Export Magasins
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Netscape HTTP Cookie File
|
||||
# https://curl.se/docs/http-cookies.html
|
||||
# This file was generated by libcurl! Edit at your own risk.
|
||||
|
||||
#HttpOnly_localhost FALSE / FALSE 1758639574 connect.sid s%3A8_9iOHdXBiypBHfh9CFiGGT7-mgFDQ-9.MPmF2NrBG7ywTs2h9HX4yW1JVNQ5dbq%2FHoZpz8jRTpo
|
||||
@@ -5021,6 +5021,184 @@ RÉSUMÉ DU SCAN
|
||||
}
|
||||
});
|
||||
|
||||
// Analytics routes
|
||||
app.get('/api/analytics/summary', isAuthenticated, async (req: any, res) => {
|
||||
try {
|
||||
const user = await storage.getUserWithGroups(req.user.claims ? req.user.claims.sub : req.user.id);
|
||||
if (!user) {
|
||||
return res.status(404).json({ message: "User not found" });
|
||||
}
|
||||
|
||||
// Parse query parameters
|
||||
const filters = {
|
||||
startDate: req.query.startDate ? new Date(req.query.startDate) : undefined,
|
||||
endDate: req.query.endDate ? new Date(req.query.endDate) : undefined,
|
||||
supplierIds: req.query.supplierIds ? req.query.supplierIds.split(',').map(Number) : undefined,
|
||||
groupIds: req.query.groupIds ? req.query.groupIds.split(',').map(Number) : undefined,
|
||||
status: req.query.status ? req.query.status.split(',') : undefined
|
||||
};
|
||||
|
||||
// Apply role-based filtering
|
||||
if (user.role !== 'admin' && user.role !== 'directeur') {
|
||||
const userGroupIds = user.groups.map((g: any) => g.groupId);
|
||||
filters.groupIds = filters.groupIds
|
||||
? filters.groupIds.filter(id => userGroupIds.includes(id))
|
||||
: userGroupIds;
|
||||
}
|
||||
|
||||
const summary = await storage.getAnalyticsSummary(filters);
|
||||
res.json(summary);
|
||||
} catch (error) {
|
||||
console.error('Error fetching analytics summary:', error);
|
||||
res.status(500).json({ message: 'Failed to fetch analytics summary' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/analytics/timeseries', isAuthenticated, async (req: any, res) => {
|
||||
try {
|
||||
const user = await storage.getUserWithGroups(req.user.claims ? req.user.claims.sub : req.user.id);
|
||||
if (!user) {
|
||||
return res.status(404).json({ message: "User not found" });
|
||||
}
|
||||
|
||||
const filters = {
|
||||
startDate: req.query.startDate ? new Date(req.query.startDate) : undefined,
|
||||
endDate: req.query.endDate ? new Date(req.query.endDate) : undefined,
|
||||
supplierIds: req.query.supplierIds ? req.query.supplierIds.split(',').map(Number) : undefined,
|
||||
groupIds: req.query.groupIds ? req.query.groupIds.split(',').map(Number) : undefined,
|
||||
granularity: (req.query.granularity as 'day' | 'week' | 'month') || 'day'
|
||||
};
|
||||
|
||||
// Apply role-based filtering
|
||||
if (user.role !== 'admin' && user.role !== 'directeur') {
|
||||
const userGroupIds = user.groups.map((g: any) => g.groupId);
|
||||
filters.groupIds = filters.groupIds
|
||||
? filters.groupIds.filter(id => userGroupIds.includes(id))
|
||||
: userGroupIds;
|
||||
}
|
||||
|
||||
const timeseries = await storage.getAnalyticsTimeseries(filters);
|
||||
res.json(timeseries);
|
||||
} catch (error) {
|
||||
console.error('Error fetching analytics timeseries:', error);
|
||||
res.status(500).json({ message: 'Failed to fetch analytics timeseries' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/analytics/by-supplier', isAuthenticated, async (req: any, res) => {
|
||||
try {
|
||||
const user = await storage.getUserWithGroups(req.user.claims ? req.user.claims.sub : req.user.id);
|
||||
if (!user) {
|
||||
return res.status(404).json({ message: "User not found" });
|
||||
}
|
||||
|
||||
const filters = {
|
||||
startDate: req.query.startDate ? new Date(req.query.startDate) : undefined,
|
||||
endDate: req.query.endDate ? new Date(req.query.endDate) : undefined,
|
||||
groupIds: req.query.groupIds ? req.query.groupIds.split(',').map(Number) : undefined
|
||||
};
|
||||
|
||||
// Apply role-based filtering
|
||||
if (user.role !== 'admin' && user.role !== 'directeur') {
|
||||
const userGroupIds = user.groups.map((g: any) => g.groupId);
|
||||
filters.groupIds = filters.groupIds
|
||||
? filters.groupIds.filter(id => userGroupIds.includes(id))
|
||||
: userGroupIds;
|
||||
}
|
||||
|
||||
const bySupplier = await storage.getAnalyticsBySupplier(filters);
|
||||
res.json(bySupplier);
|
||||
} catch (error) {
|
||||
console.error('Error fetching analytics by supplier:', error);
|
||||
res.status(500).json({ message: 'Failed to fetch analytics by supplier' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/analytics/by-store', isAuthenticated, async (req: any, res) => {
|
||||
try {
|
||||
const user = await storage.getUserWithGroups(req.user.claims ? req.user.claims.sub : req.user.id);
|
||||
if (!user) {
|
||||
return res.status(404).json({ message: "User not found" });
|
||||
}
|
||||
|
||||
const filters = {
|
||||
startDate: req.query.startDate ? new Date(req.query.startDate) : undefined,
|
||||
endDate: req.query.endDate ? new Date(req.query.endDate) : undefined,
|
||||
supplierIds: req.query.supplierIds ? req.query.supplierIds.split(',').map(Number) : undefined
|
||||
};
|
||||
|
||||
const byStore = await storage.getAnalyticsByStore(filters);
|
||||
res.json(byStore);
|
||||
} catch (error) {
|
||||
console.error('Error fetching analytics by store:', error);
|
||||
res.status(500).json({ message: 'Failed to fetch analytics by store' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/analytics/export', isAuthenticated, async (req: any, res) => {
|
||||
try {
|
||||
const user = await storage.getUserWithGroups(req.user.claims ? req.user.claims.sub : req.user.id);
|
||||
if (!user) {
|
||||
return res.status(404).json({ message: "User not found" });
|
||||
}
|
||||
|
||||
const type = req.query.type || 'summary';
|
||||
const filters = {
|
||||
startDate: req.query.startDate ? new Date(req.query.startDate) : undefined,
|
||||
endDate: req.query.endDate ? new Date(req.query.endDate) : undefined,
|
||||
supplierIds: req.query.supplierIds ? req.query.supplierIds.split(',').map(Number) : undefined,
|
||||
groupIds: req.query.groupIds ? req.query.groupIds.split(',').map(Number) : undefined,
|
||||
status: req.query.status ? req.query.status.split(',') : undefined
|
||||
};
|
||||
|
||||
// Apply role-based filtering
|
||||
if (user.role !== 'admin' && user.role !== 'directeur') {
|
||||
const userGroupIds = user.groups.map((g: any) => g.groupId);
|
||||
filters.groupIds = filters.groupIds
|
||||
? filters.groupIds.filter(id => userGroupIds.includes(id))
|
||||
: userGroupIds;
|
||||
}
|
||||
|
||||
let data: any;
|
||||
let filename = `analytics_${type}_${new Date().toISOString().split('T')[0]}.csv`;
|
||||
|
||||
switch(type) {
|
||||
case 'timeseries':
|
||||
data = await storage.getAnalyticsTimeseries({ ...filters, granularity: 'day' });
|
||||
break;
|
||||
case 'suppliers':
|
||||
data = await storage.getAnalyticsBySupplier(filters);
|
||||
break;
|
||||
case 'stores':
|
||||
data = await storage.getAnalyticsByStore(filters);
|
||||
break;
|
||||
default:
|
||||
data = [await storage.getAnalyticsSummary(filters)];
|
||||
}
|
||||
|
||||
// Convert to CSV
|
||||
if (data && data.length > 0) {
|
||||
const headers = Object.keys(data[0]).join(',');
|
||||
const rows = data.map((item: any) =>
|
||||
Object.values(item).map((val: any) =>
|
||||
typeof val === 'object' ? JSON.stringify(val) : val
|
||||
).join(',')
|
||||
).join('\n');
|
||||
|
||||
const csv = `${headers}\n${rows}`;
|
||||
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
|
||||
res.send(csv);
|
||||
} else {
|
||||
res.status(404).json({ message: 'No data to export' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error exporting analytics:', error);
|
||||
res.status(500).json({ message: 'Failed to export analytics' });
|
||||
}
|
||||
});
|
||||
|
||||
// Create server instance
|
||||
const httpServer = createServer(app);
|
||||
|
||||
|
||||
@@ -263,6 +263,43 @@ export interface IStorage {
|
||||
createReconciliationComment(comment: InsertReconciliationComment): Promise<ReconciliationComment>;
|
||||
updateReconciliationComment(id: number, comment: Partial<InsertReconciliationComment>): Promise<ReconciliationComment>;
|
||||
deleteReconciliationComment(id: number): Promise<void>;
|
||||
|
||||
// Analytics operations
|
||||
getAnalyticsSummary(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
supplierIds?: number[];
|
||||
groupIds?: number[];
|
||||
status?: string[];
|
||||
}): Promise<{
|
||||
totalOrders: number;
|
||||
totalDeliveries: number;
|
||||
onTimeRate: number;
|
||||
totalAmount: number;
|
||||
avgDeliveryDelay: number;
|
||||
topSuppliers: Array<{ id: number; name: string; count: number; amount: number }>;
|
||||
topStores: Array<{ id: number; name: string; orders: number; deliveries: number }>;
|
||||
}>;
|
||||
|
||||
getAnalyticsTimeseries(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
supplierIds?: number[];
|
||||
groupIds?: number[];
|
||||
granularity?: 'day' | 'week' | 'month';
|
||||
}): Promise<Array<{ date: string; orders: number; deliveries: number }>>;
|
||||
|
||||
getAnalyticsBySupplier(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
groupIds?: number[];
|
||||
}): Promise<Array<{ supplierId: number; supplierName: string; deliveries: number; amount: number }>>;
|
||||
|
||||
getAnalyticsByStore(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
supplierIds?: number[];
|
||||
}): Promise<Array<{ groupId: number; storeName: string; orders: number; deliveries: number }>>;
|
||||
}
|
||||
|
||||
export class DatabaseStorage implements IStorage {
|
||||
@@ -2815,6 +2852,294 @@ export class DatabaseStorage implements IStorage {
|
||||
.delete(reconciliationComments)
|
||||
.where(eq(reconciliationComments.id, id));
|
||||
}
|
||||
|
||||
// Analytics implementations
|
||||
async getAnalyticsSummary(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
supplierIds?: number[];
|
||||
groupIds?: number[];
|
||||
status?: string[];
|
||||
}): Promise<{
|
||||
totalOrders: number;
|
||||
totalDeliveries: number;
|
||||
onTimeRate: number;
|
||||
totalAmount: number;
|
||||
avgDeliveryDelay: number;
|
||||
topSuppliers: Array<{ id: number; name: string; count: number; amount: number }>;
|
||||
topStores: Array<{ id: number; name: string; orders: number; deliveries: number }>;
|
||||
}> {
|
||||
try {
|
||||
const conditions: any[] = [];
|
||||
const orderConditions: any[] = [];
|
||||
const deliveryConditions: any[] = [];
|
||||
|
||||
// Apply filters
|
||||
if (filters.startDate) {
|
||||
orderConditions.push(gte(orders.plannedDate, filters.startDate));
|
||||
deliveryConditions.push(gte(deliveries.scheduledDate, filters.startDate));
|
||||
}
|
||||
if (filters.endDate) {
|
||||
orderConditions.push(lte(orders.plannedDate, filters.endDate));
|
||||
deliveryConditions.push(lte(deliveries.scheduledDate, filters.endDate));
|
||||
}
|
||||
if (filters.supplierIds?.length) {
|
||||
orderConditions.push(inArray(orders.supplierId, filters.supplierIds));
|
||||
deliveryConditions.push(inArray(deliveries.supplierId, filters.supplierIds));
|
||||
}
|
||||
if (filters.groupIds?.length) {
|
||||
orderConditions.push(inArray(orders.groupId, filters.groupIds));
|
||||
deliveryConditions.push(inArray(deliveries.groupId, filters.groupIds));
|
||||
}
|
||||
if (filters.status?.length) {
|
||||
orderConditions.push(inArray(orders.status, filters.status));
|
||||
deliveryConditions.push(inArray(deliveries.status, filters.status));
|
||||
}
|
||||
|
||||
// Get total orders
|
||||
const orderQuery = db.select({ count: sql<number>`COUNT(*)` }).from(orders);
|
||||
if (orderConditions.length) orderQuery.where(and(...orderConditions));
|
||||
const [{ count: totalOrders }] = await orderQuery;
|
||||
|
||||
// Get total deliveries and amounts
|
||||
const deliveryQuery = db.select({
|
||||
count: sql<number>`COUNT(*)`,
|
||||
totalAmount: sql<number>`COALESCE(SUM(CAST(bl_amount AS NUMERIC)), 0) + COALESCE(SUM(CAST(invoice_amount AS NUMERIC)), 0)`,
|
||||
onTime: sql<number>`COUNT(CASE WHEN delivered_date <= scheduled_date THEN 1 END)`,
|
||||
avgDelay: sql<number>`AVG(EXTRACT(EPOCH FROM (delivered_date - scheduled_date)) / 86400)` // days
|
||||
}).from(deliveries);
|
||||
if (deliveryConditions.length) deliveryQuery.where(and(...deliveryConditions));
|
||||
const [deliveryStats] = await deliveryQuery;
|
||||
|
||||
// Get top suppliers
|
||||
const supplierQuery = db.select({
|
||||
id: suppliers.id,
|
||||
name: suppliers.name,
|
||||
count: sql<number>`COUNT(${deliveries.id})`,
|
||||
amount: sql<number>`COALESCE(SUM(CAST(${deliveries.blAmount} AS NUMERIC)), 0)`
|
||||
})
|
||||
.from(deliveries)
|
||||
.innerJoin(suppliers, eq(deliveries.supplierId, suppliers.id));
|
||||
|
||||
if (deliveryConditions.length) supplierQuery.where(and(...deliveryConditions));
|
||||
const topSuppliers = await supplierQuery
|
||||
.groupBy(suppliers.id, suppliers.name)
|
||||
.orderBy(desc(sql<number>`COUNT(${deliveries.id})`))
|
||||
.limit(5);
|
||||
|
||||
// Get top stores
|
||||
const storeQuery = db.select({
|
||||
id: groups.id,
|
||||
name: groups.name,
|
||||
orders: sql<number>`COUNT(DISTINCT ${orders.id})`,
|
||||
deliveries: sql<number>`COUNT(DISTINCT ${deliveries.id})`
|
||||
})
|
||||
.from(groups)
|
||||
.leftJoin(orders, eq(groups.id, orders.groupId))
|
||||
.leftJoin(deliveries, eq(groups.id, deliveries.groupId));
|
||||
|
||||
if (filters.groupIds?.length) {
|
||||
storeQuery.where(inArray(groups.id, filters.groupIds));
|
||||
}
|
||||
const topStores = await storeQuery
|
||||
.groupBy(groups.id, groups.name)
|
||||
.orderBy(desc(sql<number>`COUNT(DISTINCT ${orders.id}) + COUNT(DISTINCT ${deliveries.id})`))
|
||||
.limit(5);
|
||||
|
||||
return {
|
||||
totalOrders: Number(totalOrders) || 0,
|
||||
totalDeliveries: Number(deliveryStats.count) || 0,
|
||||
onTimeRate: deliveryStats.count ? (Number(deliveryStats.onTime) / Number(deliveryStats.count)) * 100 : 0,
|
||||
totalAmount: Number(deliveryStats.totalAmount) || 0,
|
||||
avgDeliveryDelay: Number(deliveryStats.avgDelay) || 0,
|
||||
topSuppliers: topSuppliers.map(s => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
count: Number(s.count),
|
||||
amount: Number(s.amount)
|
||||
})),
|
||||
topStores: topStores.map(s => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
orders: Number(s.orders),
|
||||
deliveries: Number(s.deliveries)
|
||||
}))
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Analytics summary error:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getAnalyticsTimeseries(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
supplierIds?: number[];
|
||||
groupIds?: number[];
|
||||
granularity?: 'day' | 'week' | 'month';
|
||||
}): Promise<Array<{ date: string; orders: number; deliveries: number }>> {
|
||||
const granularity = filters.granularity || 'day';
|
||||
const dateFormat = granularity === 'day' ? 'YYYY-MM-DD' :
|
||||
granularity === 'week' ? 'YYYY-IW' : 'YYYY-MM';
|
||||
|
||||
// Build WHERE clauses
|
||||
const orderConditions: string[] = [];
|
||||
const deliveryConditions: string[] = [];
|
||||
const params: any[] = [];
|
||||
|
||||
if (filters.startDate) {
|
||||
orderConditions.push(`planned_date >= $${params.length + 1}`);
|
||||
deliveryConditions.push(`scheduled_date >= $${params.length + 1}`);
|
||||
params.push(filters.startDate.toISOString());
|
||||
}
|
||||
if (filters.endDate) {
|
||||
const endParamIndex = params.length + 1;
|
||||
orderConditions.push(`planned_date <= $${endParamIndex}`);
|
||||
deliveryConditions.push(`scheduled_date <= $${endParamIndex}`);
|
||||
params.push(filters.endDate.toISOString());
|
||||
}
|
||||
if (filters.supplierIds?.length) {
|
||||
const supplierParamIndex = params.length + 1;
|
||||
orderConditions.push(`supplier_id = ANY($${supplierParamIndex})`);
|
||||
deliveryConditions.push(`supplier_id = ANY($${supplierParamIndex})`);
|
||||
params.push(filters.supplierIds);
|
||||
}
|
||||
if (filters.groupIds?.length) {
|
||||
const groupParamIndex = params.length + 1;
|
||||
orderConditions.push(`group_id = ANY($${groupParamIndex})`);
|
||||
deliveryConditions.push(`group_id = ANY($${groupParamIndex})`);
|
||||
params.push(filters.groupIds);
|
||||
}
|
||||
|
||||
const orderWhere = orderConditions.length > 0 ? `WHERE ${orderConditions.join(' AND ')}` : '';
|
||||
const deliveryWhere = deliveryConditions.length > 0 ? `WHERE ${deliveryConditions.join(' AND ')}` : '';
|
||||
|
||||
// Get orders by date using raw SQL
|
||||
const ordersSql = `
|
||||
SELECT TO_CHAR(planned_date, '${dateFormat}') as date, COUNT(*) as count
|
||||
FROM orders
|
||||
${orderWhere}
|
||||
GROUP BY TO_CHAR(planned_date, '${dateFormat}')
|
||||
ORDER BY TO_CHAR(planned_date, '${dateFormat}')
|
||||
`;
|
||||
|
||||
const ordersData = params.length > 0
|
||||
? await db.execute(sql.raw(ordersSql).values(params))
|
||||
: await db.execute(sql.raw(ordersSql));
|
||||
|
||||
// Get deliveries by date using raw SQL
|
||||
const deliveriesSql = `
|
||||
SELECT TO_CHAR(scheduled_date, '${dateFormat}') as date, COUNT(*) as count
|
||||
FROM deliveries
|
||||
${deliveryWhere}
|
||||
GROUP BY TO_CHAR(scheduled_date, '${dateFormat}')
|
||||
ORDER BY TO_CHAR(scheduled_date, '${dateFormat}')
|
||||
`;
|
||||
|
||||
const deliveriesData = params.length > 0
|
||||
? await db.execute(sql.raw(deliveriesSql).values(params))
|
||||
: await db.execute(sql.raw(deliveriesSql));
|
||||
|
||||
// Merge data
|
||||
const dataMap = new Map<string, { orders: number; deliveries: number }>();
|
||||
(ordersData.rows as any[]).forEach(row => {
|
||||
dataMap.set(row.date, { orders: Number(row.count), deliveries: 0 });
|
||||
});
|
||||
(deliveriesData.rows as any[]).forEach(row => {
|
||||
const existing = dataMap.get(row.date) || { orders: 0, deliveries: 0 };
|
||||
dataMap.set(row.date, { ...existing, deliveries: Number(row.count) });
|
||||
});
|
||||
|
||||
return Array.from(dataMap.entries())
|
||||
.map(([date, data]) => ({ date, ...data }))
|
||||
.sort((a, b) => a.date.localeCompare(b.date));
|
||||
}
|
||||
|
||||
async getAnalyticsBySupplier(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
groupIds?: number[];
|
||||
}): Promise<Array<{ supplierId: number; supplierName: string; deliveries: number; amount: number }>> {
|
||||
const conditions: any[] = [];
|
||||
if (filters.startDate) conditions.push(gte(deliveries.scheduledDate, filters.startDate));
|
||||
if (filters.endDate) conditions.push(lte(deliveries.scheduledDate, filters.endDate));
|
||||
if (filters.groupIds?.length) conditions.push(inArray(deliveries.groupId, filters.groupIds));
|
||||
|
||||
const query = db.select({
|
||||
supplierId: suppliers.id,
|
||||
supplierName: suppliers.name,
|
||||
deliveries: sql<number>`COUNT(${deliveries.id})`,
|
||||
amount: sql<number>`COALESCE(SUM(CAST(${deliveries.blAmount} AS NUMERIC)), 0)`
|
||||
})
|
||||
.from(deliveries)
|
||||
.innerJoin(suppliers, eq(deliveries.supplierId, suppliers.id));
|
||||
|
||||
if (conditions.length) query.where(and(...conditions));
|
||||
|
||||
const result = await query
|
||||
.groupBy(suppliers.id, suppliers.name)
|
||||
.orderBy(desc(sql<number>`COUNT(${deliveries.id})`));
|
||||
|
||||
return result.map(row => ({
|
||||
supplierId: row.supplierId,
|
||||
supplierName: row.supplierName,
|
||||
deliveries: Number(row.deliveries),
|
||||
amount: Number(row.amount)
|
||||
}));
|
||||
}
|
||||
|
||||
async getAnalyticsByStore(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
supplierIds?: number[];
|
||||
}): Promise<Array<{ groupId: number; storeName: string; orders: number; deliveries: number }>> {
|
||||
const orderConditions: any[] = [];
|
||||
const deliveryConditions: any[] = [];
|
||||
|
||||
if (filters.startDate) {
|
||||
const startDateStr = filters.startDate.toISOString();
|
||||
orderConditions.push(sql`${orders.plannedDate} >= ${startDateStr}`);
|
||||
deliveryConditions.push(sql`${deliveries.scheduledDate} >= ${startDateStr}`);
|
||||
}
|
||||
if (filters.endDate) {
|
||||
const endDateStr = filters.endDate.toISOString();
|
||||
orderConditions.push(sql`${orders.plannedDate} <= ${endDateStr}`);
|
||||
deliveryConditions.push(sql`${deliveries.scheduledDate} <= ${endDateStr}`);
|
||||
}
|
||||
if (filters.supplierIds?.length) {
|
||||
orderConditions.push(inArray(orders.supplierId, filters.supplierIds));
|
||||
deliveryConditions.push(inArray(deliveries.supplierId, filters.supplierIds));
|
||||
}
|
||||
|
||||
const result = await db.execute(sql`
|
||||
SELECT
|
||||
g.id as "groupId",
|
||||
g.name as "storeName",
|
||||
COALESCE(o.count, 0) as orders,
|
||||
COALESCE(d.count, 0) as deliveries
|
||||
FROM groups g
|
||||
LEFT JOIN (
|
||||
SELECT group_id, COUNT(*) as count
|
||||
FROM orders
|
||||
WHERE ${orderConditions.length ? sql.join(orderConditions, sql` AND `) : sql`1=1`}
|
||||
GROUP BY group_id
|
||||
) o ON g.id = o.group_id
|
||||
LEFT JOIN (
|
||||
SELECT group_id, COUNT(*) as count
|
||||
FROM deliveries
|
||||
WHERE ${deliveryConditions.length ? sql.join(deliveryConditions, sql` AND `) : sql`1=1`}
|
||||
GROUP BY group_id
|
||||
) d ON g.id = d.group_id
|
||||
ORDER BY (COALESCE(o.count, 0) + COALESCE(d.count, 0)) DESC
|
||||
`);
|
||||
|
||||
return result.rows.map((row: any) => ({
|
||||
groupId: row.groupId,
|
||||
storeName: row.storeName,
|
||||
orders: Number(row.orders),
|
||||
deliveries: Number(row.deliveries)
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// MemStorage class for development
|
||||
@@ -4794,6 +5119,213 @@ export class MemStorage implements IStorage {
|
||||
async deleteReconciliationComment(id: number): Promise<void> {
|
||||
this.reconciliationComments.delete(id);
|
||||
}
|
||||
|
||||
// Analytics implementations for MemStorage
|
||||
async getAnalyticsSummary(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
supplierIds?: number[];
|
||||
groupIds?: number[];
|
||||
status?: string[];
|
||||
}): Promise<{
|
||||
totalOrders: number;
|
||||
totalDeliveries: number;
|
||||
onTimeRate: number;
|
||||
totalAmount: number;
|
||||
avgDeliveryDelay: number;
|
||||
topSuppliers: Array<{ id: number; name: string; count: number; amount: number }>;
|
||||
topStores: Array<{ id: number; name: string; orders: number; deliveries: number }>;
|
||||
}> {
|
||||
// Simple implementation for development
|
||||
const orders = Array.from(this.orders.values());
|
||||
const deliveries = Array.from(this.deliveries.values());
|
||||
|
||||
// Apply filters
|
||||
const filteredOrders = orders.filter(order => {
|
||||
if (filters.startDate && order.plannedDate < filters.startDate) return false;
|
||||
if (filters.endDate && order.plannedDate > filters.endDate) return false;
|
||||
if (filters.supplierIds?.length && !filters.supplierIds.includes(order.supplierId)) return false;
|
||||
if (filters.groupIds?.length && !filters.groupIds.includes(order.groupId)) return false;
|
||||
if (filters.status?.length && !filters.status.includes(order.status)) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const filteredDeliveries = deliveries.filter(delivery => {
|
||||
if (filters.startDate && delivery.scheduledDate < filters.startDate) return false;
|
||||
if (filters.endDate && delivery.scheduledDate > filters.endDate) return false;
|
||||
if (filters.supplierIds?.length && !filters.supplierIds.includes(delivery.supplierId)) return false;
|
||||
if (filters.groupIds?.length && !filters.groupIds.includes(delivery.groupId)) return false;
|
||||
if (filters.status?.length && !filters.status.includes(delivery.status)) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
// Calculate metrics
|
||||
const totalOrders = filteredOrders.length;
|
||||
const totalDeliveries = filteredDeliveries.length;
|
||||
const onTimeDeliveries = filteredDeliveries.filter(d =>
|
||||
d.deliveredDate && d.deliveredDate <= d.scheduledDate
|
||||
).length;
|
||||
const onTimeRate = totalDeliveries > 0 ? (onTimeDeliveries / totalDeliveries) * 100 : 0;
|
||||
|
||||
const totalAmount = filteredDeliveries.reduce((sum, d) => {
|
||||
return sum + (parseFloat(d.blAmount as any) || 0) + (parseFloat(d.invoiceAmount as any) || 0);
|
||||
}, 0);
|
||||
|
||||
// Top suppliers
|
||||
const supplierStats = new Map<number, { name: string; count: number; amount: number }>();
|
||||
filteredDeliveries.forEach(d => {
|
||||
const supplier = this.suppliers.get(d.supplierId);
|
||||
if (supplier) {
|
||||
const stats = supplierStats.get(d.supplierId) || { name: supplier.name, count: 0, amount: 0 };
|
||||
stats.count++;
|
||||
stats.amount += parseFloat(d.blAmount as any) || 0;
|
||||
supplierStats.set(d.supplierId, stats);
|
||||
}
|
||||
});
|
||||
const topSuppliers = Array.from(supplierStats.entries())
|
||||
.map(([id, stats]) => ({ id, ...stats }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 5);
|
||||
|
||||
// Top stores
|
||||
const storeStats = new Map<number, { name: string; orders: number; deliveries: number }>();
|
||||
filteredOrders.forEach(o => {
|
||||
const group = this.groups.get(o.groupId);
|
||||
if (group) {
|
||||
const stats = storeStats.get(o.groupId) || { name: group.name, orders: 0, deliveries: 0 };
|
||||
stats.orders++;
|
||||
storeStats.set(o.groupId, stats);
|
||||
}
|
||||
});
|
||||
filteredDeliveries.forEach(d => {
|
||||
const group = this.groups.get(d.groupId);
|
||||
if (group) {
|
||||
const stats = storeStats.get(d.groupId) || { name: group.name, orders: 0, deliveries: 0 };
|
||||
stats.deliveries++;
|
||||
storeStats.set(d.groupId, stats);
|
||||
}
|
||||
});
|
||||
const topStores = Array.from(storeStats.entries())
|
||||
.map(([id, stats]) => ({ id, ...stats }))
|
||||
.sort((a, b) => (b.orders + b.deliveries) - (a.orders + a.deliveries))
|
||||
.slice(0, 5);
|
||||
|
||||
return {
|
||||
totalOrders,
|
||||
totalDeliveries,
|
||||
onTimeRate,
|
||||
totalAmount,
|
||||
avgDeliveryDelay: 0, // Simplified for development
|
||||
topSuppliers,
|
||||
topStores
|
||||
};
|
||||
}
|
||||
|
||||
async getAnalyticsTimeseries(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
supplierIds?: number[];
|
||||
groupIds?: number[];
|
||||
granularity?: 'day' | 'week' | 'month';
|
||||
}): Promise<Array<{ date: string; orders: number; deliveries: number }>> {
|
||||
const dataMap = new Map<string, { orders: number; deliveries: number }>();
|
||||
|
||||
// Process orders
|
||||
Array.from(this.orders.values()).forEach(order => {
|
||||
if (filters.startDate && order.plannedDate < filters.startDate) return;
|
||||
if (filters.endDate && order.plannedDate > filters.endDate) return;
|
||||
if (filters.supplierIds?.length && !filters.supplierIds.includes(order.supplierId)) return;
|
||||
if (filters.groupIds?.length && !filters.groupIds.includes(order.groupId)) return;
|
||||
|
||||
const dateKey = order.plannedDate.toISOString().split('T')[0];
|
||||
const existing = dataMap.get(dateKey) || { orders: 0, deliveries: 0 };
|
||||
existing.orders++;
|
||||
dataMap.set(dateKey, existing);
|
||||
});
|
||||
|
||||
// Process deliveries
|
||||
Array.from(this.deliveries.values()).forEach(delivery => {
|
||||
if (filters.startDate && delivery.scheduledDate < filters.startDate) return;
|
||||
if (filters.endDate && delivery.scheduledDate > filters.endDate) return;
|
||||
if (filters.supplierIds?.length && !filters.supplierIds.includes(delivery.supplierId)) return;
|
||||
if (filters.groupIds?.length && !filters.groupIds.includes(delivery.groupId)) return;
|
||||
|
||||
const dateKey = delivery.scheduledDate.toISOString().split('T')[0];
|
||||
const existing = dataMap.get(dateKey) || { orders: 0, deliveries: 0 };
|
||||
existing.deliveries++;
|
||||
dataMap.set(dateKey, existing);
|
||||
});
|
||||
|
||||
return Array.from(dataMap.entries())
|
||||
.map(([date, data]) => ({ date, ...data }))
|
||||
.sort((a, b) => a.date.localeCompare(b.date));
|
||||
}
|
||||
|
||||
async getAnalyticsBySupplier(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
groupIds?: number[];
|
||||
}): Promise<Array<{ supplierId: number; supplierName: string; deliveries: number; amount: number }>> {
|
||||
const supplierStats = new Map<number, { name: string; deliveries: number; amount: number }>();
|
||||
|
||||
Array.from(this.deliveries.values()).forEach(delivery => {
|
||||
if (filters.startDate && delivery.scheduledDate < filters.startDate) return;
|
||||
if (filters.endDate && delivery.scheduledDate > filters.endDate) return;
|
||||
if (filters.groupIds?.length && !filters.groupIds.includes(delivery.groupId)) return;
|
||||
|
||||
const supplier = this.suppliers.get(delivery.supplierId);
|
||||
if (supplier) {
|
||||
const stats = supplierStats.get(delivery.supplierId) || { name: supplier.name, deliveries: 0, amount: 0 };
|
||||
stats.deliveries++;
|
||||
stats.amount += parseFloat(delivery.blAmount as any) || 0;
|
||||
supplierStats.set(delivery.supplierId, stats);
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(supplierStats.entries())
|
||||
.map(([id, stats]) => ({ supplierId: id, supplierName: stats.name, ...stats }))
|
||||
.sort((a, b) => b.deliveries - a.deliveries);
|
||||
}
|
||||
|
||||
async getAnalyticsByStore(filters: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
supplierIds?: number[];
|
||||
}): Promise<Array<{ groupId: number; storeName: string; orders: number; deliveries: number }>> {
|
||||
const storeStats = new Map<number, { name: string; orders: number; deliveries: number }>();
|
||||
|
||||
// Count orders
|
||||
Array.from(this.orders.values()).forEach(order => {
|
||||
if (filters.startDate && order.plannedDate < filters.startDate) return;
|
||||
if (filters.endDate && order.plannedDate > filters.endDate) return;
|
||||
if (filters.supplierIds?.length && !filters.supplierIds.includes(order.supplierId)) return;
|
||||
|
||||
const group = this.groups.get(order.groupId);
|
||||
if (group) {
|
||||
const stats = storeStats.get(order.groupId) || { name: group.name, orders: 0, deliveries: 0 };
|
||||
stats.orders++;
|
||||
storeStats.set(order.groupId, stats);
|
||||
}
|
||||
});
|
||||
|
||||
// Count deliveries
|
||||
Array.from(this.deliveries.values()).forEach(delivery => {
|
||||
if (filters.startDate && delivery.scheduledDate < filters.startDate) return;
|
||||
if (filters.endDate && delivery.scheduledDate > filters.endDate) return;
|
||||
if (filters.supplierIds?.length && !filters.supplierIds.includes(delivery.supplierId)) return;
|
||||
|
||||
const group = this.groups.get(delivery.groupId);
|
||||
if (group) {
|
||||
const stats = storeStats.get(delivery.groupId) || { name: group.name, orders: 0, deliveries: 0 };
|
||||
stats.deliveries++;
|
||||
storeStats.set(delivery.groupId, stats);
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(storeStats.entries())
|
||||
.map(([id, stats]) => ({ groupId: id, storeName: stats.name, ...stats }))
|
||||
.sort((a, b) => (b.orders + b.deliveries) - (a.orders + a.deliveries));
|
||||
}
|
||||
}
|
||||
|
||||
// Use DatabaseStorage when DATABASE_URL is available, MemStorage as fallback
|
||||
|
||||
Reference in new issue
Block a user