Checkpoint: Ajout du récapitulatif annuel BAP et abonnements au tableau de bord, et de Budget réel par fournisseur avec filtres Année/Mois et ventilation abonnements/hors abonnement.
This commit is contained in:
@@ -26,6 +26,7 @@ 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" />;
|
||||
@@ -49,6 +50,7 @@ function Router() {
|
||||
<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} />
|
||||
|
||||
@@ -54,6 +54,7 @@ const menuStructure: MenuItem[] = [
|
||||
{ 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,23 @@ 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="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 className="py-8 text-center text-muted-foreground">Aucune facture finalisée avec une date disponible.</div>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Detailed Stats */}
|
||||
{showDetailedStats && (
|
||||
<>
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
24
server/invoiceAnalytics.test.ts
Normal file
24
server/invoiceAnalytics.test.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
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 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1045,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);
|
||||
}),
|
||||
}),
|
||||
|
||||
|
||||
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"),
|
||||
);
|
||||
}
|
||||
13
todo.md
13
todo.md
@@ -807,3 +807,16 @@
|
||||
- [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
|
||||
|
||||
Reference in New Issue
Block a user