import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { useQuery } from "@tanstack/react-query"; import { useAuthUnified } from "@/hooks/useAuthUnified"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Button } from "@/components/ui/button"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Checkbox } from "@/components/ui/checkbox"; import { insertCustomerOrderFrontendSchema, type CustomerOrderWithRelations, type Group, type Supplier } from "@shared/schema"; import { useStore } from "@/components/Layout"; const customerOrderFormSchema = insertCustomerOrderFrontendSchema.extend({ groupId: z.coerce.number().int().positive().optional(), createdBy: z.string().optional(), }); type CustomerOrderFormData = z.infer; interface CustomerOrderFormProps { order?: CustomerOrderWithRelations; onSubmit: (data: CustomerOrderFormData) => void; onCancel: () => void; isLoading?: boolean; } const STATUS_OPTIONS = [ "En attente de Commande", "Commande en Cours", "Disponible", "Retiré", "Annulé" ]; export function CustomerOrderForm({ order, onSubmit, onCancel, isLoading = false }: CustomerOrderFormProps) { const { user } = useAuthUnified(); const { selectedStoreId } = useStore(); // Fetch groups for store selection const { data: groups = [] } = useQuery({ queryKey: ['/api/groups'], }); // Fetch suppliers for supplier selection const { data: suppliers = [] } = useQuery({ queryKey: ['/api/suppliers'], }); const form = useForm({ resolver: zodResolver(customerOrderFormSchema), defaultValues: { orderTaker: order?.orderTaker || user?.name || "", customerName: order?.customerName || "", contactNumber: order?.customerPhone || "", productName: order?.productDesignation || "", productReference: order?.productReference || "", gencode: order?.gencode || "", quantity: order?.quantity || 1, supplierId: order?.supplierId || undefined, status: "En attente de Commande", // Statut fixe deposit: order?.deposit || 0, isPromotionalPrice: order?.isPromotionalPrice || false, customerNotified: order?.customerNotified || false, groupId: order?.groupId || (user?.role === 'admin' && selectedStoreId ? selectedStoreId : user?.userGroups?.[0]?.groupId) || 1, // Force assignment with fallback }, }); const handleSubmit = (data: CustomerOrderFormData) => { console.log("Form submission data:", data); console.log("Form errors:", form.formState.errors); console.log("Form is valid:", form.formState.isValid); // Validate required fields if (!data.customerName || data.customerName.trim() === '') { console.error("Customer name is required but empty"); return; } // Ensure groupId is set - force assignment for ALL users let groupId = data.groupId; console.log("🔍 Customer Order GroupId Debug:", { userRole: user?.role, selectedStoreId, userGroups: user?.userGroups?.map(ug => ({groupId: ug.groupId, groupName: ug.group?.name})), initialGroupId: groupId, availableGroups: groups.map(g => ({id: g.id, name: g.name})) }); if (!groupId) { if (user?.role === 'admin' && selectedStoreId) { // Admin has selected a specific store - use it groupId = selectedStoreId; console.log("🏪 Using admin selected store:", selectedStoreId); } else if (user?.userGroups?.[0]?.groupId) { // User has assigned groups - use first one groupId = user.userGroups[0].groupId; console.log("👤 Using user group:", groupId); } else if (user?.role === 'admin' && groups.length > 0) { // Admin in "tous magasins" mode - use first group groupId = groups[0].id; console.log("🏢 Admin fallback to first group:", groupId); } else if (groups.length > 0) { // EMERGENCY FALLBACK: Force assignment to first available group groupId = groups[0].id; console.log("⚠️ EMERGENCY: Force assigning to first group:", groupId); } else { // LAST RESORT: Hard-coded fallback groupId = 1; console.log("🚨 LAST RESORT: Using hard-coded groupId 1"); } } console.log("✅ Final groupId selected:", groupId); // Prepare data with proper types for frontend schema const submitData = { customerName: data.customerName.trim(), contactNumber: data.contactNumber || '', productName: data.productName || '', quantity: data.quantity, groupId: typeof groupId === 'number' ? groupId : parseInt(groupId.toString()), isPickup: false, notes: data.notes, deposit: data.deposit || 0, isPromotionalPrice: data.isPromotionalPrice || false, customerEmail: data.customerEmail, gencode: data.gencode || '', supplierId: data.supplierId || 1, }; console.log("🔍 Frontend submit data:", submitData); onSubmit(submitData); }; // Get available groups for the user const availableGroups = user?.role === 'admin' ? groups : user?.userGroups?.map(ug => ug.group) || []; // Auto-select group for users respecting admin store selection const currentGroupId = form.getValues('groupId'); if (!currentGroupId) { if (user?.role === 'admin' && selectedStoreId) { // Admin has selected a specific store - use it form.setValue('groupId', selectedStoreId); console.log("🏪 Auto-selecting admin store:", selectedStoreId); } else if (user?.userGroups?.[0]?.groupId) { // User has assigned groups - use first one form.setValue('groupId', user.userGroups[0].groupId); } else if (user?.role === 'admin' && groups.length > 0) { // Admin with no specific groups - use first available group form.setValue('groupId', groups[0].id); } } return (
{/* Informations de commande */}

Informations de commande

( Qui a pris la commande )} /> ( Nom du client )} /> ( N° de téléphone )} /> ( Fournisseur )} /> {/* Magasin automatiquement sélectionné - pas de champ visible */}

Informations produit

( Désignation du produit