Răsfoiți Sursa

migrate invoice edit and view into single page

Bernt Christian Egeland 9 luni în urmă
părinte
comite
cbe1779fbb

+ 0 - 52
src/app/(authenticated)/vehicles/[id]/service/[serviceId]/edit/documents/page.tsx

@@ -1,52 +0,0 @@
-import { db } from "@/lib/db";
-import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
-import { redirect } from "next/navigation";
-import { ServiceDocumentsManager } from "@/features/vehicles/Components/service-documents-manager";
-import { getFeatures } from "@/lib/features";
-
-export default async function EditServiceDocumentsPage({
-  params,
-}: {
-  params: Promise<{ id: string; serviceId: string }>;
-}) {
-  const { id, serviceId } = await params;
-
-  const session = await getCachedSession();
-  if (!session?.user?.id) redirect("/sign-in");
-  const membership = await getCachedMembership(session.user.id);
-  if (!membership) redirect("/sign-in");
-
-  const [record, features] = await Promise.all([
-    db.serviceRecord.findFirst({
-      where: {
-        id: serviceId,
-        vehicle: { id, organizationId: membership.organizationId },
-      },
-      select: {
-        id: true,
-        attachments: {
-          where: { category: { in: ["document", "diagnostic"] } },
-          orderBy: { createdAt: "asc" },
-        },
-      },
-    }),
-    getFeatures(membership.organizationId),
-  ]);
-
-  if (!record) {
-    return (
-      <div className="flex h-[50vh] items-center justify-center">
-        <p className="text-muted-foreground">Service record not found</p>
-      </div>
-    );
-  }
-
-  return (
-    <ServiceDocumentsManager
-      serviceRecordId={record.id}
-      initialDocuments={record.attachments}
-      maxDiagnostics={features.maxDiagnosticsPerService}
-      maxDocuments={features.maxDocumentsPerService}
-    />
-  );
-}

+ 0 - 51
src/app/(authenticated)/vehicles/[id]/service/[serviceId]/edit/images/page.tsx

@@ -1,51 +0,0 @@
-import { db } from "@/lib/db";
-import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
-import { redirect } from "next/navigation";
-import { ServiceImagesManager } from "@/features/vehicles/Components/service-images-manager";
-import { getFeatures } from "@/lib/features";
-
-export default async function EditServiceImagesPage({
-  params,
-}: {
-  params: Promise<{ id: string; serviceId: string }>;
-}) {
-  const { id, serviceId } = await params;
-
-  const session = await getCachedSession();
-  if (!session?.user?.id) redirect("/sign-in");
-  const membership = await getCachedMembership(session.user.id);
-  if (!membership) redirect("/sign-in");
-
-  const [record, features] = await Promise.all([
-    db.serviceRecord.findFirst({
-      where: {
-        id: serviceId,
-        vehicle: { id, organizationId: membership.organizationId },
-      },
-      select: {
-        id: true,
-        attachments: {
-          where: { category: "image" },
-          orderBy: { createdAt: "asc" },
-        },
-      },
-    }),
-    getFeatures(membership.organizationId),
-  ]);
-
-  if (!record) {
-    return (
-      <div className="flex h-[50vh] items-center justify-center">
-        <p className="text-muted-foreground">Service record not found</p>
-      </div>
-    );
-  }
-
-  return (
-    <ServiceImagesManager
-      serviceRecordId={record.id}
-      initialImages={record.attachments}
-      maxImages={features.maxImagesPerService}
-    />
-  );
-}

+ 0 - 57
src/app/(authenticated)/vehicles/[id]/service/[serviceId]/edit/layout.tsx

@@ -1,57 +0,0 @@
-import Link from "next/link";
-import { ArrowLeft } from "lucide-react";
-import { PageHeader } from "@/components/page-header";
-import { EditNav } from "@/features/vehicles/Components/service-edit/EditNav";
-import { EditActions } from "@/features/vehicles/Components/service-edit/EditActions";
-import { db } from "@/lib/db";
-import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
-import { redirect } from "next/navigation";
-
-export default async function EditServiceLayout({
-  params,
-  children,
-}: {
-  params: Promise<{ id: string; serviceId: string }>;
-  children: React.ReactNode;
-}) {
-  const { id, serviceId } = await params;
-
-  const session = await getCachedSession();
-  if (!session?.user?.id) redirect("/sign-in");
-  const membership = await getCachedMembership(session.user.id);
-  if (!membership) redirect("/sign-in");
-
-  const vehicle = await db.vehicle.findFirst({
-    where: { id, organizationId: membership.organizationId },
-    select: { year: true, make: true, model: true },
-  });
-
-  const vehicleName = vehicle
-    ? `${vehicle.year} ${vehicle.make} ${vehicle.model}`
-    : "Vehicle";
-
-  return (
-    <div className="flex h-svh flex-col">
-      <PageHeader />
-      <div className="shrink-0 border-b bg-background px-4 pt-2 pb-0">
-        <div className="mb-2 flex items-center justify-between">
-          <Link
-            href={`/vehicles/${id}/service/${serviceId}`}
-            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">
-              <h1 className="truncate text-lg font-semibold leading-tight">Edit Service Record</h1>
-              <p className="truncate text-xs text-muted-foreground">{vehicleName}</p>
-            </div>
-          </Link>
-          <EditActions serviceRecordId={serviceId} />
-        </div>
-        <EditNav vehicleId={id} serviceId={serviceId} />
-      </div>
-      <div className="flex-1 overflow-y-auto">
-        {children}
-      </div>
-    </div>
-  );
-}

+ 0 - 112
src/app/(authenticated)/vehicles/[id]/service/[serviceId]/edit/page.tsx

@@ -1,112 +0,0 @@
-import { getServiceRecord } from "@/features/vehicles/Actions/serviceActions";
-import { getSettings } from "@/features/settings/Actions/settingsActions";
-import { SETTING_KEYS } from "@/features/settings/Schema/settingsSchema";
-import { getInventoryPartsList } from "@/features/inventory/Actions/inventoryActions";
-import { getVehicles } from "@/features/vehicles/Actions/vehicleActions";
-import { ServiceRecordForm } from "@/features/vehicles/Components/service-edit/ServiceRecordForm";
-import { db } from "@/lib/db";
-import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
-
-export default async function EditServicePage({
-  params,
-}: {
-  params: Promise<{ id: string; serviceId: string }>;
-}) {
-  const { id, serviceId } = await params;
-  const [result, settingsResult, inventoryResult, vehiclesResult, session] = await Promise.all([
-    getServiceRecord(serviceId),
-    getSettings([SETTING_KEYS.DEFAULT_TAX_RATE, SETTING_KEYS.TAX_ENABLED, SETTING_KEYS.CURRENCY_CODE, SETTING_KEYS.DEFAULT_LABOR_RATE]),
-    getInventoryPartsList(),
-    getVehicles(),
-    getCachedSession(),
-  ]);
-
-  if (!result.success || !result.data) {
-    return (
-      <div className="flex h-[50vh] items-center justify-center">
-        <p className="text-muted-foreground">
-          {result.error || "Service record not found"}
-        </p>
-      </div>
-    );
-  }
-
-  const settings = settingsResult.success && settingsResult.data ? settingsResult.data : {};
-  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 currencyCode = settings[SETTING_KEYS.CURRENCY_CODE] || "USD";
-  const inventoryParts = inventoryResult.success && inventoryResult.data ? inventoryResult.data : [];
-  const vehicles = (vehiclesResult.success && vehiclesResult.data ? vehiclesResult.data : []).map((v) => ({
-    id: v.id,
-    label: `${v.year} ${v.make} ${v.model}${v.licensePlate ? ` (${v.licensePlate})` : ""}`,
-  }));
-  const record = result.data;
-
-  const initialData = {
-    id: record.id,
-    title: record.title,
-    description: record.description || "",
-    type: record.type,
-    status: record.status,
-    mileage: record.mileage,
-    serviceDate: new Date(record.serviceDate).toISOString().split("T")[0],
-    techName: record.techName || "",
-    diagnosticNotes: record.diagnosticNotes || "",
-    invoiceNotes: record.invoiceNotes || "",
-    invoiceNumber: record.invoiceNumber || "",
-    partItems: record.partItems.map((p) => ({
-      partNumber: p.partNumber || "",
-      name: p.name,
-      quantity: p.quantity,
-      unitPrice: p.unitPrice,
-      total: p.total,
-    })),
-    laborItems: record.laborItems.map((l) => ({
-      description: l.description,
-      hours: l.hours,
-      rate: l.rate,
-      total: l.total,
-    })),
-    attachments: [],
-    subtotal: record.subtotal,
-    taxRate: record.taxRate,
-    taxAmount: record.taxAmount,
-    totalAmount: record.totalAmount,
-  };
-
-  const vehicleName = `${record.vehicle.year} ${record.vehicle.make} ${record.vehicle.model}`;
-
-  // Fetch team members and current user name for technician dropdown
-  const membership = session?.user?.id ? await getCachedMembership(session.user.id) : null;
-  const orgId = membership?.organizationId;
-  const [members, currentUser] = await Promise.all([
-    orgId
-      ? db.organizationMember.findMany({
-          where: { organizationId: orgId },
-          select: { id: true, user: { select: { name: true } } },
-        })
-      : Promise.resolve([]),
-    session?.user?.id
-      ? db.user.findUnique({ where: { id: session.user.id }, select: { name: true } })
-      : Promise.resolve(null),
-  ]);
-  const teamMembers = members.map((m) => ({ id: m.id, name: m.user.name }));
-  const currentUserName = currentUser?.name || "";
-
-  return (
-    <ServiceRecordForm
-      vehicleId={id}
-      vehicleName={vehicleName}
-      defaultTaxRate={defaultTaxRate}
-      taxEnabled={taxEnabled}
-      defaultLaborRate={defaultLaborRate}
-      currencyCode={currencyCode}
-      initialData={initialData}
-      inventoryParts={inventoryParts}
-      vehicles={vehicles}
-      teamMembers={teamMembers}
-      currentUserName={currentUserName}
-    />
-  );
-}

