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

Open the record from a row of the dashboard's recent activity (#670)

* Open the record from a row of the dashboard's recent activity

* Link a recent activity row only for someone who may open its record
Bernt Christian Egeland 5 дней назад
Родитель
Сommit
94abda44da

+ 136 - 0
src/__tests__/features/audit/activity-links.test.ts

@@ -0,0 +1,136 @@
+/**
+ * @vitest-environment node
+ *
+ * Where a row of the dashboard's Recent Activity leads.
+ *
+ * Someone who sees "changed a work order" wants to open that work order. A
+ * row may only link to a record that still exists in this workshop: the id in
+ * an audit row outlives the record it names, and it may never be trusted to
+ * belong here.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const tables = vi.hoisted(() => {
+  const table = () => ({ findMany: vi.fn(async (_args: unknown): Promise<unknown[]> => []) })
+  return {
+    serviceRecord: table(),
+    vehicle: table(),
+    quote: table(),
+    customer: table(),
+    inspection: table(),
+    inventoryPart: table(),
+  }
+})
+vi.mock('@/lib/db', () => ({ db: tables }))
+
+import { activityLinks as linksFor } from '@/features/audit/Lib/activityLinks'
+import { PermissionSubject } from '@/lib/permissions'
+
+/** Someone who may read everything, as an owner does. */
+const everything = { reads: () => true }
+const activityLinks = (organizationId: string, rows: Parameters<typeof linksFor>[1]) =>
+  linksFor(organizationId, rows, everything)
+
+const row = (id: string, entity: string | null, entityId: string | null) => ({
+  id,
+  entity,
+  entityId,
+})
+
+beforeEach(() => {
+  for (const table of Object.values(tables)) {
+    table.findMany.mockReset()
+    table.findMany.mockResolvedValue([])
+  }
+})
+
+describe('the links of the recent activity list', () => {
+  it('opens a work order on its vehicle, and a counter sale on its own page', async () => {
+    tables.serviceRecord.findMany.mockResolvedValue([
+      { id: 'job-1', vehicleId: 'veh-1' },
+      { id: 'sale-1', vehicleId: null },
+    ])
+
+    const links = await activityLinks('org-1', [
+      row('a', 'ServiceRecord', 'job-1'),
+      row('b', 'ServiceRecord', 'sale-1'),
+    ])
+
+    expect(links.get('a')).toBe('/vehicles/veh-1/service/job-1')
+    expect(links.get('b')).toBe('/sales/sale-1')
+  })
+
+  it('opens a quote, a vehicle, a customer, an inspection and a part', async () => {
+    tables.quote.findMany.mockResolvedValue([{ id: 'q-1' }])
+    tables.vehicle.findMany.mockResolvedValue([{ id: 'v-1' }])
+    tables.customer.findMany.mockResolvedValue([{ id: 'c-1' }])
+    tables.inspection.findMany.mockResolvedValue([{ id: 'i-1' }])
+    tables.inventoryPart.findMany.mockResolvedValue([{ id: 'p-1' }])
+
+    const links = await activityLinks('org-1', [
+      row('a', 'Quote', 'q-1'),
+      row('b', 'Vehicle', 'v-1'),
+      row('c', 'Customer', 'c-1'),
+      row('d', 'Inspection', 'i-1'),
+      row('e', 'InventoryPart', 'p-1'),
+    ])
+
+    expect(Object.fromEntries(links)).toEqual({
+      a: '/quotes/q-1',
+      b: '/vehicles/v-1',
+      c: '/customers/c-1',
+      d: '/inspections/i-1',
+      e: '/inventory/p-1',
+    })
+  })
+
+  it('leaves a row plain when its record is gone or is not this workshop’s', async () => {
+    // The query is scoped to the workshop and finds nothing.
+    const links = await activityLinks('org-1', [row('a', 'Quote', 'q-deleted')])
+
+    expect(links.has('a')).toBe(false)
+    expect(tables.quote.findMany).toHaveBeenCalledWith({
+      where: { organizationId: 'org-1', id: { in: ['q-deleted'] } },
+      select: { id: true },
+    })
+  })
+
+  it('leaves a row plain when it is about something with no page of its own', async () => {
+    const links = await activityLinks('org-1', [
+      row('a', 'AppSetting', 'setting-1'),
+      row('b', null, null),
+      row('c', 'Quote', null),
+    ])
+
+    expect(links.size).toBe(0)
+    // Nothing to look up, so nothing is asked.
+    for (const table of Object.values(tables)) expect(table.findMany).not.toHaveBeenCalled()
+  })
+
+  it('shows the list without links when the lookup fails', async () => {
+    tables.serviceRecord.findMany.mockRejectedValue(new Error('database is away'))
+
+    await expect(
+      activityLinks('org-1', [row('a', 'ServiceRecord', 'job-1'), row('b', 'Quote', 'q-1')])
+    ).resolves.toEqual(new Map())
+  })
+
+  it('leaves a row plain for someone who may not read that kind of record', async () => {
+    tables.quote.findMany.mockResolvedValue([{ id: 'q-1' }])
+    tables.vehicle.findMany.mockResolvedValue([{ id: 'v-1' }])
+    tables.serviceRecord.findMany.mockResolvedValue([{ id: 'job-1', vehicleId: 'v-1' }])
+    // A role that reads vehicles and nothing else.
+    const vehiclesOnly = { reads: (subject: PermissionSubject) => subject === 'vehicles' }
+
+    const links = await linksFor(
+      'org-1',
+      [row('a', 'Quote', 'q-1'), row('b', 'Vehicle', 'v-1'), row('c', 'ServiceRecord', 'job-1')],
+      vehiclesOnly
+    )
+
+    expect(Object.fromEntries(links)).toEqual({ b: '/vehicles/v-1' })
+    // Not asked for at all, not asked and then hidden.
+    expect(tables.quote.findMany).not.toHaveBeenCalled()
+    expect(tables.serviceRecord.findMany).not.toHaveBeenCalled()
+  })
+})

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

