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

Attach a PDF to a job from the technician app (#601)

Bernt Christian Egeland 11 часов назад
Родитель
Сommit
94df1c1992

+ 141 - 0
src/__tests__/api/tech-job-documents.test.ts

@@ -0,0 +1,141 @@
+/**
+ * @vitest-environment node
+ *
+ * A document attached to a job from the technician app.
+ *
+ * A technician is handed paper that belongs with the job: a supplier's
+ * delivery note, an alignment printout, a calibration report. From the phone
+ * it arrives as a PDF and has to land where the desk looks for it, under the
+ * job's documents, not among its photos.
+ *
+ * The type on the upload is the phone's word for it. A file that only claims
+ * to be a PDF is refused, because the desk opens whatever is filed there.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const state = {
+  job: { id: 'rec-1' } as { id: string } | null,
+  documentsOnJob: 0,
+  created: null as Record<string, unknown> | null,
+}
+
+vi.mock('@/lib/db', () => ({
+  db: {
+    serviceRecord: { findFirst: vi.fn(async () => state.job) },
+    serviceAttachment: {
+      count: vi.fn(async () => state.documentsOnJob),
+      create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
+        state.created = data
+        return { id: 'att-1', ...data, createdAt: new Date('2026-11-15T10:00:00Z') }
+      }),
+    },
+  },
+}))
+
+vi.mock('node:fs/promises', () => ({
+  mkdir: vi.fn(async () => undefined),
+  writeFile: vi.fn(async () => undefined),
+  stat: vi.fn(async () => ({ size: 1234 })),
+}))
+
+vi.mock('@/lib/features', async () => ({
+  ...(await vi.importActual<typeof import('@/lib/features')>('@/lib/features')),
+  getFeatures: vi.fn(async () => ({
+    maxImagesPerService: 20,
+    maxDiagnosticsPerService: 5,
+    maxDocumentsPerService: 5,
+  })),
+}))
+
+vi.mock('@/lib/video-downscale', () => ({ queueVideoDownscale: vi.fn() }))
+
+vi.mock('@/lib/with-api-auth', async () => {
+  const actual = await vi.importActual<typeof import('@/lib/with-api-auth')>('@/lib/with-api-auth')
+  return {
+    ...actual,
+    withApiAuth: vi.fn(
+      async (
+        _request: Request,
+        handler: (ctx: {
+          organizationId: string
+          technicianIds: string[]
+          isAdmin: boolean
+        }) => Promise<Response>
+      ) => handler({ organizationId: 'org-1', technicianIds: ['tech-1'], isAdmin: false })
+    ),
+  }
+})
+
+import { POST } from '@/app/api/v1/tech/jobs/[id]/attachments/route'
+import { TECH_API_FEATURES } from '@/lib/tech-api-features'
+
+const PDF = '%PDF-1.7\n1 0 obj\n<< /Type /Catalog >>\nendobj\n%%EOF\n'
+
+function upload(content: string, name: string, type: string) {
+  const form = new FormData()
+  form.set('file', new File([content], name, { type }))
+  return POST(
+    new Request('https://app.test/api/v1/tech/jobs/rec-1/attachments', {
+      method: 'POST',
+      body: form,
+    }),
+    { params: Promise.resolve({ id: 'rec-1' }) }
+  )
+}
+
+beforeEach(() => {
+  state.job = { id: 'rec-1' }
+  state.documentsOnJob = 0
+  state.created = null
+})
+
+describe('a technician attaching a document from the app', () => {
+  it('files a PDF with the job’s documents, under the name it had on the phone', async () => {
+    const response = await upload(PDF, 'alignment-report.pdf', 'application/pdf')
+
+    expect(response.status).toBe(201)
+    expect(state.created).toMatchObject({
+      category: 'document',
+      fileName: 'alignment-report.pdf',
+      fileType: 'application/pdf',
+      serviceRecordId: 'rec-1',
+    })
+    // Stored under a name of the server's own making, never the phone's.
+    expect(state.created?.fileUrl).toMatch(
+      /^\/api\/protected\/files\/org-1\/services\/[0-9a-f-]{36}\.pdf$/
+    )
+  })
+
+  it('refuses a file that only says it is a PDF', async () => {
+    const response = await upload(
+      '<html><script>alert(1)</script></html>',
+      'report.pdf',
+      'application/pdf'
+    )
+
+    expect(response.status).toBe(400)
+    expect(await response.text()).toContain('not a PDF')
+    expect(state.created).toBeNull()
+  })
+
+  it('still refuses the formats a phone in a bay has no use for', async () => {
+    const response = await upload('a,b\n1,2\n', 'parts.csv', 'text/csv')
+
+    expect(response.status).toBe(400)
+    expect(state.created).toBeNull()
+  })
+
+  it('stops at the number of documents the plan allows on one job', async () => {
+    state.documentsOnJob = 5
+
+    const response = await upload(PDF, 'sixth.pdf', 'application/pdf')
+
+    expect(response.status).toBe(409)
+    expect(await response.text()).toContain('maximum of 5 documents')
+    expect(state.created).toBeNull()
+  })
+
+  it('tells the app it can, so an older server is never offered a document', () => {
+    expect(TECH_API_FEATURES).toContain('job-documents')
+  })
+})

+ 38 - 8
src/app/api/v1/tech/jobs/[id]/attachments/route.ts

@@ -13,7 +13,9 @@ import { isDeclaredVideo, sniffDeclaredVideo, type VideoContainer } from '@/lib/
 import { jobScopeFor } from '@/features/workboard/Lib/jobTeam'
 
 /**
- * Attaches a photo or video shot in the bay to a job.
+ * Attaches a photo or video shot in the bay to a job, or a PDF the
+ * technician has on the phone: a supplier's delivery note, an alignment
+ * printout, a calibration report.
  *
  * One request, not the web's two. The browser uploads a file, gets a URL back
  * and then posts that URL as an attachment, which is fine on a desk and wrong
@@ -23,10 +25,11 @@ import { jobScopeFor } from '@/features/workboard/Lib/jobTeam'
  */
 
 /**
- * Deliberately narrower than the web's list. This endpoint exists for a camera,
- * so it accepts what a camera produces. PDFs, spreadsheets and text files have
- * no business arriving from a phone in a bay, and every format accepted is a
- * parser somewhere that has to be right.
+ * Deliberately narrower than the web's list. This endpoint exists for a phone
+ * in a bay, so it accepts what a camera produces and the one document format
+ * a technician is actually handed: a PDF. Spreadsheets and text files stay
+ * out, because every format accepted is a parser somewhere that has to be
+ * right.
  */
 const ALLOWED = new Map<string, string>([
   ['image/jpeg', 'jpg'],
@@ -35,8 +38,21 @@ const ALLOWED = new Map<string, string>([
   ['image/heic', 'heic'],
   ['video/mp4', 'mp4'],
   ['video/quicktime', 'mov'],
+  ['application/pdf', 'pdf'],
 ])
 
+const PDF_TYPE = 'application/pdf'
+
+/**
+ * A PDF opens with its signature. The specification lets a little junk come
+ * first and readers accept it within the first kilobyte, so that is where it
+ * is looked for. A file that only claims the type is not kept as one.
+ */
+function isPdf(bytes: Uint8Array): boolean {
+  const head = Buffer.from(bytes.subarray(0, 1024)).toString('latin1')
+  return head.includes('%PDF-')
+}
+
 /**
  * Smaller than the web's 500MB. A phone on shop wifi uploading half a gigabyte
  * is a request that will not finish, and a limit that cannot be met in the
@@ -52,6 +68,9 @@ const MAX_PHOTO_BYTES = 60 * 1024 * 1024
  */
 const MAX_VIDEO_BYTES = 250 * 1024 * 1024
 
+/** A scanned report of many pages fits well inside this; nothing larger is a report. */
+const MAX_DOCUMENT_BYTES = 25 * 1024 * 1024
+
 // The multipart framing around the file adds a little to the body. The
 // margin keeps a file just under the cap from being refused for it.
 const MAX_BODY = MAX_VIDEO_BYTES + 1024 * 1024
@@ -98,7 +117,11 @@ export async function POST(request: Request, { params }: { params: Promise<{ id:
       if (file.size === 0) {
         return apiError(400, 'invalid_request', 'That file is empty.')
       }
-      const maxBytes = isDeclaredVideo(file.type) ? MAX_VIDEO_BYTES : MAX_PHOTO_BYTES
+      const maxBytes = isDeclaredVideo(file.type)
+        ? MAX_VIDEO_BYTES
+        : file.type === PDF_TYPE
+          ? MAX_DOCUMENT_BYTES
+          : MAX_PHOTO_BYTES
       if (file.size > maxBytes) {
         return apiError(
           400,
@@ -119,7 +142,12 @@ export async function POST(request: Request, { params }: { params: Promise<{ id:
         }
       }
 
-      const category = container ? 'video' : 'image'
+      const document = file.type === PDF_TYPE
+      if (document && !isPdf(bytes)) {
+        return apiError(400, 'invalid_request', 'That file is not a PDF we can read.')
+      }
+
+      const category = container ? 'video' : document ? 'document' : 'image'
       const description = (form.get('description') as string | null)?.slice(0, 500) || undefined
 
       const limitKey = CATEGORY_LIMIT[category]
@@ -133,7 +161,9 @@ export async function POST(request: Request, { params }: { params: Promise<{ id:
           return apiError(
             409,
             'conflict',
-            `This job already has the maximum of ${max} ${category === 'video' ? 'videos' : 'photos'}.`
+            `This job already has the maximum of ${max} ${
+              category === 'video' ? 'videos' : category === 'document' ? 'documents' : 'photos'
+            }.`
           )
         }
       }

+ 3 - 1
src/lib/tech-api-features.ts

@@ -16,5 +16,7 @@
  * - `checkin`: a job's check-in under `/jobs/:id/checkin`: mileage, drop-off
  *   photos by position and the condition map with its marks. A booking is
  *   on the job list from its day on.
+ * - `job-documents`: a PDF of up to 25 MB can be attached to a job, and is
+ *   filed with the job's documents.
  */
-export const TECH_API_FEATURES = ['job-video', 'checkin'] as const
+export const TECH_API_FEATURES = ['job-video', 'checkin', 'job-documents'] as const