Implement secure user authentication with role-based access control

Integrates user authentication using bcrypt, session management with PostgreSQL, and role-based access control for enhanced security and user management.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 91318273-c764-4fd4-be04-bdc12c38af32
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/0715008c-7244-40f4-befc-26c014852236/ab880d72-1a34-4d36-b5be-9f44df85ed1a.jpg
This commit is contained in:
michaelschal committed 2025-07-09 18:44:20 +00:00
1 parent 42b249e5b0
commit 5c01234fc4
16 files changed
+2384 -827

No files matched your search

+456
View File
@@ -0,0 +1,456 @@
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { insertUserSchema, insertStoreSchema, type User, type Store } from "@shared/schema";
import { Users, Building2, Plus, Edit } from "lucide-react";
import { z } from "zod";
const createUserSchema = insertUserSchema.extend({
confirmPassword: z.string(),
}).refine((data) => data.password === data.confirmPassword, {
message: "Les mots de passe ne correspondent pas",
path: ["confirmPassword"],
});
type CreateUserData = z.infer<typeof createUserSchema>;
export default function Administration() {
const { toast } = useToast();
const queryClient = useQueryClient();
const [isUserDialogOpen, setIsUserDialogOpen] = useState(false);
const [isStoreDialogOpen, setIsStoreDialogOpen] = useState(false);
// Queries
const { data: users = [], isLoading: usersLoading } = useQuery<User[]>({
queryKey: ['/api/admin/users'],
});
const { data: stores = [], isLoading: storesLoading } = useQuery<Store[]>({
queryKey: ['/api/admin/stores'],
});
// Mutations
const createUserMutation = useMutation({
mutationFn: (userData: CreateUserData) => {
const { confirmPassword, ...data } = userData;
return apiRequest('/api/admin/users', {
method: 'POST',
body: JSON.stringify(data),
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/admin/users'] });
setIsUserDialogOpen(false);
toast({ title: "Utilisateur créé avec succès" });
},
onError: () => {
toast({ title: "Erreur", description: "Impossible de créer l'utilisateur", variant: "destructive" });
},
});
const createStoreMutation = useMutation({
mutationFn: (storeData: z.infer<typeof insertStoreSchema>) =>
apiRequest('/api/admin/stores', {
method: 'POST',
body: JSON.stringify(storeData),
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/admin/stores'] });
setIsStoreDialogOpen(false);
toast({ title: "Magasin créé avec succès" });
},
onError: () => {
toast({ title: "Erreur", description: "Impossible de créer le magasin", variant: "destructive" });
},
});
// Forms
const userForm = useForm<CreateUserData>({
resolver: zodResolver(createUserSchema),
defaultValues: {
username: "",
password: "",
confirmPassword: "",
email: "",
firstName: "",
lastName: "",
role: "employee",
storeId: undefined,
isActive: true,
},
});
const storeForm = useForm<z.infer<typeof insertStoreSchema>>({
resolver: zodResolver(insertStoreSchema),
defaultValues: {
name: "",
address: "",
phone: "",
email: "",
isActive: true,
},
});
const onCreateUser = (data: CreateUserData) => {
createUserMutation.mutate(data);
};
const onCreateStore = (data: z.infer<typeof insertStoreSchema>) => {
createStoreMutation.mutate(data);
};
const getRoleBadge = (role: string) => {
const colors = {
admin: "bg-red-100 text-red-800",
manager: "bg-blue-100 text-blue-800",
employee: "bg-green-100 text-green-800",
};
return colors[role as keyof typeof colors] || "bg-gray-100 text-gray-800";
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h2 className="text-2xl font-bold">Administration</h2>
</div>
<Tabs defaultValue="users" className="space-y-4">
<TabsList>
<TabsTrigger value="users" className="flex items-center gap-2">
<Users className="h-4 w-4" />
Utilisateurs
</TabsTrigger>
<TabsTrigger value="stores" className="flex items-center gap-2">
<Building2 className="h-4 w-4" />
Magasins
</TabsTrigger>
</TabsList>
<TabsContent value="users">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
<CardTitle>Gestion des Utilisateurs</CardTitle>
<Dialog open={isUserDialogOpen} onOpenChange={setIsUserDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
Nouvel Utilisateur
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Créer un Utilisateur</DialogTitle>
</DialogHeader>
<Form {...userForm}>
<form onSubmit={userForm.handleSubmit(onCreateUser)} className="space-y-4">
<FormField
control={userForm.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Nom d'utilisateur</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-2 gap-4">
<FormField
control={userForm.control}
name="firstName"
render={({ field }) => (
<FormItem>
<FormLabel>Prénom</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={userForm.control}
name="lastName"
render={({ field }) => (
<FormItem>
<FormLabel>Nom</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={userForm.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={userForm.control}
name="role"
render={({ field }) => (
<FormItem>
<FormLabel>Rôle</FormLabel>
<Select value={field.value} onValueChange={field.onChange}>
<FormControl>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="admin">Administrateur</SelectItem>
<SelectItem value="manager">Manager</SelectItem>
<SelectItem value="employee">Employé</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={userForm.control}
name="storeId"
render={({ field }) => (
<FormItem>
<FormLabel>Magasin</FormLabel>
<Select value={field.value?.toString()} onValueChange={(value) => field.onChange(parseInt(value))}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Sélectionner un magasin" />
</SelectTrigger>
</FormControl>
<SelectContent>
{stores.map((store) => (
<SelectItem key={store.id} value={store.id.toString()}>
{store.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={userForm.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Mot de passe</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={userForm.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel>Confirmer le mot de passe</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={createUserMutation.isPending}>
{createUserMutation.isPending ? "Création..." : "Créer"}
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
</CardHeader>
<CardContent>
{usersLoading ? (
<p>Chargement...</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Utilisateur</TableHead>
<TableHead>Email</TableHead>
<TableHead>Rôle</TableHead>
<TableHead>Magasin</TableHead>
<TableHead>Statut</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{users.map((user) => (
<TableRow key={user.id}>
<TableCell>
<div>
<p className="font-medium">{user.firstName} {user.lastName}</p>
<p className="text-sm text-gray-500">{user.username}</p>
</div>
</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getRoleBadge(user.role)}`}>
{user.role === 'admin' ? 'Administrateur' :
user.role === 'manager' ? 'Manager' : 'Employé'}
</span>
</TableCell>
<TableCell>
{stores.find(s => s.id === user.storeId)?.name || '-'}
</TableCell>
<TableCell>
{user.isActive ? (
<span className="text-green-600">Actif</span>
) : (
<span className="text-red-600">Inactif</span>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="stores">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
<CardTitle>Gestion des Magasins</CardTitle>
<Dialog open={isStoreDialogOpen} onOpenChange={setIsStoreDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
Nouveau Magasin
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Créer un Magasin</DialogTitle>
</DialogHeader>
<Form {...storeForm}>
<form onSubmit={storeForm.handleSubmit(onCreateStore)} className="space-y-4">
<FormField
control={storeForm.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Nom du magasin</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={storeForm.control}
name="address"
render={({ field }) => (
<FormItem>
<FormLabel>Adresse</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={storeForm.control}
name="phone"
render={({ field }) => (
<FormItem>
<FormLabel>Téléphone</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={storeForm.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={createStoreMutation.isPending}>
{createStoreMutation.isPending ? "Création..." : "Créer"}
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
</CardHeader>
<CardContent>
{storesLoading ? (
<p>Chargement...</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Nom</TableHead>
<TableHead>Adresse</TableHead>
<TableHead>Téléphone</TableHead>
<TableHead>Email</TableHead>
<TableHead>Statut</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{stores.map((store) => (
<TableRow key={store.id}>
<TableCell className="font-medium">{store.name}</TableCell>
<TableCell>{store.address}</TableCell>
<TableCell>{store.phone}</TableCell>
<TableCell>{store.email}</TableCell>
<TableCell>
{store.isActive ? (
<span className="text-green-600">Actif</span>
) : (
<span className="text-red-600">Inactif</span>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
);
}
+389 -514
View File
@@ -1,28 +1,38 @@
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useToast } from '@/hooks/use-toast';
import { Camera, User, Package, Users, IdCard, Save, X, Trash2 } from 'lucide-react';
import { Sale, FormData, PhotoType } from '@/types/sale';
import { apiRequest } from '@/lib/queryClient';
import { validateRequiredFields, validateEAN13, ARTICLE_CATEGORY_MAPPING, IDENTITY_TYPES } from '@/lib/validation';
import { useCamera } from '@/hooks/useCamera';
import CameraModal from './CameraModal';
import { Package, User, Users, Save, X } from 'lucide-react';
interface NewSaleFormProps {
onSaveSale: (sale: Omit<Sale, 'id' | 'timestamp'>) => Promise<Sale>;
interface FormData {
vendeur: string;
dateVente: string;
typeArticle: string;
categorie: string;
quantite: string;
gencode: string;
nom: string;
prenom: string;
dateNaissance: string;
lieuNaissance: string;
typeIdentite: string;
numeroIdentite: string;
autoriteDelivrance: string;
dateDelivrance: string;
}
export default function NewSaleForm({ onSaveSale }: NewSaleFormProps) {
export default function NewSaleForm() {
const { toast } = useToast();
const [photos, setPhotos] = useState<{ recto?: string; verso?: string }>({});
const queryClient = useQueryClient();
const [isSubmitting, setIsSubmitting] = useState(false);
const camera = useCamera();
const form = useForm<FormData>({
defaultValues: {
@@ -46,92 +56,18 @@ export default function NewSaleForm({ onSaveSale }: NewSaleFormProps) {
const typeArticle = form.watch('typeArticle');
const availableCategories = typeArticle ? ARTICLE_CATEGORY_MAPPING[typeArticle as keyof typeof ARTICLE_CATEGORY_MAPPING] || [] : [];
const handlePhotoCapture = async (photoType: PhotoType) => {
try {
await camera.startCamera(photoType);
const createSaleMutation = useMutation({
mutationFn: (saleData: any) =>
apiRequest('/api/sales', {
method: 'POST',
body: JSON.stringify(saleData),
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/sales'] });
toast({
title: "Caméra activée",
description: "Positionnez la carte d'identité",
title: "Vente enregistrée",
description: "La vente a été enregistrée avec succès",
});
} catch (error) {
toast({
title: "Erreur caméra",
description: error instanceof Error ? error.message : "Impossible d'accéder à la caméra",
variant: "destructive",
});
}
};
const handlePhotoTaken = (photoType: PhotoType, photoData: string) => {
setPhotos(prev => ({ ...prev, [photoType]: photoData }));
toast({
title: "Photo capturée",
description: `Photo ${photoType} sauvegardée avec succès`,
});
};
const deletePhoto = (photoType: PhotoType) => {
setPhotos(prev => {
const newPhotos = { ...prev };
delete newPhotos[photoType];
return newPhotos;
});
toast({
title: "Photo supprimée",
description: `Photo ${photoType} supprimée`,
});
};
const onSubmit = async (data: FormData) => {
try {
setIsSubmitting(true);
console.log('Form data being submitted:', data);
console.log('Form errors:', form.formState.errors);
// Validate required fields
const missingFields = validateRequiredFields(data);
if (missingFields.length > 0) {
console.log('Missing fields found:', missingFields);
toast({
title: "Champs manquants",
description: `Veuillez remplir: ${missingFields.join(', ')}`,
variant: "destructive",
});
return;
}
// Validate EAN13 (now required)
if (!validateEAN13(data.gencode)) {
toast({
title: "Code EAN13 invalide",
description: "Le gencode doit être un code EAN13 valide à 13 chiffres",
variant: "destructive",
});
return;
}
const saleData: Omit<Sale, 'id' | 'timestamp'> = {
vendeur: data.vendeur,
dateVente: data.dateVente,
typeArticle: data.typeArticle,
categorie: data.categorie as 'F2' | 'F3',
quantite: parseInt(data.quantite),
gencode: data.gencode,
nom: data.nom,
prenom: data.prenom,
dateNaissance: data.dateNaissance,
lieuNaissance: data.lieuNaissance || undefined,
typeIdentite: data.typeIdentite,
numeroIdentite: data.numeroIdentite,
autoriteDelivrance: data.autoriteDelivrance,
dateDelivrance: data.dateDelivrance,
photoRecto: photos.recto,
photoVerso: photos.verso,
};
await onSaveSale(saleData);
// Reset form
form.reset({
vendeur: '',
dateVente: new Date().toISOString().split('T')[0],
@@ -148,445 +84,384 @@ export default function NewSaleForm({ onSaveSale }: NewSaleFormProps) {
autoriteDelivrance: '',
dateDelivrance: '',
});
setPhotos({});
toast({
title: "Vente enregistrée",
description: "La vente a été enregistrée avec succès",
});
} catch (error) {
},
onError: (error: any) => {
toast({
title: "Erreur",
description: "Erreur lors de l'enregistrement de la vente",
description: error.message || "Erreur lors de l'enregistrement de la vente",
variant: "destructive",
});
},
});
const onSubmit = async (data: FormData) => {
try {
setIsSubmitting(true);
// Validate required fields
const missingFields = validateRequiredFields(data);
if (missingFields.length > 0) {
toast({
title: "Champs manquants",
description: `Veuillez remplir: ${missingFields.join(', ')}`,
variant: "destructive",
});
return;
}
// Validate EAN13
if (!validateEAN13(data.gencode)) {
toast({
title: "Code EAN13 invalide",
description: "Le gencode doit être un code EAN13 valide à 13 chiffres",
variant: "destructive",
});
return;
}
const saleData = {
vendeur: data.vendeur,
dateVente: data.dateVente,
typeArticle: data.typeArticle,
categorie: data.categorie as 'F2' | 'F3',
quantite: parseInt(data.quantite),
gencode: data.gencode,
nom: data.nom,
prenom: data.prenom,
dateNaissance: data.dateNaissance,
lieuNaissance: data.lieuNaissance || undefined,
typeIdentite: data.typeIdentite,
numeroIdentite: data.numeroIdentite,
autoriteDelivrance: data.autoriteDelivrance,
dateDelivrance: data.dateDelivrance,
};
await createSaleMutation.mutateAsync(saleData);
} catch (error) {
console.error('Sale creation error:', error);
} finally {
setIsSubmitting(false);
}
};
return (
<>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Package className="h-5 w-5" />
Nouvelle Vente
</CardTitle>
<p className="text-sm text-muted-foreground">
Enregistrement d'une vente de feux d'artifice
</p>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
{/* Seller Information */}
<div className="border-l-4 border-primary pl-4">
<h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
<User className="h-5 w-5 text-primary" />
Informations Vendeur
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="vendeur"
render={({ field }) => (
<FormItem>
<FormLabel>Vendeur <span className="text-destructive">*</span></FormLabel>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Package className="h-5 w-5" />
Nouvelle Vente
</CardTitle>
<p className="text-sm text-muted-foreground">
Enregistrement d'une vente de feux d'artifice
</p>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
{/* Seller Information */}
<div className="border-l-4 border-primary pl-4">
<h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
<User className="h-5 w-5 text-primary" />
Informations Vendeur
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="vendeur"
render={({ field }) => (
<FormItem>
<FormLabel>Vendeur <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Nom du vendeur" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dateVente"
render={({ field }) => (
<FormItem>
<FormLabel>Date de vente</FormLabel>
<FormControl>
<Input type="date" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
{/* Product Information */}
<div className="border-l-4 border-info pl-4">
<h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
<Package className="h-5 w-5 text-info" />
Informations Produit
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="typeArticle"
render={({ field }) => (
<FormItem>
<FormLabel>Type d'article <span className="text-destructive">*</span></FormLabel>
<Select value={field.value} onValueChange={(value) => {
field.onChange(value);
form.setValue('categorie', ''); // Reset category when article changes
}}>
<FormControl>
<Input placeholder="Vendeur" {...field} />
<SelectTrigger>
<SelectValue placeholder="Sélectionner un type" />
</SelectTrigger>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dateVente"
render={({ field }) => (
<FormItem>
<FormLabel>Date de vente</FormLabel>
<SelectContent>
{Object.keys(ARTICLE_CATEGORY_MAPPING).map((type) => (
<SelectItem key={type} value={type}>
{type}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="categorie"
render={({ field }) => (
<FormItem>
<FormLabel>Catégorie réglementaire <span className="text-destructive">*</span></FormLabel>
<Select value={field.value} onValueChange={field.onChange} disabled={!typeArticle}>
<FormControl>
<Input type="date" {...field} />
<SelectTrigger>
<SelectValue placeholder="Sélectionner une catégorie" />
</SelectTrigger>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<SelectContent>
{availableCategories.map((category) => (
<SelectItem key={category} value={category}>
{category}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="quantite"
render={({ field }) => (
<FormItem>
<FormLabel>Quantité <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input type="number" min="1" placeholder="Entrez la quantité" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="gencode"
render={({ field }) => (
<FormItem>
<FormLabel>Gencode (EAN13) <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Code EAN13 à 13 chiffres" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Product Information */}
<div className="border-l-4 border-info pl-4">
<h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
<Package className="h-5 w-5 text-info" />
Informations Produit
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="typeArticle"
render={({ field }) => (
<FormItem>
<FormLabel>Type d'article <span className="text-destructive">*</span></FormLabel>
<Select value={field.value} onValueChange={(value) => {
field.onChange(value);
form.setValue('categorie', ''); // Reset category when article changes
}}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Sélectionner un type" />
</SelectTrigger>
</FormControl>
<SelectContent>
{Object.keys(ARTICLE_CATEGORY_MAPPING).map((type) => (
<SelectItem key={type} value={type}>
{type}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="categorie"
render={({ field }) => (
<FormItem>
<FormLabel>Catégorie réglementaire <span className="text-destructive">*</span></FormLabel>
<Select value={field.value} onValueChange={field.onChange} disabled={!typeArticle}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Sélectionner une catégorie" />
</SelectTrigger>
</FormControl>
<SelectContent>
{availableCategories.map((category) => (
<SelectItem key={category} value={category}>
{category}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="quantite"
render={({ field }) => (
<FormItem>
<FormLabel>Quantité <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input type="number" min="1" placeholder="Entrez la quantité" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="gencode"
render={({ field }) => (
<FormItem>
<FormLabel>Gencode (EAN13) <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Code EAN13 à 13 chiffres" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<Alert className="mt-4">
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<AlertDescription>
<strong>Information réglementaire :</strong>
<ul className="mt-1 space-y-1 text-sm">
<li>• <strong>F2</strong> : Feux d'artifice de catégorie F2 - Vente libre aux majeurs</li>
<li>• <strong>F3</strong> : Feux d'artifice de catégorie F3 - Vente soumise à autorisation préfectorale</li>
</ul>
</AlertDescription>
</Alert>
</div>
<Alert className="mt-4">
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<AlertDescription>
<strong>Information réglementaire :</strong>
<ul className="mt-1 space-y-1 text-sm">
<li>• <strong>F2</strong> : Feux d'artifice de catégorie F2 - Vente libre aux majeurs</li>
<li>• <strong>F3</strong> : Feux d'artifice de catégorie F3 - Vente soumise à autorisation préfectorale</li>
</ul>
</AlertDescription>
</Alert>
{/* Customer Information */}
<div className="border-l-4 border-success pl-4">
<h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
<Users className="h-5 w-5 text-success" />
Informations Client
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="nom"
render={({ field }) => (
<FormItem>
<FormLabel>Nom de famille <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Nom de famille" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="prenom"
render={({ field }) => (
<FormItem>
<FormLabel>Prénom <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Prénom" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dateNaissance"
render={({ field }) => (
<FormItem>
<FormLabel>Date de naissance <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input type="date" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="lieuNaissance"
render={({ field }) => (
<FormItem>
<FormLabel>Lieu de naissance</FormLabel>
<FormControl>
<Input placeholder="Ville de naissance" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
{/* Customer Information */}
<div className="border-l-4 border-success pl-4">
<h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
<Users className="h-5 w-5 text-success" />
Informations Client
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="nom"
render={({ field }) => (
<FormItem>
<FormLabel>Nom de famille <span className="text-destructive">*</span></FormLabel>
{/* Identity Information */}
<div className="border-l-4 border-warning pl-4">
<h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
<svg className="h-5 w-5 text-warning" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V8a2 2 0 00-2-2h-5m-4 0V5a2 2 0 114 0v1m-4 0a2 2 0 104 0m-5 8a2 2 0 100-4 2 2 0 000 4zm0 0c1.306 0 2.417.835 2.83 2M9 14a3.001 3.001 0 00-2.83 2M15 11h3m-3 4h2" />
</svg>
Pièce d'Identité
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="typeIdentite"
render={({ field }) => (
<FormItem>
<FormLabel>Type de pièce d'identité <span className="text-destructive">*</span></FormLabel>
<Select value={field.value} onValueChange={field.onChange}>
<FormControl>
<Input placeholder="Nom de famille" {...field} />
<SelectTrigger>
<SelectValue placeholder="Sélectionner le type" />
</SelectTrigger>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="prenom"
render={({ field }) => (
<FormItem>
<FormLabel>Prénom <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Prénom" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dateNaissance"
render={({ field }) => (
<FormItem>
<FormLabel>Date de naissance <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input type="date" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="lieuNaissance"
render={({ field }) => (
<FormItem>
<FormLabel>Lieu de naissance</FormLabel>
<FormControl>
<Input placeholder="Ville de naissance" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<SelectContent>
{IDENTITY_TYPES.map((type) => (
<SelectItem key={type.value} value={type.value}>
{type.label}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="numeroIdentite"
render={({ field }) => (
<FormItem>
<FormLabel>Numéro de pièce d'identité <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Numéro de la pièce d'identité" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="autoriteDelivrance"
render={({ field }) => (
<FormItem>
<FormLabel>Autorité de délivrance <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Préfecture, Mairie, etc." {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dateDelivrance"
render={({ field }) => (
<FormItem>
<FormLabel>Date de délivrance <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input type="date" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
{/* Identity Document */}
<div className="border-l-4 border-yellow-500 pl-4">
<h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
<IdCard className="h-5 w-5 text-yellow-600" />
Pièce d'Identité
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<FormField
control={form.control}
name="typeIdentite"
render={({ field }) => (
<FormItem>
<FormLabel>Type de pièce d'identité <span className="text-destructive">*</span></FormLabel>
<Select value={field.value} onValueChange={field.onChange}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Sélectionner un type" />
</SelectTrigger>
</FormControl>
<SelectContent>
{IDENTITY_TYPES.map((type) => (
<SelectItem key={type.value} value={type.value}>
{type.label}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="numeroIdentite"
render={({ field }) => (
<FormItem>
<FormLabel>Numéro de pièce d'identité <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Numéro de la pièce d'identité" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="autoriteDelivrance"
render={({ field }) => (
<FormItem>
<FormLabel>Autorité de délivrance <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Préfecture, Mairie, etc." {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dateDelivrance"
render={({ field }) => (
<FormItem>
<FormLabel>Date de délivrance <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input type="date" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
{/* Identity Photos */}
<div className="border-l-4 border-purple-500 pl-4">
<h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
<Camera className="h-5 w-5 text-purple-600" />
Photos de la Pièce d'Identité
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Photo Recto */}
<div className="space-y-3">
<label className="block text-sm font-medium text-gray-700">Photo Recto</label>
<div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
{photos.recto ? (
<div>
<img src={photos.recto} alt="Photo recto" className="mx-auto rounded-lg shadow-md max-h-32" />
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => deletePhoto('recto')}
className="mt-2 text-destructive hover:text-destructive"
>
<Trash2 className="h-4 w-4 mr-1" />
Supprimer
</Button>
</div>
) : (
<div>
<Camera className="h-8 w-8 text-gray-400 mx-auto mb-2" />
<p className="text-sm text-gray-500 mb-3">Aucune photo</p>
<Button
type="button"
onClick={() => handlePhotoCapture('recto')}
className="bg-primary text-white hover:bg-primary/90"
>
<Camera className="h-4 w-4 mr-2" />
Prendre photo
</Button>
</div>
)}
</div>
</div>
{/* Photo Verso */}
<div className="space-y-3">
<label className="block text-sm font-medium text-gray-700">Photo Verso</label>
<div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
{photos.verso ? (
<div>
<img src={photos.verso} alt="Photo verso" className="mx-auto rounded-lg shadow-md max-h-32" />
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => deletePhoto('verso')}
className="mt-2 text-destructive hover:text-destructive"
>
<Trash2 className="h-4 w-4 mr-1" />
Supprimer
</Button>
</div>
) : (
<div>
<Camera className="h-8 w-8 text-gray-400 mx-auto mb-2" />
<p className="text-sm text-gray-500 mb-3">Aucune photo</p>
<Button
type="button"
onClick={() => handlePhotoCapture('verso')}
className="bg-primary text-white hover:bg-primary/90"
>
<Camera className="h-4 w-4 mr-2" />
Prendre photo
</Button>
</div>
)}
</div>
</div>
</div>
</div>
{/* Form Actions - Always visible */}
<div className="flex justify-end space-x-4 pt-6 border-t border-gray-200 bg-white">
<Button type="button" variant="outline" onClick={() => {
form.reset({
vendeur: '',
dateVente: new Date().toISOString().split('T')[0],
typeArticle: '',
categorie: '',
quantite: '',
gencode: '',
nom: '',
prenom: '',
dateNaissance: '',
lieuNaissance: '',
typeIdentite: '',
numeroIdentite: '',
autoriteDelivrance: '',
dateDelivrance: '',
});
setPhotos({});
}}>
<X className="h-4 w-4 mr-2" />
Annuler
</Button>
<Button type="submit" disabled={isSubmitting} className="bg-green-600 hover:bg-green-700 text-white">
<Save className="h-4 w-4 mr-2" />
{isSubmitting ? 'Enregistrement...' : 'Enregistrer la Vente'}
</Button>
</div>
</form>
</Form>
</CardContent>
</Card>
<CameraModal
isOpen={camera.isOpen}
photoType={camera.currentPhotoType}
videoRef={camera.videoRef}
canvasRef={camera.canvasRef}
isCapturing={camera.isCapturing}
onClose={camera.stopCamera}
onCapture={async () => {
try {
const photoData = await camera.capturePhoto();
if (camera.currentPhotoType) {
handlePhotoTaken(camera.currentPhotoType, photoData);
}
camera.stopCamera();
} catch (error) {
toast({
title: "Erreur",
description: "Erreur lors de la capture de la photo",
variant: "destructive",
});
}
}}
/>
</>
{/* Form Actions - Always visible */}
<div className="flex justify-end space-x-4 pt-6 border-t border-gray-200 bg-white">
<Button type="button" variant="outline" onClick={() => {
form.reset({
vendeur: '',
dateVente: new Date().toISOString().split('T')[0],
typeArticle: '',
categorie: '',
quantite: '',
gencode: '',
nom: '',
prenom: '',
dateNaissance: '',
lieuNaissance: '',
typeIdentite: '',
numeroIdentite: '',
autoriteDelivrance: '',
dateDelivrance: '',
});
}}>
<X className="h-4 w-4 mr-2" />
Annuler
</Button>
<Button type="submit" disabled={isSubmitting || createSaleMutation.isPending} className="bg-green-600 hover:bg-green-700 text-white">
<Save className="h-4 w-4 mr-2" />
{isSubmitting || createSaleMutation.isPending ? 'Enregistrement...' : 'Enregistrer la Vente'}
</Button>
</div>
</form>
</Form>
</CardContent>
</Card>
);
}
}
+245 -243
View File
@@ -1,284 +1,286 @@
import { useState } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { useToast } from '@/hooks/use-toast';
import { Download, Save, Search, Eye, Trash2, BarChart3, AlertCircle } from 'lucide-react';
import { Sale } from '@/types/sale';
import { exportToCSV, formatDate } from '@/lib/export';
import { downloadBackup, getAutoBackup } from '@/lib/storage';
import SaleDetailsModal from './SaleDetailsModal';
import { apiRequest } from '@/lib/queryClient';
import type { Sale } from '@shared/schema';
import { History, Download, Trash2, Eye, Filter } from 'lucide-react';
interface SalesHistoryProps {
sales: Sale[];
isLoading: boolean;
error: string | null;
onDeleteSale: (id: number) => Promise<void>;
canDelete?: boolean;
}
export default function SalesHistory({ sales, isLoading, error, onDeleteSale }: SalesHistoryProps) {
export default function SalesHistory({ canDelete = false }: SalesHistoryProps) {
const { toast } = useToast();
const queryClient = useQueryClient();
const [selectedSale, setSelectedSale] = useState<Sale | null>(null);
const [isDeleting, setIsDeleting] = useState<number | null>(null);
const [startDate, setStartDate] = useState('');
const [endDate, setEndDate] = useState('');
const handleExportCSV = () => {
if (sales.length === 0) {
toast({
title: "Aucune vente à exporter",
description: "Il n'y a aucune vente enregistrée",
});
return;
}
// Query for sales
const { data: sales = [], isLoading } = useQuery<Sale[]>({
queryKey: ['/api/sales', startDate, endDate],
queryFn: () => {
const params = new URLSearchParams();
if (startDate) params.append('startDate', startDate);
if (endDate) params.append('endDate', endDate);
const queryString = params.toString();
return apiRequest(`/api/sales${queryString ? `?${queryString}` : ''}`);
},
});
try {
exportToCSV(sales);
toast({
title: "Export réussi !",
description: `${sales.length} vente(s) exportée(s)`,
});
} catch (error) {
toast({
title: "Erreur d'export",
description: "Impossible d'exporter les données",
variant: "destructive",
});
}
};
const handleDownloadBackup = () => {
const backup = getAutoBackup();
if (!backup) {
toast({
title: "Aucune sauvegarde disponible",
description: "Aucun backup automatique trouvé",
});
return;
}
try {
downloadBackup();
toast({
title: "Backup téléchargé",
description: "Sauvegarde téléchargée avec succès",
});
} catch (error) {
toast({
title: "Erreur",
description: "Impossible de télécharger la sauvegarde",
variant: "destructive",
});
}
};
const handleDiagnostic = () => {
console.log('=== DIAGNOSTIC COMPLET ===');
console.log('Nombre de ventes:', sales.length);
console.log('Données:', sales);
console.log('LocalStorage backup:', getAutoBackup());
toast({
title: "Diagnostic affiché",
description: "Vérifiez la console pour les détails",
});
};
const handleDeleteSale = async (sale: Sale) => {
const confirmed = window.confirm(
`Supprimer définitivement la vente de ${sale.nom} ${sale.prenom} ?\n\n⚠️ Cette action est irréversible !\n\nID: ${sale.id}`
);
if (!confirmed) return;
try {
setIsDeleting(sale.id);
await onDeleteSale(sale.id);
// Delete mutation
const deleteSaleMutation = useMutation({
mutationFn: (saleId: number) =>
apiRequest(`/api/sales/${saleId}`, { method: 'DELETE' }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/sales'] });
toast({
title: "Vente supprimée",
description: `Vente de ${sale.nom} ${sale.prenom} supprimée`,
description: "La vente a été supprimée avec succès",
});
} catch (error) {
},
onError: () => {
toast({
title: "Erreur",
description: "Impossible de supprimer la vente",
variant: "destructive",
});
} finally {
setIsDeleting(null);
},
});
const handleDeleteSale = async (sale: Sale) => {
if (confirm(`Êtes-vous sûr de vouloir supprimer cette vente ?`)) {
deleteSaleMutation.mutate(sale.id);
}
};
const backup = getAutoBackup();
const exportToCSV = () => {
if (sales.length === 0) {
toast({
title: "Aucune donnée",
description: "Aucune vente à exporter",
variant: "destructive",
});
return;
}
if (isLoading) {
return (
<Card>
<CardContent className="flex items-center justify-center py-8">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
<p className="text-muted-foreground">Chargement des ventes...</p>
</div>
</CardContent>
</Card>
);
}
const csvHeader = [
'Date/Heure',
'Vendeur',
'Date de vente',
'Type d\'article',
'Catégorie',
'Quantité',
'Gencode',
'Nom client',
'Prénom client',
'Date de naissance',
'Lieu de naissance',
'Type identité',
'Numéro identité',
'Autorité délivrance',
'Date délivrance'
].join(',');
if (error) {
return (
<Card>
<CardContent className="flex items-center justify-center py-8">
<div className="text-center">
<AlertCircle className="h-8 w-8 text-destructive mx-auto mb-2" />
<p className="text-destructive">{error}</p>
</div>
</CardContent>
</Card>
);
}
const csvData = sales.map(sale => [
new Date(sale.timestamp!).toLocaleString('fr-FR'),
sale.vendeur,
sale.dateVente,
sale.typeArticle,
sale.categorie,
sale.quantite,
sale.gencode,
sale.nom,
sale.prenom,
sale.dateNaissance,
sale.lieuNaissance || '',
sale.typeIdentite,
sale.numeroIdentite,
sale.autoriteDelivrance,
sale.dateDelivrance
].map(field => `"${field}"`).join(',')).join('\n');
const csvContent = csvHeader + '\n' + csvData;
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `ventes_fireworks_${new Date().toISOString().split('T')[0]}.csv`;
link.click();
toast({
title: "Export réussi",
description: `${sales.length} ventes exportées`,
});
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('fr-FR');
};
const formatDateTime = (dateString: string) => {
return new Date(dateString).toLocaleString('fr-FR');
};
return (
<>
<Card>
<CardHeader>
<div className="flex justify-between items-center">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<History className="h-5 w-5" />
Historique des Ventes
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Filters */}
<div className="flex gap-4 items-end">
<div className="grid grid-cols-2 gap-4 flex-1">
<div>
<CardTitle className="flex items-center gap-2">
<BarChart3 className="h-5 w-5" />
Historique des Ventes
</CardTitle>
<p className="text-sm text-muted-foreground mt-1">
Gestion et export des ventes enregistrées
</p>
<label className="text-sm font-medium">Date de début</label>
<Input
type="date"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
/>
</div>
<div className="flex space-x-3">
<Button onClick={handleExportCSV} className="bg-success hover:bg-success/90">
<Download className="h-4 w-4 mr-2" />
Exporter CSV
</Button>
<Button onClick={handleDownloadBackup} variant="outline">
<Save className="h-4 w-4 mr-2" />
Backup Auto
</Button>
<Button onClick={handleDiagnostic} variant="outline">
<Search className="h-4 w-4 mr-2" />
Debug
</Button>
<div>
<label className="text-sm font-medium">Date de fin</label>
<Input
type="date"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
/>
</div>
</div>
</CardHeader>
{/* Status Information */}
<div className="px-6 py-3 bg-muted border-b border-border">
<div className="flex items-center text-sm text-muted-foreground">
<svg className="h-4 w-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>
Données stockées localement ({sales.length} vente{sales.length !== 1 ? 's' : ''}) • Export CSV compatible Excel • Sauvegarde automatique à chaque ajout
</span>
</div>
<div className="text-xs text-muted-foreground mt-1">
{backup ? (
<span>
Dernier backup: {formatDate(backup.timestamp)} ({backup.recordCount} enreg.)
</span>
) : (
<span>Dernier backup: Aucun</span>
)}
</div>
<Button onClick={exportToCSV} variant="outline">
<Download className="h-4 w-4 mr-2" />
Export CSV
</Button>
</div>
<CardContent className="p-0">
{sales.length === 0 ? (
<div className="text-center py-8">
<svg className="h-12 w-12 text-muted-foreground mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
</svg>
<p className="text-muted-foreground">Aucune vente enregistrée</p>
</div>
) : (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Date</TableHead>
<TableHead>Vendeur</TableHead>
<TableHead>Client</TableHead>
<TableHead>Produit</TableHead>
<TableHead>Catégorie</TableHead>
<TableHead>Quantité</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sales.map((sale) => (
<TableRow key={sale.id}>
<TableCell>
{formatDate(sale.dateVente)}
</TableCell>
<TableCell>
{sale.vendeur || 'Non spécifié'}
</TableCell>
<TableCell>
<div>
<div className="font-medium">{sale.nom} {sale.prenom}</div>
{sale.typeIdentite && (
<div className="text-xs text-muted-foreground">{sale.typeIdentite}</div>
)}
</div>
</TableCell>
<TableCell>
<div>
<div className="font-medium">{sale.typeArticle}</div>
{sale.gencode && (
<div className="text-xs text-muted-foreground">{sale.gencode}</div>
)}
</div>
</TableCell>
<TableCell>
<Badge variant={sale.categorie === 'F2' ? 'secondary' : 'destructive'}>
{/* Sales Table */}
{isLoading ? (
<div className="flex justify-center py-8">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
</div>
) : sales.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
Aucune vente trouvée
</div>
) : (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Date/Heure</TableHead>
<TableHead>Vendeur</TableHead>
<TableHead>Client</TableHead>
<TableHead>Article</TableHead>
<TableHead>Quantité</TableHead>
<TableHead>Gencode</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sales.map((sale) => (
<TableRow key={sale.id}>
<TableCell>{formatDateTime(sale.timestamp!)}</TableCell>
<TableCell>{sale.vendeur}</TableCell>
<TableCell>
<div>
<p className="font-medium">{sale.nom} {sale.prenom}</p>
<p className="text-sm text-muted-foreground">
{formatDate(sale.dateNaissance)}
</p>
</div>
</TableCell>
<TableCell>
<div>
<p className="font-medium">{sale.typeArticle}</p>
<span className={`inline-flex px-2 py-1 text-xs rounded-full ${
sale.categorie === 'F3'
? 'bg-red-100 text-red-800'
: 'bg-green-100 text-green-800'
}`}>
{sale.categorie}
</Badge>
</TableCell>
<TableCell>
{sale.quantite}
</TableCell>
<TableCell>
<div className="flex space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() => setSelectedSale(sale)}
title="Voir les détails"
>
<Eye className="h-4 w-4" />
</Button>
</span>
</div>
</TableCell>
<TableCell>{sale.quantite}</TableCell>
<TableCell>{sale.gencode}</TableCell>
<TableCell>
<div className="flex gap-2">
<Dialog>
<DialogTrigger asChild>
<Button
variant="ghost"
size="sm"
onClick={() => setSelectedSale(sale)}
>
<Eye className="h-4 w-4" />
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Détails de la vente</DialogTitle>
</DialogHeader>
{selectedSale && (
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<h4 className="font-medium mb-2">Informations générales</h4>
<p><strong>Date/Heure :</strong> {formatDateTime(selectedSale.timestamp!)}</p>
<p><strong>Vendeur :</strong> {selectedSale.vendeur}</p>
<p><strong>Date de vente :</strong> {formatDate(selectedSale.dateVente)}</p>
</div>
<div>
<h4 className="font-medium mb-2">Produit</h4>
<p><strong>Type :</strong> {selectedSale.typeArticle}</p>
<p><strong>Catégorie :</strong> {selectedSale.categorie}</p>
<p><strong>Quantité :</strong> {selectedSale.quantite}</p>
<p><strong>Gencode :</strong> {selectedSale.gencode}</p>
</div>
<div>
<h4 className="font-medium mb-2">Client</h4>
<p><strong>Nom :</strong> {selectedSale.nom}</p>
<p><strong>Prénom :</strong> {selectedSale.prenom}</p>
<p><strong>Date de naissance :</strong> {formatDate(selectedSale.dateNaissance)}</p>
{selectedSale.lieuNaissance && (
<p><strong>Lieu de naissance :</strong> {selectedSale.lieuNaissance}</p>
)}
</div>
<div>
<h4 className="font-medium mb-2">Pièce d'identité</h4>
<p><strong>Type :</strong> {selectedSale.typeIdentite}</p>
<p><strong>Numéro :</strong> {selectedSale.numeroIdentite}</p>
<p><strong>Autorité :</strong> {selectedSale.autoriteDelivrance}</p>
<p><strong>Date délivrance :</strong> {formatDate(selectedSale.dateDelivrance)}</p>
</div>
</div>
)}
</DialogContent>
</Dialog>
{canDelete && (
<Button
variant="ghost"
size="sm"
onClick={() => handleDeleteSale(sale)}
disabled={isDeleting === sale.id}
className="text-destructive hover:text-destructive"
title="Supprimer la vente"
disabled={deleteSaleMutation.isPending}
>
<Trash2 className="h-4 w-4" />
<Trash2 className="h-4 w-4 text-red-600" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
<SaleDetailsModal
isOpen={!!selectedSale}
sale={selectedSale}
onClose={() => setSelectedSale(null)}
/>
</>
)}
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
);
}
}