@@ -4,6 +4,7 @@ import { DEFAULT_CURRENCY_CODE } from '@/lib/currencies'
 import { useTableKeyboardNav } from '@/hooks/use-table-keyboard-nav'
 import { interactiveRow } from '@/lib/interactive-row'
 import { useState, useTransition } from 'react'
+import Link from 'next/link'
 import { useRouter } from 'next/navigation'
 import { useFormatter, useTranslations } from 'next-intl'
 import { useFormatDate } from '@/lib/use-format-date'
@@ -358,6 +359,8 @@ export function DashboardClient({
     // eslint-disable-next-line @typescript-eslint/no-explicit-any
     metadata?: any
     user: { id: string; name: string | null; email: string | null } | null
+    /** The page of the record the row is about, while that record exists. */
+    href?: string | null
   }[]
   recentObservations?: DashboardObservation[]
   initialLayout?: unknown
@@ -2019,11 +2022,8 @@ export function DashboardClient({
                       const friendlyAction = tAudit.has(actionKey) ? tAudit(actionKey) : log.action
                       const entityLabel =
                         vehicleDisplay ?? quoteNumber ?? log.entityId?.substring(0, 8)
-                      return (
-                        <div
-                          key={log.id}
-                          className="px-5 py-3 text-sm flex items-center justify-between"
-                        >
+                      const row = (
+                        <>
                           <div className="min-w-0">
                             <p className="truncate">
                               <span className="font-medium">{userLabel}</span> {friendlyAction}
@@ -2043,6 +2043,21 @@ export function DashboardClient({
                           <div className="shrink-0 ml-3 text-xs text-muted-foreground">
                             {formatDate(new Date(log.timestamp))}
                           </div>
+                        </>
+                      )
+                      const rowClass = 'px-5 py-3 text-sm flex items-center justify-between'
+                      // A row about a record that is still there opens it.
+                      return log.href ? (
+                        <Link
+                          key={log.id}
+                          href={log.href}
+                          className={`${rowClass} transition-colors hover:bg-muted/50 focus-visible:bg-muted/50 focus-visible:outline-none`}
+                        >
+                          {row}
+                        </Link>
+                      ) : (
+                        <div key={log.id} className={rowClass}>
+                          {row}
                         </div>
                       )
                     })}

+ 7 - 2
src/features/audit/Actions/auditActions.ts

@@ -1,17 +1,22 @@
 'use server'
 
 import { db } from '@/lib/db'
+import { accessFor } from '@/lib/viewer-access'
 import { withAuth } from '@/lib/with-auth'
+import { activityLinks } from '../Lib/activityLinks'
 
 export async function getRecentAuditLogs(limit = 10) {
-  return withAuth(async ({ organizationId }) => {
+  return withAuth(async ({ organizationId, userId, isAdmin }) => {
     const logs = await db.auditLog.findMany({
       where: { organizationId },
       include: { user: { select: { id: true, name: true, email: true } } },
       orderBy: { timestamp: 'desc' },
       take: limit,
     })
-    return logs
+    // Where each row leads, for the ones about a record that is still there
+    // and that this person may open.
+    const links = await activityLinks(organizationId, logs, await accessFor({ userId, isAdmin }))
+    return logs.map((log) => ({ ...log, href: links.get(log.id) ?? null }))
   })
 }
 

+ 107 - 0
src/features/audit/Lib/activityLinks.ts

@@ -0,0 +1,107 @@
+import { db } from '@/lib/db'
+import { PermissionSubject } from '@/lib/permissions'
+import type { ViewerAccess } from '@/lib/viewer-access'
+
+type ActivityRow = { id: string; entity: string | null; entityId: string | null }
+
+/** The kinds of record an activity row can open, and the page each lives on. */
+const PAGES = {
+  Vehicle: (id: string) => `/vehicles/${id}`,
+  Quote: (id: string) => `/quotes/${id}`,
+  Customer: (id: string) => `/customers/${id}`,
+  Inspection: (id: string) => `/inspections/${id}`,
+  InventoryPart: (id: string) => `/inventory/${id}`,
+} as const
+
+type PagedEntity = keyof typeof PAGES
+
+/** What a person must be allowed to read for a row of that kind to open. */
+const READS: Record<PagedEntity | 'ServiceRecord', PermissionSubject> = {
+  ServiceRecord: PermissionSubject.SERVICES,
+  Vehicle: PermissionSubject.VEHICLES,
+  Quote: PermissionSubject.QUOTES,
+  Customer: PermissionSubject.CUSTOMERS,
+  Inspection: PermissionSubject.INSPECTIONS,
+  InventoryPart: PermissionSubject.INVENTORY,
+}
+
+/** The ids of one kind that still exist in this workshop. */
+async function existing(
+  entity: PagedEntity,
+  organizationId: string,
+  ids: string[]
+): Promise<string[]> {
+  const where = { organizationId, id: { in: ids } }
+  const select = { id: true } as const
+  const found =
+    entity === 'Vehicle'
+      ? await db.vehicle.findMany({ where, select })
+      : entity === 'Quote'
+        ? await db.quote.findMany({ where, select })
+        : entity === 'Customer'
+          ? await db.customer.findMany({ where, select })
+          : entity === 'Inspection'
+            ? await db.inspection.findMany({ where, select })
+            : await db.inventoryPart.findMany({ where, select })
+  return found.map((row) => row.id)
+}
+
+/**
+ * Where each row of the activity list leads: the work order, quote, vehicle,
+ * customer, inspection or part it is about. Keyed by the row's own id.
+ *
+ * A row gets a link only while its record is still there and belongs to this
+ * workshop, and only for a person who may read that kind of record: a link
+ * that ends in "no access" is worse than plain text, and opening it writes a
+ * refusal to the audit log. So a "deleted" row, one about something with no
+ * page of its own, and one this role may not open all stay plain text. A work order needs its vehicle to be addressed, and a
+ * counter sale has none, which is why these are looked up rather than built
+ * from the id alone.
+ *
+ * The list is a convenience on the dashboard: if the lookup fails, the rows
+ * are shown without links rather than the page failing.
+ */
+export async function activityLinks(
+  organizationId: string,
+  rows: ActivityRow[],
+  access: ViewerAccess
+): Promise<Map<string, string>> {
+  const links = new Map<string, string>()
+  const idsOf = (entity: PagedEntity | 'ServiceRecord') =>
+    access.reads(READS[entity])
+      ? [...new Set(rows.filter((r) => r.entity === entity && r.entityId).map((r) => r.entityId!))]
+      : []
+  try {
+    const jobIds = idsOf('ServiceRecord')
+    const [jobs, ...paged] = await Promise.all([
+      jobIds.length
+        ? db.serviceRecord.findMany({
+            where: { organizationId, id: { in: jobIds } },
+            select: { id: true, vehicleId: true },
+          })
+        : [],
+      ...(Object.keys(PAGES) as PagedEntity[]).map(async (entity) => {
+        const ids = idsOf(entity)
+        return { entity, ids: ids.length ? await existing(entity, organizationId, ids) : [] }
+      }),
+    ])
+
+    const hrefs = new Map<string, string>()
+    for (const job of jobs) {
+      hrefs.set(
+        `ServiceRecord:${job.id}`,
+        job.vehicleId ? `/vehicles/${job.vehicleId}/service/${job.id}` : `/sales/${job.id}`
+      )
+    }
+    for (const { entity, ids } of paged) {
+      for (const id of ids) hrefs.set(`${entity}:${id}`, PAGES[entity](id))
+    }
+    for (const row of rows) {
+      const href = hrefs.get(`${row.entity}:${row.entityId}`)
+      if (href) links.set(row.id, href)
+    }
+  } catch {
+    return new Map()
+  }
+  return links
+}