reference-po.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import { expect, type Page, test } from '@playwright/test'
  2. import { Client } from 'pg'
  3. import {
  4. type InvoiceDesignState,
  5. invoiceDesignState,
  6. ownerOrganizationId,
  7. restoreInvoiceDesignState,
  8. } from '../../support/db'
  9. import { settle } from '../../support/hydration'
  10. import { type PdfContent, pdfContent } from '../../support/pdf'
  11. import { openCustomFieldsTab, setReadyMadeField } from '../../support/settings'
  12. import {
  13. addLabor,
  14. newWorkOrder,
  15. saveWorkOrder,
  16. seededVehicleUrl,
  17. shareLink,
  18. } from '../../support/work-order'
  19. /**
  20. * The customer's reference / PO, from the switch to the paper.
  21. *
  22. * An opt-in field, so the first thing held here is the opt-out: a workshop
  23. * that has not switched it on has no box for it, and a design made before it
  24. * existed prints the same invoice with a reference on the job as without.
  25. * Then the flow a fleet workshop runs every day: the customer is marked "PO
  26. * required", the invoice is held while the job has no reference and says
  27. * why, the reference is typed in, the invoice goes out, and the number is on
  28. * the sheet once the design asks for it. Last, the part that only shows with
  29. * every piece assembled: a reference typed after the invoice was issued is on
  30. * the issued invoice at once.
  31. */
  32. test.describe.configure({ mode: 'serial' })
  33. const stamp = Date.now()
  34. const REFERENCE = `PO-${stamp}`
  35. const LATE_REFERENCE = `PO-LATE-${stamp}`
  36. const DESIGN_NAME = `E2E reference design ${stamp}`
  37. const SETTING = 'documents.customerReferenceEnabled'
  38. const HELD = /needs a reference or PO number on their invoices/
  39. let jobUrl = ''
  40. let customerId = ''
  41. let restoreTo: InvoiceDesignState
  42. let withoutField: PdfContent
  43. async function withDb<T>(fn: (db: Client) => Promise<T>): Promise<T> {
  44. const url = process.env.E2E_DATABASE_URL
  45. if (!url) throw new Error('E2E_DATABASE_URL is not set. See e2e/README.md.')
  46. const db = new Client({ connectionString: url })
  47. await db.connect()
  48. try {
  49. return await fn(db)
  50. } finally {
  51. await db.end()
  52. }
  53. }
  54. /** The customer the job's vehicle belongs to, whose invoices will need a PO. */
  55. async function customerOfJob(jobId: string): Promise<string> {
  56. return withDb(async (db) => {
  57. const result = await db.query<{ customerId: string }>(
  58. `select v."customerId" from service_records s join vehicles v on v.id = s."vehicleId" where s.id = $1`,
  59. [jobId]
  60. )
  61. const id = result.rows[0]?.customerId
  62. if (!id) throw new Error('the seeded vehicle has no customer')
  63. return id
  64. })
  65. }
  66. /** Leaves the workshop as the rest of the suite expects it: field off, nobody needing a PO. */
  67. async function switchEverythingOff(): Promise<void> {
  68. const organizationId = await ownerOrganizationId()
  69. await withDb(async (db) => {
  70. await db.query(`delete from app_settings where "organizationId" = $1 and key = $2`, [
  71. organizationId,
  72. SETTING,
  73. ])
  74. await db.query(`update customers set "poRequired" = false where "organizationId" = $1`, [
  75. organizationId,
  76. ])
  77. })
  78. }
  79. function referenceField(page: Page) {
  80. return page.locator('#customerReference')
  81. }
  82. async function invoicePdf(page: Page): Promise<PdfContent> {
  83. const id = jobUrl.split('/').pop()
  84. const response = await page.request.get(`/api/protected/services/${id}/pdf`, { timeout: 60_000 })
  85. expect(response.status()).toBe(200)
  86. return pdfContent(await response.body())
  87. }
  88. /** Types the reference and waits until the row has it: the box saves on its own. */
  89. async function typeReference(page: Page, value: string): Promise<void> {
  90. await referenceField(page).fill(value)
  91. await referenceField(page).blur()
  92. await expect(async () => {
  93. await page.reload()
  94. await expect(referenceField(page)).toHaveValue(value, { timeout: 5_000 })
  95. }).toPass({ timeout: 30_000 })
  96. }
  97. async function openDesigner(page: Page) {
  98. await page.goto('/invoice-designer')
  99. const carryOn = page.getByRole('button', { name: /continue with my current layout/i })
  100. const gallery = await carryOn
  101. .waitFor({ state: 'visible', timeout: 10_000 })
  102. .then(() => true)
  103. .catch(() => false)
  104. if (gallery) await carryOn.click()
  105. await expect(page.getByTestId('rail-header')).toBeVisible({ timeout: 30_000 })
  106. await settle(page)
  107. }
  108. async function selectCustomerBlock(page: Page) {
  109. await expect(async () => {
  110. await page.getByTestId('rail-customer').click()
  111. await expect(page.getByText('Section settings', { exact: true })).toBeVisible({
  112. timeout: 2_000,
  113. })
  114. }).toPass({ timeout: 30_000 })
  115. }
  116. async function saveDesign(page: Page) {
  117. const button = page.getByRole('button', { name: /save design/i }).first()
  118. await expect(button, 'the designer has something to save').toBeVisible({ timeout: 30_000 })
  119. const dialog = page.getByRole('dialog').filter({ hasText: 'Save this design' })
  120. const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Saved' }).first()
  121. await expect(async () => {
  122. await button.click()
  123. await expect(dialog.or(toast).first()).toBeVisible({ timeout: 3_000 })
  124. }).toPass({ timeout: 30_000 })
  125. if (await dialog.isVisible().catch(() => false)) {
  126. await dialog.getByPlaceholder('Design name').fill(DESIGN_NAME)
  127. await dialog.getByRole('button', { name: /^(save|update) design$/i }).click()
  128. }
  129. await expect(toast).toBeVisible({ timeout: 30_000 })
  130. }
  131. test.beforeAll(async ({ browser }) => {
  132. restoreTo = await invoiceDesignState()
  133. await switchEverythingOff()
  134. const page = await browser.newPage({ storageState: 'e2e/.auth/owner.json' })
  135. const vehicleUrl = await seededVehicleUrl(page)
  136. jobUrl = await newWorkOrder(page, vehicleUrl, `E2E reference ${stamp}`)
  137. await addLabor(page, { description: 'Inspect and report', hours: 1, rate: 100 })
  138. await saveWorkOrder(page)
  139. customerId = await customerOfJob(jobUrl.split('/').pop() ?? '')
  140. await page.close()
  141. })
  142. test.afterAll(async () => {
  143. await switchEverythingOff()
  144. await restoreInvoiceDesignState(restoreTo)
  145. })
  146. test.describe('the customer reference / PO', () => {
  147. test('a workshop that has not switched it on sees no trace of it', async ({ page }) => {
  148. await page.goto(jobUrl)
  149. await expect(page.getByTestId('job-facts')).toBeVisible()
  150. await expect(referenceField(page)).toHaveCount(0)
  151. await expect(page.getByText('Reference / PO')).toHaveCount(0)
  152. await page.goto(`/customers/${customerId}`)
  153. await page.getByRole('button', { name: 'Edit Customer' }).first().click()
  154. const dialog = page.getByRole('dialog', { name: 'Edit Customer' })
  155. await expect(dialog).toBeVisible()
  156. await expect(dialog.getByText('PO required')).toHaveCount(0)
  157. })
  158. test('is switched on in Settings, Invoice & Quotes, Custom Fields', async ({ page }) => {
  159. await openCustomFieldsTab(page)
  160. await expect(page.locator('#customerReferenceEnabled')).toHaveAttribute('aria-checked', 'false')
  161. await setReadyMadeField(page, 'customerReferenceEnabled', true)
  162. await page.reload()
  163. await expect(page.locator('#customerReferenceEnabled')).toHaveAttribute('aria-checked', 'true')
  164. })
  165. test('the work order gets the field, and asks for nothing yet', async ({ page }) => {
  166. await page.goto(jobUrl)
  167. await expect(referenceField(page)).toBeVisible()
  168. await expect(referenceField(page)).toHaveValue('')
  169. // Nobody has said this customer needs one.
  170. await expect(page.getByTestId('customer-reference-required')).toHaveCount(0)
  171. })
  172. test('a customer is marked as PO required', async ({ page }) => {
  173. await page.goto(`/customers/${customerId}`)
  174. await settle(page)
  175. await page.getByRole('button', { name: 'Edit Customer' }).first().click()
  176. const dialog = page.getByRole('dialog', { name: 'Edit Customer' })
  177. const toggle = dialog.locator('#poRequired')
  178. await expect(toggle).toHaveAttribute('aria-checked', 'false')
  179. await toggle.click()
  180. await expect(toggle).toHaveAttribute('aria-checked', 'true')
  181. await dialog.getByRole('button', { name: 'Save Changes' }).click()
  182. await expect(page.getByTestId('po-required-badge')).toBeVisible()
  183. // Saved, not just shown: the form opens with it on.
  184. await page.reload()
  185. await page.getByRole('button', { name: 'Edit Customer' }).first().click()
  186. await expect(
  187. page.getByRole('dialog', { name: 'Edit Customer' }).locator('#poRequired')
  188. ).toHaveAttribute('aria-checked', 'true')
  189. })
  190. test('the invoice is held, with the reason, while the job has no reference', async ({ page }) => {
  191. await page.goto(jobUrl)
  192. await settle(page)
  193. await expect(page.getByTestId('customer-reference-required')).toBeVisible()
  194. // Sharing is how an invoice goes out: refused, in words, and no dialog opens.
  195. await page.getByRole('button', { name: 'Share', exact: true }).click()
  196. await expect(page.locator('[data-sonner-toast]').filter({ hasText: HELD })).toBeVisible()
  197. await expect(page.getByRole('dialog', { name: 'Share Invoice' })).toHaveCount(0)
  198. // Nothing was issued and no link was made behind the refusal.
  199. const { issued, shared } = await withDb(async (db) => {
  200. const result = await db.query<{ issued: boolean; shared: boolean }>(
  201. `select "issuedAt" is not null as issued, "publicToken" is not null as shared from service_records where id = $1`,
  202. [jobUrl.split('/').pop()]
  203. )
  204. return result.rows[0]
  205. })
  206. expect(issued).toBe(false)
  207. expect(shared).toBe(false)
  208. })
  209. test('working on the job is never held: it still saves without a reference', async ({ page }) => {
  210. await page.goto(jobUrl)
  211. await addLabor(page, { description: 'Second look', hours: 0.5, rate: 100 })
  212. await saveWorkOrder(page)
  213. })
  214. test('typing the reference saves it on its own and lifts the hold', async ({ page }) => {
  215. await page.goto(jobUrl)
  216. await settle(page)
  217. await typeReference(page, REFERENCE)
  218. await expect(page.getByTestId('customer-reference-required')).toHaveCount(0)
  219. // The box is not part of the work order's own save.
  220. await expect(page.getByText('Unsaved changes')).toHaveCount(0)
  221. })
  222. test('the work order list finds the job by its reference', async ({ page }) => {
  223. await page.goto(`/work-orders?search=${encodeURIComponent(REFERENCE)}`)
  224. await expect(page.getByTestId('row-reference').filter({ visible: true }).first()).toHaveText(
  225. REFERENCE
  226. )
  227. })
  228. test('the invoice prints the reference without a visit to the designer', async ({ page }) => {
  229. // Switching the field on is asking for it on the paper: the line is on in
  230. // every design until one switches it off.
  231. await page.goto(jobUrl)
  232. const unasked = await invoicePdf(page)
  233. expect(unasked.flat).toContain(`Your reference / PO: ${REFERENCE}`)
  234. })
  235. test('a design saved with the field off prints no reference', async ({ page }) => {
  236. // Saved first, so the sheet measured here and the one after the switch
  237. // come from the same designer layout. A workshop that never saved a design
  238. // prints the classic letterhead, and its first save changes the header on
  239. // its own ("Due:" becomes a "Due Date" cell): that is the designer, not
  240. // this field, and it must not be what the comparison below measures.
  241. // The field arrives switched on; switching it off is the change saved.
  242. await openDesigner(page)
  243. await selectCustomerBlock(page)
  244. const toggle = page.getByTestId('field-customer_reference')
  245. await expect(toggle).toHaveAttribute('aria-checked', 'true')
  246. await expect(async () => {
  247. await toggle.click()
  248. await expect(toggle).toHaveAttribute('aria-checked', 'false', { timeout: 2_000 })
  249. }).toPass({ timeout: 30_000 })
  250. await saveDesign(page)
  251. await page.goto(jobUrl)
  252. withoutField = await invoicePdf(page)
  253. expect(withoutField.pages).toBeGreaterThan(0)
  254. expect(withoutField.flat, 'the reference is on the job, not on the sheet').not.toContain(
  255. REFERENCE
  256. )
  257. expect(withoutField.flat).not.toContain('Your reference')
  258. })
  259. test('switched back on in the customer block, the sample sheet shows it', async ({ page }) => {
  260. await openDesigner(page)
  261. await selectCustomerBlock(page)
  262. const toggle = page.getByTestId('field-customer_reference')
  263. await expect(toggle).toHaveAttribute('aria-checked', 'false')
  264. await expect(async () => {
  265. await toggle.click()
  266. await expect(toggle).toHaveAttribute('aria-checked', 'true', { timeout: 2_000 })
  267. }).toPass({ timeout: 30_000 })
  268. // The sample sheet shows what it will print.
  269. await expect(
  270. page
  271. .getByText(/Your reference \/ PO: PO-48213/)
  272. .filter({ visible: true })
  273. .first()
  274. ).toBeVisible()
  275. await saveDesign(page)
  276. })
  277. test('the invoice then prints it, and nothing else on the sheet moves', async ({ page }) => {
  278. await page.goto(jobUrl)
  279. const withField = await invoicePdf(page)
  280. expect(withField.flat).toContain(`Your reference / PO: ${REFERENCE}`)
  281. // The same sheet with one line more: every word it said before is still there.
  282. const added = withField.flat.replace(`Your reference / PO: ${REFERENCE}`, '')
  283. for (const word of withoutField.flat.split(' ').filter((w) => w.length > 3)) {
  284. expect(added, `the sheet still says "${word}"`).toContain(word)
  285. }
  286. expect(withField.pages).toBe(withoutField.pages)
  287. })
  288. test('with its reference the invoice goes out, and the customer reads it on the link', async ({
  289. page,
  290. }) => {
  291. await page.goto(jobUrl)
  292. await settle(page)
  293. const url = await shareLink(page)
  294. const [, orgId, token] = new URL(url).pathname.match(/\/share\/invoice\/([^/]+)\/([^/]+)/) ?? []
  295. expect(token, 'the share link carries a token').toBeTruthy()
  296. const response = await page.request.get(`/api/public/share/invoice/${orgId}/${token}/pdf`)
  297. expect(response.status()).toBe(200)
  298. const shared = await pdfContent(await response.body())
  299. expect(shared.flat).toContain(`Your reference / PO: ${REFERENCE}`)
  300. })
  301. test('a reference typed after the invoice was issued is on the issued invoice at once', async ({
  302. page,
  303. }) => {
  304. await page.goto(jobUrl)
  305. await settle(page)
  306. // Issued by the share above; the box is still there to type in.
  307. await expect(referenceField(page)).toBeEnabled()
  308. await typeReference(page, LATE_REFERENCE)
  309. const reissued = await invoicePdf(page)
  310. expect(reissued.flat).toContain(`Your reference / PO: ${LATE_REFERENCE}`)
  311. expect(reissued.flat).not.toContain(REFERENCE)
  312. })
  313. test('switched off again, it is hidden everywhere and kept', async ({ page }) => {
  314. await openCustomFieldsTab(page)
  315. await setReadyMadeField(page, 'customerReferenceEnabled', false)
  316. await page.goto(jobUrl)
  317. await expect(page.getByTestId('job-facts')).toBeVisible()
  318. await expect(referenceField(page)).toHaveCount(0)
  319. // The design still has the field switched on; the value never reaches it.
  320. const hidden = await invoicePdf(page)
  321. expect(hidden.flat).not.toContain(LATE_REFERENCE)
  322. expect(hidden.flat).not.toContain('Your reference')
  323. const kept = await withDb(async (db) => {
  324. const result = await db.query<{ customerReference: string | null }>(
  325. `select "customerReference" from service_records where id = $1`,
  326. [jobUrl.split('/').pop()]
  327. )
  328. return result.rows[0]?.customerReference
  329. })
  330. expect(kept).toBe(LATE_REFERENCE)
  331. })
  332. })