Просмотр исходного кода

improved qoutes creation flow (#42)

Bernt Christian Egeland 8 месяцев назад
Родитель
Сommit
bcd5e2a5f2

+ 30 - 3
src/app/(authenticated)/dashboard-client.tsx

@@ -43,7 +43,8 @@ import { formatCurrency } from "@/lib/format";
 import { dismissMaintenance, undismissMaintenance } from "@/features/vehicles/Actions/dismissMaintenance";
 import { dismissMaintenance, undismissMaintenance } from "@/features/vehicles/Actions/dismissMaintenance";
 import { updateQuoteRequestStatus } from "@/features/inspections/Actions/quoteRequestActions";
 import { updateQuoteRequestStatus } from "@/features/inspections/Actions/quoteRequestActions";
 import { acknowledgeQuoteResponse } from "@/features/quotes/Actions/quoteResponseActions";
 import { acknowledgeQuoteResponse } from "@/features/quotes/Actions/quoteResponseActions";
-import { convertQuoteToServiceRecord } from "@/features/quotes/Actions/quoteActions";
+import { toast } from "sonner";
+import { convertQuoteToServiceRecord, createQuote } from "@/features/quotes/Actions/quoteActions";
 import { useDashboardVisibility, DASHBOARD_CARD_IDS } from "@/hooks/use-dashboard-visibility";
 import { useDashboardVisibility, DASHBOARD_CARD_IDS } from "@/hooks/use-dashboard-visibility";
 
 
 interface ServiceItem {
 interface ServiceItem {
@@ -141,7 +142,7 @@ interface DashboardQuoteRequest {
       model: string;
       model: string;
       year: number;
       year: number;
       licensePlate: string | null;
       licensePlate: string | null;
-      customer: { name: string } | null;
+      customer: { id: string; name: string } | null;
     };
     };
     items: { id: string; name: string; section: string; condition: string; notes: string | null }[];
     items: { id: string; name: string; section: string; condition: string; notes: string | null }[];
   };
   };
@@ -844,8 +845,34 @@ export function DashboardClient({
                           onClick={() => {
                           onClick={() => {
                             startTransition(async () => {
                             startTransition(async () => {
                               await updateQuoteRequestStatus(req.id, "quoted");
                               await updateQuoteRequestStatus(req.id, "quoted");
+                              const issueItems = req.inspection.items.filter(
+                                (i) => i.condition === "fail" || i.condition === "attention"
+                              );
+                              const result = await createQuote({
+                                title: `${req.inspection.vehicle.year} ${req.inspection.vehicle.make} ${req.inspection.vehicle.model} - Inspection Quote`,
+                                vehicleId: req.inspection.vehicle.id,
+                                customerId: req.inspection.vehicle.customer?.id || undefined,
+                                inspectionId: req.inspection.id,
+                                status: "draft",
+                                laborItems: issueItems.map((item) => ({
+                                  description: `${item.name}${item.notes ? ` - ${item.notes}` : ""}`,
+                                  hours: 0,
+                                  rate: 0,
+                                  total: 0,
+                                })),
+                                subtotal: 0,
+                                taxRate: 0,
+                                taxAmount: 0,
+                                discountValue: 0,
+                                discountAmount: 0,
+                                totalAmount: 0,
+                              });
+                              if (result.success && result.data) {
+                                router.push(`/quotes/${result.data.id}`);
+                              } else {
+                                toast.error(result.error || "Failed to create quote");
+                              }
                             });
                             });
-                            router.push(`/quotes/new?fromInspection=${req.inspection.id}`);
                           }}
                           }}
                         >
                         >
                           {t("quoteRequests.createQuote")}
                           {t("quoteRequests.createQuote")}

+ 0 - 86
src/app/(authenticated)/quotes/new/page.tsx

@@ -1,86 +0,0 @@
-import { getSettings } from "@/features/settings/Actions/settingsActions";
-import { SETTING_KEYS } from "@/features/settings/Schema/settingsSchema";
-import { PageHeader } from "@/components/page-header";
-import { QuoteForm } from "@/features/quotes/Components/QuoteForm";
-import { getCustomers } from "@/features/customers/Actions/customerActions";
-import { getVehicles } from "@/features/vehicles/Actions/vehicleActions";
-import { getInspection } from "@/features/inspections/Actions/inspectionActions";
-
-export default async function NewQuotePage({
-  searchParams,
-}: {
-  searchParams: Promise<{ fromInspection?: string }>;
-}) {
-  const params = await searchParams;
-
-  const [settingsResult, customersResult, vehiclesResult] = await Promise.all([
-    getSettings([SETTING_KEYS.CURRENCY_CODE, SETTING_KEYS.DEFAULT_TAX_RATE, SETTING_KEYS.TAX_ENABLED, SETTING_KEYS.DEFAULT_LABOR_RATE, SETTING_KEYS.QUOTE_VALID_DAYS]),
-    getCustomers(),
-    getVehicles(),
-  ]);
-
-  const settings = settingsResult.success && settingsResult.data ? settingsResult.data : {};
-  const currencyCode = settings[SETTING_KEYS.CURRENCY_CODE] || "USD";
-  const taxEnabled = settings[SETTING_KEYS.TAX_ENABLED] !== "false";
-  const defaultTaxRate = taxEnabled ? (Number(settings[SETTING_KEYS.DEFAULT_TAX_RATE]) || 0) : 0;
-  const defaultLaborRate = Number(settings[SETTING_KEYS.DEFAULT_LABOR_RATE]) || 0;
-  const quoteValidDays = Number(settings[SETTING_KEYS.QUOTE_VALID_DAYS]) || 30;
-  const customers = customersResult.success && customersResult.data ? customersResult.data : [];
-  const vehicles = vehiclesResult.success && vehiclesResult.data ? vehiclesResult.data : [];
-
-  // Build prefill data from inspection if provided
-  let prefill: { title?: string; vehicleId?: string; customerId?: string; inspectionId?: string; laborItems?: { description: string; hours: number; rate: number; total: number; excluded?: boolean }[] } | undefined;
-
-  if (params.fromInspection) {
-    const inspResult = await getInspection(params.fromInspection);
-    if (inspResult.success && inspResult.data) {
-      const insp = inspResult.data;
-      const issueItems = insp.items.filter(
-        (i: { condition: string }) => i.condition === "fail" || i.condition === "attention"
-      );
-      prefill = {
-        title: `Inspection Repairs — ${insp.vehicle.year} ${insp.vehicle.make} ${insp.vehicle.model}`,
-        vehicleId: insp.vehicle.id,
-        customerId: insp.vehicle.customer?.id || undefined,
-        inspectionId: insp.id,
-        laborItems: issueItems.map((item: { name: string; section: string; notes: string | null }) => ({
-          description: `${item.section}: ${item.name}${item.notes ? ` — ${item.notes}` : ""}`,
-          hours: 0,
-          rate: defaultLaborRate,
-          total: 0,
-        })),
-      };
-    }
-  }
-
-  return (
-    <>
-      <PageHeader />
-      <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
-        <QuoteForm
-          currencyCode={currencyCode}
-          defaultTaxRate={defaultTaxRate}
-          taxEnabled={taxEnabled}
-          defaultLaborRate={defaultLaborRate}
-          quoteValidDays={quoteValidDays}
-          customers={customers.map((c: { id: string; name: string; email: string | null; company: string | null }) => ({
-            id: c.id,
-            name: c.name,
-            email: c.email,
-            company: c.company,
-          }))}
-          vehicles={vehicles.map((v: { id: string; make: string; model: string; year: number; licensePlate: string | null; customer: { id: string; name: string; company: string | null } | null }) => ({
-            id: v.id,
-            make: v.make,
-            model: v.model,
-            year: v.year,
-            licensePlate: v.licensePlate,
-            customerId: v.customer?.id || null,
-            customerName: v.customer?.name || null,
-          }))}
-          prefill={prefill}
-        />
-      </div>
-    </>
-  );
-}

+ 25 - 1
src/app/(authenticated)/quotes/page.tsx

@@ -1,6 +1,8 @@
 import { getQuotesPaginated } from "@/features/quotes/Actions/quoteActions";
 import { getQuotesPaginated } from "@/features/quotes/Actions/quoteActions";
 import { getSettings } from "@/features/settings/Actions/settingsActions";
 import { getSettings } from "@/features/settings/Actions/settingsActions";
 import { SETTING_KEYS } from "@/features/settings/Schema/settingsSchema";
 import { SETTING_KEYS } from "@/features/settings/Schema/settingsSchema";
+import { getVehicles } from "@/features/vehicles/Actions/vehicleActions";
+import { getCustomersList } from "@/features/customers/Actions/customerActions";
 import { QuotesClient } from "./quotes-client";
 import { QuotesClient } from "./quotes-client";
 import { PageHeader } from "@/components/page-header";
 import { PageHeader } from "@/components/page-header";
 
 
@@ -15,7 +17,7 @@ export default async function QuotesPage({
   }>;
   }>;
 }) {
 }) {
   const params = await searchParams;
   const params = await searchParams;
-  const [result, settingsResult] = await Promise.all([
+  const [result, settingsResult, vehiclesResult, customersResult] = await Promise.all([
     getQuotesPaginated({
     getQuotesPaginated({
       page: params.page ? parseInt(params.page) : 1,
       page: params.page ? parseInt(params.page) : 1,
       pageSize: params.pageSize ? parseInt(params.pageSize) : 20,
       pageSize: params.pageSize ? parseInt(params.pageSize) : 20,
@@ -23,6 +25,8 @@ export default async function QuotesPage({
       status: params.status || "all",
       status: params.status || "all",
     }),
     }),
     getSettings([SETTING_KEYS.CURRENCY_CODE]),
     getSettings([SETTING_KEYS.CURRENCY_CODE]),
+    getVehicles(),
+    getCustomersList(),
   ]);
   ]);
 
 
   if (!result.success || !result.data) {
   if (!result.success || !result.data) {
@@ -40,6 +44,24 @@ export default async function QuotesPage({
 
 
   const settings = settingsResult.success && settingsResult.data ? settingsResult.data : {};
   const settings = settingsResult.success && settingsResult.data ? settingsResult.data : {};
   const currencyCode = settings[SETTING_KEYS.CURRENCY_CODE] || "USD";
   const currencyCode = settings[SETTING_KEYS.CURRENCY_CODE] || "USD";
+  const vehicles = vehiclesResult.success && vehiclesResult.data
+    ? vehiclesResult.data.map((v) => ({
+        id: v.id,
+        make: v.make,
+        model: v.model,
+        year: v.year,
+        licensePlate: v.licensePlate,
+        customerId: v.customer?.id ?? null,
+        customerName: v.customer?.name ?? null,
+      }))
+    : [];
+  const customers = customersResult.success && customersResult.data
+    ? customersResult.data.map((c) => ({
+        id: c.id,
+        name: c.name,
+        company: c.company,
+      }))
+    : [];
 
 
   return (
   return (
     <>
     <>
@@ -50,6 +72,8 @@ export default async function QuotesPage({
           currencyCode={currencyCode}
           currencyCode={currencyCode}
           search={params.search || ""}
           search={params.search || ""}
           statusFilter={params.status || "all"}
           statusFilter={params.status || "all"}
+          vehicles={vehicles}
+          customers={customers}
         />
         />
       </div>
       </div>
     </>
     </>

+ 222 - 2
src/app/(authenticated)/quotes/quotes-client.tsx

@@ -7,12 +7,23 @@ import { useFormatDate } from "@/lib/use-format-date";
 import { Badge } from "@/components/ui/badge";
 import { Badge } from "@/components/ui/badge";
 import { Button } from "@/components/ui/button";
 import { Button } from "@/components/ui/button";
 import { Input } from "@/components/ui/input";
 import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
 import {
 import {
   Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
   Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
 } from "@/components/ui/table";
 } from "@/components/ui/table";
+import {
+  Dialog, DialogContent, DialogHeader, DialogTitle,
+} from "@/components/ui/dialog";
+import {
+  Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList,
+} from "@/components/ui/command";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
 import { DataTablePagination } from "@/components/data-table-pagination";
 import { DataTablePagination } from "@/components/data-table-pagination";
-import { Loader2, Plus, Search } from "lucide-react";
+import { Check, ChevronsUpDown, Loader2, Plus, Search } from "lucide-react";
+import { cn } from "@/lib/utils";
 import { formatCurrency } from "@/lib/format";
 import { formatCurrency } from "@/lib/format";
+import { toast } from "sonner";
+import { createQuote } from "@/features/quotes/Actions/quoteActions";
 
 
 interface QuoteRecord {
 interface QuoteRecord {
   id: string;
   id: string;
@@ -35,6 +46,22 @@ interface PaginatedData {
   statusCounts: Record<string, number>;
   statusCounts: Record<string, number>;
 }
 }
 
 
+interface VehicleOption {
+  id: string;
+  make: string;
+  model: string;
+  year: number;
+  licensePlate: string | null;
+  customerId: string | null;
+  customerName: string | null;
+}
+
+interface CustomerOption {
+  id: string;
+  name: string;
+  company: string | null;
+}
+
 const statusTabs = [
 const statusTabs = [
   { key: "all", titleKey: "list.statusAll" },
   { key: "all", titleKey: "list.statusAll" },
   { key: "draft", titleKey: "list.statusDraft" },
   { key: "draft", titleKey: "list.statusDraft" },
@@ -58,11 +85,15 @@ export function QuotesClient({
   currencyCode = "USD",
   currencyCode = "USD",
   search,
   search,
   statusFilter,
   statusFilter,
+  vehicles = [],
+  customers = [],
 }: {
 }: {
   data: PaginatedData;
   data: PaginatedData;
   currencyCode?: string;
   currencyCode?: string;
   search: string;
   search: string;
   statusFilter: string;
   statusFilter: string;
+  vehicles?: VehicleOption[];
+  customers?: CustomerOption[];
 }) {
 }) {
   const router = useRouter();
   const router = useRouter();
   const { formatDate } = useFormatDate();
   const { formatDate } = useFormatDate();
@@ -72,6 +103,15 @@ export function QuotesClient({
   const [searchInput, setSearchInput] = useState(search);
   const [searchInput, setSearchInput] = useState(search);
   const t = useTranslations("quotes");
   const t = useTranslations("quotes");
 
 
+  // New quote dialog state
+  const [showNewDialog, setShowNewDialog] = useState(false);
+  const [newTitle, setNewTitle] = useState("");
+  const [newVehicleId, setNewVehicleId] = useState("");
+  const [newCustomerId, setNewCustomerId] = useState("");
+  const [vehicleOpen, setVehicleOpen] = useState(false);
+  const [customerOpen, setCustomerOpen] = useState(false);
+  const [creating, setCreating] = useState(false);
+
   const navigate = useCallback(
   const navigate = useCallback(
     (params: Record<string, string | number | undefined>) => {
     (params: Record<string, string | number | undefined>) => {
       const newParams = new URLSearchParams(searchParams.toString());
       const newParams = new URLSearchParams(searchParams.toString());
@@ -98,6 +138,70 @@ export function QuotesClient({
     [navigate, searchInput]
     [navigate, searchInput]
   );
   );
 
 
+  const openNewDialog = () => {
+    setNewTitle("");
+    setNewVehicleId("");
+    setNewCustomerId("");
+    setShowNewDialog(true);
+  };
+
+  const handleVehicleSelect = (vehicleId: string) => {
+    setNewVehicleId(vehicleId);
+    setVehicleOpen(false);
+    const vehicle = vehicles.find((v) => v.id === vehicleId);
+    if (vehicle?.customerId) {
+      setNewCustomerId(vehicle.customerId);
+    }
+  };
+
+  const handleCreateQuote = async (e: React.FormEvent) => {
+    e.preventDefault();
+    if (!newTitle.trim()) return;
+    setCreating(true);
+
+    const result = await createQuote({
+      title: newTitle.trim(),
+      vehicleId: newVehicleId || undefined,
+      customerId: newCustomerId || undefined,
+      status: "draft",
+      subtotal: 0,
+      taxRate: 0,
+      taxAmount: 0,
+      discountValue: 0,
+      discountAmount: 0,
+      totalAmount: 0,
+    });
+
+    if (result.success && result.data) {
+      toast.success(t("form.created"));
+      setShowNewDialog(false);
+      router.push(`/quotes/${result.data.id}`);
+    } else {
+      toast.error(result.error || t("form.failedCreate"));
+    }
+    setCreating(false);
+  };
+
+  const filteredVehicles = newCustomerId
+    ? vehicles.filter((v) => v.customerId === newCustomerId)
+    : vehicles;
+  const selectedVehicle = vehicles.find((v) => v.id === newVehicleId);
+  const selectedCustomer = customers.find((c) => c.id === newCustomerId);
+
+  const handleCustomerSelect = (customerId: string) => {
+    setNewCustomerId(customerId);
+    setCustomerOpen(false);
+    const customerVehicles = vehicles.filter((v) => v.customerId === customerId);
+    if (customerVehicles.length > 0) {
+      setNewVehicleId(customerVehicles[0].id);
+    } else if (newVehicleId) {
+      const vehicle = vehicles.find((v) => v.id === newVehicleId);
+      if (vehicle && vehicle.customerId !== customerId) {
+        setNewVehicleId("");
+      }
+    }
+  };
+
   return (
   return (
     <div className="space-y-4">
     <div className="space-y-4">
       <div className="flex flex-wrap gap-2">
       <div className="flex flex-wrap gap-2">
@@ -135,7 +239,7 @@ export function QuotesClient({
           </form>
           </form>
           {isPending && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
           {isPending && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
         </div>
         </div>
-        <Button size="sm" onClick={() => router.push("/quotes/new")}>
+        <Button size="sm" onClick={openNewDialog}>
           <Plus className="mr-1 h-3.5 w-3.5" />
           <Plus className="mr-1 h-3.5 w-3.5" />
           {t("list.newQuote")}
           {t("list.newQuote")}
         </Button>
         </Button>
@@ -203,6 +307,122 @@ export function QuotesClient({
         totalPages={data.totalPages}
         totalPages={data.totalPages}
         onNavigate={navigate}
         onNavigate={navigate}
       />
       />
+
+      {/* New Quote Dialog */}
+      <Dialog open={showNewDialog} onOpenChange={setShowNewDialog}>
+        <DialogContent className="sm:max-w-md">
+          <DialogHeader>
+            <DialogTitle>{t("form.newQuote")}</DialogTitle>
+          </DialogHeader>
+          <form onSubmit={handleCreateQuote} className="space-y-4">
+            <div className="space-y-2">
+              <Label htmlFor="new-quote-title">{t("details.titleLabel")}</Label>
+              <Input
+                id="new-quote-title"
+                value={newTitle}
+                onChange={(e) => setNewTitle(e.target.value)}
+                placeholder={t("details.titlePlaceholder")}
+                required
+                autoFocus
+              />
+            </div>
+
+            <div className="space-y-2">
+              <Label>{t("details.vehicle")}</Label>
+              <Popover open={vehicleOpen} onOpenChange={setVehicleOpen}>
+                <PopoverTrigger asChild>
+                  <Button
+                    variant="outline"
+                    role="combobox"
+                    className="w-full justify-between font-normal"
+                  >
+                    {selectedVehicle
+                      ? `${selectedVehicle.year} ${selectedVehicle.make} ${selectedVehicle.model}${selectedVehicle.licensePlate ? ` · ${selectedVehicle.licensePlate}` : ""}`
+                      : t("details.selectVehicle")}
+                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+                  </Button>
+                </PopoverTrigger>
+                <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
+                  <Command>
+                    <CommandInput placeholder={t("details.selectVehicle")} />
+                    <CommandList>
+                      <CommandEmpty>{t("details.none")}</CommandEmpty>
+                      <CommandGroup>
+                        {filteredVehicles.map((v) => (
+                          <CommandItem
+                            key={v.id}
+                            value={`${v.year} ${v.make} ${v.model} ${v.licensePlate || ""} ${v.customerName || ""}`}
+                            onSelect={() => handleVehicleSelect(v.id)}
+                          >
+                            <Check className={cn("mr-2 h-4 w-4", newVehicleId === v.id ? "opacity-100" : "opacity-0")} />
+                            <div>
+                              <p className="text-sm">
+                                {v.year} {v.make} {v.model}
+                                {v.licensePlate && <span className="ml-1.5 text-muted-foreground">· {v.licensePlate}</span>}
+                              </p>
+                              {v.customerName && (
+                                <p className="text-xs text-muted-foreground">{v.customerName}</p>
+                              )}
+                            </div>
+                          </CommandItem>
+                        ))}
+                      </CommandGroup>
+                    </CommandList>
+                  </Command>
+                </PopoverContent>
+              </Popover>
+            </div>
+
+            <div className="space-y-2">
+              <Label>{t("details.customer")}</Label>
+              <Popover open={customerOpen} onOpenChange={setCustomerOpen}>
+                <PopoverTrigger asChild>
+                  <Button
+                    variant="outline"
+                    role="combobox"
+                    className="w-full justify-between font-normal"
+                  >
+                    {selectedCustomer
+                      ? `${selectedCustomer.name}${selectedCustomer.company ? ` (${selectedCustomer.company})` : ""}`
+                      : t("details.selectCustomer")}
+                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+                  </Button>
+                </PopoverTrigger>
+                <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
+                  <Command>
+                    <CommandInput placeholder={t("details.selectCustomer")} />
+                    <CommandList>
+                      <CommandEmpty>{t("details.none")}</CommandEmpty>
+                      <CommandGroup>
+                        {customers.map((c) => (
+                          <CommandItem
+                            key={c.id}
+                            value={`${c.name} ${c.company || ""}`}
+                            onSelect={() => handleCustomerSelect(c.id)}
+                          >
+                            <Check className={cn("mr-2 h-4 w-4", newCustomerId === c.id ? "opacity-100" : "opacity-0")} />
+                            <span>{c.name}{c.company ? ` (${c.company})` : ""}</span>
+                          </CommandItem>
+                        ))}
+                      </CommandGroup>
+                    </CommandList>
+                  </Command>
+                </PopoverContent>
+              </Popover>
+            </div>
+
+            <div className="flex justify-end gap-3 pt-2">
+              <Button type="button" variant="outline" onClick={() => setShowNewDialog(false)}>
+                {t("form.cancel")}
+              </Button>
+              <Button type="submit" disabled={creating || !newTitle.trim()}>
+                {creating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+                {t("form.createQuote")}
+              </Button>
+            </div>
+          </form>
+        </DialogContent>
+      </Dialog>
     </div>
     </div>
   );
   );
 }
 }

+ 0 - 1
src/components/page-header.tsx

@@ -46,7 +46,6 @@ const breadcrumbMap: Record<string, BreadcrumbSegment[]> = {
   '/customers': [{ key: 'customers', href: '/customers' }, { key: 'allCustomers' }],
   '/customers': [{ key: 'customers', href: '/customers' }, { key: 'allCustomers' }],
   '/work-orders': [{ key: 'workOrders', href: '/work-orders' }, { key: 'allWorkOrders' }],
   '/work-orders': [{ key: 'workOrders', href: '/work-orders' }, { key: 'allWorkOrders' }],
   '/quotes': [{ key: 'quotes', href: '/quotes' }, { key: 'allQuotes' }],
   '/quotes': [{ key: 'quotes', href: '/quotes' }, { key: 'allQuotes' }],
-  '/quotes/new': [{ key: 'quotes', href: '/quotes' }, { key: 'newQuote' }],
   '/billing': [{ key: 'billing', href: '/billing' }, { key: 'billingHistory' }],
   '/billing': [{ key: 'billing', href: '/billing' }, { key: 'billingHistory' }],
   '/inventory': [{ key: 'inventory', href: '/inventory' }, { key: 'allParts' }],
   '/inventory': [{ key: 'inventory', href: '/inventory' }, { key: 'allParts' }],
   '/reports': [{ key: 'reports', href: '/reports' }, { key: 'reports' }],
   '/reports': [{ key: 'reports', href: '/reports' }, { key: 'reports' }],

+ 1 - 1
src/features/inspections/Actions/quoteRequestActions.ts

@@ -105,7 +105,7 @@ export async function getQuoteRequests() {
                 model: true,
                 model: true,
                 year: true,
                 year: true,
                 licensePlate: true,
                 licensePlate: true,
-                customer: { select: { name: true } },
+                customer: { select: { id: true, name: true } },
               },
               },
             },
             },
             items: { select: { id: true, name: true, section: true, condition: true, notes: true } },
             items: { select: { id: true, name: true, section: true, condition: true, notes: true } },

+ 40 - 4
src/features/inspections/Components/InspectionPageClient.tsx

@@ -21,6 +21,7 @@ import {
 } from "lucide-react";
 } from "lucide-react";
 import { toast } from "sonner";
 import { toast } from "sonner";
 import { updateInspectionItem, completeInspection, deleteInspection } from "../Actions/inspectionActions";
 import { updateInspectionItem, completeInspection, deleteInspection } from "../Actions/inspectionActions";
+import { createQuote } from "@/features/quotes/Actions/quoteActions";
 import { InspectionShareDialog } from "./InspectionShareDialog";
 import { InspectionShareDialog } from "./InspectionShareDialog";
 
 
 type Condition = "pass" | "fail" | "attention" | "not_inspected";
 type Condition = "pass" | "fail" | "attention" | "not_inspected";
@@ -424,6 +425,7 @@ export function InspectionPageClient({
   const [showCompleteDialog, setShowCompleteDialog] = useState(false);
   const [showCompleteDialog, setShowCompleteDialog] = useState(false);
   const [showDeleteDialog, setShowDeleteDialog] = useState(false);
   const [showDeleteDialog, setShowDeleteDialog] = useState(false);
   const [showShareDialog, setShowShareDialog] = useState(false);
   const [showShareDialog, setShowShareDialog] = useState(false);
+  const [isCreatingQuote, setIsCreatingQuote] = useState(false);
 
 
   const isCompleted = inspection.status === "completed";
   const isCompleted = inspection.status === "completed";
 
 
@@ -445,8 +447,40 @@ export function InspectionPageClient({
   const failCount = inspection.items.filter((i) => i.condition === "fail").length;
   const failCount = inspection.items.filter((i) => i.condition === "fail").length;
   const attentionCount = inspection.items.filter((i) => i.condition === "attention").length;
   const attentionCount = inspection.items.filter((i) => i.condition === "attention").length;
   const hasIssueItems = failCount > 0 || attentionCount > 0;
   const hasIssueItems = failCount > 0 || attentionCount > 0;
+  const issueItems = inspection.items.filter(
+    (i) => i.condition === "fail" || i.condition === "attention"
+  );
   const pendingQuoteRequest = inspection.quoteRequests?.[0] ?? null;
   const pendingQuoteRequest = inspection.quoteRequests?.[0] ?? null;
 
 
+  const handleCreateQuoteFromInspection = async () => {
+    setIsCreatingQuote(true);
+    const result = await createQuote({
+      title: `${inspection.vehicle.year} ${inspection.vehicle.make} ${inspection.vehicle.model} - Inspection Quote`,
+      vehicleId: inspection.vehicle.id,
+      customerId: inspection.vehicle.customer?.id || undefined,
+      inspectionId: inspection.id,
+      status: "draft",
+      laborItems: issueItems.map((item) => ({
+        description: `${item.name}${item.notes ? ` - ${item.notes}` : ""}`,
+        hours: 0,
+        rate: 0,
+        total: 0,
+      })),
+      subtotal: 0,
+      taxRate: 0,
+      taxAmount: 0,
+      discountValue: 0,
+      discountAmount: 0,
+      totalAmount: 0,
+    });
+    if (result.success && result.data) {
+      router.push(`/quotes/${result.data.id}`);
+    } else {
+      toast.error(result.error || "Failed to create quote");
+      setIsCreatingQuote(false);
+    }
+  };
+
   const handleComplete = () => {
   const handleComplete = () => {
     startTransition(async () => {
     startTransition(async () => {
       const result = await completeInspection(inspection.id);
       const result = await completeInspection(inspection.id);
@@ -505,9 +539,10 @@ export function InspectionPageClient({
               <Button
               <Button
                 variant="outline"
                 variant="outline"
                 size="sm"
                 size="sm"
-                onClick={() => router.push(`/quotes/new?fromInspection=${inspection.id}`)}
+                disabled={isCreatingQuote}
+                onClick={handleCreateQuoteFromInspection}
               >
               >
-                <FileText className="mr-1 h-3.5 w-3.5" />
+                {isCreatingQuote ? <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" /> : <FileText className="mr-1 h-3.5 w-3.5" />}
                 Create Quote
                 Create Quote
               </Button>
               </Button>
             ) : null}
             ) : null}
@@ -648,9 +683,10 @@ export function InspectionPageClient({
                   size="sm"
                   size="sm"
                   variant="outline"
                   variant="outline"
                   className="border-amber-500/30 text-amber-900 hover:bg-amber-100 dark:text-amber-200 dark:hover:bg-amber-900/30"
                   className="border-amber-500/30 text-amber-900 hover:bg-amber-100 dark:text-amber-200 dark:hover:bg-amber-900/30"
-                  onClick={() => router.push(`/quotes/new?fromInspection=${inspection.id}`)}
+                  disabled={isCreatingQuote}
+                  onClick={handleCreateQuoteFromInspection}
                 >
                 >
-                  <FileText className="mr-1 h-3.5 w-3.5" />
+                  {isCreatingQuote ? <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" /> : <FileText className="mr-1 h-3.5 w-3.5" />}
                   Create Quote
                   Create Quote
                 </Button>
                 </Button>
               </div>
               </div>

+ 0 - 599
src/features/quotes/Components/QuoteForm.tsx

@@ -1,599 +0,0 @@
-"use client";
-
-import { useState, useCallback, useEffect } from "react";
-import { useRouter } from "next/navigation";
-import { toast } from "sonner";
-import Link from "next/link";
-import { useTranslations } from "next-intl";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import {
-  Select,
-  SelectContent,
-  SelectItem,
-  SelectTrigger,
-  SelectValue,
-} from "@/components/ui/select";
-import {
-  ResizablePanelGroup,
-  ResizablePanel,
-  ResizableHandle,
-} from "@/components/ui/resizable";
-import { useGlassModal } from "@/components/glass-modal";
-import { createQuote, updateQuote } from "@/features/quotes/Actions/quoteActions";
-import type { QuotePartInput, QuoteLaborInput } from "@/features/quotes/Schema/quoteSchema";
-import { RichTextEditor } from "@/features/vehicles/Components/service-edit/RichTextEditor";
-import { ArrowLeft, Car, ClipboardCheck, FileText, Loader2, Plus, Save, Trash2, Users, X } from "lucide-react";
-import { formatCurrency, getCurrencySymbol } from "@/lib/format";
-
-interface CustomerOption {
-  id: string;
-  name: string;
-  email: string | null;
-  company: string | null;
-}
-
-interface VehicleOption {
-  id: string;
-  make: string;
-  model: string;
-  year: number;
-  licensePlate: string | null;
-  customerId: string | null;
-  customerName: string | null;
-}
-
-interface InitialData {
-  id: string;
-  title: string;
-  description: string | null;
-  status: string;
-  validUntil: string | null;
-  customerId: string | null;
-  vehicleId: string | null;
-  notes: string | null;
-  partItems: QuotePartInput[];
-  laborItems: QuoteLaborInput[];
-  subtotal: number;
-  taxRate: number;
-  taxAmount: number;
-  discountType: string | null;
-  discountValue: number;
-  discountAmount: number;
-  totalAmount: number;
-}
-
-const emptyPart = (): QuotePartInput => ({
-  partNumber: "",
-  name: "",
-  quantity: 1,
-  unitPrice: 0,
-  total: 0,
-  excluded: false,
-});
-
-const makeEmptyLabor = (defaultRate: number): QuoteLaborInput => ({
-  description: "",
-  hours: 0,
-  rate: defaultRate,
-  total: 0,
-  excluded: false,
-});
-
-const LG_BREAKPOINT = 1024;
-
-function useIsLargeScreen() {
-  const [isLarge, setIsLarge] = useState(false);
-  useEffect(() => {
-    const mql = window.matchMedia(`(min-width: ${LG_BREAKPOINT}px)`);
-    const onChange = () => setIsLarge(mql.matches);
-    mql.addEventListener("change", onChange);
-    setIsLarge(mql.matches);
-    return () => mql.removeEventListener("change", onChange);
-  }, []);
-  return isLarge;
-}
-
-interface PrefillData {
-  title?: string;
-  vehicleId?: string;
-  customerId?: string;
-  inspectionId?: string;
-  laborItems?: (Omit<QuoteLaborInput, 'excluded'> & { excluded?: boolean })[];
-}
-
-export function QuoteForm({
-  currencyCode = "USD",
-  defaultTaxRate = 0,
-  taxEnabled = true,
-  defaultLaborRate = 0,
-  quoteValidDays = 30,
-  customers = [],
-  vehicles = [],
-  initialData,
-  prefill,
-}: {
-  currencyCode?: string;
-  defaultTaxRate?: number;
-  taxEnabled?: boolean;
-  defaultLaborRate?: number;
-  quoteValidDays?: number;
-  customers?: CustomerOption[];
-  vehicles?: VehicleOption[];
-  initialData?: InitialData;
-  prefill?: PrefillData;
-}) {
-  const cs = getCurrencySymbol(currencyCode);
-  const isEdit = !!initialData;
-  const router = useRouter();
-  const modal = useGlassModal();
-  const isLarge = useIsLargeScreen();
-  const t = useTranslations("quotes");
-  const [loading, setLoading] = useState(false);
-  const [status, setStatus] = useState(initialData?.status || "draft");
-  const [customerId, setCustomerId] = useState(initialData?.customerId || prefill?.customerId || "");
-  const [vehicleId, setVehicleId] = useState(initialData?.vehicleId || prefill?.vehicleId || "");
-  const [partItems, setPartItems] = useState<QuotePartInput[]>(initialData?.partItems || []);
-  const [laborItems, setLaborItems] = useState<QuoteLaborInput[]>(initialData?.laborItems || (prefill?.laborItems?.map((l) => ({ ...l, excluded: l.excluded ?? false }))) || []);
-  const [taxRate, setTaxRate] = useState(initialData?.taxRate ?? defaultTaxRate);
-  const [discountType, setDiscountType] = useState<string>(initialData?.discountType || "none");
-  const [discountValue, setDiscountValue] = useState(initialData?.discountValue ?? 0);
-  const [noteType, setNoteType] = useState<"public" | "internal">("public");
-  const [description, setDescription] = useState(initialData?.description || "");
-  const [notes, setNotes] = useState(initialData?.notes || "");
-
-  const [defaultValidDate] = useState(() =>
-    initialData?.validUntil
-      ? initialData.validUntil.split("T")[0]
-      : new Date(Date.now() + quoteValidDays * 86400000).toISOString().split("T")[0]
-  );
-
-  const partsSubtotal = partItems.reduce((sum, p) => p.excluded ? sum : sum + p.total, 0);
-  const laborSubtotal = laborItems.reduce((sum, l) => l.excluded ? sum : sum + l.total, 0);
-  const subtotal = partsSubtotal + laborSubtotal;
-  const discountAmount = discountType === "percentage"
-    ? subtotal * (discountValue / 100)
-    : discountType === "fixed"
-    ? Math.min(discountValue, subtotal)
-    : 0;
-  const taxAmount = (subtotal - discountAmount) * (taxRate / 100);
-  const totalAmount = subtotal - discountAmount + taxAmount;
-
-  const selectedVehicle = vehicles.find((v) => v.id === vehicleId);
-  const selectedCustomer = customers.find((c) => c.id === customerId);
-
-  const handleVehicleChange = (v: string) => {
-    const vid = v === "none" ? "" : v;
-    setVehicleId(vid);
-    if (vid) {
-      const vehicle = vehicles.find((veh) => veh.id === vid);
-      if (vehicle?.customerId) {
-        setCustomerId(vehicle.customerId);
-      }
-    }
-  };
-
-  const updatePart = useCallback((index: number, field: keyof QuotePartInput, value: string | number | boolean) => {
-    setPartItems((prev) => {
-      const updated = [...prev];
-      const part = { ...updated[index], [field]: value };
-      if (field === "quantity" || field === "unitPrice") {
-        part.total = Number(part.quantity) * Number(part.unitPrice);
-      }
-      updated[index] = part;
-      return updated;
-    });
-  }, []);
-
-  const updateLabor = useCallback((index: number, field: keyof QuoteLaborInput, value: string | number | boolean) => {
-    setLaborItems((prev) => {
-      const updated = [...prev];
-      const labor = { ...updated[index], [field]: value };
-      if (field === "hours" || field === "rate") {
-        labor.total = Number(labor.hours) * Number(labor.rate);
-      }
-      updated[index] = labor;
-      return updated;
-    });
-  }, []);
-
-  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
-    e.preventDefault();
-    setLoading(true);
-
-    const formData = new FormData(e.currentTarget);
-    const payload = {
-      title: formData.get("title") as string,
-      description: description || undefined,
-      status,
-      validUntil: (formData.get("validUntil") as string) || undefined,
-      customerId: customerId || undefined,
-      vehicleId: vehicleId || undefined,
-      notes: notes || undefined,
-      inspectionId: prefill?.inspectionId || undefined,
-      partItems: partItems.filter((p) => p.name),
-      laborItems: laborItems.filter((l) => l.description),
-      subtotal,
-      taxRate,
-      taxAmount,
-      discountType: discountType === "none" ? undefined : discountType,
-      discountValue,
-      discountAmount,
-      totalAmount,
-    };
-
-    const result = isEdit
-      ? await updateQuote({ id: initialData.id, ...payload })
-      : await createQuote(payload);
-
-    if (result.success && result.data) {
-      toast.success(isEdit ? t("form.updated") : t("form.created"));
-      router.push(`/quotes/${result.data.id}`);
-      router.refresh();
-    } else {
-      modal.open("error", "Error", result.error || (isEdit ? t("form.failedUpdate") : t("form.failedCreate")));
-    }
-    setLoading(false);
-  };
-
-  // --- Left column: Parts, Labor, Notes ---
-  const leftColumn = (
-    <div className="space-y-3">
-      {/* Parts */}
-      <div className="rounded-lg border p-3 space-y-2">
-        <div className="flex items-center justify-between">
-          <h3 className="text-sm font-semibold">{t("parts.title")}</h3>
-          <Button type="button" variant="outline" size="sm" onClick={() => setPartItems([...partItems, emptyPart()])}>
-            <Plus className="mr-1 h-3.5 w-3.5" /> {t("parts.addPart")}
-          </Button>
-        </div>
-        {partItems.length > 0 && (
-          <>
-            <div className="hidden grid-cols-[1fr_2fr_0.7fr_1fr_1fr_auto] gap-2 text-xs font-medium text-muted-foreground sm:grid">
-              <span>{t("parts.partNumber")}</span><span>{t("parts.name")}</span><span>{t("parts.qty")}</span><span>{t("parts.unitPrice")}</span><span>{t("parts.total")}</span><span />
-            </div>
-            {partItems.map((part, i) => (
-              <div key={i} className={`grid grid-cols-2 gap-2 sm:grid-cols-[1fr_2fr_0.7fr_1fr_1fr_auto]${part.excluded ? " line-through opacity-50" : ""}`}>
-                <Input placeholder={t("parts.partNumber")} value={part.partNumber ?? ""} onChange={(e) => updatePart(i, "partNumber", e.target.value)} />
-                <Input placeholder={t("parts.namePlaceholder")} value={part.name} onChange={(e) => updatePart(i, "name", e.target.value)} />
-                <Input type="number" min="0" step="1" value={part.quantity} onChange={(e) => updatePart(i, "quantity", e.target.value)} />
-                <Input type="number" min="0" step="0.01" value={part.unitPrice} onChange={(e) => updatePart(i, "unitPrice", e.target.value)} />
-                <div className="flex items-center rounded-md bg-muted/50 px-3 text-sm font-medium">{formatCurrency(part.total, currencyCode)}</div>
-                <div className="flex items-center gap-1">
-                  <input type="checkbox" checked={part.excluded ?? false} onChange={(e) => updatePart(i, "excluded", e.target.checked)} className="h-4 w-4 rounded border-gray-300" title="Exclude from total" />
-                  <Button type="button" variant="ghost" size="icon" className="h-9 w-9 text-muted-foreground hover:text-destructive" onClick={() => setPartItems(partItems.filter((_, j) => j !== i))}>
-                    <Trash2 className="h-4 w-4" />
-                  </Button>
-                </div>
-              </div>
-            ))}
-            <button
-              type="button"
-              className="flex w-full items-center justify-center rounded-md border border-dashed border-muted-foreground/25 py-1.5 text-muted-foreground transition-colors hover:border-muted-foreground/50 hover:text-foreground"
-              onClick={() => setPartItems([...partItems, emptyPart()])}
-            >
-              <Plus className="h-4 w-4" />
-            </button>
-            <div className="flex justify-end pt-1 text-sm">
-              <span className="font-medium">{t("parts.subtotal", { amount: formatCurrency(partsSubtotal, currencyCode) })}</span>
-            </div>
-          </>
-        )}
-        {partItems.length === 0 && (
-          <button
-            type="button"
-            className="flex w-full items-center justify-center rounded-md border border-dashed border-muted-foreground/25 py-1.5 text-muted-foreground transition-colors hover:border-muted-foreground/50 hover:text-foreground"
-            onClick={() => setPartItems([...partItems, emptyPart()])}
-          >
-            <Plus className="mr-1 h-4 w-4" />
-            <span className="text-sm">{t("parts.addPart")}</span>
-          </button>
-        )}
-      </div>
-
-      {/* Labor */}
-      <div className="rounded-lg border p-3 space-y-2">
-        <div className="flex items-center justify-between">
-          <h3 className="text-sm font-semibold">{t("labor.title")}</h3>
-          <Button type="button" variant="outline" size="sm" onClick={() => setLaborItems([...laborItems, makeEmptyLabor(defaultLaborRate)])}>
-            <Plus className="mr-1 h-3.5 w-3.5" /> {t("labor.addLabor")}
-          </Button>
-        </div>
-        {laborItems.length > 0 && (
-          <>
-            <div className="hidden grid-cols-[2fr_1fr_1fr_1fr_auto] gap-2 text-xs font-medium text-muted-foreground sm:grid">
-              <span>{t("labor.description")}</span><span>{t("labor.hours")}</span><span>{t("labor.rate", { currency: cs })}</span><span>{t("labor.total")}</span><span />
-            </div>
-            {laborItems.map((labor, i) => (
-              <div key={i} className={`grid grid-cols-2 gap-2 sm:grid-cols-[2fr_1fr_1fr_1fr_auto]${labor.excluded ? " line-through opacity-50" : ""}`}>
-                <Input placeholder={t("labor.descriptionPlaceholder")} value={labor.description} onChange={(e) => updateLabor(i, "description", e.target.value)} className="col-span-2 sm:col-span-1" />
-                <Input type="number" min="0" step="0.1" value={labor.hours} onChange={(e) => updateLabor(i, "hours", e.target.value)} />
-                <Input type="number" min="0" step="0.01" value={labor.rate} onChange={(e) => updateLabor(i, "rate", e.target.value)} />
-                <div className="flex items-center rounded-md bg-muted/50 px-3 text-sm font-medium">{formatCurrency(labor.total, currencyCode)}</div>
-                <div className="flex items-center gap-1">
-                  <input type="checkbox" checked={labor.excluded ?? false} onChange={(e) => updateLabor(i, "excluded", e.target.checked)} className="h-4 w-4 rounded border-gray-300" title="Exclude from total" />
-                  <Button type="button" variant="ghost" size="icon" className="h-9 w-9 text-muted-foreground hover:text-destructive" onClick={() => setLaborItems(laborItems.filter((_, j) => j !== i))}>
-                    <Trash2 className="h-4 w-4" />
-                  </Button>
-                </div>
-              </div>
-            ))}
-            <button
-              type="button"
-              className="flex w-full items-center justify-center rounded-md border border-dashed border-muted-foreground/25 py-1.5 text-muted-foreground transition-colors hover:border-muted-foreground/50 hover:text-foreground"
-              onClick={() => setLaborItems([...laborItems, makeEmptyLabor(defaultLaborRate)])}
-            >
-              <Plus className="h-4 w-4" />
-            </button>
-            <div className="flex justify-end pt-1 text-sm">
-              <span className="font-medium">{t("labor.subtotal", { amount: formatCurrency(laborSubtotal, currencyCode) })}</span>
-            </div>
-          </>
-        )}
-        {laborItems.length === 0 && (
-          <button
-            type="button"
-            className="flex w-full items-center justify-center rounded-md border border-dashed border-muted-foreground/25 py-1.5 text-muted-foreground transition-colors hover:border-muted-foreground/50 hover:text-foreground"
-            onClick={() => setLaborItems([...laborItems, makeEmptyLabor(defaultLaborRate)])}
-          >
-            <Plus className="mr-1 h-4 w-4" />
-            <span className="text-sm">{t("labor.addLabor")}</span>
-          </button>
-        )}
-      </div>
-
-      {/* Notes */}
-      <div className="rounded-lg border p-3 space-y-3">
-        <div className="flex items-center justify-between">
-          <h3 className="flex items-center gap-2 text-sm font-semibold">
-            <FileText className="h-3.5 w-3.5" />
-            {t("notes.title")}
-          </h3>
-          <Select value={noteType} onValueChange={(v) => setNoteType(v as "public" | "internal")}>
-            <SelectTrigger className="h-7 w-[120px] text-xs">
-              <SelectValue />
-            </SelectTrigger>
-            <SelectContent>
-              <SelectItem value="public">{t("notes.public")}</SelectItem>
-              <SelectItem value="internal">{t("notes.internal")}</SelectItem>
-            </SelectContent>
-          </Select>
-        </div>
-        {noteType === "public" && (
-          <div className="space-y-1">
-            <RichTextEditor
-              content={description}
-              onChange={setDescription}
-              placeholder={t("notes.publicPlaceholder")}
-            />
-            <p className="text-xs text-muted-foreground">{t("notes.publicHelper")}</p>
-          </div>
-        )}
-        {noteType === "internal" && (
-          <div className="space-y-1">
-            <RichTextEditor
-              content={notes}
-              onChange={setNotes}
-              placeholder={t("notes.internalPlaceholder")}
-            />
-            <p className="text-xs text-muted-foreground">{t("notes.internalHelper")}</p>
-          </div>
-        )}
-      </div>
-    </div>
-  );
-
-  // --- Right column: Vehicle & Customer, Quote Details, Totals ---
-  const rightColumn = (
-    <div className="space-y-3">
-      {/* Vehicle & Customer */}
-      <div className="rounded-lg border p-3 space-y-3">
-        <div className="space-y-1">
-          <Label className="text-xs">{t("details.vehicle")}</Label>
-          <Select value={vehicleId || "none"} onValueChange={handleVehicleChange}>
-            <SelectTrigger><SelectValue placeholder={t("details.selectVehicle")} /></SelectTrigger>
-            <SelectContent>
-              <SelectItem value="none">{t("details.none")}</SelectItem>
-              {vehicles.map((v) => (
-                <SelectItem key={v.id} value={v.id}>{v.year} {v.make} {v.model}{v.licensePlate ? ` (${v.licensePlate})` : ""}</SelectItem>
-              ))}
-            </SelectContent>
-          </Select>
-        </div>
-
-        {selectedVehicle && (
-          <div className="flex items-center gap-2 rounded-md bg-muted/50 px-3 py-2">
-            <Car className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
-            <div className="min-w-0 flex-1 text-sm">
-              <span className="font-medium">{selectedVehicle.year} {selectedVehicle.make} {selectedVehicle.model}</span>
-              {selectedVehicle.licensePlate && (
-                <span className="ml-1.5 text-muted-foreground">{selectedVehicle.licensePlate}</span>
-              )}
-            </div>
-            <Button type="button" variant="ghost" size="icon" className="h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground" onClick={() => setVehicleId("")}>
-              <X className="h-3 w-3" />
-            </Button>
-          </div>
-        )}
-
-        <div className="space-y-1">
-          <Label className="text-xs">{t("details.customer")}</Label>
-          <Select value={customerId || "none"} onValueChange={(v) => setCustomerId(v === "none" ? "" : v)}>
-            <SelectTrigger><SelectValue placeholder={t("details.selectCustomer")} /></SelectTrigger>
-            <SelectContent>
-              <SelectItem value="none">{t("details.none")}</SelectItem>
-              {customers.map((c) => (
-                <SelectItem key={c.id} value={c.id}>{c.name}{c.company ? ` (${c.company})` : ""}</SelectItem>
-              ))}
-            </SelectContent>
-          </Select>
-        </div>
-
-        {selectedCustomer && (
-          <div className="flex items-center gap-2 rounded-md bg-muted/50 px-3 py-2">
-            <Users className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
-            <div className="min-w-0 flex-1 text-sm">
-              <span className="font-medium">{selectedCustomer.name}</span>
-              {selectedCustomer.company && (
-                <span className="ml-1.5 text-muted-foreground">{selectedCustomer.company}</span>
-              )}
-            </div>
-            <Button type="button" variant="ghost" size="icon" className="h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground" onClick={() => setCustomerId("")}>
-              <X className="h-3 w-3" />
-            </Button>
-          </div>
-        )}
-      </div>
-
-      {/* Quote Details */}
-      <div className="rounded-lg border p-3 space-y-3">
-        <h3 className="text-sm font-semibold">{t("details.title")}</h3>
-        <div className="space-y-1">
-          <Label htmlFor="title" className="text-xs">{t("details.titleLabel")}</Label>
-          <Input id="title" name="title" placeholder={t("details.titlePlaceholder")} defaultValue={initialData?.title || prefill?.title || ""} required />
-        </div>
-        <div className="grid grid-cols-2 gap-2">
-          <div className="space-y-1">
-            <Label className="text-xs">{t("details.status")}</Label>
-            <Select value={status} onValueChange={setStatus}>
-              <SelectTrigger><SelectValue /></SelectTrigger>
-              <SelectContent>
-                <SelectItem value="draft">{t("details.statusDraft")}</SelectItem>
-                <SelectItem value="sent">{t("details.statusSent")}</SelectItem>
-                <SelectItem value="accepted">{t("details.statusAccepted")}</SelectItem>
-                <SelectItem value="rejected">{t("details.statusRejected")}</SelectItem>
-              </SelectContent>
-            </Select>
-          </div>
-          <div className="space-y-1">
-            <Label htmlFor="validUntil" className="text-xs">{t("details.validUntil")}</Label>
-            <Input id="validUntil" name="validUntil" type="date" defaultValue={defaultValidDate} />
-          </div>
-        </div>
-        {prefill?.inspectionId && (
-          <Link
-            href={`/inspections/${prefill.inspectionId}`}
-            className="flex items-center gap-2 rounded-md bg-muted/50 px-3 py-2 text-sm text-muted-foreground transition-colors hover:text-foreground"
-          >
-            <ClipboardCheck className="h-3.5 w-3.5 shrink-0" />
-            <span>{t("details.viewInspection")}</span>
-          </Link>
-        )}
-      </div>
-
-      {/* Totals */}
-      <div className="rounded-lg border p-3 space-y-2">
-        <h3 className="text-sm font-semibold">{t("totals.title")}</h3>
-        <div className="space-y-2">
-          <div className="flex items-center justify-between text-sm">
-            <span className="text-muted-foreground">{t("totals.parts")}</span>
-            <span>{formatCurrency(partsSubtotal, currencyCode)}</span>
-          </div>
-          <div className="flex items-center justify-between text-sm">
-            <span className="text-muted-foreground">{t("totals.labor")}</span>
-            <span>{formatCurrency(laborSubtotal, currencyCode)}</span>
-          </div>
-          <div className="flex items-center justify-between text-sm">
-            <span className="text-muted-foreground">{t("totals.subtotal")}</span>
-            <span className="font-medium">{formatCurrency(subtotal, currencyCode)}</span>
-          </div>
-          <div className="flex items-center justify-between text-sm">
-            <div className="flex items-center gap-2">
-              <span className="text-muted-foreground">{t("totals.discount")}</span>
-              <Select value={discountType} onValueChange={setDiscountType}>
-                <SelectTrigger className="h-7 w-28 text-xs"><SelectValue /></SelectTrigger>
-                <SelectContent>
-                  <SelectItem value="none">{t("totals.discountNone")}</SelectItem>
-                  <SelectItem value="percentage">{t("totals.discountPercentage")}</SelectItem>
-                  <SelectItem value="fixed">{t("totals.discountFixed")}</SelectItem>
-                </SelectContent>
-              </Select>
-              {discountType !== "none" && (
-                <Input
-                  type="number" min="0" step="0.01"
-                  value={discountValue}
-                  onChange={(e) => setDiscountValue(e.target.value === "" ? 0 : Number(e.target.value))}
-                  className="h-7 w-20 text-right text-xs"
-                />
-              )}
-              {discountType === "percentage" && <span className="text-muted-foreground">%</span>}
-            </div>
-            {discountAmount > 0 && (
-              <span className="text-destructive">{formatCurrency(-discountAmount, currencyCode)}</span>
-            )}
-          </div>
-          {taxEnabled && (
-            <div className="flex items-center justify-between text-sm">
-              <div className="flex items-center gap-2">
-                <span className="text-muted-foreground">{t("totals.tax")}</span>
-                <Input
-                  type="number" min="0" step="0.1"
-                  value={taxRate}
-                  onChange={(e) => setTaxRate(e.target.value === "" ? 0 : Number(e.target.value))}
-                  className="h-7 w-20 text-right text-xs"
-                />
-                <span className="text-muted-foreground">%</span>
-              </div>
-              <span>{formatCurrency(taxAmount, currencyCode)}</span>
-            </div>
-          )}
-          <div className="flex items-center justify-between border-t pt-2 text-lg font-bold">
-            <span>{t("totals.total")}</span>
-            <span>{formatCurrency(totalAmount, currencyCode)}</span>
-          </div>
-        </div>
-      </div>
-    </div>
-  );
-
-  return (
-    <form onSubmit={handleSubmit} className="flex min-h-0 flex-1 flex-col overflow-hidden">
-      {/* Header */}
-      <div className="flex items-center justify-between border-b px-4 py-2">
-        <div className="flex items-center gap-3">
-          <Link
-            href="/quotes"
-            className="inline-flex items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-foreground"
-          >
-            <ArrowLeft className="h-4 w-4" />
-          </Link>
-          <h1 className="text-lg font-semibold">{isEdit ? t("form.editQuote") : t("form.newQuote")}</h1>
-        </div>
-        <div className="flex items-center gap-2">
-          <Button type="button" variant="outline" size="sm" asChild>
-            <Link href="/quotes">{t("form.cancel")}</Link>
-          </Button>
-          <Button type="submit" size="sm" disabled={loading}>
-            {loading ? <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" /> : <Save className="mr-1 h-3.5 w-3.5" />}
-            {isEdit ? t("form.updateQuote") : t("form.createQuote")}
-          </Button>
-        </div>
-      </div>
-
-      {/* Content */}
-      {isLarge ? (
-        <ResizablePanelGroup orientation="horizontal" className="flex-1 overflow-hidden">
-          <ResizablePanel defaultSize={75} minSize={40}>
-            <div className="h-full overflow-y-auto overscroll-contain p-4 pr-2">
-              <div className="space-y-3 pb-40">{leftColumn}</div>
-            </div>
-          </ResizablePanel>
-          <ResizableHandle withHandle />
-          <ResizablePanel defaultSize={25} minSize={15}>
-            <div className="h-full overflow-y-auto overscroll-contain p-4 pl-2">
-              <div className="space-y-3 pb-40">{rightColumn}</div>
-            </div>
-          </ResizablePanel>
-        </ResizablePanelGroup>
-      ) : (
-        <div className="flex-1 overflow-y-auto overscroll-contain p-4">
-          <div className="space-y-3 pb-40">
-            {leftColumn}
-            {rightColumn}
-          </div>
-        </div>
-      )}
-    </form>
-  );
-}