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

Add auth & multi-tenancy test suite (#5)

* added vitest, and test files for authentications routes

* test for public pages

* Fix multi-tenancy bugs and add defense-in-depth org scoping to all write operations

- Fix 4 silent-success bugs: updateVehicle, deleteVehicle, updateCustomer, deleteCustomer
  now properly check count/null and throw when targeting cross-org resources
- Harden 7 write operations with organizationId in where clauses (defense-in-depth):
  updateQuoteStatus, deleteQuote, convertQuoteToServiceRecord, completeInspection,
  deleteInspection, adjustInventoryStock, applyMarkupToAll
- Add 74 multi-tenancy isolation tests across 3 test suites covering vehicles,
  service records, customers, inventory, quotes, and inspections
* Add team invitation isolation & role-correctness tests (41 tests, 3 bugs exposed)

Tests cover:
- acceptInvitation: org and role assignment accuracy, token security
- sendInvitation: org scoping, role storage, roleId org validation
- cancelInvitation: org isolation, role authorization
- getPendingInvitations: org scoping, expired/non-pending exclusion
- assignRole: org isolation, cross-org role prevention

Bugs exposed (failing tests — fix required):
- BUG-5: sendInvitation uses role.findUnique without organizationId filter,
  allowing a cross-org roleId to be embedded in an invitation
- BUG-6: cancelInvitation blocks custom isAdmin members (checks built-in role string)
- BUG-7: assignRole blocks custom isAdmin members (checks built-in role in auth context)
* invite tests

* permission tests

* types

* test

---------
Bernt Christian Egeland 8 месяцев назад
Родитель
Сommit
50e27b1302
35 измененных файлов с 6132 добавлено и 142 удалено
  1. 2 0
      .github/workflows/ci.yml
  2. 1117 77
      package-lock.json
  3. 10 2
      package.json
  4. 476 0
      src/__tests__/auth/permission-enforcement.test.ts
  5. 130 0
      src/__tests__/auth/reset-password-validation.test.tsx
  6. 137 0
      src/__tests__/features/auth/acceptInvitation.test.ts
  7. 99 0
      src/__tests__/features/auth/registration-hook.test.ts
  8. 407 0
      src/__tests__/features/public/inspection-view.test.tsx
  9. 440 0
      src/__tests__/features/public/invoice-view.test.tsx
  10. 369 0
      src/__tests__/features/public/quote-view.test.tsx
  11. 200 0
      src/__tests__/features/public/quoteRequestActions.test.ts
  12. 188 0
      src/__tests__/features/public/respondToQuote.test.ts
  13. 101 0
      src/__tests__/lib/get-auth-context.test.ts
  14. 58 0
      src/__tests__/lib/permissions.test.ts
  15. 172 0
      src/__tests__/lib/with-auth.test.ts
  16. 451 0
      src/__tests__/multitenancy/customer-inventory-isolation.test.ts
  17. 533 0
      src/__tests__/multitenancy/quote-inspection-isolation.test.ts
  18. 797 0
      src/__tests__/multitenancy/team-invite-isolation.test.ts
  19. 351 0
      src/__tests__/multitenancy/vehicle-service-isolation.test.ts
  20. 1 0
      src/__tests__/setup.ts
  21. 2 2
      src/app/(authenticated)/inspections/[id]/page.tsx
  22. 4 2
      src/features/customers/Actions/customerActions.ts
  23. 3 3
      src/features/inspections/Actions/inspectionActions.ts
  24. 1 1
      src/features/inspections/Components/InspectionPageClient.tsx
  25. 4 4
      src/features/inventory/Actions/inventoryActions.ts
  26. 5 5
      src/features/quotes/Actions/quoteActions.ts
  27. 3 3
      src/features/team/Actions/acceptInvitation.ts
  28. 2 3
      src/features/team/Actions/assignRole.ts
  29. 3 3
      src/features/team/Actions/cancelInvitation.ts
  30. 34 28
      src/features/team/Actions/sendInvitation.ts
  31. 2 0
      src/features/vehicles/Actions/vehicleActions.ts
  32. 1 1
      src/lib/cached-session.ts
  33. 7 3
      src/lib/get-auth-context.ts
  34. 7 5
      src/lib/with-auth.ts
  35. 15 0
      vitest.config.ts

+ 2 - 0
.github/workflows/ci.yml

@@ -22,4 +22,6 @@ jobs:
 
       - run: npx prisma generate
 
+      - run: npm test
+
       - run: npm run build

Разница между файлами не показана из-за своего большого размера
+ 1117 - 77
package-lock.json


+ 10 - 2
package.json

@@ -12,7 +12,9 @@
     "format": "biome format . --write",
     "check": "biome check .",
     "check:fix": "biome check . --write",
-    "prepare": "next-ws patch"
+    "prepare": "next-ws patch",
+    "test": "vitest run",
+    "test:coverage": "vitest --coverage"
   },
   "dependencies": {
     "@aws-sdk/client-ses": "^3.992.0",
@@ -64,6 +66,9 @@
   "devDependencies": {
     "@biomejs/biome": "2.3.15",
     "@tailwindcss/postcss": "^4",
+    "@testing-library/jest-dom": "^6.9.1",
+    "@testing-library/react": "^16.3.2",
+    "@testing-library/user-event": "^14.6.1",
     "@types/archiver": "^7.0.0",
     "@types/cron": "^2.0.1",
     "@types/node": "^20",
@@ -71,11 +76,14 @@
     "@types/react": "^19",
     "@types/react-dom": "^19",
     "@types/ws": "^8.18.1",
+    "@vitest/coverage-v8": "^4.0.18",
     "dotenv": "^17.2.4",
+    "jsdom": "^28.1.0",
     "shadcn": "^3.8.5",
     "tailwindcss": "^4",
     "tw-animate-css": "^1.4.0",
-    "typescript": "^5"
+    "typescript": "^5",
+    "vitest": "^4.0.18"
   },
   "overrides": {
     "fast-xml-parser": ">=5.3.6",

+ 476 - 0
src/__tests__/auth/permission-enforcement.test.ts

@@ -0,0 +1,476 @@
+/**
+ * Permission enforcement tests
+ *
+ * Verifies that:
+ *  1. Every permission subject correctly denies access to custom-role users lacking permissions
+ *  2. Users with the correct permission pass the permission gate
+ *  3. Owner, admin, custom-admin, and members without custom roles bypass permission checks
+ *  4. Permission checks are action-specific and subject-specific
+ *  5. All withAuth-protected actions reject unauthenticated calls
+ */
+
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+// ---------- Module mocks (hoisted) ----------
+
+vi.mock("@/lib/cached-session", () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+
+vi.mock("next/headers", () => ({
+  headers: vi.fn().mockResolvedValue(new Headers()),
+  cookies: vi.fn().mockResolvedValue({ set: vi.fn(), get: vi.fn() }),
+}));
+
+vi.mock("@/lib/email", () => ({
+  sendOrgMail: vi.fn(),
+  getOrgFromAddress: vi.fn(),
+}));
+
+vi.mock("@/lib/features", () => ({
+  getFeatures: vi.fn().mockResolvedValue({
+    maxCustomers: 999999,
+    maxUsers: 999999,
+    templates: 999999,
+    customTemplates: true,
+    reports: true,
+    smtp: true,
+    api: true,
+    payments: true,
+    customFields: true,
+    brandingRemoved: true,
+    customPlatformName: true,
+    maxImagesPerService: 999999,
+    maxDiagnosticsPerService: 999999,
+    maxDocumentsPerService: 999999,
+  }),
+  FeatureGatedError: class FeatureGatedError extends Error {
+    feature: string;
+    constructor(f: string) {
+      super(`Feature gated: ${f}`);
+      this.feature = f;
+      this.name = "FeatureGatedError";
+    }
+  },
+  isCloudMode: vi.fn().mockReturnValue(false),
+  requireFeature: vi.fn(),
+}));
+
+vi.mock("@/lib/db", () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    vehicle: { findMany: vi.fn(), findFirst: vi.fn(), count: vi.fn(), create: vi.fn(), update: vi.fn(), updateMany: vi.fn(), delete: vi.fn(), deleteMany: vi.fn() },
+    customer: { findMany: vi.fn(), findFirst: vi.fn(), count: vi.fn(), create: vi.fn(), update: vi.fn(), updateMany: vi.fn(), delete: vi.fn(), deleteMany: vi.fn() },
+    serviceRecord: { findMany: vi.fn(), findFirst: vi.fn(), count: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn(), aggregate: vi.fn() },
+    quote: { findMany: vi.fn(), findFirst: vi.fn(), count: vi.fn(), create: vi.fn(), update: vi.fn(), updateMany: vi.fn(), delete: vi.fn(), deleteMany: vi.fn() },
+    inventoryPart: { findMany: vi.fn(), findFirst: vi.fn(), count: vi.fn(), create: vi.fn(), update: vi.fn(), updateMany: vi.fn(), delete: vi.fn(), deleteMany: vi.fn() },
+    inspection: { findMany: vi.fn(), findFirst: vi.fn(), count: vi.fn(), create: vi.fn(), update: vi.fn(), updateMany: vi.fn(), delete: vi.fn(), deleteMany: vi.fn() },
+    inspectionItem: { findMany: vi.fn(), update: vi.fn() },
+    inspectionTemplate: { findMany: vi.fn(), findFirst: vi.fn(), count: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn() },
+    organizationMember: { findFirst: vi.fn(), findMany: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn(), count: vi.fn() },
+    organizationSetting: { findFirst: vi.fn(), findMany: vi.fn(), upsert: vi.fn() },
+    appSetting: { findMany: vi.fn() },
+    subscription: { findUnique: vi.fn() },
+    teamInvitation: { findFirst: vi.fn(), findMany: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn(), deleteMany: vi.fn() },
+    role: { findFirst: vi.fn(), findMany: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn() },
+    quoteRequest: { findMany: vi.fn(), findFirst: vi.fn(), update: vi.fn() },
+    payment: { create: vi.fn(), delete: vi.fn(), findFirst: vi.fn() },
+    recurringInvoice: { findMany: vi.fn(), findFirst: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn(), count: vi.fn() },
+    fieldDefinition: { findMany: vi.fn(), findFirst: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn() },
+    customFieldValue: { findMany: vi.fn(), upsert: vi.fn(), deleteMany: vi.fn() },
+    note: { create: vi.fn(), update: vi.fn(), delete: vi.fn(), findFirst: vi.fn() },
+    reminder: { create: vi.fn(), update: vi.fn(), delete: vi.fn(), findFirst: vi.fn() },
+    $queryRaw: vi.fn(),
+    $transaction: vi.fn(),
+  },
+}));
+
+// ---------- Imports ----------
+
+import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
+import { db } from "@/lib/db";
+
+// Representative actions — one per permission subject
+import { getDashboardStats } from "@/features/vehicles/Actions/dashboardActions";
+import { getVehicles, createVehicle, updateVehicle } from "@/features/vehicles/Actions/vehicleActions";
+import { getCustomers } from "@/features/customers/Actions/customerActions";
+import { getWorkOrders, getServiceRecords } from "@/features/vehicles/Actions/serviceActions";
+import { getQuotesPaginated } from "@/features/quotes/Actions/quoteActions";
+import { getBillingHistory } from "@/features/billing/Actions/billingActions";
+import { getInventoryPartsPaginated } from "@/features/inventory/Actions/inventoryActions";
+import { getInspectionsPaginated } from "@/features/inspections/Actions/inspectionActions";
+import { getRevenueReport } from "@/features/reports/Actions/reportActions";
+import { getSetting } from "@/features/settings/Actions/settingsActions";
+import { removeMember } from "@/features/team/Actions/teamActions";
+import { deleteVehicle } from "@/features/vehicles/Actions/deleteVehicle";
+
+// ---------- Helpers ----------
+
+const mockSession = vi.mocked(getCachedSession);
+const mockMembership = vi.mocked(getCachedMembership);
+const mockUserFindUnique = vi.mocked(db.user.findUnique);
+
+const ORG_A = "org-a";
+
+/**
+ * Set up a user with a custom role and the given permissions.
+ * Empty permissions array triggers "Insufficient permissions" for any protected action.
+ */
+function setupRestrictedUser(permissions: { action: string; subject: string }[] = []) {
+  mockSession.mockResolvedValue({ user: { id: "restricted-user" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "member",
+    roleId: "custom-role-id",
+    customRole: { isAdmin: false, permissions },
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+function setupOwner() {
+  mockSession.mockResolvedValue({ user: { id: "owner-user" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "owner",
+    roleId: null,
+    customRole: null,
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+function setupAdmin() {
+  mockSession.mockResolvedValue({ user: { id: "admin-user" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "admin",
+    roleId: null,
+    customRole: null,
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+function setupCustomAdmin() {
+  mockSession.mockResolvedValue({ user: { id: "custom-admin-user" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "member",
+    roleId: "admin-custom-role-id",
+    customRole: { isAdmin: true, permissions: [] },
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+function setupMemberNoCustomRole() {
+  mockSession.mockResolvedValue({ user: { id: "plain-member" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "member",
+    roleId: null,
+    customRole: null,
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+function setupSuperAdmin() {
+  mockSession.mockResolvedValue({ user: { id: "super-admin" } } as any);
+  mockMembership.mockResolvedValue(null as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: true } as any);
+}
+
+beforeEach(() => {
+  vi.resetAllMocks();
+});
+
+// =============================================================================
+// 1. Permission denial — every subject blocks users with no permissions
+// =============================================================================
+
+describe("Permission denial — restricted custom role with no permissions", () => {
+  beforeEach(() => setupRestrictedUser());
+
+  const denialCases: [string, string, () => Promise<any>][] = [
+    ["DASHBOARD", "READ", () => getDashboardStats()],
+    ["VEHICLES", "READ", () => getVehicles()],
+    ["CUSTOMERS", "READ", () => getCustomers()],
+    ["WORK_ORDERS", "READ", () => getWorkOrders({})],
+    ["QUOTES", "READ", () => getQuotesPaginated({})],
+    ["SERVICES", "READ", () => getServiceRecords("any-vehicle-id")],
+    ["BILLING", "READ", () => getBillingHistory({})],
+    ["INVENTORY", "READ", () => getInventoryPartsPaginated({})],
+    ["INSPECTIONS", "READ", () => getInspectionsPaginated({})],
+    ["REPORTS", "READ", () => getRevenueReport({})],
+    ["SETTINGS", "READ", () => getSetting("organization.name" as any)],
+    ["SETTINGS", "MANAGE", () => removeMember("some-member-id")],
+  ];
+
+  it.each(denialCases)(
+    "denies access to %s (%s) when user has no permissions",
+    async (_subject, _action, callAction) => {
+      const result = await callAction();
+      expect(result).toEqual(
+        expect.objectContaining({ success: false, error: "Insufficient permissions" })
+      );
+    }
+  );
+});
+
+// =============================================================================
+// 2. Permission grant — correct permission passes the gate
+// =============================================================================
+
+describe("Permission grant — correct permission allows access past the gate", () => {
+  const grantCases: [string, { action: string; subject: string }, () => Promise<any>][] = [
+    ["DASHBOARD (READ)", { action: "read", subject: "dashboard" }, () => getDashboardStats()],
+    ["VEHICLES (READ)", { action: "read", subject: "vehicles" }, () => getVehicles()],
+    ["VEHICLES (CREATE)", { action: "create", subject: "vehicles" }, () => createVehicle({})],
+    ["VEHICLES (UPDATE)", { action: "update", subject: "vehicles" }, () => updateVehicle({})],
+    ["VEHICLES (DELETE)", { action: "delete", subject: "vehicles" }, () => deleteVehicle("any-id")],
+    ["CUSTOMERS (READ)", { action: "read", subject: "customers" }, () => getCustomers()],
+    ["WORK_ORDERS (READ)", { action: "read", subject: "work_orders" }, () => getWorkOrders({})],
+    ["QUOTES (READ)", { action: "read", subject: "quotes" }, () => getQuotesPaginated({})],
+    ["SERVICES (READ)", { action: "read", subject: "services" }, () => getServiceRecords("any-id")],
+    ["BILLING (READ)", { action: "read", subject: "billing" }, () => getBillingHistory({})],
+    ["INVENTORY (READ)", { action: "read", subject: "inventory" }, () => getInventoryPartsPaginated({})],
+    ["INSPECTIONS (READ)", { action: "read", subject: "inspections" }, () => getInspectionsPaginated({})],
+    ["REPORTS (READ)", { action: "read", subject: "reports" }, () => getRevenueReport({})],
+    ["SETTINGS (READ)", { action: "read", subject: "settings" }, () => getSetting("organization.name" as any)],
+    ["SETTINGS (MANAGE)", { action: "manage", subject: "settings" }, () => removeMember("some-id")],
+  ];
+
+  it.each(grantCases)(
+    "grants access to %s when user has the correct permission",
+    async (_label, permission, callAction) => {
+      setupRestrictedUser([permission]);
+      const result = await callAction();
+      // The action may fail for other reasons (ZodError, missing DB data, etc.)
+      // but it must NOT fail with "Insufficient permissions"
+      expect(result.error).not.toBe("Insufficient permissions");
+    }
+  );
+});
+
+// =============================================================================
+// 3. Permission bypass — privileged roles skip permission checks
+// =============================================================================
+
+describe("Permission bypass — privileged roles skip permission checks", () => {
+  // Use getVehicles (requires READ+VEHICLES) as the test action.
+  // None of these roles should get "Insufficient permissions".
+
+  it("owner bypasses permission checks", async () => {
+    setupOwner();
+    vi.mocked(db.vehicle.findMany).mockResolvedValue([]);
+    const result = await getVehicles();
+    expect(result.error).not.toBe("Insufficient permissions");
+  });
+
+  it("admin bypasses permission checks", async () => {
+    setupAdmin();
+    vi.mocked(db.vehicle.findMany).mockResolvedValue([]);
+    const result = await getVehicles();
+    expect(result.error).not.toBe("Insufficient permissions");
+  });
+
+  it("custom role with isAdmin:true bypasses permission checks", async () => {
+    setupCustomAdmin();
+    vi.mocked(db.vehicle.findMany).mockResolvedValue([]);
+    const result = await getVehicles();
+    expect(result.error).not.toBe("Insufficient permissions");
+  });
+
+  it("member without custom role bypasses permission checks (full access by design)", async () => {
+    setupMemberNoCustomRole();
+    vi.mocked(db.vehicle.findMany).mockResolvedValue([]);
+    const result = await getVehicles();
+    expect(result.error).not.toBe("Insufficient permissions");
+  });
+
+  it("super admin bypasses all permission checks even without org membership", async () => {
+    setupSuperAdmin();
+    vi.mocked(db.vehicle.findMany).mockResolvedValue([]);
+    const result = await getVehicles();
+    expect(result.error).not.toBe("Insufficient permissions");
+  });
+});
+
+// =============================================================================
+// 4. Permission specificity — wrong action or subject is denied
+// =============================================================================
+
+describe("Permission specificity — wrong action or subject is denied", () => {
+  it("READ+VEHICLES does not grant access to CREATE+VEHICLES (wrong action)", async () => {
+    setupRestrictedUser([{ action: "read", subject: "vehicles" }]);
+    const result = await createVehicle({});
+    expect(result).toEqual(
+      expect.objectContaining({ success: false, error: "Insufficient permissions" })
+    );
+  });
+
+  it("READ+VEHICLES does not grant access to DELETE+VEHICLES (wrong action)", async () => {
+    setupRestrictedUser([{ action: "read", subject: "vehicles" }]);
+    const result = await deleteVehicle("any-id");
+    expect(result).toEqual(
+      expect.objectContaining({ success: false, error: "Insufficient permissions" })
+    );
+  });
+
+  it("UPDATE+VEHICLES does not grant access to READ+VEHICLES (wrong action)", async () => {
+    setupRestrictedUser([{ action: "update", subject: "vehicles" }]);
+    const result = await getVehicles();
+    expect(result).toEqual(
+      expect.objectContaining({ success: false, error: "Insufficient permissions" })
+    );
+  });
+
+  it("READ+CUSTOMERS does not grant access to READ+VEHICLES (wrong subject)", async () => {
+    setupRestrictedUser([{ action: "read", subject: "customers" }]);
+    const result = await getVehicles();
+    expect(result).toEqual(
+      expect.objectContaining({ success: false, error: "Insufficient permissions" })
+    );
+  });
+
+  it("READ+VEHICLES does not grant access to READ+CUSTOMERS (wrong subject)", async () => {
+    setupRestrictedUser([{ action: "read", subject: "vehicles" }]);
+    const result = await getCustomers();
+    expect(result).toEqual(
+      expect.objectContaining({ success: false, error: "Insufficient permissions" })
+    );
+  });
+
+  it("UPDATE+SETTINGS does not grant access to MANAGE+SETTINGS", async () => {
+    setupRestrictedUser([{ action: "update", subject: "settings" }]);
+    const result = await removeMember("some-id");
+    expect(result).toEqual(
+      expect.objectContaining({ success: false, error: "Insufficient permissions" })
+    );
+  });
+
+  it("MANAGE+SETTINGS does not grant access to READ+DASHBOARD (wrong subject)", async () => {
+    setupRestrictedUser([{ action: "manage", subject: "settings" }]);
+    const result = await getDashboardStats();
+    expect(result).toEqual(
+      expect.objectContaining({ success: false, error: "Insufficient permissions" })
+    );
+  });
+
+  it("READ+REPORTS does not grant access to READ+BILLING (wrong subject)", async () => {
+    setupRestrictedUser([{ action: "read", subject: "reports" }]);
+    const result = await getBillingHistory({});
+    expect(result).toEqual(
+      expect.objectContaining({ success: false, error: "Insufficient permissions" })
+    );
+  });
+});
+
+// =============================================================================
+// 5. Multiple permissions — user can hold permissions for multiple subjects
+// =============================================================================
+
+describe("Multiple permissions — user can hold permissions for multiple subjects", () => {
+  it("user with READ+VEHICLES and READ+CUSTOMERS can access both", async () => {
+    setupRestrictedUser([
+      { action: "read", subject: "vehicles" },
+      { action: "read", subject: "customers" },
+    ]);
+    vi.mocked(db.vehicle.findMany).mockResolvedValue([]);
+    vi.mocked(db.customer.findMany).mockResolvedValue([]);
+
+    const vehicleResult = await getVehicles();
+    const customerResult = await getCustomers();
+
+    expect(vehicleResult.error).not.toBe("Insufficient permissions");
+    expect(customerResult.error).not.toBe("Insufficient permissions");
+  });
+
+  it("user with READ+VEHICLES and READ+CUSTOMERS is still denied BILLING", async () => {
+    setupRestrictedUser([
+      { action: "read", subject: "vehicles" },
+      { action: "read", subject: "customers" },
+    ]);
+
+    const result = await getBillingHistory({});
+    expect(result).toEqual(
+      expect.objectContaining({ success: false, error: "Insufficient permissions" })
+    );
+  });
+
+  it("user with all CRUD on VEHICLES can create, read, update, and delete", async () => {
+    setupRestrictedUser([
+      { action: "create", subject: "vehicles" },
+      { action: "read", subject: "vehicles" },
+      { action: "update", subject: "vehicles" },
+      { action: "delete", subject: "vehicles" },
+    ]);
+
+    const readResult = await getVehicles();
+    const createResult = await createVehicle({});
+    const updateResult = await updateVehicle({});
+    const deleteResult = await deleteVehicle("any-id");
+
+    expect(readResult.error).not.toBe("Insufficient permissions");
+    expect(createResult.error).not.toBe("Insufficient permissions");
+    expect(updateResult.error).not.toBe("Insufficient permissions");
+    expect(deleteResult.error).not.toBe("Insufficient permissions");
+  });
+});
+
+// =============================================================================
+// 6. Unauthenticated access — all actions reject unauthenticated calls
+// =============================================================================
+
+describe("Unauthenticated access — all actions require authentication", () => {
+  beforeEach(() => {
+    mockSession.mockResolvedValue(null);
+  });
+
+  const unauthCases: [string, () => Promise<any>][] = [
+    ["getDashboardStats", () => getDashboardStats()],
+    ["getVehicles", () => getVehicles()],
+    ["getCustomers", () => getCustomers()],
+    ["getWorkOrders", () => getWorkOrders({})],
+    ["getQuotesPaginated", () => getQuotesPaginated({})],
+    ["getServiceRecords", () => getServiceRecords("any-id")],
+    ["getBillingHistory", () => getBillingHistory({})],
+    ["getInventoryPartsPaginated", () => getInventoryPartsPaginated({})],
+    ["getInspectionsPaginated", () => getInspectionsPaginated({})],
+    ["getRevenueReport", () => getRevenueReport({})],
+    ["getSetting", () => getSetting("organization.name" as any)],
+    ["removeMember", () => removeMember("some-id")],
+    ["createVehicle", () => createVehicle({})],
+    ["updateVehicle", () => updateVehicle({})],
+    ["deleteVehicle", () => deleteVehicle("any-id")],
+  ];
+
+  it.each(unauthCases)(
+    "%s rejects unauthenticated calls",
+    async (_name, callAction) => {
+      const result = await callAction();
+      expect(result).toEqual(
+        expect.objectContaining({ success: false, error: "Unauthorized" })
+      );
+    }
+  );
+});
+
+// =============================================================================
+// 7. No-org access — users without organization membership are rejected
+// =============================================================================
+
+describe("No-org access — users without organization are rejected", () => {
+  beforeEach(() => {
+    mockSession.mockResolvedValue({ user: { id: "orphan-user" } } as any);
+    mockMembership.mockResolvedValue(null as any);
+    mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+  });
+
+  it("rejects non-super-admin users without an organization", async () => {
+    const result = await getVehicles();
+    expect(result).toEqual(
+      expect.objectContaining({ success: false, error: "No organization found" })
+    );
+  });
+});

+ 130 - 0
src/__tests__/auth/reset-password-validation.test.tsx

@@ -0,0 +1,130 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+// Mock next/navigation before importing the component
+const mockGet = vi.fn();
+vi.mock("next/navigation", () => ({
+  useSearchParams: () => ({ get: mockGet }),
+  useRouter: () => ({ push: vi.fn() }),
+  usePathname: () => "/auth/reset-password",
+}));
+
+// Mock next/link
+vi.mock("next/link", () => ({
+  default: ({ href, children }: { href: string; children: React.ReactNode }) => (
+    <a href={href}>{children}</a>
+  ),
+}));
+
+// Mock lucide-react icons used in the component
+vi.mock("lucide-react", () => ({
+  Gauge: () => <svg data-testid="icon-gauge" />,
+  Loader2: () => <svg data-testid="icon-loader" />,
+  XCircle: () => <svg data-testid="icon-xcircle" />,
+}));
+
+// Mock UI components (pass-through)
+vi.mock("@/components/ui/button", () => ({
+  Button: ({ children, ...props }: React.HTMLAttributes<HTMLButtonElement> & { variant?: string }) => (
+    <button {...props}>{children}</button>
+  ),
+}));
+vi.mock("@/components/ui/input", () => ({
+  Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+}));
+vi.mock("@/components/ui/label", () => ({
+  Label: ({ children, ...props }: React.LabelHTMLAttributes<HTMLLabelElement>) => (
+    <label {...props}>{children}</label>
+  ),
+}));
+
+// Mock authClient
+const mockResetPassword = vi.fn();
+vi.mock("@/lib/auth-client", () => ({
+  authClient: {
+    resetPassword: (...args: unknown[]) => mockResetPassword(...args),
+  },
+}));
+
+// Import the inner component — we test ResetPasswordInner via ResetPasswordPage's Suspense wrapper
+// Since ResetPasswordInner is not exported, we render the default export which wraps it in Suspense.
+import ResetPasswordPage from "@/app/(public)/auth/reset-password/page";
+
+beforeEach(() => {
+  vi.resetAllMocks();
+});
+
+describe("ResetPasswordPage — ResetPasswordInner", () => {
+  it("shows invalid token message when no token in URL", () => {
+    mockGet.mockReturnValue(null);
+    render(<ResetPasswordPage />);
+    expect(screen.getByText(/invalid or missing reset token/i)).toBeInTheDocument();
+    expect(screen.queryByRole("form")).not.toBeInTheDocument();
+  });
+
+  it("shows the form when a token is present", () => {
+    mockGet.mockReturnValue("valid-token-abc");
+    render(<ResetPasswordPage />);
+    expect(screen.getByLabelText(/new password/i)).toBeInTheDocument();
+    expect(screen.getByLabelText(/confirm password/i)).toBeInTheDocument();
+  });
+
+  it("shows passwords do not match error without calling resetPassword", async () => {
+    mockGet.mockReturnValue("valid-token-abc");
+    render(<ResetPasswordPage />);
+
+    await userEvent.type(screen.getByLabelText(/new password/i), "password1");
+    await userEvent.type(screen.getByLabelText(/confirm password/i), "password2");
+    fireEvent.submit(screen.getByRole("button", { name: /reset password/i }));
+
+    await waitFor(() => {
+      expect(screen.getByText(/passwords do not match/i)).toBeInTheDocument();
+    });
+    expect(mockResetPassword).not.toHaveBeenCalled();
+  });
+
+  it("shows password length error without calling resetPassword", async () => {
+    mockGet.mockReturnValue("valid-token-abc");
+    render(<ResetPasswordPage />);
+
+    await userEvent.type(screen.getByLabelText(/new password/i), "short");
+    await userEvent.type(screen.getByLabelText(/confirm password/i), "short");
+    fireEvent.submit(screen.getByRole("button", { name: /reset password/i }));
+
+    await waitFor(() => {
+      expect(screen.getByText(/at least 8 characters/i)).toBeInTheDocument();
+    });
+    expect(mockResetPassword).not.toHaveBeenCalled();
+  });
+
+  it("shows error message when authClient.resetPassword returns an error", async () => {
+    mockGet.mockReturnValue("valid-token-abc");
+    mockResetPassword.mockResolvedValue({ error: { message: "Token has expired" } });
+    render(<ResetPasswordPage />);
+
+    await userEvent.type(screen.getByLabelText(/new password/i), "securepass1");
+    await userEvent.type(screen.getByLabelText(/confirm password/i), "securepass1");
+    fireEvent.submit(screen.getByRole("button", { name: /reset password/i }));
+
+    await waitFor(() => {
+      expect(screen.getByText(/token has expired/i)).toBeInTheDocument();
+    });
+  });
+
+  it("shows success state with sign-in link when reset succeeds", async () => {
+    mockGet.mockReturnValue("valid-token-abc");
+    mockResetPassword.mockResolvedValue({ error: null });
+    render(<ResetPasswordPage />);
+
+    await userEvent.type(screen.getByLabelText(/new password/i), "securepass1");
+    await userEvent.type(screen.getByLabelText(/confirm password/i), "securepass1");
+    fireEvent.submit(screen.getByRole("button", { name: /reset password/i }));
+
+    await waitFor(() => {
+      expect(screen.getByText(/password has been reset successfully/i)).toBeInTheDocument();
+    });
+    // The success state renders a "Sign In" button (distinct from the footer "Back to Sign In" link)
+    expect(screen.getByRole("button", { name: /^sign in$/i })).toBeInTheDocument();
+  });
+});

+ 137 - 0
src/__tests__/features/auth/acceptInvitation.test.ts

@@ -0,0 +1,137 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+// Mock next/headers
+vi.mock("next/headers", () => ({
+  headers: vi.fn().mockResolvedValue(new Headers()),
+  cookies: vi.fn().mockResolvedValue({
+    set: vi.fn(),
+    get: vi.fn(),
+  }),
+}));
+
+// Mock auth — acceptInvitation calls auth.api.getSession directly
+vi.mock("@/lib/auth", () => ({
+  auth: {
+    api: {
+      getSession: vi.fn(),
+    },
+  },
+}));
+
+// Mock db
+vi.mock("@/lib/db", () => ({
+  db: {
+    teamInvitation: {
+      findUnique: vi.fn(),
+      update: vi.fn(),
+    },
+    organizationMember: {
+      findFirst: vi.fn(),
+      create: vi.fn(),
+    },
+    $transaction: vi.fn(),
+  },
+}));
+
+import { acceptInvitation } from "@/features/team/Actions/acceptInvitation";
+import { auth } from "@/lib/auth";
+import { db } from "@/lib/db";
+import { cookies } from "next/headers";
+
+const mockGetSession = vi.mocked(auth.api.getSession);
+const mockFindInvitation = vi.mocked(db.teamInvitation.findUnique);
+const mockFindMembership = vi.mocked(db.organizationMember.findFirst);
+const mockUpdateInvitation = vi.mocked(db.teamInvitation.update);
+const mockTransaction = vi.mocked(db.$transaction);
+
+const SESSION = { user: { id: "user-1", email: "invited@example.com" } };
+const VALID_INVITATION = {
+  id: "inv-1",
+  token: "tok-abc",
+  email: "invited@example.com",
+  organizationId: "org-1",
+  status: "pending",
+  role: "member",
+  roleId: null,
+  expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days future
+};
+
+beforeEach(() => {
+  vi.resetAllMocks();
+  // Restore cookies mock after reset
+  vi.mocked(cookies).mockResolvedValue({ set: vi.fn(), get: vi.fn() } as any);
+});
+
+describe("acceptInvitation", () => {
+  it("returns error when user is not signed in", async () => {
+    mockGetSession.mockResolvedValue(null);
+    const result = await acceptInvitation({ token: "tok-abc" });
+    expect(result).toEqual({ success: false, error: "You must be signed in to accept an invitation" });
+  });
+
+  it("returns error when invitation is not found", async () => {
+    mockGetSession.mockResolvedValue(SESSION as any);
+    mockFindInvitation.mockResolvedValue(null);
+    const result = await acceptInvitation({ token: "tok-abc" });
+    expect(result).toEqual({ success: false, error: "Invitation not found" });
+  });
+
+  it("returns error when invitation status is not pending", async () => {
+    mockGetSession.mockResolvedValue(SESSION as any);
+    mockFindInvitation.mockResolvedValue({ ...VALID_INVITATION, status: "accepted" } as any);
+    const result = await acceptInvitation({ token: "tok-abc" });
+    expect(result).toEqual({ success: false, error: "This invitation is no longer valid" });
+  });
+
+  it("returns error when invitation is expired", async () => {
+    mockGetSession.mockResolvedValue(SESSION as any);
+    mockFindInvitation.mockResolvedValue({
+      ...VALID_INVITATION,
+      expiresAt: new Date(Date.now() - 1000), // 1 second in the past
+    } as any);
+    const result = await acceptInvitation({ token: "tok-abc" });
+    expect(result).toEqual({ success: false, error: "This invitation has expired" });
+  });
+
+  it("returns error when email does not match signed-in user", async () => {
+    mockGetSession.mockResolvedValue({ user: { id: "user-1", email: "other@example.com" } } as any);
+    mockFindInvitation.mockResolvedValue(VALID_INVITATION as any);
+    const result = await acceptInvitation({ token: "tok-abc" });
+    expect(result).toEqual({ success: false, error: "This invitation was sent to a different email address" });
+  });
+
+  it("marks invitation accepted and returns success when user is already a member", async () => {
+    mockGetSession.mockResolvedValue(SESSION as any);
+    mockFindInvitation.mockResolvedValue(VALID_INVITATION as any);
+    mockFindMembership.mockResolvedValue({ id: "mem-1" } as any);
+    mockUpdateInvitation.mockResolvedValue({} as any);
+
+    const result = await acceptInvitation({ token: "tok-abc" });
+    expect(result).toEqual({ success: true, data: { accepted: true } });
+    expect(mockUpdateInvitation).toHaveBeenCalledWith({
+      where: { id: "inv-1" },
+      data: { status: "accepted" },
+    });
+  });
+
+  it("creates membership and marks invitation accepted in transaction on happy path", async () => {
+    mockGetSession.mockResolvedValue(SESSION as any);
+    mockFindInvitation.mockResolvedValue(VALID_INVITATION as any);
+    mockFindMembership.mockResolvedValue(null);
+    mockTransaction.mockResolvedValue([{}, {}] as any);
+
+    const result = await acceptInvitation({ token: "tok-abc" });
+    expect(result).toEqual({ success: true, data: { accepted: true } });
+    expect(mockTransaction).toHaveBeenCalled();
+  });
+
+  it("returns error when transaction throws", async () => {
+    mockGetSession.mockResolvedValue(SESSION as any);
+    mockFindInvitation.mockResolvedValue(VALID_INVITATION as any);
+    mockFindMembership.mockResolvedValue(null);
+    mockTransaction.mockRejectedValue(new Error("DB error"));
+
+    const result = await acceptInvitation({ token: "tok-abc" });
+    expect(result).toEqual({ success: false, error: "DB error" });
+  });
+});

+ 99 - 0
src/__tests__/features/auth/registration-hook.test.ts

@@ -0,0 +1,99 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+/**
+ * Tests for the registration `before` hook in src/lib/auth.ts.
+ * The hook logic is extracted and tested directly here.
+ */
+
+vi.mock("@/lib/db", () => ({
+  db: {
+    systemSetting: {
+      findUnique: vi.fn(),
+    },
+    teamInvitation: {
+      findFirst: vi.fn(),
+    },
+  },
+}));
+
+import { db } from "@/lib/db";
+
+const mockFindSetting = vi.mocked(db.systemSetting.findUnique);
+const mockFindInvitation = vi.mocked(db.teamInvitation.findFirst);
+
+// This is the exact logic from src/lib/auth.ts databaseHooks.user.create.before
+async function registrationBeforeHook(user: { email: string; name?: string }) {
+  const setting = await db.systemSetting.findUnique({
+    where: { key: "registration.disabled" },
+  });
+  if (setting?.value === "true") {
+    const invitation = await db.teamInvitation.findFirst({
+      where: {
+        email: user.email,
+        status: "pending",
+        expiresAt: { gt: new Date() },
+      },
+    });
+    if (!invitation) {
+      return false;
+    }
+  }
+  return { data: user };
+}
+
+beforeEach(() => {
+  vi.resetAllMocks();
+});
+
+describe("registration before hook", () => {
+  const user = { email: "newuser@example.com", name: "New User" };
+
+  it("allows registration when registration.disabled setting is not found", async () => {
+    mockFindSetting.mockResolvedValue(null);
+    const result = await registrationBeforeHook(user);
+    expect(result).toEqual({ data: user });
+    expect(mockFindInvitation).not.toHaveBeenCalled();
+  });
+
+  it("allows registration when registration.disabled = 'false'", async () => {
+    mockFindSetting.mockResolvedValue({ key: "registration.disabled", value: "false" } as any);
+    const result = await registrationBeforeHook(user);
+    expect(result).toEqual({ data: user });
+    expect(mockFindInvitation).not.toHaveBeenCalled();
+  });
+
+  it("blocks registration when disabled=true and no valid invitation exists", async () => {
+    mockFindSetting.mockResolvedValue({ key: "registration.disabled", value: "true" } as any);
+    mockFindInvitation.mockResolvedValue(null);
+    const result = await registrationBeforeHook(user);
+    expect(result).toBe(false);
+  });
+
+  it("allows registration when disabled=true but a valid pending non-expired invitation exists", async () => {
+    mockFindSetting.mockResolvedValue({ key: "registration.disabled", value: "true" } as any);
+    mockFindInvitation.mockResolvedValue({
+      id: "inv-1",
+      email: user.email,
+      status: "pending",
+      expiresAt: new Date(Date.now() + 60_000),
+    } as any);
+    const result = await registrationBeforeHook(user);
+    expect(result).toEqual({ data: user });
+  });
+
+  it("blocks registration when disabled=true and invitation is expired (findFirst returns null due to expiresAt filter)", async () => {
+    // The DB query filters expiresAt > now, so an expired invitation won't be returned
+    mockFindSetting.mockResolvedValue({ key: "registration.disabled", value: "true" } as any);
+    mockFindInvitation.mockResolvedValue(null); // expired invitation filtered out by DB
+    const result = await registrationBeforeHook(user);
+    expect(result).toBe(false);
+  });
+
+  it("blocks registration when disabled=true and invitation status is not pending (findFirst returns null)", async () => {
+    // The DB query filters status: "pending", so non-pending won't be returned
+    mockFindSetting.mockResolvedValue({ key: "registration.disabled", value: "true" } as any);
+    mockFindInvitation.mockResolvedValue(null); // non-pending invitation filtered out by DB
+    const result = await registrationBeforeHook(user);
+    expect(result).toBe(false);
+  });
+});

+ 407 - 0
src/__tests__/features/public/inspection-view.test.tsx

@@ -0,0 +1,407 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+vi.mock("lucide-react", () => ({
+  AlertTriangle: () => <span data-testid="icon-alert" />,
+  Check: () => <span data-testid="icon-check" />,
+  CheckCircle2: () => <span data-testid="icon-check-circle" />,
+  ChevronLeft: () => <span data-testid="icon-left" />,
+  ChevronRight: () => <span data-testid="icon-right" />,
+  ClipboardCheck: () => <span data-testid="icon-clipboard" />,
+  Download: () => <span data-testid="icon-download" />,
+  FileText: () => <span data-testid="icon-file-text" />,
+  Loader2: () => <span data-testid="icon-loader" />,
+  X: () => <span data-testid="icon-x" />,
+}));
+
+vi.mock("sonner", () => ({
+  toast: {
+    success: vi.fn(),
+    error: vi.fn(),
+  },
+}));
+
+vi.mock("@/components/ui/button", () => ({
+  Button: ({ children, onClick, disabled, ...props }: React.HTMLAttributes<HTMLButtonElement> & { disabled?: boolean; variant?: string }) => (
+    <button onClick={onClick} disabled={disabled} {...props}>
+      {children}
+    </button>
+  ),
+}));
+
+vi.mock("@/features/inspections/Components/QuoteRequestDialog", () => ({
+  QuoteRequestDialog: ({ open, onOpenChange, onSuccess }: { open: boolean; onOpenChange: (v: boolean) => void; onSuccess: () => void }) =>
+    open ? (
+      <div data-testid="quote-request-dialog">
+        <button onClick={onSuccess} data-testid="dialog-submit">Submit</button>
+        <button onClick={() => onOpenChange(false)} data-testid="dialog-close">Close</button>
+      </div>
+    ) : null,
+}));
+
+import { InspectionView } from "@/app/(public)/share/inspection/[orgId]/[token]/inspection-view";
+import { toast } from "sonner";
+
+const WORKSHOP = {
+  name: "Quality Auto",
+  address: "5 Shop Lane",
+  phone: "555-2222",
+  email: "qa@example.com",
+};
+
+const VEHICLE = {
+  make: "Ford",
+  model: "F-150",
+  year: 2021,
+  vin: "FORD123",
+  licensePlate: "TR-001",
+  mileage: 30000,
+  customer: { name: "Dave Owner", email: "dave@example.com", phone: "555-3333" },
+};
+
+const PASS_ITEM = {
+  id: "item-pass",
+  name: "Oil Level",
+  section: "Engine",
+  sortOrder: 1,
+  condition: "pass",
+  notes: null,
+  imageUrls: [],
+};
+
+const FAIL_ITEM = {
+  id: "item-fail",
+  name: "Brake Pads",
+  section: "Brakes",
+  sortOrder: 2,
+  condition: "fail",
+  notes: "Worn down to 2mm",
+  imageUrls: [],
+};
+
+const ATTENTION_ITEM = {
+  id: "item-attention",
+  name: "Tire Tread",
+  section: "Tires",
+  sortOrder: 3,
+  condition: "attention",
+  notes: null,
+  imageUrls: [],
+};
+
+const BASE_INSPECTION = {
+  id: "insp-1",
+  status: "completed",
+  mileage: 30000,
+  notes: null,
+  completedAt: new Date("2024-04-01"),
+  createdAt: new Date("2024-04-01"),
+  vehicle: VEHICLE,
+  template: { name: "Full Inspection" },
+  items: [PASS_ITEM, FAIL_ITEM, ATTENTION_ITEM],
+};
+
+const DEFAULT_PROPS = {
+  inspection: BASE_INSPECTION,
+  workshop: WORKSHOP,
+  logoUrl: "",
+  primaryColor: "#d97706",
+  showTorqvoiceBranding: false,
+  publicToken: "pub-tok-insp",
+  orgId: "org-1",
+  hasExistingQuoteRequest: false,
+};
+
+let mockFetch: ReturnType<typeof vi.fn>;
+let mockWindowOpen: ReturnType<typeof vi.fn>;
+
+beforeEach(() => {
+  vi.resetAllMocks();
+  mockFetch = vi.fn();
+  vi.stubGlobal("fetch", mockFetch);
+  mockWindowOpen = vi.fn();
+  vi.stubGlobal("open", mockWindowOpen);
+});
+
+describe("InspectionView", () => {
+  describe("rendering", () => {
+    it("renders the workshop name", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("Quality Auto")).toBeInTheDocument();
+    });
+
+    it("renders vehicle information", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("2021 Ford F-150")).toBeInTheDocument();
+      expect(screen.getByText("VIN: FORD123")).toBeInTheDocument();
+    });
+
+    it("renders customer information", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("Dave Owner")).toBeInTheDocument();
+    });
+
+    it("renders Vehicle Inspection heading", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("Vehicle Inspection")).toBeInTheDocument();
+    });
+  });
+
+  describe("summary bar", () => {
+    it("shows total inspected item count", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      // The summary renders: <span class="font-semibold text-gray-900">3</span> inspected
+      // getByText can't match compound nodes, so check the count span directly.
+      const countSpan = document.querySelector("span.font-semibold.text-gray-900");
+      expect(countSpan?.textContent).toBe("3");
+    });
+
+    it("shows correct pass count", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("1 Pass")).toBeInTheDocument();
+    });
+
+    it("shows correct fail count", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("1 Fail")).toBeInTheDocument();
+    });
+
+    it("shows correct attention count", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("1 Attention")).toBeInTheDocument();
+    });
+
+    it("excludes not_inspected items from the summary", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        inspection: {
+          ...BASE_INSPECTION,
+          items: [
+            PASS_ITEM,
+            { ...FAIL_ITEM, condition: "not_inspected" },
+          ],
+        },
+      };
+      render(<InspectionView {...props} />);
+      expect(screen.getByText("1 Pass")).toBeInTheDocument();
+      expect(screen.getByText("0 Fail")).toBeInTheDocument();
+    });
+  });
+
+  describe("inspection items", () => {
+    it("renders inspection items grouped by section", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("Engine")).toBeInTheDocument();
+      expect(screen.getByText("Brakes")).toBeInTheDocument();
+      expect(screen.getByText("Tires")).toBeInTheDocument();
+    });
+
+    it("shows Pass badge on passing item", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("Pass")).toBeInTheDocument();
+    });
+
+    it("shows Fail badge on failing item", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("Fail")).toBeInTheDocument();
+    });
+
+    it("shows Attention badge on attention item", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("Attention")).toBeInTheDocument();
+    });
+
+    it("renders item notes when present", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("Worn down to 2mm")).toBeInTheDocument();
+    });
+
+    it("does not render not_inspected items", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        inspection: {
+          ...BASE_INSPECTION,
+          items: [{ ...PASS_ITEM, condition: "not_inspected", name: "Hidden Item" }],
+        },
+      };
+      render(<InspectionView {...props} />);
+      expect(screen.queryByText("Hidden Item")).not.toBeInTheDocument();
+    });
+  });
+
+  describe("quote request button", () => {
+    it("shows Request a Quote button when there are issues", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.getByRole("button", { name: /request a quote/i })).toBeInTheDocument();
+    });
+
+    it("does not show Request a Quote button when all items pass", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        inspection: { ...BASE_INSPECTION, items: [PASS_ITEM] },
+      };
+      render(<InspectionView {...props} />);
+      expect(screen.queryByRole("button", { name: /request a quote/i })).not.toBeInTheDocument();
+    });
+
+    it("shows Quote Requested — Cancel button when hasExistingQuoteRequest=true", () => {
+      render(<InspectionView {...DEFAULT_PROPS} hasExistingQuoteRequest={true} />);
+      expect(screen.getByRole("button", { name: /quote requested/i })).toBeInTheDocument();
+      expect(screen.getByText(/cancel/i)).toBeInTheDocument();
+    });
+
+    it("does not show Request a Quote when quote is already requested", () => {
+      render(<InspectionView {...DEFAULT_PROPS} hasExistingQuoteRequest={true} />);
+      expect(screen.queryByRole("button", { name: /^request a quote$/i })).not.toBeInTheDocument();
+    });
+
+    it("opens quote request dialog when button is clicked", async () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /request a quote/i }));
+      expect(screen.getByTestId("quote-request-dialog")).toBeInTheDocument();
+    });
+
+    it("switches to Quote Requested state after dialog submission", async () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /request a quote/i }));
+      await userEvent.click(screen.getByTestId("dialog-submit"));
+
+      await waitFor(() => {
+        expect(screen.getByRole("button", { name: /quote requested/i })).toBeInTheDocument();
+        expect(screen.queryByRole("button", { name: /^request a quote$/i })).not.toBeInTheDocument();
+      });
+    });
+  });
+
+  describe("cancel quote request", () => {
+    it("calls DELETE /api/public/inspection-quote-request with correct body", async () => {
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ success: true }),
+      });
+      render(<InspectionView {...DEFAULT_PROPS} hasExistingQuoteRequest={true} />);
+      await userEvent.click(screen.getByRole("button", { name: /quote requested/i }));
+
+      await waitFor(() => {
+        expect(mockFetch).toHaveBeenCalledWith(
+          "/api/public/inspection-quote-request",
+          expect.objectContaining({ method: "DELETE" })
+        );
+        const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+        expect(body.inspectionId).toBe("insp-1");
+        expect(body.publicToken).toBe("pub-tok-insp");
+      });
+    });
+
+    it("shows Request a Quote button after successful cancellation", async () => {
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ success: true }),
+      });
+      render(<InspectionView {...DEFAULT_PROPS} hasExistingQuoteRequest={true} />);
+      await userEvent.click(screen.getByRole("button", { name: /quote requested/i }));
+
+      await waitFor(() => {
+        expect(screen.getByRole("button", { name: /request a quote/i })).toBeInTheDocument();
+      });
+    });
+
+    it("shows toast success after cancellation", async () => {
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ success: true }),
+      });
+      render(<InspectionView {...DEFAULT_PROPS} hasExistingQuoteRequest={true} />);
+      await userEvent.click(screen.getByRole("button", { name: /quote requested/i }));
+
+      await waitFor(() => {
+        expect(toast.success).toHaveBeenCalledWith("Quote request cancelled");
+      });
+    });
+
+    it("shows toast error when cancellation fails", async () => {
+      mockFetch.mockResolvedValue({
+        ok: false,
+        json: () => Promise.resolve({ success: false, error: "Not found" }),
+      });
+      render(<InspectionView {...DEFAULT_PROPS} hasExistingQuoteRequest={true} />);
+      await userEvent.click(screen.getByRole("button", { name: /quote requested/i }));
+
+      await waitFor(() => {
+        expect(toast.error).toHaveBeenCalledWith("Not found");
+      });
+    });
+  });
+
+  describe("Download PDF", () => {
+    it("opens the PDF in a new window with the correct URL", async () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /download pdf/i }));
+      expect(mockWindowOpen).toHaveBeenCalledWith(
+        "/api/share/inspection/org-1/pub-tok-insp/pdf",
+        "_blank"
+      );
+    });
+  });
+
+  describe("quote available banner", () => {
+    it("shows the quote available banner when quoteShareUrl is provided", () => {
+      render(<InspectionView {...DEFAULT_PROPS} quoteShareUrl="/share/quote/org-1/quote-tok" />);
+      expect(screen.getByText(/a quote has been prepared/i)).toBeInTheDocument();
+    });
+
+    it("renders View Quote link pointing to the share URL", () => {
+      render(<InspectionView {...DEFAULT_PROPS} quoteShareUrl="/share/quote/org-1/quote-tok" />);
+      const link = screen.getByRole("link", { name: /view quote/i });
+      expect(link).toHaveAttribute("href", "/share/quote/org-1/quote-tok");
+    });
+
+    it("does not show quote banner when quoteShareUrl is not provided", () => {
+      render(<InspectionView {...DEFAULT_PROPS} />);
+      expect(screen.queryByText(/a quote has been prepared/i)).not.toBeInTheDocument();
+    });
+  });
+
+  describe("image carousel", () => {
+    // Use a PASS item (Check icon) to avoid collision with the Fail badge X icon
+    const IMG_ITEM = {
+      ...PASS_ITEM,
+      name: "Oil Level",
+      imageUrls: ["/api/files/public/tok/services/photo1.jpg"],
+    };
+
+    it("renders inspection image thumbnails", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        inspection: { ...BASE_INSPECTION, items: [IMG_ITEM] },
+      };
+      render(<InspectionView {...props} />);
+      expect(screen.getByAltText("Oil Level 1")).toBeInTheDocument();
+    });
+
+    it("opens carousel when image is clicked", async () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        inspection: { ...BASE_INSPECTION, items: [IMG_ITEM] },
+      };
+      render(<InspectionView {...props} />);
+      const thumbnail = screen.getByAltText("Oil Level 1").closest("button")!;
+      await userEvent.click(thumbnail);
+      // Carousel modal appears — only one X icon because PASS uses Check icon
+      expect(screen.getByTestId("icon-x").closest("button")).toBeInTheDocument();
+    });
+
+    it("closes carousel when X button is clicked", async () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        inspection: { ...BASE_INSPECTION, items: [IMG_ITEM] },
+      };
+      render(<InspectionView {...props} />);
+      await userEvent.click(screen.getByAltText("Oil Level 1").closest("button")!);
+      await userEvent.click(screen.getByTestId("icon-x").closest("button")!);
+      // After close, the carousel X button is gone
+      expect(screen.queryByTestId("icon-x")).not.toBeInTheDocument();
+    });
+  });
+});

