Przeglądaj źródła

Merge branch 'main' of github.com:Torqvoice/torqvoice

Bernt Christian Egeland 9 miesięcy temu
rodzic
commit
eac47c77de
28 zmienionych plików z 2299 dodań i 1819 usunięć
  1. 82 921
      package-lock.json
  2. 7 5
      package.json
  3. 2 0
      prisma/migrations/20260218071159_qoute_share_link/migration.sql
  4. 1 0
      prisma/schema.prisma
  5. 0 91
      src/app/(authenticated)/quotes/[id]/edit/page.tsx
  6. 79 14
      src/app/(authenticated)/quotes/[id]/page.tsx
  7. 0 417
      src/app/(authenticated)/quotes/[id]/quote-detail-client.tsx
  8. 4 2
      src/app/(authenticated)/quotes/new/page.tsx
  9. 4 4
      src/app/(authenticated)/quotes/quotes-client.tsx
  10. 2 2
      src/app/(authenticated)/settings/settings-nav.tsx
  11. 12 4
      src/app/(authenticated)/settings/templates/page.tsx
  12. 125 49
      src/app/(authenticated)/settings/templates/template-settings.tsx
  13. 97 38
      src/app/(public)/share/invoice/[orgId]/[token]/invoice-view.tsx
  14. 4 0
      src/app/(public)/share/invoice/[orgId]/[token]/page.tsx
  15. 117 0
      src/app/(public)/share/quote/[orgId]/[token]/page.tsx
  16. 394 0
      src/app/(public)/share/quote/[orgId]/[token]/quote-view.tsx
  17. 17 5
      src/app/api/files/public/[token]/[...path]/route.ts
  18. 3 3
      src/app/api/quotes/[id]/pdf/route.ts
  19. 122 0
      src/app/api/share/quote/[orgId]/[token]/pdf/route.ts
  20. 1 1
      src/components/page-header.tsx
  21. 34 16
      src/features/billing/Actions/billingActions.ts
  22. 42 0
      src/features/quotes/Actions/quoteShareActions.ts
  23. 371 232
      src/features/quotes/Components/QuoteForm.tsx
  24. 653 0
      src/features/quotes/Components/QuotePageClient.tsx
  25. 98 0
      src/features/quotes/Components/QuoteShareDialog.tsx
  26. 1 1
      src/features/search/Components/SearchCommand.tsx
  27. 3 0
      src/features/settings/Schema/settingsSchema.ts
  28. 24 14
      src/features/vehicles/Components/service-detail/PaymentsSection.tsx

Plik diff jest za duży
+ 82 - 921
package-lock.json


+ 7 - 5
package.json

@@ -14,7 +14,7 @@
     "check:fix": "biome check . --write"
   },
   "dependencies": {
-    "@aws-sdk/client-ses": "^3.990.0",
+    "@aws-sdk/client-ses": "^3.992.0",
     "@hookform/resolvers": "^5.2.2",
     "@prisma/client": "^6.19.2",
     "@react-pdf/renderer": "^4.3.2",
@@ -68,11 +68,13 @@
     "@types/react": "^19",
     "@types/react-dom": "^19",
     "dotenv": "^17.2.4",
-    "eslint": "^9",
-    "eslint-config-next": "16.1.6",
-    "shadcn": "^3.8.4",
+    "shadcn": "^3.8.5",
     "tailwindcss": "^4",
     "tw-animate-css": "^1.4.0",
     "typescript": "^5"
+  },
+  "overrides": {
+    "fast-xml-parser": ">=5.3.6",
+    "qs": ">=6.14.2"
   }
-}
+}

+ 2 - 0
prisma/migrations/20260218071159_qoute_share_link/migration.sql

@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "quotes" ADD COLUMN     "publicToken" TEXT;

+ 1 - 0
prisma/schema.prisma

@@ -372,6 +372,7 @@ model Quote {
   discountAmount Float     @default(0)
   totalAmount    Float     @default(0)
   notes          String?
+  publicToken    String?
   convertedToId  String?
   createdAt      DateTime  @default(now())
   updatedAt      DateTime  @updatedAt

+ 0 - 91
src/app/(authenticated)/quotes/[id]/edit/page.tsx

@@ -1,91 +0,0 @@
-import { getQuote } from "@/features/quotes/Actions/quoteActions";
-import { getSettings } from "@/features/settings/Actions/settingsActions";
-import { SETTING_KEYS } from "@/features/settings/Schema/settingsSchema";
-import { getCustomers } from "@/features/customers/Actions/customerActions";
-import { getVehicles } from "@/features/vehicles/Actions/vehicleActions";
-import { PageHeader } from "@/components/page-header";
-import { QuoteForm } from "@/features/quotes/Components/QuoteForm";
-
-export default async function EditQuotePage({
-  params,
-}: {
-  params: Promise<{ id: string }>;
-}) {
-  const { id } = await params;
-  const [result, settingsResult, customersResult, vehiclesResult] = await Promise.all([
-    getQuote(id),
-    getSettings([SETTING_KEYS.CURRENCY_CODE, SETTING_KEYS.DEFAULT_TAX_RATE, SETTING_KEYS.TAX_ENABLED, SETTING_KEYS.DEFAULT_LABOR_RATE]),
-    getCustomers(),
-    getVehicles(),
-  ]);
-
-  if (!result.success || !result.data) {
-    return (
-      <>
-        <PageHeader />
-        <div className="flex h-[50vh] items-center justify-center">
-          <p className="text-muted-foreground">{result.error || "Quote not found"}</p>
-        </div>
-      </>
-    );
-  }
-
-  const quote = result.data;
-  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 customers = customersResult.success && customersResult.data ? customersResult.data : [];
-  const vehicles = vehiclesResult.success && vehiclesResult.data ? vehiclesResult.data : [];
-
-  return (
-    <>
-      <PageHeader />
-      <div className="flex flex-1 flex-col gap-4 p-4 pt-0">
-        <QuoteForm
-          currencyCode={currencyCode}
-          defaultTaxRate={defaultTaxRate}
-          taxEnabled={taxEnabled}
-          defaultLaborRate={defaultLaborRate}
-          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 }) => ({
-            id: v.id, make: v.make, model: v.model, year: v.year, licensePlate: v.licensePlate,
-          }))}
-          initialData={{
-            id: quote.id,
-            title: quote.title,
-            description: quote.description,
-            status: quote.status,
-            validUntil: quote.validUntil ? new Date(quote.validUntil).toISOString() : null,
-            customerId: quote.customer?.id || null,
-            vehicleId: quote.vehicle?.id || null,
-            notes: quote.notes,
-            partItems: quote.partItems.map((p) => ({
-              partNumber: p.partNumber || "",
-              name: p.name,
-              quantity: p.quantity,
-              unitPrice: p.unitPrice,
-              total: p.total,
-            })),
-            laborItems: quote.laborItems.map((l) => ({
-              description: l.description,
-              hours: l.hours,
-              rate: l.rate,
-              total: l.total,
-            })),
-            subtotal: quote.subtotal,
-            taxRate: quote.taxRate,
-            taxAmount: quote.taxAmount,
-            discountType: quote.discountType,
-            discountValue: quote.discountValue,
-            discountAmount: quote.discountAmount,
-            totalAmount: quote.totalAmount,
-          }}
-        />
-      </div>
-    </>
-  );
-}

+ 79 - 14
src/app/(authenticated)/quotes/[id]/page.tsx

@@ -1,9 +1,11 @@
 import { getQuote } from "@/features/quotes/Actions/quoteActions";
 import { getSettings } from "@/features/settings/Actions/settingsActions";
 import { SETTING_KEYS } from "@/features/settings/Schema/settingsSchema";
+import { getCustomers } from "@/features/customers/Actions/customerActions";
 import { getVehicles } from "@/features/vehicles/Actions/vehicleActions";
+import { getAuthContext } from "@/lib/get-auth-context";
 import { PageHeader } from "@/components/page-header";
-import { QuoteDetailClient } from "./quote-detail-client";
+import { QuotePageClient } from "@/features/quotes/Components/QuotePageClient";
 
 export default async function QuoteDetailPage({
   params,
@@ -11,35 +13,98 @@ export default async function QuoteDetailPage({
   params: Promise<{ id: string }>;
 }) {
   const { id } = await params;
-  const [result, settingsResult, vehiclesResult] = await Promise.all([
-    getQuote(id),
-    getSettings([SETTING_KEYS.CURRENCY_CODE]),
-    getVehicles(),
-  ]);
+  const [result, settingsResult, customersResult, vehiclesResult, authContext] =
+    await Promise.all([
+      getQuote(id),
+      getSettings([
+        SETTING_KEYS.CURRENCY_CODE,
+        SETTING_KEYS.DEFAULT_TAX_RATE,
+        SETTING_KEYS.TAX_ENABLED,
+        SETTING_KEYS.DEFAULT_LABOR_RATE,
+      ]),
+      getCustomers(),
+      getVehicles(),
+      getAuthContext(),
+    ]);
 
   if (!result.success || !result.data) {
     return (
       <>
         <PageHeader />
         <div className="flex h-[50vh] items-center justify-center">
-          <p className="text-muted-foreground">{result.error || "Quote not found"}</p>
+          <p className="text-muted-foreground">
+            {result.error || "Quote not found"}
+          </p>
         </div>
       </>
     );
   }
 
-  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 vehicles = vehiclesResult.success && vehiclesResult.data
-    ? vehiclesResult.data.map((v) => ({ id: v.id, make: v.make, model: v.model, year: v.year, licensePlate: v.licensePlate }))
-    : [];
+  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 customers =
+    customersResult.success && customersResult.data
+      ? customersResult.data
+      : [];
+  const vehicles =
+    vehiclesResult.success && vehiclesResult.data
+      ? vehiclesResult.data
+      : [];
+  const organizationId = authContext?.organizationId || "";
 
   return (
     <>
       <PageHeader />
-      <div className="flex flex-1 flex-col gap-4 p-4 pt-0">
-        <QuoteDetailClient quote={result.data} currencyCode={currencyCode} vehicles={vehicles} />
-      </div>
+      <QuotePageClient
+        quote={result.data}
+        organizationId={organizationId}
+        currencyCode={currencyCode}
+        defaultTaxRate={defaultTaxRate}
+        taxEnabled={taxEnabled}
+        defaultLaborRate={defaultLaborRate}
+        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,
+          })
+        )}
+      />
     </>
   );
 }

+ 0 - 417
src/app/(authenticated)/quotes/[id]/quote-detail-client.tsx

