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

Show a shared quote's logo to customers who are not signed in (#649)

The quote share page rewrote only the older stored address form, so a logo uploaded today reached the customer as the signed-in address and did not load. Both forms now go through one helper.
Bernt Christian Egeland 1 неделя назад
Родитель
Сommit
52203a4efe

+ 75 - 0
e2e/specs/quotes/shared-logo.spec.ts

@@ -0,0 +1,75 @@
+import { randomUUID } from 'node:crypto'
+import { mkdir, rm, writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { expect, test } from '@playwright/test'
+import { forgetWorkshopSetting, ownerOrganizationId, setWorkshopSetting } from '../../support/db'
+import { sharesDiskWithServer, uploadPath } from '../../support/files'
+import { TINY_PNG } from '../../support/pdf'
+import { addQuotePart, newQuote, quoteShareLink, saveQuote } from '../../support/quote'
+
+/**
+ * The workshop's letterhead on a quote a customer opens from a link.
+ *
+ * A logo uploaded today is stored as `/api/protected/files/...`, which needs
+ * a signed-in session. The customer has none, so the shared quote has to hand
+ * the browser the link's own public address for it, or the letterhead shows
+ * as a broken image.
+ */
+
+test.describe.configure({ mode: 'serial' })
+
+const stamp = Date.now()
+let organizationId = ''
+let logoFile = ''
+let logoName = ''
+let previousLogo: string | null = null
+
+test.beforeAll(async () => {
+  test.skip(!sharesDiskWithServer(), 'the suite does not share a disk with the app server')
+  organizationId = await ownerOrganizationId()
+  // Planted rather than uploaded: the logo upload route replaces the
+  // workshop's company logo, which every other sheet in the suite prints.
+  logoName = `${randomUUID()}.png`
+  logoFile = uploadPath(organizationId, 'logos', logoName)
+  await mkdir(path.dirname(logoFile), { recursive: true })
+  await writeFile(logoFile, TINY_PNG)
+  previousLogo = await setWorkshopSetting(
+    organizationId,
+    'quote.logo',
+    `/api/protected/files/${organizationId}/logos/${logoName}`
+  )
+})
+
+test.afterAll(async () => {
+  if (!organizationId) return
+  if (previousLogo === null) await forgetWorkshopSetting(organizationId, 'quote.logo')
+  else await setWorkshopSetting(organizationId, 'quote.logo', previousLogo)
+  if (logoFile) await rm(logoFile, { force: true })
+})
+
+test('a shared quote shows the logo uploaded for quotes to a customer with no session', async ({
+  page,
+  browser,
+}) => {
+  await newQuote(page, `E2E quote logo ${stamp}`)
+  await addQuotePart(page, { name: `E2E wiper ${stamp}`, quantity: 1, unitPrice: 100 })
+  await saveQuote(page)
+  const shareUrl = await quoteShareLink(page)
+
+  const context = await browser.newContext({ storageState: { cookies: [], origins: [] } })
+  const customer = await context.newPage()
+  await customer.goto(shareUrl)
+
+  const logo = customer.locator(`img[src*="${logoName}"]`).first()
+  await expect(logo).toBeAttached()
+  const src = (await logo.getAttribute('src')) ?? ''
+  expect(src, 'the logo is addressed through the link, not the signed-in route').toMatch(
+    /^\/api\/public\/files\/[^/]+\/logos\//
+  )
+  await expect
+    .poll(() => logo.evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth > 0))
+    .toBe(true)
+  const response = await context.request.get(src)
+  expect(response.status()).toBe(200)
+  await context.close()
+})

+ 31 - 0
src/__tests__/lib/share-file-url.test.ts

@@ -0,0 +1,31 @@
+/**
+ * A share link's page hands the customer addresses the link's token opens.
+ * A logo uploaded today is stored under the signed-in route, and a customer
+ * with no session could not load it.
+ */
+import { describe, expect, it } from 'vitest'
+import { shareFileUrl } from '@/lib/share-file-url'
+
+describe('shareFileUrl', () => {
+  it('rewrites an upload stored today to the link’s public address', () => {
+    expect(shareFileUrl('/api/protected/files/org_1/logos/mark.png', 'tok')).toBe(
+      '/api/public/files/tok/logos/mark.png'
+    )
+  })
+
+  it('rewrites an upload stored in the older form too', () => {
+    expect(shareFileUrl('/api/files/org_1/quotes/photo.jpg', 'tok')).toBe(
+      '/api/public/files/tok/quotes/photo.jpg'
+    )
+  })
+
+  it('leaves anything that is not a stored upload as it is', () => {
+    for (const url of [
+      'https://example.com/logo.png',
+      'data:image/png;base64,AAAA',
+      '/uploads/logos/mark.png',
+    ]) {
+      expect(shareFileUrl(url, 'tok')).toBe(url)
+    }
+  })
+})

+ 7 - 10
src/app/(public)/share/quote/[orgId]/[token]/page.tsx

@@ -1,5 +1,6 @@
 import { getTranslations } from 'next-intl/server'
 import { resolveCurrencyCode, resolveCurrencyFormat } from '@/lib/currencies'
+import { shareFileUrl } from '@/lib/share-file-url'
 import { documentLogoPath } from '@/features/invoice-designer/Lib/documentLogo'
 import { db } from '@/lib/db'
 import { notFound } from 'next/navigation'
@@ -162,18 +163,14 @@ export default async function PublicQuotePage({
     settingsMap['workshop.currencyFormat']
   )
 
-  // Rewrite logo URL for public access
+  // The logo and the attachments, at addresses this link's token opens. A
+  // logo uploaded today is stored under the signed-in route, which a customer
+  // with no session cannot load.
+  const toPublicUrl = (url: string) => shareFileUrl(url, token)
   const rawLogoUrl = documentLogoPath(settingsMap, 'quote')
-  let logoUrl = ''
-  if (rawLogoUrl) {
-    const match = rawLogoUrl.match(/^\/api\/files\/[^/]+\/(.+)$/)
-    if (match) logoUrl = `/api/public/files/${token}/${match[1]}`
-    else logoUrl = rawLogoUrl
-  }
+  const logoUrl = rawLogoUrl ? toPublicUrl(rawLogoUrl) : ''
 
-  // Attachments, named field by field, with addresses this link's token opens.
-  const toPublicUrl = (url: string) =>
-    url.replace(/^\/api\/protected\/files\/[^/]+\//, `/api/public/files/${token}/`)
+  // Attachments, named field by field.
   const attachmentsOf = (category: string) =>
     quote.attachments
       .filter((file) => file.category === category)

+ 14 - 0
src/lib/share-file-url.ts

@@ -0,0 +1,14 @@
+/**
+ * The address a share link's page gives the browser for one of the
+ * workshop's stored files.
+ *
+ * Uploads are stored under the signed-in file route, in either of the forms
+ * it has had (`/api/protected/files/<org>/...` today, `/api/files/<org>/...`
+ * before). The customer opening a link has no session, so each is rewritten
+ * to the public route the link's token opens. Anything else (a picture on
+ * another site, a data URI, an older `/uploads/...` path) is left as it is.
+ */
+export function shareFileUrl(url: string, token: string): string {
+  const match = url.match(/^\/api\/(?:protected\/)?files\/[^/]+\/(.+)$/)
+  return match ? `/api/public/files/${token}/${match[1]}` : url
+}