+ 440 - 0
src/__tests__/features/public/invoice-view.test.tsx

@@ -0,0 +1,440 @@
+import { describe, it, expect, vi, beforeEach, beforeAll } from "vitest";
+import { render, screen, waitFor, fireEvent } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+vi.mock("lucide-react", () => ({
+  Camera: () => <span data-testid="icon-camera" />,
+  ChevronLeft: () => <span data-testid="icon-chevron-left" />,
+  ChevronRight: () => <span data-testid="icon-chevron-right" />,
+  CreditCard: () => <span data-testid="icon-credit-card" />,
+  Download: () => <span data-testid="icon-download" />,
+  FileText: () => <span data-testid="icon-file-text" />,
+  Film: () => <span data-testid="icon-film" />,
+  Loader2: () => <span data-testid="icon-loader" />,
+  Paperclip: () => <span data-testid="icon-paperclip" />,
+  X: () => <span data-testid="icon-x" />,
+}));
+
+import { InvoiceView } from "@/app/(public)/share/invoice/[orgId]/[token]/invoice-view";
+
+const WORKSHOP = {
+  name: "Speed Shop",
+  address: "123 Main St",
+  phone: "555-1234",
+  email: "shop@example.com",
+};
+
+const VEHICLE = {
+  make: "Honda",
+  model: "Civic",
+  year: 2019,
+  vin: "VIN999",
+  licensePlate: "XYZ-789",
+  mileage: 55000,
+  customer: {
+    name: "Bob Builder",
+    email: "bob@example.com",
+    phone: "555-0001",
+    address: "99 Build St",
+    company: null,
+  },
+};
+
+const BASE_RECORD = {
+  id: "inv-1",
+  title: "Full Service",
+  description: null,
+  type: "service",
+  status: "completed",
+  serviceDate: new Date("2024-03-10"),
+  shopName: null,
+  techName: "Alice",
+  mileage: 55000,
+  diagnosticNotes: null,
+  invoiceNotes: null,
+  subtotal: 200,
+  taxRate: 0,
+  taxAmount: 0,
+  totalAmount: 200,
+  cost: 200,
+  invoiceNumber: "INV-0001",
+  manuallyPaid: false,
+  discountType: null,
+  discountValue: 0,
+  discountAmount: 0,
+  partItems: [],
+  laborItems: [],
+  payments: [],
+  attachments: [],
+  vehicle: VEHICLE,
+};
+
+const DEFAULT_PROPS = {
+  record: BASE_RECORD,
+  workshop: WORKSHOP,
+  currencyCode: "USD",
+  orgId: "org-1",
+  token: "tok-xyz",
+  enabledProviders: [],
+};
+
+let mockFetch: ReturnType<typeof vi.fn>;
+
+beforeAll(() => {
+  URL.createObjectURL = vi.fn().mockReturnValue("blob:mock-url");
+  URL.revokeObjectURL = vi.fn();
+});
+
+beforeEach(() => {
+  vi.resetAllMocks();
+  URL.createObjectURL = vi.fn().mockReturnValue("blob:mock-url");
+  URL.revokeObjectURL = vi.fn();
+  mockFetch = vi.fn();
+  vi.stubGlobal("fetch", mockFetch);
+  // Default: no payment params in URL
+  vi.stubGlobal("location", {
+    search: "",
+    pathname: "/share/invoice/org-1/tok-xyz",
+    href: "http://localhost/share/invoice/org-1/tok-xyz",
+  });
+  vi.stubGlobal("history", { replaceState: vi.fn() });
+});
+
+describe("InvoiceView", () => {
+  describe("rendering", () => {
+    it("renders invoice number and title", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("INV-0001")).toBeInTheDocument();
+      expect(screen.getByText("Full Service")).toBeInTheDocument();
+    });
+
+    it("renders Download PDF button", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} />);
+      expect(screen.getByRole("button", { name: /download pdf/i })).toBeInTheDocument();
+    });
+
+    it("renders customer info in Bill To section", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("Bill To")).toBeInTheDocument();
+      expect(screen.getByText("Bob Builder")).toBeInTheDocument();
+      expect(screen.getByText("bob@example.com")).toBeInTheDocument();
+    });
+
+    it("renders vehicle info", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("2019 Honda Civic")).toBeInTheDocument();
+    });
+
+    it("renders technician name", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("Tech: Alice")).toBeInTheDocument();
+    });
+
+    it("renders parts table when parts are present", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        record: {
+          ...BASE_RECORD,
+          partItems: [{ partNumber: "B-200", name: "Brake Pads", quantity: 2, unitPrice: 45, total: 90 }],
+        },
+      };
+      render(<InvoiceView {...props} />);
+      expect(screen.getByText("Parts")).toBeInTheDocument();
+      expect(screen.getByText("Brake Pads")).toBeInTheDocument();
+    });
+
+    it("renders labor table when labor items are present", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        record: {
+          ...BASE_RECORD,
+          laborItems: [{ description: "Brake Replacement", hours: 1.5, rate: 90, total: 135 }],
+        },
+      };
+      render(<InvoiceView {...props} />);
+      expect(screen.getByText("Labor")).toBeInTheDocument();
+      expect(screen.getByText("Brake Replacement")).toBeInTheDocument();
+    });
+
+    it("renders terms of sale link when termsOfSaleUrl is provided", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} termsOfSaleUrl="https://example.com/terms" />);
+      const link = screen.getByRole("link", { name: /terms of sale/i });
+      expect(link).toHaveAttribute("href", "https://example.com/terms");
+    });
+
+    it("does not render terms of sale link when not provided", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} />);
+      expect(screen.queryByRole("link", { name: /terms of sale/i })).not.toBeInTheDocument();
+    });
+  });
+
+  describe("payment section", () => {
+    it("shows payment section when balance is due and providers are enabled", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        enabledProviders: ["stripe"],
+      };
+      render(<InvoiceView {...props} />);
+      expect(screen.getByText("Balance Due")).toBeInTheDocument();
+    });
+
+    it("hides payment provider buttons when invoice is manually paid", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        enabledProviders: ["stripe"],
+        record: { ...BASE_RECORD, manuallyPaid: true },
+      };
+      render(<InvoiceView {...props} />);
+      // Payment provider buttons should not render when balance is zero
+      expect(screen.queryByRole("button", { name: /pay.*card/i })).not.toBeInTheDocument();
+    });
+
+    it("hides payment provider buttons when balance is zero from payments", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        enabledProviders: ["stripe"],
+        record: {
+          ...BASE_RECORD,
+          payments: [{ amount: 200, date: new Date(), method: "card" }],
+        },
+      };
+      render(<InvoiceView {...props} />);
+      expect(screen.queryByRole("button", { name: /pay.*card/i })).not.toBeInTheDocument();
+    });
+
+    it("shows Stripe pay button when stripe provider is enabled", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["stripe"]} />);
+      expect(screen.getByRole("button", { name: /pay.*card/i })).toBeInTheDocument();
+    });
+
+    it("shows Vipps pay button when vipps provider is enabled", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["vipps"]} />);
+      expect(screen.getByRole("button", { name: /pay.*vipps/i })).toBeInTheDocument();
+    });
+
+    it("shows PayPal pay button when paypal provider is enabled", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["paypal"]} />);
+      expect(screen.getByRole("button", { name: /pay.*paypal/i })).toBeInTheDocument();
+    });
+
+    it("shows Full amount and Partial payment toggle buttons", () => {
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["stripe"]} />);
+      expect(screen.getByRole("button", { name: /full amount/i })).toBeInTheDocument();
+      expect(screen.getByRole("button", { name: /partial payment/i })).toBeInTheDocument();
+    });
+
+    it("shows amount input when Partial payment is selected", async () => {
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["stripe"]} />);
+      await userEvent.click(screen.getByRole("button", { name: /partial payment/i }));
+      expect(screen.getByLabelText(/enter amount/i)).toBeInTheDocument();
+    });
+
+    it("hides amount input when Full amount is re-selected", async () => {
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["stripe"]} />);
+      await userEvent.click(screen.getByRole("button", { name: /partial payment/i }));
+      expect(screen.getByLabelText(/enter amount/i)).toBeInTheDocument();
+      await userEvent.click(screen.getByRole("button", { name: /full amount/i }));
+      expect(screen.queryByLabelText(/enter amount/i)).not.toBeInTheDocument();
+    });
+
+    it("shows validation error when amount is invalid", async () => {
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["stripe"]} />);
+      await userEvent.click(screen.getByRole("button", { name: /partial payment/i }));
+      const input = screen.getByLabelText(/enter amount/i);
+      // Use fireEvent for number inputs to avoid userEvent quirks with controlled inputs
+      fireEvent.change(input, { target: { value: "0" } });
+      await userEvent.click(screen.getByRole("button", { name: /pay.*card/i }));
+      await waitFor(() => {
+        expect(screen.getByText(/valid amount/i)).toBeInTheDocument();
+      });
+    });
+
+    it("calls checkout endpoint when pay button is clicked", async () => {
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ redirectUrl: "https://stripe.com/pay" }),
+      });
+      vi.stubGlobal("location", {
+        search: "",
+        pathname: "/share/invoice/org-1/tok-xyz",
+        href: "http://localhost/share/invoice/org-1/tok-xyz",
+        assign: vi.fn(),
+      });
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["stripe"]} />);
+      await userEvent.click(screen.getByRole("button", { name: /pay.*card/i }));
+
+      await waitFor(() => {
+        expect(mockFetch).toHaveBeenCalledWith(
+          "/api/share/invoice/org-1/tok-xyz/checkout",
+          expect.objectContaining({ method: "POST" })
+        );
+        const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+        expect(body.provider).toBe("stripe");
+        expect(body.amount).toBe(200);
+      });
+    });
+
+    it("shows payment error when checkout fails", async () => {
+      mockFetch.mockResolvedValue({
+        ok: false,
+        json: () => Promise.resolve({ error: "Provider unavailable" }),
+      });
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["stripe"]} />);
+      await userEvent.click(screen.getByRole("button", { name: /pay.*card/i }));
+
+      await waitFor(() => {
+        expect(screen.getByText("Provider unavailable")).toBeInTheDocument();
+      });
+    });
+
+    it("shows payment success banner after verifying payment from URL params", async () => {
+      vi.stubGlobal("location", {
+        search: "?session_id=stripe-session-123",
+        pathname: "/share/invoice/org-1/tok-xyz",
+        href: "http://localhost/share/invoice/org-1/tok-xyz?session_id=stripe-session-123",
+      });
+      vi.stubGlobal("history", { replaceState: vi.fn() });
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ verified: true, amount: 200 }),
+      });
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["stripe"]} />);
+
+      await waitFor(() => {
+        expect(screen.getByText(/payment received/i)).toBeInTheDocument();
+      });
+      expect(mockFetch).toHaveBeenCalledWith(
+        "/api/share/invoice/org-1/tok-xyz/verify",
+        expect.objectContaining({
+          method: "POST",
+          body: expect.stringContaining('"provider":"stripe"'),
+        })
+      );
+    });
+
+    it("verifies Vipps payment from reference URL param", async () => {
+      vi.stubGlobal("location", {
+        search: "?reference=vipps-ref-456",
+        pathname: "/share/invoice/org-1/tok-xyz",
+        href: "http://localhost/share/invoice/org-1/tok-xyz?reference=vipps-ref-456",
+      });
+      vi.stubGlobal("history", { replaceState: vi.fn() });
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ verified: true, amount: 200 }),
+      });
+      render(<InvoiceView {...DEFAULT_PROPS} enabledProviders={["vipps"]} />);
+
+      await waitFor(() => {
+        const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+        expect(body.provider).toBe("vipps");
+        expect(body.externalId).toBe("vipps-ref-456");
+      });
+    });
+
+    it("shows PAID IN FULL when balance is zero", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        record: {
+          ...BASE_RECORD,
+          payments: [{ amount: 200, date: new Date(), method: "card" }],
+        },
+      };
+      render(<InvoiceView {...props} />);
+      expect(screen.getByText("PAID IN FULL")).toBeInTheDocument();
+    });
+  });
+
+  describe("service images", () => {
+    const IMAGE_ATTACHMENT = {
+      id: "att-1",
+      fileName: "service-photo.jpg",
+      fileUrl: "/api/files/public/tok-xyz/services/service-photo.jpg",
+      fileType: "image/jpeg",
+      fileSize: 50000,
+      category: "services",
+      description: "Before photo",
+    };
+
+    it("renders image thumbnails when image attachments are present", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        record: { ...BASE_RECORD, attachments: [IMAGE_ATTACHMENT] },
+      };
+      render(<InvoiceView {...props} />);
+      expect(screen.getByText(/service images/i)).toBeInTheDocument();
+      expect(screen.getByAltText("Before photo")).toBeInTheDocument();
+    });
+
+    it("opens carousel when image thumbnail is clicked", async () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        record: { ...BASE_RECORD, attachments: [IMAGE_ATTACHMENT] },
+      };
+      render(<InvoiceView {...props} />);
+      const thumbnail = screen.getByAltText("Before photo");
+      await userEvent.click(thumbnail.closest("button")!);
+      // Carousel is shown (image is in a fullscreen modal)
+      expect(screen.getAllByAltText("Before photo").length).toBeGreaterThan(1);
+    });
+
+    it("closes carousel when X button is clicked", async () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        record: { ...BASE_RECORD, attachments: [IMAGE_ATTACHMENT] },
+      };
+      render(<InvoiceView {...props} />);
+      await userEvent.click(screen.getByAltText("Before photo").closest("button")!);
+      const closeBtn = screen.getByTestId("icon-x").closest("button")!;
+      await userEvent.click(closeBtn);
+      // After closing, only one image remains (the thumbnail)
+      expect(screen.getAllByAltText("Before photo").length).toBe(1);
+    });
+
+    it("deduplicates images with the same filename", () => {
+      const duplicate = { ...IMAGE_ATTACHMENT, id: "att-2" };
+      const props = {
+        ...DEFAULT_PROPS,
+        record: { ...BASE_RECORD, attachments: [IMAGE_ATTACHMENT, duplicate] },
+      };
+      render(<InvoiceView {...props} />);
+      // Should show "1" in the title, not "2"
+      expect(screen.getByText(/service images \(1\)/i)).toBeInTheDocument();
+    });
+  });
+
+  describe("diagnostic reports", () => {
+    it("renders PDF attachment as a downloadable link", () => {
+      const pdfAttachment = {
+        id: "att-pdf",
+        fileName: "diagnostic.pdf",
+        fileUrl: "/api/files/public/tok-xyz/services/diagnostic.pdf",
+        fileType: "application/pdf",
+        fileSize: 20000,
+        category: "services",
+        description: null,
+      };
+      const props = {
+        ...DEFAULT_PROPS,
+        record: { ...BASE_RECORD, attachments: [pdfAttachment] },
+      };
+      render(<InvoiceView {...props} />);
+      expect(screen.getByText(/diagnostic reports/i)).toBeInTheDocument();
+      const link = screen.getByRole("link", { name: /diagnostic.pdf/i });
+      expect(link).toHaveAttribute("download", "diagnostic.pdf");
+    });
+  });
+
+  describe("Download PDF", () => {
+    it("fetches the PDF from the correct API URL", async () => {
+      const mockBlob = new Blob(["pdf"], { type: "application/pdf" });
+      mockFetch.mockResolvedValue({ ok: true, blob: () => Promise.resolve(mockBlob) });
+      render(<InvoiceView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /download pdf/i }));
+
+      await waitFor(() => {
+        expect(mockFetch).toHaveBeenCalledWith("/api/share/invoice/org-1/tok-xyz/pdf");
+      });
+    });
+  });
+});