@@ -1,417 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { useFormatDate } from "@/lib/use-format-date";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Separator } from "@/components/ui/separator";
-import { useGlassModal } from "@/components/glass-modal";
-import { useConfirm } from "@/components/confirm-dialog";
-import { toast } from "sonner";
-import { deleteQuote, updateQuoteStatus, convertQuoteToServiceRecord } from "@/features/quotes/Actions/quoteActions";
-import { sendQuoteEmail } from "@/features/email/Actions/emailActions";
-import { SendEmailDialog } from "@/features/email/Components/SendEmailDialog";
-import {
-  Select,
-  SelectContent,
-  SelectItem,
-  SelectTrigger,
-  SelectValue,
-} from "@/components/ui/select";
-import {
-  Dialog,
-  DialogContent,
-  DialogHeader,
-  DialogTitle,
-} from "@/components/ui/dialog";
-import {
-  ArrowLeft,
-  ArrowRight,
-  Building2,
-  Car,
-  Download,
-  Loader2,
-  Mail,
-  MapPin,
-  Pencil,
-  Phone,
-  Trash2,
-  Users,
-  Wrench,
-} from "lucide-react";
-import { formatCurrency, getCurrencySymbol } from "@/lib/format";
-
-const statusColors: Record<string, string> = {
-  draft: "bg-gray-500/10 text-gray-500 border-gray-500/20",
-  sent: "bg-blue-500/10 text-blue-500 border-blue-500/20",
-  accepted: "bg-emerald-500/10 text-emerald-600 border-emerald-500/20",
-  rejected: "bg-red-500/10 text-red-500 border-red-500/20",
-  expired: "bg-amber-500/10 text-amber-600 border-amber-500/20",
-  converted: "bg-purple-500/10 text-purple-500 border-purple-500/20",
-};
-
-interface QuoteDetail {
-  id: string;
-  quoteNumber: string | null;
-  title: string;
-  description: string | null;
-  status: string;
-  validUntil: Date | null;
-  subtotal: number;
-  taxRate: number;
-  taxAmount: number;
-  discountType: string | null;
-  discountValue: number;
-  discountAmount: number;
-  totalAmount: number;
-  notes: string | null;
-  convertedToId: string | null;
-  createdAt: Date;
-  partItems: { id: string; partNumber: string | null; name: string; quantity: number; unitPrice: number; total: number }[];
-  laborItems: { id: string; description: string; hours: number; rate: number; total: number }[];
-  customer: { id: string; name: string; email: string | null; phone: string | null; address: string | null; company: string | null } | null;
-  vehicle: { id: string; make: string; model: string; year: number; vin: string | null; licensePlate: string | null; mileage: number } | null;
-}
-
-interface VehicleOption {
-  id: string;
-  make: string;
-  model: string;
-  year: number;
-  licensePlate: string | null;
-}
-
-export function QuoteDetailClient({
-  quote,
-  currencyCode = "USD",
-  vehicles = [],
-}: {
-  quote: QuoteDetail;
-  currencyCode?: string;
-  vehicles?: VehicleOption[];
-}) {
-  const cs = getCurrencySymbol(currencyCode);
-  const router = useRouter();
-  const { formatDate } = useFormatDate();
-  const modal = useGlassModal();
-  const confirm = useConfirm();
-  const [downloading, setDownloading] = useState(false);
-  const [showEmailDialog, setShowEmailDialog] = useState(false);
-  const [showConvertDialog, setShowConvertDialog] = useState(false);
-  const [convertVehicleId, setConvertVehicleId] = useState(quote.vehicle?.id || "");
-  const [converting, setConverting] = useState(false);
-
-  const partsSubtotal = quote.partItems.reduce((sum, p) => sum + p.total, 0);
-  const laborSubtotal = quote.laborItems.reduce((sum, l) => sum + l.total, 0);
-
-  const handleDelete = async () => {
-    const ok = await confirm({ title: "Delete Quote", description: "This will permanently delete this quote.", confirmLabel: "Delete", destructive: true });
-    if (!ok) return;
-    const result = await deleteQuote(quote.id);
-    if (result.success) {
-      router.push("/quotes");
-      router.refresh();
-    } else {
-      modal.open("error", "Error", result.error || "Failed to delete");
-    }
-  };
-
-  const handleDownloadPDF = async () => {
-    setDownloading(true);
-    try {
-      const res = await fetch(`/api/quotes/${quote.id}/pdf`);
-      if (!res.ok) throw new Error("Failed to generate PDF");
-      const blob = await res.blob();
-      const url = URL.createObjectURL(blob);
-      const a = document.createElement("a");
-      a.href = url;
-      a.download = `quote-${quote.quoteNumber || quote.id}.pdf`;
-      a.click();
-      URL.revokeObjectURL(url);
-    } catch {
-      modal.open("error", "Error", "Failed to generate PDF");
-    }
-    setDownloading(false);
-  };
-
-  const handleStatusChange = async (newStatus: string) => {
-    await updateQuoteStatus(quote.id, newStatus);
-    toast.success("Quote status updated");
-    router.refresh();
-  };
-
-  const handleConvert = async () => {
-    if (!convertVehicleId) {
-      modal.open("error", "Error", "Please select a vehicle");
-      return;
-    }
-    setConverting(true);
-    const result = await convertQuoteToServiceRecord(quote.id, convertVehicleId);
-    if (result.success && result.data) {
-      router.push(`/vehicles/${convertVehicleId}/service/${result.data.id}`);
-      router.refresh();
-    } else {
-      modal.open("error", "Error", result.error || "Failed to convert");
-    }
-    setConverting(false);
-  };
-
-  return (
-    <div className="space-y-6">
-      <div>
-        <Link
-          href="/quotes"
-          className="mb-4 inline-flex items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-foreground"
-        >
-          <ArrowLeft className="h-4 w-4" />
-          Back to Quotes
-        </Link>
-        <div className="flex items-start justify-between">
-          <div>
-            <div className="flex items-center gap-3">
-              <Badge variant="outline" className={statusColors[quote.status] || ""}>{quote.status}</Badge>
-              <h1 className="text-2xl font-bold">{quote.title}</h1>
-            </div>
-            <p className="mt-1 text-sm text-muted-foreground">
-              {quote.quoteNumber} · Created {formatDate(new Date(quote.createdAt))}
-              {quote.validUntil && ` · Valid until ${formatDate(new Date(quote.validUntil))}`}
-            </p>
-          </div>
-          <div className="flex items-center gap-2">
-            {quote.status !== "converted" && (
-              <>
-                <Button variant="outline" size="sm" asChild>
-                  <Link href={`/quotes/${quote.id}/edit`}>
-                    <Pencil className="mr-1 h-3.5 w-3.5" /> Edit
-                  </Link>
-                </Button>
-                <Button variant="outline" size="sm" onClick={() => setShowConvertDialog(true)}>
-                  <ArrowRight className="mr-1 h-3.5 w-3.5" /> Convert to Work Order
-                </Button>
-              </>
-            )}
-            <Button variant="outline" size="sm" onClick={handleDownloadPDF} disabled={downloading}>
-              {downloading ? <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" /> : <Download className="mr-1 h-3.5 w-3.5" />}
-              PDF
-            </Button>
-            <Button variant="outline" size="sm" onClick={() => setShowEmailDialog(true)}>
-              <Mail className="mr-1 h-3.5 w-3.5" />
-              Email
-            </Button>
-            <Button variant="outline" size="sm" className="text-destructive hover:bg-destructive/10" onClick={handleDelete}>
-              <Trash2 className="mr-1 h-3.5 w-3.5" /> Delete
-            </Button>
-          </div>
-        </div>
-      </div>
-
-      {/* Status Actions */}
-      {quote.status !== "converted" && (
-        <Card className="border-0 shadow-sm">
-          <CardContent className="flex items-center gap-3 pt-6">
-            <span className="text-sm text-muted-foreground">Update status:</span>
-            {["draft", "sent", "accepted", "rejected"].map((s) => (
-              <Button
-                key={s}
-                variant={quote.status === s ? "default" : "outline"}
-                size="sm"
-                onClick={() => handleStatusChange(s)}
-                className="capitalize"
-              >
-                {s}
-              </Button>
-            ))}
-          </CardContent>
-        </Card>
-      )}
-
-      {/* Customer & Vehicle */}
-      <div className="grid gap-4 sm:grid-cols-2">
-        {quote.customer && (
-          <Card className="border-0 shadow-sm">
-            <CardHeader className="pb-2">
-              <CardTitle className="flex items-center gap-2 text-sm text-muted-foreground">
-                <Users className="h-4 w-4" /> Customer
-              </CardTitle>
-            </CardHeader>
-            <CardContent>
-              <Link href={`/customers/${quote.customer.id}`} className="font-semibold hover:underline">{quote.customer.name}</Link>
-              <div className="mt-1 space-y-0.5 text-sm text-muted-foreground">
-                {quote.customer.company && <div className="flex items-center gap-1.5"><Building2 className="h-3 w-3" />{quote.customer.company}</div>}
-                {quote.customer.email && <div className="flex items-center gap-1.5"><Mail className="h-3 w-3" />{quote.customer.email}</div>}
-                {quote.customer.phone && <div className="flex items-center gap-1.5"><Phone className="h-3 w-3" />{quote.customer.phone}</div>}
-                {quote.customer.address && <div className="flex items-center gap-1.5"><MapPin className="h-3 w-3" />{quote.customer.address}</div>}
-              </div>
-            </CardContent>
-          </Card>
-        )}
-        {quote.vehicle && (
-          <Card className="border-0 shadow-sm">
-            <CardHeader className="pb-2">
-              <CardTitle className="flex items-center gap-2 text-sm text-muted-foreground">
-                <Car className="h-4 w-4" /> Vehicle
-              </CardTitle>
-            </CardHeader>
-            <CardContent>
-              <p className="font-semibold">{quote.vehicle.year} {quote.vehicle.make} {quote.vehicle.model}</p>
-              {quote.vehicle.licensePlate && <p className="mt-0.5 font-mono text-xs text-muted-foreground">{quote.vehicle.licensePlate}</p>}
-              {quote.vehicle.vin && <p className="font-mono text-xs text-muted-foreground">VIN: {quote.vehicle.vin}</p>}
-            </CardContent>
-          </Card>
-        )}
-      </div>
-
-      {/* Description */}
-      {quote.description && (
-        <Card className="border-0 shadow-sm">
-          <CardHeader><CardTitle className="text-base">Description</CardTitle></CardHeader>
-          <CardContent><p className="whitespace-pre-wrap text-sm">{quote.description}</p></CardContent>
-        </Card>
-      )}
-
-      {/* Parts */}
-      {quote.partItems.length > 0 && (
-        <Card className="border-0 shadow-sm">
-          <CardHeader>
-            <CardTitle className="flex items-center gap-2 text-base">
-              <Wrench className="h-4 w-4" /> Parts ({quote.partItems.length})
-            </CardTitle>
-          </CardHeader>
-          <CardContent>
-            <div className="overflow-x-auto">
-              <table className="w-full text-sm">
-                <thead>
-                  <tr className="border-b text-left text-muted-foreground">
-                    <th className="pb-2 font-medium">Part #</th>
-                    <th className="pb-2 font-medium">Name</th>
-                    <th className="pb-2 text-right font-medium">Qty</th>
-                    <th className="pb-2 text-right font-medium">Unit Price</th>
-                    <th className="pb-2 text-right font-medium">Total</th>
-                  </tr>
-                </thead>
-                <tbody className="divide-y">
-                  {quote.partItems.map((p) => (
-                    <tr key={p.id}>
-                      <td className="py-2 font-mono text-xs">{p.partNumber || "-"}</td>
-                      <td className="py-2">{p.name}</td>
-                      <td className="py-2 text-right">{p.quantity}</td>
-                      <td className="py-2 text-right">{formatCurrency(p.unitPrice, currencyCode)}</td>
-                      <td className="py-2 text-right font-medium">{formatCurrency(p.total, currencyCode)}</td>
-                    </tr>
-                  ))}
-                </tbody>
-                <tfoot>
-                  <tr className="border-t"><td colSpan={4} className="pt-2 text-right font-medium">Parts Subtotal</td><td className="pt-2 text-right font-bold">{formatCurrency(partsSubtotal, currencyCode)}</td></tr>
-                </tfoot>
-              </table>
-            </div>
-          </CardContent>
-        </Card>
-      )}
-
-      {/* Labor */}
-      {quote.laborItems.length > 0 && (
-        <Card className="border-0 shadow-sm">
-          <CardHeader><CardTitle className="text-base">Labor ({quote.laborItems.length})</CardTitle></CardHeader>
-          <CardContent>
-            <div className="overflow-x-auto">
-              <table className="w-full text-sm">
-                <thead>
-                  <tr className="border-b text-left text-muted-foreground">
-                    <th className="pb-2 font-medium">Description</th>
-                    <th className="pb-2 text-right font-medium">Hours</th>
-                    <th className="pb-2 text-right font-medium">Rate</th>
-                    <th className="pb-2 text-right font-medium">Total</th>
-                  </tr>
-                </thead>
-                <tbody className="divide-y">
-                  {quote.laborItems.map((l) => (
-                    <tr key={l.id}>
-                      <td className="py-2">{l.description}</td>
-                      <td className="py-2 text-right">{l.hours}</td>
-                      <td className="py-2 text-right">{formatCurrency(l.rate, currencyCode)}/hr</td>
-                      <td className="py-2 text-right font-medium">{formatCurrency(l.total, currencyCode)}</td>
-                    </tr>
-                  ))}
-                </tbody>
-                <tfoot>
-                  <tr className="border-t"><td colSpan={3} className="pt-2 text-right font-medium">Labor Subtotal</td><td className="pt-2 text-right font-bold">{formatCurrency(laborSubtotal, currencyCode)}</td></tr>
-                </tfoot>
-              </table>
-            </div>
-          </CardContent>
-        </Card>
-      )}
-
-      {/* Totals */}
-      <Card className="border-0 shadow-sm">
-        <CardHeader><CardTitle className="text-base">Quote Summary</CardTitle></CardHeader>
-        <CardContent>
-          <div className="space-y-2">
-            {quote.subtotal > 0 && <div className="flex justify-between text-sm"><span className="text-muted-foreground">Subtotal</span><span>{formatCurrency(quote.subtotal, currencyCode)}</span></div>}
-            {quote.discountAmount > 0 && (
-              <div className="flex justify-between text-sm">
-                <span className="text-muted-foreground">Discount{quote.discountType === "percentage" ? ` (${quote.discountValue}%)` : ""}</span>
-                <span className="text-destructive">{formatCurrency(-quote.discountAmount, currencyCode)}</span>
-              </div>
-            )}
-            {quote.taxRate > 0 && <div className="flex justify-between text-sm"><span className="text-muted-foreground">Tax ({quote.taxRate}%)</span><span>{formatCurrency(quote.taxAmount, currencyCode)}</span></div>}
-            <Separator />
-            <div className="flex justify-between text-lg font-bold"><span>Total</span><span>{formatCurrency(quote.totalAmount, currencyCode)}</span></div>
-          </div>
-        </CardContent>
-      </Card>
-
-      {/* Notes */}
-      {quote.notes && (
-        <Card className="border-0 shadow-sm">
-          <CardHeader><CardTitle className="text-base">Internal Notes</CardTitle></CardHeader>
-          <CardContent><p className="whitespace-pre-wrap text-sm">{quote.notes}</p></CardContent>
-        </Card>
-      )}
-
-      {/* Email Quote Dialog */}
-      <SendEmailDialog
-        open={showEmailDialog}
-        onOpenChange={setShowEmailDialog}
-        defaultEmail={quote.customer?.email || ""}
-        entityLabel="Quote"
-        onSend={async (email, message) => {
-          return sendQuoteEmail({ quoteId: quote.id, recipientEmail: email, message });
-        }}
-      />
-
-      {/* Convert to Work Order Dialog */}
-      <Dialog open={showConvertDialog} onOpenChange={setShowConvertDialog}>
-        <DialogContent className="max-w-md">
-          <DialogHeader>
-            <DialogTitle>Convert Quote to Work Order</DialogTitle>
-          </DialogHeader>
-          <div className="space-y-4">
-            <p className="text-sm text-muted-foreground">
-              This will create a new service record (work order) from this quote. Select a vehicle for the work order.
-            </p>
-            <Select value={convertVehicleId} onValueChange={setConvertVehicleId}>
-              <SelectTrigger><SelectValue placeholder="Select vehicle..." /></SelectTrigger>
-              <SelectContent>
-                {vehicles.map((v) => (
-                  <SelectItem key={v.id} value={v.id}>{v.year} {v.make} {v.model}{v.licensePlate ? ` (${v.licensePlate})` : ""}</SelectItem>
-                ))}
-              </SelectContent>
-            </Select>
-            <div className="flex gap-2">
-              <Button onClick={handleConvert} disabled={converting || !convertVehicleId}>
-                {converting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-                Convert
-              </Button>
-              <Button variant="ghost" onClick={() => setShowConvertDialog(false)}>Cancel</Button>
-            </div>
-          </div>
-        </DialogContent>
-      </Dialog>
-    </div>
-  );
-}

+ 4 - 2
src/app/(authenticated)/quotes/new/page.tsx

@@ -24,7 +24,7 @@ export default async function NewQuotePage() {
   return (
     <>
       <PageHeader />
-      <div className="flex flex-1 flex-col gap-4 p-4 pt-0">
+      <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
         <QuoteForm
           currencyCode={currencyCode}
           defaultTaxRate={defaultTaxRate}
@@ -37,12 +37,14 @@ export default async function NewQuotePage() {
             email: c.email,
             company: c.company,
           }))}
-          vehicles={vehicles.map((v: { id: string; make: string; model: string; year: number; licensePlate: string | null }) => ({
+          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,
           }))}
         />
       </div>

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

@@ -143,13 +143,13 @@ export function QuotesClient({
         <Table>
           <TableHeader>
             <TableRow>
-              <TableHead className="w-[100px]">Quote #</TableHead>
+              <TableHead className="w-25">Quote #</TableHead>
               <TableHead>Title</TableHead>
               <TableHead className="hidden md:table-cell">Customer</TableHead>
               <TableHead className="hidden lg:table-cell">Vehicle</TableHead>
-              <TableHead className="w-[110px]">Status</TableHead>
-              <TableHead className="w-[90px]">Date</TableHead>
-              <TableHead className="w-[90px] text-right">Total</TableHead>
+              <TableHead className="w-27.5">Status</TableHead>
+              <TableHead className="w-22.5">Date</TableHead>
+              <TableHead className="w-22.5 text-right">Total</TableHead>
             </TableRow>
           </TableHeader>
           <TableBody>

+ 2 - 2
src/app/(authenticated)/settings/settings-nav.tsx

@@ -66,9 +66,9 @@ const settingsNav: SettingsNavItem[] = [
   },
   {
     title: "Templates",
-    href: "/settings/invoice-template",
+    href: "/settings/templates",
     icon: Layout,
-    description: "Invoice styling & colors",
+    description: "Invoice & quote styling",
     gate: "customTemplates",
   },
   {

+ 12 - 4
src/app/(authenticated)/settings/invoice-template/page.tsx → src/app/(authenticated)/settings/templates/page.tsx

@@ -6,7 +6,7 @@ import { getFeatures, isCloudMode } from "@/lib/features";
 import { FeatureLockedMessage } from "../feature-locked-message";
 import { redirect } from "next/navigation";
 
-export default async function InvoiceTemplatePage() {
+export default async function TemplatePage() {
   const data = await getLayoutData();
 
   if (data.status === "unauthenticated") redirect("/auth/sign-in");
@@ -17,8 +17,8 @@ export default async function InvoiceTemplatePage() {
   if (!features.customTemplates) {
     return (
       <FeatureLockedMessage
-        feature="Invoice Templates"
-        description="Choose from pre-built invoice templates and customize colors, fonts, and header layouts for your PDF invoices and quotes."
+        feature="Templates"
+        description="Choose from pre-built templates and customize colors, fonts, and header layouts for your PDF invoices and quotes."
         isCloud={isCloudMode()}
       />
     );
@@ -28,17 +28,25 @@ export default async function InvoiceTemplatePage() {
     SETTING_KEYS.INVOICE_PRIMARY_COLOR,
     SETTING_KEYS.INVOICE_FONT_FAMILY,
     SETTING_KEYS.INVOICE_HEADER_STYLE,
+    SETTING_KEYS.QUOTE_PRIMARY_COLOR,
+    SETTING_KEYS.QUOTE_FONT_FAMILY,
+    SETTING_KEYS.QUOTE_HEADER_STYLE,
   ]);
 
   const settings = result.success && result.data ? result.data : {};
 
   return (
     <TemplateSettings
-      initialValues={{
+      initialInvoiceValues={{
         primaryColor: settings[SETTING_KEYS.INVOICE_PRIMARY_COLOR] || "#d97706",
         fontFamily: settings[SETTING_KEYS.INVOICE_FONT_FAMILY] || "Helvetica",
         headerStyle: settings[SETTING_KEYS.INVOICE_HEADER_STYLE] || "standard",
       }}
+      initialQuoteValues={{
+        primaryColor: settings[SETTING_KEYS.QUOTE_PRIMARY_COLOR] || "#d97706",
+        fontFamily: settings[SETTING_KEYS.QUOTE_FONT_FAMILY] || "Helvetica",
+        headerStyle: settings[SETTING_KEYS.QUOTE_HEADER_STYLE] || "standard",
+      }}
     />
   );
 }

+ 125 - 49
src/app/(authenticated)/settings/invoice-template/template-settings.tsx → src/app/(authenticated)/settings/templates/template-settings.tsx

@@ -18,6 +18,7 @@ import { SETTING_KEYS } from "@/features/settings/Schema/settingsSchema";
 import { templatePresets } from "@/features/settings/Schema/templatePresets";
 import { Check, Loader2, Palette } from "lucide-react";
 import { ReadOnlyBanner, SaveButton, ReadOnlyWrapper } from "../read-only-guard";
+import { cn } from "@/lib/utils";
 
 interface TemplateValues {
   primaryColor: string;
@@ -25,6 +26,8 @@ interface TemplateValues {
   headerStyle: string;
 }
 
+type TabType = "invoice" | "quotation";
+
 const fontMap: Record<string, string> = {
   Helvetica: "Helvetica, Arial, sans-serif",
   "Times-Roman": "'Times New Roman', Times, serif",
@@ -46,12 +49,15 @@ function PreviewHeader({
   values,
   headerStyle,
   fontFamily,
+  documentLabel,
 }: {
   values: TemplateValues;
   headerStyle: string;
   fontFamily: string;
+  documentLabel: string;
 }) {
   const style = { fontFamily: fontMap[fontFamily] || "sans-serif" };
+  const docNumber = documentLabel === "QUOTE" ? "QT-1001" : "INV-1001";
 
   if (headerStyle === "compact") {
     return (
@@ -75,8 +81,8 @@ function PreviewHeader({
             </div>
           </div>
           <div className="text-right">
-            <p className="text-sm font-bold">INVOICE</p>
-            <p className="text-[9px] text-gray-500">INV-1001</p>
+            <p className="text-sm font-bold">{documentLabel}</p>
+            <p className="text-[9px] text-gray-500">{docNumber}</p>
           </div>
         </div>
       </div>
@@ -98,9 +104,9 @@ function PreviewHeader({
           </div>
         </div>
         <div className="mt-2 flex items-center justify-between">
-          <p className="text-sm font-bold">INVOICE</p>
+          <p className="text-sm font-bold">{documentLabel}</p>
           <div className="flex gap-3 text-[9px] text-gray-500">
-            <span>INV-1001</span>
+            <span>{docNumber}</span>
             <span>Jan 15, 2026</span>
           </div>
         </div>
@@ -130,9 +136,9 @@ function PreviewHeader({
         </div>
         <div className="text-right">
           <p className="text-lg font-bold tracking-tight" style={{ color: values.primaryColor }}>
-            INVOICE
+            {documentLabel}
           </p>
-          <p className="text-[9px] text-gray-500">INV-1001</p>
+          <p className="text-[9px] text-gray-500">{docNumber}</p>
           <p className="text-[9px] text-gray-500">Jan 15, 2026</p>
         </div>
       </div>
@@ -140,28 +146,23 @@ function PreviewHeader({
   );
 }
 
-export function TemplateSettings({
-  initialValues,
+function TemplateTab({
+  values,
+  setValues,
+  documentLabel,
+  billToLabel,
 }: {
-  initialValues: TemplateValues;
+  values: TemplateValues;
+  setValues: (v: TemplateValues) => void;
+  documentLabel: string;
+  billToLabel: string;
 }) {
-  const [saving, setSaving] = useState(false);
-  const [values, setValues] = useState(initialValues);
-
-  const handleSave = async () => {
-    setSaving(true);
-    try {
-      await Promise.all([
-        setSetting(SETTING_KEYS.INVOICE_PRIMARY_COLOR, values.primaryColor),
-        setSetting(SETTING_KEYS.INVOICE_FONT_FAMILY, values.fontFamily),
-        setSetting(SETTING_KEYS.INVOICE_HEADER_STYLE, values.headerStyle),
-      ]);
-      toast.success("Template settings saved");
-    } catch {
-      toast.error("Failed to save settings");
-    }
-    setSaving(false);
-  };
+  const currentPresetId = templatePresets.find(
+    (p) =>
+      p.primaryColor === values.primaryColor &&
+      p.fontFamily === values.fontFamily &&
+      p.headerStyle === values.headerStyle
+  )?.id;
 
   const applyPreset = (presetId: string) => {
     const preset = templatePresets.find((p) => p.id === presetId);
@@ -174,25 +175,8 @@ export function TemplateSettings({
     }
   };
 
-  const currentPresetId = templatePresets.find(
-    (p) =>
-      p.primaryColor === values.primaryColor &&
-      p.fontFamily === values.fontFamily &&
-      p.headerStyle === values.headerStyle
-  )?.id;
-
   return (
-    <div className="space-y-6">
-      <ReadOnlyBanner />
-      <div>
-        <h2 className="text-lg font-semibold">Invoice Template</h2>
-        <p className="text-sm text-muted-foreground">
-          Choose a template preset or customize the appearance of your PDF invoices and quotes.
-        </p>
-      </div>
-
-      <ReadOnlyWrapper>
-
+    <>
       {/* Template Gallery */}
       <Card className="border-0 shadow-sm">
         <CardHeader>
@@ -354,15 +338,14 @@ export function TemplateSettings({
                 </SelectContent>
               </Select>
             </div>
-
           </CardContent>
         </Card>
       </div>
 
-      {/* Invoice Preview */}
+      {/* Preview */}
       <Card className="border-0 shadow-sm">
         <CardHeader>
-          <CardTitle className="text-base">Invoice Preview</CardTitle>
+          <CardTitle className="text-base">{documentLabel} Preview</CardTitle>
         </CardHeader>
         <CardContent>
           <div
@@ -373,13 +356,14 @@ export function TemplateSettings({
               values={values}
               headerStyle={values.headerStyle}
               fontFamily={values.fontFamily}
+              documentLabel={documentLabel === "Quotation" ? "QUOTE" : "INVOICE"}
             />
 
             {/* Bill To / Vehicle */}
             <div className="my-4 grid grid-cols-2 gap-4">
               <div>
                 <p className="mb-1 text-[10px] font-semibold uppercase tracking-wider" style={{ color: values.primaryColor }}>
-                  Bill To
+                  {billToLabel}
                 </p>
                 <p className="text-sm font-medium">John Smith</p>
                 <p className="text-xs text-gray-500">john@example.com</p>
@@ -462,14 +446,106 @@ export function TemplateSettings({
           </div>
         </CardContent>
       </Card>
+    </>
+  );
+}
 
+export function TemplateSettings({
+  initialInvoiceValues,
+  initialQuoteValues,
+}: {
+  initialInvoiceValues: TemplateValues;
+  initialQuoteValues: TemplateValues;
+}) {
+  const [tab, setTab] = useState<TabType>("invoice");
+  const [saving, setSaving] = useState(false);
+  const [invoiceValues, setInvoiceValues] = useState(initialInvoiceValues);
+  const [quoteValues, setQuoteValues] = useState(initialQuoteValues);
+
+  const handleSave = async () => {
+    setSaving(true);
+    try {
+      if (tab === "invoice") {
+        await Promise.all([
+          setSetting(SETTING_KEYS.INVOICE_PRIMARY_COLOR, invoiceValues.primaryColor),
+          setSetting(SETTING_KEYS.INVOICE_FONT_FAMILY, invoiceValues.fontFamily),
+          setSetting(SETTING_KEYS.INVOICE_HEADER_STYLE, invoiceValues.headerStyle),
+        ]);
+      } else {
+        await Promise.all([
+          setSetting(SETTING_KEYS.QUOTE_PRIMARY_COLOR, quoteValues.primaryColor),
+          setSetting(SETTING_KEYS.QUOTE_FONT_FAMILY, quoteValues.fontFamily),
+          setSetting(SETTING_KEYS.QUOTE_HEADER_STYLE, quoteValues.headerStyle),
+        ]);
+      }
+      toast.success(`${tab === "invoice" ? "Invoice" : "Quotation"} template settings saved`);
+    } catch {
+      toast.error("Failed to save settings");
+    }
+    setSaving(false);
+  };
+
+  return (
+    <div className="space-y-6">
+      <ReadOnlyBanner />
+      <div>
+        <h2 className="text-lg font-semibold">Templates</h2>
+        <p className="text-sm text-muted-foreground">
+          Customize the appearance of your PDF invoices and quotes.
+        </p>
+      </div>
+
+      {/* Tab Buttons */}
+      <div className="flex gap-1 rounded-lg border bg-muted p-1">
+        <button
+          type="button"
+          onClick={() => setTab("invoice")}
+          className={cn(
+            "flex-1 rounded-md px-4 py-2 text-sm font-medium transition-colors",
+            tab === "invoice"
+              ? "bg-background text-foreground shadow-sm"
+              : "text-muted-foreground hover:text-foreground"
+          )}
+        >
+          Invoice
+        </button>
+        <button
+          type="button"
+          onClick={() => setTab("quotation")}
+          className={cn(
+            "flex-1 rounded-md px-4 py-2 text-sm font-medium transition-colors",
+            tab === "quotation"
+              ? "bg-background text-foreground shadow-sm"
+              : "text-muted-foreground hover:text-foreground"
+          )}
+        >
+          Quotation
+        </button>
+      </div>
+
+      <ReadOnlyWrapper>
+        {tab === "invoice" ? (
+          <TemplateTab
+            values={invoiceValues}
+            setValues={setInvoiceValues}
+            documentLabel="Invoice"
+            billToLabel="Bill To"
+          />
+        ) : (
+          <TemplateTab
+            values={quoteValues}
+            setValues={setQuoteValues}
+            documentLabel="Quotation"
+            billToLabel="Prepared For"
+          />
+        )}
       </ReadOnlyWrapper>
 
       <SaveButton>
         <div className="flex justify-end">
           <Button onClick={handleSave} disabled={saving}>
             {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-            Save Template Settings
+            Save {tab === "invoice" ? "Invoice" : "Quotation"} Template
           </Button>
         </div>
       </SaveButton>

+ 97 - 38
src/app/(public)/share/invoice/[orgId]/[token]/invoice-view.tsx

@@ -107,6 +107,8 @@ export function InvoiceView({
   dateFormat,
   timezone,
   termsOfSaleUrl,
+  primaryColor = '#d97706',
+  headerStyle = 'standard',
 }: {
   record: InvoiceRecord
   workshop: { name: string; address: string; phone: string; email: string }
@@ -122,6 +124,8 @@ export function InvoiceView({
   dateFormat?: string
   timezone?: string
   termsOfSaleUrl?: string
+  primaryColor?: string
+  headerStyle?: string
 }) {
   const [carouselIndex, setCarouselIndex] = useState<number | null>(null)
   const [paymentAmount, setPaymentAmount] = useState('')
@@ -296,7 +300,8 @@ export function InvoiceView({
         <h1 className="text-2xl font-bold">Invoice</h1>
         <button
           onClick={handleDownloadPDF}
-          className="inline-flex items-center gap-2 rounded-lg bg-amber-600 px-4 py-2 text-sm font-medium text-white hover:bg-amber-700"
+          className="inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white"
+          style={{ backgroundColor: primaryColor }}
         >
           <Download className="h-4 w-4" />
           Download PDF
@@ -456,40 +461,93 @@ export function InvoiceView({
 
       <div className="rounded-xl border bg-white p-6 shadow-sm sm:p-8 dark:bg-gray-900">
         {/* Header */}
-        <div className="flex flex-col gap-4 border-b-2 border-amber-500 pb-6 sm:flex-row sm:items-start sm:justify-between">
-          <div>
-            {showLogo && logoUrl && (
-              <img
-                src={logoUrl}
-                alt={shopName}
-                className="mb-2 max-h-16 max-w-[180px] object-contain object-left"
-              />
-            )}
-            {showCompanyName && (
-              <h2 className="text-xl font-bold text-amber-600 sm:text-2xl">{shopName}</h2>
-            )}
-            {workshop.address && <p className="mt-1 text-sm text-gray-500">{workshop.address}</p>}
-            {workshop.phone && <p className="text-sm text-gray-500">Tel: {workshop.phone}</p>}
-            {workshop.email && <p className="text-sm text-gray-500">{workshop.email}</p>}
-          </div>
-          <div className="sm:text-right">
-            {showTorqvoiceBranding && (
-              <div className="mb-2 inline-flex items-center gap-1.5 rounded-full bg-gray-100 px-2.5 py-1 dark:bg-gray-800">
-                <img src="/torqvoice_app_logo.png" alt="Torqvoice" className="h-4 w-4" />
-                <span className="text-xs font-semibold text-gray-500 dark:text-gray-400">Torqvoice</span>
+        {headerStyle === 'modern' ? (
+          <>
+            <div className="rounded-lg p-6 text-center text-white" style={{ backgroundColor: primaryColor }}>
+              {showLogo && logoUrl && (
+                <img
+                  src={logoUrl}
+                  alt={shopName}
+                  className="mx-auto mb-2 max-h-16 max-w-[180px] object-contain"
+                />
+              )}
+              {showCompanyName && (
+                <h2 className="text-xl font-bold sm:text-2xl">{shopName}</h2>
+              )}
+              {workshop.address && <p className="mt-1 text-sm opacity-80">{workshop.address}</p>}
+              <div className="mt-1 flex flex-wrap justify-center gap-3 text-sm opacity-70">
+                {workshop.phone && <span>Tel: {workshop.phone}</span>}
+                {workshop.email && <span>{workshop.email}</span>}
               </div>
-            )}
-            <h3 className="text-xl font-bold">INVOICE</h3>
-            <p className="mt-1 text-sm text-gray-500">{invoiceNum}</p>
-            <p className="text-sm text-gray-500">{serviceDate}</p>
+            </div>
+            <div className="mt-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
+              <h3 className="text-xl font-bold">INVOICE</h3>
+              <div className="flex gap-3 text-sm text-gray-500">
+                <span>{invoiceNum}</span>
+                <span>{serviceDate}</span>
+              </div>
+            </div>
+          </>
+        ) : headerStyle === 'compact' ? (
+          <div className="flex flex-col gap-4 border-b pb-6 sm:flex-row sm:items-center sm:justify-between" style={{ borderColor: '#e5e7eb' }}>
+            <div className="flex items-center gap-3">
+              {showLogo && logoUrl && (
+                <img
+                  src={logoUrl}
+                  alt={shopName}
+                  className="h-12 w-12 rounded object-contain"
+                />
+              )}
+              <div>
+                {showCompanyName && (
+                  <h2 className="text-lg font-bold" style={{ color: primaryColor }}>{shopName}</h2>
+                )}
+                {workshop.address && <p className="text-sm text-gray-500">{workshop.address}</p>}
+              </div>
+            </div>
+            <div className="sm:text-right">
+              <h3 className="text-lg font-bold">INVOICE</h3>
+              <p className="text-sm text-gray-500">{invoiceNum}</p>
+              <p className="text-sm text-gray-500">{serviceDate}</p>
+            </div>
           </div>
-        </div>
+        ) : (
+          /* Standard */
+          <div className="flex flex-col gap-4 border-b-2 pb-6 sm:flex-row sm:items-start sm:justify-between" style={{ borderColor: primaryColor }}>
+            <div>
+              {showLogo && logoUrl && (
+                <img
+                  src={logoUrl}
+                  alt={shopName}
+                  className="mb-2 max-h-16 max-w-[180px] object-contain object-left"
+                />
+              )}
+              {showCompanyName && (
+                <h2 className="text-xl font-bold sm:text-2xl" style={{ color: primaryColor }}>{shopName}</h2>
+              )}
+              {workshop.address && <p className="mt-1 text-sm text-gray-500">{workshop.address}</p>}
+              {workshop.phone && <p className="text-sm text-gray-500">Tel: {workshop.phone}</p>}
+              {workshop.email && <p className="text-sm text-gray-500">{workshop.email}</p>}
+            </div>
+            <div className="sm:text-right">
+              {showTorqvoiceBranding && (
+                <div className="mb-2 inline-flex items-center gap-1.5 rounded-full bg-gray-100 px-2.5 py-1 dark:bg-gray-800">
+                  <img src="/torqvoice_app_logo.png" alt="Torqvoice" className="h-4 w-4" />
+                  <span className="text-xs font-semibold text-gray-500 dark:text-gray-400">Torqvoice</span>
+                </div>
+              )}
+              <h3 className="text-xl font-bold" style={{ color: primaryColor }}>INVOICE</h3>
+              <p className="mt-1 text-sm text-gray-500">{invoiceNum}</p>
+              <p className="text-sm text-gray-500">{serviceDate}</p>
+            </div>
+          </div>
+        )}
 
         {/* Info Boxes */}
         <div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
           {record.vehicle.customer && (
             <div className="rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
-              <p className="mb-1 text-xs font-bold uppercase text-amber-600">Bill To</p>
+              <p className="mb-1 text-xs font-bold uppercase" style={{ color: primaryColor }}>Bill To</p>
               <p className="font-semibold">{record.vehicle.customer.name}</p>
               {record.vehicle.customer.company && (
                 <p className="text-sm">{record.vehicle.customer.company}</p>
@@ -506,7 +564,7 @@ export function InvoiceView({
             </div>
           )}
           <div className="rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
-            <p className="mb-1 text-xs font-bold uppercase text-amber-600">Vehicle</p>
+            <p className="mb-1 text-xs font-bold uppercase" style={{ color: primaryColor }}>Vehicle</p>
             <p className="font-semibold">{vehicleName}</p>
             {record.vehicle.vin && (
               <p className="text-sm text-gray-500">VIN: {record.vehicle.vin}</p>
@@ -516,7 +574,7 @@ export function InvoiceView({
             )}
           </div>
           <div className="rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
-            <p className="mb-1 text-xs font-bold uppercase text-amber-600">Service</p>
+            <p className="mb-1 text-xs font-bold uppercase" style={{ color: primaryColor }}>Service</p>
             <p className="font-semibold">{record.title}</p>
             <p className="text-sm text-gray-500">Type: {record.type}</p>
             {record.techName && <p className="text-sm text-gray-500">Tech: {record.techName}</p>}
@@ -530,7 +588,7 @@ export function InvoiceView({
             <div className="-mx-6 overflow-x-auto px-6 sm:mx-0 sm:px-0">
               <table className="w-full min-w-125 text-sm">
                 <thead>
-                  <tr className="border-b bg-amber-50 text-left dark:bg-amber-900/20">
+                  <tr className="border-b text-left" style={{ backgroundColor: `${primaryColor}15` }}>
                     <th className="p-2 font-medium">Part #</th>
                     <th className="p-2 font-medium">Description</th>
                     <th className="p-2 text-right font-medium">Qty</th>
@@ -565,7 +623,7 @@ export function InvoiceView({
             <div className="-mx-6 overflow-x-auto px-6 sm:mx-0 sm:px-0">
               <table className="w-full min-w-112.5 text-sm">
                 <thead>
-                  <tr className="border-b bg-amber-50 text-left dark:bg-amber-900/20">
+                  <tr className="border-b text-left" style={{ backgroundColor: `${primaryColor}15` }}>
                     <th className="p-2 font-medium">Description</th>
                     <th className="p-2 text-right font-medium">Hours</th>
                     <th className="p-2 text-right font-medium">Rate</th>
@@ -614,13 +672,14 @@ export function InvoiceView({
             </div>
           )}
           <div
-            className={`border-t pt-2 ${totalPaid > 0 ? 'border-gray-200' : 'border-amber-500'}`}
+            className={`border-t pt-2 ${totalPaid > 0 ? 'border-gray-200' : ''}`}
+            style={totalPaid > 0 ? undefined : { borderColor: primaryColor }}
           >
             <div
               className={`flex justify-between ${totalPaid > 0 ? 'text-sm text-gray-500' : 'text-lg font-bold'}`}
             >
               <span>Total</span>
-              <span className={totalPaid > 0 ? '' : 'text-amber-600'}>
+              <span style={totalPaid > 0 ? undefined : { color: primaryColor }}>
                 {formatCurrency(displayTotal, currencyCode)}
               </span>
             </div>
@@ -666,8 +725,8 @@ export function InvoiceView({
           (invoiceSettings.bankAccount ||
             invoiceSettings.orgNumber ||
             invoiceSettings.paymentTerms) && (
-            <div className="mt-6 rounded-lg border border-amber-200 bg-amber-50/50 p-4 dark:border-amber-800 dark:bg-amber-900/10">
-              <p className="mb-2 text-xs font-bold uppercase text-amber-600">Payment Information</p>
+            <div className="mt-6 rounded-lg border p-4" style={{ borderColor: `${primaryColor}40`, backgroundColor: `${primaryColor}08` }}>
+              <p className="mb-2 text-xs font-bold uppercase" style={{ color: primaryColor }}>Payment Information</p>
               <div className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
                 {invoiceSettings.showBankAccount && invoiceSettings.bankAccount && (
                   <div>
@@ -812,7 +871,7 @@ export function InvoiceView({
         {/* Notes */}
         {record.invoiceNotes && (
           <div className="mt-6 rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
-            <p className="mb-1 text-xs font-bold uppercase text-amber-600">Notes</p>
+            <p className="mb-1 text-xs font-bold uppercase" style={{ color: primaryColor }}>Notes</p>
             <div
               className="notes-content text-sm text-gray-600 dark:text-gray-400"
               dangerouslySetInnerHTML={{ __html: sanitizeHtml(record.invoiceNotes) }}
@@ -821,7 +880,7 @@ export function InvoiceView({
         )}
         {record.diagnosticNotes && (
           <div className="mt-4 rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
-            <p className="mb-1 text-xs font-bold uppercase text-amber-600">Diagnostic Notes</p>
+            <p className="mb-1 text-xs font-bold uppercase" style={{ color: primaryColor }}>Diagnostic Notes</p>
             <div
               className="notes-content text-sm text-gray-600 dark:text-gray-400"
               dangerouslySetInnerHTML={{ __html: sanitizeHtml(record.diagnosticNotes) }}

+ 4 - 0
src/app/(public)/share/invoice/[orgId]/[token]/page.tsx

@@ -81,6 +81,8 @@ export default async function PublicInvoicePage({
             "invoice.dueDays",
             "invoice.showLogo",
             "invoice.showCompanyName",
+            "invoice.primaryColor",
+            "invoice.headerStyle",
             "payment.providersEnabled",
             "payment.termsOfSale",
             "payment.termsOfSaleUrl",
@@ -164,6 +166,8 @@ export default async function PublicInvoicePage({
       dateFormat={settingsMap["workshop.dateFormat"] || undefined}
       timezone={settingsMap["workshop.timezone"] || undefined}
       termsOfSaleUrl={termsOfSaleUrl}
+      primaryColor={settingsMap["invoice.primaryColor"] || "#d97706"}
+      headerStyle={settingsMap["invoice.headerStyle"] || "standard"}
     />
   );
 }

+ 117 - 0
src/app/(public)/share/quote/[orgId]/[token]/page.tsx

@@ -0,0 +1,117 @@
+import { db } from "@/lib/db";
+import { notFound } from "next/navigation";
+import { QuoteView } from "./quote-view";
+import { getFeatures } from "@/lib/features";
+import type { Metadata } from "next";
+
+export const revalidate = 60;
+
+export const metadata: Metadata = {
+  robots: { index: false, follow: false },
+};
+
+export default async function PublicQuotePage({
+  params,
+}: {
+  params: Promise<{ orgId: string; token: string }>;
+}) {
+  const { orgId, token } = await params;
+
+  const quote = await db.quote.findFirst({
+    where: { publicToken: token, organizationId: orgId },
+    include: {
+      partItems: true,
+      laborItems: true,
+      customer: {
+        select: {
+          name: true,
+          email: true,
+          phone: true,
+          address: true,
+          company: true,
+        },
+      },
+      vehicle: {
+        select: {
+          make: true,
+          model: true,
+          year: true,
+          vin: true,
+          licensePlate: true,
+        },
+      },
+    },
+  });
+
+  if (!quote) {
+    notFound();
+  }
+
+  const [settings, org, features] = await Promise.all([
+    db.appSetting.findMany({
+      where: {
+        organizationId: orgId,
+        key: {
+          in: [
+            "workshop.address",
+            "workshop.phone",
+            "workshop.email",
+            "workshop.logo",
+            "workshop.currencyCode",
+            "workshop.dateFormat",
+            "workshop.timezone",
+            "quote.primaryColor",
+            "quote.headerStyle",
+            "invoice.primaryColor",
+            "invoice.headerStyle",
+          ],
+        },
+      },
+    }),
+    db.organization.findUnique({
+      where: { id: orgId },
+      select: { name: true },
+    }),
+    getFeatures(orgId),
+  ]);
+
+  const settingsMap: Record<string, string> = {};
+  for (const s of settings) settingsMap[s.key] = s.value;
+
+  const workshop = {
+    name: org?.name || "",
+    address: settingsMap["workshop.address"] || "",
+    phone: settingsMap["workshop.phone"] || "",
+    email: settingsMap["workshop.email"] || "",
+  };
+
+  const currencyCode = settingsMap["workshop.currencyCode"] || "USD";
+
+  // Rewrite logo URL for public access
+  const rawLogoUrl = settingsMap["workshop.logo"] || "";
+  let logoUrl = "";
+  if (rawLogoUrl) {
+    const match = rawLogoUrl.match(/^\/api\/files\/[^/]+\/(.+)$/);
+    if (match) logoUrl = `/api/files/public/${token}/${match[1]}`;
+    else logoUrl = rawLogoUrl;
+  }
+
+  const primaryColor = settingsMap["quote.primaryColor"] || settingsMap["invoice.primaryColor"] || "#d97706";
+  const headerStyle = settingsMap["quote.headerStyle"] || settingsMap["invoice.headerStyle"] || "standard";
+
+  return (
+    <QuoteView
+      quote={quote}
+      workshop={workshop}
+      currencyCode={currencyCode}
+      orgId={orgId}
+      token={token}
+      logoUrl={logoUrl}
+      showTorqvoiceBranding={!features.brandingRemoved}
+      dateFormat={settingsMap["workshop.dateFormat"] || undefined}
+      timezone={settingsMap["workshop.timezone"] || undefined}
+      primaryColor={primaryColor}
+      headerStyle={headerStyle}
+    />
+  );
+}

+ 394 - 0
src/app/(public)/share/quote/[orgId]/[token]/quote-view.tsx

@@ -0,0 +1,394 @@
+"use client";
+
+import { Download, Loader2 } from "lucide-react";
+import { useState } from "react";
+import { formatCurrency, formatDate as fmtDate, DEFAULT_DATE_FORMAT } from "@/lib/format";
+import { sanitizeHtml } from "@/lib/sanitize-html";
+
+interface QuoteRecord {
+  id: string;
+  quoteNumber: string | null;
+  title: string;
+  description: string | null;
+  status: string;
+  validUntil: Date | null;
+  createdAt: Date;
+  subtotal: number;
+  taxRate: number;
+  taxAmount: number;
+  discountType: string | null;
+  discountValue: number;
+  discountAmount: number;
+  totalAmount: number;
+  notes: string | null;
+  partItems: {
+    partNumber: string | null;
+    name: string;
+    quantity: number;
+    unitPrice: number;
+    total: number;
+  }[];
+  laborItems: {
+    description: string;
+    hours: number;
+    rate: number;
+    total: number;
+  }[];
+  customer: {
+    name: string;
+    email: string | null;
+    phone: string | null;
+    address: string | null;
+    company: string | null;
+  } | null;
+  vehicle: {
+    make: string;
+    model: string;
+    year: number;
+    vin: string | null;
+    licensePlate: string | null;
+  } | null;
+}
+
+const statusLabels: Record<string, string> = {
+  draft: "Draft",
+  sent: "Sent",
+  accepted: "Accepted",
+  rejected: "Rejected",
+  expired: "Expired",
+  converted: "Converted",
+};
+
+export function QuoteView({
+  quote,
+  workshop,
+  currencyCode,
+  orgId,
+  token,
+  logoUrl,
+  showTorqvoiceBranding,
+  dateFormat,
+  timezone,
+  primaryColor = "#d97706",
+  headerStyle = "standard",
+}: {
+  quote: QuoteRecord;
+  workshop: { name: string; address: string; phone: string; email: string };
+  currencyCode: string;
+  orgId: string;
+  token: string;
+  logoUrl?: string;
+  showTorqvoiceBranding?: boolean;
+  dateFormat?: string;
+  timezone?: string;
+  primaryColor?: string;
+  headerStyle?: string;
+}) {
+  const [downloading, setDownloading] = useState(false);
+
+  const quoteNum = quote.quoteNumber || `QT-${quote.id.slice(-8).toUpperCase()}`;
+  const df = dateFormat || DEFAULT_DATE_FORMAT;
+  const tz = timezone || undefined;
+  const createdDate = fmtDate(quote.createdAt, df, tz);
+  const validUntilDate = quote.validUntil ? fmtDate(quote.validUntil, df, tz) : null;
+  const shopName = workshop.name || "Torqvoice";
+
+  const handleDownloadPDF = async () => {
+    setDownloading(true);
+    try {
+      const res = await fetch(`/api/share/quote/${orgId}/${token}/pdf`);
+      if (!res.ok) throw new Error("Failed");
+      const blob = await res.blob();
+      const url = URL.createObjectURL(blob);
+      const a = document.createElement("a");
+      a.href = url;
+      a.download = `${quoteNum}.pdf`;
+      a.click();
+      URL.revokeObjectURL(url);
+    } catch {
+      // silent
+    }
+    setDownloading(false);
+  };
+
+  return (
+    <div className="mx-auto max-w-3xl p-4 sm:p-8">
+      <div className="mb-6 flex items-center justify-between">
+        <h1 className="text-2xl font-bold">Quote</h1>
+        <button
+          onClick={handleDownloadPDF}
+          disabled={downloading}
+          className="inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
+          style={{ backgroundColor: primaryColor }}
+        >
+          {downloading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
+          Download PDF
+        </button>
+      </div>
+
+      <div className="rounded-xl border bg-white p-6 shadow-sm sm:p-8 dark:bg-gray-900">
+        {/* Header */}
+        {headerStyle === "modern" ? (
+          <>
+            <div className="rounded-lg p-6 text-center text-white" style={{ backgroundColor: primaryColor }}>
+              <img
+                src={logoUrl || "/torqvoice_app_logo.png"}
+                alt={shopName}
+                className="mx-auto mb-2 max-h-16 max-w-[180px] object-contain"
+              />
+              <h2 className="text-xl font-bold sm:text-2xl">{shopName}</h2>
+              {workshop.address && <p className="mt-1 text-sm opacity-80">{workshop.address}</p>}
+              <div className="mt-1 flex flex-wrap justify-center gap-3 text-sm opacity-70">
+                {workshop.phone && <span>Tel: {workshop.phone}</span>}
+                {workshop.email && <span>{workshop.email}</span>}
+              </div>
+            </div>
+            <div className="mt-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
+              <div className="flex items-center gap-3">
+                <h3 className="text-xl font-bold">QUOTE</h3>
+                <span className={`inline-block rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${
+                  quote.status === "accepted"
+                    ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400"
+                    : quote.status === "rejected"
+                    ? "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
+                    : "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"
+                }`}>
+                  {statusLabels[quote.status] || quote.status}
+                </span>
+              </div>
+              <div className="flex gap-3 text-sm text-gray-500">
+                <span>{quoteNum}</span>
+                <span>{createdDate}</span>
+                {validUntilDate && <span>Valid until: {validUntilDate}</span>}
+              </div>
+            </div>
+          </>
+        ) : headerStyle === "compact" ? (
+          <div className="flex flex-col gap-4 border-b pb-6 sm:flex-row sm:items-center sm:justify-between" style={{ borderColor: "#e5e7eb" }}>
+            <div className="flex items-center gap-3">
+              <img
+                src={logoUrl || "/torqvoice_app_logo.png"}
+                alt={shopName}
+                className="h-12 w-12 rounded object-contain"
+              />
+              <div>
+                <h2 className="text-lg font-bold" style={{ color: primaryColor }}>{shopName}</h2>
+                {workshop.address && <p className="text-sm text-gray-500">{workshop.address}</p>}
+              </div>
+            </div>
+            <div className="sm:text-right">
+              <h3 className="text-lg font-bold">QUOTE</h3>
+              <p className="text-sm text-gray-500">{quoteNum}</p>
+              <p className="text-sm text-gray-500">{createdDate}</p>
+              {validUntilDate && (
+                <p className="text-sm text-gray-500">Valid until: {validUntilDate}</p>
+              )}
+              <span className={`mt-1 inline-block rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${
+                quote.status === "accepted"
+                  ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400"
+                  : quote.status === "rejected"
+                  ? "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
+                  : "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"
+              }`}>
+                {statusLabels[quote.status] || quote.status}
+              </span>
+            </div>
+          </div>
+        ) : (
+          /* Standard */
+          <div className="flex flex-col gap-4 border-b-2 pb-6 sm:flex-row sm:items-start sm:justify-between" style={{ borderColor: primaryColor }}>
+            <div>
+              <img
+                src={logoUrl || "/torqvoice_app_logo.png"}
+                alt={shopName}
+                className="mb-2 max-h-16 max-w-[180px] object-contain object-left"
+              />
+              <h2 className="text-xl font-bold sm:text-2xl" style={{ color: primaryColor }}>{shopName}</h2>
+              {workshop.address && <p className="mt-1 text-sm text-gray-500">{workshop.address}</p>}
+              {workshop.phone && <p className="text-sm text-gray-500">Tel: {workshop.phone}</p>}
+              {workshop.email && <p className="text-sm text-gray-500">{workshop.email}</p>}
+            </div>
+            <div className="sm:text-right">
+              {showTorqvoiceBranding && (
+                <div className="mb-2 inline-flex items-center gap-1.5 rounded-full bg-gray-100 px-2.5 py-1 dark:bg-gray-800">
+                  <img src="/torqvoice_app_logo.png" alt="Torqvoice" className="h-4 w-4" />
+                  <span className="text-xs font-semibold text-gray-500 dark:text-gray-400">Torqvoice</span>
+                </div>
+              )}
+              <h3 className="text-xl font-bold" style={{ color: primaryColor }}>QUOTE</h3>
+              <p className="mt-1 text-sm text-gray-500">{quoteNum}</p>
+              <p className="text-sm text-gray-500">{createdDate}</p>
+              {validUntilDate && (
+                <p className="text-sm text-gray-500">Valid until: {validUntilDate}</p>
+              )}
+              <span className={`mt-2 inline-block rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${
+                quote.status === "accepted"
+                  ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400"
+                  : quote.status === "rejected"
+                  ? "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
+                  : "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"
+              }`}>
+                {statusLabels[quote.status] || quote.status}
+              </span>
+            </div>
+          </div>
+        )}
+
+        {/* Info Boxes */}
+        <div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
+          {quote.customer && (
+            <div className="rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
+              <p className="mb-1 text-xs font-bold uppercase" style={{ color: primaryColor }}>Prepared For</p>
+              <p className="font-semibold">{quote.customer.name}</p>
+              {quote.customer.company && <p className="text-sm">{quote.customer.company}</p>}
+              {quote.customer.address && <p className="text-sm text-gray-500">{quote.customer.address}</p>}
+              {quote.customer.email && <p className="text-sm text-gray-500">{quote.customer.email}</p>}
+              {quote.customer.phone && <p className="text-sm text-gray-500">{quote.customer.phone}</p>}
+            </div>
+          )}
+          {quote.vehicle && (
+            <div className="rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
+              <p className="mb-1 text-xs font-bold uppercase" style={{ color: primaryColor }}>Vehicle</p>
+              <p className="font-semibold">{quote.vehicle.year} {quote.vehicle.make} {quote.vehicle.model}</p>
+              {quote.vehicle.vin && <p className="text-sm text-gray-500">VIN: {quote.vehicle.vin}</p>}
+              {quote.vehicle.licensePlate && <p className="text-sm text-gray-500">Plate: {quote.vehicle.licensePlate}</p>}
+            </div>
+          )}
+          <div className="rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
+            <p className="mb-1 text-xs font-bold uppercase" style={{ color: primaryColor }}>Quote Details</p>
+            <p className="font-semibold">{quote.title}</p>
+          </div>
+        </div>
+
+        {/* Description */}
+        {quote.description && (
+          <div className="mt-6 rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
+            <p className="mb-1 text-xs font-bold uppercase" style={{ color: primaryColor }}>Description</p>
+            <div
+              className="notes-content text-sm text-gray-600 dark:text-gray-400"
+              dangerouslySetInnerHTML={{ __html: sanitizeHtml(quote.description) }}
+            />
+          </div>
+        )}
+
+        {/* Parts */}
+        {quote.partItems.length > 0 && (
+          <div className="mt-6">
+            <h4 className="mb-3 font-semibold">Parts</h4>
+            <div className="-mx-6 overflow-x-auto px-6 sm:mx-0 sm:px-0">
+              <table className="w-full min-w-125 text-sm">
+                <thead>
+                  <tr className="border-b text-left" style={{ backgroundColor: `${primaryColor}15` }}>
+                    <th className="p-2 font-medium">Part #</th>
+                    <th className="p-2 font-medium">Description</th>
+                    <th className="p-2 text-right font-medium">Qty</th>
+                    <th className="p-2 text-right font-medium">Unit Price</th>
+                    <th className="p-2 text-right font-medium">Total</th>
+                  </tr>
+                </thead>
+                <tbody className="divide-y">
+                  {quote.partItems.map((p, i) => (
+                    <tr key={i}>
+                      <td className="p-2 font-mono text-xs">{p.partNumber || "-"}</td>
+                      <td className="p-2">{p.name}</td>
+                      <td className="p-2 text-right">{p.quantity}</td>
+                      <td className="p-2 text-right">{formatCurrency(p.unitPrice, currencyCode)}</td>
+                      <td className="p-2 text-right font-medium">{formatCurrency(p.total, currencyCode)}</td>
+                    </tr>
+                  ))}
+                </tbody>
+              </table>
+            </div>
+          </div>
+        )}
+
+        {/* Labor */}
+        {quote.laborItems.length > 0 && (
+          <div className="mt-6">
+            <h4 className="mb-3 font-semibold">Labor</h4>
+            <div className="-mx-6 overflow-x-auto px-6 sm:mx-0 sm:px-0">
+              <table className="w-full min-w-112.5 text-sm">
+                <thead>
+                  <tr className="border-b text-left" style={{ backgroundColor: `${primaryColor}15` }}>
+                    <th className="p-2 font-medium">Description</th>
+                    <th className="p-2 text-right font-medium">Hours</th>
+                    <th className="p-2 text-right font-medium">Rate</th>
+                    <th className="p-2 text-right font-medium">Total</th>
+                  </tr>
+                </thead>
+                <tbody className="divide-y">
+                  {quote.laborItems.map((l, i) => (
+                    <tr key={i}>
+                      <td className="p-2">{l.description}</td>
+                      <td className="p-2 text-right">{l.hours}</td>
+                      <td className="p-2 text-right">{formatCurrency(l.rate, currencyCode)}/hr</td>
+                      <td className="p-2 text-right font-medium">{formatCurrency(l.total, currencyCode)}</td>
+                    </tr>
+                  ))}
+                </tbody>
+              </table>
+            </div>
+          </div>
+        )}
+
+        {/* Totals */}
+        <div className="mt-6 ml-auto max-w-xs space-y-2">
+          {quote.subtotal > 0 && (
+            <div className="flex justify-between text-sm">
+              <span className="text-gray-500">Subtotal</span>
+              <span>{formatCurrency(quote.subtotal, currencyCode)}</span>
+            </div>
+          )}
+          {quote.discountAmount > 0 && (
+            <div className="flex justify-between text-sm">
+              <span className="text-gray-500">
+                Discount{quote.discountType === "percentage" ? ` (${quote.discountValue}%)` : ""}
+              </span>
+              <span className="text-red-500">{formatCurrency(-quote.discountAmount, currencyCode)}</span>
+            </div>
+          )}
+          {quote.taxRate > 0 && (
+            <div className="flex justify-between text-sm">
+              <span className="text-gray-500">Tax ({quote.taxRate}%)</span>
+              <span>{formatCurrency(quote.taxAmount, currencyCode)}</span>
+            </div>
+          )}
+          <div className="border-t pt-2" style={{ borderColor: primaryColor }}>
+            <div className="flex justify-between text-lg font-bold">
+              <span>Total</span>
+              <span style={{ color: primaryColor }}>{formatCurrency(quote.totalAmount, currencyCode)}</span>
+            </div>
+          </div>
+        </div>
+
+        {/* Torqvoice branding near totals */}
+        {showTorqvoiceBranding && (
+          <div className="mt-3 flex items-center justify-end gap-1.5">
+            <span className="text-xs text-gray-400">Powered by</span>
+            <img src="/torqvoice_app_logo.png" alt="Torqvoice" className="h-3.5 w-3.5" />
+            <span className="text-xs font-semibold text-gray-500 dark:text-gray-400">Torqvoice</span>
+          </div>
+        )}
+      </div>
+
+      <div className="mt-4 flex items-center justify-center gap-1.5">
+        {showTorqvoiceBranding ? (
+          <>
+            <span className="text-xs text-gray-400">Powered by</span>
+            <img src="/torqvoice_app_logo.png" alt="Torqvoice" className="h-4 w-4" />
+            <a
+              href="https://torqvoice.com"
+              target="_blank"
+              rel="noopener noreferrer"
+              className="text-xs font-semibold text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
+            >
+              Torqvoice
+            </a>
+          </>
+        ) : (
+          <p className="text-center text-xs text-gray-400">{shopName}</p>
+        )}
+      </div>
+    </div>
+  );
+}

+ 17 - 5
src/app/api/files/public/[token]/[...path]/route.ts

@@ -41,17 +41,29 @@ export async function GET(
     return NextResponse.json({ error: "Invalid filename" }, { status: 400 });
   }
 
-  // Validate token and get org
-  const record = await db.serviceRecord.findUnique({
+  // Validate token and get org (check both invoice and quote tokens)
+  let orgId: string | undefined;
+
+  const serviceRecord = await db.serviceRecord.findUnique({
     where: { publicToken: token },
     select: { vehicle: { select: { organizationId: true } } },
   });
 
-  if (!record || !record.vehicle.organizationId) {
-    return NextResponse.json({ error: "Not found" }, { status: 404 });
+  if (serviceRecord?.vehicle.organizationId) {
+    orgId = serviceRecord.vehicle.organizationId;
+  } else {
+    const quote = await db.quote.findFirst({
+      where: { publicToken: token },
+      select: { organizationId: true },
+    });
+    if (quote?.organizationId) {
+      orgId = quote.organizationId;
+    }
   }
 
-  const orgId = record.vehicle.organizationId;
+  if (!orgId) {
+    return NextResponse.json({ error: "Not found" }, { status: 404 });
+  }
   const filePath = path.join(process.cwd(), "data", "uploads", orgId, category, filename);
 
   try {

+ 3 - 3
src/app/api/quotes/[id]/pdf/route.ts

@@ -68,11 +68,11 @@ export async function GET(
     }
 
     const template = {
-      primaryColor: settingsMap["invoice.primaryColor"] || "#d97706",
-      fontFamily: settingsMap["invoice.fontFamily"] || "Helvetica",
+      primaryColor: settingsMap["quote.primaryColor"] || settingsMap["invoice.primaryColor"] || "#d97706",
+      fontFamily: settingsMap["quote.fontFamily"] || settingsMap["invoice.fontFamily"] || "Helvetica",
       showLogo: settingsMap["invoice.showLogo"] !== "false",
       showCompanyName: settingsMap["invoice.showCompanyName"] !== "false",
-      headerStyle: settingsMap["invoice.headerStyle"] || "standard",
+      headerStyle: settingsMap["quote.headerStyle"] || settingsMap["invoice.headerStyle"] || "standard",
     };
 
     const element = React.createElement(QuotePDF, {

+ 122 - 0
src/app/api/share/quote/[orgId]/[token]/pdf/route.ts

@@ -0,0 +1,122 @@
+import { NextResponse } from "next/server";
+import { renderToBuffer } from "@react-pdf/renderer";
+import { db } from "@/lib/db";
+import { QuotePDF } from "@/features/quotes/Components/QuotePDF";
+import React from "react";
+import { readFile } from "fs/promises";
+import { resolveUploadPath } from "@/lib/resolve-upload-path";
+import { getFeatures } from "@/lib/features";
+import { getTorqvoiceLogoDataUri } from "@/lib/torqvoice-branding";
+
+export async function GET(
+  _request: Request,
+  { params }: { params: Promise<{ orgId: string; token: string }> }
+) {
+  try {
+    const { orgId, token } = await params;
+
+    const quote = await db.quote.findFirst({
+      where: { publicToken: token, organizationId: orgId },
+      include: {
+        partItems: true,
+        laborItems: true,
+        customer: {
+          select: { name: true, email: true, phone: true, address: true, company: true },
+        },
+        vehicle: {
+          select: { make: true, model: true, year: true, vin: true, licensePlate: true },
+        },
+      },
+    });
+
+    if (!quote) {
+      return NextResponse.json({ error: "Quote not found" }, { status: 404 });
+    }
+
+    const [settings, org] = await Promise.all([
+      db.appSetting.findMany({ where: { organizationId: orgId } }),
+      db.organization.findUnique({
+        where: { id: orgId },
+        select: { name: true },
+      }),
+    ]);
+
+    const settingsMap: Record<string, string> = {};
+    for (const s of settings) settingsMap[s.key] = s.value;
+
+    let logoDataUri: string | undefined;
+    const logoPath = settingsMap["workshop.logo"];
+    if (logoPath) {
+      try {
+        const fullPath = resolveUploadPath(logoPath);
+        const logoBuffer = await readFile(fullPath);
+        const ext = logoPath.split(".").pop()?.toLowerCase() || "png";
+        const mimeMap: Record<string, string> = {
+          png: "image/png",
+          jpg: "image/jpeg",
+          jpeg: "image/jpeg",
+          webp: "image/webp",
+          svg: "image/svg+xml",
+        };
+        const mime = mimeMap[ext] || "image/png";
+        logoDataUri = `data:${mime};base64,${logoBuffer.toString("base64")}`;
+      } catch {
+        // Skip
+      }
+    }
+
+    const features = await getFeatures(orgId);
+    let torqvoiceLogoDataUri: string | undefined;
+    if (!features.brandingRemoved) {
+      torqvoiceLogoDataUri = await getTorqvoiceLogoDataUri();
+    }
+
+    const template = {
+      primaryColor: settingsMap["quote.primaryColor"] || settingsMap["invoice.primaryColor"] || "#d97706",
+      fontFamily: settingsMap["quote.fontFamily"] || settingsMap["invoice.fontFamily"] || "Helvetica",
+      showLogo: settingsMap["invoice.showLogo"] !== "false",
+      showCompanyName: settingsMap["invoice.showCompanyName"] !== "false",
+      headerStyle: settingsMap["quote.headerStyle"] || settingsMap["invoice.headerStyle"] || "standard",
+    };
+
+    const element = React.createElement(QuotePDF, {
+      data: quote,
+      workshop: {
+        name: org?.name || "",
+        address: settingsMap["workshop.address"] || "",
+        phone: settingsMap["workshop.phone"] || "",
+        email: settingsMap["workshop.email"] || "",
+      },
+      currencyCode: settingsMap["workshop.currencyCode"] || "USD",
+      logoDataUri,
+      torqvoiceLogoDataUri,
+      dateFormat: settingsMap["workshop.dateFormat"] || undefined,
+      timezone: settingsMap["workshop.timezone"] || undefined,
+      template,
+      // eslint-disable-next-line @typescript-eslint/no-explicit-any
+    }) as any;
+    const buffer = await renderToBuffer(element);
+
+    const quoteNum =
+      quote.quoteNumber || `QT-${quote.id.slice(-8).toUpperCase()}`;
+
+    return new NextResponse(
+      buffer.buffer.slice(
+        buffer.byteOffset,
+        buffer.byteOffset + buffer.byteLength
+      ) as ArrayBuffer,
+      {
+        headers: {
+          "Content-Type": "application/pdf",
+          "Content-Disposition": `attachment; filename="${quoteNum}.pdf"`,
+        },
+      }
+    );
+  } catch (error) {
+    console.error("[Public Quote PDF] Error:", error);
+    return NextResponse.json(
+      { error: "Failed to generate PDF" },
+      { status: 500 }
+    );
+  }
+}

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

@@ -56,7 +56,7 @@ const breadcrumbMap: Record<string, BreadcrumbSegment[]> = {
   '/settings/company': [{ label: 'Settings', href: '/settings' }, { label: 'Company' }],
   '/settings/account': [{ label: 'Settings', href: '/settings' }, { label: 'Account' }],
   '/settings/custom-fields': [{ label: 'Settings', href: '/settings' }, { label: 'Custom Fields' }],
-  '/settings/invoice-template': [{ label: 'Settings', href: '/settings' }, { label: 'Templates' }],
+  '/settings/templates': [{ label: 'Settings', href: '/settings' }, { label: 'Templates' }],
   '/settings/team': [{ label: 'Settings', href: '/settings' }, { label: 'Team' }],
   '/settings/invoice': [{ label: 'Settings', href: '/settings' }, { label: 'Invoice' }],
   '/settings/payment': [{ label: 'Settings', href: '/settings' }, { label: 'Payment' }],

+ 34 - 16
src/features/billing/Actions/billingActions.ts

@@ -27,13 +27,14 @@ async function getBillingSummary(organizationId: string): Promise<BillingSummary
     SELECT
       COALESCE(SUM(CASE WHEN sub.total > 0 THEN sub.total ELSE sub.cost END), 0) AS total_revenue,
       COALESCE(SUM(sub.paid), 0) AS total_paid,
-      COUNT(*) FILTER (WHERE sub.paid >= (CASE WHEN sub.total > 0 THEN sub.total ELSE sub.cost END) AND (CASE WHEN sub.total > 0 THEN sub.total ELSE sub.cost END) > 0) AS paid_count,
-      COUNT(*) FILTER (WHERE sub.paid > 0 AND sub.paid < (CASE WHEN sub.total > 0 THEN sub.total ELSE sub.cost END)) AS partial_count,
-      COUNT(*) FILTER (WHERE sub.paid = 0) AS unpaid_count
+      COUNT(*) FILTER (WHERE sub."manuallyPaid" = true OR (sub.paid >= (CASE WHEN sub.total > 0 THEN sub.total ELSE sub.cost END) AND (CASE WHEN sub.total > 0 THEN sub.total ELSE sub.cost END) > 0)) AS paid_count,
+      COUNT(*) FILTER (WHERE sub."manuallyPaid" = false AND sub.paid > 0 AND sub.paid < (CASE WHEN sub.total > 0 THEN sub.total ELSE sub.cost END)) AS partial_count,
+      COUNT(*) FILTER (WHERE sub."manuallyPaid" = false AND sub.paid = 0) AS unpaid_count
     FROM (
       SELECT
         sr."totalAmount" AS total,
         sr.cost,
+        sr."manuallyPaid",
         CASE WHEN sr."manuallyPaid" = true
           THEN CASE WHEN sr."totalAmount" > 0 THEN sr."totalAmount" ELSE sr.cost END
           ELSE COALESCE((SELECT SUM(p.amount) FROM payments p WHERE p."serviceRecordId" = sr.id), 0)
@@ -97,17 +98,18 @@ export async function getBillingHistory(params: {
 
       let statusCondition: Prisma.Sql;
       if (params.status === "paid") {
-        statusCondition = Prisma.sql`AND paid_amount >= effective_total AND effective_total > 0`;
+        statusCondition = Prisma.sql`AND (manually_paid = true OR (paid_amount >= effective_total AND effective_total > 0))`;
       } else if (params.status === "partial") {
-        statusCondition = Prisma.sql`AND paid_amount > 0 AND paid_amount < effective_total`;
+        statusCondition = Prisma.sql`AND manually_paid = false AND paid_amount > 0 AND paid_amount < effective_total`;
       } else {
-        statusCondition = Prisma.sql`AND paid_amount = 0`;
+        statusCondition = Prisma.sql`AND manually_paid = false AND paid_amount = 0`;
       }
 
       const countRows = await db.$queryRaw<{ cnt: bigint }[]>(Prisma.sql`
         SELECT COUNT(*) AS cnt FROM (
           SELECT
             sr.id,
+            sr."manuallyPaid" AS manually_paid,
             CASE WHEN sr."totalAmount" > 0 THEN sr."totalAmount" ELSE sr.cost END AS effective_total,
             CASE WHEN sr."manuallyPaid" = true
               THEN CASE WHEN sr."totalAmount" > 0 THEN sr."totalAmount" ELSE sr.cost END
@@ -131,7 +133,7 @@ export async function getBillingHistory(params: {
           serviceDate: Date;
           effective_total: number;
           paid_amount: number;
-          status: string;
+          manually_paid: boolean;
           vehicle_id: string;
           vehicle_make: string | null;
           vehicle_model: string | null;
@@ -148,7 +150,7 @@ export async function getBillingHistory(params: {
           sub."serviceDate",
           sub.effective_total,
           sub.paid_amount,
-          sub.status,
+          sub.manually_paid,
           sub.vehicle_id,
           sub.vehicle_make,
           sub.vehicle_model,
@@ -162,7 +164,7 @@ export async function getBillingHistory(params: {
             sr.title,
             sr."invoiceNumber",
             sr."serviceDate",
-            sr.status,
+            sr."manuallyPaid" AS manually_paid,
             CASE WHEN sr."totalAmount" > 0 THEN sr."totalAmount" ELSE sr.cost END AS effective_total,
             CASE WHEN sr."manuallyPaid" = true
               THEN CASE WHEN sr."totalAmount" > 0 THEN sr."totalAmount" ELSE sr.cost END
@@ -187,14 +189,23 @@ export async function getBillingHistory(params: {
       `);
 
       return {
-        records: rows.map((r) => ({
+        records: rows.map((r) => {
+          const effectiveTotal = Number(r.effective_total);
+          const paidAmount = Number(r.paid_amount);
+          const manuallyPaid = r.manually_paid;
+          const paymentStatus = manuallyPaid || (paidAmount >= effectiveTotal && effectiveTotal > 0)
+            ? "paid"
+            : paidAmount > 0
+              ? "partial"
+              : "unpaid";
+          return {
           id: r.id,
           title: r.title || "",
           invoiceNumber: r.invoiceNumber,
           serviceDate: r.serviceDate,
-          totalAmount: Number(r.effective_total),
-          totalPaid: Number(r.paid_amount),
-          status: r.status,
+          totalAmount: effectiveTotal,
+          totalPaid: paidAmount,
+          status: paymentStatus,
           vehicle: {
             id: r.vehicle_id,
             make: r.vehicle_make || "",
@@ -203,7 +214,8 @@ export async function getBillingHistory(params: {
             licensePlate: r.vehicle_license_plate,
             customer: r.customer_id ? { id: r.customer_id, name: r.customer_name || "" } : null,
           },
-        })),
+        };
+        }),
         total,
         page,
         pageSize,
@@ -239,7 +251,13 @@ export async function getBillingHistory(params: {
     return {
       records: records.map((r) => {
         const effectiveTotal = r.totalAmount > 0 ? r.totalAmount : r.cost;
-        const totalPaid = r.manuallyPaid ? effectiveTotal : r.payments.reduce((s, p) => s + p.amount, 0);
+        const paidFromPayments = r.payments.reduce((s, p) => s + p.amount, 0);
+        const totalPaid = r.manuallyPaid ? effectiveTotal : paidFromPayments;
+        const paymentStatus = r.manuallyPaid || (totalPaid >= effectiveTotal && effectiveTotal > 0)
+          ? "paid"
+          : totalPaid > 0
+            ? "partial"
+            : "unpaid";
         return {
           id: r.id,
           title: r.title,
@@ -247,7 +265,7 @@ export async function getBillingHistory(params: {
           serviceDate: r.serviceDate,
           totalAmount: effectiveTotal,
           totalPaid,
-          status: r.status,
+          status: paymentStatus,
           vehicle: r.vehicle,
         };
       }),

+ 42 - 0
src/features/quotes/Actions/quoteShareActions.ts

@@ -0,0 +1,42 @@
+"use server";
+
+import { randomUUID } from "crypto";
+import { db } from "@/lib/db";
+import { withAuth } from "@/lib/with-auth";
+import { revalidatePath } from "next/cache";
+import { PermissionAction, PermissionSubject } from "@/lib/permissions";
+
+export async function generateQuotePublicLink(quoteId: string) {
+  return withAuth(async ({ organizationId }) => {
+    const quote = await db.quote.findFirst({
+      where: { id: quoteId, organizationId },
+    });
+    if (!quote) throw new Error("Quote not found");
+
+    const token = randomUUID();
+    await db.quote.update({
+      where: { id: quoteId },
+      data: { publicToken: token },
+    });
+
+    revalidatePath(`/quotes/${quoteId}`);
+    return { token, organizationId };
+  }, { requiredPermissions: [{ action: PermissionAction.UPDATE, subject: PermissionSubject.QUOTES }] });
+}
+
+export async function revokeQuotePublicLink(quoteId: string) {
+  return withAuth(async ({ organizationId }) => {
+    const quote = await db.quote.findFirst({
+      where: { id: quoteId, organizationId },
+    });
+    if (!quote) throw new Error("Quote not found");
+
+    await db.quote.update({
+      where: { id: quoteId },
+      data: { publicToken: null },
+    });
+
+    revalidatePath(`/quotes/${quoteId}`);
+    return { revoked: true };
+  }, { requiredPermissions: [{ action: PermissionAction.UPDATE, subject: PermissionSubject.QUOTES }] });
+}

+ 371 - 232
src/features/quotes/Components/QuoteForm.tsx

@@ -1,14 +1,12 @@
 "use client";
 
-import { useState, useCallback } from "react";
+import { useState, useCallback, useEffect } from "react";
 import { useRouter } from "next/navigation";
 import { toast } from "sonner";
 import Link from "next/link";
 import { Button } from "@/components/ui/button";
 import { Input } from "@/components/ui/input";
 import { Label } from "@/components/ui/label";
-import { Textarea } from "@/components/ui/textarea";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
 import {
   Select,
   SelectContent,
@@ -16,10 +14,16 @@ import {
   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 { ArrowLeft, Loader2, Plus, Trash2 } from "lucide-react";
+import { RichTextEditor } from "@/features/vehicles/Components/service-edit/RichTextEditor";
+import { ArrowLeft, Car, FileText, Loader2, Plus, Save, Trash2, Users, X } from "lucide-react";
 import { formatCurrency, getCurrencySymbol } from "@/lib/format";
 
 interface CustomerOption {
@@ -35,6 +39,8 @@ interface VehicleOption {
   model: string;
   year: number;
   licensePlate: string | null;
+  customerId: string | null;
+  customerName: string | null;
 }
 
 interface InitialData {
@@ -72,6 +78,20 @@ const makeEmptyLabor = (defaultRate: number): QuoteLaborInput => ({
   total: 0,
 });
 
+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;
+}
+
 export function QuoteForm({
   currencyCode = "USD",
   defaultTaxRate = 0,
@@ -95,6 +115,7 @@ export function QuoteForm({
   const isEdit = !!initialData;
   const router = useRouter();
   const modal = useGlassModal();
+  const isLarge = useIsLargeScreen();
   const [loading, setLoading] = useState(false);
   const [status, setStatus] = useState(initialData?.status || "draft");
   const [customerId, setCustomerId] = useState(initialData?.customerId || "");
@@ -104,6 +125,9 @@ export function QuoteForm({
   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
@@ -122,6 +146,20 @@ export function QuoteForm({
   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) => {
     setPartItems((prev) => {
       const updated = [...prev];
@@ -153,12 +191,12 @@ export function QuoteForm({
     const formData = new FormData(e.currentTarget);
     const payload = {
       title: formData.get("title") as string,
-      description: (formData.get("description") as string) || undefined,
+      description: description || undefined,
       status,
       validUntil: (formData.get("validUntil") as string) || undefined,
       customerId: customerId || undefined,
       vehicleId: vehicleId || undefined,
-      notes: (formData.get("notes") as string) || undefined,
+      notes: notes || undefined,
       partItems: partItems.filter((p) => p.name),
       laborItems: laborItems.filter((l) => l.description),
       subtotal,
@@ -184,247 +222,348 @@ export function QuoteForm({
     setLoading(false);
   };
 
-  return (
-    <div className="space-y-6">
-      <div>
-        <Link
-          href="/quotes"
-          className="mb-4 inline-flex items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-foreground"
-        >
-          <ArrowLeft className="h-4 w-4" />
-          Back to Quotes
-        </Link>
-        <h1 className="text-2xl font-bold">{isEdit ? "Edit Quote" : "New Quote"}</h1>
+  // --- 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">Parts</h3>
+          <Button type="button" variant="outline" size="sm" onClick={() => setPartItems([...partItems, emptyPart()])}>
+            <Plus className="mr-1 h-3.5 w-3.5" /> Add Part
+          </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>Part #</span><span>Name</span><span>Qty</span><span>Unit Price</span><span>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]">
+                <Input placeholder="Part #" value={part.partNumber ?? ""} onChange={(e) => updatePart(i, "partNumber", e.target.value)} />
+                <Input placeholder="Name *" 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", Number(e.target.value))} />
+                <Input type="number" min="0" step="0.01" value={part.unitPrice} onChange={(e) => updatePart(i, "unitPrice", Number(e.target.value))} />
+                <div className="flex items-center rounded-md bg-muted/50 px-3 text-sm font-medium">{formatCurrency(part.total, currencyCode)}</div>
+                <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>
+            ))}
+            <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">Parts Subtotal: {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">Add Part</span>
+          </button>
+        )}
       </div>
 
-      <form onSubmit={handleSubmit} className="space-y-6">
-        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
-          {/* Column 1: Basic Info */}
-          <Card className="border-0 shadow-sm">
-            <CardHeader>
-              <CardTitle className="text-base">Quote Details</CardTitle>
-            </CardHeader>
-            <CardContent className="space-y-3">
-              <div className="space-y-2">
-                <Label htmlFor="title">Title *</Label>
-                <Input id="title" name="title" placeholder="Vehicle repair estimate" defaultValue={initialData?.title || ""} required />
-              </div>
-              <div className="space-y-2">
-                <Label>Status</Label>
-                <Select value={status} onValueChange={setStatus}>
-                  <SelectTrigger><SelectValue /></SelectTrigger>
-                  <SelectContent>
-                    <SelectItem value="draft">Draft</SelectItem>
-                    <SelectItem value="sent">Sent</SelectItem>
-                    <SelectItem value="accepted">Accepted</SelectItem>
-                    <SelectItem value="rejected">Rejected</SelectItem>
-                  </SelectContent>
-                </Select>
-              </div>
-              <div className="space-y-2">
-                <Label htmlFor="validUntil">Valid Until</Label>
-                <Input id="validUntil" name="validUntil" type="date" defaultValue={defaultValidDate} />
-              </div>
-              <div className="space-y-2">
-                <Label>Customer</Label>
-                <Select value={customerId || "none"} onValueChange={(v) => setCustomerId(v === "none" ? "" : v)}>
-                  <SelectTrigger><SelectValue placeholder="Select customer..." /></SelectTrigger>
-                  <SelectContent>
-                    <SelectItem value="none">None</SelectItem>
-                    {customers.map((c) => (
-                      <SelectItem key={c.id} value={c.id}>{c.name}{c.company ? ` (${c.company})` : ""}</SelectItem>
-                    ))}
-                  </SelectContent>
-                </Select>
-              </div>
-              <div className="space-y-2">
-                <Label>Vehicle</Label>
-                <Select value={vehicleId || "none"} onValueChange={(v) => setVehicleId(v === "none" ? "" : v)}>
-                  <SelectTrigger><SelectValue placeholder="Select vehicle..." /></SelectTrigger>
-                  <SelectContent>
-                    <SelectItem value="none">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>
+      {/* Labor */}
+      <div className="rounded-lg border p-3 space-y-2">
+        <div className="flex items-center justify-between">
+          <h3 className="text-sm font-semibold">Labor</h3>
+          <Button type="button" variant="outline" size="sm" onClick={() => setLaborItems([...laborItems, makeEmptyLabor(defaultLaborRate)])}>
+            <Plus className="mr-1 h-3.5 w-3.5" /> Add Labor
+          </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>Description</span><span>Hours</span><span>Rate ({cs}/hr)</span><span>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]">
+                <Input placeholder="Description *" 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.5" value={labor.hours} onChange={(e) => updateLabor(i, "hours", Number(e.target.value))} />
+                <Input type="number" min="0" step="0.01" value={labor.rate} onChange={(e) => updateLabor(i, "rate", Number(e.target.value))} />
+                <div className="flex items-center rounded-md bg-muted/50 px-3 text-sm font-medium">{formatCurrency(labor.total, currencyCode)}</div>
+                <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>
-            </CardContent>
-          </Card>
+            ))}
+            <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">Labor Subtotal: {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">Add Labor</span>
+          </button>
+        )}
+      </div>
 
-          {/* Column 2: Notes */}
-          <Card className="border-0 shadow-sm">
-            <CardHeader>
-              <CardTitle className="text-base">Notes</CardTitle>
-            </CardHeader>
-            <CardContent className="space-y-4">
-              <Textarea
-                name="description"
-                placeholder="Quote description..."
-                rows={6}
-                defaultValue={initialData?.description || ""}
-              />
-              <div className="space-y-2">
-                <Label className="text-base font-semibold">Internal Notes</Label>
-                <Textarea
-                  name="notes"
-                  placeholder="Internal notes (not shown to customer)..."
-                  rows={6}
-                  defaultValue={initialData?.notes || ""}
-                />
-              </div>
-            </CardContent>
-          </Card>
+      {/* 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" />
+            Notes
+          </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">Public</SelectItem>
+              <SelectItem value="internal">Internal</SelectItem>
+            </SelectContent>
+          </Select>
+        </div>
+        {noteType === "public" && (
+          <div className="space-y-1">
+            <RichTextEditor
+              content={description}
+              onChange={setDescription}
+              placeholder="Quote description shown to the customer..."
+            />
+            <p className="text-xs text-muted-foreground">Shown on the quote document</p>
+          </div>
+        )}
+        {noteType === "internal" && (
+          <div className="space-y-1">
+            <RichTextEditor
+              content={notes}
+              onChange={setNotes}
+              placeholder="Internal notes (not shown to customer)..."
+            />
+            <p className="text-xs text-muted-foreground">Only visible to your team</p>
+          </div>
+        )}
+      </div>
+    </div>
+  );
 
-          {/* Column 3: Totals */}
-          <Card className="border-0 shadow-sm">
-            <CardHeader>
-              <CardTitle className="text-base">Totals</CardTitle>
-            </CardHeader>
-            <CardContent>
-              <div className="space-y-3">
-                <div className="flex items-center justify-between text-sm">
-                  <span className="text-muted-foreground">Parts</span>
-                  <span>{formatCurrency(partsSubtotal, currencyCode)}</span>
-                </div>
-                <div className="flex items-center justify-between text-sm">
-                  <span className="text-muted-foreground">Labor</span>
-                  <span>{formatCurrency(laborSubtotal, currencyCode)}</span>
-                </div>
-                <div className="flex items-center justify-between text-sm">
-                  <span className="text-muted-foreground">Subtotal</span>
-                  <span className="font-medium">{formatCurrency(subtotal, currencyCode)}</span>
-                </div>
-                <div className="space-y-2">
-                  <div className="flex items-center justify-between text-sm">
-                    <div className="flex items-center gap-2">
-                      <span className="text-muted-foreground">Discount</span>
-                      <Select value={discountType} onValueChange={setDiscountType}>
-                        <SelectTrigger className="h-7 w-28 text-xs"><SelectValue /></SelectTrigger>
-                        <SelectContent>
-                          <SelectItem value="none">None</SelectItem>
-                          <SelectItem value="percentage">Percentage</SelectItem>
-                          <SelectItem value="fixed">Fixed</SelectItem>
-                        </SelectContent>
-                      </Select>
-                      {discountType !== "none" && (
-                        <Input
-                          type="number"
-                          min="0"
-                          step="0.01"
-                          value={discountValue}
-                          onChange={(e) => setDiscountValue(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>
-                </div>
-                {taxEnabled && (
-                  <div className="flex items-center justify-between text-sm">
-                    <div className="flex items-center gap-2">
-                      <span className="text-muted-foreground">Tax</span>
-                      <Input
-                        type="number"
-                        min="0"
-                        step="0.1"
-                        value={taxRate}
-                        onChange={(e) => setTaxRate(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-3 text-lg font-bold">
-                  <span>Total</span>
-                  <span>{formatCurrency(totalAmount, currencyCode)}</span>
-                </div>
-              </div>
-            </CardContent>
-          </Card>
+  // --- 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">Vehicle</Label>
+          <Select value={vehicleId || "none"} onValueChange={handleVehicleChange}>
+            <SelectTrigger><SelectValue placeholder="Select vehicle..." /></SelectTrigger>
+            <SelectContent>
+              <SelectItem value="none">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>
 
-        {/* Parts */}
-        <Card className="border-0 shadow-sm">
-          <CardHeader className="flex flex-row items-center justify-between">
-            <CardTitle className="text-base">Parts</CardTitle>
-            <Button type="button" variant="outline" size="sm" onClick={() => setPartItems([...partItems, emptyPart()])}>
-              <Plus className="mr-1 h-3.5 w-3.5" /> Add Part
+        {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>
-          </CardHeader>
-          <CardContent>
-            {partItems.length === 0 ? (
-              <p className="py-4 text-center text-sm text-muted-foreground">No parts added yet</p>
-            ) : (
-              <div className="space-y-3">
-                <div className="hidden grid-cols-[1fr_2fr_0.7fr_1fr_1fr_auto] gap-2 text-xs font-medium text-muted-foreground sm:grid">
-                  <span>Part #</span><span>Name</span><span>Qty</span><span>Unit Price</span><span>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]">
-                    <Input placeholder="Part #" value={part.partNumber ?? ""} onChange={(e) => updatePart(i, "partNumber", e.target.value)} />
-                    <Input placeholder="Name *" 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", Number(e.target.value))} />
-                    <Input type="number" min="0" step="0.01" value={part.unitPrice} onChange={(e) => updatePart(i, "unitPrice", Number(e.target.value))} />
-                    <div className="flex items-center rounded-md bg-muted/50 px-3 text-sm font-medium">{formatCurrency(part.total, currencyCode)}</div>
-                    <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>
-            )}
-          </CardContent>
-        </Card>
+          </div>
+        )}
 
-        {/* Labor */}
-        <Card className="border-0 shadow-sm">
-          <CardHeader className="flex flex-row items-center justify-between">
-            <CardTitle className="text-base">Labor</CardTitle>
-            <Button type="button" variant="outline" size="sm" onClick={() => setLaborItems([...laborItems, makeEmptyLabor(defaultLaborRate)])}>
-              <Plus className="mr-1 h-3.5 w-3.5" /> Add Labor
+        <div className="space-y-1">
+          <Label className="text-xs">Customer</Label>
+          <Select value={customerId || "none"} onValueChange={(v) => setCustomerId(v === "none" ? "" : v)}>
+            <SelectTrigger><SelectValue placeholder="Select customer..." /></SelectTrigger>
+            <SelectContent>
+              <SelectItem value="none">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>
-          </CardHeader>
-          <CardContent>
-            {laborItems.length === 0 ? (
-              <p className="py-4 text-center text-sm text-muted-foreground">No labor added yet</p>
-            ) : (
-              <div className="space-y-3">
-                <div className="hidden grid-cols-[2fr_1fr_1fr_1fr_auto] gap-2 text-xs font-medium text-muted-foreground sm:grid">
-                  <span>Description</span><span>Hours</span><span>Rate ({cs}/hr)</span><span>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]">
-                    <Input placeholder="Description *" 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.5" value={labor.hours} onChange={(e) => updateLabor(i, "hours", Number(e.target.value))} />
-                    <Input type="number" min="0" step="0.01" value={labor.rate} onChange={(e) => updateLabor(i, "rate", Number(e.target.value))} />
-                    <div className="flex items-center rounded-md bg-muted/50 px-3 text-sm font-medium">{formatCurrency(labor.total, currencyCode)}</div>
-                    <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>
+          </div>
+        )}
+      </div>
+
+      {/* Quote Details */}
+      <div className="rounded-lg border p-3 space-y-3">
+        <h3 className="text-sm font-semibold">Quote Details</h3>
+        <div className="space-y-1">
+          <Label htmlFor="title" className="text-xs">Title *</Label>
+          <Input id="title" name="title" placeholder="Vehicle repair estimate" defaultValue={initialData?.title || ""} required />
+        </div>
+        <div className="grid grid-cols-2 gap-2">
+          <div className="space-y-1">
+            <Label className="text-xs">Status</Label>
+            <Select value={status} onValueChange={setStatus}>
+              <SelectTrigger><SelectValue /></SelectTrigger>
+              <SelectContent>
+                <SelectItem value="draft">Draft</SelectItem>
+                <SelectItem value="sent">Sent</SelectItem>
+                <SelectItem value="accepted">Accepted</SelectItem>
+                <SelectItem value="rejected">Rejected</SelectItem>
+              </SelectContent>
+            </Select>
+          </div>
+          <div className="space-y-1">
+            <Label htmlFor="validUntil" className="text-xs">Valid Until</Label>
+            <Input id="validUntil" name="validUntil" type="date" defaultValue={defaultValidDate} />
+          </div>
+        </div>
+      </div>
+
+      {/* Totals */}
+      <div className="rounded-lg border p-3 space-y-2">
+        <h3 className="text-sm font-semibold">Totals</h3>
+        <div className="space-y-2">
+          <div className="flex items-center justify-between text-sm">
+            <span className="text-muted-foreground">Parts</span>
+            <span>{formatCurrency(partsSubtotal, currencyCode)}</span>
+          </div>
+          <div className="flex items-center justify-between text-sm">
+            <span className="text-muted-foreground">Labor</span>
+            <span>{formatCurrency(laborSubtotal, currencyCode)}</span>
+          </div>
+          <div className="flex items-center justify-between text-sm">
+            <span className="text-muted-foreground">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">Discount</span>
+              <Select value={discountType} onValueChange={setDiscountType}>
+                <SelectTrigger className="h-7 w-28 text-xs"><SelectValue /></SelectTrigger>
+                <SelectContent>
+                  <SelectItem value="none">None</SelectItem>
+                  <SelectItem value="percentage">Percentage</SelectItem>
+                  <SelectItem value="fixed">Fixed</SelectItem>
+                </SelectContent>
+              </Select>
+              {discountType !== "none" && (
+                <Input
+                  type="number" min="0" step="0.01"
+                  value={discountValue}
+                  onChange={(e) => setDiscountValue(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>
             )}
-          </CardContent>
-        </Card>
+          </div>
+          {taxEnabled && (
+            <div className="flex items-center justify-between text-sm">
+              <div className="flex items-center gap-2">
+                <span className="text-muted-foreground">Tax</span>
+                <Input
+                  type="number" min="0" step="0.1"
+                  value={taxRate}
+                  onChange={(e) => setTaxRate(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>Total</span>
+            <span>{formatCurrency(totalAmount, currencyCode)}</span>
+          </div>
+        </div>
+      </div>
+    </div>
+  );
 
-        <div className="flex justify-end gap-3 pb-8">
-          <Button type="button" variant="outline" asChild>
+  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 ? "Edit Quote" : "New Quote"}</h1>
+        </div>
+        <div className="flex items-center gap-2">
+          <Button type="button" variant="outline" size="sm" asChild>
             <Link href="/quotes">Cancel</Link>
           </Button>
-          <Button type="submit" disabled={loading}>
-            {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-            {isEdit ? "Update Quote" : "Create Quote"}
+          <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 ? "Update" : "Create"} Quote
           </Button>
         </div>
-      </form>
-    </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>
   );
 }

+ 653 - 0
src/features/quotes/Components/QuotePageClient.tsx

@@ -0,0 +1,653 @@
+"use client";
+
+import { useState, useCallback, useEffect } from "react";
+import { useRouter } from "next/navigation";
+import Link from "next/link";
+import { toast } from "sonner";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { ButtonGroup } from "@/components/ui/button-group";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+  Select,
+  SelectContent,
+  SelectItem,
+  SelectTrigger,
+  SelectValue,
+} from "@/components/ui/select";
+import {
+  Dialog,
+  DialogContent,
+  DialogHeader,
+  DialogTitle,
+} from "@/components/ui/dialog";
+import {
+  ResizablePanelGroup,
+  ResizablePanel,
+  ResizableHandle,
+} from "@/components/ui/resizable";
+import { useGlassModal } from "@/components/glass-modal";
+import { useConfirm } from "@/components/confirm-dialog";
+import { updateQuote, deleteQuote, convertQuoteToServiceRecord } from "@/features/quotes/Actions/quoteActions";
+import { sendQuoteEmail } from "@/features/email/Actions/emailActions";
+import { SendEmailDialog } from "@/features/email/Components/SendEmailDialog";
+import { QuoteShareDialog } from "@/features/quotes/Components/QuoteShareDialog";
+import { RichTextEditor } from "@/features/vehicles/Components/service-edit/RichTextEditor";
+import type { QuotePartInput, QuoteLaborInput } from "@/features/quotes/Schema/quoteSchema";
+import {
+  ArrowLeft,
+  ArrowRight,
+  Car,
+  Download,
+  FileText,
+  Globe,
+  Loader2,
+  Mail,
+  Plus,
+  Save,
+  Trash2,
+  Users,
+  X,
+} from "lucide-react";
+import { formatCurrency, getCurrencySymbol } from "@/lib/format";
+
+const statusColors: Record<string, string> = {
+  draft: "bg-gray-500/10 text-gray-500 border-gray-500/20",
+  sent: "bg-blue-500/10 text-blue-500 border-blue-500/20",
+  accepted: "bg-emerald-500/10 text-emerald-600 border-emerald-500/20",
+  rejected: "bg-red-500/10 text-red-500 border-red-500/20",
+  expired: "bg-amber-500/10 text-amber-600 border-amber-500/20",
+  converted: "bg-purple-500/10 text-purple-500 border-purple-500/20",
+};
+
+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 QuoteRecord {
+  id: string;
+  quoteNumber: string | null;
+  title: string;
+  description: string | null;
+  status: string;
+  validUntil: Date | null;
+  subtotal: number;
+  taxRate: number;
+  taxAmount: number;
+  discountType: string | null;
+  discountValue: number;
+  discountAmount: number;
+  totalAmount: number;
+  notes: string | null;
+  publicToken: string | null;
+  convertedToId: string | null;
+  createdAt: Date;
+  partItems: { id: string; partNumber: string | null; name: string; quantity: number; unitPrice: number; total: number }[];
+  laborItems: { id: string; description: string; hours: number; rate: number; total: number }[];
+  customer: { id: string; name: string; email: string | null; phone: string | null; address: string | null; company: string | null } | null;
+  vehicle: { id: string; make: string; model: string; year: number; vin: string | null; licensePlate: string | null; mileage: number } | null;
+}
+
+const emptyPart = (): QuotePartInput => ({
+  partNumber: "",
+  name: "",
+  quantity: 1,
+  unitPrice: 0,
+  total: 0,
+});
+
+const makeEmptyLabor = (defaultRate: number): QuoteLaborInput => ({
+  description: "",
+  hours: 0,
+  rate: defaultRate,
+  total: 0,
+});
+
+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;
+}
+
+export function QuotePageClient({
+  quote,
+  organizationId,
+  currencyCode = "USD",
+  defaultTaxRate = 0,
+  taxEnabled = true,
+  defaultLaborRate = 0,
+  customers = [],
+  vehicles = [],
+}: {
+  quote: QuoteRecord;
+  organizationId: string;
+  currencyCode?: string;
+  defaultTaxRate?: number;
+  taxEnabled?: boolean;
+  defaultLaborRate?: number;
+  customers?: CustomerOption[];
+  vehicles?: VehicleOption[];
+}) {
+  const cs = getCurrencySymbol(currencyCode);
+  const router = useRouter();
+  const modal = useGlassModal();
+  const confirm = useConfirm();
+  const isLarge = useIsLargeScreen();
+
+  // Form state
+  const [saving, setSaving] = useState(false);
+  const [downloading, setDownloading] = useState(false);
+  const [status, setStatus] = useState(quote.status);
+  const [customerId, setCustomerId] = useState(quote.customer?.id || "");
+  const [vehicleId, setVehicleId] = useState(quote.vehicle?.id || "");
+  const [partItems, setPartItems] = useState<QuotePartInput[]>(
+    quote.partItems.map((p) => ({ partNumber: p.partNumber || "", name: p.name, quantity: p.quantity, unitPrice: p.unitPrice, total: p.total }))
+  );
+  const [laborItems, setLaborItems] = useState<QuoteLaborInput[]>(
+    quote.laborItems.map((l) => ({ description: l.description, hours: l.hours, rate: l.rate, total: l.total }))
+  );
+  const [taxRate, setTaxRate] = useState(quote.taxRate ?? defaultTaxRate);
+  const [discountType, setDiscountType] = useState<string>(quote.discountType || "none");
+  const [discountValue, setDiscountValue] = useState(quote.discountValue ?? 0);
+  const [noteType, setNoteType] = useState<"public" | "internal">("public");
+  const [description, setDescription] = useState(quote.description || "");
+  const [notes, setNotes] = useState(quote.notes || "");
+
+  // Dialog state
+  const [showEmailDialog, setShowEmailDialog] = useState(false);
+  const [showShareDialog, setShowShareDialog] = useState(false);
+  const [showConvertDialog, setShowConvertDialog] = useState(false);
+  const [convertVehicleId, setConvertVehicleId] = useState(quote.vehicle?.id || "");
+  const [converting, setConverting] = useState(false);
+
+  const [defaultValidDate] = useState(() =>
+    quote.validUntil ? new Date(quote.validUntil).toISOString().split("T")[0] : ""
+  );
+
+  // Calculations
+  const partsSubtotal = partItems.reduce((sum, p) => sum + p.total, 0);
+  const laborSubtotal = laborItems.reduce((sum, l) => 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) => {
+    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) => {
+    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();
+    setSaving(true);
+    const formData = new FormData(e.currentTarget);
+    const result = await updateQuote({
+      id: quote.id,
+      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,
+      partItems: partItems.filter((p) => p.name),
+      laborItems: laborItems.filter((l) => l.description),
+      subtotal,
+      taxRate,
+      taxAmount,
+      discountType: discountType === "none" ? undefined : discountType,
+      discountValue,
+      discountAmount,
+      totalAmount,
+    });
+    if (result.success) {
+      toast.success("Quote saved");
+      router.refresh();
+    } else {
+      modal.open("error", "Error", result.error || "Failed to save quote");
+    }
+    setSaving(false);
+  };
+
+  const handleDelete = async () => {
+    const ok = await confirm({ title: "Delete Quote", description: "This will permanently delete this quote.", confirmLabel: "Delete", destructive: true });
+    if (!ok) return;
+    const result = await deleteQuote(quote.id);
+    if (result.success) {
+      router.push("/quotes");
+      router.refresh();
+    } else {
+      modal.open("error", "Error", result.error || "Failed to delete");
+    }
+  };
+
+  const handleDownloadPDF = async () => {
+    setDownloading(true);
+    try {
+      const res = await fetch(`/api/quotes/${quote.id}/pdf`);
+      if (!res.ok) throw new Error("Failed to generate PDF");
+      const blob = await res.blob();
+      const url = URL.createObjectURL(blob);
+      const a = document.createElement("a");
+      a.href = url;
+      a.download = `quote-${quote.quoteNumber || quote.id}.pdf`;
+      a.click();
+      URL.revokeObjectURL(url);
+    } catch {
+      modal.open("error", "Error", "Failed to generate PDF");
+    }
+    setDownloading(false);
+  };
+
+  const handleConvert = async () => {
+    if (!convertVehicleId) {
+      modal.open("error", "Error", "Please select a vehicle");
+      return;
+    }
+    setConverting(true);
+    const result = await convertQuoteToServiceRecord(quote.id, convertVehicleId);
+    if (result.success && result.data) {
+      router.push(`/vehicles/${convertVehicleId}/service/${result.data.id}`);
+      router.refresh();
+    } else {
+      modal.open("error", "Error", result.error || "Failed to convert");
+    }
+    setConverting(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">Parts</h3>
+          <Button type="button" variant="outline" size="sm" onClick={() => setPartItems([...partItems, emptyPart()])}>
+            <Plus className="mr-1 h-3.5 w-3.5" /> Add Part
+          </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>Part #</span><span>Name</span><span>Qty</span><span>Unit Price</span><span>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]">
+                <Input placeholder="Part #" value={part.partNumber ?? ""} onChange={(e) => updatePart(i, "partNumber", e.target.value)} />
+                <Input placeholder="Name *" 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", Number(e.target.value))} />
+                <Input type="number" min="0" step="0.01" value={part.unitPrice} onChange={(e) => updatePart(i, "unitPrice", Number(e.target.value))} />
+                <div className="flex items-center rounded-md bg-muted/50 px-3 text-sm font-medium">{formatCurrency(part.total, currencyCode)}</div>
+                <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>
+            ))}
+            <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">Parts Subtotal: {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">Add Part</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">Labor</h3>
+          <Button type="button" variant="outline" size="sm" onClick={() => setLaborItems([...laborItems, makeEmptyLabor(defaultLaborRate)])}><Plus className="mr-1 h-3.5 w-3.5" /> Add Labor</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>Description</span><span>Hours</span><span>Rate ({cs}/hr)</span><span>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]">
+                <Input placeholder="Description *" 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.5" value={labor.hours} onChange={(e) => updateLabor(i, "hours", Number(e.target.value))} />
+                <Input type="number" min="0" step="0.01" value={labor.rate} onChange={(e) => updateLabor(i, "rate", Number(e.target.value))} />
+                <div className="flex items-center rounded-md bg-muted/50 px-3 text-sm font-medium">{formatCurrency(labor.total, currencyCode)}</div>
+                <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>
+            ))}
+            <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">Labor Subtotal: {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">Add Labor</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" />Notes</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">Public</SelectItem>
+              <SelectItem value="internal">Internal</SelectItem>
+            </SelectContent>
+          </Select>
+        </div>
+        {noteType === "public" && (
+          <div className="space-y-1">
+            <RichTextEditor content={description} onChange={setDescription} placeholder="Quote description shown to the customer..." />
+            <p className="text-xs text-muted-foreground">Shown on the quote document</p>
+          </div>
+        )}
+        {noteType === "internal" && (
+          <div className="space-y-1">
+            <RichTextEditor content={notes} onChange={setNotes} placeholder="Internal notes (not shown to customer)..." />
+            <p className="text-xs text-muted-foreground">Only visible to your team</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">Vehicle</Label>
+          <Select value={vehicleId || "none"} onValueChange={handleVehicleChange}>
+            <SelectTrigger><SelectValue placeholder="Select vehicle..." /></SelectTrigger>
+            <SelectContent>
+              <SelectItem value="none">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">Customer</Label>
+          <Select value={customerId || "none"} onValueChange={(v) => setCustomerId(v === "none" ? "" : v)}>
+            <SelectTrigger><SelectValue placeholder="Select customer..." /></SelectTrigger>
+            <SelectContent>
+              <SelectItem value="none">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">Quote Details</h3>
+        <div className="space-y-1">
+          <Label htmlFor="title" className="text-xs">Title *</Label>
+          <Input id="title" name="title" placeholder="Vehicle repair estimate" defaultValue={quote.title} required />
+        </div>
+        <div className="grid grid-cols-2 gap-2">
+          <div className="space-y-1">
+            <Label className="text-xs">Status</Label>
+            <Select value={status} onValueChange={setStatus}>
+              <SelectTrigger><SelectValue /></SelectTrigger>
+              <SelectContent>
+                <SelectItem value="draft">Draft</SelectItem>
+                <SelectItem value="sent">Sent</SelectItem>
+                <SelectItem value="accepted">Accepted</SelectItem>
+                <SelectItem value="rejected">Rejected</SelectItem>
+              </SelectContent>
+            </Select>
+          </div>
+          <div className="space-y-1">
+            <Label htmlFor="validUntil" className="text-xs">Valid Until</Label>
+            <Input id="validUntil" name="validUntil" type="date" defaultValue={defaultValidDate} />
+          </div>
+        </div>
+      </div>
+
+      {/* Totals */}
+      <div className="rounded-lg border p-3 space-y-2">
+        <h3 className="text-sm font-semibold">Totals</h3>
+        <div className="space-y-2">
+          <div className="flex items-center justify-between text-sm"><span className="text-muted-foreground">Parts</span><span>{formatCurrency(partsSubtotal, currencyCode)}</span></div>
+          <div className="flex items-center justify-between text-sm"><span className="text-muted-foreground">Labor</span><span>{formatCurrency(laborSubtotal, currencyCode)}</span></div>
+          <div className="flex items-center justify-between text-sm"><span className="text-muted-foreground">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">Discount</span>
+              <Select value={discountType} onValueChange={setDiscountType}>
+                <SelectTrigger className="h-7 w-28 text-xs"><SelectValue /></SelectTrigger>
+                <SelectContent>
+                  <SelectItem value="none">None</SelectItem>
+                  <SelectItem value="percentage">Percentage</SelectItem>
+                  <SelectItem value="fixed">Fixed</SelectItem>
+                </SelectContent>
+              </Select>
+              {discountType !== "none" && (
+                <Input type="number" min="0" step="0.01" value={discountValue} onChange={(e) => setDiscountValue(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">Tax</span>
+                <Input type="number" min="0" step="0.1" value={taxRate} onChange={(e) => setTaxRate(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>Total</span><span>{formatCurrency(totalAmount, currencyCode)}</span></div>
+        </div>
+      </div>
+
+      {/* Convert to Work Order */}
+      {quote.status !== "converted" && (
+        <div className="rounded-lg border p-3">
+          <Button type="button" variant="outline" size="sm" className="w-full" onClick={() => setShowConvertDialog(true)}>
+            <ArrowRight className="mr-1 h-3.5 w-3.5" /> Convert to Work Order
+          </Button>
+        </div>
+      )}
+    </div>
+  );
+
+  return (
+    <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
+      {/* Header */}
+      <div className="shrink-0 border-b bg-background px-4 py-2">
+        <div className="flex items-center justify-between">
+          <Link
+            href="/quotes"
+            className="flex min-w-0 items-center gap-3 text-foreground transition-colors hover:text-muted-foreground"
+          >
+            <ArrowLeft className="h-4 w-4 shrink-0" />
+            <div className="min-w-0">
+              <div className="flex items-center gap-2">
+                <Badge variant="outline" className={`shrink-0 text-xs capitalize ${statusColors[status] || ""}`}>
+                  {status}
+                </Badge>
+                <h1 className="truncate text-lg font-semibold leading-tight">{quote.title}</h1>
+              </div>
+              <p className="truncate text-xs text-muted-foreground">
+                {quote.quoteNumber || `Quote`}
+                {quote.customer ? ` · ${quote.customer.name}` : ""}
+              </p>
+            </div>
+          </Link>
+          <div className="flex shrink-0 items-center gap-2">
+            <Button type="submit" form="quote-form" size="sm" disabled={saving}>
+              {saving ? <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" /> : <Save className="mr-1 h-3.5 w-3.5" />}
+              Save
+            </Button>
+            <ButtonGroup>
+              <Button variant="outline" size="sm" onClick={handleDownloadPDF} disabled={downloading}>
+                {downloading ? <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" /> : <Download className="mr-1 h-3.5 w-3.5" />}
+                PDF
+              </Button>
+              <Button variant="outline" size="sm" onClick={() => setShowEmailDialog(true)}>
+                <Mail className="mr-1 h-3.5 w-3.5" />
+                Email
+              </Button>
+              <Button variant="outline" size="sm" onClick={() => setShowShareDialog(true)}>
+                <Globe className="mr-1 h-3.5 w-3.5" />
+                Share
+              </Button>
+              <Button variant="outline" size="sm" className="text-destructive hover:bg-destructive/10" onClick={handleDelete}>
+                <Trash2 className="mr-1 h-3.5 w-3.5" />
+                Delete
+              </Button>
+            </ButtonGroup>
+          </div>
+        </div>
+      </div>
+
+      {/* Form */}
+      <form id="quote-form" onSubmit={handleSubmit} className="flex min-h-0 flex-1 flex-col overflow-hidden">
+        {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>
+
+      {/* Dialogs */}
+      <SendEmailDialog
+        open={showEmailDialog}
+        onOpenChange={setShowEmailDialog}
+        defaultEmail={quote.customer?.email || ""}
+        entityLabel="Quote"
+        onSend={async (email, message) => sendQuoteEmail({ quoteId: quote.id, recipientEmail: email, message })}
+      />
+
+      <QuoteShareDialog
+        open={showShareDialog}
+        onOpenChange={setShowShareDialog}
+        quoteId={quote.id}
+        organizationId={organizationId}
+        initialToken={quote.publicToken}
+      />
+
+      <Dialog open={showConvertDialog} onOpenChange={setShowConvertDialog}>
+        <DialogContent className="max-w-md">
+          <DialogHeader><DialogTitle>Convert Quote to Work Order</DialogTitle></DialogHeader>
+          <div className="space-y-4">
+            <p className="text-sm text-muted-foreground">This will create a new service record (work order) from this quote. Select a vehicle for the work order.</p>
+            <Select value={convertVehicleId} onValueChange={setConvertVehicleId}>
+              <SelectTrigger><SelectValue placeholder="Select vehicle..." /></SelectTrigger>
+              <SelectContent>
+                {vehicles.map((v) => (
+                  <SelectItem key={v.id} value={v.id}>{v.year} {v.make} {v.model}{v.licensePlate ? ` (${v.licensePlate})` : ""}</SelectItem>
+                ))}
+              </SelectContent>
+            </Select>
+            <div className="flex gap-2">
+              <Button type="button" onClick={handleConvert} disabled={converting || !convertVehicleId}>
+                {converting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+                Convert
+              </Button>
+              <Button type="button" variant="ghost" onClick={() => setShowConvertDialog(false)}>Cancel</Button>
+            </div>
+          </div>
+        </DialogContent>
+      </Dialog>
+    </div>
+  );
+}

+ 98 - 0
src/features/quotes/Components/QuoteShareDialog.tsx

@@ -0,0 +1,98 @@
+"use client";
+
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+  Dialog,
+  DialogContent,
+  DialogHeader,
+  DialogTitle,
+} from "@/components/ui/dialog";
+import { Check, Copy, Link2, Loader2 } from "lucide-react";
+import { generateQuotePublicLink, revokeQuotePublicLink } from "@/features/quotes/Actions/quoteShareActions";
+
+interface QuoteShareDialogProps {
+  open: boolean;
+  onOpenChange: (open: boolean) => void;
+  quoteId: string;
+  organizationId: string;
+  initialToken: string | null;
+}
+
+export function QuoteShareDialog({
+  open,
+  onOpenChange,
+  quoteId,
+  organizationId,
+  initialToken,
+}: QuoteShareDialogProps) {
+  const [publicToken, setPublicToken] = useState<string | null>(initialToken);
+  const [generatingLink, setGeneratingLink] = useState(false);
+  const [copied, setCopied] = useState(false);
+
+  const publicUrl = publicToken && organizationId
+    ? `${typeof window !== "undefined" ? window.location.origin : ""}/share/quote/${organizationId}/${publicToken}`
+    : null;
+
+  const handleGenerate = async () => {
+    setGeneratingLink(true);
+    const result = await generateQuotePublicLink(quoteId);
+    if (result.success && result.data) setPublicToken(result.data.token);
+    setGeneratingLink(false);
+  };
+
+  const handleRevoke = async () => {
+    await revokeQuotePublicLink(quoteId);
+    setPublicToken(null);
+  };
+
+  const handleCopy = () => {
+    if (publicUrl) {
+      navigator.clipboard.writeText(publicUrl);
+      setCopied(true);
+      setTimeout(() => setCopied(false), 2000);
+    }
+  };
+
+  return (
+    <Dialog open={open} onOpenChange={onOpenChange}>
+      <DialogContent className="max-w-md">
+        <DialogHeader>
+          <DialogTitle className="flex items-center gap-2">
+            <Link2 className="h-5 w-5" />
+            Share Quote
+          </DialogTitle>
+        </DialogHeader>
+        <div className="space-y-4">
+          <p className="text-sm text-muted-foreground">
+            Generate a public link that allows anyone to view and download this quote without signing in.
+          </p>
+          {publicUrl ? (
+            <>
+              <div className="flex items-center gap-2">
+                <Input value={publicUrl} readOnly className="text-xs font-mono" />
+                <Button variant="outline" size="icon" onClick={handleCopy}>
+                  {copied ? <Check className="h-4 w-4 text-emerald-500" /> : <Copy className="h-4 w-4" />}
+                </Button>
+              </div>
+              <Button
+                variant="ghost"
+                size="sm"
+                className="text-destructive hover:text-destructive"
+                onClick={handleRevoke}
+              >
+                Revoke Link
+              </Button>
+            </>
+          ) : (
+            <Button onClick={handleGenerate} disabled={generatingLink}>
+              {generatingLink && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+              Generate Public Link
+            </Button>
+          )}
+        </div>
+      </DialogContent>
+    </Dialog>
+  );
+}

+ 1 - 1
src/features/search/Components/SearchCommand.tsx

@@ -59,7 +59,7 @@ const SEARCHABLE_SETTINGS = [
   { label: "Account", description: "Account, profile, password", href: "/settings/account", keywords: ["account", "profile", "password", "email", "2fa"] },
   { label: "Team", description: "Team members and roles", href: "/settings/team", keywords: ["team", "members", "roles", "invite"] },
   { label: "Invoice", description: "Invoice layout and prefix", href: "/settings/invoice", keywords: ["invoice", "layout", "prefix", "footer", "due"] },
-  { label: "Templates", description: "Invoice template styling", href: "/settings/invoice-template", keywords: ["template", "styling", "colors", "font", "header"] },
+  { label: "Templates", description: "Invoice & quote template styling", href: "/settings/templates", keywords: ["template", "styling", "colors", "font", "header", "quote"] },
   { label: "Payment", description: "Payment and bank settings", href: "/settings/payment", keywords: ["payment", "bank", "vipps", "stripe", "terms"] },
   { label: "Currency", description: "Currency, tax, and VAT", href: "/settings/currency", keywords: ["currency", "tax", "vat", "unit"] },
   { label: "Custom Fields", description: "Custom fields configuration", href: "/settings/custom-fields", keywords: ["custom fields", "fields"] },

+ 3 - 0
src/features/settings/Schema/settingsSchema.ts

@@ -54,6 +54,9 @@ export const SETTING_KEYS = {
   DATE_FORMAT: "workshop.dateFormat",
   TIME_FORMAT: "workshop.timeFormat",
   TIMEZONE: "workshop.timezone",
+  QUOTE_PRIMARY_COLOR: "quote.primaryColor",
+  QUOTE_FONT_FAMILY: "quote.fontFamily",
+  QUOTE_HEADER_STYLE: "quote.headerStyle",
 } as const;
 
 export type SettingKey = (typeof SETTING_KEYS)[keyof typeof SETTING_KEYS];

+ 24 - 14
src/features/vehicles/Components/service-detail/PaymentsSection.tsx

@@ -1,6 +1,6 @@
 "use client";
 
-import { useState } from "react";
+import { useRef, useState } from "react";
 import { Badge } from "@/components/ui/badge";
 import { Button } from "@/components/ui/button";
 import { Input } from "@/components/ui/input";
@@ -48,18 +48,26 @@ export function PaymentsSection({
   deletingPayment,
 }: PaymentsSectionProps) {
   const [showForm, setShowForm] = useState(false);
+  const [paymentMethod, setPaymentMethod] = useState("other");
   const { formatDate } = useFormatDate();
+  const formRef = useRef<HTMLDivElement>(null);
 
-  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
-    e.preventDefault();
-    const formData = new FormData(e.currentTarget);
+  const handleSubmit = async () => {
+    if (!formRef.current) return;
+    const amount = formRef.current.querySelector<HTMLInputElement>('[name="paymentAmount"]');
+    const date = formRef.current.querySelector<HTMLInputElement>('[name="paymentDate"]');
+    const note = formRef.current.querySelector<HTMLInputElement>('[name="paymentNote"]');
+    if (!amount?.value || Number(amount.value) <= 0) return;
     const success = await onCreatePayment({
-      amount: Number(formData.get("paymentAmount")),
-      date: (formData.get("paymentDate") as string) || new Date().toISOString(),
-      method: formData.get("paymentMethod") as string,
-      note: (formData.get("paymentNote") as string) || undefined,
+      amount: Number(amount.value),
+      date: date?.value || new Date().toISOString(),
+      method: paymentMethod,
+      note: note?.value || undefined,
     });
-    if (success) setShowForm(false);
+    if (success) {
+      setShowForm(false);
+      setPaymentMethod("other");
+    }
   };
 
   return (
@@ -76,6 +84,7 @@ export function PaymentsSection({
         </div>
         <div className="flex items-center gap-2">
           <Button
+            type="button"
             variant="outline"
             size="sm"
             className="h-7 text-xs"
@@ -91,7 +100,7 @@ export function PaymentsSection({
             )}
             {manuallyPaid ? "Mark as Unpaid" : "Mark as Paid"}
           </Button>
-          <Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setShowForm(!showForm)}>
+          <Button type="button" variant="outline" size="sm" className="h-7 text-xs" onClick={() => setShowForm(!showForm)}>
             <Plus className="mr-1 h-3 w-3" />
             Record Payment
           </Button>
@@ -107,7 +116,7 @@ export function PaymentsSection({
         </div>
 
         {showForm && (
-          <form onSubmit={handleSubmit} className="space-y-3 rounded-lg border p-3">
+          <div ref={formRef} className="space-y-3 rounded-lg border p-3">
             <div className="grid gap-3 sm:grid-cols-2">
               <div className="space-y-1">
                 <Label htmlFor="paymentAmount" className="text-xs">Amount</Label>
@@ -125,7 +134,7 @@ export function PaymentsSection({
               </div>
               <div className="space-y-1">
                 <Label className="text-xs">Method</Label>
-                <Select name="paymentMethod" defaultValue="other">
+                <Select value={paymentMethod} onValueChange={setPaymentMethod}>
                   <SelectTrigger><SelectValue /></SelectTrigger>
                   <SelectContent>
                     <SelectItem value="cash">Cash</SelectItem>
@@ -141,7 +150,7 @@ export function PaymentsSection({
               </div>
             </div>
             <div className="flex gap-2">
-              <Button type="submit" size="sm" disabled={paymentLoading}>
+              <Button type="button" size="sm" disabled={paymentLoading} onClick={handleSubmit}>
                 {paymentLoading && <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />}
                 Save Payment
               </Button>
@@ -149,7 +158,7 @@ export function PaymentsSection({
                 Cancel
               </Button>
             </div>
-          </form>
+          </div>
         )}
 
         {payments.length > 0 && (
@@ -175,6 +184,7 @@ export function PaymentsSection({
                     <td className="py-1.5 text-muted-foreground">{payment.note || "-"}</td>
                     <td className="py-1.5">
                       <Button
+                        type="button"
                         variant="ghost" size="icon"
                         className="h-6 w-6 text-muted-foreground hover:text-destructive"
                         disabled={deletingPayment === payment.id}

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików