Checkpoint: Améliorations Factures BAP : suppression colonne Abonnement, mode d'export configurable (navigateur/dossier), génération PDF annoté avec zone blanche (CAPEX/OPEX | BAP | Destinataire + signature du service) lors du clic BAP, historique BAP dans le menu Traçabilité, table bapHistory en DB.

This commit is contained in:
Manus
2026-04-12 05:57:02 -04:00
parent edf7cc704d
commit 5f7c8c7c7f
12 changed files with 2261 additions and 39 deletions

View File

@@ -17,6 +17,7 @@ import History from "./pages/History";
import Users from "./pages/Users";
import ListsAdmin from "./pages/ListsAdmin";
import AutomationRules from "./pages/AutomationRules";
import BapHistory from "./pages/BapHistory";
function Router() {
return (
@@ -34,6 +35,7 @@ function Router() {
<Route path="/users" component={Users} />
<Route path="/lists-admin" component={ListsAdmin} />
<Route path="/automation-rules" component={AutomationRules} />
<Route path="/bap-history" component={BapHistory} />
<Route path="/404" component={NotFound} />
<Route component={NotFound} />
</Switch>

View File

@@ -25,7 +25,7 @@ import {
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { getLoginUrl } from "@/const";
import { useIsMobile } from "@/hooks/useMobile";
import { LayoutDashboard, LogOut, PanelLeft, Users, FileText, Upload, History, Settings, Download, List, Zap, ChevronDown, Receipt, Cog, ClipboardList } from "lucide-react";
import { LayoutDashboard, LogOut, PanelLeft, Users, FileText, Upload, History, Settings, Download, List, Zap, ChevronDown, Receipt, Cog, ClipboardList, CheckSquare } from "lucide-react";
import { CSSProperties, useEffect, useRef, useState } from "react";
import { useLocation } from "wouter";
import { DashboardLayoutSkeleton } from './DashboardLayoutSkeleton';
@@ -75,6 +75,7 @@ const menuStructure: MenuItem[] = [
color: "from-green-500 to-emerald-500",
children: [
{ icon: History, label: "Historiques", path: "/history" },
{ icon: CheckSquare, label: "Historique BAP", path: "/bap-history" },
],
},
];

View File

@@ -0,0 +1,281 @@
import { useState } from "react";
import { trpc } from "@/lib/trpc";
import DashboardLayout from "@/components/DashboardLayout";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { toast } from "sonner";
import {
Loader2,
CheckSquare,
Search,
Trash2,
ExternalLink,
FolderOpen,
Monitor,
Calendar,
Building2,
User,
FileText,
} from "lucide-react";
export default function BapHistory() {
const { data: entries, isLoading, refetch } = trpc.bapHistory.getAll.useQuery();
const deleteMutation = trpc.bapHistory.delete.useMutation();
const [search, setSearch] = useState("");
const filtered = (entries || []).filter((e) => {
const q = search.toLowerCase();
return (
!q ||
(e.supplierName || "").toLowerCase().includes(q) ||
(e.invoiceNumber || "").toLowerCase().includes(q) ||
(e.serviceConcerne || "").toLowerCase().includes(q) ||
(e.recipientName || "").toLowerCase().includes(q) ||
(e.typeAchat || "").toLowerCase().includes(q)
);
});
const handleDelete = async (id: number) => {
try {
await deleteMutation.mutateAsync({ id });
toast.success("Entrée supprimée");
refetch();
} catch {
toast.error("Impossible de supprimer cette entrée");
}
};
const formatDate = (d: Date | string | null) => {
if (!d) return "—";
return new Date(d).toLocaleDateString("fr-FR", {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
});
};
const formatAmount = (a: string | null) => {
if (!a) return "—";
const n = parseFloat(a);
return isNaN(n) ? a : n.toLocaleString("fr-FR", { style: "currency", currency: "EUR" });
};
return (
<DashboardLayout>
<div className="max-w-7xl space-y-6">
{/* Header */}
<div className="space-y-2">
<div className="flex items-center gap-3">
<div className="p-3 bg-gradient-to-br from-green-500 to-emerald-600 rounded-xl shadow-lg">
<CheckSquare className="w-7 h-7 text-white" />
</div>
<div>
<h1 className="text-4xl font-bold bg-gradient-to-r from-green-600 to-emerald-600 bg-clip-text text-transparent">
Historique BAP
</h1>
<p className="text-muted-foreground mt-1">
Toutes les factures validées "Bon à Payer" avec leur PDF annoté
</p>
</div>
</div>
</div>
{/* Stats rapides */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<Card className="border-green-200 dark:border-green-800">
<CardContent className="pt-4 pb-3">
<div className="text-2xl font-bold text-green-600">{(entries || []).length}</div>
<div className="text-sm text-muted-foreground">Total validations</div>
</CardContent>
</Card>
<Card className="border-blue-200 dark:border-blue-800">
<CardContent className="pt-4 pb-3">
<div className="text-2xl font-bold text-blue-600">
{(entries || []).filter((e) => e.exportMode === "browser").length}
</div>
<div className="text-sm text-muted-foreground">Ouverts navigateur</div>
</CardContent>
</Card>
<Card className="border-orange-200 dark:border-orange-800">
<CardContent className="pt-4 pb-3">
<div className="text-2xl font-bold text-orange-600">
{(entries || []).filter((e) => e.exportMode === "folder").length}
</div>
<div className="text-sm text-muted-foreground">Exportés dossier</div>
</CardContent>
</Card>
<Card className="border-purple-200 dark:border-purple-800">
<CardContent className="pt-4 pb-3">
<div className="text-2xl font-bold text-purple-600">
{(entries || []).filter((e) => e.signatureName).length}
</div>
<div className="text-sm text-muted-foreground">Avec signature</div>
</CardContent>
</Card>
</div>
{/* Tableau */}
<Card>
<CardHeader className="border-b bg-gradient-to-r from-green-50 to-emerald-50 dark:from-green-950/20 dark:to-emerald-950/20">
<div className="flex items-center justify-between gap-4 flex-wrap">
<div>
<CardTitle>Validations BAP</CardTitle>
<CardDescription>
{filtered.length} résultat{filtered.length !== 1 ? "s" : ""}
{search ? ` pour "${search}"` : ""}
</CardDescription>
</div>
<div className="relative w-72">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Rechercher..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-9 h-9"
/>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
{isLoading ? (
<div className="flex items-center justify-center h-40 gap-3">
<Loader2 className="w-6 h-6 animate-spin text-primary" />
<span className="text-muted-foreground">Chargement...</span>
</div>
) : filtered.length === 0 ? (
<div className="flex flex-col items-center justify-center h-40 gap-2 text-muted-foreground">
<CheckSquare className="w-10 h-10 opacity-30" />
<p className="text-sm">
{search ? "Aucun résultat pour cette recherche" : "Aucune validation BAP enregistrée"}
</p>
</div>
) : (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow className="bg-muted/30">
<TableHead className="w-36">
<div className="flex items-center gap-1">
<Calendar className="h-3.5 w-3.5" />
Date validation
</div>
</TableHead>
<TableHead>
<div className="flex items-center gap-1">
<Building2 className="h-3.5 w-3.5" />
Fournisseur
</div>
</TableHead>
<TableHead>N° Facture</TableHead>
<TableHead>Montant</TableHead>
<TableHead>Type achat</TableHead>
<TableHead>
<div className="flex items-center gap-1">
<User className="h-3.5 w-3.5" />
Destinataire
</div>
</TableHead>
<TableHead>Service</TableHead>
<TableHead>Signature</TableHead>
<TableHead>Export</TableHead>
<TableHead className="w-20">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filtered.map((entry) => (
<TableRow key={entry.id} className="hover:bg-muted/20">
<TableCell className="text-xs text-muted-foreground whitespace-nowrap">
{formatDate(entry.validatedAt)}
</TableCell>
<TableCell className="font-medium max-w-[140px] truncate">
{entry.supplierName || "—"}
</TableCell>
<TableCell className="text-sm">
{entry.invoiceNumber || "—"}
</TableCell>
<TableCell className="text-sm font-mono">
{formatAmount(entry.totalAmount)}
</TableCell>
<TableCell>
{entry.typeAchat ? (
<Badge
variant="outline"
className={
entry.typeAchat.toLowerCase().includes("capex")
? "border-blue-400 text-blue-700 dark:text-blue-300"
: "border-green-400 text-green-700 dark:text-green-300"
}
>
{entry.typeAchat.toUpperCase()}
</Badge>
) : (
"—"
)}
</TableCell>
<TableCell className="text-sm max-w-[120px] truncate">
{entry.recipientName || (
<span className="text-muted-foreground italic text-xs">TOUS</span>
)}
</TableCell>
<TableCell className="text-sm max-w-[120px] truncate">
{entry.serviceConcerne || "—"}
</TableCell>
<TableCell className="text-sm">
{entry.signatureName ? (
<Badge variant="secondary" className="text-xs">
{entry.signatureName}
</Badge>
) : (
<span className="text-muted-foreground text-xs"></span>
)}
</TableCell>
<TableCell>
{entry.exportMode === "browser" && entry.pdfUrl ? (
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-blue-600 hover:text-blue-700"
onClick={() => window.open(entry.pdfUrl!, "_blank")}
>
<Monitor className="h-3.5 w-3.5 mr-1" />
<span className="text-xs">Voir PDF</span>
</Button>
) : entry.exportMode === "folder" && entry.exportPath ? (
<div className="flex items-center gap-1 text-orange-600">
<FolderOpen className="h-3.5 w-3.5" />
<span className="text-xs truncate max-w-[100px]" title={entry.exportPath}>
Dossier
</span>
</div>
) : (
<span className="text-muted-foreground text-xs"></span>
)}
</TableCell>
<TableCell>
<Button
variant="ghost"
size="sm"
className="h-7 w-7 p-0 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => handleDelete(entry.id)}
disabled={deleteMutation.isPending}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
</div>
</DashboardLayout>
);
}

View File

@@ -7,7 +7,7 @@ import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { Loader2, Save, Upload, FolderOpen, Mail, Play, Square, Download, Inbox, CheckCircle2 } from "lucide-react";
import { Loader2, Save, Upload, FolderOpen, Mail, Play, Square, Download, Inbox, CheckCircle2, Monitor, FolderOutput } from "lucide-react";
import DashboardLayout from "@/components/DashboardLayout";
export default function ImportSettings() {
@@ -40,6 +40,8 @@ export default function ImportSettings() {
// Export folder
const [exportFolder, setExportFolder] = useState("");
// BAP export mode
const [bapExportMode, setBapExportMode] = useState<"browser" | "folder">("browser");
// Initialize form with settings from database
useEffect(() => {
@@ -55,6 +57,7 @@ export default function ImportSettings() {
setEmailImportPort(settings.emailImportPort || 993);
setEmailImportFrequency(settings.emailImportFrequency || 30);
setExportFolder(settings.exportFolder || "");
setBapExportMode((settings.bapExportMode as "browser" | "folder") || "browser");
}
}, [settings]);
@@ -72,6 +75,7 @@ export default function ImportSettings() {
emailImportPort: emailImportPort,
emailImportFrequency: emailImportFrequency,
exportFolder: exportFolder || null,
bapExportMode: bapExportMode,
});
toast.success("Paramètres enregistrés avec succès");
@@ -469,7 +473,7 @@ export default function ImportSettings() {
</CardContent>
</Card>
{/* Export Folder */}
{/* Export Folder & BAP Export Mode */}
<Card className="border-2 hover:border-primary/50 transition-colors">
<CardHeader className="bg-gradient-to-r from-orange-50 to-amber-50 dark:from-orange-950/20 dark:to-amber-950/20 border-b">
<div className="flex items-center gap-3">
@@ -477,16 +481,57 @@ export default function ImportSettings() {
<Download className="w-6 h-6 text-white" />
</div>
<div>
<CardTitle className="text-xl">Dossier d'export</CardTitle>
<CardTitle className="text-xl">Export des factures BAP</CardTitle>
<CardDescription className="mt-1">
Configurez le dossier de destination pour l'export des factures
Configurez le mode d'export et le dossier de destination pour les factures validées BAP
</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="space-y-4 pt-6">
<CardContent className="space-y-6 pt-6">
{/* BAP Export Mode */}
<div className="space-y-3">
<Label className="text-base font-medium">Mode d'export BAP</Label>
<div className="grid grid-cols-2 gap-3">
<button
type="button"
onClick={() => setBapExportMode("browser")}
className={`flex flex-col items-center gap-2 p-4 rounded-xl border-2 transition-all ${
bapExportMode === "browser"
? "border-blue-500 bg-blue-50 dark:bg-blue-950/30 text-blue-700 dark:text-blue-300"
: "border-muted hover:border-muted-foreground/40 text-muted-foreground"
}`}
>
<Monitor className="w-8 h-8" />
<div className="text-center">
<div className="font-semibold text-sm">Ouvrir dans le navigateur</div>
<div className="text-xs mt-0.5 opacity-70">Le PDF s'ouvre directement dans un nouvel onglet</div>
</div>
</button>
<button
type="button"
onClick={() => setBapExportMode("folder")}
className={`flex flex-col items-center gap-2 p-4 rounded-xl border-2 transition-all ${
bapExportMode === "folder"
? "border-orange-500 bg-orange-50 dark:bg-orange-950/30 text-orange-700 dark:text-orange-300"
: "border-muted hover:border-muted-foreground/40 text-muted-foreground"
}`}
>
<FolderOutput className="w-8 h-8" />
<div className="text-center">
<div className="font-semibold text-sm">Enregistrer dans un dossier</div>
<div className="text-xs mt-0.5 opacity-70">Le PDF est copié dans le dossier configuré ci-dessous</div>
</div>
</button>
</div>
</div>
{/* Export Folder (shown for both modes but required for folder mode) */}
<div className="space-y-2">
<Label htmlFor="exportFolder" className="text-base font-medium">Chemin du dossier d'export</Label>
<Label htmlFor="exportFolder" className="text-base font-medium">
Chemin du dossier d'export
{bapExportMode === "folder" && <span className="text-red-500 ml-1">*</span>}
</Label>
<Input
id="exportFolder"
type="text"
@@ -496,7 +541,9 @@ export default function ImportSettings() {
className="h-11"
/>
<p className="text-sm text-muted-foreground">
Spécifiez le chemin absolu du dossier les factures seront exportées
{bapExportMode === "folder"
? "Chemin absolu obligatoire du dossier où les PDF BAP seront enregistrés"
: "Chemin optionnel du dossier d'export (utilisé pour l'export SFTP et l'export groupé)"}
</p>
</div>
</CardContent>

View File

@@ -132,8 +132,15 @@ export default function InvoicesBAP() {
});
const validateBAPMutation = trpc.invoices.validateBAP.useMutation({
onSuccess: () => {
toast.success("Facture validée BAP avec succès !");
onSuccess: (data) => {
if (data.exportMode === 'browser' && data.pdfUrl) {
toast.success("Facture validée BAP ! Ouverture du PDF annoté...", { duration: 3000 });
window.open(data.pdfUrl, '_blank');
} else if (data.exportMode === 'folder' && data.exportPath) {
toast.success(`Facture validée BAP ! PDF enregistré dans : ${data.exportPath}`, { duration: 6000 });
} else {
toast.success("Facture validée BAP avec succès !");
}
utils.invoices.list.invalidate();
},
onError: (error) => {
@@ -475,7 +482,6 @@ export default function InvoicesBAP() {
<TableHead>Service</TableHead>
<TableHead>Type achat</TableHead>
<TableHead>Ventilation</TableHead>
<TableHead>Abonnement</TableHead>
<TableHead>Score</TableHead>
<TableHead>Statut</TableHead>
<TableHead className="w-32">Actions</TableHead>
@@ -596,21 +602,6 @@ export default function InvoicesBAP() {
<option value="__ADD_NEW__" className="font-semibold text-blue-600"> Ajouter...</option>
</select>
</TableCell>
<TableCell className="text-sm">
<select
value={invoice.isSubscription ? "OUI" : "NON"}
onChange={(e) => {
updateFieldMutation.mutate({
id: invoice.id,
data: { isSubscription: e.target.value === "OUI" ? 1 : 0 },
});
}}
className="w-full px-2 py-1 border rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="NON">NON</option>
<option value="OUI">OUI</option>
</select>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
{getQualityBadge(invoice.qualityScore)}

View File

@@ -0,0 +1,21 @@
CREATE TABLE `bapHistory` (
`id` int AUTO_INCREMENT NOT NULL,
`userId` int NOT NULL,
`invoiceId` int NOT NULL,
`supplierName` varchar(255),
`invoiceNumber` varchar(100),
`invoiceDate` timestamp,
`totalAmount` varchar(50),
`typeAchat` varchar(50),
`serviceConcerne` varchar(100),
`ventilationComptable` varchar(100),
`recipientName` varchar(255),
`exportMode` enum('browser','folder') NOT NULL DEFAULT 'browser',
`exportPath` text,
`pdfUrl` text,
`signatureName` varchar(255),
`validatedAt` timestamp NOT NULL DEFAULT (now()),
CONSTRAINT `bapHistory_id` PRIMARY KEY(`id`)
);
--> statement-breakpoint
ALTER TABLE `importSettings` ADD `bapExportMode` enum('browser','folder') DEFAULT 'browser' NOT NULL;

File diff suppressed because it is too large Load Diff

View File

@@ -120,6 +120,13 @@
"when": 1775985531192,
"tag": "0016_tricky_quasimodo",
"breakpoints": true
},
{
"idx": 17,
"version": "5",
"when": 1775987314108,
"tag": "0017_clammy_toad",
"breakpoints": true
}
]
}

View File

@@ -178,6 +178,7 @@ export const importSettings = mysqlTable("importSettings", {
// Export folder settings
exportFolder: text("exportFolder"), // Path to folder for exporting invoices
bapExportMode: mysqlEnum("bapExportMode", ["browser", "folder"]).default("browser").notNull(), // BAP export mode: open in browser or save to folder
createdAt: timestamp("createdAt").defaultNow().notNull(),
updatedAt: timestamp("updatedAt").defaultNow().onUpdateNow().notNull(),
@@ -347,3 +348,27 @@ export const serviceSignatures = mysqlTable("serviceSignatures", {
export type ServiceSignature = typeof serviceSignatures.$inferSelect;
export type InsertServiceSignature = typeof serviceSignatures.$inferInsert;
/**
* BAP History table - records every BAP validation with PDF export details
*/
export const bapHistory = mysqlTable("bapHistory", {
id: int("id").autoincrement().primaryKey(),
userId: int("userId").notNull(),
invoiceId: int("invoiceId").notNull(),
supplierName: varchar("supplierName", { length: 255 }),
invoiceNumber: varchar("invoiceNumber", { length: 100 }),
invoiceDate: timestamp("invoiceDate"),
totalAmount: varchar("totalAmount", { length: 50 }),
typeAchat: varchar("typeAchat", { length: 50 }), // CAPEX / OPEX
serviceConcerne: varchar("serviceConcerne", { length: 100 }),
ventilationComptable: varchar("ventilationComptable", { length: 100 }),
recipientName: varchar("recipientName", { length: 255 }),
exportMode: mysqlEnum("exportMode", ["browser", "folder"]).default("browser").notNull(),
exportPath: text("exportPath"), // null for browser mode
pdfUrl: text("pdfUrl"), // S3 URL for browser mode
signatureName: varchar("signatureName", { length: 255 }), // Signer name if applied
validatedAt: timestamp("validatedAt").defaultNow().notNull(),
});
export type BapHistory = typeof bapHistory.$inferSelect;
export type InsertBapHistory = typeof bapHistory.$inferInsert;

View File

@@ -38,7 +38,10 @@ import {
Signature,
serviceSignatures,
InsertServiceSignature,
ServiceSignature
ServiceSignature,
bapHistory,
InsertBapHistory,
BapHistory
} from "../drizzle/schema";
import { ENV } from './_core/env';
@@ -776,3 +779,35 @@ export async function deleteServiceSignature(userId: number, serviceName: string
await db.delete(serviceSignatures).where(eq(serviceSignatures.id, match.id));
}
}
// ============= BAP HISTORY HELPERS =============
export async function createBapHistoryEntry(data: InsertBapHistory): Promise<BapHistory> {
const db = await getDb();
if (!db) throw new Error("Database not available");
const result = await db.insert(bapHistory).values(data);
const insertId = (result[0] as any).insertId;
const created = await getBapHistoryById(insertId);
if (!created) throw new Error("Failed to retrieve created BAP history entry");
return created;
}
export async function getBapHistoryById(id: number): Promise<BapHistory | undefined> {
const db = await getDb();
if (!db) return undefined;
const results = await db.select().from(bapHistory).where(eq(bapHistory.id, id));
return results[0];
}
export async function getBapHistoryByUser(userId: number): Promise<BapHistory[]> {
const db = await getDb();
if (!db) return [];
return db.select().from(bapHistory)
.where(eq(bapHistory.userId, userId))
.orderBy(desc(bapHistory.validatedAt));
}
export async function deleteBapHistoryEntry(id: number): Promise<void> {
const db = await getDb();
if (!db) return;
await db.delete(bapHistory).where(eq(bapHistory.id, id));
}

View File

@@ -63,6 +63,9 @@ import {
getServiceSignaturesByUser,
upsertServiceSignature,
deleteServiceSignature,
createBapHistoryEntry,
getBapHistoryByUser,
deleteBapHistoryEntry,
} from "./db";
import { loginLocal, hashPassword, getAzureAuthUrl, isAzureAdConfigured, generateToken } from "./auth";
import { extractInvoicesWithMistral, generateMetadataJSON } from "./invoiceExtractor";
@@ -386,28 +389,22 @@ export const appRouter = router({
return { success: true };
}),
validateBAP: protectedProcedure
validateBAP: protectedProcedure
.input(z.object({ id: z.number() }))
.mutation(async ({ input, ctx }) => {
const invoice = await getInvoiceById(input.id);
if (!invoice || invoice.userId !== ctx.user.id) {
throw new TRPCError({ code: "NOT_FOUND" });
}
// Vérifier les critères de validation BAP
const score = invoice.qualityScore || 0;
const isNotExported = invoice.exportStatus !== "exported";
const isNotSubscription = invoice.isSubscription === 0;
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 (!isNotExported) {
throw new TRPCError({ code: "BAD_REQUEST", message: "La facture a déjà été exportée" });
}
if (!isNotSubscription) {
throw new TRPCError({ code: "BAD_REQUEST", message: "La facture est marquée comme abonnement" });
}
@@ -415,15 +412,191 @@ export const appRouter = router({
throw new TRPCError({ code: "BAD_REQUEST", message: "Les champs Service, Type d'achat et Ventilation doivent être remplis" });
}
// ── Génération du PDF annoté ──────────────────────────────────────
const fs = await import('fs/promises');
const path = await import('path');
const { PDFDocument, rgb, StandardFonts } = await import('pdf-lib');
const { storagePut } = await import('./storage');
const importSettings = await getImportSettingsByUser(ctx.user.id);
const bapExportMode = importSettings?.bapExportMode || 'browser';
const exportFolder = importSettings?.exportFolder || null;
const STORAGE_BASE_PATH = process.env.STORAGE_BASE_PATH || path.join(process.cwd(), 'storage');
let pdfUrl: string | null = null;
let exportPath: string | null = null;
let signatureName: string | null = null;
try {
if (!invoice.fileKey) throw new Error('Fichier PDF source introuvable');
const sourcePath = path.join(STORAGE_BASE_PATH, invoice.fileKey);
const pdfBytes = await fs.readFile(sourcePath);
const pdfDoc = await PDFDocument.load(pdfBytes);
const pages = pdfDoc.getPages();
const lastPage = pages[pages.length - 1];
const { width, height } = lastPage.getSize();
// ── Zone blanche BAP (bas de page, hauteur 140pt) ────────────────
const zoneHeight = 140;
const zoneX = 30;
const zoneY = 10;
const zoneW = width - 60;
// Fond blanc
lastPage.drawRectangle({
x: zoneX,
y: zoneY,
width: zoneW,
height: zoneHeight,
color: rgb(1, 1, 1),
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 0.5,
});
const font = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const fontNormal = await pdfDoc.embedFont(StandardFonts.Helvetica);
// Ligne 1 : CAPEX/OPEX | BAP | Destinataire
const typeAchatText = (invoice.typeAchat || 'N/A').toUpperCase();
const recipientRaw = (invoice as any).recipientName || '';
const destinataireText = recipientRaw ? recipientRaw : 'TOUS';
const line1 = `${typeAchatText} | BON À PAYER | ${destinataireText}`;
const line1Size = 11;
const line1W = font.widthOfTextAtSize(line1, line1Size);
lastPage.drawText(line1, {
x: zoneX + (zoneW - line1W) / 2,
y: zoneY + zoneHeight - 22,
size: line1Size,
font,
color: rgb(0.1, 0.1, 0.5),
});
// Séparateur
lastPage.drawLine({
start: { x: zoneX + 10, y: zoneY + zoneHeight - 30 },
end: { x: zoneX + zoneW - 10, y: zoneY + zoneHeight - 30 },
thickness: 0.5,
color: rgb(0.7, 0.7, 0.7),
});
// Ligne 2 : Service + Ventilation
const line2 = `Service : ${invoice.serviceConcerne || '-'} | Ventilation : ${invoice.ventilationComptable || '-'}`;
lastPage.drawText(line2, {
x: zoneX + 10,
y: zoneY + zoneHeight - 48,
size: 9,
font: fontNormal,
color: rgb(0.2, 0.2, 0.2),
});
// Ligne 3 : Date de validation
const now = new Date();
const dateStr = now.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric' });
const timeStr = now.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
lastPage.drawText(`Validé le ${dateStr} à ${timeStr}`, {
x: zoneX + 10,
y: zoneY + zoneHeight - 64,
size: 8,
font: fontNormal,
color: rgb(0.4, 0.4, 0.4),
});
// ── Signature du service ──────────────────────────────────────────
const serviceAssociations = await getServiceSignaturesByUser(ctx.user.id);
const serviceName = invoice.serviceConcerne || '';
const assoc = serviceAssociations.find(
a => a.serviceName.toLowerCase() === serviceName.toLowerCase()
);
if (assoc) {
const sig = await getSignatureById(assoc.signatureId);
if (sig) {
signatureName = `${sig.firstName} ${sig.lastName}`;
try {
const sigImagePath = path.join(STORAGE_BASE_PATH, sig.imageKey);
const sigImageBytes = await fs.readFile(sigImagePath);
const mimeType = sig.imageKey.toLowerCase().endsWith('.png') ? 'image/png' : 'image/jpeg';
let embeddedSig;
if (mimeType === 'image/png') {
embeddedSig = await pdfDoc.embedPng(sigImageBytes);
} else {
embeddedSig = await pdfDoc.embedJpg(sigImageBytes);
}
const sigWidth = 100;
const sigHeight = 45;
lastPage.drawImage(embeddedSig, {
x: zoneX + zoneW - sigWidth - 10,
y: zoneY + 20,
width: sigWidth,
height: sigHeight,
});
lastPage.drawText(signatureName, {
x: zoneX + zoneW - sigWidth - 10,
y: zoneY + 12,
size: 8,
font: fontNormal,
color: rgb(0.3, 0.3, 0.3),
});
} catch (_) { /* ignore signature errors */ }
}
}
const signedPdfBytes = await pdfDoc.save();
const filename = path.basename(invoice.fileKey);
const bapFilename = `BAP_${Date.now()}_${filename}`;
if (bapExportMode === 'folder' && exportFolder) {
// Mode dossier : enregistrer sur le disque
await fs.mkdir(exportFolder, { recursive: true });
exportPath = path.join(exportFolder, bapFilename);
await fs.writeFile(exportPath, signedPdfBytes);
} else {
// Mode navigateur : uploader sur S3 et retourner l'URL
const { storagePut: put } = await import('./storage');
const { url } = await put(`bap-exports/${bapFilename}`, Buffer.from(signedPdfBytes), 'application/pdf');
pdfUrl = url;
}
} catch (pdfError: any) {
console.warn('[BAP] Erreur génération PDF:', pdfError.message);
// On continue même si le PDF échoue — on valide quand même
}
// ── Mise à jour de la facture ─────────────────────────────────────
const validatedAt = new Date();
await updateInvoice(input.id, {
bapValidated: 1,
bapValidatedAt: new Date(),
bapValidatedAt: validatedAt,
});
return { success: true, validatedAt: new Date() };
// ── Enregistrement dans l'historique BAP ─────────────────────────
await createBapHistoryEntry({
userId: ctx.user.id,
invoiceId: invoice.id,
supplierName: invoice.supplierName || null,
invoiceNumber: invoice.invoiceNumber || null,
invoiceDate: invoice.invoiceDate || null,
totalAmount: invoice.totalAmount ? String(invoice.totalAmount) : null,
typeAchat: invoice.typeAchat || null,
serviceConcerne: invoice.serviceConcerne || null,
ventilationComptable: invoice.ventilationComptable || null,
recipientName: (invoice as any).recipientName || null,
exportMode: bapExportMode === 'folder' ? 'folder' : 'browser',
exportPath: exportPath || null,
pdfUrl: pdfUrl || null,
signatureName: signatureName || null,
validatedAt,
});
return {
success: true,
validatedAt,
pdfUrl,
exportPath,
exportMode: bapExportMode,
};
}),
search: protectedProcedure
// ── Historique BAP ────────────────────────────────────────────────────
search: protectedProcedure
.input(z.object({ query: z.string() }))
.query(async ({ input, ctx }) => {
return searchInvoices(ctx.user.id, input.query);
@@ -434,6 +607,22 @@ export const appRouter = router({
}),
}),
// ============= BAP HISTORY ROUTES =============
bapHistory: router({
getAll: protectedProcedure.query(async ({ ctx }) => {
return getBapHistoryByUser(ctx.user.id);
}),
delete: protectedProcedure
.input(z.object({ id: z.number() }))
.mutation(async ({ input, ctx }) => {
const entries = await getBapHistoryByUser(ctx.user.id);
const entry = entries.find(e => e.id === input.id);
if (!entry) throw new TRPCError({ code: 'NOT_FOUND' });
await deleteBapHistoryEntry(input.id);
return { success: true };
}),
}),
// ============= SOURCE FILES ROUTES =============
sourceFiles: router({
getByIds: protectedProcedure
@@ -888,6 +1077,7 @@ export const appRouter = router({
emailImportPort: 993,
emailImportFrequency: 30,
exportFolder: null,
bapExportMode: "browser" as const,
};
}
@@ -907,6 +1097,7 @@ export const appRouter = router({
emailImportPort: z.number().min(1).max(65535).optional(),
emailImportFrequency: z.number().min(1).optional(),
exportFolder: z.string().nullable().optional(),
bapExportMode: z.enum(["browser", "folder"]).optional(),
}))
.mutation(async ({ input, ctx }) => {
const settings = await upsertImportSettings({

11
todo.md
View File

@@ -586,3 +586,14 @@
- [x] Ajouter graphique Top destinataires dans Dashboard.tsx
- [x] Ajouter filtre destinataire dans la section SFTP de Settings.tsx
- [x] Mettre à jour la route settings.upsert pour sftpRecipientFilter
## Améliorations Factures BAP + Export PDF annoté + Historique BAP
- [x] Supprimer la colonne "Abonnement" de la fenêtre Factures BAP
- [x] Ajouter le choix du mode d'export dans les paramètres (dossier local ou ouverture navigateur)
- [x] Ajouter colonne bapExportMode dans importSettings (schéma DB + migration)
- [x] Générer PDF annoté lors du clic BAP : zone blanche avec CAPEX/OPEX, BAP, destinataire, signature du service
- [x] Exporter ou ouvrir le PDF selon le mode d'export configuré
- [x] Créer la page Historique BAP dans le menu Traçabilité
- [x] Ajouter table bapHistory en base de données (schéma + migration)
- [x] Enregistrer chaque validation BAP dans l'historique
- [x] Ajouter la route dans App.tsx et le lien dans le menu Traçabilité