+ 369 - 0
src/__tests__/features/public/quote-view.test.tsx

@@ -0,0 +1,369 @@
+import { describe, it, expect, vi, beforeEach, beforeAll } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+vi.mock("lucide-react", () => ({
+  Check: () => <span data-testid="icon-check" />,
+  Download: () => <span data-testid="icon-download" />,
+  Loader2: () => <span data-testid="icon-loader" />,
+  MessageSquare: () => <span data-testid="icon-message" />,
+}));
+
+import { QuoteView } from "@/app/(public)/share/quote/[orgId]/[token]/quote-view";
+
+const WORKSHOP = {
+  name: "Speed Shop",
+  address: "123 Main St",
+  phone: "555-1234",
+  email: "shop@example.com",
+};
+
+const BASE_QUOTE = {
+  id: "quote-1",
+  quoteNumber: "QT-0001",
+  title: "Oil Change & Filter",
+  description: null,
+  status: "sent",
+  validUntil: null,
+  createdAt: new Date("2024-01-15"),
+  subtotal: 100,
+  taxRate: 0,
+  taxAmount: 0,
+  discountType: null,
+  discountValue: 0,
+  discountAmount: 0,
+  totalAmount: 100,
+  notes: null,
+  partItems: [],
+  laborItems: [],
+  customer: null,
+  vehicle: null,
+};
+
+const DEFAULT_PROPS = {
+  quote: BASE_QUOTE,
+  workshop: WORKSHOP,
+  currencyCode: "USD",
+  orgId: "org-1",
+  token: "tok-abc",
+};
+
+let mockFetch: ReturnType<typeof vi.fn>;
+
+beforeAll(() => {
+  URL.createObjectURL = vi.fn().mockReturnValue("blob:mock-url");
+  URL.revokeObjectURL = vi.fn();
+});
+
+beforeEach(() => {
+  vi.resetAllMocks();
+  URL.createObjectURL = vi.fn().mockReturnValue("blob:mock-url");
+  URL.revokeObjectURL = vi.fn();
+  mockFetch = vi.fn();
+  vi.stubGlobal("fetch", mockFetch);
+});
+
+describe("QuoteView", () => {
+  describe("rendering", () => {
+    it("renders the quote number and title", () => {
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      expect(screen.getByText("QT-0001")).toBeInTheDocument();
+      expect(screen.getByText("Oil Change & Filter")).toBeInTheDocument();
+    });
+
+    it("renders the Download PDF button", () => {
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      expect(screen.getByRole("button", { name: /download pdf/i })).toBeInTheDocument();
+    });
+
+    it("renders customer info when provided", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        quote: {
+          ...BASE_QUOTE,
+          customer: {
+            name: "Jane Doe",
+            email: "jane@example.com",
+            phone: "555-9999",
+            address: "1 Park Ave",
+            company: "Acme Corp",
+          },
+        },
+      };
+      render(<QuoteView {...props} />);
+      expect(screen.getByText("Jane Doe")).toBeInTheDocument();
+      expect(screen.getByText("jane@example.com")).toBeInTheDocument();
+      expect(screen.getByText("Acme Corp")).toBeInTheDocument();
+    });
+
+    it("renders vehicle info when provided", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        quote: {
+          ...BASE_QUOTE,
+          vehicle: { year: 2020, make: "Toyota", model: "Camry", vin: "VIN123", licensePlate: "ABC-123" },
+        },
+      };
+      render(<QuoteView {...props} />);
+      expect(screen.getByText("2020 Toyota Camry")).toBeInTheDocument();
+      expect(screen.getByText("VIN: VIN123")).toBeInTheDocument();
+      expect(screen.getByText("Plate: ABC-123")).toBeInTheDocument();
+    });
+
+    it("renders parts table when parts are present", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        quote: {
+          ...BASE_QUOTE,
+          partItems: [{ partNumber: "P-001", name: "Oil Filter", quantity: 1, unitPrice: 15, total: 15 }],
+        },
+      };
+      render(<QuoteView {...props} />);
+      expect(screen.getByText("Parts")).toBeInTheDocument();
+      expect(screen.getByText("Oil Filter")).toBeInTheDocument();
+      expect(screen.getByText("P-001")).toBeInTheDocument();
+    });
+
+    it("does not render parts table when there are no parts", () => {
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      expect(screen.queryByText("Parts")).not.toBeInTheDocument();
+    });
+
+    it("renders labor table when labor items are present", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        quote: {
+          ...BASE_QUOTE,
+          laborItems: [{ description: "Labor - Oil Change", hours: 0.5, rate: 80, total: 40 }],
+        },
+      };
+      render(<QuoteView {...props} />);
+      expect(screen.getByText("Labor")).toBeInTheDocument();
+      expect(screen.getByText("Labor - Oil Change")).toBeInTheDocument();
+    });
+
+    it("renders tax row when taxRate > 0", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        quote: { ...BASE_QUOTE, taxRate: 10, taxAmount: 10, totalAmount: 110 },
+      };
+      render(<QuoteView {...props} />);
+      expect(screen.getByText("Tax (10%)")).toBeInTheDocument();
+    });
+
+    it("renders discount row when discountAmount > 0", () => {
+      const props = {
+        ...DEFAULT_PROPS,
+        quote: {
+          ...BASE_QUOTE,
+          discountType: "fixed",
+          discountValue: 10,
+          discountAmount: 10,
+          subtotal: 110,
+          totalAmount: 100,
+        },
+      };
+      render(<QuoteView {...props} />);
+      expect(screen.getByText(/discount/i)).toBeInTheDocument();
+    });
+
+    it("renders workshop name in header", () => {
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      // Name appears in both the header h2 and the footer — verify at least one is a heading
+      const instances = screen.getAllByText("Speed Shop");
+      expect(instances.length).toBeGreaterThanOrEqual(1);
+      expect(instances.some((el) => el.tagName === "H2")).toBe(true);
+    });
+  });
+
+  describe("status badges and action buttons", () => {
+    it("shows Accept Quote and Request Changes buttons when status=sent", () => {
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      expect(screen.getByRole("button", { name: /accept quote/i })).toBeInTheDocument();
+      expect(screen.getByRole("button", { name: /request changes/i })).toBeInTheDocument();
+    });
+
+    it("shows Accept Quote and Request Changes buttons when status=draft", () => {
+      const props = { ...DEFAULT_PROPS, quote: { ...BASE_QUOTE, status: "draft" } };
+      render(<QuoteView {...props} />);
+      expect(screen.getByRole("button", { name: /accept quote/i })).toBeInTheDocument();
+    });
+
+    it("hides action buttons when status=accepted", () => {
+      const props = { ...DEFAULT_PROPS, quote: { ...BASE_QUOTE, status: "accepted" } };
+      render(<QuoteView {...props} />);
+      expect(screen.queryByRole("button", { name: /accept quote/i })).not.toBeInTheDocument();
+      expect(screen.queryByRole("button", { name: /request changes/i })).not.toBeInTheDocument();
+    });
+
+    it("hides action buttons when status=rejected", () => {
+      const props = { ...DEFAULT_PROPS, quote: { ...BASE_QUOTE, status: "rejected" } };
+      render(<QuoteView {...props} />);
+      expect(screen.queryByRole("button", { name: /accept quote/i })).not.toBeInTheDocument();
+    });
+
+    it("hides action buttons when status=expired", () => {
+      const props = { ...DEFAULT_PROPS, quote: { ...BASE_QUOTE, status: "expired" } };
+      render(<QuoteView {...props} />);
+      expect(screen.queryByRole("button", { name: /accept quote/i })).not.toBeInTheDocument();
+    });
+
+    it("shows Quote Accepted confirmation when status=accepted", () => {
+      const props = { ...DEFAULT_PROPS, quote: { ...BASE_QUOTE, status: "accepted" } };
+      render(<QuoteView {...props} />);
+      expect(screen.getByText("Quote Accepted")).toBeInTheDocument();
+    });
+
+    it("shows Changes Requested confirmation when status=changes_requested", () => {
+      const props = { ...DEFAULT_PROPS, quote: { ...BASE_QUOTE, status: "changes_requested" } };
+      render(<QuoteView {...props} />);
+      // Unique confirmation message (the badge also says "Changes Requested" but this text is unique)
+      expect(screen.getByText(/your change request has been submitted/i)).toBeInTheDocument();
+    });
+  });
+
+  describe("Accept Quote interaction", () => {
+    it("calls /api/public/quote-response with action=accepted", async () => {
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ success: true }),
+      });
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /accept quote/i }));
+
+      await waitFor(() => {
+        expect(mockFetch).toHaveBeenCalledWith(
+          "/api/public/quote-response",
+          expect.objectContaining({ method: "POST" })
+        );
+        const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+        expect(body.action).toBe("accepted");
+        expect(body.quoteId).toBe("quote-1");
+        expect(body.publicToken).toBe("tok-abc");
+      });
+    });
+
+    it("shows Quote Accepted message after successful accept", async () => {
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ success: true }),
+      });
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /accept quote/i }));
+
+      await waitFor(() => {
+        expect(screen.getByText("Quote Accepted")).toBeInTheDocument();
+      });
+    });
+
+    it("hides action buttons after accepting", async () => {
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ success: true }),
+      });
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /accept quote/i }));
+
+      await waitFor(() => {
+        expect(screen.queryByRole("button", { name: /accept quote/i })).not.toBeInTheDocument();
+      });
+    });
+  });
+
+  describe("Request Changes interaction", () => {
+    it("shows the changes form when Request Changes is clicked", async () => {
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /request changes/i }));
+      expect(screen.getByPlaceholderText(/describe the changes/i)).toBeInTheDocument();
+    });
+
+    it("Submit Request button is disabled when message is empty", async () => {
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /request changes/i }));
+      expect(screen.getByRole("button", { name: /submit request/i })).toBeDisabled();
+    });
+
+    it("Submit Request button is enabled after typing a message", async () => {
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /request changes/i }));
+      await userEvent.type(screen.getByPlaceholderText(/describe the changes/i), "Please fix the price");
+      expect(screen.getByRole("button", { name: /submit request/i })).not.toBeDisabled();
+    });
+
+    it("submits changes_requested with the typed message", async () => {
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ success: true }),
+      });
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /request changes/i }));
+      await userEvent.type(screen.getByPlaceholderText(/describe the changes/i), "Need a discount");
+      await userEvent.click(screen.getByRole("button", { name: /submit request/i }));
+
+      await waitFor(() => {
+        const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+        expect(body.action).toBe("changes_requested");
+        expect(body.message).toBe("Need a discount");
+      });
+    });
+
+    it("shows Changes Requested confirmation after submitting", async () => {
+      mockFetch.mockResolvedValue({
+        ok: true,
+        json: () => Promise.resolve({ success: true }),
+      });
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /request changes/i }));
+      await userEvent.type(screen.getByPlaceholderText(/describe the changes/i), "Fix it");
+      await userEvent.click(screen.getByRole("button", { name: /submit request/i }));
+
+      await waitFor(() => {
+        expect(screen.getByText(/your change request has been submitted/i)).toBeInTheDocument();
+        expect(screen.queryByPlaceholderText(/describe the changes/i)).not.toBeInTheDocument();
+      });
+    });
+
+    it("Cancel button hides the changes form", async () => {
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /request changes/i }));
+      expect(screen.getByPlaceholderText(/describe the changes/i)).toBeInTheDocument();
+      await userEvent.click(screen.getByRole("button", { name: /^cancel$/i }));
+      expect(screen.queryByPlaceholderText(/describe the changes/i)).not.toBeInTheDocument();
+    });
+  });
+
+  describe("Download PDF", () => {
+    it("fetches the PDF from the correct API URL", async () => {
+      const mockBlob = new Blob(["pdf"], { type: "application/pdf" });
+      mockFetch.mockResolvedValue({ ok: true, blob: () => Promise.resolve(mockBlob) });
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /download pdf/i }));
+
+      await waitFor(() => {
+        expect(mockFetch).toHaveBeenCalledWith("/api/share/quote/org-1/tok-abc/pdf");
+      });
+    });
+
+    it("creates an object URL for the downloaded blob", async () => {
+      const mockBlob = new Blob(["pdf"], { type: "application/pdf" });
+      mockFetch.mockResolvedValue({ ok: true, blob: () => Promise.resolve(mockBlob) });
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /download pdf/i }));
+
+      await waitFor(() => {
+        expect(URL.createObjectURL).toHaveBeenCalledWith(mockBlob);
+      });
+    });
+
+    it("revokes the object URL after download", async () => {
+      const mockBlob = new Blob(["pdf"], { type: "application/pdf" });
+      mockFetch.mockResolvedValue({ ok: true, blob: () => Promise.resolve(mockBlob) });
+      render(<QuoteView {...DEFAULT_PROPS} />);
+      await userEvent.click(screen.getByRole("button", { name: /download pdf/i }));
+
+      await waitFor(() => {
+        expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:mock-url");
+      });
+    });
+  });
+});

