Compare commits
12 Commits
1a7d5cb64e
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9997e383cc | ||
|
|
5128322a6d | ||
|
|
43fc8d523c | ||
|
|
cd73dd3d58 | ||
|
|
28a00cc771 | ||
|
|
e2d067ff4b | ||
|
|
0b01ebe331 | ||
|
|
a9a2a4b312 | ||
|
|
deb5b5735c | ||
|
|
a0c440dfae | ||
|
|
a88b342a0d | ||
|
|
7e1253615b |
@@ -26,6 +26,15 @@ const ImportReport = lazy(() => import("./pages/ImportReport"));
|
||||
const LearningSettings = lazy(() => import("./pages/LearningSettings"));
|
||||
const VentilationFreePro = lazy(() => import("./pages/VentilationFreePro"));
|
||||
const WebImportSources = lazy(() => import("./pages/WebImportSources"));
|
||||
const RealBudget = lazy(() => import("./pages/RealBudget"));
|
||||
|
||||
function SubscriptionInvoices() {
|
||||
return <Invoices scope="subscriptions" />;
|
||||
}
|
||||
|
||||
function AllInvoices() {
|
||||
return <Invoices />;
|
||||
}
|
||||
|
||||
function RouteFallback() {
|
||||
return <div className="min-h-screen bg-background" aria-busy="true" aria-label="Chargement" />;
|
||||
@@ -38,8 +47,10 @@ function Router() {
|
||||
<Route path="/login" component={Login} />
|
||||
<Route path="/dashboard" component={Dashboard} />
|
||||
<Route path="/upload" component={Upload} />
|
||||
<Route path="/invoices" component={Invoices} />
|
||||
<Route path="/invoices" component={AllInvoices} />
|
||||
<Route path="/invoices-bap" component={InvoicesBAP} />
|
||||
<Route path="/invoices-subscriptions" component={SubscriptionInvoices} />
|
||||
<Route path="/real-budget" component={RealBudget} />
|
||||
<Route path="/invoices/:id" component={InvoiceDetail} />
|
||||
<Route path="/settings" component={Settings} />
|
||||
<Route path="/import-settings" component={ImportSettings} />
|
||||
|
||||
@@ -53,6 +53,8 @@ const menuStructure: MenuItem[] = [
|
||||
{ icon: Upload, label: "Import", path: "/upload" },
|
||||
{ icon: FileText, label: "Factures", path: "/invoices" },
|
||||
{ icon: FileText, label: "Factures BAP", path: "/invoices-bap" },
|
||||
{ icon: FileText, label: "Factures abonnements", path: "/invoices-subscriptions" },
|
||||
{ icon: BarChart2, label: "Budget réel", path: "/real-budget" },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -148,6 +148,38 @@ export default function Dashboard() {
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Récapitulatif annuel</CardTitle>
|
||||
<CardDescription>Volumes et montants des factures finalisées, séparés entre BAP (hors abonnement) et abonnements.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{stats?.annualSummary?.length ? (
|
||||
<div className="space-y-6">
|
||||
<div className="h-[300px] rounded-lg border bg-white p-4">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={[...stats.annualSummary].reverse()} margin={{ top: 8, right: 16, left: 12, bottom: 4 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
||||
<XAxis dataKey="year" />
|
||||
<YAxis tickFormatter={(value) => new Intl.NumberFormat("fr-FR", { notation: "compact", maximumFractionDigits: 1 }).format(value)} />
|
||||
<Tooltip formatter={(value: number) => formatCurrency(Number(value))} labelFormatter={(year) => `Année ${year}`} />
|
||||
<Legend />
|
||||
<Bar dataKey="bapAmount" name="Montant BAP" fill="#2563eb" radius={[4, 4, 0, 0]} />
|
||||
<Bar dataKey="subscriptionAmount" name="Montant abonnements" fill="#7c3aed" radius={[4, 4, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full min-w-[780px] text-sm">
|
||||
<thead className="bg-muted/60 text-left text-muted-foreground"><tr><th className="px-4 py-3 font-medium">Année</th><th className="px-4 py-3 text-right font-medium">Factures BAP</th><th className="px-4 py-3 text-right font-medium">Montant BAP</th><th className="px-4 py-3 text-right font-medium">Abonnements</th><th className="px-4 py-3 text-right font-medium">Montant abonnements</th><th className="px-4 py-3 text-right font-medium">Total annuel</th></tr></thead>
|
||||
<tbody>{stats.annualSummary.map((row) => <tr key={row.year} className="border-t hover:bg-muted/30"><td className="px-4 py-3 font-semibold">{row.year}</td><td className="px-4 py-3 text-right">{row.bapCount}</td><td className="px-4 py-3 text-right text-blue-700">{formatCurrency(row.bapAmount)}</td><td className="px-4 py-3 text-right">{row.subscriptionCount}</td><td className="px-4 py-3 text-right text-violet-700">{formatCurrency(row.subscriptionAmount)}</td><td className="px-4 py-3 text-right font-semibold text-emerald-700">{formatCurrency(row.totalAmount)}</td></tr>)}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
) : <div className="py-8 text-center text-muted-foreground">Aucune facture finalisée avec une date disponible.</div>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Detailed Stats */}
|
||||
{showDetailedStats && (
|
||||
<>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import DashboardLayout from "@/components/DashboardLayout";
|
||||
import { useAuth } from "@/_core/hooks/useAuth";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
@@ -34,17 +34,28 @@ import {
|
||||
} from "@/components/ui/table";
|
||||
import { trpc } from "@/lib/trpc";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Search, FileText, Download, FileSpreadsheet, Trash2, Edit, Trash, Filter, LayoutList, LayoutGrid, ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";
|
||||
import { Search, FileText, Download, FileSpreadsheet, Trash2, Edit, Trash, Filter, LayoutList, LayoutGrid, ArrowUpDown, ArrowUp, ArrowDown, CalendarDays } from "lucide-react";
|
||||
import * as XLSX from 'xlsx';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { toast } from "sonner";
|
||||
import { useLocation } from "wouter";
|
||||
import { matchesInvoicePeriod } from "@shared/invoicePeriod";
|
||||
|
||||
type SortField = "invoiceDate" | "createdAt";
|
||||
type SortDir = "asc" | "desc";
|
||||
|
||||
export default function Invoices() {
|
||||
type InvoiceScope = "all" | "subscriptions";
|
||||
|
||||
const MONTHS = [
|
||||
["01", "Janvier"], ["02", "Février"], ["03", "Mars"], ["04", "Avril"],
|
||||
["05", "Mai"], ["06", "Juin"], ["07", "Août"], ["08", "Septembre"],
|
||||
["09", "Septembre"], ["10", "Octobre"], ["11", "Novembre"], ["12", "Décembre"],
|
||||
] as const;
|
||||
|
||||
export default function Invoices({ scope = "all" }: { scope?: InvoiceScope }) {
|
||||
const [, setLocation] = useLocation();
|
||||
const currentYear = new Date().getFullYear();
|
||||
const isSubscriptionPage = scope === "subscriptions";
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [compactMode, setCompactMode] = useState(true);
|
||||
const [sortField, setSortField] = useState<SortField>("createdAt");
|
||||
@@ -52,9 +63,11 @@ export default function Invoices() {
|
||||
const [selectedIds, setSelectedIds] = useState<number[]>([]);
|
||||
const [statusFilter, setStatusFilter] = useState<string>("all");
|
||||
const [recipientFilter, setRecipientFilter] = useState<string>("all");
|
||||
const [subscriptionFilter, setSubscriptionFilter] = useState<string>("all"); // all | yes | no
|
||||
const [subscriptionFilter, setSubscriptionFilter] = useState<string>(isSubscriptionPage ? "yes" : "all"); // all | yes | no
|
||||
const [entityFilter, setEntityFilter] = useState<string>("all"); // all | santinova | itinova
|
||||
const [ventilationFilter, setVentilationFilter] = useState<string>("all");
|
||||
const [selectedYear, setSelectedYear] = useState<string>(String(currentYear));
|
||||
const [selectedMonth, setSelectedMonth] = useState<string>("all");
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [invoiceToDelete, setInvoiceToDelete] = useState<number | null>(null);
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
@@ -194,17 +207,20 @@ export default function Invoices() {
|
||||
};
|
||||
|
||||
// Collect unique recipients for the filter dropdown
|
||||
const uniqueRecipients = Array.from(
|
||||
new Set(
|
||||
(invoices || []).map(inv => (inv as any).recipientName).filter(Boolean)
|
||||
)
|
||||
).sort();
|
||||
const scopedInvoices = useMemo(
|
||||
() => (invoices || []).filter(inv => !isSubscriptionPage || inv.isSubscription === 1),
|
||||
[invoices, isSubscriptionPage],
|
||||
);
|
||||
|
||||
const uniqueVentilations = Array.from(
|
||||
new Set(
|
||||
(invoices || []).map(inv => (inv as any).ventilationComptable).filter(Boolean)
|
||||
)
|
||||
).sort();
|
||||
const uniqueRecipients = useMemo(
|
||||
() => Array.from(new Set(scopedInvoices.map(inv => (inv as any).recipientName).filter(Boolean))).sort(),
|
||||
[scopedInvoices],
|
||||
);
|
||||
|
||||
const uniqueVentilations = useMemo(
|
||||
() => Array.from(new Set(scopedInvoices.map(inv => (inv as any).ventilationComptable).filter(Boolean))).sort(),
|
||||
[scopedInvoices],
|
||||
);
|
||||
|
||||
const handleSort = (field: SortField) => {
|
||||
if (sortField === field) {
|
||||
@@ -220,7 +236,7 @@ export default function Invoices() {
|
||||
return sortDir === "asc" ? <ArrowUp className="w-3 h-3 ml-1" /> : <ArrowDown className="w-3 h-3 ml-1" />;
|
||||
};
|
||||
|
||||
const filteredInvoices = invoices?.filter((inv) => {
|
||||
const filteredInvoices = scopedInvoices.filter((inv) => {
|
||||
// Filter by search query
|
||||
if (searchQuery) {
|
||||
const query = searchQuery.toLowerCase();
|
||||
@@ -230,6 +246,9 @@ export default function Invoices() {
|
||||
if (!matchesSearch) return false;
|
||||
}
|
||||
|
||||
// Même convention que Factures BAP : date de facture, sinon réception.
|
||||
if (!matchesInvoicePeriod(inv, selectedYear, selectedMonth)) return false;
|
||||
|
||||
// Filter by export status
|
||||
if (statusFilter !== "all") {
|
||||
if (statusFilter === "exported" && inv.exportStatus !== "exported") return false;
|
||||
@@ -268,22 +287,17 @@ export default function Invoices() {
|
||||
return true;
|
||||
});
|
||||
|
||||
const invoicesInPeriod = useMemo(
|
||||
() => scopedInvoices.filter(inv => matchesInvoicePeriod(inv, selectedYear, selectedMonth)),
|
||||
[scopedInvoices, selectedYear, selectedMonth],
|
||||
);
|
||||
|
||||
const statusCounts = {
|
||||
all: invoices?.length || 0,
|
||||
exported: invoices?.filter(inv => inv.exportStatus === "exported").length || 0,
|
||||
not_exported: invoices?.filter(inv => inv.exportStatus === "not_exported").length || 0,
|
||||
export_error: invoices?.filter(inv => inv.exportStatus === "export_error").length || 0,
|
||||
all: invoicesInPeriod.length,
|
||||
exported: invoicesInPeriod.filter(inv => inv.exportStatus === "exported").length,
|
||||
not_exported: invoicesInPeriod.filter(inv => inv.exportStatus === "not_exported").length,
|
||||
export_error: invoicesInPeriod.filter(inv => inv.exportStatus === "export_error").length,
|
||||
};
|
||||
|
||||
// Old filter logic (to be removed)
|
||||
const _oldFilteredInvoices = invoices?.filter((inv) => {
|
||||
if (!searchQuery) return true;
|
||||
const query = searchQuery.toLowerCase();
|
||||
return (
|
||||
inv.supplierName?.toLowerCase().includes(query) ||
|
||||
inv.invoiceNumber?.toLowerCase().includes(query)
|
||||
);
|
||||
});
|
||||
|
||||
const handleSelectAll = (checked: boolean) => {
|
||||
if (checked) {
|
||||
@@ -370,8 +384,10 @@ export default function Invoices() {
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">Factures</h1>
|
||||
<p className="text-gray-500 mt-1">Gérez toutes vos factures importées</p>
|
||||
<h1 className="text-3xl font-bold">{isSubscriptionPage ? "Factures abonnements" : "Factures"}</h1>
|
||||
<p className="text-gray-500 mt-1">
|
||||
{isSubscriptionPage ? "Gérez les factures identifiées comme abonnements" : "Gérez toutes vos factures importées"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
@@ -456,9 +472,30 @@ export default function Invoices() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Ligne 2 : Filtres destinataire, abonnement, entité, ventilation */}
|
||||
{/* Ligne 2 : Filtres de période, destinataire, abonnement, entité, ventilation */}
|
||||
<div className="flex gap-2 items-center flex-wrap mb-3">
|
||||
<Filter className="w-4 h-4 text-blue-400 shrink-0" />
|
||||
<div className="flex items-center gap-1.5 text-sm font-medium text-blue-600">
|
||||
<CalendarDays className="w-4 h-4" />
|
||||
Période :
|
||||
</div>
|
||||
<Select value={selectedYear} onValueChange={(value) => { setSelectedYear(value); if (value === "all") setSelectedMonth("all"); }}>
|
||||
<SelectTrigger className="w-28 h-8 bg-white border-blue-200 text-sm"><SelectValue placeholder="Année" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Toute année</SelectItem>
|
||||
{Array.from({ length: 5 }, (_, index) => currentYear - index).map(year => <SelectItem key={year} value={String(year)}>{year}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={selectedMonth} onValueChange={setSelectedMonth} disabled={selectedYear === "all"}>
|
||||
<SelectTrigger className="w-36 h-8 bg-white border-blue-200 text-sm"><SelectValue placeholder="Mois" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Tous les mois</SelectItem>
|
||||
{MONTHS.map(([value, label]) => <SelectItem key={value} value={value}>{label}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{(selectedYear !== String(currentYear) || selectedMonth !== "all") && (
|
||||
<button onClick={() => { setSelectedYear(String(currentYear)); setSelectedMonth("all"); }} className="text-xs text-blue-600 hover:text-blue-800 underline">Réinitialiser</button>
|
||||
)}
|
||||
<Select value={recipientFilter} onValueChange={setRecipientFilter}>
|
||||
<SelectTrigger className="w-[180px] bg-white border-blue-200 text-sm">
|
||||
<SelectValue placeholder="Destinataire" />
|
||||
@@ -471,7 +508,7 @@ export default function Invoices() {
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={subscriptionFilter} onValueChange={setSubscriptionFilter}>
|
||||
<Select value={isSubscriptionPage ? "yes" : subscriptionFilter} onValueChange={setSubscriptionFilter} disabled={isSubscriptionPage}>
|
||||
<SelectTrigger className="w-[170px] bg-white border-blue-200 text-sm">
|
||||
<SelectValue placeholder="Abonnement" />
|
||||
</SelectTrigger>
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { trpc } from "@/lib/trpc";
|
||||
import { BAP_MIN_QUALITY_SCORE, meetsBapQualityThreshold } from "@shared/bapEligibility";
|
||||
import { Search, FileText, Download, FileSpreadsheet, Trash2, Edit, Trash, CheckCircle, CheckCircle2, ShieldCheck, RefreshCw, FolderDown, ChevronDown, ChevronRight, ChevronsUpDown, CalendarDays, ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
|
||||
@@ -394,7 +395,7 @@ export default function InvoicesBAP() {
|
||||
// Déclarée ici (avant filteredInvoices et statusCounts) pour éviter le hoisting error
|
||||
const isEligibleForBAPValidation = (invoice: any) => {
|
||||
return (
|
||||
(invoice.qualityScore || 0) === 100 &&
|
||||
meetsBapQualityThreshold(invoice.qualityScore) &&
|
||||
invoice.exportStatus !== "exported" &&
|
||||
invoice.isSubscription === 0 &&
|
||||
invoice.serviceConcerne &&
|
||||
@@ -526,19 +527,19 @@ export default function InvoicesBAP() {
|
||||
|
||||
const getQualityBadge = (score: number | null) => {
|
||||
if (score === null) return <Badge variant="outline">-</Badge>;
|
||||
if (score === 100) return <Badge className="bg-green-100 text-green-800 hover:bg-green-100">{score}%</Badge>;
|
||||
if (meetsBapQualityThreshold(score)) return <Badge className="bg-green-100 text-green-800 hover:bg-green-100">{score}%</Badge>;
|
||||
if (score >= 80) return <Badge className="bg-yellow-100 text-yellow-800 hover:bg-yellow-100">{score}%</Badge>;
|
||||
return <Badge className="bg-red-100 text-red-800 hover:bg-red-100">{score}%</Badge>;
|
||||
};
|
||||
|
||||
const isEligibleForExport = (invoice: any) => {
|
||||
// Une facture BAP est exportable si :
|
||||
// 1. Score = 100%
|
||||
// 1. Score >= 90 % (seuil BAP)
|
||||
// 2. Type d'achat rempli
|
||||
// 3. Service concerné rempli
|
||||
// 4. Ventilation comptable remplie
|
||||
return (
|
||||
(invoice.qualityScore || 0) === 100 &&
|
||||
meetsBapQualityThreshold(invoice.qualityScore) &&
|
||||
invoice.typeAchat &&
|
||||
invoice.serviceConcerne &&
|
||||
invoice.ventilationComptable
|
||||
@@ -549,7 +550,7 @@ export default function InvoicesBAP() {
|
||||
|
||||
const getBAPValidationTooltip = (invoice: any): string => {
|
||||
const reasons: string[] = [];
|
||||
if ((invoice.qualityScore || 0) < 100) reasons.push("Score < 100%");
|
||||
if (!meetsBapQualityThreshold(invoice.qualityScore)) reasons.push(`Score < ${BAP_MIN_QUALITY_SCORE}%`);
|
||||
if (invoice.exportStatus === "exported") reasons.push("Déjà exportée");
|
||||
if (invoice.isSubscription !== 0) reasons.push("Marquée comme abonnement");
|
||||
if (!invoice.serviceConcerne) reasons.push("Service manquant");
|
||||
@@ -655,7 +656,7 @@ export default function InvoicesBAP() {
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (confirm("Valider en BAP toutes les factures éligibles (score 100%, champs remplis, non abonnement) ? Les PDFs annotés seront générés automatiquement.")) {
|
||||
if (confirm(`Valider en BAP toutes les factures éligibles (score ≥ ${BAP_MIN_QUALITY_SCORE}%, champs remplis, non abonnement) ? Les PDFs annotés seront générés automatiquement.`)) {
|
||||
validateBAPBulkMutation.mutate();
|
||||
}
|
||||
}}
|
||||
|
||||
90
client/src/pages/RealBudget.tsx
Normal file
90
client/src/pages/RealBudget.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
import DashboardLayout from "@/components/DashboardLayout";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { trpc } from "@/lib/trpc";
|
||||
import { buildSupplierBudgetSummary } from "@shared/invoiceAnalytics";
|
||||
import { CalendarDays, Euro, FileText } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
const MONTHS = [
|
||||
["01", "Janvier"], ["02", "Février"], ["03", "Mars"], ["04", "Avril"],
|
||||
["05", "Mai"], ["06", "Juin"], ["07", "Juillet"], ["08", "Août"],
|
||||
["09", "Septembre"], ["10", "Octobre"], ["11", "Novembre"], ["12", "Décembre"],
|
||||
] as const;
|
||||
|
||||
function formatCurrency(value: number) {
|
||||
return new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" }).format(value);
|
||||
}
|
||||
|
||||
export default function RealBudget() {
|
||||
const currentYear = new Date().getFullYear();
|
||||
const [selectedYear, setSelectedYear] = useState(String(currentYear));
|
||||
const [selectedMonth, setSelectedMonth] = useState("all");
|
||||
const { data: invoices, isLoading } = trpc.invoices.list.useQuery();
|
||||
|
||||
const availableYears = useMemo(() => {
|
||||
const years = new Set<number>([currentYear]);
|
||||
(invoices || []).forEach((invoice) => {
|
||||
const value = invoice.invoiceDate ?? invoice.createdAt;
|
||||
if (!value) return;
|
||||
const date = new Date(value);
|
||||
if (!Number.isNaN(date.getTime())) years.add(date.getFullYear());
|
||||
});
|
||||
return Array.from(years).sort((a, b) => b - a);
|
||||
}, [invoices, currentYear]);
|
||||
|
||||
const rows = useMemo(
|
||||
() => buildSupplierBudgetSummary(invoices || [], selectedYear, selectedMonth),
|
||||
[invoices, selectedYear, selectedMonth],
|
||||
);
|
||||
const totals = useMemo(() => rows.reduce((total, row) => ({
|
||||
subscriptionAmount: total.subscriptionAmount + row.subscriptionAmount,
|
||||
nonSubscriptionAmount: total.nonSubscriptionAmount + row.nonSubscriptionAmount,
|
||||
totalAmount: total.totalAmount + row.totalAmount,
|
||||
}), { subscriptionAmount: 0, nonSubscriptionAmount: 0, totalAmount: 0 }), [rows]);
|
||||
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">Budget réel</h1>
|
||||
<p className="mt-1 text-muted-foreground">Montants réellement facturés, regroupés par fournisseur.</p>
|
||||
</div>
|
||||
|
||||
<Card className="border-blue-100 bg-blue-50/70">
|
||||
<CardContent className="flex flex-wrap items-center gap-3 py-4">
|
||||
<div className="flex items-center gap-1.5 text-sm font-medium text-blue-700"><CalendarDays className="h-4 w-4" /> Période :</div>
|
||||
<Select value={selectedYear} onValueChange={(value) => { setSelectedYear(value); if (value === "all") setSelectedMonth("all"); }}>
|
||||
<SelectTrigger className="w-28 bg-white"><SelectValue placeholder="Année" /></SelectTrigger>
|
||||
<SelectContent><SelectItem value="all">Toute année</SelectItem>{availableYears.map((year) => <SelectItem key={year} value={String(year)}>{year}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
<Select value={selectedMonth} onValueChange={setSelectedMonth} disabled={selectedYear === "all"}>
|
||||
<SelectTrigger className="w-40 bg-white"><SelectValue placeholder="Mois" /></SelectTrigger>
|
||||
<SelectContent><SelectItem value="all">Tous les mois</SelectItem>{MONTHS.map(([value, label]) => <SelectItem key={value} value={value}>{label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<Card><CardHeader className="pb-2"><CardTitle className="text-sm font-medium">Abonnements</CardTitle></CardHeader><CardContent><div className="text-2xl font-bold text-violet-700">{formatCurrency(totals.subscriptionAmount)}</div></CardContent></Card>
|
||||
<Card><CardHeader className="pb-2"><CardTitle className="text-sm font-medium">Hors abonnement</CardTitle></CardHeader><CardContent><div className="text-2xl font-bold text-blue-700">{formatCurrency(totals.nonSubscriptionAmount)}</div></CardContent></Card>
|
||||
<Card><CardHeader className="pb-2"><CardTitle className="flex items-center gap-2 text-sm font-medium"><Euro className="h-4 w-4" /> Total facturé</CardTitle></CardHeader><CardContent><div className="text-2xl font-bold text-emerald-700">{formatCurrency(totals.totalAmount)}</div></CardContent></Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Budget réel par fournisseur</CardTitle><CardDescription>Les factures finalisées sont séparées entre abonnements et hors abonnement.</CardDescription></CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? <div className="py-12 text-center text-muted-foreground">Chargement du budget…</div> : rows.length === 0 ? <div className="flex flex-col items-center gap-2 py-12 text-muted-foreground"><FileText className="h-10 w-10" />Aucune facture finalisée pour cette période.</div> : (
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full min-w-[850px] text-sm"><thead className="bg-muted/60 text-left text-muted-foreground"><tr><th className="px-4 py-3 font-medium">Fournisseur</th><th className="px-4 py-3 text-right font-medium">Abonnements</th><th className="px-4 py-3 text-right font-medium">Montant abonnements</th><th className="px-4 py-3 text-right font-medium">Hors abonnement</th><th className="px-4 py-3 text-right font-medium">Montant hors abonnement</th><th className="px-4 py-3 text-right font-medium">Total</th></tr></thead>
|
||||
<tbody>{rows.map((row) => <tr key={row.supplierName} className="border-t hover:bg-muted/30"><td className="px-4 py-3 font-medium">{row.supplierName}</td><td className="px-4 py-3 text-right">{row.subscriptionCount}</td><td className="px-4 py-3 text-right text-violet-700">{formatCurrency(row.subscriptionAmount)}</td><td className="px-4 py-3 text-right">{row.nonSubscriptionCount}</td><td className="px-4 py-3 text-right text-blue-700">{formatCurrency(row.nonSubscriptionAmount)}</td><td className="px-4 py-3 text-right font-semibold">{formatCurrency(row.totalAmount)}</td></tr>)}</tbody>
|
||||
<tfoot className="border-t-2 bg-muted/50 font-semibold"><tr><td className="px-4 py-3">Total</td><td colSpan={2} className="px-4 py-3 text-right text-violet-700">{formatCurrency(totals.subscriptionAmount)}</td><td colSpan={2} className="px-4 py-3 text-right text-blue-700">{formatCurrency(totals.nonSubscriptionAmount)}</td><td className="px-4 py-3 text-right text-emerald-700">{formatCurrency(totals.totalAmount)}</td></tr></tfoot>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
16
server/bapEligibility.test.ts
Normal file
16
server/bapEligibility.test.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BAP_MIN_QUALITY_SCORE, meetsBapQualityThreshold } from "@shared/bapEligibility";
|
||||
|
||||
describe("meetsBapQualityThreshold", () => {
|
||||
it("autorise exactement le seuil de 90 %", () => {
|
||||
expect(BAP_MIN_QUALITY_SCORE).toBe(90);
|
||||
expect(meetsBapQualityThreshold(90)).toBe(true);
|
||||
expect(meetsBapQualityThreshold(100)).toBe(true);
|
||||
});
|
||||
|
||||
it("refuse les scores inférieurs ou absents", () => {
|
||||
expect(meetsBapQualityThreshold(89)).toBe(false);
|
||||
expect(meetsBapQualityThreshold(null)).toBe(false);
|
||||
expect(meetsBapQualityThreshold(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
12
server/db.ts
12
server/db.ts
@@ -50,6 +50,7 @@ import {
|
||||
WebImportSource
|
||||
} from "../drizzle/schema";
|
||||
import { ENV } from './_core/env';
|
||||
import { buildAnnualInvoiceSummary } from "@shared/invoiceAnalytics";
|
||||
|
||||
let _db: ReturnType<typeof drizzle> | null = null;
|
||||
|
||||
@@ -332,7 +333,7 @@ export async function searchInvoices(userId: number | null, query: string): Prom
|
||||
.orderBy(desc(invoices.createdAt));
|
||||
}
|
||||
|
||||
export async function getInvoiceStats(userId: number) {
|
||||
export async function getInvoiceStats(userId?: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return {
|
||||
total: 0,
|
||||
@@ -346,10 +347,12 @@ export async function getInvoiceStats(userId: number) {
|
||||
topSuppliers: [],
|
||||
suppliersList: [],
|
||||
topRecipients: [],
|
||||
recipientsList: []
|
||||
recipientsList: [],
|
||||
annualSummary: [],
|
||||
};
|
||||
|
||||
const allInvoices = await getInvoicesByUserId(userId);
|
||||
// Le tableau de bord est global pour les administrateurs, comme les listes Factures.
|
||||
const allInvoices = userId ? await getInvoicesByUserId(userId) : await getAllInvoices();
|
||||
|
||||
// Calculate basic stats
|
||||
const completed = allInvoices.filter(i => i.status === "completed");
|
||||
@@ -458,7 +461,8 @@ export async function getInvoiceStats(userId: number) {
|
||||
topSuppliers,
|
||||
suppliersList,
|
||||
topRecipients,
|
||||
recipientsList
|
||||
recipientsList,
|
||||
annualSummary: buildAnnualInvoiceSummary(allInvoices),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
33
server/invoiceAnalytics.test.ts
Normal file
33
server/invoiceAnalytics.test.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildAnnualInvoiceSummary, buildSupplierBudgetSummary } from "@shared/invoiceAnalytics";
|
||||
|
||||
const invoices = [
|
||||
{ invoiceDate: "2026-05-15", createdAt: "2026-05-16", status: "completed", isSubscription: 0, supplierName: "SFR", totalAmount: "100" },
|
||||
{ invoiceDate: "2026-05-20", createdAt: "2026-05-21", status: "completed", isSubscription: 1, supplierName: "SFR", totalAmount: "20" },
|
||||
{ invoiceDate: "2025-03-10", createdAt: "2025-03-11", status: "completed", isSubscription: 1, supplierName: "Microsoft", totalAmount: "50" },
|
||||
{ invoiceDate: "2026-05-01", createdAt: "2026-05-01", status: "error", isSubscription: 0, supplierName: "Ignorée", totalAmount: "999" },
|
||||
];
|
||||
|
||||
describe("agrégats de facturation", () => {
|
||||
it("calcule les volumes et montants BAP et abonnements par année", () => {
|
||||
expect(buildAnnualInvoiceSummary(invoices)).toEqual([
|
||||
{ year: 2026, bapCount: 1, bapAmount: 100, subscriptionCount: 1, subscriptionAmount: 20, totalAmount: 120 },
|
||||
{ year: 2025, bapCount: 0, bapAmount: 0, subscriptionCount: 1, subscriptionAmount: 50, totalAmount: 50 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("filtre le budget par période et ventile chaque fournisseur par type", () => {
|
||||
expect(buildSupplierBudgetSummary(invoices, "2026", "05")).toEqual([
|
||||
{ supplierName: "SFR", subscriptionCount: 1, subscriptionAmount: 20, nonSubscriptionCount: 1, nonSubscriptionAmount: 100, totalAmount: 120 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("classe le budget du fournisseur le plus facturé au moins facturé", () => {
|
||||
const rows = buildSupplierBudgetSummary([
|
||||
...invoices,
|
||||
{ invoiceDate: "2026-05-22", createdAt: "2026-05-22", status: "completed", isSubscription: 0, supplierName: "Orange", totalAmount: "300" },
|
||||
], "2026", "05");
|
||||
|
||||
expect(rows.map((row) => row.supplierName)).toEqual(["Orange", "SFR"]);
|
||||
});
|
||||
});
|
||||
17
server/invoicePeriod.test.ts
Normal file
17
server/invoicePeriod.test.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getInvoicePeriodDate, matchesInvoicePeriod } from "@shared/invoicePeriod";
|
||||
|
||||
describe("filtres de période des factures", () => {
|
||||
it("privilégie la date de facture et accepte le mois demandé", () => {
|
||||
const invoice = { invoiceDate: "2026-05-11T00:00:00.000Z", createdAt: "2026-06-02T00:00:00.000Z" };
|
||||
expect(getInvoicePeriodDate(invoice)?.getFullYear()).toBe(2026);
|
||||
expect(matchesInvoicePeriod(invoice, "2026", "05")).toBe(true);
|
||||
expect(matchesInvoicePeriod(invoice, "2026", "06")).toBe(false);
|
||||
});
|
||||
|
||||
it("utilise la date de réception lorsque la date de facture est absente", () => {
|
||||
const invoice = { invoiceDate: null, createdAt: "2025-01-31T00:00:00.000Z" };
|
||||
expect(matchesInvoicePeriod(invoice, "2025", "01")).toBe(true);
|
||||
expect(matchesInvoicePeriod(invoice, "2026", "all")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { COOKIE_NAME } from "@shared/const";
|
||||
import { BAP_MIN_QUALITY_SCORE, meetsBapQualityThreshold } from "@shared/bapEligibility";
|
||||
|
||||
interface Condition {
|
||||
field: string;
|
||||
@@ -499,8 +500,8 @@ export const appRouter = router({
|
||||
const hasService = !!invoice.serviceConcerne;
|
||||
const hasTypeAchat = !!invoice.typeAchat;
|
||||
const hasVentilation = !!invoice.ventilationComptable;
|
||||
if (score < 100) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Le score de qualité doit être à 100% pour valider" });
|
||||
if (!meetsBapQualityThreshold(score)) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: `Le score de qualité doit être au moins de ${BAP_MIN_QUALITY_SCORE}% pour valider` });
|
||||
}
|
||||
if (!isNotSubscription) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "La facture est marquée comme abonnement" });
|
||||
@@ -720,7 +721,7 @@ export const appRouter = router({
|
||||
const allInvoices = ctx.user.role === 'admin' ? await getAllInvoices() : await getInvoicesByUser(ctx.user.id);
|
||||
// Filtrer les factures éligibles (non déjà validées)
|
||||
const eligible = allInvoices.filter((inv: any) =>
|
||||
(inv.qualityScore || 0) >= 100 &&
|
||||
meetsBapQualityThreshold(inv.qualityScore) &&
|
||||
inv.isSubscription === 0 &&
|
||||
!!inv.serviceConcerne &&
|
||||
!!inv.typeAchat &&
|
||||
@@ -1044,7 +1045,8 @@ export const appRouter = router({
|
||||
}),
|
||||
|
||||
getStats: protectedProcedure.query(async ({ ctx }) => {
|
||||
return getInvoiceStats(ctx.user.id);
|
||||
// Les administrateurs consultent les mêmes données globales que les listes Factures.
|
||||
return getInvoiceStats(ctx.user.role === "admin" ? undefined : ctx.user.id);
|
||||
}),
|
||||
}),
|
||||
|
||||
|
||||
10
shared/bapEligibility.ts
Normal file
10
shared/bapEligibility.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
/** Score minimal requis pour générer et valider un BAP. */
|
||||
export const BAP_MIN_QUALITY_SCORE = 90;
|
||||
|
||||
/**
|
||||
* Centralise le seuil BAP afin que l’interface et le serveur appliquent la
|
||||
* même règle métier, y compris pour les scores nuls ou absents.
|
||||
*/
|
||||
export function meetsBapQualityThreshold(score: number | null | undefined): boolean {
|
||||
return typeof score === "number" && Number.isFinite(score) && score >= BAP_MIN_QUALITY_SCORE;
|
||||
}
|
||||
108
shared/invoiceAnalytics.ts
Normal file
108
shared/invoiceAnalytics.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { getInvoicePeriodDate, matchesInvoicePeriod } from "./invoicePeriod";
|
||||
|
||||
export type AnalyticsInvoice = {
|
||||
invoiceDate?: Date | string | number | null;
|
||||
createdAt?: Date | string | number | null;
|
||||
isSubscription?: number | null;
|
||||
status?: string | null;
|
||||
supplierName?: string | null;
|
||||
totalAmount?: number | string | null;
|
||||
};
|
||||
|
||||
export type AnnualInvoiceSummary = {
|
||||
year: number;
|
||||
bapCount: number;
|
||||
bapAmount: number;
|
||||
subscriptionCount: number;
|
||||
subscriptionAmount: number;
|
||||
totalAmount: number;
|
||||
};
|
||||
|
||||
export type SupplierBudgetSummary = {
|
||||
supplierName: string;
|
||||
subscriptionCount: number;
|
||||
subscriptionAmount: number;
|
||||
nonSubscriptionCount: number;
|
||||
nonSubscriptionAmount: number;
|
||||
totalAmount: number;
|
||||
};
|
||||
|
||||
function getAmount(value: AnalyticsInvoice["totalAmount"]): number {
|
||||
const amount = Number(value);
|
||||
return Number.isFinite(amount) ? amount : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agrège les factures finalisées par année métier. « BAP » désigne ici les
|
||||
* factures hors abonnement, éligibles au circuit BAP, validées ou non.
|
||||
*/
|
||||
export function buildAnnualInvoiceSummary(invoices: AnalyticsInvoice[]): AnnualInvoiceSummary[] {
|
||||
const summaryByYear = new Map<number, AnnualInvoiceSummary>();
|
||||
|
||||
for (const invoice of invoices) {
|
||||
if (invoice.status !== "completed") continue;
|
||||
const date = getInvoicePeriodDate(invoice);
|
||||
if (!date) continue;
|
||||
|
||||
const year = date.getFullYear();
|
||||
const current = summaryByYear.get(year) ?? {
|
||||
year,
|
||||
bapCount: 0,
|
||||
bapAmount: 0,
|
||||
subscriptionCount: 0,
|
||||
subscriptionAmount: 0,
|
||||
totalAmount: 0,
|
||||
};
|
||||
const amount = getAmount(invoice.totalAmount);
|
||||
|
||||
if (invoice.isSubscription === 1) {
|
||||
current.subscriptionCount += 1;
|
||||
current.subscriptionAmount += amount;
|
||||
} else {
|
||||
current.bapCount += 1;
|
||||
current.bapAmount += amount;
|
||||
}
|
||||
current.totalAmount += amount;
|
||||
summaryByYear.set(year, current);
|
||||
}
|
||||
|
||||
return Array.from(summaryByYear.values()).sort((a, b) => b.year - a.year);
|
||||
}
|
||||
|
||||
/** Agrège le budget réellement facturé par fournisseur sur la période choisie. */
|
||||
export function buildSupplierBudgetSummary(
|
||||
invoices: AnalyticsInvoice[],
|
||||
year: string,
|
||||
month: string,
|
||||
): SupplierBudgetSummary[] {
|
||||
const summaryBySupplier = new Map<string, SupplierBudgetSummary>();
|
||||
|
||||
for (const invoice of invoices) {
|
||||
if (invoice.status !== "completed" || !matchesInvoicePeriod(invoice, year, month)) continue;
|
||||
|
||||
const supplierName = invoice.supplierName?.trim() || "Fournisseur inconnu";
|
||||
const current = summaryBySupplier.get(supplierName) ?? {
|
||||
supplierName,
|
||||
subscriptionCount: 0,
|
||||
subscriptionAmount: 0,
|
||||
nonSubscriptionCount: 0,
|
||||
nonSubscriptionAmount: 0,
|
||||
totalAmount: 0,
|
||||
};
|
||||
const amount = getAmount(invoice.totalAmount);
|
||||
|
||||
if (invoice.isSubscription === 1) {
|
||||
current.subscriptionCount += 1;
|
||||
current.subscriptionAmount += amount;
|
||||
} else {
|
||||
current.nonSubscriptionCount += 1;
|
||||
current.nonSubscriptionAmount += amount;
|
||||
}
|
||||
current.totalAmount += amount;
|
||||
summaryBySupplier.set(supplierName, current);
|
||||
}
|
||||
|
||||
return Array.from(summaryBySupplier.values()).sort((a, b) =>
|
||||
b.totalAmount - a.totalAmount || a.supplierName.localeCompare(b.supplierName, "fr"),
|
||||
);
|
||||
}
|
||||
27
shared/invoicePeriod.ts
Normal file
27
shared/invoicePeriod.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Date métier utilisée pour les listes de factures : date de facture si elle
|
||||
* est connue, sinon date de réception. Cette règle est partagée avec BAP.
|
||||
*/
|
||||
export function getInvoicePeriodDate(invoice: {
|
||||
invoiceDate?: Date | string | number | null;
|
||||
createdAt?: Date | string | number | null;
|
||||
}): Date | null {
|
||||
const value = invoice.invoiceDate ?? invoice.createdAt;
|
||||
if (!value) return null;
|
||||
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
/** Indique si une facture correspond au filtre Année/Mois sélectionné. */
|
||||
export function matchesInvoicePeriod(
|
||||
invoice: Parameters<typeof getInvoicePeriodDate>[0],
|
||||
year: string,
|
||||
month: string,
|
||||
): boolean {
|
||||
if (year === "all") return true;
|
||||
|
||||
const date = getInvoicePeriodDate(invoice);
|
||||
if (!date || date.getFullYear() !== Number(year)) return false;
|
||||
return month === "all" || date.getMonth() + 1 === Number(month);
|
||||
}
|
||||
51
todo.md
51
todo.md
@@ -778,7 +778,50 @@
|
||||
- [x] Ajouter les tests et valider TypeScript, tests et build
|
||||
|
||||
## Déploiement — filtre par action des automatismes
|
||||
- [ ] Pousser le filtre par action vers Gitea recette
|
||||
- [ ] Déployer et vérifier le filtre par action en recette
|
||||
- [ ] Pousser la version validée vers Gitea production
|
||||
- [ ] Déployer et vérifier le filtre par action en production
|
||||
- [x] Pousser le filtre par action vers Gitea recette
|
||||
- [x] Déployer et vérifier le filtre par action en recette
|
||||
- [x] Pousser la version validée vers Gitea production
|
||||
- [x] Déployer et vérifier le filtre par action en production
|
||||
|
||||
## Seuil d’éligibilité BAP à 90 %
|
||||
- [x] Identifier les validations BAP fondées sur le score de qualité
|
||||
- [x] Abaisser le seuil de 100 % à 90 % pour les opérations BAP
|
||||
- [x] Ajouter les tests de seuil et valider TypeScript, tests et build
|
||||
|
||||
## Déploiement — seuil BAP à 90 %
|
||||
- [x] Pousser le correctif vers Gitea recette
|
||||
- [x] Déployer et vérifier le seuil BAP à 90 % en recette
|
||||
- [x] Pousser la version validée vers Gitea production
|
||||
- [x] Déployer et vérifier le seuil BAP à 90 % en production
|
||||
|
||||
## Rétablissement du serveur de recette
|
||||
- [x] Redémarrer le serveur de recette autorisé par l’utilisateur
|
||||
- [x] Rétablir le conteneur applicatif et terminer le déploiement BAP à 90 %
|
||||
|
||||
## Factures abonnements et filtres de période
|
||||
- [x] Analyser les listes Factures, Factures BAP et le menu Facturation
|
||||
- [x] Ajouter les filtres Année et Mois à la page Factures
|
||||
- [x] Créer la page Factures abonnements affichant uniquement les abonnements
|
||||
- [x] Reprendre les recherches, filtres et actions de la page Factures
|
||||
- [x] Ajouter l’entrée Factures abonnements après Factures BAP dans le menu
|
||||
- [x] Ajouter les tests et valider TypeScript, build et affichage en sandbox
|
||||
- [x] Déployer et vérifier le correctif en recette
|
||||
- [x] Déployer et vérifier le correctif en production
|
||||
|
||||
## Synthèse annuelle du tableau de bord
|
||||
- [x] Analyser les données et le tableau de bord existant
|
||||
- [x] Calculer par année les volumes et montants BAP et abonnements
|
||||
- [x] Afficher le nombre de factures et les montants par type, puis le total
|
||||
- [x] Ajouter les tests et valider TypeScript, build et affichage en sandbox
|
||||
|
||||
## Budget réel par fournisseur
|
||||
- [x] Définir l’agrégation des montants par fournisseur et statut Abonnement
|
||||
- [x] Ajouter les filtres Année et Mois à l’écran Budget réel
|
||||
- [x] Créer l’écran Budget réel à la fin du menu Facturation
|
||||
- [x] Afficher par fournisseur les montants Abonnement, Hors abonnement et le total
|
||||
- [x] Ajouter les tests et valider TypeScript, build et affichage en sandbox
|
||||
|
||||
## Améliorations Budget réel et tableau de bord
|
||||
- [x] Confirmer le tri décroissant par montant total dans le budget
|
||||
- [x] Ajouter un graphique annuel BAP versus abonnements au tableau de bord
|
||||
- [x] Ajouter les tests et valider TypeScript, build et rendu sandbox
|
||||
|
||||
Reference in New Issue
Block a user