+ 0 - 46
src/app/(authenticated)/vehicles/[id]/service/[serviceId]/edit/video/page.tsx

@@ -1,46 +0,0 @@
-import { db } from "@/lib/db";
-import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
-import { redirect } from "next/navigation";
-import { ServiceVideoManager } from "@/features/vehicles/Components/service-video-manager";
-
-export default async function EditServiceVideoPage({
-  params,
-}: {
-  params: Promise<{ id: string; serviceId: string }>;
-}) {
-  const { id, serviceId } = await params;
-
-  const session = await getCachedSession();
-  if (!session?.user?.id) redirect("/sign-in");
-  const membership = await getCachedMembership(session.user.id);
-  if (!membership) redirect("/sign-in");
-
-  const record = await db.serviceRecord.findFirst({
-    where: {
-      id: serviceId,
-      vehicle: { id, organizationId: membership.organizationId },
-    },
-    select: {
-      id: true,
-      attachments: {
-        where: { category: "video" },
-        orderBy: { createdAt: "asc" },
-      },
-    },
-  });
-
-  if (!record) {
-    return (
-      <div className="flex h-[50vh] items-center justify-center">
-        <p className="text-muted-foreground">Service record not found</p>
-      </div>
-    );
-  }
-
-  return (
-    <ServiceVideoManager
-      serviceRecordId={record.id}
-      initialVideos={record.attachments}
-    />
-  );
-}

+ 139 - 9
src/app/(authenticated)/vehicles/[id]/service/[serviceId]/page.tsx

@@ -1,8 +1,13 @@
 import { getServiceRecord } from "@/features/vehicles/Actions/serviceActions";
 import { getSettings } from "@/features/settings/Actions/settingsActions";
 import { SETTING_KEYS } from "@/features/settings/Schema/settingsSchema";
+import { getInventoryPartsList } from "@/features/inventory/Actions/inventoryActions";
+import { getVehicles } from "@/features/vehicles/Actions/vehicleActions";
 import { getAuthContext } from "@/lib/get-auth-context";