+ 200 - 0
src/__tests__/features/public/quoteRequestActions.test.ts

@@ -0,0 +1,200 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("@/lib/db", () => ({
+  db: {
+    inspection: {
+      findFirst: vi.fn(),
+    },
+    inspectionQuoteRequest: {
+      findFirst: vi.fn(),
+      create: vi.fn(),
+      delete: vi.fn(),
+    },
+  },
+}));
+
+vi.mock("@/lib/notify", () => ({
+  notify: vi.fn(),
+}));
+
+import { createQuoteRequest, cancelQuoteRequest } from "@/features/inspections/Actions/quoteRequestActions";
+import { db } from "@/lib/db";
+import { notify } from "@/lib/notify";
+
+const mockFindInspection = vi.mocked(db.inspection.findFirst);
+const mockFindRequest = vi.mocked(db.inspectionQuoteRequest.findFirst);
+const mockCreateRequest = vi.mocked(db.inspectionQuoteRequest.create);
+const mockDeleteRequest = vi.mocked(db.inspectionQuoteRequest.delete);
+const mockNotify = vi.mocked(notify);
+
+const INSPECTION = {
+  id: "insp-1",
+  publicToken: "pub-tok-1",
+  organizationId: "org-1",
+  vehicle: { customer: { name: "Jane Smith" } },
+};
+
+const PENDING_REQUEST = {
+  id: "req-1",
+  inspectionId: "insp-1",
+  status: "pending",
+};
+
+beforeEach(() => {
+  vi.resetAllMocks();
+  mockCreateRequest.mockResolvedValue({} as any);
+  mockDeleteRequest.mockResolvedValue({} as any);
+});
+
+describe("createQuoteRequest", () => {
+  it("throws ZodError when required fields are missing", async () => {
+    await expect(createQuoteRequest({})).rejects.toThrow();
+  });
+
+  it("throws ZodError when selectedItemIds is empty", async () => {
+    await expect(
+      createQuoteRequest({ inspectionId: "insp-1", publicToken: "tok-1", selectedItemIds: [] })
+    ).rejects.toThrow();
+  });
+
+  it("returns error when inspection is not found", async () => {
+    mockFindInspection.mockResolvedValue(null);
+    const result = await createQuoteRequest({
+      inspectionId: "bad-id",
+      publicToken: "bad-token",
+      selectedItemIds: ["item-1"],
+    });
+    expect(result).toEqual({ success: false, error: "Inspection not found" });
+  });
+
+  it("returns error when a pending request already exists", async () => {
+    mockFindInspection.mockResolvedValue(INSPECTION as any);
+    mockFindRequest.mockResolvedValue(PENDING_REQUEST as any);
+    const result = await createQuoteRequest({
+      inspectionId: "insp-1",
+      publicToken: "pub-tok-1",
+      selectedItemIds: ["item-1"],
+    });
+    expect(result).toEqual({
+      success: false,
+      error: "A quote request is already pending for this inspection",
+    });
+  });
+
+  it("creates the request and returns success", async () => {
+    mockFindInspection.mockResolvedValue(INSPECTION as any);
+    mockFindRequest.mockResolvedValue(null);
+    const result = await createQuoteRequest({
+      inspectionId: "insp-1",
+      publicToken: "pub-tok-1",
+      selectedItemIds: ["item-1", "item-2"],
+    });
+    expect(result).toEqual({ success: true });
+    expect(mockCreateRequest).toHaveBeenCalledWith({
+      data: expect.objectContaining({
+        inspectionId: "insp-1",
+        selectedItemIds: ["item-1", "item-2"],
+        organizationId: "org-1",
+      }),
+    });
+  });
+
+  it("stores optional message in the quote request", async () => {
+    mockFindInspection.mockResolvedValue(INSPECTION as any);
+    mockFindRequest.mockResolvedValue(null);
+    await createQuoteRequest({
+      inspectionId: "insp-1",
+      publicToken: "pub-tok-1",
+      selectedItemIds: ["item-1"],
+      message: "Please prioritize the brakes",
+    });
+    expect(mockCreateRequest).toHaveBeenCalledWith({
+      data: expect.objectContaining({ message: "Please prioritize the brakes" }),
+    });
+  });
+
+  it("sends a notification after creating the request", async () => {
+    mockFindInspection.mockResolvedValue(INSPECTION as any);
+    mockFindRequest.mockResolvedValue(null);
+    await createQuoteRequest({
+      inspectionId: "insp-1",
+      publicToken: "pub-tok-1",
+      selectedItemIds: ["item-1", "item-2"],
+    });
+    expect(mockNotify).toHaveBeenCalledWith(
+      expect.objectContaining({
+        organizationId: "org-1",
+        type: "inspection_quote_request",
+        entityId: "insp-1",
+      })
+    );
+  });
+
+  it("includes item count in notification message", async () => {
+    mockFindInspection.mockResolvedValue(INSPECTION as any);
+    mockFindRequest.mockResolvedValue(null);
+    await createQuoteRequest({
+      inspectionId: "insp-1",
+      publicToken: "pub-tok-1",
+      selectedItemIds: ["item-1", "item-2", "item-3"],
+    });
+    expect(mockNotify).toHaveBeenCalledWith(
+      expect.objectContaining({ message: expect.stringContaining("3 item(s)") })
+    );
+  });
+
+  it("uses customer name in notification message", async () => {
+    mockFindInspection.mockResolvedValue(INSPECTION as any);
+    mockFindRequest.mockResolvedValue(null);
+    await createQuoteRequest({
+      inspectionId: "insp-1",
+      publicToken: "pub-tok-1",
+      selectedItemIds: ["item-1"],
+    });
+    expect(mockNotify).toHaveBeenCalledWith(
+      expect.objectContaining({ message: expect.stringContaining("Jane Smith") })
+    );
+  });
+
+  it("falls back to 'A customer' when customer is missing", async () => {
+    mockFindInspection.mockResolvedValue({ ...INSPECTION, vehicle: { customer: null } } as any);
+    mockFindRequest.mockResolvedValue(null);
+    await createQuoteRequest({
+      inspectionId: "insp-1",
+      publicToken: "pub-tok-1",
+      selectedItemIds: ["item-1"],
+    });
+    expect(mockNotify).toHaveBeenCalledWith(
+      expect.objectContaining({ message: expect.stringContaining("A customer") })
+    );
+  });
+});
+
+describe("cancelQuoteRequest", () => {
+  it("returns error when inspection is not found", async () => {
+    mockFindInspection.mockResolvedValue(null);
+    const result = await cancelQuoteRequest({ inspectionId: "bad-id", publicToken: "bad-token" });
+    expect(result).toEqual({ success: false, error: "Inspection not found" });
+  });
+
+  it("returns error when no pending request exists", async () => {
+    mockFindInspection.mockResolvedValue(INSPECTION as any);
+    mockFindRequest.mockResolvedValue(null);
+    const result = await cancelQuoteRequest({ inspectionId: "insp-1", publicToken: "pub-tok-1" });
+    expect(result).toEqual({ success: false, error: "No pending quote request found" });
+  });
+
+  it("deletes the pending request and returns success", async () => {
+    mockFindInspection.mockResolvedValue(INSPECTION as any);
+    mockFindRequest.mockResolvedValue(PENDING_REQUEST as any);
+    const result = await cancelQuoteRequest({ inspectionId: "insp-1", publicToken: "pub-tok-1" });
+    expect(result).toEqual({ success: true });
+    expect(mockDeleteRequest).toHaveBeenCalledWith({ where: { id: "req-1" } });
+  });
+
+  it("does not delete when inspection token does not match", async () => {
+    mockFindInspection.mockResolvedValue(null);
+    await cancelQuoteRequest({ inspectionId: "insp-1", publicToken: "wrong-token" });
+    expect(mockDeleteRequest).not.toHaveBeenCalled();
+  });
+});

+ 188 - 0
src/__tests__/features/public/respondToQuote.test.ts

