Jelajahi Sumber

Fix an issue creating inspections (#41)

Bernt Christian Egeland 8 bulan lalu
induk
melakukan
272205cff3

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

@@ -520,7 +520,7 @@ export function DashboardClient({
                     <div
                     <div
                       key={r.id}
                       key={r.id}
                       className="flex items-center justify-between px-5 py-3 cursor-pointer hover:bg-muted/50 transition-colors"
                       className="flex items-center justify-between px-5 py-3 cursor-pointer hover:bg-muted/50 transition-colors"
-                      onClick={() => router.push(`/vehicles/${r.vehicle.id}`)}
+                      onClick={() => router.push(`/vehicles/${r.vehicle.id}?tab=reminders`)}
                     >
                     >
                       <div className="flex items-center gap-3 min-w-0">
                       <div className="flex items-center gap-3 min-w-0">
                         <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${
                         <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${

+ 7 - 1
src/features/inspections/Actions/inspectionActions.ts

@@ -139,13 +139,19 @@ export async function createInspection(input: unknown) {
     });
     });
     if (!template) throw new Error("Template not found");
     if (!template) throw new Error("Template not found");
 
 
+    // Look up technician linked to current user
+    const technician = await db.technician.findFirst({
+      where: { memberId: userId, organizationId, isActive: true },
+      select: { id: true },
+    });
+
     const inspection = await db.$transaction(async (tx) => {
     const inspection = await db.$transaction(async (tx) => {
       const created = await tx.inspection.create({
       const created = await tx.inspection.create({
         data: {
         data: {
           vehicleId: data.vehicleId,
           vehicleId: data.vehicleId,
           templateId: data.templateId,
           templateId: data.templateId,
           mileage: data.mileage,
           mileage: data.mileage,
-          technicianId: userId,
+          technicianId: technician?.id ?? null,
           organizationId,
           organizationId,
         },
         },
       });
       });

+ 59 - 3
src/features/search/Actions/searchActions.ts

@@ -26,7 +26,7 @@ export async function getRecentCustomers() {
 export async function globalSearch(query: string) {
 export async function globalSearch(query: string) {
   return withAuth(async ({ organizationId }) => {
   return withAuth(async ({ organizationId }) => {
     if (!query || query.trim().length < 2) {
     if (!query || query.trim().length < 2) {
-      return { vehicles: [], customers: [], services: [], parts: [], quotes: [] };
+      return { vehicles: [], customers: [], services: [], parts: [], quotes: [], reminders: [], inspections: [] };
     }
     }
 
 
     const q = query.trim();
     const q = query.trim();
@@ -42,7 +42,7 @@ export async function globalSearch(query: string) {
       vehicleOr.push({ year: Number(q) });
       vehicleOr.push({ year: Number(q) });
     }
     }
 
 
-    const [vehicles, customers, services, parts, quotes] = await Promise.all([
+    const [vehicles, customers, services, parts, quotes, reminders, inspections] = await Promise.all([
       db.vehicle.findMany({
       db.vehicle.findMany({
         where: { organizationId, OR: vehicleOr },
         where: { organizationId, OR: vehicleOr },
         select: {
         select: {
@@ -133,8 +133,64 @@ export async function globalSearch(query: string) {
         },
         },
         take: 10,
         take: 10,
       }),
       }),
+      db.reminder.findMany({
+        where: {
+          vehicle: { organizationId },
+          OR: [
+            { title: { contains: q, mode } },
+            { description: { contains: q, mode } },
+            { vehicle: { make: { contains: q, mode } } },
+            { vehicle: { model: { contains: q, mode } } },
+            { vehicle: { licensePlate: { contains: q, mode } } },
+          ],
+        },
+        select: {
+          id: true,
+          title: true,
+          dueDate: true,
+          isCompleted: true,
+          vehicle: {
+            select: {
+              id: true,
+              make: true,
+              model: true,
+              year: true,
+              licensePlate: true,
+            },
+          },
+        },
+        take: 10,
+      }),
+      db.inspection.findMany({
+        where: {
+          vehicle: { organizationId },
+          OR: [
+            { template: { name: { contains: q, mode } } },
+            { notes: { contains: q, mode } },
+            { vehicle: { make: { contains: q, mode } } },
+            { vehicle: { model: { contains: q, mode } } },
+            { vehicle: { licensePlate: { contains: q, mode } } },
+          ],
+        },
+        select: {
+          id: true,
+          status: true,
+          createdAt: true,
+          template: { select: { name: true } },
+          vehicle: {
+            select: {
+              id: true,
+              make: true,
+              model: true,
+              year: true,
+              licensePlate: true,
+            },
+          },
+        },
+        take: 10,
+      }),
     ]);
     ]);
 
 
-    return { vehicles, customers, services, parts, quotes };
+    return { vehicles, customers, services, parts, quotes, reminders, inspections };
   }, { requiredPermissions: [{ action: PermissionAction.READ, subject: PermissionSubject.DASHBOARD }] });
   }, { requiredPermissions: [{ action: PermissionAction.READ, subject: PermissionSubject.DASHBOARD }] });
 }
 }

+ 71 - 4
src/features/search/Components/SearchCommand.tsx

@@ -10,7 +10,7 @@ import {
   CommandGroup,
   CommandGroup,
   CommandItem,
   CommandItem,
 } from "@/components/ui/command";
 } from "@/components/ui/command";
-import { Car, FileText, Package, Settings, Users, Wrench } from "lucide-react";
+import { Bell, Car, ClipboardCheck, FileText, Package, Settings, Users, Wrench } from "lucide-react";
 import { globalSearch, getRecentCustomers } from "@/features/search/Actions/searchActions";
 import { globalSearch, getRecentCustomers } from "@/features/search/Actions/searchActions";
 
 
 interface SearchResult {
 interface SearchResult {
@@ -52,6 +52,32 @@ interface SearchResult {
     quoteNumber: string | null;
     quoteNumber: string | null;
     status: string;
     status: string;
   }[];
   }[];
+  reminders: {
+    id: string;
+    title: string;
+    dueDate: Date | null;
+    isCompleted: boolean;
+    vehicle: {
+      id: string;
+      make: string;
+      model: string;
+      year: number;
+      licensePlate: string | null;
+    };
+  }[];
+  inspections: {
+    id: string;
+    status: string;
+    createdAt: Date;
+    template: { name: string };
+    vehicle: {
+      id: string;
+      make: string;
+      model: string;
+      year: number;
+      licensePlate: string | null;
+    };
+  }[];
 }
 }
 
 
 const SEARCHABLE_SETTINGS = [
 const SEARCHABLE_SETTINGS = [
@@ -101,7 +127,7 @@ export function SearchCommand() {
   const router = useRouter();
   const router = useRouter();
   const [open, setOpen] = useState(false);
   const [open, setOpen] = useState(false);
   const [query, setQuery] = useState("");
   const [query, setQuery] = useState("");
-  const [results, setResults] = useState<SearchResult>({ vehicles: [], customers: [], services: [], parts: [], quotes: [] });
+  const [results, setResults] = useState<SearchResult>({ vehicles: [], customers: [], services: [], parts: [], quotes: [], reminders: [], inspections: [] });
   const [loading, setLoading] = useState(false);
   const [loading, setLoading] = useState(false);
   const [recentCustomers, setRecentCustomers] = useState<RecentCustomer[]>([]);
   const [recentCustomers, setRecentCustomers] = useState<RecentCustomer[]>([]);
   const recentFetchedRef = useRef(false);
   const recentFetchedRef = useRef(false);
@@ -136,7 +162,7 @@ export function SearchCommand() {
   useEffect(() => {
   useEffect(() => {
     if (!debouncedQuery || debouncedQuery.length < 2) {
     if (!debouncedQuery || debouncedQuery.length < 2) {
       // eslint-disable-next-line react-hooks/set-state-in-effect -- clearing results on query change is intentional
       // eslint-disable-next-line react-hooks/set-state-in-effect -- clearing results on query change is intentional
-      setResults({ vehicles: [], customers: [], services: [], parts: [], quotes: [] });
+      setResults({ vehicles: [], customers: [], services: [], parts: [], quotes: [], reminders: [], inspections: [] });
       setLoading(false);
       setLoading(false);
       return;
       return;
     }
     }
@@ -167,7 +193,7 @@ export function SearchCommand() {
   );
   );
 
 
   const hasQuery = debouncedQuery.length >= 2;
   const hasQuery = debouncedQuery.length >= 2;
-  const hasResults = results.vehicles.length > 0 || results.customers.length > 0 || results.services.length > 0 || results.parts.length > 0 || results.quotes.length > 0;
+  const hasResults = results.vehicles.length > 0 || results.customers.length > 0 || results.services.length > 0 || results.parts.length > 0 || results.quotes.length > 0 || results.reminders.length > 0 || results.inspections.length > 0;
   const matchedSettings = hasQuery ? filterSettings(debouncedQuery) : SEARCHABLE_SETTINGS;
   const matchedSettings = hasQuery ? filterSettings(debouncedQuery) : SEARCHABLE_SETTINGS;
   const showDefault = !hasQuery;
   const showDefault = !hasQuery;
 
 
@@ -313,6 +339,47 @@ export function SearchCommand() {
                 ))}
                 ))}
               </CommandGroup>
               </CommandGroup>
             )}
             )}
+            {results.reminders.length > 0 && (
+              <CommandGroup heading="Reminders">
+                {results.reminders.map((r) => (
+                  <CommandItem
+                    key={r.id}
+                    value={`${r.title} ${r.vehicle.make} ${r.vehicle.model} ${r.vehicle.licensePlate || ""}`}
+                    onSelect={() => handleSelect(`/vehicles/${r.vehicle.id}?tab=reminders`)}
+                  >
+                    <Bell className="mr-2 h-4 w-4 text-muted-foreground" />
+                    <div className="flex flex-col">
+                      <span>{r.title}{r.isCompleted && <span className="ml-1.5 text-muted-foreground line-through">(done)</span>}</span>
+                      <span className="text-xs text-muted-foreground">
+                        {`${r.vehicle.year} ${r.vehicle.make} ${r.vehicle.model}`}
+                        {r.vehicle.licensePlate && ` · ${r.vehicle.licensePlate}`}
+                      </span>
+                    </div>
+                  </CommandItem>
+                ))}
+              </CommandGroup>
+            )}
+            {results.inspections.length > 0 && (
+              <CommandGroup heading="Inspections">
+                {results.inspections.map((insp) => (
+                  <CommandItem
+                    key={insp.id}
+                    value={`${insp.template.name} ${insp.vehicle.make} ${insp.vehicle.model} ${insp.vehicle.licensePlate || ""}`}
+                    onSelect={() => handleSelect(`/inspections/${insp.id}`)}
+                  >
+                    <ClipboardCheck className="mr-2 h-4 w-4 text-muted-foreground" />
+                    <div className="flex flex-col">
+                      <span>{insp.template.name}</span>
+                      <span className="text-xs text-muted-foreground">
+                        {`${insp.vehicle.year} ${insp.vehicle.make} ${insp.vehicle.model}`}
+                        {insp.vehicle.licensePlate && ` · ${insp.vehicle.licensePlate}`}
+                        {` · ${insp.status}`}
+                      </span>
+                    </div>
+                  </CommandItem>
+                ))}
+              </CommandGroup>
+            )}
           </>
           </>
         )}
         )}
 
 

+ 1 - 1
src/features/vehicles/Components/RemindersPageClient.tsx

@@ -290,7 +290,7 @@ export function RemindersPageClient({ reminders, vehicles, unitSystem }: Reminde
                       <span className="text-xs text-muted-foreground">
                       <span className="text-xs text-muted-foreground">
                         <span
                         <span
                           className="hover:underline cursor-pointer"
                           className="hover:underline cursor-pointer"
-                          onClick={() => router.push(`/vehicles/${r.vehicle.id}`)}
+                          onClick={() => router.push(`/vehicles/${r.vehicle.id}?tab=reminders`)}
                         >
                         >
                           {r.vehicle.year} {r.vehicle.make} {r.vehicle.model}
                           {r.vehicle.year} {r.vehicle.make} {r.vehicle.model}
                           {r.vehicle.licensePlate && ` · ${r.vehicle.licensePlate}`}
                           {r.vehicle.licensePlate && ` · ${r.vehicle.licensePlate}`}