owned-records.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import 'server-only'
  2. import { db, type TxClient } from '@/lib/db'
  3. /**
  4. * A record may only point at customers and vehicles of its own workshop.
  5. *
  6. * Every write that stores a customerId or vehicleId it was handed goes
  7. * through here first. The row being written is always loaded org-scoped;
  8. * these make sure the ids written into it are too, so a quote or a tire set
  9. * can never be made to show another workshop's customer. An empty value is
  10. * a clearing and passes; a wrong id fails the same way a wrong row id does.
  11. */
  12. type Reader = Pick<TxClient, 'customer' | 'vehicle'>
  13. export async function assertOwnedCustomer(
  14. customerId: string | null | undefined,
  15. organizationId: string,
  16. client: Reader = db
  17. ): Promise<void> {
  18. if (!customerId) return
  19. const customer = await client.customer.findFirst({
  20. where: { id: customerId, organizationId },
  21. select: { id: true },
  22. })
  23. if (!customer) throw new Error('Customer not found')
  24. }
  25. export async function assertOwnedVehicle(
  26. vehicleId: string | null | undefined,
  27. organizationId: string,
  28. client: Reader = db
  29. ): Promise<void> {
  30. if (!vehicleId) return
  31. const vehicle = await client.vehicle.findFirst({
  32. where: { id: vehicleId, organizationId },
  33. select: { id: true },
  34. })
  35. if (!vehicle) throw new Error('Vehicle not found')
  36. }