@@ -0,0 +1,188 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("@/lib/db", () => ({
+  db: {
+    quote: {
+      findFirst: vi.fn(),
+      update: vi.fn(),
+    },
+  },
+}));
+
+vi.mock("@/lib/notify", () => ({
+  notify: vi.fn(),
+}));
+
+import { respondToQuote } from "@/features/quotes/Actions/quoteResponseActions";
+import { db } from "@/lib/db";
+import { notify } from "@/lib/notify";
+
+const mockFindFirst = vi.mocked(db.quote.findFirst);
+const mockUpdate = vi.mocked(db.quote.update);
+const mockNotify = vi.mocked(notify);
+
+const SENT_QUOTE = {
+  id: "quote-1",
+  quoteNumber: "QT-0001",
+  title: "Oil Change",
+  status: "sent",
+  organizationId: "org-1",
+  customer: { name: "John Doe" },
+};
+
+beforeEach(() => {
+  vi.resetAllMocks();
+  mockUpdate.mockResolvedValue({} as any);
+});
+
+describe("respondToQuote", () => {
+  it("throws ZodError when required fields are missing", async () => {
+    await expect(respondToQuote({})).rejects.toThrow();
+  });
+
+  it("throws ZodError when action is not a valid enum value", async () => {
+    await expect(
+      respondToQuote({ quoteId: "q-1", publicToken: "tok-1", action: "rejected" })
+    ).rejects.toThrow();
+  });
+
+  it("returns error when quote is not found", async () => {
+    mockFindFirst.mockResolvedValue(null);
+    const result = await respondToQuote({
+      quoteId: "bad-id",
+      publicToken: "bad-token",
+      action: "accepted",
+    });
+    expect(result).toEqual({ success: false, error: "Quote not found" });
+  });
+
+  it("returns error when quote status is already accepted", async () => {
+    mockFindFirst.mockResolvedValue({ ...SENT_QUOTE, status: "accepted" } as any);
+    const result = await respondToQuote({
+      quoteId: "quote-1",
+      publicToken: "tok-1",
+      action: "accepted",
+    });
+    expect(result).toEqual({ success: false, error: "This quote can no longer be updated" });
+  });
+
+  it("returns error when quote status is rejected", async () => {
+    mockFindFirst.mockResolvedValue({ ...SENT_QUOTE, status: "rejected" } as any);
+    const result = await respondToQuote({
+      quoteId: "quote-1",
+      publicToken: "tok-1",
+      action: "accepted",
+    });
+    expect(result).toEqual({ success: false, error: "This quote can no longer be updated" });
+  });
+
+  it("returns error when quote status is expired", async () => {
+    mockFindFirst.mockResolvedValue({ ...SENT_QUOTE, status: "expired" } as any);
+    const result = await respondToQuote({
+      quoteId: "quote-1",
+      publicToken: "tok-1",
+      action: "accepted",
+    });
+    expect(result).toEqual({ success: false, error: "This quote can no longer be updated" });
+  });
+
+  it("returns error when quote status is converted", async () => {
+    mockFindFirst.mockResolvedValue({ ...SENT_QUOTE, status: "converted" } as any);
+    const result = await respondToQuote({
+      quoteId: "quote-1",
+      publicToken: "tok-1",
+      action: "accepted",
+    });
+    expect(result).toEqual({ success: false, error: "This quote can no longer be updated" });
+  });
+
+  it("accepts a sent quote and updates status", async () => {
+    mockFindFirst.mockResolvedValue(SENT_QUOTE as any);
+    const result = await respondToQuote({
+      quoteId: "quote-1",
+      publicToken: "tok-1",
+      action: "accepted",
+    });
+    expect(result).toEqual({ success: true });
+    expect(mockUpdate).toHaveBeenCalledWith({
+      where: { id: "quote-1" },
+      data: { status: "accepted", customerMessage: null },
+    });
+  });
+
+  it("accepts a draft quote", async () => {
+    mockFindFirst.mockResolvedValue({ ...SENT_QUOTE, status: "draft" } as any);
+    const result = await respondToQuote({
+      quoteId: "quote-1",
+      publicToken: "tok-1",
+      action: "accepted",
+    });
+    expect(result).toEqual({ success: true });
+  });
+
+  it("submits changes_requested and stores customer message", async () => {
+    mockFindFirst.mockResolvedValue(SENT_QUOTE as any);
+    const result = await respondToQuote({
+      quoteId: "quote-1",
+      publicToken: "tok-1",
+      action: "changes_requested",
+      message: "Please add an extra oil filter",
+    });
+    expect(result).toEqual({ success: true });
+    expect(mockUpdate).toHaveBeenCalledWith({
+      where: { id: "quote-1" },
+      data: { status: "changes_requested", customerMessage: "Please add an extra oil filter" },
+    });
+  });
+
+  it("stores null customerMessage when no message is provided", async () => {
+    mockFindFirst.mockResolvedValue(SENT_QUOTE as any);
+    await respondToQuote({ quoteId: "quote-1", publicToken: "tok-1", action: "accepted" });
+    expect(mockUpdate).toHaveBeenCalledWith(
+      expect.objectContaining({ data: expect.objectContaining({ customerMessage: null }) })
+    );
+  });
+
+  it("sends a notification after accepting", async () => {
+    mockFindFirst.mockResolvedValue(SENT_QUOTE as any);
+    await respondToQuote({ quoteId: "quote-1", publicToken: "tok-1", action: "accepted" });
+    expect(mockNotify).toHaveBeenCalledWith(
+      expect.objectContaining({
+        organizationId: "org-1",
+        type: "quote_response",
+        title: "Quote Accepted",
+        entityId: "quote-1",
+      })
+    );
+  });
+
+  it("sends a notification after changes_requested", async () => {
+    mockFindFirst.mockResolvedValue(SENT_QUOTE as any);
+    await respondToQuote({ quoteId: "quote-1", publicToken: "tok-1", action: "changes_requested" });
+    expect(mockNotify).toHaveBeenCalledWith(
+      expect.objectContaining({ type: "quote_response", title: "Quote Changes Requested" })
+    );
+  });
+
+  it("does not send a notification when quote has no organizationId", async () => {
+    mockFindFirst.mockResolvedValue({ ...SENT_QUOTE, organizationId: null } as any);
+    await respondToQuote({ quoteId: "quote-1", publicToken: "tok-1", action: "accepted" });
+    expect(mockNotify).not.toHaveBeenCalled();
+  });
+
+  it("uses customer name in notification message", async () => {
+    mockFindFirst.mockResolvedValue({ ...SENT_QUOTE, customer: { name: "Alice" } } as any);
+    await respondToQuote({ quoteId: "quote-1", publicToken: "tok-1", action: "accepted" });
+    expect(mockNotify).toHaveBeenCalledWith(
+      expect.objectContaining({ message: expect.stringContaining("Alice") })
+    );
+  });
+
+  it("falls back to 'A customer' in notification when customer name is missing", async () => {
+    mockFindFirst.mockResolvedValue({ ...SENT_QUOTE, customer: null } as any);
+    await respondToQuote({ quoteId: "quote-1", publicToken: "tok-1", action: "accepted" });
+    expect(mockNotify).toHaveBeenCalledWith(
+      expect.objectContaining({ message: expect.stringContaining("A customer") })
+    );
+  });
+});

+ 101 - 0
src/__tests__/lib/get-auth-context.test.ts

@@ -0,0 +1,101 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("@/lib/cached-session", () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}));
+
+vi.mock("@/lib/db", () => ({
+  db: {
+    user: {
+      findUnique: vi.fn(),
+    },
+  },
+}));
+
+import { getAuthContext, getAuthContextDetailed } from "@/lib/get-auth-context";
+import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
+import { db } from "@/lib/db";
+
+const mockGetCachedSession = vi.mocked(getCachedSession);
+const mockGetCachedMembership = vi.mocked(getCachedMembership);
+const mockFindUnique = vi.mocked(db.user.findUnique);
+
+const SESSION = { user: { id: "user-1", email: "user@example.com" } };
+const MEMBERSHIP = {
+  organizationId: "org-1",
+  role: "member",
+  roleId: null,
+  customRole: null,
+};
+
+beforeEach(() => {
+  vi.resetAllMocks();
+});
+
+describe("getAuthContext", () => {
+  it("returns null when unauthenticated", async () => {
+    mockGetCachedSession.mockResolvedValue(null);
+    expect(await getAuthContext()).toBeNull();
+  });
+
+  it("returns null when session exists but no membership and not super admin", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockGetCachedMembership.mockResolvedValue(null);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    expect(await getAuthContext()).toBeNull();
+  });
+
+  it("returns context when session and membership are present", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockGetCachedMembership.mockResolvedValue(MEMBERSHIP as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    const ctx = await getAuthContext();
+    expect(ctx).toMatchObject({
+      userId: "user-1",
+      organizationId: "org-1",
+      role: "member",
+      isSuperAdmin: false,
+      isAdmin: false,
+    });
+  });
+});
+
+describe("getAuthContextDetailed", () => {
+  it("returns unauthenticated when no session", async () => {
+    mockGetCachedSession.mockResolvedValue(null);
+    expect(await getAuthContextDetailed()).toEqual({ status: "unauthenticated" });
+  });
+
+  it("returns no-organization when session exists but no membership and not super admin", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockGetCachedMembership.mockResolvedValue(null);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    expect(await getAuthContextDetailed()).toEqual({ status: "no-organization" });
+  });
+
+  it("returns ok with context when membership is present", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockGetCachedMembership.mockResolvedValue(MEMBERSHIP as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    const result = await getAuthContextDetailed();
+    expect(result).toEqual({
+      status: "ok",
+      context: {
+        userId: "user-1",
+        organizationId: "org-1",
+        role: "member",
+        isSuperAdmin: false,
+        isAdmin: false,
+      },
+    });
+  });
+
+  it("super admin with no membership returns no-organization", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockGetCachedMembership.mockResolvedValue(null);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: true } as any);
+    const result = await getAuthContextDetailed();
+    expect(result).toEqual({ status: "no-organization" });
+  });
+});

+ 58 - 0
src/__tests__/lib/permissions.test.ts

@@ -0,0 +1,58 @@
+import { describe, it, expect } from "vitest";
+import {
+  hasPermission,
+  hasAllPermissions,
+  PermissionAction,
+  PermissionSubject,
+} from "@/lib/permissions";
+
+describe("hasPermission", () => {
+  const read_quotes = { action: PermissionAction.READ, subject: PermissionSubject.QUOTES };
+  const create_quotes = { action: PermissionAction.CREATE, subject: PermissionSubject.QUOTES };
+  const read_vehicles = { action: PermissionAction.READ, subject: PermissionSubject.VEHICLES };
+
+  it("returns true when permission matches action and subject", () => {
+    expect(hasPermission([read_quotes], read_quotes)).toBe(true);
+  });
+
+  it("returns false when action does not match", () => {
+    expect(hasPermission([read_quotes], create_quotes)).toBe(false);
+  });
+
+  it("returns false when subject does not match", () => {
+    expect(hasPermission([read_quotes], read_vehicles)).toBe(false);
+  });
+
+  it("returns false for empty permissions array", () => {
+    expect(hasPermission([], read_quotes)).toBe(false);
+  });
+
+  it("returns true when the matching permission is among multiple", () => {
+    expect(hasPermission([create_quotes, read_vehicles, read_quotes], read_quotes)).toBe(true);
+  });
+});
+
+describe("hasAllPermissions", () => {
+  const read_quotes = { action: PermissionAction.READ, subject: PermissionSubject.QUOTES };
+  const create_quotes = { action: PermissionAction.CREATE, subject: PermissionSubject.QUOTES };
+  const read_vehicles = { action: PermissionAction.READ, subject: PermissionSubject.VEHICLES };
+
+  it("returns true when all required permissions are present", () => {
+    expect(
+      hasAllPermissions([read_quotes, create_quotes, read_vehicles], [read_quotes, create_quotes]),
+    ).toBe(true);
+  });
+
+  it("returns false when one required permission is missing", () => {
+    expect(hasAllPermissions([read_quotes], [read_quotes, create_quotes])).toBe(false);
+  });
+
+  it("returns true when required array is empty", () => {
+    expect(hasAllPermissions([], [])).toBe(true);
+    expect(hasAllPermissions([read_quotes], [])).toBe(true);
+  });
+
+  it("returns false when user has no permissions", () => {
+    expect(hasAllPermissions([], [read_quotes])).toBe(false);
+  });
+});

+ 172 - 0
src/__tests__/lib/with-auth.test.ts

@@ -0,0 +1,172 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { ZodError } from "zod";
+import { PermissionAction, PermissionSubject } from "@/lib/permissions";
+
+// Hoisted mocks
+vi.mock("@/lib/cached-session", () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}));
+
+vi.mock("@/lib/db", () => ({
+  db: {
+    user: {
+      findUnique: vi.fn(),
+    },
+  },
+}));
+
+import { withAuth } from "@/lib/with-auth";
+import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
+import { db } from "@/lib/db";
+
+const mockGetCachedSession = vi.mocked(getCachedSession);
+const mockGetCachedMembership = vi.mocked(getCachedMembership);
+const mockFindUnique = vi.mocked(db.user.findUnique);
+
+const SESSION = { user: { id: "user-1", email: "user@example.com" } };
+const MEMBERSHIP = {
+  organizationId: "org-1",
+  role: "member",
+  roleId: null,
+  customRole: null,
+};
+
+beforeEach(() => {
+  vi.resetAllMocks();
+});
+
+describe("withAuth", () => {
+  it("returns Unauthorized when there is no session", async () => {
+    mockGetCachedSession.mockResolvedValue(null);
+    const result = await withAuth(async () => "ok");
+    expect(result).toEqual({ success: false, error: "Unauthorized" });
+  });
+
+  it("returns No organization found when user has no membership and is not super admin", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    mockGetCachedMembership.mockResolvedValue(null);
+    const result = await withAuth(async () => "ok");
+    expect(result).toEqual({ success: false, error: "No organization found" });
+  });
+
+  it("super admin with no membership returns No organization found", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: true } as any);
+    mockGetCachedMembership.mockResolvedValue(null);
+    const result = await withAuth(async (ctx) => ctx);
+    expect(result).toEqual({ success: false, error: "No organization found" });
+  });
+
+  it("regular member with no required permissions — action runs", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    mockGetCachedMembership.mockResolvedValue(MEMBERSHIP as any);
+    const result = await withAuth(async (ctx) => ctx);
+    expect(result.success).toBe(true);
+    expect((result.data as any).organizationId).toBe("org-1");
+  });
+
+  it("owner bypasses permission check", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    mockGetCachedMembership.mockResolvedValue({ ...MEMBERSHIP, role: "owner" } as any);
+    const result = await withAuth(async (ctx) => ctx, {
+      requiredPermissions: [{ action: PermissionAction.MANAGE, subject: PermissionSubject.SETTINGS }],
+    });
+    expect(result.success).toBe(true);
+  });
+
+  it("admin bypasses permission check", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    mockGetCachedMembership.mockResolvedValue({ ...MEMBERSHIP, role: "admin" } as any);
+    const result = await withAuth(async (ctx) => ctx, {
+      requiredPermissions: [{ action: PermissionAction.MANAGE, subject: PermissionSubject.SETTINGS }],
+    });
+    expect(result.success).toBe(true);
+  });
+
+  it("custom role user with isAdmin=true bypasses permission check", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    mockGetCachedMembership.mockResolvedValue({
+      ...MEMBERSHIP,
+      roleId: "role-1",
+      customRole: { isAdmin: true, permissions: [] },
+    } as any);
+    const result = await withAuth(async (ctx) => ctx, {
+      requiredPermissions: [{ action: PermissionAction.MANAGE, subject: PermissionSubject.SETTINGS }],
+    });
+    expect(result.success).toBe(true);
+  });
+
+  it("custom role user with correct permissions — passes", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    mockGetCachedMembership.mockResolvedValue({
+      ...MEMBERSHIP,
+      roleId: "role-1",
+      customRole: {
+        isAdmin: false,
+        permissions: [{ action: PermissionAction.MANAGE, subject: PermissionSubject.SETTINGS }],
+      },
+    } as any);
+    const result = await withAuth(async (ctx) => ctx, {
+      requiredPermissions: [{ action: PermissionAction.MANAGE, subject: PermissionSubject.SETTINGS }],
+    });
+    expect(result.success).toBe(true);
+  });
+
+  it("custom role user missing required permissions — Insufficient permissions", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    mockGetCachedMembership.mockResolvedValue({
+      ...MEMBERSHIP,
+      roleId: "role-1",
+      customRole: {
+        isAdmin: false,
+        permissions: [{ action: PermissionAction.READ, subject: PermissionSubject.QUOTES }],
+      },
+    } as any);
+    const result = await withAuth(async () => "ok", {
+      requiredPermissions: [{ action: PermissionAction.MANAGE, subject: PermissionSubject.SETTINGS }],
+    });
+    expect(result).toEqual({ success: false, error: "Insufficient permissions" });
+  });
+
+  it("super admin with membership bypasses all permission checks", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: true } as any);
+    mockGetCachedMembership.mockResolvedValue(MEMBERSHIP as any);
+    const result = await withAuth(async (ctx) => ctx, {
+      requiredPermissions: [{ action: PermissionAction.MANAGE, subject: PermissionSubject.SETTINGS }],
+    });
+    expect(result.success).toBe(true);
+    expect((result.data as any).isSuperAdmin).toBe(true);
+    expect((result.data as any).organizationId).toBe("org-1");
+  });
+
+  it("action throwing ZodError returns formatted field errors", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    mockGetCachedMembership.mockResolvedValue(MEMBERSHIP as any);
+
+    const zodErr = new ZodError([
+      { code: "too_small", path: ["email"], message: "Required", minimum: 1, type: "string", inclusive: true },
+    ]);
+    const result = await withAuth(async () => { throw zodErr; });
+    expect(result.success).toBe(false);
+    expect(result.error).toContain("email");
+    expect(result.error).toContain("Required");
+  });
+
+  it("action throwing a generic Error returns the error message", async () => {
+    mockGetCachedSession.mockResolvedValue(SESSION as any);
+    mockFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    mockGetCachedMembership.mockResolvedValue(MEMBERSHIP as any);
+    const result = await withAuth(async () => { throw new Error("something went wrong"); });
+    expect(result).toEqual({ success: false, error: "something went wrong" });
+  });
+});

+ 451 - 0
src/__tests__/multitenancy/customer-inventory-isolation.test.ts