-import { ServiceDetailClient } from "@/features/vehicles/Components/service-detail/ServiceDetailClient";
+import { getFeatures } from "@/lib/features";
+import { db } from "@/lib/db";
+import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
+import { ServicePageClient } from "@/features/vehicles/Components/service-page/ServicePageClient";
 import { PageHeader } from "@/components/page-header";
 
 export default async function ServiceDetailPage({
@@ -11,11 +16,22 @@ export default async function ServiceDetailPage({
   params: Promise<{ id: string; serviceId: string }>;
 }) {
   const { id, serviceId } = await params;
-  const [result, settingsResult, authContext] = await Promise.all([
-    getServiceRecord(serviceId),
-    getSettings([SETTING_KEYS.CURRENCY_CODE, SETTING_KEYS.UNIT_SYSTEM]),
-    getAuthContext(),
-  ]);
+
+  const [result, settingsResult, inventoryResult, vehiclesResult, authContext, session] =
+    await Promise.all([
+      getServiceRecord(serviceId),
+      getSettings([
+        SETTING_KEYS.CURRENCY_CODE,
+        SETTING_KEYS.UNIT_SYSTEM,
+        SETTING_KEYS.DEFAULT_TAX_RATE,
+        SETTING_KEYS.TAX_ENABLED,
+        SETTING_KEYS.DEFAULT_LABOR_RATE,
+      ]),
+      getInventoryPartsList(),
+      getVehicles(),
+      getAuthContext(),
+      getCachedSession(),
+    ]);
 
   if (!result.success || !result.data) {
     return (
@@ -30,14 +46,128 @@ export default async function ServiceDetailPage({
     );
   }
 
-  const settings = settingsResult.success && settingsResult.data ? settingsResult.data : {};
+  const record = result.data;
+  const settings =
+    settingsResult.success && settingsResult.data ? settingsResult.data : {};
   const currencyCode = settings[SETTING_KEYS.CURRENCY_CODE] || "USD";
-  const unitSystem = (settings[SETTING_KEYS.UNIT_SYSTEM] || "imperial") as "metric" | "imperial";
+  const unitSystem = (settings[SETTING_KEYS.UNIT_SYSTEM] || "imperial") as
+    | "metric"
+    | "imperial";
+  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 inventoryParts =
+    inventoryResult.success && inventoryResult.data ? inventoryResult.data : [];
+  const vehicles = (
+    vehiclesResult.success && vehiclesResult.data ? vehiclesResult.data : []
+  ).map((v) => ({
+    id: v.id,
+    label: `${v.year} ${v.make} ${v.model}${v.licensePlate ? ` (${v.licensePlate})` : ""}`,
+  }));
+  const organizationId = authContext?.organizationId || "";
+
+  // Fetch team members and features
+  const membership = session?.user?.id
+    ? await getCachedMembership(session.user.id)
+    : null;
+  const orgId = membership?.organizationId;
+
+  const [members, currentUser, features] = await Promise.all([
+    orgId
+      ? db.organizationMember.findMany({
+          where: { organizationId: orgId },
+          select: { id: true, user: { select: { name: true } } },
+        })
+      : Promise.resolve([]),
+    session?.user?.id
+      ? db.user.findUnique({
+          where: { id: session.user.id },
+          select: { name: true },
+        })
+      : Promise.resolve(null),
+    orgId ? getFeatures(orgId) : Promise.resolve(null),
+  ]);
+
+  const teamMembers = members.map((m) => ({ id: m.id, name: m.user.name }));
+  const currentUserName = currentUser?.name || "";
+
+  const initialData = {
+    id: record.id,
+    title: record.title,
+    description: record.description || "",
+    type: record.type,
+    status: record.status,
+    mileage: record.mileage,
+    serviceDate: new Date(record.serviceDate).toISOString().split("T")[0],
+    techName: record.techName || "",
+    diagnosticNotes: record.diagnosticNotes || "",
+    invoiceNotes: record.invoiceNotes || "",
+    invoiceNumber: record.invoiceNumber || "",
+    partItems: record.partItems.map((p) => ({
+      partNumber: p.partNumber || "",
+      name: p.name,
+      quantity: p.quantity,
+      unitPrice: p.unitPrice,
+      total: p.total,
+    })),
+    laborItems: record.laborItems.map((l) => ({
+      description: l.description,
+      hours: l.hours,
+      rate: l.rate,
+      total: l.total,
+    })),
+    attachments: [],
+    subtotal: record.subtotal,
+    taxRate: record.taxRate,
+    taxAmount: record.taxAmount,
+    totalAmount: record.totalAmount,
+    discountType: record.discountType || undefined,
+    discountValue: record.discountValue,
+    discountAmount: record.discountAmount,
+  };
+
+  // Prepare media attachments for managers
+  // The Prisma query returns includeInInvoice on each attachment; cast to include it
+  const allAttachments = record.attachments as (typeof record.attachments[number] & { includeInInvoice: boolean })[] || [];
+  const imageAttachmentsForManager = allAttachments
+    .filter((a) => a.category === "image")
+    .map((a) => ({ ...a, includeInInvoice: a.includeInInvoice ?? true }));
+  const videoAttachments = allAttachments
+    .filter((a) => a.category === "video")
+    .map((a) => ({ ...a, includeInInvoice: a.includeInInvoice ?? true }));
+  const documentAttachments = allAttachments
+    .filter((a) => a.category === "document" || a.category === "diagnostic")
+    .map((a) => ({ ...a, includeInInvoice: a.includeInInvoice ?? true }));
+
+  const vehicleName = `${record.vehicle.year} ${record.vehicle.make} ${record.vehicle.model}`;
 
   return (
     <div className="flex h-svh flex-col overflow-hidden">
       <PageHeader />
-      <ServiceDetailClient record={result.data} vehicleId={id} organizationId={authContext?.organizationId || ""} currencyCode={currencyCode} unitSystem={unitSystem} />
+      <ServicePageClient
+        record={result.data}
+        vehicleId={id}
+        organizationId={organizationId}
+        currencyCode={currencyCode}
+        unitSystem={unitSystem}
+        defaultTaxRate={defaultTaxRate}
+        taxEnabled={taxEnabled}
+        defaultLaborRate={defaultLaborRate}
+        initialData={initialData}
+        inventoryParts={inventoryParts}
+        vehicles={vehicles}
+        teamMembers={teamMembers}
+        currentUserName={currentUserName}
+        imageAttachmentsForManager={imageAttachmentsForManager}
+        videoAttachments={videoAttachments}
+        documentAttachments={documentAttachments}
+        maxImagesPerService={features?.maxImagesPerService ?? 999999}
+        maxDiagnosticsPerService={features?.maxDiagnosticsPerService ?? 999999}
+        maxDocumentsPerService={features?.maxDocumentsPerService ?? 999999}
+      />
     </div>
   );
 }

+ 1 - 1
src/app/(authenticated)/vehicles/[id]/service/new/page.tsx

@@ -10,7 +10,7 @@ export default async function NewServicePage({
   const result = await createDraftServiceRecord(id);
 
   if (result.success && result.data?.id) {
-    redirect(`/vehicles/${id}/service/${result.data.id}/edit`);
+    redirect(`/vehicles/${id}/service/${result.data.id}`);
   }
 
   return (

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

@@ -88,17 +88,6 @@ export function PageHeader() {
     else if (/^\/quotes\/[^/]+$/.test(pathname)) {
       segments = [{ label: 'Quotes', href: '/quotes' }, { label: 'Quote Details' }]
     }
-    // /vehicles/[id]/service/[serviceId]/edit
-    else if (/^\/vehicles\/[^/]+\/service\/[^/]+\/edit$/.test(pathname)) {
-      const parts = pathname.split('/')
-      const vehicleId = parts[2]
-      const serviceId = parts[4]
-      segments = [
-        { label: 'Vehicles', href: '/vehicles' },
-        { label: 'Service Details', href: `/vehicles/${vehicleId}/service/${serviceId}` },
-        { label: 'Edit' },
-      ]
-    }
     // /vehicles/[id]/service/new
     else if (/^\/vehicles\/[^/]+\/service\/new$/.test(pathname)) {
       const vehicleId = pathname.split('/')[2]

+ 0 - 48
src/features/vehicles/Components/service-detail/LaborTable.tsx

@@ -1,48 +0,0 @@
-"use client";
-
-import { formatCurrency } from "@/lib/format";
-import type { LaborItem } from "./types";
-
-interface LaborTableProps {
-  laborItems: LaborItem[];
-  laborSubtotal: number;
-  currencyCode: string;
-}
-
-export function LaborTable({ laborItems, laborSubtotal, currencyCode }: LaborTableProps) {
-  if (laborItems.length === 0) return null;
-
-  return (
-    <div className="rounded-lg border p-3">
-      <h3 className="mb-2 text-sm font-semibold">Labor ({laborItems.length})</h3>
-      <div className="overflow-x-auto">
-        <table className="w-full text-sm">
-          <thead>
-            <tr className="border-b text-left text-xs text-muted-foreground">
-              <th className="pb-1.5 font-medium" style={{ width: "40%" }}>Description</th>
-              <th className="pb-1.5 text-right font-medium">Hours</th>
-              <th className="pb-1.5 text-right font-medium">Rate</th>
-              <th className="pb-1.5 text-right font-medium">Total</th>
-            </tr>
-          </thead>
-          <tbody className="divide-y">
-            {laborItems.map((labor) => (
-              <tr key={labor.id}>
-                <td className="py-1.5 whitespace-pre-wrap">{labor.description}</td>
-                <td className="py-1.5 text-right">{labor.hours}</td>
-                <td className="py-1.5 text-right">{formatCurrency(labor.rate, currencyCode)}/hr</td>
-                <td className="py-1.5 text-right font-medium">{formatCurrency(labor.total, currencyCode)}</td>
-              </tr>
-            ))}
-          </tbody>
-          <tfoot>
-            <tr className="border-t">
-              <td colSpan={3} className="pt-1.5 text-right text-xs font-medium">Labor Subtotal</td>
-              <td className="pt-1.5 text-right text-sm font-bold">{formatCurrency(laborSubtotal, currencyCode)}</td>
-            </tr>
-          </tfoot>
-        </table>
-      </div>
-    </div>
-  );
-}

+ 0 - 54
src/features/vehicles/Components/service-detail/PartsTable.tsx

@@ -1,54 +0,0 @@
-"use client";
-
-import { Wrench } from "lucide-react";
-import { formatCurrency } from "@/lib/format";
-import type { PartItem } from "./types";
-
-interface PartsTableProps {
-  parts: PartItem[];
-  partsSubtotal: number;
-  currencyCode: string;
-}
-
-export function PartsTable({ parts, partsSubtotal, currencyCode }: PartsTableProps) {
-  if (parts.length === 0) return null;
-
-  return (
-    <div className="rounded-lg border p-3">
-      <h3 className="mb-2 flex items-center gap-2 text-sm font-semibold">
-        <Wrench className="h-3.5 w-3.5" />
-        Parts ({parts.length})
-      </h3>
-      <div className="overflow-x-auto">
-        <table className="w-full text-sm">
-          <thead>
-            <tr className="border-b text-left text-xs text-muted-foreground">
-              <th className="pb-1.5 font-medium">Part #</th>
-              <th className="pb-1.5 font-medium">Name</th>
-              <th className="pb-1.5 text-right font-medium">Qty</th>
-              <th className="pb-1.5 text-right font-medium">Unit Price</th>
-              <th className="pb-1.5 text-right font-medium">Total</th>
-            </tr>
-          </thead>
-          <tbody className="divide-y">
-            {parts.map((part) => (
-              <tr key={part.id}>
-                <td className="py-1.5 font-mono text-xs">{part.partNumber || "-"}</td>
-                <td className="py-1.5">{part.name}</td>
-                <td className="py-1.5 text-right">{part.quantity}</td>
-                <td className="py-1.5 text-right">{formatCurrency(part.unitPrice, currencyCode)}</td>
-                <td className="py-1.5 text-right font-medium">{formatCurrency(part.total, currencyCode)}</td>
-              </tr>
-            ))}
-          </tbody>
-          <tfoot>
-            <tr className="border-t">
-              <td colSpan={4} className="pt-1.5 text-right text-xs font-medium">Parts Subtotal</td>
-              <td className="pt-1.5 text-right text-sm font-bold">{formatCurrency(partsSubtotal, currencyCode)}</td>
-            </tr>
-          </tfoot>
-        </table>
-      </div>
-    </div>
-  );
-}

+ 0 - 215
src/features/vehicles/Components/service-detail/ServiceDetailClient.tsx

@@ -1,215 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { useRouter } from "next/navigation";
-import { useGlassModal } from "@/components/glass-modal";
-import { useConfirm } from "@/components/confirm-dialog";
-import { toast } from "sonner";
-import { deleteServiceRecord, deleteServiceAttachment, toggleManuallyPaid } from "@/features/vehicles/Actions/serviceActions";
-import { createPayment, deletePayment } from "@/features/payments/Actions/paymentActions";
-import { sendInvoiceEmail } from "@/features/email/Actions/emailActions";
-import { SendEmailDialog } from "@/features/email/Components/SendEmailDialog";
-import { useFormatDate } from "@/lib/use-format-date";
-import type { ServiceDetail } from "./types";
-import { ServiceDetailHeader } from "./ServiceDetailHeader";
-import { PartsTable } from "./PartsTable";
-import { LaborTable } from "./LaborTable";
-import { InvoiceSummary } from "./InvoiceSummary";
-import { PaymentsSection } from "./PaymentsSection";
-import { ServiceSidebar } from "./ServiceSidebar";
-import { ServiceAttachments } from "./ServiceAttachments";
-import { ServiceNotesDisplay } from "./ServiceNotesDisplay";
-import { ImageCarousel } from "./ImageCarousel";
-import { ShareDialog } from "./ShareDialog";
-import { ServiceDetailContent } from "./ServiceDetailContent";
-
-export function ServiceDetailClient({
-  record,
-  vehicleId,
-  organizationId,
-  currencyCode = "USD",
-  unitSystem = "imperial",
-}: {
-  record: ServiceDetail;
-  vehicleId: string;
-  organizationId: string;
-  currencyCode?: string;
-  unitSystem?: "metric" | "imperial";
-}) {
-  const router = useRouter();
-  const { formatDate } = useFormatDate();
-  const modal = useGlassModal();
-  const confirm = useConfirm();
-  const distUnit = unitSystem === "metric" ? "km" : "mi";
-
-  const [downloading, setDownloading] = useState(false);
-  const [deletingAttachment, setDeletingAttachment] = useState<string | null>(null);
-  const [carouselIndex, setCarouselIndex] = useState<number | null>(null);
-  const [paymentLoading, setPaymentLoading] = useState(false);
-  const [deletingPayment, setDeletingPayment] = useState<string | null>(null);
-  const [showShareDialog, setShowShareDialog] = useState(false);
-  const [showEmailDialog, setShowEmailDialog] = useState(false);
-
-  const partsSubtotal = record.partItems.reduce((sum, p) => sum + p.total, 0);
-  const laborSubtotal = record.laborItems.reduce((sum, l) => sum + l.total, 0);
-  const displayTotal = record.totalAmount > 0 ? record.totalAmount : record.cost;
-  const totalPaid = record.payments?.reduce((sum, p) => sum + p.amount, 0) || 0;
-  const balanceDue = displayTotal - totalPaid;
-  const paymentStatus = record.manuallyPaid ? "paid" : totalPaid === 0 ? "unpaid" : balanceDue <= 0 ? "paid" : "partial";
-  const imageAttachments = record.attachments?.filter((a) => a.category === "image") || [];
-  const vehicleName = `${record.vehicle.year} ${record.vehicle.make} ${record.vehicle.model}`;
-
-  const handleDelete = async () => {
-    const ok = await confirm({
-      title: "Delete Service Record",
-      description: "This will permanently delete this service record and all associated data. This cannot be undone.",
-      confirmLabel: "Delete", destructive: true,
-    });
-    if (!ok) return;
-    const result = await deleteServiceRecord(record.id);
-    if (result.success) { router.push(`/vehicles/${vehicleId}`); router.refresh(); }
-    else modal.open("error", "Error", result.error || "Failed to delete");
-  };
-
-  const handleDownloadPDF = async () => {
-    setDownloading(true);
-    try {
-      const res = await fetch(`/api/services/${record.id}/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 = res.headers.get("Content-Disposition")?.match(/filename="(.+)"/)?.[1]
-        || `invoice-${record.invoiceNumber || record.id}.pdf`;
-      a.click();
-      URL.revokeObjectURL(url);
-    } catch { modal.open("error", "Error", "Failed to generate PDF invoice"); }
-    setDownloading(false);
-  };
-
-  const handleDeleteAttachment = async (id: string) => {
-    const ok = await confirm({
-      title: "Delete Attachment",
-      description: "This will permanently delete this attachment. This cannot be undone.",
-      confirmLabel: "Delete", destructive: true,
-    });
-    if (!ok) return;
-    setDeletingAttachment(id);
-    const result = await deleteServiceAttachment(id);
-    if (result.success) { toast.success("Attachment deleted"); router.refresh(); }
-    else modal.open("error", "Error", result.error || "Failed to delete attachment");
-    setDeletingAttachment(null);
-  };
-
-  const handleCreatePayment = async (data: { amount: number; date: string; method: string; note?: string }) => {
-    setPaymentLoading(true);
-    const result = await createPayment({ serviceRecordId: record.id, ...data });
-    setPaymentLoading(false);
-    if (result.success) { toast.success("Payment recorded"); router.refresh(); return true; }
-    modal.open("error", "Error", result.error || "Failed to record payment");
-    return false;
-  };
-
-  const handleTogglePaid = async () => {
-    setPaymentLoading(true);
-    const result = await toggleManuallyPaid(record.id);
-    setPaymentLoading(false);
-    if (result.success) {
-      toast.success(result.data?.manuallyPaid ? "Marked as paid" : "Marked as unpaid");
-      router.refresh();
-    } else {
-      modal.open("error", "Error", result.error || "Failed to update payment status");
-    }
-  };
-
-  const handleDeletePayment = async (id: string) => {
-    const ok = await confirm({
-      title: "Delete Payment",
-      description: "This will remove this payment record.",
-      confirmLabel: "Delete", destructive: true,
-    });
-    if (!ok) return;
-    setDeletingPayment(id);
-    const result = await deletePayment(id);
-    if (result.success) { toast.success("Payment deleted"); router.refresh(); }
-    else modal.open("error", "Error", result.error || "Failed to delete payment");
-    setDeletingPayment(null);
-  };
-
-  return (
-    <div className="flex min-h-0 flex-1 flex-col">
-      <ServiceDetailHeader
-        vehicleId={vehicleId} recordId={record.id} title={record.title}
-        status={record.status} serviceDate={formatDate(new Date(record.serviceDate))}
-        shopName={record.shopName} techName={record.techName} paymentStatus={paymentStatus}
-        downloading={downloading} onDownloadPDF={handleDownloadPDF} onDelete={handleDelete}
-        onShowEmail={() => setShowEmailDialog(true)} onShowShare={() => setShowShareDialog(true)}
-      />
-      <ServiceDetailContent
-        leftColumn={
-          <>
-            <PartsTable parts={record.partItems} partsSubtotal={partsSubtotal} currencyCode={currencyCode} />
-            <LaborTable laborItems={record.laborItems} laborSubtotal={laborSubtotal} currencyCode={currencyCode} />
-            {record.partItems.length === 0 && record.laborItems.length === 0 && (record.parts || record.laborHours) && (
-              <div className="rounded-lg border p-3">
-                <h3 className="mb-2 text-sm font-semibold">Service Details</h3>
-                <div className="space-y-1 text-sm">
-                  {record.parts && <div><span className="font-medium text-muted-foreground">Parts: </span>{record.parts}</div>}
-                  {record.laborHours && <div><span className="font-medium text-muted-foreground">Labor Hours: </span>{record.laborHours}h</div>}
-                </div>
-              </div>
-            )}
-            <InvoiceSummary
-              hasPartItems={record.partItems.length > 0} hasLaborItems={record.laborItems.length > 0}
-              partsSubtotal={partsSubtotal} laborSubtotal={laborSubtotal} subtotal={record.subtotal}
-              discountAmount={record.discountAmount} discountType={record.discountType}
-              discountValue={record.discountValue} taxRate={record.taxRate} taxAmount={record.taxAmount}
-              displayTotal={displayTotal} totalPaid={totalPaid} balanceDue={balanceDue}
-              hasPayments={(record.payments?.length ?? 0) > 0} currencyCode={currencyCode}
-            />
-            <PaymentsSection
-              payments={record.payments || []} paymentStatus={paymentStatus}
-              manuallyPaid={record.manuallyPaid}
-              totalPaid={totalPaid} displayTotal={displayTotal} balanceDue={balanceDue}
-              currencyCode={currencyCode} onCreatePayment={handleCreatePayment}
-              onDeletePayment={handleDeletePayment} onTogglePaid={handleTogglePaid}
-              paymentLoading={paymentLoading} deletingPayment={deletingPayment}
-            />
-            <ServiceNotesDisplay
-              invoiceNotes={record.invoiceNotes}
-              diagnosticNotes={record.diagnosticNotes}
-              description={record.description}
-            />
-          </>
-        }
-        rightColumn={
-          <>
-            <ServiceSidebar
-              recordId={record.id} vehicle={record.vehicle} vehicleName={vehicleName}
-              distUnit={distUnit} mileage={record.mileage}
-            />
-            <ServiceAttachments
-              attachments={record.attachments || []} imageAttachments={imageAttachments}
-              onImageClick={setCarouselIndex} onDeleteAttachment={handleDeleteAttachment}
-              deletingAttachment={deletingAttachment}
-            />
-          </>
-        }
-      />
-      <ImageCarousel
-        images={imageAttachments} currentIndex={carouselIndex}
-        onClose={() => setCarouselIndex(null)} onChangeIndex={setCarouselIndex}
-      />
-      <SendEmailDialog
-        open={showEmailDialog} onOpenChange={setShowEmailDialog}
-        defaultEmail={record.vehicle.customer?.email || ""} entityLabel="Invoice"
-        onSend={async (email, message) => sendInvoiceEmail({ serviceRecordId: record.id, recipientEmail: email, message })}
-      />
-      <ShareDialog
-        open={showShareDialog} onOpenChange={setShowShareDialog}
-        recordId={record.id} organizationId={organizationId} initialToken={record.publicToken}
-      />
-    </div>
-  );
-}

+ 0 - 69
src/features/vehicles/Components/service-edit/EditActions.tsx

@@ -1,69 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { usePathname } from "next/navigation";
-import { Button } from "@/components/ui/button";
-import { useGlassModal } from "@/components/glass-modal";
-import { toast } from "sonner";
-import { Download, Loader2, Save } from "lucide-react";
-
-interface EditActionsProps {
-  serviceRecordId: string;
-}
-
-export function EditActions({ serviceRecordId }: EditActionsProps) {
-  const [downloading, setDownloading] = useState(false);
-  const modal = useGlassModal();
-  const pathname = usePathname();
-  const isDetailsTab = pathname.endsWith("/edit");
-
-  const handleDownloadPDF = async () => {
-    setDownloading(true);
-    try {
-      const res = await fetch(`/api/services/${serviceRecordId}/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 =
-        res.headers.get("Content-Disposition")?.match(/filename="(.+)"/)?.[1] ||
-        `invoice-${serviceRecordId}.pdf`;
-      a.click();
-      URL.revokeObjectURL(url);
-    } catch {
-      modal.open("error", "Error", "Failed to generate PDF invoice");
-    }
-    setDownloading(false);
-  };
-
-  return (
-    <div className="flex items-center gap-2">
-      {isDetailsTab ? (
-        <Button type="submit" form="service-record-form" size="sm">
-          <Save className="mr-1 h-3.5 w-3.5" />
-          Update
-        </Button>
-      ) : (
-        <Button size="sm" onClick={() => toast.success("All changes saved")}>
-          <Save className="mr-1 h-3.5 w-3.5" />
-          Done
-        </Button>
-      )}
-      <Button
-        type="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 Invoice
-      </Button>
-    </div>
-  );
-}

+ 0 - 44
src/features/vehicles/Components/service-edit/EditNav.tsx

@@ -1,44 +0,0 @@
-"use client";
-
-import Link from "next/link";
-import { usePathname } from "next/navigation";
-import { cn } from "@/lib/utils";
-
-interface EditNavProps {
-  vehicleId: string;
-  serviceId: string;
-}
-
-export function EditNav({ vehicleId, serviceId }: EditNavProps) {
-  const pathname = usePathname();
-  const base = `/vehicles/${vehicleId}/service/${serviceId}/edit`;
-
-  const tabs = [
-    { label: "Details", href: base },
-    { label: "Images", href: `${base}/images` },
-    { label: "Video", href: `${base}/video` },
-    { label: "Documents", href: `${base}/documents` },
-  ];
-
-  return (
-    <nav className="flex gap-1 border-b">
-      {tabs.map((tab) => {
-        const isActive = pathname === tab.href;
-        return (
-          <Link
-            key={tab.href}
-            href={tab.href}
-            className={cn(
-              "px-3 py-1.5 text-sm font-medium transition-colors -mb-px border-b-2",
-              isActive
-                ? "border-primary text-foreground"
-                : "border-transparent text-muted-foreground hover:text-foreground hover:border-muted-foreground/50"
-            )}
-          >
-            {tab.label}
-          </Link>
-        );
-      })}
-    </nav>
-  );
-}

+ 0 - 225
src/features/vehicles/Components/service-edit/ServiceRecordForm.tsx

@@ -1,225 +0,0 @@
-'use client'
-
-import { useState, useCallback, useRef } from 'react'
-import { useRouter } from 'next/navigation'
-import { toast } from 'sonner'
-import { useGlassModal } from '@/components/glass-modal'
-import { updateServiceRecord } from '@/features/vehicles/Actions/serviceActions'
-import type { ServicePartInput, ServiceLaborInput } from '@/features/vehicles/Schema/serviceSchema'
-import { ServiceDetailContent } from '../service-detail/ServiceDetailContent'
-import { BasicInfoSection } from './BasicInfoSection'
-import { PartsEditor } from './PartsEditor'
-import { LaborEditor } from './LaborEditor'
-import { TotalsSection } from './TotalsSection'
-import { NotesSection } from './NotesSection'
-import { InventoryPickerDialog } from './InventoryPickerDialog'
-import type { ServiceRecordFormProps } from './form-types'
-
-export function ServiceRecordForm({
-  vehicleId,
-  vehicleName,
-  defaultTaxRate = 0,
-  taxEnabled = true,
-  defaultLaborRate = 0,
-  currencyCode = 'USD',
-  initialData,
-  inventoryParts = [],
-  vehicles = [],
-  teamMembers = [],
-  currentUserName = '',
-}: ServiceRecordFormProps) {
-  const router = useRouter()
-  const modal = useGlassModal()
-  const [loading, setLoading] = useState(false)
-  const [selectedVehicleId, setSelectedVehicleId] = useState(vehicleId)
-  const [vehicleOpen, setVehicleOpen] = useState(false)
-  const [techName, setTechName] = useState(initialData.techName || currentUserName)
-  const [techOpen, setTechOpen] = useState(false)
-  const [type, setType] = useState(initialData.type || 'maintenance')
-  const [status, setStatus] = useState(initialData.status || 'completed')
-  const [partItems, setPartItems] = useState<ServicePartInput[]>(initialData.partItems || [])
-  const [laborItems, setLaborItems] = useState<ServiceLaborInput[]>(initialData.laborItems || [])
-  const [taxRate, setTaxRate] = useState(initialData.taxRate ?? defaultTaxRate)
-  const [discountType, setDiscountType] = useState<string>(initialData.discountType || 'none')
-  const [discountValue, setDiscountValue] = useState(initialData.discountValue ?? 0)
-  const [showInventoryPicker, setShowInventoryPicker] = useState(false)
-  const notesRef = useRef({
-    invoiceNotes: initialData.invoiceNotes || '',
-    diagnosticNotes: initialData.diagnosticNotes || '',
-    description: initialData.description || '',
-  })
-
-  const handleNotesChange = useCallback(
-    (field: 'invoiceNotes' | 'diagnosticNotes' | 'description', value: string) => {
-      notesRef.current[field] = value
-    },
-    []
-  )
-
-  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 updatePart = useCallback(
-    (index: number, field: keyof ServicePartInput, 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 ServiceLaborInput, 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()
-    setLoading(true)
-
-    const formData = new FormData(e.currentTarget)
-    const payload = {
-      id: initialData.id,
-      vehicleId: selectedVehicleId,
-      title: formData.get('title') as string,
-      description: notesRef.current.description || undefined,
-      type,
-      status,
-      cost: totalAmount,
-      mileage: Number(formData.get('mileage')) || undefined,
-      serviceDate: (formData.get('serviceDate') as string) || new Date().toISOString(),
-      techName: techName || undefined,
-      diagnosticNotes: notesRef.current.diagnosticNotes || undefined,
-      invoiceNotes: notesRef.current.invoiceNotes || undefined,
-      invoiceNumber: (formData.get('invoiceNumber') as string) || undefined,
-      partItems: partItems.filter((p) => p.name),
-      laborItems: laborItems.filter((l) => l.description),
-      subtotal,
-      taxRate,
-      taxAmount,
-      totalAmount,
-      discountType: discountType === 'none' ? undefined : discountType,
-      discountValue,
-      discountAmount,
-    }
-
-    const result = await updateServiceRecord(payload)
-
-    if (result.success) {
-      toast.success('Service record updated')
-      if (selectedVehicleId !== vehicleId) {
-        router.push(`/vehicles/${selectedVehicleId}/service/${initialData.id}`)
-      } else {
-        router.refresh()
-      }
-    } else {
-      modal.open('error', 'Error', result.error || 'Failed to update service record')
-    }
-
-    setLoading(false)
-  }
-
-  const leftColumn = (
-    <div className="space-y-3">
-      <PartsEditor
-        partItems={partItems}
-        setPartItems={setPartItems}
-        updatePart={updatePart}
-        partsSubtotal={partsSubtotal}
-        currencyCode={currencyCode}
-        hasInventory={inventoryParts.length > 0}
-        onOpenInventory={() => setShowInventoryPicker(true)}
-      />
-      <LaborEditor
-        laborItems={laborItems}
-        setLaborItems={setLaborItems}
-        updateLabor={updateLabor}
-        laborSubtotal={laborSubtotal}
-        currencyCode={currencyCode}
-        defaultLaborRate={defaultLaborRate}
-      />
-      <NotesSection initialData={initialData} onNotesChange={handleNotesChange} />
-    </div>
-  )
-
-  const rightColumn = (
-    <div className="space-y-3">
-      <BasicInfoSection
-        initialData={initialData}
-        vehicleId={vehicleId}
-        vehicleName={vehicleName}
-        selectedVehicleId={selectedVehicleId}
-        setSelectedVehicleId={setSelectedVehicleId}
-        vehicles={vehicles}
-        vehicleOpen={vehicleOpen}
-        setVehicleOpen={setVehicleOpen}
-        type={type}
-        setType={setType}
-        status={status}
-        setStatus={setStatus}
-        techName={techName}
-        setTechName={setTechName}
-        techOpen={techOpen}
-        setTechOpen={setTechOpen}
-        teamMembers={teamMembers}
-      />
-      <TotalsSection
-        partsSubtotal={partsSubtotal}
-        laborSubtotal={laborSubtotal}
-        subtotal={subtotal}
-        discountType={discountType}
-        setDiscountType={setDiscountType}
-        discountValue={discountValue}
-        setDiscountValue={setDiscountValue}
-        discountAmount={discountAmount}
-        taxEnabled={taxEnabled}
-        taxRate={taxRate}
-        setTaxRate={setTaxRate}
-        taxAmount={taxAmount}
-        totalAmount={totalAmount}
-        currencyCode={currencyCode}
-      />
-    </div>
-  )
-
-  return (
-    <>
-      <form id="service-record-form" onSubmit={handleSubmit} className="flex h-full flex-col">
-        <ServiceDetailContent leftColumn={leftColumn} rightColumn={rightColumn} />
-      </form>
-
-      <InventoryPickerDialog
-        open={showInventoryPicker}
-        onOpenChange={setShowInventoryPicker}
-        inventoryParts={inventoryParts}
-        currencyCode={currencyCode}
-        onSelectPart={(part) => setPartItems((prev) => [...prev, part])}
-      />
-    </>
-  )
-}

+ 547 - 0
src/features/vehicles/Components/service-page/ServicePageClient.tsx

@@ -0,0 +1,547 @@
+'use client'
+
+import { useState, useCallback, useRef } from 'react'
+import { useRouter } from 'next/navigation'
+import { toast } from 'sonner'
+import { useGlassModal } from '@/components/glass-modal'
+import { useConfirm } from '@/components/confirm-dialog'
+import { updateServiceRecord, deleteServiceRecord, deleteServiceAttachment, toggleManuallyPaid } from '@/features/vehicles/Actions/serviceActions'
+import { createPayment, deletePayment } from '@/features/payments/Actions/paymentActions'
+import { sendInvoiceEmail } from '@/features/email/Actions/emailActions'
+import { SendEmailDialog } from '@/features/email/Components/SendEmailDialog'
+import type { ServicePartInput, ServiceLaborInput } from '@/features/vehicles/Schema/serviceSchema'
+import type { ServiceDetail } from '../service-detail/types'
+import type { InitialData, InventoryPartOption, VehicleOption, TeamMemberOption } from '../service-edit/form-types'
+
+import { ServiceDetailContent } from '../service-detail/ServiceDetailContent'
+import { InvoiceSummary } from '../service-detail/InvoiceSummary'
+import { PaymentsSection } from '../service-detail/PaymentsSection'
+import { ServiceSidebar } from '../service-detail/ServiceSidebar'
+import { ServiceAttachments } from '../service-detail/ServiceAttachments'
+import { ImageCarousel } from '../service-detail/ImageCarousel'
+import { ShareDialog } from '../service-detail/ShareDialog'
+
+import { BasicInfoSection } from '../service-edit/BasicInfoSection'
+import { PartsEditor } from '../service-edit/PartsEditor'
+import { LaborEditor } from '../service-edit/LaborEditor'
+import { TotalsSection } from '../service-edit/TotalsSection'
+import { NotesSection } from '../service-edit/NotesSection'
+import { InventoryPickerDialog } from '../service-edit/InventoryPickerDialog'
+
+import { ServiceImagesManager } from '../service-images-manager'
+import { ServiceVideoManager } from '../service-video-manager'
+import { ServiceDocumentsManager } from '../service-documents-manager'
+
+import { UnifiedServiceHeader, type ServiceTab } from './UnifiedServiceHeader'
+
+interface Attachment {
+  id: string
+  fileName: string
+  fileUrl: string
+  fileType: string
+  fileSize: number
+  category: string
+  description: string | null
+  includeInInvoice: boolean
+  createdAt: Date
+}
+
+export interface ServicePageClientProps {
+  record: ServiceDetail
+  vehicleId: string
+  organizationId: string
+  currencyCode: string
+  unitSystem: 'metric' | 'imperial'
+  defaultTaxRate: number
+  taxEnabled: boolean
+  defaultLaborRate: number
+  initialData: InitialData
+  inventoryParts: InventoryPartOption[]
+  vehicles: VehicleOption[]
+  teamMembers: TeamMemberOption[]
+  currentUserName: string
+  // Media data
+  imageAttachmentsForManager: Attachment[]
+  videoAttachments: Attachment[]
+  documentAttachments: Attachment[]
+  maxImagesPerService: number
+  maxDiagnosticsPerService: number
+  maxDocumentsPerService: number
+}
+
+export function ServicePageClient({
+  record,
+  vehicleId,
+  organizationId,
+  currencyCode,
+  unitSystem,
+  defaultTaxRate,
+  taxEnabled,
+  defaultLaborRate,
+  initialData,
+  inventoryParts,
+  vehicles,
+  teamMembers,
+  currentUserName,
+  imageAttachmentsForManager,
+  videoAttachments,
+  documentAttachments,
+  maxImagesPerService,
+  maxDiagnosticsPerService,
+  maxDocumentsPerService,
+}: ServicePageClientProps) {
+  const router = useRouter()
+  const modal = useGlassModal()
+  const confirm = useConfirm()
+  const distUnit = unitSystem === 'metric' ? 'km' : 'mi'
+
+  // Tab state
+  const [activeTab, setActiveTab] = useState<ServiceTab>('details')
+
+  // Form state (from ServiceRecordForm)
+  const [loading, setLoading] = useState(false)
+  const [selectedVehicleId, setSelectedVehicleId] = useState(vehicleId)
+  const [vehicleOpen, setVehicleOpen] = useState(false)
+  const [techName, setTechName] = useState(initialData.techName || currentUserName)
+  const [techOpen, setTechOpen] = useState(false)
+  const [type, setType] = useState(initialData.type || 'maintenance')
+  const [status, setStatus] = useState(initialData.status || 'completed')
+  const [partItems, setPartItems] = useState<ServicePartInput[]>(initialData.partItems || [])
+  const [laborItems, setLaborItems] = useState<ServiceLaborInput[]>(initialData.laborItems || [])
+  const [taxRate, setTaxRate] = useState(initialData.taxRate ?? defaultTaxRate)
+  const [discountType, setDiscountType] = useState<string>(initialData.discountType || 'none')
+  const [discountValue, setDiscountValue] = useState(initialData.discountValue ?? 0)
+  const [showInventoryPicker, setShowInventoryPicker] = useState(false)
+  const notesRef = useRef({
+    invoiceNotes: initialData.invoiceNotes || '',
+    diagnosticNotes: initialData.diagnosticNotes || '',
+    description: initialData.description || '',
+  })
+
+  const handleNotesChange = useCallback(
+    (field: 'invoiceNotes' | 'diagnosticNotes' | 'description', value: string) => {
+      notesRef.current[field] = value
+    },
+    []
+  )
+
+  // Computed totals
+  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
+
+  // Detail-page state
+  const [downloading, setDownloading] = useState(false)
+  const [deletingAttachment, setDeletingAttachment] = useState<string | null>(null)
+  const [carouselIndex, setCarouselIndex] = useState<number | null>(null)
+  const [paymentLoading, setPaymentLoading] = useState(false)
+  const [deletingPayment, setDeletingPayment] = useState<string | null>(null)
+  const [showShareDialog, setShowShareDialog] = useState(false)
+  const [showEmailDialog, setShowEmailDialog] = useState(false)
+
+  const displayTotal = totalAmount > 0 ? totalAmount : record.cost
+  const totalPaid = record.payments?.reduce((sum, p) => sum + p.amount, 0) || 0
+  const balanceDue = displayTotal - totalPaid
+  const paymentStatus = record.manuallyPaid
+    ? 'paid'
+    : totalPaid === 0
+      ? 'unpaid'
+      : balanceDue <= 0
+        ? 'paid'
+        : 'partial'
+  const imageAttachments = record.attachments?.filter((a) => a.category === 'image') || []
+  const vehicleName = `${record.vehicle.year} ${record.vehicle.make} ${record.vehicle.model}`
+
+  // Part/labor update helpers
+  const updatePart = useCallback(
+    (index: number, field: keyof ServicePartInput, 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 ServiceLaborInput, 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
+      })
+    },
+    []
+  )
+
+  // Form submit
+  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
+    e.preventDefault()
+    setLoading(true)
+
+    const formData = new FormData(e.currentTarget)
+    const payload = {
+      id: initialData.id,
+      vehicleId: selectedVehicleId,
+      title: formData.get('title') as string,
+      description: notesRef.current.description || undefined,
+      type,
+      status,
+      cost: totalAmount,
+      mileage: Number(formData.get('mileage')) || undefined,
+      serviceDate: (formData.get('serviceDate') as string) || new Date().toISOString(),
+      techName: techName || undefined,
+      diagnosticNotes: notesRef.current.diagnosticNotes || undefined,
+      invoiceNotes: notesRef.current.invoiceNotes || undefined,
+      invoiceNumber: (formData.get('invoiceNumber') as string) || undefined,
+      partItems: partItems.filter((p) => p.name),
+      laborItems: laborItems.filter((l) => l.description),
+      subtotal,
+      taxRate,
+      taxAmount,
+      totalAmount,
+      discountType: discountType === 'none' ? undefined : discountType,
+      discountValue,
+      discountAmount,
+    }
+
+    const result = await updateServiceRecord(payload)
+
+    if (result.success) {
+      toast.success('Service record updated')
+      if (selectedVehicleId !== vehicleId) {
+        router.push(`/vehicles/${selectedVehicleId}/service/${initialData.id}`)
+      } else {
+        router.refresh()
+      }
+    } else {
+      modal.open('error', 'Error', result.error || 'Failed to update service record')
+    }
+
+    setLoading(false)
+  }
+
+  // Detail actions
+  const handleDelete = async () => {
+    const ok = await confirm({
+      title: 'Delete Service Record',
+      description:
+        'This will permanently delete this service record and all associated data. This cannot be undone.',
+      confirmLabel: 'Delete',
+      destructive: true,
+    })
+    if (!ok) return
+    const result = await deleteServiceRecord(record.id)
+    if (result.success) {
+      router.push(`/vehicles/${vehicleId}`)
+      router.refresh()
+    } else {
+      modal.open('error', 'Error', result.error || 'Failed to delete')
+    }
+  }
+
+  const handleDownloadPDF = async () => {
+    setDownloading(true)
+    try {
+      const res = await fetch(`/api/services/${record.id}/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 =
+        res.headers.get('Content-Disposition')?.match(/filename="(.+)"/)?.[1] ||
+        `invoice-${record.invoiceNumber || record.id}.pdf`
+      a.click()
+      URL.revokeObjectURL(url)
+    } catch {
+      modal.open('error', 'Error', 'Failed to generate PDF invoice')
+    }
+    setDownloading(false)
+  }
+
+  const handleDeleteAttachment = async (id: string) => {
+    const ok = await confirm({
+      title: 'Delete Attachment',
+      description: 'This will permanently delete this attachment. This cannot be undone.',
+      confirmLabel: 'Delete',
+      destructive: true,
+    })
+    if (!ok) return
+    setDeletingAttachment(id)
+    const result = await deleteServiceAttachment(id)
+    if (result.success) {
+      toast.success('Attachment deleted')
+      router.refresh()
+    } else {
+      modal.open('error', 'Error', result.error || 'Failed to delete attachment')
+    }
+    setDeletingAttachment(null)
+  }
+
+  const handleCreatePayment = async (data: {
+    amount: number
+    date: string
+    method: string
+    note?: string
+  }) => {
+    setPaymentLoading(true)
+    const result = await createPayment({ serviceRecordId: record.id, ...data })
+    setPaymentLoading(false)
+    if (result.success) {
+      toast.success('Payment recorded')
+      router.refresh()
+      return true
+    }
+    modal.open('error', 'Error', result.error || 'Failed to record payment')
+    return false
+  }
+
+  const handleTogglePaid = async () => {
+    setPaymentLoading(true)
+    const result = await toggleManuallyPaid(record.id)
+    setPaymentLoading(false)
+    if (result.success) {
+      toast.success(result.data?.manuallyPaid ? 'Marked as paid' : 'Marked as unpaid')
+      router.refresh()
+    } else {
+      modal.open('error', 'Error', result.error || 'Failed to update payment status')
+    }
+  }
+
+  const handleDeletePayment = async (id: string) => {
+    const ok = await confirm({
+      title: 'Delete Payment',
+      description: 'This will remove this payment record.',
+      confirmLabel: 'Delete',
+      destructive: true,
+    })
+    if (!ok) return
+    setDeletingPayment(id)
+    const result = await deletePayment(id)
+    if (result.success) {
+      toast.success('Payment deleted')
+      router.refresh()
+    } else {
+      modal.open('error', 'Error', result.error || 'Failed to delete payment')
+    }
+    setDeletingPayment(null)
+  }
+
+  // Details tab content
+  const detailsLeftColumn = (
+    <div className="space-y-3">
+      <PartsEditor
+        partItems={partItems}
+        setPartItems={setPartItems}
+        updatePart={updatePart}
+        partsSubtotal={partsSubtotal}
+        currencyCode={currencyCode}
+        hasInventory={inventoryParts.length > 0}
+        onOpenInventory={() => setShowInventoryPicker(true)}
+      />
+      <LaborEditor
+        laborItems={laborItems}
+        setLaborItems={setLaborItems}
+        updateLabor={updateLabor}
+        laborSubtotal={laborSubtotal}
+        currencyCode={currencyCode}
+        defaultLaborRate={defaultLaborRate}
+      />
+      <NotesSection initialData={initialData} onNotesChange={handleNotesChange} />
+      <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
+        <PaymentsSection
+          payments={record.payments || []}
+          paymentStatus={paymentStatus}
+          manuallyPaid={record.manuallyPaid}
+          totalPaid={totalPaid}
+          displayTotal={displayTotal}
+          balanceDue={balanceDue}
+          currencyCode={currencyCode}
+          onCreatePayment={handleCreatePayment}
+          onDeletePayment={handleDeletePayment}
+          onTogglePaid={handleTogglePaid}
+          paymentLoading={paymentLoading}
+          deletingPayment={deletingPayment}
+        />
+        <InvoiceSummary
+          hasPartItems={partItems.length > 0}
+          hasLaborItems={laborItems.length > 0}
+          partsSubtotal={partsSubtotal}
+          laborSubtotal={laborSubtotal}
+          subtotal={subtotal}
+          discountAmount={discountAmount}
+          discountType={discountType === 'none' ? null : discountType}
+          discountValue={discountValue}
+          taxRate={taxRate}
+          taxAmount={taxAmount}
+          displayTotal={displayTotal}
+          totalPaid={totalPaid}
+          balanceDue={balanceDue}
+          hasPayments={(record.payments?.length ?? 0) > 0}
+          currencyCode={currencyCode}
+        />
+      </div>
+    </div>
+  )
+
+  const detailsRightColumn = (
+    <div className="space-y-3">
+      <BasicInfoSection
+        initialData={initialData}
+        vehicleId={vehicleId}
+        vehicleName={vehicleName}
+        selectedVehicleId={selectedVehicleId}
+        setSelectedVehicleId={setSelectedVehicleId}
+        vehicles={vehicles}
+        vehicleOpen={vehicleOpen}
+        setVehicleOpen={setVehicleOpen}
+        type={type}
+        setType={setType}
+        status={status}
+        setStatus={setStatus}
+        techName={techName}
+        setTechName={setTechName}
+        techOpen={techOpen}
+        setTechOpen={setTechOpen}
+        teamMembers={teamMembers}
+      />
+      <TotalsSection
+        partsSubtotal={partsSubtotal}
+        laborSubtotal={laborSubtotal}
+        subtotal={subtotal}
+        discountType={discountType}
+        setDiscountType={setDiscountType}
+        discountValue={discountValue}
+        setDiscountValue={setDiscountValue}
+        discountAmount={discountAmount}
+        taxEnabled={taxEnabled}
+        taxRate={taxRate}
+        setTaxRate={setTaxRate}
+        taxAmount={taxAmount}
+        totalAmount={totalAmount}
+        currencyCode={currencyCode}
+      />
+      <ServiceSidebar
+        recordId={record.id}
+        vehicle={record.vehicle}
+        vehicleName={vehicleName}
+        distUnit={distUnit}
+        mileage={record.mileage}
+      />
+      <ServiceAttachments
+        attachments={record.attachments || []}
+        imageAttachments={imageAttachments}
+        onImageClick={setCarouselIndex}
+        onDeleteAttachment={handleDeleteAttachment}
+        deletingAttachment={deletingAttachment}
+      />
+    </div>
+  )
+
+  return (
+    <div className="flex min-h-0 flex-1 flex-col">
+      <UnifiedServiceHeader
+        vehicleId={vehicleId}
+        vehicleName={vehicleName}
+        title={record.title}
+        status={status}
+        paymentStatus={paymentStatus}
+        activeTab={activeTab}
+        onTabChange={setActiveTab}
+        downloading={downloading}
+        saving={loading}
+        onDownloadPDF={handleDownloadPDF}
+        onDelete={handleDelete}
+        onShowEmail={() => setShowEmailDialog(true)}
+        onShowShare={() => setShowShareDialog(true)}
+      />
+
+      {activeTab === 'details' && (
+        <form id="service-record-form" onSubmit={handleSubmit} className="flex min-h-0 flex-1 flex-col">
+          <ServiceDetailContent leftColumn={detailsLeftColumn} rightColumn={detailsRightColumn} />
+        </form>
+      )}
+
+      {activeTab === 'images' && (
+        <div className="flex-1 overflow-y-auto p-4">
+          <ServiceImagesManager
+            serviceRecordId={record.id}
+            initialImages={imageAttachmentsForManager}
+            maxImages={maxImagesPerService}
+          />
+        </div>
+      )}
+
+      {activeTab === 'video' && (
+        <div className="flex-1 overflow-y-auto p-4">
+          <ServiceVideoManager
+            serviceRecordId={record.id}
+            initialVideos={videoAttachments}
+          />
+        </div>
+      )}
+
+      {activeTab === 'documents' && (
+        <div className="flex-1 overflow-y-auto p-4">
+          <ServiceDocumentsManager
+            serviceRecordId={record.id}
+            initialDocuments={documentAttachments}
+            maxDiagnostics={maxDiagnosticsPerService}
+            maxDocuments={maxDocumentsPerService}
+          />
+        </div>
+      )}
+
+      <InventoryPickerDialog
+        open={showInventoryPicker}
+        onOpenChange={setShowInventoryPicker}
+        inventoryParts={inventoryParts}
+        currencyCode={currencyCode}
+        onSelectPart={(part) => setPartItems((prev) => [...prev, part])}
+      />
+
+      <ImageCarousel
+        images={imageAttachments}
+        currentIndex={carouselIndex}
+        onClose={() => setCarouselIndex(null)}
+        onChangeIndex={setCarouselIndex}
+      />
+
+      <SendEmailDialog
+        open={showEmailDialog}
+        onOpenChange={setShowEmailDialog}
+        defaultEmail={record.vehicle.customer?.email || ''}
+        entityLabel="Invoice"
+        onSend={async (email, message) =>
+          sendInvoiceEmail({ serviceRecordId: record.id, recipientEmail: email, message })
+        }
+      />
+
+      <ShareDialog
+        open={showShareDialog}
+        onOpenChange={setShowShareDialog}
+        recordId={record.id}
+        organizationId={organizationId}
+        initialToken={record.publicToken}
+      />
+    </div>
+  )
+}

+ 66 - 28
src/features/vehicles/Components/service-detail/ServiceDetailHeader.tsx → src/features/vehicles/Components/service-page/UnifiedServiceHeader.tsx

@@ -3,46 +3,64 @@
 import Link from 'next/link'
 import { Badge } from '@/components/ui/badge'
 import { Button } from '@/components/ui/button'
-import { ArrowLeft, Download, Globe, Loader2, Mail, Pencil, Trash2 } from 'lucide-react'
-import { statusColors, paymentStatusColors, paymentStatusLabels } from './types'
+import { cn } from '@/lib/utils'
+import {
+  ArrowLeft,
+  Download,
+  Globe,
+  Loader2,
+  Mail,
+  Save,
+  Trash2,
+} from 'lucide-react'
+import { statusColors, paymentStatusColors, paymentStatusLabels } from '../service-detail/types'
 
-interface ServiceDetailHeaderProps {
+export type ServiceTab = 'details' | 'images' | 'video' | 'documents'
+
+interface UnifiedServiceHeaderProps {
   vehicleId: string
-  recordId: string
+  vehicleName: string
   title: string
   status: string
-  serviceDate: string
-  shopName: string | null
-  techName: string | null
   paymentStatus: string
+  activeTab: ServiceTab
+  onTabChange: (tab: ServiceTab) => void
   downloading: boolean
+  saving: boolean
   onDownloadPDF: () => void
   onDelete: () => void
   onShowEmail: () => void
   onShowShare: () => void
 }
 
-export function ServiceDetailHeader({
+const tabs: { label: string; value: ServiceTab }[] = [
+  { label: 'Details', value: 'details' },
+  { label: 'Images', value: 'images' },
+  { label: 'Video', value: 'video' },
+  { label: 'Documents', value: 'documents' },
+]
+
+export function UnifiedServiceHeader({
   vehicleId,
-  recordId,
+  vehicleName,
   title,
   status,
-  serviceDate,
-  shopName,
-  techName,
   paymentStatus,
+  activeTab,
+  onTabChange,
   downloading,
+  saving,
   onDownloadPDF,
   onDelete,
   onShowEmail,
   onShowShare,
-}: ServiceDetailHeaderProps) {
+}: UnifiedServiceHeaderProps) {
   return (
-    <div className="shrink-0 border-b bg-background px-4 pt-2 pb-2">
-      <div className="flex min-w-0 items-center gap-4">
+    <div className="shrink-0 border-b bg-background px-4 pt-2 pb-0">
+      <div className="mb-2 flex items-center justify-between">
         <Link
           href={`/vehicles/${vehicleId}`}
-          className="flex min-w-0 flex-1 items-center gap-3 text-foreground transition-colors hover:text-muted-foreground"
+          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">
@@ -53,25 +71,28 @@ export function ServiceDetailHeader({
               >
                 {paymentStatusLabels[paymentStatus] || 'Unpaid'}
               </Badge>
-              <Badge variant="outline" className={`shrink-0 text-xs ${statusColors[status] || ''}`}>
+              <Badge
+                variant="outline"
+                className={`shrink-0 text-xs ${statusColors[status] || ''}`}
+              >
                 {status}
               </Badge>
               <h1 className="truncate text-lg font-semibold leading-tight">{title}</h1>
             </div>
-            <p className="truncate text-xs text-muted-foreground">
-              {serviceDate}
-              {shopName && ` · ${shopName}`}
-              {techName && ` · Tech: ${techName}`}
-            </p>
+            <p className="truncate text-xs text-muted-foreground">{vehicleName}</p>
           </div>
         </Link>
         <div className="flex shrink-0 items-center gap-2">
-          <Button variant="outline" size="sm" asChild>
-            <Link href={`/vehicles/${vehicleId}/service/${recordId}/edit`}>
-              <Pencil className="mr-1 h-3.5 w-3.5" />
-              Edit
-            </Link>
-          </Button>
+          {activeTab === 'details' && (
+            <Button type="submit" form="service-record-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>
+          )}
           <Button variant="outline" size="sm" onClick={onDownloadPDF} disabled={downloading}>
             {downloading ? (
               <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
@@ -99,6 +120,23 @@ export function ServiceDetailHeader({
           </Button>
         </div>
       </div>
+      <nav className="flex gap-1 border-b">
+        {tabs.map((tab) => (
+          <button
+            key={tab.value}
+            type="button"
+            onClick={() => onTabChange(tab.value)}
+            className={cn(
+              'px-3 py-1.5 text-sm font-medium transition-colors -mb-px border-b-2',
+              activeTab === tab.value
+                ? 'border-primary text-foreground'
+                : 'border-transparent text-muted-foreground hover:text-foreground hover:border-muted-foreground/50'
+            )}
+          >
+            {tab.label}
+          </button>
+        ))}
+      </nav>
     </div>
   )
 }