Saved your changes before starting work

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 4b008663-bd72-492b-b0b6-fa252367e730
This commit is contained in:
michaelschal committed 2025-07-19 13:16:10 +00:00
1 parent a0fd8e0a25
commit ae1fd208c2
21 files changed
+2232 -969

No files matched your search

+39 -23
View File
@@ -74,14 +74,11 @@ export default function CameraModal({
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-lg w-full mx-auto">
<DialogHeader>
<DialogTitle className="flex items-center justify-between">
<span>Capturer photo {photoType}</span>
<Button variant="ghost" size="sm" onClick={onClose}>
<X className="h-4 w-4" />
</Button>
<DialogTitle>
Photo {photoType ? photoType.charAt(0).toUpperCase() + photoType.slice(1) : ''}
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="relative">
<video
@@ -89,29 +86,48 @@ export default function CameraModal({
autoPlay
playsInline
muted
className="w-full h-64 object-cover bg-black rounded"
/>
<canvas
ref={canvasRef}
className="hidden"
className="w-full max-w-full h-auto camera-preview rounded-lg border bg-black"
style={{
aspectRatio: '16/9',
objectFit: 'cover',
maxHeight: '400px',
minHeight: '200px'
}}
onLoadedMetadata={() => console.log('CameraModal: Video metadata loaded')}
onCanPlay={() => console.log('CameraModal: Video can play')}
onPlay={() => console.log('CameraModal: Video playing')}
onError={(e) => console.error('CameraModal: Video error:', e)}
/>
<canvas ref={canvasRef} className="hidden" />
{/* Overlay pour aider à cadrer la pièce d'identité */}
<div className="absolute inset-0 pointer-events-none">
<div className="absolute inset-4 border-2 border-white border-dashed rounded-lg opacity-70"></div>
<div className="absolute bottom-2 left-2 text-white text-sm bg-black bg-opacity-70 px-2 py-1 rounded">
Cadrez la pièce d'identité dans le rectangle
</div>
<div className="absolute top-2 right-2 text-white text-xs bg-black bg-opacity-70 px-2 py-1 rounded">
{photoType === 'recto' ? 'RECTO' : 'VERSO'}
</div>
</div>
</div>
<div className="flex justify-center gap-4">
<Button
onClick={onCapture}
disabled={isCapturing}
className="flex items-center gap-2"
>
<Camera className="h-4 w-4" />
{isCapturing ? 'Capture...' : 'Prendre la photo'}
<div className="flex justify-between space-x-3">
<Button variant="outline" onClick={onClose} className="flex-1">
<X className="h-4 w-4 mr-2" />
Fermer
</Button>
<Button variant="outline" onClick={onClose}>
Annuler
<Button
onClick={onCapture}
disabled={isCapturing}
className="bg-green-600 hover:bg-green-700 text-white flex-1"
>
<Camera className="h-4 w-4 mr-2" />
{isCapturing ? 'Capture...' : 'Prendre la photo'}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
);
}
}
+2 -2
View File
@@ -2,7 +2,7 @@ import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Shield, Flame, Plus, History } from 'lucide-react';
import NewSaleFormMultiProduct from './NewSaleFormMultiProduct';
import NewSaleForm from './NewSaleForm';
import SalesHistory from './SalesHistory';
import { useAuth } from '@/hooks/useAuth';
import { useStoreContext } from '@/hooks/useStoreContext';
@@ -68,7 +68,7 @@ export default function FireworksApp() {
</TabsList>
<TabsContent value="nouvelle-vente">
<NewSaleFormMultiProduct />
<NewSaleForm />
</TabsContent>
<TabsContent value="historique">
+301 -228
View File
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -9,23 +9,21 @@ import { Alert, AlertDescription } from '@/components/ui/alert';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/hooks/useAuth';
import { useStoreContext } from '@/hooks/useStoreContext';
import { useSimpleCamera } from '@/hooks/useSimpleCamera';
import { apiRequest } from '@/lib/queryClient';
import { validateRequiredFields, validateEAN13, ARTICLE_CATEGORY_MAPPING, IDENTITY_TYPES, PAYMENT_METHODS } from '@/lib/validation';
import { Package, User, Users, Save, Calendar, BadgeCheck, Info, Camera, Upload, Trash2, Plus, X } from 'lucide-react';
import CameraModal from '@/components/CameraModal';
import { Package, User, Users, Save, Calendar, BadgeCheck, Info, Camera, Upload, Trash2 } from 'lucide-react';
import SimpleCameraModal from '@/components/SimpleCameraModal';
import type { PhotoType } from '@/types/sale';
interface Product {
interface FormData {
vendeur: string;
dateVente: string;
typeArticle: string;
categorie: string;
quantite: string;
gencode: string;
}
interface FormData {
vendeur: string;
products: Product[];
nom: string;
prenom: string;
dateNaissance: string;
@@ -48,14 +46,26 @@ export default function NewSaleForm() {
const { selectedStoreId } = useStoreContext();
const [isSubmitting, setIsSubmitting] = useState(false);
// Camera state
const [isCameraOpen, setIsCameraOpen] = useState(false);
const [currentPhotoType, setCurrentPhotoType] = useState<PhotoType | null>(null);
// Camera functionality
const {
isOpen: isCameraOpen,
currentPhotoType,
isCapturing,
videoRef,
canvasRef,
startCamera,
capturePhoto,
stopCamera
} = useSimpleCamera();
const form = useForm<FormData>({
defaultValues: {
vendeur: '',
products: [{ typeArticle: '', categorie: '', quantite: '1', gencode: '' }],
dateVente: new Date().toISOString().split('T')[0],
typeArticle: '',
categorie: '',
quantite: '',
gencode: '',
nom: '',
prenom: '',
dateNaissance: '',
@@ -71,10 +81,8 @@ export default function NewSaleForm() {
}
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "products"
});
const typeArticle = form.watch('typeArticle');
const availableCategories = typeArticle ? ARTICLE_CATEGORY_MAPPING[typeArticle as keyof typeof ARTICLE_CATEGORY_MAPPING] || [] : [];
const createSaleMutation = useMutation({
mutationFn: async (saleData: any) => {
@@ -98,7 +106,11 @@ export default function NewSaleForm() {
});
form.reset({
vendeur: '',
products: [{ typeArticle: '', categorie: '', quantite: '1', gencode: '' }],
dateVente: new Date().toISOString().split('T')[0],
typeArticle: '',
categorie: '',
quantite: '',
gencode: '',
nom: '',
prenom: '',
dateNaissance: '',
@@ -136,26 +148,21 @@ export default function NewSaleForm() {
return;
}
// Validation EAN13 pour chaque produit
for (const product of data.products) {
if (!validateEAN13(product.gencode)) {
toast({
title: "Code EAN13 invalide",
description: `Le gencode "${product.gencode}" doit être un code EAN13 valide à 13 chiffres`,
variant: "destructive",
});
return;
}
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,
products: data.products.map(product => ({
typeArticle: product.typeArticle,
categorie: product.categorie as 'F2' | 'F3',
quantite: parseInt(product.quantite),
gencode: product.gencode,
})),
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,
@@ -179,28 +186,84 @@ export default function NewSaleForm() {
};
// Photo capture functions
const handlePhotoCapture = (photoType: PhotoType) => {
setCurrentPhotoType(photoType);
setIsCameraOpen(true);
const handlePhotoCapture = async (photoType: PhotoType) => {
console.log('=== PHOTO CAPTURE REQUESTED ===');
console.log('Photo type:', photoType);
// Vérifications préliminaires
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
toast({
title: "Navigateur non compatible",
description: "Votre navigateur ne supporte pas la capture photo. Utilisez Chrome, Firefox ou Safari récent.",
variant: "destructive",
});
return;
}
// Vérifier si nous sommes en HTTPS (requis par certains navigateurs)
if (location.protocol !== 'https:' && location.hostname !== 'localhost') {
toast({
title: "Connexion sécurisée requise",
description: "L'accès à la caméra nécessite une connexion HTTPS.",
variant: "destructive",
});
return;
}
try {
console.log('Attempting to start camera...');
// Afficher toast de démarrage
toast({
title: "Démarrage de la caméra",
description: "Préparation de la caméra en cours...",
});
// Démarrer la caméra simple
await startCamera(photoType);
console.log('Simple camera started successfully');
} catch (error) {
console.error('Camera start failed:', error);
toast({
title: "Erreur d'accès à la caméra",
description: error instanceof Error ? error.message : "Impossible d'accéder à la caméra",
variant: "destructive",
});
}
};
const handlePhotoTaken = (photoData: string) => {
if (currentPhotoType === 'recto') {
form.setValue('photoRecto', photoData);
} else if (currentPhotoType === 'verso') {
form.setValue('photoVerso', photoData);
} else if (currentPhotoType === 'ticket') {
form.setValue('photoTicket', photoData);
const handleTakePhoto = async () => {
if (!currentPhotoType) return;
try {
console.log('Attempting to capture photo...');
const photoData = await capturePhoto();
console.log('Photo captured successfully, data length:', photoData.length);
if (currentPhotoType === 'recto') {
form.setValue('photoRecto', photoData);
} else if (currentPhotoType === 'verso') {
form.setValue('photoVerso', photoData);
} else if (currentPhotoType === 'ticket') {
form.setValue('photoTicket', photoData);
}
toast({
title: "Photo capturée",
description: `Photo ${currentPhotoType} enregistrée avec succès`,
variant: "success",
});
stopCamera();
} catch (error) {
console.error('Photo capture error:', error);
toast({
title: "Erreur de capture",
description: error instanceof Error ? error.message : "Erreur lors de la capture",
variant: "destructive",
});
}
toast({
title: "Photo capturée",
description: `Photo ${currentPhotoType} enregistrée avec succès`,
variant: "success",
});
setIsCameraOpen(false);
setCurrentPhotoType(null);
};
const handleRemovePhoto = (photoType: PhotoType) => {
@@ -253,222 +316,236 @@ export default function NewSaleForm() {
toast({
title: "Photo ajoutée",
description: `Photo ${photoType} ajoutée avec succès`,
variant: "success",
});
};
reader.readAsDataURL(file);
};
// Camera test function
const handleCameraTest = async () => {
toast({
title: "Test en cours...",
description: "Vérification de l'accès aux caméras",
});
const results = await runCameraTest();
let message = `Test de caméra terminé:\n`;
message += `✓ Navigateur compatible: ${results.hasMediaDevices ? 'Oui' : 'Non'}\n`;
message += `✓ getUserMedia disponible: ${results.hasGetUserMedia ? 'Oui' : 'Non'}\n`;
message += `✓ Caméras détectées: ${results.videoDevicesCount}\n`;
message += `✓ Permissions: ${results.permissions}\n`;
if (results.error) {
message += `❌ Erreur: ${results.error}`;
} else {
message += `✅ Caméra fonctionnelle`;
}
toast({
title: results.error ? "Test échoué" : "Test réussi",
description: message,
variant: results.error ? "destructive" : "default",
});
};
return (
<div className="space-y-6">
<div className="modern-card">
<div className="elegant-card animate-slide-in">
<div className="p-6">
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
{/* Section Vendeur */}
<div className="modern-section" style={{ backgroundColor: '#f0f9ff' }}>
<div className="flex items-center gap-2 mb-4">
<User className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold text-gray-900">Informations Vendeur</h3>
<div className="section-vendor">
<div className="section-header">
<User className="h-5 w-5" />
<span>Informations Vendeur</span>
</div>
<div className="grid grid-cols-1 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" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="vendeur"
render={({ field }) => (
<FormItem>
<FormLabel>Nom du vendeur *</FormLabel>
<FormControl>
<Input {...field} className="modern-input" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Section Produits */}
<div className="modern-section" style={{ backgroundColor: '#f0fdf4' }}>
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<Package className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold text-gray-900">Produits</h3>
</div>
<Button
type="button"
onClick={() => append({ typeArticle: '', categorie: '', quantite: '1', gencode: '' })}
variant="outline"
size="sm"
>
<Plus className="h-4 w-4 mr-2" />
Ajouter un produit
</Button>
{/* Section Produit */}
<div className="section-product">
<div className="section-header">
<Package className="h-5 w-5" />
<span>Informations Produit</span>
</div>
<div className="grid grid-cols-1 sm: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', '');
}}>
<FormControl>
<SelectTrigger className="modern-input">
<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 className="modern-input">
<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é" className="modern-input" {...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" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="space-y-4">
{fields.map((field, index) => (
<div key={field.id} className="grid grid-cols-1 md:grid-cols-5 gap-4 p-4 border rounded-lg bg-white">
<FormField
control={form.control}
name={`products.${index}.typeArticle`}
render={({ field }) => (
<FormItem>
<FormLabel>Type d'article *</FormLabel>
<FormControl>
<Input {...field} className="modern-input" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`products.${index}.categorie`}
render={({ field }) => (
<FormItem>
<FormLabel>Catégorie *</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger className="modern-input">
<SelectValue placeholder="Choisir" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="F2">F2</SelectItem>
<SelectItem value="F3">F3</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`products.${index}.quantite`}
render={({ field }) => (
<FormItem>
<FormLabel>Quantité *</FormLabel>
<FormControl>
<Input {...field} type="number" min="1" className="modern-input" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`products.${index}.gencode`}
render={({ field }) => (
<FormItem>
<FormLabel>Gencode EAN13 *</FormLabel>
<FormControl>
<Input {...field} className="modern-input" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex items-end">
{fields.length > 1 && (
<Button
type="button"
onClick={() => remove(index)}
variant="outline"
size="sm"
className="text-red-600 hover:text-red-700"
>
<X className="h-4 w-4" />
</Button>
)}
</div>
</div>
))}
</div>
<Alert className="mt-4 border-blue-200 bg-blue-50">
<Info className="h-4 w-4 text-blue-600" />
<AlertDescription className="text-blue-800">
<strong>Information réglementaire :</strong> F1 = vente interdite aux mineurs de moins de 12 ans • F2/F3 = artifices puissants réservés aux majeurs, vente encadrée
</AlertDescription>
</Alert>
</div>
{/* Section Client */}
<div className="modern-section" style={{ backgroundColor: '#fefce8' }}>
<div className="flex items-center gap-2 mb-4">
<Users className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold text-gray-900">Informations Client</h3>
<div className="section-client">
<div className="section-header">
<Users className="h-5 w-5" />
<span>Informations Client</span>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormField
control={form.control}
name="nom"
render={({ field }) => (
<FormItem>
<FormLabel>Nom *</FormLabel>
<FormLabel>Nom de famille <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input {...field} className="modern-input" />
<Input placeholder="Nom de famille" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="prenom"
render={({ field }) => (
<FormItem>
<FormLabel>Prénom *</FormLabel>
<FormLabel>Prénom <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input {...field} className="modern-input" />
<Input placeholder="Prénom" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dateNaissance"
render={({ field }) => (
<FormItem>
<FormLabel>Date de naissance *</FormLabel>
<FormLabel>Date de naissance <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input {...field} type="date" className="modern-input" />
<Input type="date" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="lieuNaissance"
render={({ field }) => (
<FormItem>
<FormLabel>Lieu de naissance *</FormLabel>
<FormLabel>Lieu de naissance <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input {...field} className="modern-input" />
<Input placeholder="Ville de naissance" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="modePaiement"
render={({ field }) => (
<FormItem>
<FormLabel>Mode de paiement *</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormLabel>Mode de paiement <span className="text-destructive">*</span></FormLabel>
<Select value={field.value} onValueChange={field.onChange}>
<FormControl>
<SelectTrigger className="modern-input">
<SelectValue />
<SelectValue placeholder="Sélectionner le mode de paiement" />
</SelectTrigger>
</FormControl>
<SelectContent>
{PAYMENT_METHODS.map((method) => (
<SelectItem key={method} value={method}>
{method}
<SelectItem key={method.value} value={method.value}>
{method.label}
</SelectItem>
))}
</SelectContent>
@@ -481,29 +558,28 @@ export default function NewSaleForm() {
</div>
{/* Section Identité */}
<div className="modern-section" style={{ backgroundColor: '#fdf2f8' }}>
<div className="flex items-center gap-2 mb-4">
<BadgeCheck className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold text-gray-900">Pièce d'Identité</h3>
<div className="section-identity">
<div className="section-header">
<BadgeCheck className="h-5 w-5" />
<span>Pièce d'Identité</span>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormField
control={form.control}
name="typeIdentite"
render={({ field }) => (
<FormItem>
<FormLabel>Type de pièce d'identité *</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormLabel>Type de pièce d'identité <span className="text-destructive">*</span></FormLabel>
<Select value={field.value} onValueChange={field.onChange}>
<FormControl>
<SelectTrigger className="modern-input">
<SelectValue placeholder="Choisir un type" />
<SelectValue placeholder="Sélectionner le type" />
</SelectTrigger>
</FormControl>
<SelectContent>
{IDENTITY_TYPES.map((type) => (
<SelectItem key={type} value={type}>
{type}
<SelectItem key={type.value} value={type.value}>
{type.label}
</SelectItem>
))}
</SelectContent>
@@ -512,21 +588,19 @@ export default function NewSaleForm() {
</FormItem>
)}
/>
<FormField
control={form.control}
name="numeroIdentite"
render={({ field }) => (
<FormItem>
<FormLabel>Numéro de pièce d'identité *</FormLabel>
<FormLabel>Numéro de pièce d'identité <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input {...field} className="modern-input" />
<Input placeholder="Numéro de la pièce" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="autoriteDelivrance"
@@ -534,35 +608,34 @@ export default function NewSaleForm() {
<FormItem>
<FormLabel>Autorité de délivrance</FormLabel>
<FormControl>
<Input {...field} className="modern-input" />
<Input placeholder="Autorité ayant délivré la pièce (optionnel)" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dateDelivrance"
render={({ field }) => (
<FormItem>
<FormLabel>Date de délivrance *</FormLabel>
<FormLabel>Date de délivrance <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input {...field} type="date" className="modern-input" />
<Input type="date" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Photos pièce d'identité */}
{/* Section Photos */}
<div className="mt-6 space-y-4">
<div>
<h4 className="text-sm font-medium text-gray-700">Photos de la pièce d'identité</h4>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{/* Photo Recto */}
<div className="space-y-2">
<label className="text-sm font-medium text-gray-600">Photo Recto</label>
@@ -571,7 +644,7 @@ export default function NewSaleForm() {
<img
src={form.watch('photoRecto')}
alt="Photo recto"
className="w-full h-32 object-cover border"
className="w-full h-32 object-cover rounded border"
/>
<Button
type="button"
@@ -622,7 +695,7 @@ export default function NewSaleForm() {
<img
src={form.watch('photoVerso')}
alt="Photo verso"
className="w-full h-32 object-cover border"
className="w-full h-32 object-cover rounded border"
/>
<Button
type="button"
@@ -680,7 +753,7 @@ export default function NewSaleForm() {
<img
src={form.watch('photoTicket')}
alt="Photo ticket"
className="w-full h-32 object-cover border"
className="w-full h-32 object-cover rounded border"
/>
<Button
type="button"
@@ -748,14 +821,14 @@ export default function NewSaleForm() {
</div>
{/* Camera Modal */}
<CameraModal
<SimpleCameraModal
isOpen={isCameraOpen}
photoType={currentPhotoType}
onClose={() => {
setIsCameraOpen(false);
setCurrentPhotoType(null);
}}
onPhotoTaken={handlePhotoTaken}
videoRef={videoRef}
canvasRef={canvasRef}
isCapturing={isCapturing}
onClose={stopCamera}
onCapture={handleTakePhoto}
/>
</div>
);
+700
View File
@@ -0,0 +1,700 @@
import { useState } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
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 { useAuth } from '@/hooks/useAuth';
import { useStoreContext } from '@/hooks/useStoreContext';
import { useSimpleCamera } from '@/hooks/useSimpleCamera';
import { apiRequest } from '@/lib/queryClient';
import { validateRequiredFields, validateEAN13, ARTICLE_CATEGORY_MAPPING, IDENTITY_TYPES, PAYMENT_METHODS } from '@/lib/validation';
import { Package, User, Users, Save, Calendar, BadgeCheck, Info, Camera, Upload, Trash2, Plus, Minus } from 'lucide-react';
import SimpleCameraModal from '@/components/SimpleCameraModal';
import type { PhotoType, FormData } from '@/types/sale';
export default function NewSaleFormMulti() {
const { toast } = useToast();
const queryClient = useQueryClient();
const { user } = useAuth();
const { selectedStoreId } = useStoreContext();
const [isSubmitting, setIsSubmitting] = useState(false);
// Camera functionality
const {
isOpen: isCameraOpen,
currentPhotoType,
isCapturing,
videoRef,
canvasRef,
startCamera,
capturePhoto,
stopCamera
} = useSimpleCamera();
const form = useForm<FormData>({
defaultValues: {
vendeur: '',
products: [
{
typeArticle: '',
categorie: '',
quantite: '',
gencode: '',
}
],
nom: '',
prenom: '',
dateNaissance: '',
lieuNaissance: '',
modePaiement: 'Espèce',
typeIdentite: '',
numeroIdentite: '',
autoriteDelivrance: '',
dateDelivrance: '',
photoRecto: '',
photoVerso: '',
photoTicket: '',
}
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "products"
});
const createSaleMutation = useMutation({
mutationFn: async (saleData: any) => {
const dataToSend = {
...saleData,
...(user?.role === 'admin' && selectedStoreId && { storeId: selectedStoreId })
};
const response = await apiRequest('/api/sales', {
method: 'POST',
body: JSON.stringify(dataToSend),
});
return response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/sales'], exact: false });
toast({
title: "Vente enregistrée",
description: "La vente a été enregistrée avec succès",
variant: "success",
});
form.reset();
},
onError: (error: any) => {
const errorMessage = error.message || 'Erreur lors de la création de la vente';
toast({
title: "Erreur",
description: errorMessage,
variant: "destructive",
});
},
});
const onSubmit = async (data: FormData) => {
console.log('Form data:', data);
setIsSubmitting(true);
try {
// Validation des champs requis
const missingFields = validateRequiredFields(data);
if (missingFields.length > 0) {
toast({
title: "Champs obligatoires manquants",
description: `Veuillez remplir : ${missingFields.join(', ')}`,
variant: "destructive",
});
setIsSubmitting(false);
return;
}
// Validation EAN-13 pour tous les produits
const invalidBarcodes = data.products.filter(product => !validateEAN13(product.gencode));
if (invalidBarcodes.length > 0) {
toast({
title: "Code-barres invalide",
description: "Certains codes EAN-13 ne sont pas valides",
variant: "destructive",
});
setIsSubmitting(false);
return;
}
await createSaleMutation.mutateAsync(data);
} catch (error) {
console.error('Submit error:', error);
} finally {
setIsSubmitting(false);
}
};
const handlePhotoCapture = async (photoType: PhotoType) => {
await startCamera(photoType);
};
const handleRemovePhoto = (photoType: PhotoType) => {
const field = photoType === 'recto' ? 'photoRecto' :
photoType === 'verso' ? 'photoVerso' : 'photoTicket';
form.setValue(field, '');
};
const handleFileUpload = (photoType: PhotoType, event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
const result = e.target?.result as string;
const field = photoType === 'recto' ? 'photoRecto' :
photoType === 'verso' ? 'photoVerso' : 'photoTicket';
form.setValue(field, result);
};
reader.readAsDataURL(file);
}
};
const addProduct = () => {
append({
typeArticle: '',
categorie: '',
quantite: '',
gencode: '',
});
};
const removeProduct = (index: number) => {
if (fields.length > 1) {
remove(index);
}
};
const getAvailableCategories = (typeArticle: string) => {
return typeArticle ? ARTICLE_CATEGORY_MAPPING[typeArticle as keyof typeof ARTICLE_CATEGORY_MAPPING] || [] : [];
};
return (
<div className="space-y-6">
<SimpleCameraModal
isOpen={isCameraOpen}
photoType={currentPhotoType}
videoRef={videoRef}
canvasRef={canvasRef}
isCapturing={isCapturing}
onClose={stopCamera}
onCapture={capturePhoto}
/>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
{/* Section Vendeur */}
<div className="modern-section bg-blue-50 p-6 border border-blue-200">
<div className="flex items-center gap-2 mb-4">
<User className="h-5 w-5 text-blue-600" />
<h3 className="text-lg font-semibold text-blue-800">Informations vendeur</h3>
</div>
<FormField
control={form.control}
name="vendeur"
render={({ field }) => (
<FormItem>
<FormLabel>Nom du vendeur *</FormLabel>
<FormControl>
<Input {...field} className="modern-input" placeholder="Nom du vendeur" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Section Produits */}
<div className="modern-section bg-green-50 p-6 border border-green-200">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<Package className="h-5 w-5 text-green-600" />
<h3 className="text-lg font-semibold text-green-800">Produits</h3>
</div>
<Button
type="button"
onClick={addProduct}
variant="outline"
size="sm"
className="text-green-600 border-green-300 hover:bg-green-100"
>
<Plus className="h-4 w-4 mr-1" />
Ajouter un produit
</Button>
</div>
<div className="space-y-4">
{fields.map((field, index) => (
<div key={field.id} className="p-4 border border-green-200 rounded-lg bg-white space-y-3">
<div className="flex items-center justify-between">
<h4 className="font-medium text-green-700">Produit {index + 1}</h4>
{fields.length > 1 && (
<Button
type="button"
onClick={() => removeProduct(index)}
variant="outline"
size="sm"
className="text-red-600 border-red-300 hover:bg-red-100"
>
<Minus className="h-4 w-4" />
</Button>
)}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name={`products.${index}.typeArticle`}
render={({ field }) => (
<FormItem>
<FormLabel>Type d'article *</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger className="modern-input">
<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={`products.${index}.categorie`}
render={({ field }) => (
<FormItem>
<FormLabel>Catégorie *</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger className="modern-input">
<SelectValue placeholder="Sélectionner une catégorie" />
</SelectTrigger>
</FormControl>
<SelectContent>
{getAvailableCategories(form.watch(`products.${index}.typeArticle`)).map((cat) => (
<SelectItem key={cat} value={cat}>
{cat}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`products.${index}.quantite`}
render={({ field }) => (
<FormItem>
<FormLabel>Quantité *</FormLabel>
<FormControl>
<Input {...field} type="number" min="1" className="modern-input" placeholder="1" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`products.${index}.gencode`}
render={({ field }) => (
<FormItem>
<FormLabel>Code EAN-13 *</FormLabel>
<FormControl>
<Input {...field} className="modern-input" placeholder="Code-barres EAN-13" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
))}
</div>
</div>
{/* Section Client */}
<div className="modern-section bg-purple-50 p-6 border border-purple-200">
<div className="flex items-center gap-2 mb-4">
<Users className="h-5 w-5 text-purple-600" />
<h3 className="text-lg font-semibold text-purple-800">Informations client</h3>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="nom"
render={({ field }) => (
<FormItem>
<FormLabel>Nom *</FormLabel>
<FormControl>
<Input {...field} className="modern-input" placeholder="Nom de famille" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="prenom"
render={({ field }) => (
<FormItem>
<FormLabel>Prénom *</FormLabel>
<FormControl>
<Input {...field} className="modern-input" placeholder="Prénom" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dateNaissance"
render={({ field }) => (
<FormItem>
<FormLabel>Date de naissance *</FormLabel>
<FormControl>
<Input {...field} type="date" className="modern-input" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="lieuNaissance"
render={({ field }) => (
<FormItem>
<FormLabel>Lieu de naissance *</FormLabel>
<FormControl>
<Input {...field} className="modern-input" placeholder="Lieu de naissance" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="modePaiement"
render={({ field }) => (
<FormItem>
<FormLabel>Mode de paiement *</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger className="modern-input">
<SelectValue />
</SelectTrigger>
</FormControl>
<SelectContent>
{PAYMENT_METHODS.map((method) => (
<SelectItem key={method.value} value={method.value}>
{method.label}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
{/* Section Identité */}
<div className="modern-section bg-orange-50 p-6 border border-orange-200">
<div className="flex items-center gap-2 mb-4">
<BadgeCheck className="h-5 w-5 text-orange-600" />
<h3 className="text-lg font-semibold text-orange-800">Pièce d'identité</h3>
</div>
<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é *</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger className="modern-input">
<SelectValue placeholder="Sélectionner le 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é *</FormLabel>
<FormControl>
<Input {...field} className="modern-input" placeholder="Numéro de la pièce" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="autoriteDelivrance"
render={({ field }) => (
<FormItem>
<FormLabel>Autorité de délivrance</FormLabel>
<FormControl>
<Input {...field} className="modern-input" placeholder="Optionnel" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dateDelivrance"
render={({ field }) => (
<FormItem>
<FormLabel>Date de délivrance *</FormLabel>
<FormControl>
<Input {...field} type="date" className="modern-input" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Photos */}
<div className="mt-6 space-y-4">
<h4 className="font-medium text-orange-700">Photos de la pièce d'identité</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Photo Recto */}
<div className="space-y-2">
<label className="text-sm font-medium">Photo recto</label>
<div className="flex gap-2">
<Button
type="button"
onClick={() => handlePhotoCapture('recto')}
variant="outline"
size="sm"
className="flex-1"
>
<Camera className="h-4 w-4 mr-1" />
Caméra
</Button>
<label className="flex-1">
<Button
type="button"
variant="outline"
size="sm"
className="w-full"
asChild
>
<span>
<Upload className="h-4 w-4 mr-1" />
Fichier
</span>
</Button>
<input
type="file"
accept="image/*"
className="hidden"
onChange={(e) => handleFileUpload('recto', e)}
/>
</label>
{form.watch('photoRecto') && (
<Button
type="button"
onClick={() => handleRemovePhoto('recto')}
variant="outline"
size="sm"
className="text-red-600"
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
{form.watch('photoRecto') && (
<div className="text-xs text-green-600">✓ Photo recto capturée</div>
)}
</div>
{/* Photo Verso */}
<div className="space-y-2">
<label className="text-sm font-medium">Photo verso</label>
<div className="flex gap-2">
<Button
type="button"
onClick={() => handlePhotoCapture('verso')}
variant="outline"
size="sm"
className="flex-1"
>
<Camera className="h-4 w-4 mr-1" />
Caméra
</Button>
<label className="flex-1">
<Button
type="button"
variant="outline"
size="sm"
className="w-full"
asChild
>
<span>
<Upload className="h-4 w-4 mr-1" />
Fichier
</span>
</Button>
<input
type="file"
accept="image/*"
className="hidden"
onChange={(e) => handleFileUpload('verso', e)}
/>
</label>
{form.watch('photoVerso') && (
<Button
type="button"
onClick={() => handleRemovePhoto('verso')}
variant="outline"
size="sm"
className="text-red-600"
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
{form.watch('photoVerso') && (
<div className="text-xs text-green-600">✓ Photo verso capturée</div>
)}
</div>
</div>
{/* Photo Ticket */}
<div className="space-y-2">
<label className="text-sm font-medium">Photo du ticket (optionnel)</label>
<div className="flex gap-2 max-w-md">
<Button
type="button"
onClick={() => handlePhotoCapture('ticket')}
variant="outline"
size="sm"
className="flex-1"
>
<Camera className="h-4 w-4 mr-1" />
Caméra
</Button>
<label className="flex-1">
<Button
type="button"
variant="outline"
size="sm"
className="w-full"
asChild
>
<span>
<Upload className="h-4 w-4 mr-1" />
Fichier
</span>
</Button>
<input
type="file"
accept="image/*"
className="hidden"
onChange={(e) => handleFileUpload('ticket', e)}
/>
</label>
{form.watch('photoTicket') && (
<Button
type="button"
onClick={() => handleRemovePhoto('ticket')}
variant="outline"
size="sm"
className="text-red-600"
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
{form.watch('photoTicket') && (
<div className="text-xs text-green-600">✓ Photo ticket capturée</div>
)}
</div>
</div>
</div>
{/* Boutons d'action */}
<div className="flex gap-4 justify-end">
<Button
type="button"
variant="outline"
onClick={() => form.reset()}
className="border"
>
Réinitialiser
</Button>
<Button
type="submit"
disabled={isSubmitting}
className="bg-green-600 hover:bg-green-700 text-white px-8"
>
{isSubmitting ? (
<span className="flex items-center">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Enregistrement...
</span>
) : (
<span className="flex items-center">
<Save className="h-4 w-4 mr-2" />
Enregistrer la vente
</span>
)}
</Button>
</div>
</form>
</Form>
</div>
);
}
@@ -1,706 +0,0 @@
import { useState } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useToast } from "@/hooks/use-toast";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { useStoreContext } from "@/hooks/useStoreContext";
import { Package, User, Users, IdCard, Camera, Plus, Minus, Info } from "lucide-react";
import { validateEAN13, ARTICLE_CATEGORY_MAPPING, PAYMENT_METHODS, IDENTITY_TYPES } from "@/lib/validation";
import SimpleCameraModal from "@/components/SimpleCameraModal";
import { useSimpleCamera } from "@/hooks/useSimpleCamera";
// Types pour les photos
type PhotoType = 'recto' | 'verso' | 'ticket';
// Schema de validation pour un produit
const productSchema = z.object({
typeArticle: z.string().min(1, "Type d'article requis"),
categorie: z.string().min(1, "Catégorie requise"),
quantite: z.string().min(1, "Quantité requise").refine((val) => !isNaN(Number(val)) && Number(val) > 0, "Quantité invalide"),
gencode: z.string().length(13, "Code EAN-13 requis (13 chiffres)").refine(validateEAN13, "Code EAN-13 invalide"),
});
// Schema principal du formulaire
const formSchema = z.object({
vendeur: z.string().min(1, "Vendeur requis"),
products: z.array(productSchema).min(1, "Au moins un produit requis"),
nom: z.string().min(1, "Nom requis"),
prenom: z.string().min(1, "Prénom requis"),
dateNaissance: z.string().min(1, "Date de naissance requise"),
lieuNaissance: z.string().min(1, "Lieu de naissance requis"),
modePaiement: z.string().min(1, "Mode de paiement requis"),
typeIdentite: z.string().min(1, "Type d'identité requis"),
numeroIdentite: z.string().min(1, "Numéro d'identité requis"),
autoriteDelivrance: z.string().optional(),
dateDelivrance: z.string().min(1, "Date de délivrance requise"),
photoRecto: z.string().optional(),
photoVerso: z.string().optional(),
photoTicket: z.string().optional(),
});
type FormData = z.infer<typeof formSchema>;
export default function NewSaleFormMultiProduct() {
const { toast } = useToast();
const queryClient = useQueryClient();
const { selectedStoreId } = useStoreContext();
// Hook camera qui fonctionne
const {
isOpen: isCameraOpen,
currentPhotoType,
isCapturing,
videoRef,
canvasRef,
startCamera,
capturePhoto,
stopCamera
} = useSimpleCamera();
const [isSubmitting, setIsSubmitting] = useState(false);
// Formulaire avec valeurs par défaut
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
vendeur: '',
products: [{ typeArticle: '', categorie: '', quantite: '1', gencode: '' }],
nom: '',
prenom: '',
dateNaissance: '',
lieuNaissance: '',
modePaiement: '',
typeIdentite: '',
numeroIdentite: '',
autoriteDelivrance: '',
dateDelivrance: '',
photoRecto: '',
photoVerso: '',
photoTicket: '',
},
});
// Gestion des produits dynamiques
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "products"
});
// Mutation pour créer une vente
const createSaleMutation = useMutation({
mutationFn: async (data: any) => {
return await apiRequest(`/api/sales`, {
method: 'POST',
body: JSON.stringify(data),
});
},
onSuccess: () => {
toast({
title: "Vente enregistrée",
description: "La vente a été enregistrée avec succès",
});
// Réinitialiser le formulaire
form.reset({
vendeur: '',
products: [{ typeArticle: '', categorie: '', quantite: '1', gencode: '' }],
nom: '',
prenom: '',
dateNaissance: '',
lieuNaissance: '',
modePaiement: '',
typeIdentite: '',
numeroIdentite: '',
autoriteDelivrance: '',
dateDelivrance: '',
photoRecto: '',
photoVerso: '',
photoTicket: '',
});
// Invalider le cache des ventes
queryClient.invalidateQueries({ queryKey: ['/api/sales'] });
},
onError: (error: any) => {
toast({
title: "Erreur",
description: error.message || "Erreur lors de l'enregistrement de la vente",
variant: "destructive",
});
},
});
// Ajouter un nouveau produit
const addProduct = () => {
append({ typeArticle: '', categorie: '', quantite: '1', gencode: '' });
};
// Supprimer un produit
const removeProduct = (index: number) => {
if (fields.length > 1) {
remove(index);
}
};
// Soumission du formulaire
const onSubmit = async (data: FormData) => {
if (!selectedStoreId) {
toast({
title: "Erreur",
description: "Aucun magasin sélectionné",
variant: "destructive",
});
return;
}
setIsSubmitting(true);
try {
const saleData = {
storeId: selectedStoreId,
vendeur: data.vendeur,
products: data.products.map(product => ({
typeArticle: product.typeArticle,
categorie: product.categorie,
quantite: parseInt(product.quantite),
gencode: product.gencode,
})),
nom: data.nom,
prenom: data.prenom,
dateNaissance: data.dateNaissance,
lieuNaissance: data.lieuNaissance,
modePaiement: data.modePaiement,
typeIdentite: data.typeIdentite,
numeroIdentite: data.numeroIdentite,
autoriteDelivrance: data.autoriteDelivrance,
dateDelivrance: data.dateDelivrance,
photoRecto: data.photoRecto,
photoVerso: data.photoVerso,
photoTicket: data.photoTicket,
};
await createSaleMutation.mutateAsync(saleData);
} catch (error) {
console.error('Sale creation error:', error);
} finally {
setIsSubmitting(false);
}
};
// Gestion des photos avec le hook qui fonctionne
const handlePhotoCapture = async (photoType: PhotoType) => {
try {
await startCamera(photoType);
} catch (error) {
console.error('Erreur ouverture caméra:', error);
toast({
title: "Erreur caméra",
description: "Impossible d'accéder à la caméra. Vérifiez les autorisations.",
variant: "destructive",
});
}
};
const handleCapture = async () => {
try {
const photoData = await capturePhoto();
if (currentPhotoType) {
const fieldName = `photo${currentPhotoType.charAt(0).toUpperCase() + currentPhotoType.slice(1)}` as keyof FormData;
form.setValue(fieldName, photoData);
toast({
title: "Photo capturée",
description: `Photo ${currentPhotoType} enregistrée avec succès`,
});
}
stopCamera();
} catch (error) {
console.error('Erreur capture:', error);
toast({
title: "Erreur capture",
description: "Impossible de capturer la photo",
variant: "destructive",
});
}
};
const handleRemovePhoto = (photoType: PhotoType) => {
if (photoType === 'recto') {
form.setValue('photoRecto', '');
} else if (photoType === 'verso') {
form.setValue('photoVerso', '');
} else if (photoType === 'ticket') {
form.setValue('photoTicket', '');
}
toast({
title: "Photo supprimée",
description: `Photo ${photoType} supprimée`,
});
};
return (
<div className="elegant-card animate-slide-in">
<div className="p-6">
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
{/* Section Vendeur */}
<div className="section-vendor">
<div className="section-header">
<User className="h-5 w-5" />
<span>Informations Vendeur</span>
</div>
<div className="grid grid-cols-1 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" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
{/* Section Produits */}
<div className="section-product">
<div className="section-header">
<Package className="h-5 w-5" />
<span>Produits ({fields.length})</span>
<Button
type="button"
onClick={addProduct}
variant="outline"
size="sm"
className="ml-auto"
>
<Plus className="h-4 w-4 mr-2" />
Ajouter
</Button>
</div>
<div className="space-y-4">
{fields.map((field, index) => (
<div key={field.id} className="modern-card bg-green-50 dark:bg-green-900/20">
<div className="flex items-center justify-between mb-4">
<h3 className="font-medium text-gray-900 dark:text-white">
Produit {index + 1}
</h3>
{fields.length > 1 && (
<Button
type="button"
onClick={() => removeProduct(index)}
variant="outline"
size="sm"
className="text-red-600 hover:text-red-700"
>
<Minus className="h-4 w-4" />
</Button>
)}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name={`products.${index}.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(`products.${index}.categorie`, '');
}}
>
<FormControl>
<SelectTrigger className="modern-input">
<SelectValue placeholder="Sélectionner le type" />
</SelectTrigger>
</FormControl>
<SelectContent>
{Object.keys(ARTICLE_CATEGORY_MAPPING).map((type) => (
<SelectItem key={`type-${index}-${type}`} value={type}>
{type}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`products.${index}.categorie`}
render={({ field }) => {
const selectedType = form.watch(`products.${index}.typeArticle`);
const availableCategories = selectedType ?
ARTICLE_CATEGORY_MAPPING[selectedType as keyof typeof ARTICLE_CATEGORY_MAPPING] || [] : [];
return (
<FormItem>
<FormLabel>Catégorie <span className="text-destructive">*</span></FormLabel>
<Select
value={field.value}
onValueChange={field.onChange}
disabled={!selectedType}
>
<FormControl>
<SelectTrigger className="modern-input">
<SelectValue placeholder="Sélectionner la catégorie" />
</SelectTrigger>
</FormControl>
<SelectContent>
{availableCategories.map((cat) => (
<SelectItem key={`cat-${index}-${cat}`} value={cat}>
{cat}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
);
}}
/>
<FormField
control={form.control}
name={`products.${index}.quantite`}
render={({ field }) => (
<FormItem>
<FormLabel>Quantité <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input
type="number"
min="1"
placeholder="Quantité"
className="modern-input"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`products.${index}.gencode`}
render={({ field }) => (
<FormItem>
<FormLabel>Code EAN-13 <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input
placeholder="Code EAN-13 (13 chiffres)"
className="modern-input"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
))}
</div>
<Alert className="mt-4 border-blue-200 bg-blue-50">
<Info className="h-4 w-4 text-blue-600" />
<AlertDescription className="text-blue-800">
<strong>Information réglementaire :</strong> F1 = vente interdite aux mineurs de moins de 12 ans • F2/F3 = artifices puissants réservés aux majeurs, vente encadrée
</AlertDescription>
</Alert>
</div>
{/* Section Client */}
<div className="section-client">
<div className="section-header">
<Users className="h-5 w-5" />
<span>Informations Client</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormField
control={form.control}
name="nom"
render={({ field }) => (
<FormItem>
<FormLabel>Nom <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Nom de famille" className="modern-input" {...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" className="modern-input" {...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" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="lieuNaissance"
render={({ field }) => (
<FormItem>
<FormLabel>Lieu de naissance <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Ville de naissance" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="modePaiement"
render={({ field }) => (
<FormItem>
<FormLabel>Mode de paiement <span className="text-destructive">*</span></FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger className="modern-input">
<SelectValue placeholder="Mode de paiement" />
</SelectTrigger>
</FormControl>
<SelectContent>
{PAYMENT_METHODS.map((method, methodIndex) => (
<SelectItem key={`payment-method-${methodIndex}`} value={method}>
{method}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
{/* Section Identité */}
<div className="section-identity">
<div className="section-header">
<IdCard className="h-5 w-5" />
<span>Pièce d'Identité</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormField
control={form.control}
name="typeIdentite"
render={({ field }) => (
<FormItem>
<FormLabel>Type d'identité <span className="text-destructive">*</span></FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger className="modern-input">
<SelectValue placeholder="Type d'identité" />
</SelectTrigger>
</FormControl>
<SelectContent>
{IDENTITY_TYPES.map((type, typeIndex) => (
<SelectItem key={`identity-type-${typeIndex}`} value={type}>
{type}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="numeroIdentite"
render={({ field }) => (
<FormItem>
<FormLabel>Numéro <span className="text-destructive">*</span></FormLabel>
<FormControl>
<Input placeholder="Numéro de la pièce" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="autoriteDelivrance"
render={({ field }) => (
<FormItem>
<FormLabel>Autorité de délivrance</FormLabel>
<FormControl>
<Input placeholder="Autorité (optionnel)" className="modern-input" {...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" className="modern-input" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Section Photos */}
<div className="mt-6 space-y-4">
<h3 className="text-lg font-medium">Photos des documents</h3>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
{/* Photo Recto */}
<div className="space-y-2">
<label className="text-sm font-medium">Photo Recto</label>
<div className="flex flex-col gap-2">
<Button
type="button"
onClick={() => handlePhotoCapture('recto')}
variant="outline"
size="sm"
className="w-full"
>
<Camera className="h-4 w-4 mr-2" />
{form.watch('photoRecto') ? 'Modifier' : 'Capturer'}
</Button>
{form.watch('photoRecto') && (
<Button
type="button"
onClick={() => handleRemovePhoto('recto')}
variant="outline"
size="sm"
className="w-full text-red-600"
>
Supprimer
</Button>
)}
</div>
</div>
{/* Photo Verso */}
<div className="space-y-2">
<label className="text-sm font-medium">Photo Verso</label>
<div className="flex flex-col gap-2">
<Button
type="button"
onClick={() => handlePhotoCapture('verso')}
variant="outline"
size="sm"
className="w-full"
>
<Camera className="h-4 w-4 mr-2" />
{form.watch('photoVerso') ? 'Modifier' : 'Capturer'}
</Button>
{form.watch('photoVerso') && (
<Button
type="button"
onClick={() => handleRemovePhoto('verso')}
variant="outline"
size="sm"
className="w-full text-red-600"
>
Supprimer
</Button>
)}
</div>
</div>
{/* Photo Ticket */}
<div className="space-y-2">
<label className="text-sm font-medium">Photo Ticket</label>
<div className="flex flex-col gap-2">
<Button
type="button"
onClick={() => handlePhotoCapture('ticket')}
variant="outline"
size="sm"
className="w-full"
>
<Camera className="h-4 w-4 mr-2" />
{form.watch('photoTicket') ? 'Modifier' : 'Capturer'}
</Button>
{form.watch('photoTicket') && (
<Button
type="button"
onClick={() => handleRemovePhoto('ticket')}
variant="outline"
size="sm"
className="w-full text-red-600"
>
Supprimer
</Button>
)}
</div>
</div>
</div>
</div>
</div>
{/* Bouton de soumission */}
<div className="flex justify-end">
<Button
type="submit"
disabled={isSubmitting}
className="bg-green-600 hover:bg-green-700 text-white px-8 py-2 text-lg font-medium"
>
{isSubmitting ? "Enregistrement..." : "Enregistrer la vente"}
</Button>
</div>
</form>
</Form>
</div>
{/* Modal Camera qui fonctionne */}
<SimpleCameraModal
isOpen={isCameraOpen}
photoType={currentPhotoType}
videoRef={videoRef}
canvasRef={canvasRef}
isCapturing={isCapturing}
onClose={stopCamera}
onCapture={handleCapture}
/>
</div>
);
}
+8 -8
View File
@@ -81,15 +81,15 @@ export const ARTICLE_CATEGORY_MAPPING = {
} as const;
export const IDENTITY_TYPES = [
"Carte Nationale d'Identité",
"Passeport",
"Permis de conduire"
{ value: "CNI", label: "Carte Nationale d'Identité" },
{ value: "Passeport", label: "Passeport" },
{ value: "Permis de conduire", label: "Permis de conduire" }
] as const;
export const PAYMENT_METHODS = [
"Carte Bancaire",
"Espèce",
"Chèque",
"Carte Cadeau",
"Autre"
{ value: "Carte Bancaire", label: "Carte Bancaire" },
{ value: "Espèce", label: "Espèce" },
{ value: "Chèque", label: "Chèque" },
{ value: "Carte Cadeau", label: "Carte Cadeau" },
{ value: "Autre", label: "Autre" }
] as const;
+2 -2
View File
@@ -5,7 +5,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useAuth } from "@/hooks/useAuth";
import { StoreProvider, useStoreContext } from "@/hooks/useStoreContext";
import NewSaleFormMultiProduct from "@/components/NewSaleFormMultiProduct";
import NewSaleFormMulti from "@/components/NewSaleFormMulti";
import SalesHistory from "@/components/SalesHistory";
import Administration from "@/components/Administration";
import { Package, History, Settings, LogOut, User, Building2, Shield } from "lucide-react";
@@ -146,7 +146,7 @@ function DashboardContent() {
<TabsContent value="new-sale" className="mt-8">
<div className="slide-in-up">
<NewSaleFormMultiProduct />
<NewSaleFormMulti />
</div>
</TabsContent>