@@ -0,0 +1,451 @@
+/**
+ * Multi-tenancy isolation tests: Customers & Inventory Parts
+ *
+ * Verifies that a user from Org A cannot read, modify, or delete customers or
+ * inventory parts belonging to Org B.
+ *
+ */
+
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("@/lib/cached-session", () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+
+vi.mock("@/lib/resolve-upload-path", () => ({
+  resolveUploadPath: vi.fn((url: string) => `/uploads/${url}`),
+}));
+
+vi.mock("@/lib/features", () => ({
+  getFeatures: vi.fn().mockResolvedValue({ maxCustomers: 1000 }),
+  FeatureGatedError: class FeatureGatedError extends Error {
+    constructor(feature: string, msg: string) { super(msg); }
+  },
+}));
+
+vi.mock("@/lib/db", () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    customer: {
+      findFirst: vi.fn(),
+      findMany: vi.fn(),
+      count: vi.fn(),
+      updateMany: vi.fn(),
+      deleteMany: vi.fn(),
+    },
+    inventoryPart: {
+      findFirst: vi.fn(),
+      updateMany: vi.fn(),
+      deleteMany: vi.fn(),
+      update: vi.fn(),
+    },
+  },
+}));
+
+import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
+import { db } from "@/lib/db";
+import {
+  getCustomer,
+  getCustomers,
+  updateCustomer,
+  deleteCustomer,
+} from "@/features/customers/Actions/customerActions";
+import {
+  getInventoryPart,
+  updateInventoryPart,
+  deleteInventoryPart,
+  adjustInventoryStock,
+} from "@/features/inventory/Actions/inventoryActions";
+
+const mockSession = vi.mocked(getCachedSession);
+const mockMembership = vi.mocked(getCachedMembership);
+const mockUserFindUnique = vi.mocked(db.user.findUnique);
+
+const ORG_A = "org-a";
+const ORG_B = "org-b";
+
+function setupOrgAOwner() {
+  mockSession.mockResolvedValue({ user: { id: "user-a", email: "a@example.com" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "owner",
+    roleId: null,
+    customRole: null,
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+const ORG_A_CUSTOMER = {
+  id: "cust-a",
+  organizationId: ORG_A,
+  name: "Alice Smith",
+  email: "alice@example.com",
+  phone: null,
+  address: null,
+  company: null,
+  notes: null,
+  vehicles: [],
+};
+
+const ORG_A_PART = {
+  id: "part-a",
+  organizationId: ORG_A,
+  name: "Oil Filter",
+  quantity: 10,
+  unitCost: 5,
+  sellPrice: 10,
+  isArchived: false,
+  imageUrl: null,
+};
+
+beforeEach(() => {
+  vi.resetAllMocks();
+});
+
+// ---------------------------------------------------------------------------
+// Customer read isolation
+// ---------------------------------------------------------------------------
+
+describe("getCustomer — cross-org isolation", () => {
+  it("returns 'Customer not found' error when requesting another org's customer", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.customer.findFirst).mockResolvedValue(null);
+
+    const result = await getCustomer(`${ORG_B}-customer-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Customer not found");
+  });
+
+  it("returns customer data when requesting the caller's own customer", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.customer.findFirst).mockResolvedValue(ORG_A_CUSTOMER as any);
+
+    const result = await getCustomer("cust-a");
+
+    expect(result.success).toBe(true);
+    expect((result.data as any).id).toBe("cust-a");
+  });
+
+  it("read query always scopes to the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.customer.findFirst).mockResolvedValue(ORG_A_CUSTOMER as any);
+
+    await getCustomer("cust-a");
+
+    expect(vi.mocked(db.customer.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Customer list isolation
+// ---------------------------------------------------------------------------
+
+describe("getCustomers — org scoping", () => {
+  it("list query always scopes to the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.customer.findMany).mockResolvedValue([ORG_A_CUSTOMER] as any);
+
+    await getCustomers();
+
+    expect(vi.mocked(db.customer.findMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("returns only the caller's own customers", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.customer.findMany).mockResolvedValue([ORG_A_CUSTOMER] as any);
+
+    const result = await getCustomers();
+
+    expect(result.success).toBe(true);
+    expect(result.data).toHaveLength(1);
+    expect((result.data as any)[0].organizationId).toBe(ORG_A);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Customer update isolation
+// ---------------------------------------------------------------------------
+
+describe("updateCustomer — cross-org isolation", () => {
+  it("🐛 BUG-3: silently returns success when targeting another org's customer — nothing is actually changed", async () => {
+    setupOrgAOwner();
+    // updateMany with org filter matches 0 rows for a cross-org customer id
+    vi.mocked(db.customer.updateMany).mockResolvedValue({ count: 0 } as any);
+
+    const result = await updateCustomer({ id: `${ORG_B}-customer-id`, name: "Hacked" });
+
+    // BUG: should be { success: false, error: "Customer not found" }
+    // Fix: check `result.count === 0` and throw (same pattern as inventoryActions).
+    expect(result.success).toBe(false); // FAILS until bug is fixed
+  });
+
+  it("update query always includes organizationId to prevent cross-org writes", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.customer.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    await updateCustomer({ id: "cust-a", name: "Alice Updated" });
+
+    expect(vi.mocked(db.customer.updateMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("successfully updates the caller's own customer", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.customer.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await updateCustomer({ id: "cust-a", name: "Alice Updated" });
+
+    expect(result.success).toBe(true);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Customer delete isolation
+// ---------------------------------------------------------------------------
+
+describe("deleteCustomer — cross-org isolation", () => {
+  it("🐛 BUG-4: silently returns success when deleting another org's customer — nothing is actually deleted", async () => {
+    setupOrgAOwner();
+    // deleteMany with org filter matches 0 rows for a cross-org customer id
+    vi.mocked(db.customer.deleteMany).mockResolvedValue({ count: 0 } as any);
+
+    const result = await deleteCustomer(`${ORG_B}-customer-id`);
+
+    // BUG: should be { success: false, error: "Customer not found" }
+    // Fix: check `result.count === 0` and throw (same pattern as inventoryActions).
+    expect(result.success).toBe(false); // FAILS until bug is fixed
+  });
+
+  it("delete query always includes organizationId to prevent cross-org deletes", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.customer.deleteMany).mockResolvedValue({ count: 1 } as any);
+
+    await deleteCustomer("cust-a");
+
+    expect(vi.mocked(db.customer.deleteMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("successfully deletes the caller's own customer", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.customer.deleteMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await deleteCustomer("cust-a");
+
+    expect(result.success).toBe(true);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Inventory read isolation
+// ---------------------------------------------------------------------------
+
+describe("getInventoryPart — cross-org isolation", () => {
+  it("returns 'Part not found' error when requesting another org's inventory part", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue(null);
+
+    const result = await getInventoryPart(`${ORG_B}-part-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Part not found");
+  });
+
+  it("returns part data when requesting the caller's own part", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue(ORG_A_PART as any);
+
+    const result = await getInventoryPart("part-a");
+
+    expect(result.success).toBe(true);
+    expect((result.data as any).id).toBe("part-a");
+  });
+
+  it("read query always scopes to the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue(ORG_A_PART as any);
+
+    await getInventoryPart("part-a");
+
+    expect(vi.mocked(db.inventoryPart.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Inventory update isolation
+// ---------------------------------------------------------------------------
+
+describe("updateInventoryPart — cross-org isolation", () => {
+  it("returns 'Part not found' error when targeting another org's part (count check enforced)", async () => {
+    setupOrgAOwner();
+    // updateMany with org filter matches 0 rows — action checks count and throws
+    vi.mocked(db.inventoryPart.updateMany).mockResolvedValue({ count: 0 } as any);
+
+    const result = await updateInventoryPart({ id: `${ORG_B}-part-id`, name: "Hacked" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Part not found");
+  });
+
+  it("update query always includes organizationId to prevent cross-org writes", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    await updateInventoryPart({ id: "part-a", name: "Updated Filter" });
+
+    expect(vi.mocked(db.inventoryPart.updateMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("successfully updates the caller's own inventory part", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await updateInventoryPart({ id: "part-a", name: "Updated Filter" });
+
+    expect(result.success).toBe(true);
+    expect((result.data as any).updated).toBe(true);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Inventory delete isolation
+// ---------------------------------------------------------------------------
+
+describe("deleteInventoryPart — cross-org isolation", () => {
+  it("returns 'Part not found' error when targeting another org's part (count check enforced)", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue(null); // no imageUrl to clean
+    vi.mocked(db.inventoryPart.deleteMany).mockResolvedValue({ count: 0 } as any);
+
+    const result = await deleteInventoryPart(`${ORG_B}-part-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Part not found");
+  });
+
+  it("delete query always includes organizationId to prevent cross-org deletes", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue({ imageUrl: null } as any);
+    vi.mocked(db.inventoryPart.deleteMany).mockResolvedValue({ count: 1 } as any);
+
+    await deleteInventoryPart("part-a");
+
+    expect(vi.mocked(db.inventoryPart.deleteMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("successfully deletes the caller's own inventory part", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue({ imageUrl: null } as any);
+    vi.mocked(db.inventoryPart.deleteMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await deleteInventoryPart("part-a");
+
+    expect(result.success).toBe(true);
+    expect((result.data as any).deleted).toBe(true);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Inventory stock adjustment isolation
+// ---------------------------------------------------------------------------
+
+describe("adjustInventoryStock — cross-org isolation", () => {
+  it("returns 'Part not found' error when targeting another org's part", async () => {
+    setupOrgAOwner();
+    // findFirst with organizationId filter returns null for cross-org part
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue(null);
+
+    const result = await adjustInventoryStock({ id: `${ORG_B}-part-id`, adjustment: 10 });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Part not found");
+  });
+
+  it("ownership findFirst always includes organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue(null);
+
+    await adjustInventoryStock({ id: "part-x", adjustment: 5 });
+
+    expect(vi.mocked(db.inventoryPart.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("inventory update is never called when ownership check fails", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue(null);
+
+    await adjustInventoryStock({ id: `${ORG_B}-part-id`, adjustment: 99 });
+
+    expect(vi.mocked(db.inventoryPart.updateMany)).not.toHaveBeenCalled();
+  });
+
+  it("successfully adjusts stock for the caller's own part", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue(ORG_A_PART as any);
+    vi.mocked(db.inventoryPart.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await adjustInventoryStock({ id: "part-a", adjustment: 5 });
+
+    expect(result.success).toBe(true);
+    expect((result.data as any).quantity).toBe(15);
+  });
+
+  it("stock adjustment query includes organizationId for defense-in-depth", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue(ORG_A_PART as any);
+    vi.mocked(db.inventoryPart.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    await adjustInventoryStock({ id: "part-a", adjustment: 5 });
+
+    expect(vi.mocked(db.inventoryPart.updateMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("returns 'Insufficient stock' error when adjustment would make quantity negative", async () => {
+    setupOrgAOwner();
+    // quantity is 10, adjustment is -15 → would go to -5
+    vi.mocked(db.inventoryPart.findFirst).mockResolvedValue({ ...ORG_A_PART, quantity: 10 } as any);
+
+    const result = await adjustInventoryStock({ id: "part-a", adjustment: -15 });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Insufficient stock");
+  });
+});

+ 533 - 0
src/__tests__/multitenancy/quote-inspection-isolation.test.ts

@@ -0,0 +1,533 @@
+/**
+ * Multi-tenancy isolation tests: Quotes & Inspections
+ *
+ * Verifies that a user from Org A cannot read, modify, or delete quotes or
+ * inspections belonging to Org B.
+ *
+ */
+
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("@/lib/cached-session", () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+
+vi.mock("@/lib/lib/invoice-utils", () => ({
+  resolveInvoicePrefix: vi.fn((p: string) => p),
+}));
+
+vi.mock("@/lib/db", () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    appSetting: { findMany: vi.fn() },
+    quote: {
+      findFirst: vi.fn(),
+      findMany: vi.fn(),
+      count: vi.fn(),
+      groupBy: vi.fn(),
+      create: vi.fn(),
+      update: vi.fn(),
+      updateMany: vi.fn(),
+      delete: vi.fn(),
+      deleteMany: vi.fn(),
+    },
+    inspection: {
+      findFirst: vi.fn(),
+      update: vi.fn(),
+      updateMany: vi.fn(),
+      delete: vi.fn(),
+      deleteMany: vi.fn(),
+    },
+    inspectionItem: {
+      findFirst: vi.fn(),
+      update: vi.fn(),
+    },
+    $transaction: vi.fn(),
+  },
+}));
+
+import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
+import { db } from "@/lib/db";
+import {
+  getQuote,
+  getQuotesPaginated,
+  updateQuote,
+  updateQuoteStatus,
+  deleteQuote,
+} from "@/features/quotes/Actions/quoteActions";
+import {
+  getInspection,
+  getInspectionsPaginated,
+  updateInspectionItem,
+  completeInspection,
+  deleteInspection,
+} from "@/features/inspections/Actions/inspectionActions";
+
+const mockSession = vi.mocked(getCachedSession);
+const mockMembership = vi.mocked(getCachedMembership);
+const mockUserFindUnique = vi.mocked(db.user.findUnique);
+
+const ORG_A = "org-a";
+const ORG_B = "org-b";
+
+function setupOrgAOwner() {
+  mockSession.mockResolvedValue({ user: { id: "user-a", email: "a@example.com" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "owner",
+    roleId: null,
+    customRole: null,
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+const ORG_A_QUOTE = {
+  id: "quote-a",
+  organizationId: ORG_A,
+  title: "Brake Service",
+  quoteNumber: "QT-1001",
+  status: "sent",
+  partItems: [],
+  laborItems: [],
+  customer: null,
+  vehicle: null,
+  inspection: null,
+};
+
+const ORG_A_INSPECTION = {
+  id: "insp-a",
+  organizationId: ORG_A,
+  status: "in_progress",
+  vehicleId: "veh-a",
+  vehicle: null,
+  template: null,
+  items: [],
+  quotes: [],
+  quoteRequests: [],
+};
+
+beforeEach(() => {
+  vi.resetAllMocks();
+});
+
+// ---------------------------------------------------------------------------
+// Quote read isolation
+// ---------------------------------------------------------------------------
+
+describe("getQuote — cross-org isolation", () => {
+  it("returns 'Quote not found' error when requesting another org's quote ID", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(null);
+
+    const result = await getQuote(`${ORG_B}-quote-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Quote not found");
+  });
+
+  it("returns quote data when requesting the caller's own quote", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(ORG_A_QUOTE as any);
+
+    const result = await getQuote("quote-a");
+
+    expect(result.success).toBe(true);
+    expect((result.data as any).id).toBe("quote-a");
+  });
+
+  it("read query always scopes to the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(ORG_A_QUOTE as any);
+
+    await getQuote("quote-a");
+
+    expect(vi.mocked(db.quote.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Quote list isolation
+// ---------------------------------------------------------------------------
+
+describe("getQuotesPaginated — org scoping", () => {
+  it("list query always scopes to the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findMany).mockResolvedValue([]);
+    vi.mocked(db.quote.count).mockResolvedValue(0);
+    vi.mocked(db.quote.groupBy).mockResolvedValue([]);
+
+    await getQuotesPaginated({});
+
+    expect(vi.mocked(db.quote.findMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Quote update isolation
+// ---------------------------------------------------------------------------
+
+describe("updateQuote — cross-org isolation", () => {
+  it("returns 'Quote not found' error when targeting another org's quote", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(null);
+
+    const result = await updateQuote({ id: `${ORG_B}-quote-id`, title: "Injected" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Quote not found");
+  });
+
+  it("ownership is verified before the update transaction runs", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(null);
+
+    await updateQuote({ id: `${ORG_B}-quote-id`, title: "Injected" });
+
+    // $transaction must never be called if ownership check fails
+    expect(vi.mocked(db.$transaction)).not.toHaveBeenCalled();
+  });
+
+  it("successfully updates the caller's own quote", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(ORG_A_QUOTE as any);
+    const updatedQuote = { ...ORG_A_QUOTE, title: "Updated Title" };
+    vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
+      fn({
+        quote: { update: vi.fn().mockResolvedValue(updatedQuote) },
+        quotePart: { deleteMany: vi.fn().mockResolvedValue({ count: 0 }), createMany: vi.fn() },
+        quoteLabor: { deleteMany: vi.fn().mockResolvedValue({ count: 0 }), createMany: vi.fn() },
+      })
+    );
+
+    const result = await updateQuote({ id: "quote-a", title: "Updated Title" });
+
+    expect(result.success).toBe(true);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Quote status update isolation
+// ---------------------------------------------------------------------------
+
+describe("updateQuoteStatus — cross-org isolation", () => {
+  it("returns 'Quote not found' error when targeting another org's quote status", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(null);
+
+    const result = await updateQuoteStatus(`${ORG_B}-quote-id`, "accepted");
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Quote not found");
+  });
+
+  it("successfully updates status of the caller's own quote", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(ORG_A_QUOTE as any);
+    vi.mocked(db.quote.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await updateQuoteStatus("quote-a", "accepted");
+
+    expect(result.success).toBe(true);
+  });
+
+  it("status update query includes organizationId for defense-in-depth", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(ORG_A_QUOTE as any);
+    vi.mocked(db.quote.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    await updateQuoteStatus("quote-a", "accepted");
+
+    expect(vi.mocked(db.quote.updateMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Quote delete isolation
+// ---------------------------------------------------------------------------
+
+describe("deleteQuote — cross-org isolation", () => {
+  it("returns 'Quote not found' error when targeting another org's quote", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(null);
+
+    const result = await deleteQuote(`${ORG_B}-quote-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Quote not found");
+  });
+
+  it("delete is never called when ownership check fails", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(null);
+
+    await deleteQuote(`${ORG_B}-quote-id`);
+
+    expect(vi.mocked(db.quote.deleteMany)).not.toHaveBeenCalled();
+  });
+
+  it("successfully deletes the caller's own quote", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(ORG_A_QUOTE as any);
+    vi.mocked(db.quote.deleteMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await deleteQuote("quote-a");
+
+    expect(result.success).toBe(true);
+  });
+
+  it("delete query includes organizationId for defense-in-depth", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.quote.findFirst).mockResolvedValue(ORG_A_QUOTE as any);
+    vi.mocked(db.quote.deleteMany).mockResolvedValue({ count: 1 } as any);
+
+    await deleteQuote("quote-a");
+
+    expect(vi.mocked(db.quote.deleteMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Inspection read isolation
+// ---------------------------------------------------------------------------
+
+describe("getInspection — cross-org isolation", () => {
+  it("returns 'Inspection not found' error when requesting another org's inspection", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(null);
+
+    const result = await getInspection(`${ORG_B}-insp-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Inspection not found");
+  });
+
+  it("returns inspection data when requesting the caller's own inspection", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(ORG_A_INSPECTION as any);
+
+    const result = await getInspection("insp-a");
+
+    expect(result.success).toBe(true);
+    expect((result.data as any).id).toBe("insp-a");
+  });
+
+  it("read query always scopes to the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(ORG_A_INSPECTION as any);
+
+    await getInspection("insp-a");
+
+    expect(vi.mocked(db.inspection.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Inspection list isolation
+// ---------------------------------------------------------------------------
+
+describe("getInspectionsPaginated — org scoping", () => {
+  it("list query always scopes to the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(null);
+
+    // Mock the underlying db calls getInspectionsPaginated uses
+    const mockDb = vi.mocked(db) as any;
+    if (!mockDb.inspection.findMany) {
+      mockDb.inspection.findMany = vi.fn().mockResolvedValue([]);
+    } else {
+      vi.mocked(mockDb.inspection.findMany).mockResolvedValue([]);
+    }
+    if (!mockDb.inspection.count) {
+      mockDb.inspection.count = vi.fn().mockResolvedValue(0);
+    } else {
+      vi.mocked(mockDb.inspection.count).mockResolvedValue(0);
+    }
+    if (!mockDb.inspection.groupBy) {
+      mockDb.inspection.groupBy = vi.fn().mockResolvedValue([]);
+    } else {
+      vi.mocked(mockDb.inspection.groupBy).mockResolvedValue([]);
+    }
+
+    await getInspectionsPaginated({});
+
+    // The findMany inside getInspectionsPaginated should use organizationId
+    expect(mockDb.inspection.findMany).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Inspection item update isolation
+// ---------------------------------------------------------------------------
+
+describe("updateInspectionItem — cross-org isolation", () => {
+  it("returns 'Inspection item not found' when updating an item from another org", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspectionItem.findFirst).mockResolvedValue(null);
+
+    const result = await updateInspectionItem(`${ORG_B}-item-id`, { condition: "pass" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Inspection item not found");
+  });
+
+  it("item lookup always scopes through the inspection's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspectionItem.findFirst).mockResolvedValue(null);
+
+    await updateInspectionItem("item-x", { condition: "pass" });
+
+    expect(vi.mocked(db.inspectionItem.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({
+          inspection: expect.objectContaining({ organizationId: ORG_A }),
+        }),
+      })
+    );
+  });
+
+  it("update is never called when ownership check fails", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspectionItem.findFirst).mockResolvedValue(null);
+
+    await updateInspectionItem(`${ORG_B}-item-id`, { condition: "fail" });
+
+    expect(vi.mocked(db.inspectionItem.update)).not.toHaveBeenCalled();
+  });
+
+  it("successfully updates an inspection item belonging to the caller's org", async () => {
+    setupOrgAOwner();
+    const item = { id: "item-a", inspectionId: "insp-a", condition: "not_inspected" };
+    vi.mocked(db.inspectionItem.findFirst).mockResolvedValue(item as any);
+    vi.mocked(db.inspectionItem.update).mockResolvedValue({ ...item, condition: "pass" } as any);
+
+    const result = await updateInspectionItem("item-a", { condition: "pass" });
+
+    expect(result.success).toBe(true);
+    expect((result.data as any).condition).toBe("pass");
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Complete inspection isolation
+// ---------------------------------------------------------------------------
+
+describe("completeInspection — cross-org isolation", () => {
+  it("returns 'Inspection not found' when completing another org's inspection", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(null);
+
+    const result = await completeInspection(`${ORG_B}-insp-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Inspection not found");
+  });
+
+  it("inspection update is never called when ownership check fails", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(null);
+
+    await completeInspection(`${ORG_B}-insp-id`);
+
+    expect(vi.mocked(db.inspection.updateMany)).not.toHaveBeenCalled();
+  });
+
+  it("successfully completes the caller's own inspection", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(ORG_A_INSPECTION as any);
+    vi.mocked(db.inspection.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await completeInspection("insp-a");
+
+    expect(result.success).toBe(true);
+  });
+
+  it("complete query includes organizationId for defense-in-depth", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(ORG_A_INSPECTION as any);
+    vi.mocked(db.inspection.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    await completeInspection("insp-a");
+
+    expect(vi.mocked(db.inspection.updateMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Delete inspection isolation
+// ---------------------------------------------------------------------------
+
+describe("deleteInspection — cross-org isolation", () => {
+  it("returns 'Inspection not found' when deleting another org's inspection", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(null);
+
+    const result = await deleteInspection(`${ORG_B}-insp-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Inspection not found");
+  });
+
+  it("inspection delete is never called when ownership check fails", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(null);
+
+    await deleteInspection(`${ORG_B}-insp-id`);
+
+    expect(vi.mocked(db.inspection.deleteMany)).not.toHaveBeenCalled();
+  });
+
+  it("successfully deletes the caller's own inspection", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(ORG_A_INSPECTION as any);
+    vi.mocked(db.inspection.deleteMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await deleteInspection("insp-a");
+
+    expect(result.success).toBe(true);
+  });
+
+  it("delete query includes organizationId for defense-in-depth", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.inspection.findFirst).mockResolvedValue(ORG_A_INSPECTION as any);
+    vi.mocked(db.inspection.deleteMany).mockResolvedValue({ count: 1 } as any);
+
+    await deleteInspection("insp-a");
+
+    expect(vi.mocked(db.inspection.deleteMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});

+ 797 - 0
src/__tests__/multitenancy/team-invite-isolation.test.ts

@@ -0,0 +1,797 @@
+/**
+ * Team invitation isolation & role-correctness tests
+ *
+ * Verifies that:
+ *  1. acceptInvitation creates memberships in the correct org with the correct role
+ *  2. sendInvitation cannot be used to embed a cross-org custom roleId
+ *  3. cancelInvitation is properly scoped to the caller's org
+ *  4. getPendingInvitations only returns the caller's org's invitations
+ *  5. assignRole cannot target members or roles from another org
+ *  6. Custom isAdmin roles are respected by cancelInvitation and assignRole
+ */
+
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("@/lib/cached-session", () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+
+vi.mock("next/headers", () => ({
+  headers: vi.fn().mockResolvedValue(new Headers()),
+  cookies: vi.fn().mockResolvedValue({ set: vi.fn(), get: vi.fn() }),
+}));
+
+vi.mock("@/lib/email", () => ({
+  sendOrgMail: vi.fn(),
+  getOrgFromAddress: vi.fn(),
+}));
+
+vi.mock("@/lib/db", () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    teamInvitation: {
+      findUnique: vi.fn(),
+      findFirst: vi.fn(),
+      findMany: vi.fn(),
+      create: vi.fn(),
+      update: vi.fn(),
+      delete: vi.fn(),
+      deleteMany: vi.fn(),
+    },
+    organizationMember: {
+      findFirst: vi.fn(),
+      create: vi.fn(),
+      update: vi.fn(),
+    },
+    role: {
+      findUnique: vi.fn(),
+      findFirst: vi.fn(),
+    },
+    $transaction: vi.fn(),
+  },
+}));
+
+import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
+import { db } from "@/lib/db";
+import { cookies } from "next/headers";
+import { sendOrgMail, getOrgFromAddress } from "@/lib/email";
+import { acceptInvitation } from "@/features/team/Actions/acceptInvitation";
+import { sendInvitation } from "@/features/team/Actions/sendInvitation";
+import { cancelInvitation } from "@/features/team/Actions/cancelInvitation";
+import { getPendingInvitations } from "@/features/team/Actions/getPendingInvitations";
+import { assignRole } from "@/features/team/Actions/assignRole";
+
+const mockSession = vi.mocked(getCachedSession);
+const mockMembership = vi.mocked(getCachedMembership);
+const mockUserFindUnique = vi.mocked(db.user.findUnique);
+const mockSendOrgMail = vi.mocked(sendOrgMail);
+const mockGetOrgFromAddress = vi.mocked(getOrgFromAddress);
+
+const ORG_A = "org-a";
+const ORG_B = "org-b";
+
+// ---------- Auth setup helpers ----------
+
+function setupOrgAOwner() {
+  mockSession.mockResolvedValue({ user: { id: "user-a", email: "owner@orgA.com" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "owner",
+    roleId: null,
+    customRole: null,
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+function setupOrgAAdmin() {
+  mockSession.mockResolvedValue({ user: { id: "user-a", email: "admin@orgA.com" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "admin",
+    roleId: null,
+    customRole: null,
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+function setupOrgAMember() {
+  mockSession.mockResolvedValue({ user: { id: "user-a", email: "member@orgA.com" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "member",
+    roleId: null,
+    customRole: null,
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+/**
+ * User whose built-in role is "member" but whose custom role has isAdmin:true.
+ * withAuth grants them access (roleIsAdmin=true), but actions that check the
+ * built-in role string will incorrectly block them (BUG-6, BUG-7).
+ */
+function setupOrgACustomAdmin() {
+  mockSession.mockResolvedValue({ user: { id: "user-a", email: "cadmin@orgA.com" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "member",
+    roleId: "custom-admin-role-id",
+    customRole: { isAdmin: true, permissions: [] },
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+// ---------- Shared fixtures ----------
+
+const VALID_INVITATION = {
+  id: "inv-1",
+  token: "tok-abc",
+  email: "invited@example.com",
+  organizationId: ORG_A,
+  status: "pending",
+  role: "member",
+  roleId: null,
+  expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
+};
+
+beforeEach(() => {
+  vi.resetAllMocks();
+  vi.mocked(cookies).mockResolvedValue({ set: vi.fn(), get: vi.fn() } as any);
+});
+
+// ============================================================================
+// acceptInvitation — role and org assignment correctness
+// ============================================================================
+
+describe("acceptInvitation — role and org assignment correctness", () => {
+  beforeEach(() => {
+    // acceptInvitation uses getCachedSession directly (not withAuth)
+    mockSession.mockResolvedValue({
+      user: { id: "invited-user", email: "invited@example.com" },
+    } as any);
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue(null);
+    vi.mocked(db.$transaction).mockResolvedValue([{}, {}] as any);
+  });
+
+  it("creates membership in the invitation's org, not any other org", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue({
+      ...VALID_INVITATION,
+      organizationId: ORG_A,
+    } as any);
+
+    await acceptInvitation({ token: "tok-abc" });
+
+    expect(vi.mocked(db.organizationMember.create)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("assigns the role specified in the invitation — 'admin'", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue({
+      ...VALID_INVITATION,
+      role: "admin",
+    } as any);
+
+    await acceptInvitation({ token: "tok-abc" });
+
+    expect(vi.mocked(db.organizationMember.create)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: expect.objectContaining({ role: "admin" }),
+      })
+    );
+  });
+
+  it("assigns the role specified in the invitation — 'member'", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue({
+      ...VALID_INVITATION,
+      role: "member",
+    } as any);
+
+    await acceptInvitation({ token: "tok-abc" });
+
+    expect(vi.mocked(db.organizationMember.create)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: expect.objectContaining({ role: "member" }),
+      })
+    );
+  });
+
+  it("assigns the custom roleId from the invitation when present", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue({
+      ...VALID_INVITATION,
+      roleId: "custom-technician-role",
+    } as any);
+
+    await acceptInvitation({ token: "tok-abc" });
+
+    expect(vi.mocked(db.organizationMember.create)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: expect.objectContaining({ roleId: "custom-technician-role" }),
+      })
+    );
+  });
+
+  it("assigns null roleId when the invitation has no custom role", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue({
+      ...VALID_INVITATION,
+      roleId: null,
+    } as any);
+
+    await acceptInvitation({ token: "tok-abc" });
+
+    expect(vi.mocked(db.organizationMember.create)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: expect.objectContaining({ roleId: null }),
+      })
+    );
+  });
+
+  it("sets the active-org cookie to the invitation's organizationId after accept", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue({
+      ...VALID_INVITATION,
+      organizationId: ORG_A,
+    } as any);
+    const mockSet = vi.fn();
+    vi.mocked(cookies).mockResolvedValue({ set: mockSet, get: vi.fn() } as any);
+
+    await acceptInvitation({ token: "tok-abc" });
+
+    expect(mockSet).toHaveBeenCalledWith("active-org-id", ORG_A, expect.any(Object));
+  });
+
+  it("does not create a second membership when the user is already a member", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue(VALID_INVITATION as any);
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({ id: "existing-mem" } as any);
+    vi.mocked(db.teamInvitation.update).mockResolvedValue({} as any);
+
+    const result = await acceptInvitation({ token: "tok-abc" });
+
+    expect(result.success).toBe(true);
+    expect(vi.mocked(db.organizationMember.create)).not.toHaveBeenCalled();
+    expect(vi.mocked(db.$transaction)).not.toHaveBeenCalled();
+  });
+
+  it("email mismatch prevents joining another org's team via a stolen token", async () => {
+    mockSession.mockResolvedValue({
+      user: { id: "attacker", email: "attacker@evil.com" },
+    } as any);
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue(VALID_INVITATION as any);
+
+    const result = await acceptInvitation({ token: "tok-abc" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("This invitation was sent to a different email address");
+    expect(vi.mocked(db.organizationMember.create)).not.toHaveBeenCalled();
+  });
+
+  it("cancelled invitation cannot be accepted", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue({
+      ...VALID_INVITATION,
+      status: "cancelled",
+    } as any);
+
+    const result = await acceptInvitation({ token: "tok-abc" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("This invitation is no longer valid");
+    expect(vi.mocked(db.organizationMember.create)).not.toHaveBeenCalled();
+  });
+
+  it("already-accepted invitation cannot be re-accepted", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue({
+      ...VALID_INVITATION,
+      status: "accepted",
+    } as any);
+
+    const result = await acceptInvitation({ token: "tok-abc" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("This invitation is no longer valid");
+    expect(vi.mocked(db.organizationMember.create)).not.toHaveBeenCalled();
+  });
+
+  it("expired invitation cannot be accepted", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue({
+      ...VALID_INVITATION,
+      expiresAt: new Date(Date.now() - 1000),
+    } as any);
+
+    const result = await acceptInvitation({ token: "tok-abc" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("This invitation has expired");
+    expect(vi.mocked(db.organizationMember.create)).not.toHaveBeenCalled();
+  });
+
+  it("unknown/garbage token returns 'Invitation not found'", async () => {
+    vi.mocked(db.teamInvitation.findUnique).mockResolvedValue(null);
+
+    const result = await acceptInvitation({ token: "garbage-token" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Invitation not found");
+    expect(vi.mocked(db.organizationMember.create)).not.toHaveBeenCalled();
+  });
+
+  it("unauthenticated call returns an error without touching the DB", async () => {
+    mockSession.mockResolvedValue(null);
+
+    const result = await acceptInvitation({ token: "tok-abc" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("You must be signed in to accept an invitation");
+    expect(vi.mocked(db.teamInvitation.findUnique)).not.toHaveBeenCalled();
+  });
+});
+
+// ============================================================================
+// sendInvitation — org scoping, role storage, roleId validation
+// ============================================================================
+
+describe("sendInvitation — org scoping and role validation", () => {
+  beforeEach(() => {
+    setupOrgAOwner();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-1",
+      organizationId: ORG_A,
+      role: "owner",
+      organization: { name: "Org A Auto" },
+    } as any);
+    vi.mocked(db.teamInvitation.findFirst).mockResolvedValue(null);
+    vi.mocked(db.teamInvitation.deleteMany).mockResolvedValue({ count: 0 } as any);
+    vi.mocked(db.teamInvitation.create).mockResolvedValue({
+      id: "inv-new",
+      token: "new-tok",
+      organizationId: ORG_A,
+    } as any);
+    mockSendOrgMail.mockResolvedValue(undefined as any);
+    mockGetOrgFromAddress.mockResolvedValue("noreply@org.com" as any);
+  });
+
+  it("invitation is scoped to the caller's organizationId (from auth context)", async () => {
+    await sendInvitation({ email: "new@example.com", role: "member" });
+
+    expect(vi.mocked(db.teamInvitation.create)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("stores the requested role in the invitation", async () => {
+    await sendInvitation({ email: "new@example.com", role: "admin" });
+
+    expect(vi.mocked(db.teamInvitation.create)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: expect.objectContaining({ role: "admin" }),
+      })
+    );
+  });
+
+  it("stores the invitedById as the caller's userId", async () => {
+    await sendInvitation({ email: "new@example.com", role: "member" });
+
+    expect(vi.mocked(db.teamInvitation.create)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: expect.objectContaining({ invitedById: "user-a" }),
+      })
+    );
+  });
+
+  it("rejects a duplicate invitation for the same email in the same org", async () => {
+    vi.mocked(db.teamInvitation.findFirst).mockResolvedValue({ id: "existing-inv" } as any);
+
+    const result = await sendInvitation({ email: "existing@example.com", role: "member" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("An invitation has already been sent to this email");
+    expect(vi.mocked(db.teamInvitation.create)).not.toHaveBeenCalled();
+  });
+
+  it("cleans up stale non-pending invitations before creating a fresh one", async () => {
+    await sendInvitation({ email: "returning@example.com", role: "member" });
+
+    expect(vi.mocked(db.teamInvitation.deleteMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({
+          email: "returning@example.com",
+          organizationId: ORG_A,
+          status: { not: "pending" },
+        }),
+      })
+    );
+  });
+
+  it("rolls back the invitation record when the email send fails", async () => {
+    mockSendOrgMail.mockRejectedValue(new Error("SMTP error") as any);
+    vi.mocked(db.teamInvitation.delete).mockResolvedValue({} as any);
+
+    const result = await sendInvitation({ email: "new@example.com", role: "member" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Failed to send invitation email. Please try again.");
+    expect(vi.mocked(db.teamInvitation.delete)).toHaveBeenCalledWith(
+      expect.objectContaining({ where: { id: "inv-new" } })
+    );
+  });
+
+  it("duplicate check is scoped to the caller's org — same email in different org is allowed", async () => {
+    // findFirst with { email, organizationId: ORG_A, status: "pending" } returns null
+    vi.mocked(db.teamInvitation.findFirst).mockResolvedValue(null);
+
+    const result = await sendInvitation({ email: "shared@example.com", role: "member" });
+
+    expect(result.success).toBe(true);
+    expect(vi.mocked(db.teamInvitation.create)).toHaveBeenCalled();
+  });
+
+  it("rejects a roleId from another org (org-scoped validation)", async () => {
+    // role.findFirst with { id, organizationId: ORG_A } returns null for a foreign role
+    vi.mocked(db.role.findFirst).mockResolvedValue(null);
+
+    const result = await sendInvitation({
+      email: "new@example.com",
+      role: "member",
+      roleId: "org-b-role-id",
+    });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Role not found");
+    expect(vi.mocked(db.teamInvitation.create)).not.toHaveBeenCalled();
+  });
+
+  it("roleId lookup is scoped to the caller's organizationId", async () => {
+    vi.mocked(db.role.findFirst).mockResolvedValue(null);
+
+    await sendInvitation({
+      email: "new@example.com",
+      role: "member",
+      roleId: "some-role-id",
+    });
+
+    expect(vi.mocked(db.role.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ============================================================================
+// cancelInvitation — org isolation and authorization
+// ============================================================================
+
+describe("cancelInvitation — org isolation and authorization", () => {
+  it("owner can cancel their org's pending invitation", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-1",
+      role: "owner",
+      organizationId: ORG_A,
+    } as any);
+    vi.mocked(db.teamInvitation.findFirst).mockResolvedValue({ ...VALID_INVITATION } as any);
+    vi.mocked(db.teamInvitation.update).mockResolvedValue({} as any);
+
+    const result = await cancelInvitation({ invitationId: "inv-1" });
+
+    expect(result.success).toBe(true);
+  });
+
+  it("admin can cancel their org's pending invitation", async () => {
+    setupOrgAAdmin();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-1",
+      role: "admin",
+      organizationId: ORG_A,
+    } as any);
+    vi.mocked(db.teamInvitation.findFirst).mockResolvedValue({ ...VALID_INVITATION } as any);
+    vi.mocked(db.teamInvitation.update).mockResolvedValue({} as any);
+
+    const result = await cancelInvitation({ invitationId: "inv-1" });
+
+    expect(result.success).toBe(true);
+  });
+
+  it("plain member (built-in role) cannot cancel an invitation", async () => {
+    setupOrgAMember();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-1",
+      role: "member",
+      organizationId: ORG_A,
+    } as any);
+
+    const result = await cancelInvitation({ invitationId: "inv-1" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Only owners and admins can cancel invitations");
+    expect(vi.mocked(db.teamInvitation.update)).not.toHaveBeenCalled();
+  });
+
+  it("custom isAdmin member can cancel invitations (isAdmin covers custom roles)", async () => {
+    setupOrgACustomAdmin();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-1",
+      role: "member",
+      organizationId: ORG_A,
+    } as any);
+    vi.mocked(db.teamInvitation.findFirst).mockResolvedValue({ ...VALID_INVITATION } as any);
+    vi.mocked(db.teamInvitation.update).mockResolvedValue({} as any);
+
+    const result = await cancelInvitation({ invitationId: "inv-1" });
+
+    expect(result.success).toBe(true);
+  });
+
+  it("cannot cancel an invitation that belongs to another org", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-1",
+      role: "owner",
+      organizationId: ORG_A,
+    } as any);
+    // The invitation lookup is scoped to organizationId: ORG_A → returns null for Org B's invite
+    vi.mocked(db.teamInvitation.findFirst).mockResolvedValue(null);
+
+    const result = await cancelInvitation({ invitationId: "org-b-inv-id" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Invitation not found");
+    expect(vi.mocked(db.teamInvitation.update)).not.toHaveBeenCalled();
+  });
+
+  it("cannot cancel an already-cancelled invitation", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-1",
+      role: "owner",
+      organizationId: ORG_A,
+    } as any);
+    // status:"pending" filter excludes cancelled invitations
+    vi.mocked(db.teamInvitation.findFirst).mockResolvedValue(null);
+
+    const result = await cancelInvitation({ invitationId: "inv-1" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Invitation not found");
+  });
+
+  it("invitation lookup is scoped to the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-1",
+      role: "owner",
+      organizationId: ORG_A,
+    } as any);
+    vi.mocked(db.teamInvitation.findFirst).mockResolvedValue(null);
+
+    await cancelInvitation({ invitationId: "inv-x" });
+
+    expect(vi.mocked(db.teamInvitation.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ============================================================================
+// getPendingInvitations — org scoping
+// ============================================================================
+
+describe("getPendingInvitations — org scoping", () => {
+  it("query is scoped to the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.teamInvitation.findMany).mockResolvedValue([]);
+
+    await getPendingInvitations();
+
+    expect(vi.mocked(db.teamInvitation.findMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("filters out expired invitations via expiresAt > now", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.teamInvitation.findMany).mockResolvedValue([]);
+
+    await getPendingInvitations();
+
+    expect(vi.mocked(db.teamInvitation.findMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({
+          status: "pending",
+          expiresAt: expect.objectContaining({ gt: expect.any(Date) }),
+        }),
+      })
+    );
+  });
+
+  it("returns the caller's org's invitations", async () => {
+    setupOrgAOwner();
+    const orgAInvites = [
+      { id: "inv-1", email: "a@example.com", role: "member", organizationId: ORG_A },
+    ];
+    vi.mocked(db.teamInvitation.findMany).mockResolvedValue(orgAInvites as any);
+
+    const result = await getPendingInvitations();
+
+    expect(result.success).toBe(true);
+    expect(result.data).toHaveLength(1);
+    expect((result.data as any)[0].id).toBe("inv-1");
+  });
+
+  it("owner from Org B gets an empty list even if Org A has pending invitations", async () => {
+    // Setup: Org B owner's auth context
+    mockSession.mockResolvedValue({ user: { id: "user-b", email: "owner@orgB.com" } } as any);
+    mockMembership.mockResolvedValue({
+      organizationId: ORG_B,
+      role: "owner",
+      roleId: null,
+      customRole: null,
+    } as any);
+    mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+    // DB returns empty because the where clause uses organizationId: ORG_B
+    vi.mocked(db.teamInvitation.findMany).mockResolvedValue([]);
+
+    const result = await getPendingInvitations();
+
+    expect(result.success).toBe(true);
+    expect(result.data).toHaveLength(0);
+    // Verify the query used ORG_B, not ORG_A
+    expect(vi.mocked(db.teamInvitation.findMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_B }),
+      })
+    );
+  });
+});
+
+// ============================================================================
+// assignRole — org isolation and role validation
+// ============================================================================
+
+describe("assignRole — org isolation and role validation", () => {
+  it("owner can assign a built-in role to a member", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-2",
+      organizationId: ORG_A,
+      role: "member",
+    } as any);
+    vi.mocked(db.organizationMember.update).mockResolvedValue({} as any);
+
+    const result = await assignRole({ memberId: "mem-2", role: "admin", roleId: null });
+
+    expect(result.success).toBe(true);
+  });
+
+  it("member not in the caller's org returns 'Member not found'", async () => {
+    setupOrgAOwner();
+    // findFirst scoped to organizationId: ORG_A returns null for a foreign member
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue(null);
+
+    const result = await assignRole({ memberId: "org-b-member-id", roleId: null });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Member not found");
+    expect(vi.mocked(db.organizationMember.update)).not.toHaveBeenCalled();
+  });
+
+  it("member lookup always includes the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue(null);
+
+    await assignRole({ memberId: "mem-x", roleId: null });
+
+    expect(vi.mocked(db.organizationMember.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("cannot assign a role to the org owner", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-owner",
+      organizationId: ORG_A,
+      role: "owner",
+    } as any);
+
+    const result = await assignRole({ memberId: "mem-owner", role: "admin", roleId: null });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Cannot assign a role to the owner");
+    expect(vi.mocked(db.organizationMember.update)).not.toHaveBeenCalled();
+  });
+
+  it("rejects a roleId that does not belong to the caller's org", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-2",
+      organizationId: ORG_A,
+      role: "member",
+    } as any);
+    // role.findFirst({ where: { id, organizationId: ORG_A } }) returns null for a foreign role
+    vi.mocked(db.role.findFirst).mockResolvedValue(null);
+
+    const result = await assignRole({ memberId: "mem-2", roleId: "org-b-role-id" });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Role not found");
+    expect(vi.mocked(db.organizationMember.update)).not.toHaveBeenCalled();
+  });
+
+  it("role lookup always includes the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-2",
+      organizationId: ORG_A,
+      role: "member",
+    } as any);
+    vi.mocked(db.role.findFirst).mockResolvedValue(null);
+
+    await assignRole({ memberId: "mem-2", roleId: "some-role-id" });
+
+    expect(vi.mocked(db.role.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("plain member (built-in role) cannot assign roles", async () => {
+    setupOrgAMember();
+
+    const result = await assignRole({ memberId: "mem-2", role: "admin", roleId: null });
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Only owners and admins can assign roles");
+    expect(vi.mocked(db.organizationMember.update)).not.toHaveBeenCalled();
+  });
+
+  it("custom isAdmin member can assign roles (isAdmin covers custom roles)", async () => {
+    setupOrgACustomAdmin();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-2",
+      organizationId: ORG_A,
+      role: "member",
+    } as any);
+    vi.mocked(db.organizationMember.update).mockResolvedValue({} as any);
+
+    const result = await assignRole({ memberId: "mem-2", role: "member", roleId: null });
+
+    expect(result.success).toBe(true);
+  });
+
+  it("admin can assign a custom role to a member", async () => {
+    setupOrgAAdmin();
+    vi.mocked(db.organizationMember.findFirst).mockResolvedValue({
+      id: "mem-2",
+      organizationId: ORG_A,
+      role: "member",
+    } as any);
+    vi.mocked(db.role.findFirst).mockResolvedValue({
+      id: "tech-role-id",
+      name: "Technician",
+      organizationId: ORG_A,
+    } as any);
+    vi.mocked(db.organizationMember.update).mockResolvedValue({} as any);
+
+    const result = await assignRole({ memberId: "mem-2", roleId: "tech-role-id" });
+
+    expect(result.success).toBe(true);
+    expect(vi.mocked(db.organizationMember.update)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: expect.objectContaining({ roleId: "tech-role-id" }),
+      })
+    );
+  });
+});

+ 351 - 0
src/__tests__/multitenancy/vehicle-service-isolation.test.ts

@@ -0,0 +1,351 @@
+/**
+ * Multi-tenancy isolation tests: Vehicles & Service Records
+ *
+ * Verifies that a user from Org A cannot read, modify, or delete data
+ * belonging to Org B.  The DB mocks simulate what Prisma returns when a
+ * where-clause contains a mismatched organizationId: findFirst → null,
+ * updateMany/deleteMany → { count: 0 }.
+ *
+ */
+
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("@/lib/cached-session", () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+
+vi.mock("@/lib/resolve-upload-path", () => ({
+  resolveUploadPath: vi.fn((url: string) => `/uploads/${url}`),
+}));
+
+vi.mock("@/lib/db", () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    vehicle: {
+      findFirst: vi.fn(),
+      findMany: vi.fn(),
+      updateMany: vi.fn(),
+      deleteMany: vi.fn(),
+    },
+    serviceRecord: {
+      findFirst: vi.fn(),
+      delete: vi.fn(),
+    },
+    serviceAttachment: {
+      findFirst: vi.fn(),
+      delete: vi.fn(),
+    },
+  },
+}));
+
+import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
+import { db } from "@/lib/db";
+import {
+  getVehicle,
+  getVehicles,
+  updateVehicle,
+  deleteVehicle,
+} from "@/features/vehicles/Actions/vehicleActions";
+import {
+  getServiceRecord,
+  deleteServiceRecord,
+  deleteServiceAttachment,
+} from "@/features/vehicles/Actions/serviceActions";
+
+const mockSession = vi.mocked(getCachedSession);
+const mockMembership = vi.mocked(getCachedMembership);
+const mockUserFindUnique = vi.mocked(db.user.findUnique);
+
+const ORG_A = "org-a";
+const ORG_B = "org-b";
+
+function setupOrgAOwner() {
+  mockSession.mockResolvedValue({ user: { id: "user-a", email: "a@example.com" } } as any);
+  mockMembership.mockResolvedValue({
+    organizationId: ORG_A,
+    role: "owner",
+    roleId: null,
+    customRole: null,
+  } as any);
+  mockUserFindUnique.mockResolvedValue({ isSuperAdmin: false } as any);
+}
+
+const ORG_A_VEHICLE = {
+  id: "veh-a",
+  organizationId: ORG_A,
+  make: "Toyota",
+  model: "Camry",
+  year: 2020,
+  mileage: 50000,
+  imageUrl: null,
+  isArchived: false,
+  serviceRecords: [],
+  notes: [],
+  reminders: [],
+  customer: null,
+  _count: { serviceRecords: 0, notes: 0, reminders: 0 },
+};
+
+beforeEach(() => {
+  vi.resetAllMocks();
+});
+
+// ---------------------------------------------------------------------------
+// Vehicle read isolation
+// ---------------------------------------------------------------------------
+
+describe("getVehicle — cross-org isolation", () => {
+  it("returns 'Vehicle not found' error when requesting another org's vehicle ID", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.vehicle.findFirst).mockResolvedValue(null);
+
+    const result = await getVehicle(`${ORG_B}-vehicle-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Vehicle not found");
+  });
+
+  it("returns vehicle data for a vehicle that belongs to the caller's org", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.vehicle.findFirst).mockResolvedValue(ORG_A_VEHICLE as any);
+
+    const result = await getVehicle("veh-a");
+
+    expect(result.success).toBe(true);
+    expect((result.data as any).id).toBe("veh-a");
+  });
+
+  it("db query always scopes vehicles to the caller's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.vehicle.findFirst).mockResolvedValue(ORG_A_VEHICLE as any);
+
+    await getVehicle("veh-a");
+
+    expect(vi.mocked(db.vehicle.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Vehicle list isolation
+// ---------------------------------------------------------------------------
+
+describe("getVehicles — org scoping", () => {
+  it("list query always includes the caller's organizationId in the where clause", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.vehicle.findMany).mockResolvedValue([ORG_A_VEHICLE] as any);
+
+    await getVehicles();
+
+    expect(vi.mocked(db.vehicle.findMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Vehicle update isolation
+// ---------------------------------------------------------------------------
+
+describe("updateVehicle — cross-org isolation", () => {
+  it("🐛 BUG-1: silently returns success when targeting another org's vehicle — nothing is actually changed", async () => {
+    setupOrgAOwner();
+    // updateMany with org filter matches 0 rows for a cross-org id
+    vi.mocked(db.vehicle.updateMany).mockResolvedValue({ count: 0 } as any);
+
+    const result = await updateVehicle({ id: `${ORG_B}-vehicle-id`, make: "Hacked" });
+
+    // BUG: should be { success: false, error: "Vehicle not found" }
+    // Fix: check `result.count === 0` in updateVehicle and throw.
+    expect(result.success).toBe(false); // FAILS until bug is fixed
+  });
+
+  it("update query always includes organizationId to prevent cross-org writes", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.vehicle.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    await updateVehicle({ id: "veh-a", make: "Toyota" });
+
+    expect(vi.mocked(db.vehicle.updateMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("successfully updates a vehicle belonging to the caller's org", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.vehicle.updateMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await updateVehicle({ id: "veh-a", make: "Toyota", model: "Updated" });
+
+    expect(result.success).toBe(true);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Vehicle delete isolation
+// ---------------------------------------------------------------------------
+
+describe("deleteVehicle — cross-org isolation", () => {
+  it("🐛 BUG-2: silently returns success when targeting another org's vehicle — nothing is actually deleted", async () => {
+    setupOrgAOwner();
+    // findFirst returns null (cross-org vehicle invisible to caller)
+    vi.mocked(db.vehicle.findFirst).mockResolvedValue(null);
+    // deleteMany with org filter matches 0 rows
+    vi.mocked(db.vehicle.deleteMany).mockResolvedValue({ count: 0 } as any);
+
+    const result = await deleteVehicle(`${ORG_B}-vehicle-id`);
+
+    // BUG: should be { success: false, error: "Vehicle not found" }
+    // Fix: throw when findFirst returns null (before deleteMany).
+    expect(result.success).toBe(false); // FAILS until bug is fixed
+  });
+
+  it("delete query always includes organizationId to prevent cross-org deletes", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.vehicle.findFirst).mockResolvedValue({ imageUrl: null, serviceRecords: [] } as any);
+    vi.mocked(db.vehicle.deleteMany).mockResolvedValue({ count: 1 } as any);
+
+    await deleteVehicle("veh-a");
+
+    expect(vi.mocked(db.vehicle.deleteMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ organizationId: ORG_A }),
+      })
+    );
+  });
+
+  it("successfully deletes a vehicle belonging to the caller's org", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.vehicle.findFirst).mockResolvedValue({ imageUrl: null, serviceRecords: [] } as any);
+    vi.mocked(db.vehicle.deleteMany).mockResolvedValue({ count: 1 } as any);
+
+    const result = await deleteVehicle("veh-a");
+
+    expect(result.success).toBe(true);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Service record isolation
+// ---------------------------------------------------------------------------
+
+describe("getServiceRecord — cross-org isolation", () => {
+  it("returns null data (not an error) when querying another org's service record", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(null);
+
+    const result = await getServiceRecord(`${ORG_B}-record-id`);
+
+    // Returns success:true with null data — caller must check for null.
+    // Note: inconsistent with getVehicle / getQuote which throw. Not a
+    // security issue (no cross-org data is returned) but worth noting.
+    expect(result.success).toBe(true);
+    expect(result.data).toBeNull();
+  });
+
+  it("db query scopes service records to the caller's org via vehicle relation", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(null);
+
+    await getServiceRecord("sr-a");
+
+    expect(vi.mocked(db.serviceRecord.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({
+          vehicle: expect.objectContaining({ organizationId: ORG_A }),
+        }),
+      })
+    );
+  });
+
+  it("returns service record data when querying the caller's own record", async () => {
+    setupOrgAOwner();
+    const record = { id: "sr-a", vehicleId: "veh-a", title: "Oil Change" };
+    vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(record as any);
+
+    const result = await getServiceRecord("sr-a");
+
+    expect(result.success).toBe(true);
+    expect((result.data as any)?.id).toBe("sr-a");
+  });
+});
+
+describe("deleteServiceRecord — cross-org isolation", () => {
+  it("returns 'Record not found' error when targeting another org's service record", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(null);
+
+    const result = await deleteServiceRecord(`${ORG_B}-record-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Record not found");
+  });
+
+  it("successfully deletes a service record belonging to the caller's org", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.serviceRecord.findFirst).mockResolvedValue({
+      id: "sr-a",
+      vehicleId: "veh-a",
+      attachments: [],
+    } as any);
+    vi.mocked(db.serviceRecord.delete).mockResolvedValue({} as any);
+
+    const result = await deleteServiceRecord("sr-a");
+
+    expect(result.success).toBe(true);
+  });
+});
+
+describe("deleteServiceAttachment — cross-org isolation", () => {
+  it("returns 'Attachment not found' error when targeting another org's attachment", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.serviceAttachment.findFirst).mockResolvedValue(null);
+
+    const result = await deleteServiceAttachment(`${ORG_B}-attachment-id`);
+
+    expect(result.success).toBe(false);
+    expect(result.error).toBe("Attachment not found");
+  });
+
+  it("attachment lookup always scopes through vehicle's organizationId", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.serviceAttachment.findFirst).mockResolvedValue(null);
+
+    await deleteServiceAttachment("att-x");
+
+    expect(vi.mocked(db.serviceAttachment.findFirst)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({
+          serviceRecord: expect.objectContaining({
+            vehicle: expect.objectContaining({ organizationId: ORG_A }),
+          }),
+        }),
+      })
+    );
+  });
+
+  it("successfully deletes an attachment belonging to the caller's org", async () => {
+    setupOrgAOwner();
+    vi.mocked(db.serviceAttachment.findFirst).mockResolvedValue({
+      id: "att-a",
+      fileUrl: "uploads/photo.jpg",
+      serviceRecord: { vehicleId: "veh-a", id: "sr-a" },
+    } as any);
+    vi.mocked(db.serviceAttachment.delete).mockResolvedValue({} as any);
+
+    const result = await deleteServiceAttachment("att-a");
+
+    expect(result.success).toBe(true);
+    expect((result.data as any)?.deleted).toBe(true);
+  });
+});

+ 1 - 0
src/__tests__/setup.ts

@@ -0,0 +1 @@
+import "@testing-library/jest-dom";

+ 2 - 2
src/app/(authenticated)/inspections/[id]/page.tsx

@@ -1,5 +1,5 @@
 import { getInspection } from "@/features/inspections/Actions/inspectionActions";
-import { InspectionPageClient } from "@/features/inspections/Components/InspectionPageClient";
+import { InspectionPageClient, type InspectionData } from "@/features/inspections/Components/InspectionPageClient";
 import { PageHeader } from "@/components/page-header";
 
 export default async function InspectionDetailPage({
@@ -28,7 +28,7 @@ export default async function InspectionDetailPage({
     <>
       <PageHeader />
       <div className="flex flex-1 flex-col gap-4 p-4 pt-0">
-        <InspectionPageClient inspection={result.data} />
+        <InspectionPageClient inspection={result.data as InspectionData} />
       </div>
     </>
   );

+ 4 - 2
src/features/customers/Actions/customerActions.ts

@@ -64,13 +64,14 @@ export async function createCustomer(input: unknown) {
 export async function updateCustomer(input: unknown) {
   return withAuth(async ({ userId, organizationId }) => {
     const { id, ...data } = updateCustomerSchema.parse(input);
-    await db.customer.updateMany({
+    const result = await db.customer.updateMany({
       where: { id, organizationId },
       data: {
         ...data,
         email: data.email || null,
       },
     });
+    if (result.count === 0) throw new Error("Customer not found");
     revalidatePath("/customers");
     revalidatePath(`/customers/${id}`);
     return { id };
@@ -79,7 +80,8 @@ export async function updateCustomer(input: unknown) {
 
 export async function deleteCustomer(customerId: string) {
   return withAuth(async ({ userId, organizationId }) => {
-    await db.customer.deleteMany({ where: { id: customerId, organizationId } });
+    const result = await db.customer.deleteMany({ where: { id: customerId, organizationId } });
+    if (result.count === 0) throw new Error("Customer not found");
     revalidatePath("/customers");
   }, { requiredPermissions: [{ action: PermissionAction.DELETE, subject: PermissionSubject.CUSTOMERS }] });
 }

+ 3 - 3
src/features/inspections/Actions/inspectionActions.ts

@@ -202,8 +202,8 @@ export async function completeInspection(id: string) {
     });
     if (!inspection) throw new Error("Inspection not found");
 
-    await db.inspection.update({
-      where: { id },
+    await db.inspection.updateMany({
+      where: { id, organizationId },
       data: { status: "completed", completedAt: new Date() },
     });
 
@@ -221,7 +221,7 @@ export async function deleteInspection(id: string) {
     });
     if (!inspection) throw new Error("Inspection not found");
 
-    await db.inspection.delete({ where: { id } });
+    await db.inspection.deleteMany({ where: { id, organizationId } });
     revalidatePath("/inspections");
     revalidatePath(`/vehicles/${inspection.vehicleId}`);
   }, { requiredPermissions: [{ action: PermissionAction.DELETE, subject: PermissionSubject.INSPECTIONS }] });

+ 1 - 1
src/features/inspections/Components/InspectionPageClient.tsx

@@ -35,7 +35,7 @@ interface InspectionItem {
   imageUrls: string[];
 }
 
-interface InspectionData {
+export interface InspectionData {
   id: string;
   status: string;
   mileage: number | null;

+ 4 - 4
src/features/inventory/Actions/inventoryActions.ts

@@ -160,8 +160,8 @@ export async function adjustInventoryStock(input: unknown) {
     const newQuantity = part.quantity + adjustment;
     if (newQuantity < 0) throw new Error("Insufficient stock");
 
-    await db.inventoryPart.update({
-      where: { id },
+    await db.inventoryPart.updateMany({
+      where: { id, organizationId },
       data: { quantity: newQuantity },
     });
     revalidatePath("/inventory");
@@ -214,8 +214,8 @@ export async function applyMarkupToAll(input: unknown) {
 
     await db.$transaction(
       parts.map((p) =>
-        db.inventoryPart.update({
-          where: { id: p.id },
+        db.inventoryPart.updateMany({
+          where: { id: p.id, organizationId },
           data: { sellPrice: Math.round(p.unitCost * multiplier * 100) / 100 },
         })
       )

+ 5 - 5
src/features/quotes/Actions/quoteActions.ts

@@ -203,8 +203,8 @@ export async function updateQuoteStatus(quoteId: string, status: string) {
     });
     if (!quote) throw new Error("Quote not found");
 
-    await db.quote.update({
-      where: { id: quoteId },
+    await db.quote.updateMany({
+      where: { id: quoteId, organizationId },
       data: { status },
     });
 
@@ -221,7 +221,7 @@ export async function deleteQuote(quoteId: string) {
     });
     if (!quote) throw new Error("Quote not found");
 
-    await db.quote.delete({ where: { id: quoteId } });
+    await db.quote.deleteMany({ where: { id: quoteId, organizationId } });
     revalidatePath("/quotes");
   }, { requiredPermissions: [{ action: PermissionAction.DELETE, subject: PermissionSubject.QUOTES }] });
 }
@@ -313,8 +313,8 @@ export async function convertQuoteToServiceRecord(quoteId: string, vehicleId: st
       }
 
       // Mark quote as converted
-      await tx.quote.update({
-        where: { id: quoteId },
+      await tx.quote.updateMany({
+        where: { id: quoteId, organizationId },
         data: { status: "converted", convertedToId: created.id },
       });
 

+ 3 - 3
src/features/team/Actions/acceptInvitation.ts

@@ -1,15 +1,15 @@
 "use server";
 
-import { headers, cookies } from "next/headers";
-import { auth } from "@/lib/auth";
+import { cookies } from "next/headers";
 import { db } from "@/lib/db";
+import { getCachedSession } from "@/lib/cached-session";
 import { acceptInvitationSchema } from "../Schema/teamSchema";
 
 export async function acceptInvitation(input: unknown) {
   try {
     const data = acceptInvitationSchema.parse(input);
 
-    const session = await auth.api.getSession({ headers: await headers() });
+    const session = await getCachedSession();
     if (!session?.user?.id) {
       return { success: false, error: "You must be signed in to accept an invitation" };
     }

+ 2 - 3
src/features/team/Actions/assignRole.ts

@@ -7,11 +7,10 @@ import { revalidatePath } from "next/cache";
 import { PermissionAction, PermissionSubject } from "@/lib/permissions";
 
 export async function assignRole(input: unknown) {
-  return withAuth(async ({ organizationId, role, isSuperAdmin }) => {
-    if (!isSuperAdmin && role !== "owner" && role !== "admin") {
+  return withAuth(async ({ organizationId, isAdmin }) => {
+    if (!isAdmin) {
       throw new Error("Only owners and admins can assign roles");
     }
-
     const data = assignRoleSchema.parse(input);
 
     const member = await db.organizationMember.findFirst({

+ 3 - 3
src/features/team/Actions/cancelInvitation.ts

@@ -7,15 +7,15 @@ import { PermissionAction, PermissionSubject } from "@/lib/permissions";
 import { revalidatePath } from "next/cache";
 
 export async function cancelInvitation(input: unknown) {
-  return withAuth(async ({ userId, organizationId }) => {
+  return withAuth(async ({ userId, organizationId, isAdmin }) => {
     const data = cancelInvitationSchema.parse(input);
 
-    // Verify caller is owner or admin
+    // Verify caller belongs to an organization
     const membership = await db.organizationMember.findFirst({
       where: { userId, organizationId },
     });
     if (!membership) throw new Error("You don't belong to an organization");
-    if (membership.role === "member") throw new Error("Only owners and admins can cancel invitations");
+    if (!isAdmin) throw new Error("Only owners and admins can cancel invitations");
 
     const invitation = await db.teamInvitation.findFirst({
       where: { id: data.invitationId, organizationId, status: "pending" },

+ 34 - 28
src/features/team/Actions/sendInvitation.ts

@@ -12,13 +12,12 @@ export async function sendInvitation(input: unknown) {
   return withAuth(async ({ userId, organizationId }) => {
     const data = sendInvitationSchema.parse(input);
 
-    // Verify caller is owner or admin
+    // Fetch membership for organization name (authorization is handled by withAuth's requiredPermissions)
     const membership = await db.organizationMember.findFirst({
       where: { userId, organizationId },
       include: { organization: true },
     });
     if (!membership) throw new Error("You don't belong to an organization");
-    if (membership.role === "member") throw new Error("Only owners and admins can invite members");
 
     // Check for existing pending invitation
     const existing = await db.teamInvitation.findFirst({
@@ -43,14 +42,15 @@ export async function sendInvitation(input: unknown) {
     const token = randomUUID();
     const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
 
-    // Look up custom role name if roleId is provided
+    // Validate and look up custom role name if roleId is provided
     let customRoleName: string | undefined;
     if (data.roleId) {
-      const customRole = await db.role.findUnique({ where: { id: data.roleId }, select: { name: true } });
-      customRoleName = customRole?.name;
+      const customRole = await db.role.findFirst({ where: { id: data.roleId, organizationId }, select: { name: true } });
+      if (!customRole) throw new Error("Role not found");
+      customRoleName = customRole.name;
     }
 
-    await db.teamInvitation.create({
+    const invitation = await db.teamInvitation.create({
       data: {
         email: data.email,
         role: data.role,
@@ -69,29 +69,35 @@ export async function sendInvitation(input: unknown) {
 
     const roleLabel = customRoleName || data.role;
 
-    await sendOrgMail(organizationId, {
-      from,
-      to: data.email,
-      subject: `You've been invited to join ${membership.organization.name} on Torqvoice`,
-      html: `
-        <div style="font-family: sans-serif; max-width: 480px; margin: 0 auto;">
-          <h2>Team Invitation</h2>
-          <p>You've been invited to join <strong>${membership.organization.name}</strong> on Torqvoice as a <strong>${roleLabel}</strong>.</p>
-          <p>Click the button below to create your account and join the team:</p>
-          <div style="margin: 24px 0;">
-            <a href="${signupUrl}" style="display: inline-block; padding: 12px 24px; background-color: #171717; color: #ffffff; text-decoration: none; border-radius: 8px; font-weight: 500;">
-              Accept Invitation
-            </a>
+    try {
+      await sendOrgMail(organizationId, {
+        from,
+        to: data.email,
+        subject: `You've been invited to join ${membership.organization.name} on Torqvoice`,
+        html: `
+          <div style="font-family: sans-serif; max-width: 480px; margin: 0 auto;">
+            <h2>Team Invitation</h2>
+            <p>You've been invited to join <strong>${membership.organization.name}</strong> on Torqvoice as a <strong>${roleLabel}</strong>.</p>
+            <p>Click the button below to create your account and join the team:</p>
+            <div style="margin: 24px 0;">
+              <a href="${signupUrl}" style="display: inline-block; padding: 12px 24px; background-color: #171717; color: #ffffff; text-decoration: none; border-radius: 8px; font-weight: 500;">
+                Accept Invitation
+              </a>
+            </div>
+            <p style="color: #6b7280; font-size: 14px;">This invitation expires in 7 days.</p>
+            <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
+            <p style="color: #6b7280; font-size: 12px;">
+              If the button doesn't work, copy and paste this URL into your browser:<br/>
+              <a href="${signupUrl}" style="color: #6b7280;">${signupUrl}</a>
+            </p>
           </div>
-          <p style="color: #6b7280; font-size: 14px;">This invitation expires in 7 days.</p>
-          <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
-          <p style="color: #6b7280; font-size: 12px;">
-            If the button doesn't work, copy and paste this URL into your browser:<br/>
-            <a href="${signupUrl}" style="color: #6b7280;">${signupUrl}</a>
-          </p>
-        </div>
-      `,
-    });
+        `,
+      });
+    } catch (emailError) {
+      // Roll back the invitation record so the admin can retry
+      await db.teamInvitation.delete({ where: { id: invitation.id } });
+      throw new Error("Failed to send invitation email. Please try again.");
+    }
 
     revalidatePath("/settings/team");
     return { invited: true, pending: true };

+ 2 - 0
src/features/vehicles/Actions/vehicleActions.ts

@@ -162,6 +162,7 @@ export async function updateVehicle(input: unknown) {
         customerId: data.customerId !== undefined ? (data.customerId || null) : undefined,
       },
     });
+    if (vehicle.count === 0) throw new Error("Vehicle not found");
     revalidatePath("/");
     revalidatePath("/vehicles");
     revalidatePath(`/vehicles/${id}`);
@@ -181,6 +182,7 @@ export async function deleteVehicle(vehicleId: string) {
         },
       },
     });
+    if (!vehicle) throw new Error("Vehicle not found");
 
     await db.vehicle.deleteMany({ where: { id: vehicleId, organizationId } });
 

+ 1 - 1
src/lib/cached-session.ts

@@ -16,7 +16,7 @@ export const getCachedMembership = cache(async (userId: string) => {
     role: true,
     roleId: true,
     customRole: {
-      include: { permissions: { select: { action: true, subject: true } } },
+      select: { isAdmin: true, permissions: { select: { action: true, subject: true } } },
     },
   } as const;
 

+ 7 - 3
src/lib/get-auth-context.ts

@@ -28,15 +28,19 @@ export async function getAuthContextDetailed(): Promise<AuthContextResult> {
 
   const isSuperAdmin = user?.isSuperAdmin ?? false;
 
-  if (!membership && !isSuperAdmin) return { status: "no-organization" };
+  if (!membership?.organizationId) return { status: "no-organization" };
+
+  const isOwnerOrAdmin = membership.role === "owner" || membership.role === "admin";
+  const roleIsAdmin = membership.customRole?.isAdmin === true;
 
   return {
     status: "ok",
     context: {
       userId: session.user.id,
-      organizationId: membership?.organizationId ?? "",
-      role: isSuperAdmin ? "super_admin" : (membership?.role ?? "member"),
+      organizationId: membership.organizationId,
+      role: isSuperAdmin ? "super_admin" : (membership.role ?? "member"),
       isSuperAdmin,
+      isAdmin: isSuperAdmin || isOwnerOrAdmin || roleIsAdmin,
     },
   };
 }

+ 7 - 5
src/lib/with-auth.ts

@@ -15,6 +15,7 @@ export type AuthContext = {
   organizationId: string;
   role: string;
   isSuperAdmin: boolean;
+  isAdmin: boolean;
 };
 
 type WithAuthOptions = {
@@ -41,15 +42,15 @@ export async function withAuth<T>(
 
     const membership = await getCachedMembership(session.user.id);
 
-    // Super admins can bypass the organization requirement
-    if (!membership && !isSuperAdmin) {
+    if (!membership?.organizationId) {
       return { success: false, error: "No organization found" };
     }
 
+    const isOwnerOrAdmin = membership?.role === "owner" || membership?.role === "admin";
+    const roleIsAdmin = membership?.customRole?.isAdmin === true;
+
     // Check permissions if required (super admins bypass all permission checks)
     if (!isSuperAdmin && options.requiredPermissions && options.requiredPermissions.length > 0) {
-      const isOwnerOrAdmin = membership?.role === "owner" || membership?.role === "admin";
-      const roleIsAdmin = membership?.customRole?.isAdmin === true;
       // Members without a custom role have full access (no restrictions)
       const hasNoCustomRole = !membership?.roleId;
 
@@ -63,9 +64,10 @@ export async function withAuth<T>(
 
     const data = await action({
       userId: session.user.id,
-      organizationId: membership?.organizationId ?? "",
+      organizationId: membership.organizationId,
       role: isSuperAdmin ? "super_admin" : (membership?.role ?? "member"),
       isSuperAdmin,
+      isAdmin: isSuperAdmin || isOwnerOrAdmin || roleIsAdmin,
     });
     return { success: true, data };
   } catch (error) {

+ 15 - 0
vitest.config.ts

@@ -0,0 +1,15 @@
+import { defineConfig } from "vitest/config";
+import { resolve } from "path";
+
+export default defineConfig({
+  test: {
+    environment: "jsdom",
+    globals: true,
+    setupFiles: ["./src/__tests__/setup.ts"],
+  },
+  resolve: {
+    alias: {
+      "@": resolve(__dirname, "./src"),
+    },
+  },
+});

Некоторые файлы не были показаны из-за большого количества измененных файлов