db.ts 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392
  1. import { randomBytes, scryptSync } from 'node:crypto'
  2. import { Client } from 'pg'
  3. /**
  4. * A look into the database the suite seeded, for the few things a browser
  5. * cannot see. Mail is not one of them any more: what the app posts is read
  6. * back from the sink in `support/mail.ts`, which is what a person would see.
  7. * What is left is the secret behind a two-factor QR code.
  8. *
  9. * Plain pg rather than the app's Prisma client: the tests run in Playwright's
  10. * process, which has no adapter wired up, and one query does not need one.
  11. */
  12. async function withDb<T>(fn: (db: Client) => Promise<T>): Promise<T> {
  13. const url = process.env.E2E_DATABASE_URL
  14. if (!url) throw new Error('E2E_DATABASE_URL is not set. See e2e/README.md.')
  15. const db = new Client({ connectionString: url })
  16. await db.connect()
  17. try {
  18. return await fn(db)
  19. } finally {
  20. await db.end()
  21. }
  22. }
  23. /** The workshop the seeded owner belongs to. */
  24. export async function ownerOrganizationId(email = 'demo@torqvoice.com'): Promise<string> {
  25. return withDb(async (db) => {
  26. const result = await db.query<{ organizationId: string }>(
  27. `select m."organizationId"
  28. from organization_members m
  29. join users u on u.id = m."userId"
  30. where u.email = $1
  31. limit 1`,
  32. [email]
  33. )
  34. const id = result.rows[0]?.organizationId
  35. if (!id) throw new Error(`no organization for ${email}`)
  36. return id
  37. })
  38. }
  39. /** The workshop a signed-up account ended up owning, by the address it used. */
  40. export async function organizationIdFor(email: string): Promise<string> {
  41. return ownerOrganizationId(email)
  42. }
  43. /**
  44. * Everything a save from the invoice designer writes, as it stands now.
  45. *
  46. * The designer does not edit one record: it writes the workshop's live
  47. * layout, its palette and which design is in use, and that changes every
  48. * invoice printed afterwards — including the ones the pricing and parity
  49. * specs pin to the cent. Saving also graduates an organization from the
  50. * classic pre-designer sheet to the designer's, which is not something a
  51. * test may leave behind it. So the state is taken before and put back after.
  52. */
  53. export interface InvoiceDesignState {
  54. organizationId: string
  55. settings: { key: string; value: string }[]
  56. designIds: string[]
  57. }
  58. export async function invoiceDesignState(): Promise<InvoiceDesignState> {
  59. const organizationId = await ownerOrganizationId()
  60. return withDb(async (db) => {
  61. const settings = await db.query<{ key: string; value: string }>(
  62. `select key, value from app_settings where "organizationId" = $1 and key like 'invoice.%'`,
  63. [organizationId]
  64. )
  65. const designs = await db.query<{ id: string }>(
  66. `select id from document_designs where "organizationId" = $1`,
  67. [organizationId]
  68. )
  69. return {
  70. organizationId,
  71. settings: settings.rows,
  72. designIds: designs.rows.map((row) => row.id),
  73. }
  74. })
  75. }
  76. /** Puts the workshop back exactly as `invoiceDesignState` found it. */
  77. export async function restoreInvoiceDesignState(state: InvoiceDesignState): Promise<void> {
  78. const keys = state.settings.map((row) => row.key)
  79. await withDb(async (db) => {
  80. // Anything the designer added goes; anything it changed goes back.
  81. await db.query(
  82. `delete from app_settings
  83. where "organizationId" = $1 and key like 'invoice.%' and not (key = any($2::text[]))`,
  84. [state.organizationId, keys]
  85. )
  86. for (const row of state.settings) {
  87. await db.query(
  88. `update app_settings set value = $3 where "organizationId" = $1 and key = $2`,
  89. [state.organizationId, row.key, row.value]
  90. )
  91. }
  92. await db.query(
  93. `delete from document_designs
  94. where "organizationId" = $1 and not (id = any($2::text[]))`,
  95. [state.organizationId, state.designIds]
  96. )
  97. })
  98. }
  99. /**
  100. * Every setting Settings > Tax saves (`setTax` in support/settings.ts goes
  101. * through that page), by its key in SETTING_KEYS: the tax keys, the default
  102. * rate, which is not named `workshop.tax…`, and whether invoice lines show
  103. * prices with tax.
  104. */
  105. const TAX_SETTING_KEYS = [
  106. 'workshop.taxEnabled',
  107. 'workshop.defaultTaxRate',
  108. 'workshop.taxInclusive',
  109. 'workshop.taxLabel',
  110. 'workshop.taxMode',
  111. 'workshop.taxComponents',
  112. 'workshop.taxSelective',
  113. 'workshop.taxAppliesToParts',
  114. 'workshop.taxAppliesToLabor',
  115. 'workshop.taxAppliesToShopFee',
  116. 'invoice.lineItemsInclTax',
  117. ] as const
  118. /** The workshop's tax settings, for a spec that sets its own and must hand them back. */
  119. export interface TaxSettingsState {
  120. organizationId: string
  121. /** The rows as they were, whole: a key missing here had no row. */
  122. settings: { id: string; key: string; value: string; userId: string }[]
  123. }
  124. export async function taxSettingsState(): Promise<TaxSettingsState> {
  125. const organizationId = await ownerOrganizationId()
  126. return withDb(async (db) => {
  127. const settings = await db.query<{ id: string; key: string; value: string; userId: string }>(
  128. `select id, key, value, "userId" from app_settings
  129. where "organizationId" = $1 and key = any($2::text[])`,
  130. [organizationId, [...TAX_SETTING_KEYS]]
  131. )
  132. return { organizationId, settings: settings.rows }
  133. })
  134. }
  135. /**
  136. * Puts the tax settings back exactly as `taxSettingsState` found them: a row
  137. * the spec added is deleted, a row it changed gets its value back, and a row
  138. * it deleted is put back as it was, id and owner included.
  139. */
  140. export async function restoreTaxSettings(state: TaxSettingsState): Promise<void> {
  141. const kept = state.settings.map((row) => row.key)
  142. await withDb(async (db) => {
  143. await db.query('begin')
  144. try {
  145. await db.query(
  146. `delete from app_settings
  147. where "organizationId" = $1 and key = any($2::text[]) and not (key = any($3::text[]))`,
  148. [state.organizationId, [...TAX_SETTING_KEYS], kept]
  149. )
  150. for (const row of state.settings) {
  151. await db.query(
  152. `insert into app_settings (id, key, value, "userId", "organizationId")
  153. values ($1, $2, $3, $4, $5)
  154. on conflict ("organizationId", key) do update set value = excluded.value`,
  155. [row.id, row.key, row.value, row.userId, state.organizationId]
  156. )
  157. }
  158. await db.query('commit')
  159. } catch (error) {
  160. await db.query('rollback')
  161. throw error
  162. }
  163. })
  164. }
  165. /**
  166. * Addresses of the seeded workshop's own records, for the tests that check a
  167. * different workshop cannot reach them. Read straight from the database
  168. * because the point is to ask for them as an outsider: going through the app
  169. * to find them first would need the very access under test.
  170. */
  171. export interface TenantFixtures {
  172. organizationId: string
  173. vehicleId: string
  174. serviceRecordId: string
  175. customerId: string
  176. quoteId: string
  177. /**
  178. * Words that belong to this workshop and nobody else. A cross-tenant page
  179. * can answer 200 and render an empty shell, which is a refusal too, so the
  180. * test asks whether any of these reached the screen rather than what the
  181. * status code was.
  182. */
  183. vehiclePlate: string
  184. customerName: string
  185. quoteNumber: string
  186. }
  187. /** A customer and a quote, each taken whole so its id and its words agree. */
  188. async function pairs(
  189. db: Client,
  190. organizationId: string
  191. ): Promise<Pick<TenantFixtures, 'customerId' | 'customerName' | 'quoteId' | 'quoteNumber'>> {
  192. const customer = await db.query<{ id: string; name: string }>(
  193. `select id, name from customers where "organizationId" = $1 order by "createdAt", id limit 1`,
  194. [organizationId]
  195. )
  196. if (!customer.rows[0]) throw new Error('the seeded workshop has no customer')
  197. const quote = await db.query<{ id: string; quoteNumber: string }>(
  198. `select id, "quoteNumber" from quotes
  199. where "organizationId" = $1 and "quoteNumber" is not null and "quoteNumber" <> ''
  200. order by "createdAt", id limit 1`,
  201. [organizationId]
  202. )
  203. if (!quote.rows[0]) throw new Error('the seeded workshop has no numbered quote')
  204. return {
  205. customerId: customer.rows[0].id,
  206. customerName: customer.rows[0].name,
  207. quoteId: quote.rows[0].id,
  208. quoteNumber: quote.rows[0].quoteNumber,
  209. }
  210. }
  211. export async function seededTenantFixtures(): Promise<TenantFixtures> {
  212. const organizationId = await ownerOrganizationId()
  213. return withDb(async (db) => {
  214. /**
  215. * A vehicle and one of its own jobs, from one row.
  216. *
  217. * Two queries answered this before, and on a database the suite had been
  218. * run against they happened to agree. On a fresh seed they did not, and
  219. * the job of one vehicle opened under the id of another draws a page with
  220. * nothing on it.
  221. *
  222. * The organisation comes off the vehicle: `service_records.organizationId`
  223. * is nullable and the seed leaves it null, scoping a job by the vehicle it
  224. * sits on.
  225. */
  226. const pair = await db.query<{
  227. vehicleId: string
  228. serviceRecordId: string
  229. licensePlate: string
  230. }>(
  231. `select v.id as "vehicleId", s.id as "serviceRecordId", v."licensePlate"
  232. from service_records s
  233. join vehicles v on v.id = s."vehicleId"
  234. where coalesce(s."organizationId", v."organizationId") = $1
  235. and v."licensePlate" is not null and v."licensePlate" <> ''
  236. order by s."createdAt"
  237. limit 1`,
  238. [organizationId]
  239. )
  240. const job = pair.rows[0]
  241. if (!job) throw new Error('the seeded workshop has no work order on a plated vehicle')
  242. return {
  243. organizationId,
  244. vehicleId: job.vehicleId,
  245. serviceRecordId: job.serviceRecordId,
  246. vehiclePlate: job.licensePlate,
  247. // Id and words from one row each, for the same reason the vehicle and
  248. // its job come from one row: `limit 1` without an order is not a
  249. // promise, and two queries for "a customer" can answer with two
  250. // different customers. That way round the id opens one record and the
  251. // name that is searched for on it belongs to another.
  252. ...(await pairs(db, organizationId)),
  253. }
  254. })
  255. }
  256. /**
  257. * Any work order belonging to a given workshop, for the tests that point one
  258. * workshop's credential at another's records. A workshop that has just been
  259. * opened has a few of its own from onboarding, which is what makes a
  260. * freshly signed-up account a usable target.
  261. */
  262. export async function foreignServiceRecordId(organizationId: string): Promise<string> {
  263. return withDb(async (db) => {
  264. const result = await db.query<{ id: string }>(
  265. `select s.id
  266. from service_records s
  267. join vehicles v on v.id = s."vehicleId"
  268. where coalesce(s."organizationId", v."organizationId") = $1
  269. order by s."createdAt"
  270. limit 1`,
  271. [organizationId]
  272. )
  273. const id = result.rows[0]?.id
  274. if (!id) throw new Error(`no work order in organization ${organizationId}`)
  275. return id
  276. })
  277. }
  278. /** The stored (encrypted) TOTP secret of a user, or null when 2FA is not set up. */
  279. export async function storedTwoFactorSecret(email: string): Promise<string | null> {
  280. return withDb(async (db) => {
  281. const result = await db.query<{ secret: string }>(
  282. `select tf.secret from two_factor tf join users u on u.id = tf."userId" where u.email = $1`,
  283. [email]
  284. )
  285. return result.rows[0]?.secret ?? null
  286. })
  287. }
  288. export interface StockedPart {
  289. id: string
  290. name: string
  291. /** What the ledger says it has on hand right now. */
  292. quantity: number
  293. }
  294. /**
  295. * A seeded inventory part with enough on hand to be consumed by a job, and
  296. * whose name is distinctive enough to search for in the picker.
  297. *
  298. * The part is chosen rather than created, because what is under test is the
  299. * path a workshop actually walks: pick a stocked part, use it, and watch the
  300. * count fall.
  301. */
  302. export async function stockedPart(organizationId: string, atLeast = 10): Promise<StockedPart> {
  303. return withDb(async (db) => {
  304. const result = await db.query<StockedPart>(
  305. `select id, name, quantity
  306. from inventory_parts
  307. where "organizationId" = $1 and quantity >= $2
  308. order by quantity desc, name
  309. limit 1`,
  310. [organizationId, atLeast]
  311. )
  312. const part = result.rows[0]
  313. if (!part) throw new Error(`no inventory part with ${atLeast} or more on hand`)
  314. return { ...part, quantity: Number(part.quantity) }
  315. })
  316. }
  317. /**
  318. * The highest reading known for a job's vehicle: its own, or any job's on it.
  319. * A reading typed far above this is asked about before it is saved.
  320. */
  321. export async function highestReadingForJob(serviceRecordId: string): Promise<number> {
  322. return withDb(async (db) => {
  323. const result = await db.query<{ highest: number | null }>(
  324. `select greatest(v.mileage, (select max(s.mileage) from service_records s where s."vehicleId" = v.id)) as highest
  325. from service_records r join vehicles v on v.id = r."vehicleId"
  326. where r.id = $1`,
  327. [serviceRecordId]
  328. )
  329. if (!result.rows[0]) throw new Error(`no vehicle for job ${serviceRecordId}`)
  330. return Number(result.rows[0].highest ?? 0)
  331. })
  332. }
  333. /** What one inventory part has on hand. */
  334. export async function partQuantity(partId: string): Promise<number> {
  335. return withDb(async (db) => {
  336. const result = await db.query<{ quantity: number }>(
  337. `select quantity from inventory_parts where id = $1`,
  338. [partId]
  339. )
  340. if (!result.rows[0]) throw new Error(`no inventory part ${partId}`)
  341. return Number(result.rows[0].quantity)
  342. })
  343. }
  344. /** Set a part's quantity outright, to put the seed back as it was found. */
  345. export async function setPartQuantity(partId: string, quantity: number): Promise<void> {
  346. await withDb((db) =>
  347. db.query(`update inventory_parts set quantity = $2 where id = $1`, [partId, quantity])
  348. )
  349. }
  350. export interface StockMovement {
  351. delta: number
  352. quantityAfter: number
  353. reason: string
  354. serviceRecordId: string | null
  355. }
  356. /**
  357. * The ledger for one part, oldest first. Every movement is a row: the count on
  358. * the part is only ever the running total of these, which is why a spec that
  359. * checks stock checks both.
  360. */
  361. export async function stockMovements(
  362. partId: string,
  363. serviceRecordId?: string
  364. ): Promise<StockMovement[]> {
  365. return withDb(async (db) => {
  366. const result = await db.query<StockMovement>(
  367. `select delta, "quantityAfter", reason, "serviceRecordId"
  368. from stock_movements
  369. where "inventoryPartId" = $1
  370. and ($2::text is null or "serviceRecordId" = $2)
  371. order by "createdAt", id`,
  372. [partId, serviceRecordId ?? null]
  373. )
  374. return result.rows.map((row) => ({
  375. ...row,
  376. delta: Number(row.delta),
  377. quantityAfter: Number(row.quantityAfter),
  378. }))
  379. })
  380. }
  381. /** When a reminder is due, as the instant that was stored for it. */
  382. export async function reminderDueDate(title: string): Promise<Date> {
  383. return withDb(async (db) => {
  384. const result = await db.query<{ dueDate: Date }>(
  385. `select "dueDate" from reminders where title = $1 order by "createdAt" desc limit 1`,
  386. [title]
  387. )
  388. const due = result.rows[0]?.dueDate
  389. if (!due) throw new Error(`no reminder titled "${title}" with a due date`)
  390. return new Date(due)
  391. })
  392. }
  393. /** Removes the reminders a spec made, whatever state the page was left in. */
  394. export async function deleteRemindersTitled(title: string): Promise<void> {
  395. await withDb((db) => db.query(`delete from reminders where title = $1`, [title]))
  396. }
  397. /**
  398. * The newest file on a work order, as the app stored its address.
  399. *
  400. * A spec that needs a file belonging to one workshop uploads one and reads it
  401. * back here. Looking for a seeded one instead only worked on a database the
  402. * attachment spec had already run against.
  403. */
  404. export async function latestAttachmentUrl(serviceRecordId: string): Promise<string> {
  405. return withDb(async (db) => {
  406. const result = await db.query<{ fileUrl: string }>(
  407. `select "fileUrl" from service_attachments
  408. where "serviceRecordId" = $1 and "fileUrl" like '/api/protected/files/%'
  409. order by "createdAt" desc
  410. limit 1`,
  411. [serviceRecordId]
  412. )
  413. const url = result.rows[0]?.fileUrl
  414. if (!url) throw new Error(`no stored file on work order ${serviceRecordId}`)
  415. return url
  416. })
  417. }
  418. /**
  419. * Backdates a job's scheduled start, and its invoice date when it has one, to
  420. * an hour ago. A new work order is booked into the shop's next free slot,
  421. * often tomorrow, and the financial reports run up to the present moment and
  422. * count a job on its invoice date, so a job made by a spec is not in this
  423. * year's tax report until both are moved into the past.
  424. */
  425. export async function scheduleServiceRecordInThePast(serviceRecordId: string): Promise<void> {
  426. await withDb((db) =>
  427. db.query(
  428. `update service_records
  429. set "startDateTime" = now() - interval '1 hour',
  430. "invoiceDate" = case when "invoiceDate" is null then null else now() - interval '1 hour' end
  431. where id = $1`,
  432. [serviceRecordId]
  433. )
  434. )
  435. }
  436. /**
  437. * Email templates a spec made, gone again, and every kind back on its
  438. * built-in preset.
  439. *
  440. * The gallery's own delete is what a workshop uses and one test walks it, but
  441. * a file that fails halfway must not leave the workshop sending mail designed
  442. * by a test: the pointer is an `email.template.<kind>` setting, and a
  443. * template row it names is what the resolver prefers over the preset.
  444. */
  445. export async function forgetEmailTemplates(namePrefix: string): Promise<void> {
  446. await withDb(async (db) => {
  447. await db.query(`delete from email_templates where name like $1`, [`${namePrefix}%`])
  448. await db.query(
  449. `delete from app_settings
  450. where key like 'email.template.%'
  451. and value not in (select 'design:' || id from email_templates)`
  452. )
  453. })
  454. }
  455. /** The names of the templates saved for one kind of mail. */
  456. export async function emailTemplateNames(kind: string): Promise<string[]> {
  457. return withDb(async (db) => {
  458. const result = await db.query<{ name: string }>(
  459. `select name from email_templates where kind = $1 order by "createdAt"`,
  460. [kind]
  461. )
  462. return result.rows.map((row) => row.name)
  463. })
  464. }
  465. /**
  466. * Whose car it is, and where to write to them.
  467. *
  468. * The customer of the vehicle a spec is working on, not the first customer in
  469. * the workshop: a message sent from a job goes to the owner of that car, so a
  470. * spec waiting on another customer's mailbox waits forever.
  471. */
  472. export async function customerOfVehicle(
  473. vehicleId: string
  474. ): Promise<{ name: string; email: string }> {
  475. return withDb(async (db) => {
  476. const result = await db.query<{ name: string; email: string }>(
  477. `select c.name, c.email
  478. from vehicles v
  479. join customers c on c.id = v."customerId"
  480. where v.id = $1`,
  481. [vehicleId]
  482. )
  483. const customer = result.rows[0]
  484. if (!customer?.email) throw new Error(`vehicle ${vehicleId} has no customer with an email`)
  485. return customer
  486. })
  487. }
  488. /** Where a workshop's connection to a vendor stands: active, pending, error, or none at all. */
  489. export async function connectionStatus(connectorId: string): Promise<string | null> {
  490. const organizationId = await ownerOrganizationId()
  491. return withDb(async (db) => {
  492. const result = await db.query<{ status: string }>(
  493. `select status from integration_connections
  494. where "organizationId" = $1 and "connectorId" = $2`,
  495. [organizationId, connectorId]
  496. )
  497. return result.rows[0]?.status ?? null
  498. })
  499. }
  500. /**
  501. * Every connection a spec made to a vendor, gone. The payment specs connect
  502. * Stripe and PayPal to the seeded workshop, and a connection left behind puts
  503. * pay buttons on every invoice the rest of the suite shares.
  504. */
  505. export async function forgetConnections(connectorIds: string[]): Promise<void> {
  506. const organizationId = await ownerOrganizationId()
  507. await withDb((db) =>
  508. db.query(
  509. `delete from integration_connections
  510. where "organizationId" = $1 and "connectorId" = any($2::text[])`,
  511. [organizationId, connectorIds]
  512. )
  513. )
  514. }
  515. export interface RecordedPayment {
  516. amount: number
  517. provider: string | null
  518. method: string
  519. externalId: string | null
  520. }
  521. /** The money recorded against one work order, oldest first. */
  522. export async function paymentsFor(serviceRecordId: string): Promise<RecordedPayment[]> {
  523. return withDb(async (db) => {
  524. const result = await db.query<RecordedPayment>(
  525. `select amount, provider, method, "externalId" from payments
  526. where "serviceRecordId" = $1
  527. order by "createdAt", id`,
  528. [serviceRecordId]
  529. )
  530. return result.rows.map((row) => ({ ...row, amount: Number(row.amount) }))
  531. })
  532. }
  533. /**
  534. * Writes a vendor payment row straight into the table, bypassing the app.
  535. *
  536. * For the one question only the database can answer: whether it refuses a
  537. * second row for a payment it already holds. Returns the Postgres error code
  538. * when the insert is refused, or null when it went in.
  539. */
  540. export async function insertVendorPaymentRow(row: {
  541. serviceRecordId: string
  542. provider: string
  543. externalId: string
  544. amount: number
  545. }): Promise<string | null> {
  546. return withDb(async (db) => {
  547. try {
  548. await db.query(
  549. `insert into payments (id, amount, method, provider, "externalId", "serviceRecordId", "updatedAt")
  550. values (md5(random()::text || clock_timestamp()::text), $1, $2, $2, $3, $4, now())`,
  551. [row.amount, row.provider, row.externalId, row.serviceRecordId]
  552. )
  553. return null
  554. } catch (error) {
  555. return (error as { code?: string }).code ?? 'unknown'
  556. }
  557. })
  558. }
  559. /**
  560. * How many rows one invoice holds for one vendor payment.
  561. *
  562. * Counted against the invoice as well as the id: a vendor's id means one
  563. * payment on one invoice, and a count across the whole table also finds any
  564. * other invoice that happens to carry the same id, which is not a duplicate.
  565. */
  566. export async function vendorPaymentRows(
  567. serviceRecordId: string,
  568. externalId: string
  569. ): Promise<number> {
  570. return withDb(async (db) => {
  571. const result = await db.query<{ n: number }>(
  572. `select count(*)::int as n from payments
  573. where "serviceRecordId" = $1 and "externalId" = $2`,
  574. [serviceRecordId, externalId]
  575. )
  576. return result.rows[0]?.n ?? 0
  577. })
  578. }
  579. /** Removes the rows a spec wrote for one vendor payment. */
  580. export async function deleteVendorPaymentRows(externalId: string): Promise<void> {
  581. await withDb((db) => db.query(`delete from payments where "externalId" = $1`, [externalId]))
  582. }
  583. /** The id of the user signed up with an address. */
  584. export async function userIdFor(email: string): Promise<string> {
  585. return withDb(async (db) => {
  586. const result = await db.query<{ id: string }>(
  587. `select id from users where lower(email) = lower($1)`,
  588. [email]
  589. )
  590. const id = result.rows[0]?.id
  591. if (!id) throw new Error(`no user with ${email}`)
  592. return id
  593. })
  594. }
  595. /**
  596. * Writes customers straight into a workshop, as if it had typed them in.
  597. *
  598. * For reaching a plan limit without twenty trips through a form: what is
  599. * under test is the one customer past the limit, and that one goes through
  600. * the app. These are real customers, not sample ones, so they count.
  601. */
  602. export async function insertCustomers(
  603. organizationId: string,
  604. userId: string,
  605. count: number,
  606. prefix: string
  607. ): Promise<void> {
  608. await withDb((db) =>
  609. db.query(
  610. `insert into customers (id, name, "userId", "organizationId", "updatedAt")
  611. select md5(random()::text || clock_timestamp()::text || n), $3 || ' ' || n, $2, $1, now()
  612. from generate_series(1, $4::int) as n`,
  613. [organizationId, userId, prefix, count]
  614. )
  615. )
  616. }
  617. /** Every customer row a workshop holds, sample ones included. */
  618. export async function customerRows(organizationId: string): Promise<number> {
  619. return withDb(async (db) => {
  620. const result = await db.query<{ n: number }>(
  621. `select count(*)::int as n from customers where "organizationId" = $1`,
  622. [organizationId]
  623. )
  624. return result.rows[0]?.n ?? 0
  625. })
  626. }
  627. /** Team invitations a workshop has sent. */
  628. export async function teamInvitations(organizationId: string): Promise<number> {
  629. return withDb(async (db) => {
  630. const result = await db.query<{ n: number }>(
  631. `select count(*)::int as n from team_invitations where "organizationId" = $1`,
  632. [organizationId]
  633. )
  634. return result.rows[0]?.n ?? 0
  635. })
  636. }
  637. /**
  638. * Puts a workshop on an active Pro subscription, as a paid checkout would.
  639. * Returns the plan's id so the spec can take it away again.
  640. */
  641. export async function giveProPlan(
  642. organizationId: string,
  643. stripe?: { subscriptionId: string; customerId: string }
  644. ): Promise<string> {
  645. return withDb(async (db) => {
  646. const plan = await db.query<{ id: string }>(
  647. `insert into subscription_plans (id, name, price, "updatedAt")
  648. values (md5(random()::text || clock_timestamp()::text), 'E2E Pro', 0, now())
  649. returning id`
  650. )
  651. const planId = plan.rows[0].id
  652. // With Stripe ids the row looks like a real purchase, which is what the
  653. // manage-subscription card and its buttons are shown for.
  654. await db.query(
  655. `insert into subscriptions (id, status, "organizationId", "planId", "currentPeriodEnd", "updatedAt",
  656. "stripeSubscriptionId", "stripeCustomerId")
  657. values (md5(random()::text || clock_timestamp()::text), 'active', $1, $2, now() + interval '30 days', now(), $3, $4)`,
  658. [organizationId, planId, stripe?.subscriptionId ?? null, stripe?.customerId ?? null]
  659. )
  660. return planId
  661. })
  662. }
  663. /** Flags a subscription as ending at the period end, as a cancel through torqvoice.com would. */
  664. export async function setCancelAtPeriodEnd(organizationId: string, value: boolean): Promise<void> {
  665. await withDb((db) =>
  666. db.query(`update subscriptions set "cancelAtPeriodEnd" = $2 where "organizationId" = $1`, [
  667. organizationId,
  668. value,
  669. ])
  670. )
  671. }
  672. /** Takes a subscription and its plan away again. */
  673. export async function removePlan(organizationId: string, planId: string): Promise<void> {
  674. await withDb(async (db) => {
  675. await db.query(`delete from subscriptions where "organizationId" = $1`, [organizationId])
  676. await db.query(`delete from subscription_plans where id = $1`, [planId])
  677. })
  678. }
  679. export interface PersonRecord {
  680. /** How many users hold the address: more than one is two people where there should be one. */
  681. users: number
  682. /** How each of them can sign in: `credential` for a password, `google`. */
  683. providers: string[]
  684. emailVerified: boolean
  685. }
  686. /** Who holds an address, and how they can sign in. */
  687. export async function personWithEmail(email: string): Promise<PersonRecord> {
  688. return withDb(async (db) => {
  689. const users = await db.query<{ id: string; emailVerified: boolean }>(
  690. `select id, "emailVerified" from users where lower(email) = lower($1)`,
  691. [email]
  692. )
  693. const providers = await db.query<{ providerId: string }>(
  694. `select a."providerId" from accounts a join users u on u.id = a."userId"
  695. where lower(u.email) = lower($1) order by a."providerId"`,
  696. [email]
  697. )
  698. return {
  699. users: users.rows.length,
  700. providers: providers.rows.map((row) => row.providerId),
  701. emailVerified: users.rows.some((row) => row.emailVerified),
  702. }
  703. })
  704. }
  705. /** Every vehicle row a workshop holds. */
  706. export async function vehicleRows(organizationId: string): Promise<number> {
  707. return withDb(async (db) => {
  708. const result = await db.query<{ n: number }>(
  709. `select count(*)::int as n from vehicles where "organizationId" = $1`,
  710. [organizationId]
  711. )
  712. return result.rows[0]?.n ?? 0
  713. })
  714. }
  715. /** One of a workshop's settings as stored, or null when it was never saved. */
  716. export async function workshopSetting(organizationId: string, key: string): Promise<string | null> {
  717. return withDb(async (db) => {
  718. const result = await db.query<{ value: string }>(
  719. `select value from app_settings where "organizationId" = $1 and key = $2`,
  720. [organizationId, key]
  721. )
  722. return result.rows[0]?.value ?? null
  723. })
  724. }
  725. /**
  726. * A vehicle registry connected to a workshop, active, the way the header's
  727. * plate lookup looks for one. No keys: nothing is looked up, only offered.
  728. */
  729. export async function connectRegistry(
  730. organizationId: string,
  731. userId: string,
  732. connectorId: string
  733. ): Promise<void> {
  734. await withDb((db) =>
  735. db.query(
  736. `insert into integration_connections
  737. (id, "organizationId", "connectorId", status, "createdById", "updatedAt")
  738. values ($1, $2, $3, 'active', $4, now())`,
  739. [`e2e-${connectorId}-${Date.now()}`, organizationId, connectorId, userId]
  740. )
  741. )
  742. }
  743. export async function disconnectRegistry(
  744. organizationId: string,
  745. connectorId: string
  746. ): Promise<void> {
  747. await withDb((db) =>
  748. db.query(
  749. `delete from integration_connections where "organizationId" = $1 and "connectorId" = $2`,
  750. [organizationId, connectorId]
  751. )
  752. )
  753. }
  754. /** The id of a workshop's customer with exactly this name. */
  755. export async function customerIdNamed(organizationId: string, name: string): Promise<string> {
  756. return withDb(async (db) => {
  757. const result = await db.query<{ id: string }>(
  758. `select id from customers where "organizationId" = $1 and name = $2`,
  759. [organizationId, name]
  760. )
  761. const id = result.rows[0]?.id
  762. if (!id) throw new Error(`no customer named ${name}`)
  763. return id
  764. })
  765. }
  766. // ─── The security specs ──────────────────────────────────────────────────────
  767. /**
  768. * A custom role carrying every action on every subject the app knows, and no
  769. * admin standing. It is the sharpest test of "logged in is not allowed": a
  770. * member with this role passes every `requiredPermissions` check there is,
  771. * and the owner-only and admin-only actions have to refuse them anyway.
  772. */
  773. export async function createRoleWithEveryPermission(
  774. organizationId: string,
  775. name: string
  776. ): Promise<string> {
  777. const subjects = [
  778. 'dashboard',
  779. 'vehicles',
  780. 'customers',
  781. 'work_orders',
  782. 'quotes',
  783. 'services',
  784. 'billing',
  785. 'inventory',
  786. 'labor_presets',
  787. 'inspections',
  788. 'tire_hotel',
  789. 'reports',
  790. 'settings',
  791. 'work_board',
  792. 'ai_assistant',
  793. 'time_tracking',
  794. ]
  795. const actions = ['create', 'read', 'update', 'delete', 'manage']
  796. return withDb(async (db) => {
  797. const role = await db.query<{ id: string }>(
  798. `insert into roles (id, name, "isAdmin", "organizationId", "createdAt", "updatedAt")
  799. values (gen_random_uuid()::text, $1, false, $2, now(), now())
  800. returning id`,
  801. [name, organizationId]
  802. )
  803. const roleId = role.rows[0].id
  804. for (const subject of subjects) {
  805. for (const action of actions) {
  806. await db.query(
  807. `insert into permissions (id, action, subject, "roleId")
  808. values (gen_random_uuid()::text, $1, $2, $3)`,
  809. [action, subject, roleId]
  810. )
  811. }
  812. }
  813. return roleId
  814. })
  815. }
  816. /** Gives a member a custom role, and a built-in standing (member or admin) beside it. */
  817. export async function setMembership(
  818. email: string,
  819. organizationId: string,
  820. membership: { roleId: string | null; role: 'member' | 'admin' }
  821. ): Promise<void> {
  822. await withDb((db) =>
  823. db.query(
  824. `update organization_members m
  825. set "roleId" = $3, role = $4
  826. from users u
  827. where u.id = m."userId" and u.email = $1 and m."organizationId" = $2`,
  828. [email, organizationId, membership.roleId, membership.role]
  829. )
  830. )
  831. }
  832. /** The credential in a pending invitation, or null when there is none for the address. */
  833. export async function invitationTokenFor(
  834. email: string,
  835. organizationId: string
  836. ): Promise<string | null> {
  837. return withDb(async (db) => {
  838. const result = await db.query<{ token: string }>(
  839. `select token from team_invitations
  840. where email = $1 and "organizationId" = $2 and status = 'pending'`,
  841. [email, organizationId]
  842. )
  843. return result.rows[0]?.token ?? null
  844. })
  845. }
  846. /** How much of the workshop there is, for a test that must find it all still there. */
  847. export async function contentCounts(organizationId: string): Promise<Record<string, number>> {
  848. return withDb(async (db) => {
  849. const counts: Record<string, number> = {}
  850. for (const table of ['vehicles', 'customers', 'quotes', 'inventory_parts', 'notifications']) {
  851. const result = await db.query<{ n: string }>(
  852. `select count(*)::text as n from ${table} where "organizationId" = $1`,
  853. [organizationId]
  854. )
  855. counts[table] = Number(result.rows[0].n)
  856. }
  857. return counts
  858. })
  859. }
  860. /**
  861. * A file row written straight to the job, bypassing the schema that guards
  862. * the action: what a record carried before the guard existed, or what a
  863. * restore could bring in. The path resolver is the last line for these.
  864. */
  865. export async function insertServiceAttachment(row: {
  866. serviceRecordId: string
  867. fileName: string
  868. fileUrl: string
  869. fileType: string
  870. }): Promise<string> {
  871. return withDb(async (db) => {
  872. const result = await db.query<{ id: string }>(
  873. `insert into service_attachments
  874. (id, "fileName", "fileUrl", "fileType", "fileSize", category, "includeInInvoice", "serviceRecordId")
  875. values (gen_random_uuid()::text, $1, $2, $3, 1, 'image', true, $4)
  876. returning id`,
  877. [row.fileName, row.fileUrl, row.fileType, row.serviceRecordId]
  878. )
  879. return result.rows[0].id
  880. })
  881. }
  882. export async function deleteServiceAttachments(ids: string[]): Promise<void> {
  883. await withDb((db) =>
  884. db.query(`delete from service_attachments where id = any($1::text[])`, [ids])
  885. )
  886. }
  887. /** How many file rows carry a name, on any job. */
  888. export async function serviceAttachmentsNamed(fileName: string): Promise<number> {
  889. return withDb(async (db) => {
  890. const result = await db.query<{ n: string }>(
  891. `select count(*)::text as n from service_attachments where "fileName" = $1`,
  892. [fileName]
  893. )
  894. return Number(result.rows[0].n)
  895. })
  896. }
  897. /** A live connection to a vendor, planted with sealed keys; see `support/webhooks.ts`. */
  898. export async function insertConnection(row: {
  899. organizationId: string
  900. connectorId: string
  901. credentials: string
  902. settings: Record<string, unknown>
  903. createdById: string
  904. }): Promise<string> {
  905. return withDb(async (db) => {
  906. const result = await db.query<{ id: string }>(
  907. `insert into integration_connections
  908. (id, "organizationId", "connectorId", status, credentials, settings, "createdById", "createdAt", "updatedAt")
  909. values (gen_random_uuid()::text, $1, $2, 'active', $3, $4::jsonb, $5, now(), now())
  910. returning id`,
  911. [
  912. row.organizationId,
  913. row.connectorId,
  914. row.credentials,
  915. JSON.stringify(row.settings),
  916. row.createdById,
  917. ]
  918. )
  919. return result.rows[0].id
  920. })
  921. }
  922. /** Inbound text messages with exactly this body, for a workshop. */
  923. export async function inboundSmsCount(organizationId: string, body: string): Promise<number> {
  924. return withDb(async (db) => {
  925. const result = await db.query<{ n: string }>(
  926. `select count(*)::text as n from sms_messages
  927. where "organizationId" = $1 and direction = 'inbound' and body = $2`,
  928. [organizationId, body]
  929. )
  930. return Number(result.rows[0].n)
  931. })
  932. }
  933. export async function deleteInboundSms(organizationId: string, body: string): Promise<void> {
  934. await withDb((db) =>
  935. db.query(
  936. `delete from sms_messages where "organizationId" = $1 and direction = 'inbound' and body = $2`,
  937. [organizationId, body]
  938. )
  939. )
  940. }
  941. // ─── Work order titles ───────────────────────────────────────────────────────
  942. /** What a job is called and numbered, straight from its row. */
  943. export async function serviceRecordNames(
  944. serviceRecordId: string
  945. ): Promise<{ title: string; invoiceNumber: string | null }> {
  946. return withDb(async (db) => {
  947. const result = await db.query<{ title: string; invoiceNumber: string | null }>(
  948. `select title, "invoiceNumber" from service_records where id = $1`,
  949. [serviceRecordId]
  950. )
  951. const row = result.rows[0]
  952. if (!row) throw new Error(`no work order ${serviceRecordId}`)
  953. return row
  954. })
  955. }
  956. /** The words a title template can print about one vehicle and its owner. */
  957. export async function vehicleFacts(vehicleId: string): Promise<{
  958. licensePlate: string | null
  959. make: string
  960. model: string
  961. year: number
  962. vin: string | null
  963. customerName: string | null
  964. }> {
  965. return withDb(async (db) => {
  966. const result = await db.query<{
  967. licensePlate: string | null
  968. make: string
  969. model: string
  970. year: number
  971. vin: string | null
  972. customerName: string | null
  973. }>(
  974. `select v."licensePlate", v.make, v.model, v.year, v.vin, c.name as "customerName"
  975. from vehicles v
  976. left join customers c on c.id = v."customerId"
  977. where v.id = $1`,
  978. [vehicleId]
  979. )
  980. const row = result.rows[0]
  981. if (!row) throw new Error(`no vehicle ${vehicleId}`)
  982. return row
  983. })
  984. }
  985. /** Removes a workshop setting so the app falls back to its default for it. */
  986. export async function forgetWorkshopSetting(organizationId: string, key: string): Promise<void> {
  987. await withDb((db) =>
  988. db.query(`delete from app_settings where "organizationId" = $1 and key = $2`, [
  989. organizationId,
  990. key,
  991. ])
  992. )
  993. }
  994. /** Marks the address verified, as clicking the mail's link would. */
  995. export async function markEmailVerified(email: string): Promise<void> {
  996. await withDb((db) =>
  997. db.query(`update users set "emailVerified" = true where lower(email) = lower($1)`, [email])
  998. )
  999. }
  1000. export interface MembershipRecord {
  1001. id: string
  1002. role: string
  1003. roleId: string | null
  1004. }
  1005. /** A person's membership of a workshop, as stored. */
  1006. export async function membershipOf(
  1007. email: string,
  1008. organizationId: string
  1009. ): Promise<MembershipRecord> {
  1010. return withDb(async (db) => {
  1011. const result = await db.query<MembershipRecord>(
  1012. `select m.id, m.role, m."roleId" from organization_members m
  1013. join users u on u.id = m."userId"
  1014. where lower(u.email) = lower($1) and m."organizationId" = $2`,
  1015. [email, organizationId]
  1016. )
  1017. if (!result.rows[0]) throw new Error(`${email} is not a member of ${organizationId}`)
  1018. return result.rows[0]
  1019. })
  1020. }
  1021. /** A role that carries the admin switch and nothing else. */
  1022. export async function createAdminRole(organizationId: string, name: string): Promise<string> {
  1023. return withDb(async (db) => {
  1024. const result = await db.query<{ id: string }>(
  1025. `insert into roles (id, name, "isAdmin", "organizationId", "createdAt", "updatedAt")
  1026. values (gen_random_uuid()::text, $1, true, $2, now(), now()) returning id`,
  1027. [name, organizationId]
  1028. )
  1029. return result.rows[0].id
  1030. })
  1031. }
  1032. export async function deleteRoles(ids: string[]): Promise<void> {
  1033. if (ids.length === 0) return
  1034. await withDb((db) => db.query(`delete from roles where id = any($1::text[])`, [ids]))
  1035. }
  1036. /** A technician on a workshop's board, made here so the spec owns it. */
  1037. export async function insertTechnician(organizationId: string, name: string): Promise<string> {
  1038. return withDb(async (db) => {
  1039. const result = await db.query<{ id: string }>(
  1040. `insert into technicians (id, name, "organizationId", "createdAt", "updatedAt")
  1041. values (gen_random_uuid()::text, $1, $2, now(), now()) returning id`,
  1042. [name, organizationId]
  1043. )
  1044. return result.rows[0].id
  1045. })
  1046. }
  1047. export async function insertWorkBay(organizationId: string, name: string): Promise<string> {
  1048. return withDb(async (db) => {
  1049. const result = await db.query<{ id: string }>(
  1050. `insert into work_bays (id, name, "organizationId", "createdAt", "updatedAt")
  1051. values (gen_random_uuid()::text, $1, $2, now(), now()) returning id`,
  1052. [name, organizationId]
  1053. )
  1054. return result.rows[0].id
  1055. })
  1056. }
  1057. export async function deleteTechnicians(ids: string[]): Promise<void> {
  1058. if (ids.length === 0) return
  1059. await withDb((db) => db.query(`delete from technicians where id = any($1::text[])`, [ids]))
  1060. }
  1061. export async function deleteWorkBays(ids: string[]): Promise<void> {
  1062. if (ids.length === 0) return
  1063. await withDb((db) => db.query(`delete from work_bays where id = any($1::text[])`, [ids]))
  1064. }
  1065. export interface JobAssignment {
  1066. id: string
  1067. technicianId: string | null
  1068. workBayId: string | null
  1069. }
  1070. /** A job's technician and bay as stored, by its id. */
  1071. export async function jobAssignment(serviceRecordId: string): Promise<JobAssignment> {
  1072. return withDb(async (db) => {
  1073. const result = await db.query<JobAssignment>(
  1074. `select id, "technicianId", "workBayId" from service_records where id = $1`,
  1075. [serviceRecordId]
  1076. )
  1077. if (!result.rows[0]) throw new Error(`no job ${serviceRecordId}`)
  1078. return result.rows[0]
  1079. })
  1080. }
  1081. /** Everybody on a job beside its technician, as technician ids, sorted. */
  1082. export async function jobHelperIds(serviceRecordId: string): Promise<string[]> {
  1083. return withDb(async (db) => {
  1084. const result = await db.query<{ technicianId: string }>(
  1085. `select "technicianId" from service_record_helpers
  1086. where "serviceRecordId" = $1 order by "technicianId"`,
  1087. [serviceRecordId]
  1088. )
  1089. return result.rows.map((row) => row.technicianId)
  1090. })
  1091. }
  1092. /**
  1093. * When a job is booked to start. The column has no zone and holds UTC, which
  1094. * pg would read in the test process's zone, so it is read as UTC text.
  1095. */
  1096. export async function jobStart(serviceRecordId: string): Promise<Date | null> {
  1097. return withDb(async (db) => {
  1098. const result = await db.query<{ start: string | null }>(
  1099. `select to_char("startDateTime", 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') as start
  1100. from service_records where id = $1`,
  1101. [serviceRecordId]
  1102. )
  1103. const start = result.rows[0]?.start
  1104. return start ? new Date(start) : null
  1105. })
  1106. }
  1107. /** A workshop's technician by name, for one the desk made through the page. */
  1108. export async function technicianIdNamed(organizationId: string, name: string): Promise<string> {
  1109. return withDb(async (db) => {
  1110. const result = await db.query<{ id: string }>(
  1111. `select id from technicians where "organizationId" = $1 and name = $2 limit 1`,
  1112. [organizationId, name]
  1113. )
  1114. const id = result.rows[0]?.id
  1115. if (!id) throw new Error(`no technician named ${name}`)
  1116. return id
  1117. })
  1118. }
  1119. /** How many jobs a vehicle has, before and after an attempt to add one. */
  1120. export async function jobCount(vehicleId: string): Promise<number> {
  1121. return withDb(async (db) => {
  1122. const result = await db.query<{ n: string }>(
  1123. `select count(*)::text as n from service_records where "vehicleId" = $1`,
  1124. [vehicleId]
  1125. )
  1126. return Number(result.rows[0].n)
  1127. })
  1128. }
  1129. /** Inbound WhatsApp messages with exactly this body, for a workshop. */
  1130. export async function inboundWhatsappCount(organizationId: string, body: string): Promise<number> {
  1131. return withDb(async (db) => {
  1132. const result = await db.query<{ n: string }>(
  1133. `select count(*)::text as n from whatsapp_messages
  1134. where "organizationId" = $1 and direction = 'inbound' and body = $2`,
  1135. [organizationId, body]
  1136. )
  1137. return Number(result.rows[0].n)
  1138. })
  1139. }
  1140. export async function deleteInboundWhatsapp(organizationId: string, body: string): Promise<void> {
  1141. await withDb((db) =>
  1142. db.query(
  1143. `delete from whatsapp_messages where "organizationId" = $1 and direction = 'inbound' and body like $2`,
  1144. [organizationId, `${body}%`]
  1145. )
  1146. )
  1147. }
  1148. /** Open sessions a person has, however many browsers and phones that is. */
  1149. export async function sessionCountFor(email: string): Promise<number> {
  1150. return withDb(async (db) => {
  1151. const result = await db.query<{ n: string }>(
  1152. `select count(*)::text as n from sessions s join users u on u.id = s."userId"
  1153. where lower(u.email) = lower($1) and s."expiresAt" > now()`,
  1154. [email]
  1155. )
  1156. return Number(result.rows[0].n)
  1157. })
  1158. }
  1159. /**
  1160. * Makes every open sign-in of a person look `minutes` old, the way a tab left
  1161. * open ages. What the app asks of a sign-in that is no longer recent cannot
  1162. * be waited for in a test.
  1163. */
  1164. export async function ageSessionsOf(email: string, minutes: number): Promise<void> {
  1165. await withDb(async (db) => {
  1166. await db.query(
  1167. `update sessions s set "createdAt" = now() - make_interval(mins => $2::int)
  1168. from users u
  1169. where u.id = s."userId" and lower(u.email) = lower($1)`,
  1170. [email, minutes]
  1171. )
  1172. })
  1173. }
  1174. /** Device rows a person has whose user agent mentions `needle`. */
  1175. export async function deviceCountFor(email: string, needle: string): Promise<number> {
  1176. return withDb(async (db) => {
  1177. const result = await db.query<{ n: string }>(
  1178. `select count(*)::text as n from user_devices d join users u on u.id = d."userId"
  1179. where lower(u.email) = lower($1) and d."userAgent" like $2`,
  1180. [email, `%${needle}%`]
  1181. )
  1182. return Number(result.rows[0].n)
  1183. })
  1184. }
  1185. /**
  1186. * Matches better-auth's scrypt parameters, the same way the seed does, so a
  1187. * password written here is accepted by the sign-in form.
  1188. */
  1189. function hashPassword(password: string): string {
  1190. const N = 16384
  1191. const r = 16
  1192. const p = 1
  1193. const salt = randomBytes(16).toString('hex')
  1194. const key = scryptSync(password.normalize('NFKC'), salt, 64, { N, r, p, maxmem: 128 * N * r * 2 })
  1195. return `${salt}:${key.toString('hex')}`
  1196. }
  1197. export interface PlantedWorkshop {
  1198. userId: string
  1199. organizationId: string
  1200. }
  1201. /**
  1202. * A second tenant, put straight into the database.
  1203. *
  1204. * A self-hosted install opens one workshop; every later sign-up is told to
  1205. * ask for an invitation. A spec that needs a second, separate workshop to
  1206. * prove isolation therefore cannot sign one up and has to plant it: a
  1207. * verified person with a password, and a workshop they own.
  1208. */
  1209. export async function plantWorkshop(input: {
  1210. name: string
  1211. email: string
  1212. password: string
  1213. workshopName: string
  1214. }): Promise<PlantedWorkshop> {
  1215. return withDb(async (db) => {
  1216. const user = await db.query<{ id: string }>(
  1217. `insert into users (id, name, email, "emailVerified", "termsAcceptedAt", "createdAt", "updatedAt")
  1218. values (md5(random()::text || clock_timestamp()::text), $1, $2, true, now(), now(), now())
  1219. returning id`,
  1220. [input.name, input.email.toLowerCase()]
  1221. )
  1222. const userId = user.rows[0].id
  1223. await db.query(
  1224. `insert into accounts (id, "accountId", "providerId", "userId", password, "createdAt", "updatedAt")
  1225. values (md5(random()::text || clock_timestamp()::text), $1, 'credential', $1, $2, now(), now())`,
  1226. [userId, hashPassword(input.password)]
  1227. )
  1228. const org = await db.query<{ id: string }>(
  1229. `insert into organizations (id, name, "createdAt", "updatedAt")
  1230. values (md5(random()::text || clock_timestamp()::text), $1, now(), now())
  1231. returning id`,
  1232. [input.workshopName]
  1233. )
  1234. const organizationId = org.rows[0].id
  1235. await db.query(
  1236. `insert into organization_members (id, role, "userId", "organizationId")
  1237. values (md5(random()::text || clock_timestamp()::text), 'owner', $1, $2)`,
  1238. [userId, organizationId]
  1239. )
  1240. return { userId, organizationId }
  1241. })
  1242. }
  1243. /** Removes a person and, through the cascade, their memberships and sessions. */
  1244. export async function deletePersonWithEmail(email: string): Promise<void> {
  1245. await withDb((db) => db.query(`delete from users where lower(email) = lower($1)`, [email]))
  1246. }
  1247. /** How many workshops the install has. */
  1248. export async function organizationCount(): Promise<number> {
  1249. return withDb(async (db) => {
  1250. const result = await db.query<{ count: string }>(
  1251. `select count(*)::text as count from organizations`
  1252. )
  1253. return Number(result.rows[0].count)
  1254. })
  1255. }
  1256. /**
  1257. * One customer, one vehicle and one work order in a workshop, for a spec
  1258. * that needs a job to point at. A planted workshop has none of the sample
  1259. * data onboarding would have given it.
  1260. */
  1261. export async function plantJob(
  1262. organizationId: string,
  1263. userId: string,
  1264. title: string
  1265. ): Promise<{ serviceRecordId: string; vehicleId: string }> {
  1266. return withDb(async (db) => {
  1267. const customer = await db.query<{ id: string }>(
  1268. `insert into customers (id, name, "userId", "organizationId", "updatedAt")
  1269. values (md5(random()::text || clock_timestamp()::text), $1, $2, $3, now())
  1270. returning id`,
  1271. [`${title} customer`, userId, organizationId]
  1272. )
  1273. const vehicle = await db.query<{ id: string }>(
  1274. `insert into vehicles (id, make, model, year, "userId", "organizationId", "customerId", "updatedAt")
  1275. values (md5(random()::text || clock_timestamp()::text), 'E2E', $1, 2020, $2, $3, $4, now())
  1276. returning id`,
  1277. [title, userId, organizationId, customer.rows[0].id]
  1278. )
  1279. const vehicleId = vehicle.rows[0].id
  1280. const job = await db.query<{ id: string }>(
  1281. `insert into service_records (id, title, "vehicleId", "organizationId", "updatedAt")
  1282. values (md5(random()::text || clock_timestamp()::text), $1, $2, $3, now())
  1283. returning id`,
  1284. [title, vehicleId, organizationId]
  1285. )
  1286. return { serviceRecordId: job.rows[0].id, vehicleId }
  1287. })
  1288. }
  1289. // ─── Notifications ───────────────────────────────────────────────────────────
  1290. export interface PlantedNotification {
  1291. type: string
  1292. title: string
  1293. message: string
  1294. entityType: string
  1295. entityId: string
  1296. entityUrl: string
  1297. }
  1298. /**
  1299. * A notification written straight into the bell, with the address the code
  1300. * that raises it builds. Planting it rather than provoking it lets a spec
  1301. * follow links whose trigger needs a provider the harness cannot play (an
  1302. * inbound SMS, a Telegram webhook), and also links already stored in the old
  1303. * shape, which the pages still have to honour.
  1304. */
  1305. export async function plantNotification(
  1306. organizationId: string,
  1307. n: PlantedNotification
  1308. ): Promise<string> {
  1309. return withDb(async (db) => {
  1310. const result = await db.query<{ id: string }>(
  1311. `insert into notifications (id, type, title, message, "entityType", "entityId", "entityUrl", read, "organizationId", "createdAt")
  1312. values (md5(random()::text || clock_timestamp()::text), $1, $2, $3, $4, $5, $6, false, $7, now())
  1313. returning id`,
  1314. [n.type, n.title, n.message, n.entityType, n.entityId, n.entityUrl, organizationId]
  1315. )
  1316. return result.rows[0].id
  1317. })
  1318. }
  1319. export async function deleteNotifications(ids: string[]): Promise<void> {
  1320. if (ids.length === 0) return
  1321. await withDb((db) => db.query('delete from notifications where id = any($1)', [ids]))
  1322. }
  1323. /** An inbound message on a customer's thread, as the webhook would have stored it. */
  1324. export async function plantInboundMessage(
  1325. channel: 'sms' | 'telegram',
  1326. organizationId: string,
  1327. customerId: string,
  1328. body: string
  1329. ): Promise<void> {
  1330. await withDb((db) =>
  1331. channel === 'sms'
  1332. ? db.query(
  1333. `insert into sms_messages (id, direction, "fromNumber", "toNumber", body, status, "organizationId", "customerId", "createdAt", "updatedAt")
  1334. values (md5(random()::text || clock_timestamp()::text), 'inbound', '+4790000000', '+4790000001', $1, 'received', $2, $3, now(), now())`,
  1335. [body, organizationId, customerId]
  1336. )
  1337. : db.query(
  1338. `insert into telegram_messages (id, direction, "chatId", body, status, "organizationId", "customerId", "createdAt", "updatedAt")
  1339. values (md5(random()::text || clock_timestamp()::text), 'inbound', '777000', $1, 'received', $2, $3, now(), now())`,
  1340. [body, organizationId, customerId]
  1341. )
  1342. )
  1343. }
  1344. /**
  1345. * Links a customer to a Telegram chat and hands back what was there before.
  1346. * A real inbound Telegram message only ever comes from a linked chat, and the
  1347. * conversation shows nothing but "not connected yet" without one.
  1348. */
  1349. export async function linkTelegramChat(
  1350. customerId: string,
  1351. chatId: string | null
  1352. ): Promise<string | null> {
  1353. return withDb(async (db) => {
  1354. const before = await db.query<{ telegramChatId: string | null }>(
  1355. 'select "telegramChatId" from customers where id = $1',
  1356. [customerId]
  1357. )
  1358. await db.query('update customers set "telegramChatId" = $1 where id = $2', [chatId, customerId])
  1359. return before.rows[0]?.telegramChatId ?? null
  1360. })
  1361. }
  1362. export async function deleteMessagesWithBody(body: string): Promise<void> {
  1363. await withDb(async (db) => {
  1364. await db.query('delete from sms_messages where body = $1', [body])
  1365. await db.query('delete from telegram_messages where body = $1', [body])
  1366. })
  1367. }
  1368. /** A vehicle job with the customer it belongs to, taken from one row so the ids agree. */
  1369. export async function jobWithCustomer(organizationId: string): Promise<{
  1370. vehicleId: string
  1371. serviceRecordId: string
  1372. customerId: string
  1373. customerName: string
  1374. }> {
  1375. return withDb(async (db) => {
  1376. const result = await db.query<{
  1377. vehicleId: string
  1378. serviceRecordId: string
  1379. customerId: string
  1380. customerName: string
  1381. }>(
  1382. `select v.id as "vehicleId", s.id as "serviceRecordId", c.id as "customerId", c.name as "customerName"
  1383. from service_records s
  1384. join vehicles v on v.id = s."vehicleId"
  1385. join customers c on c.id = v."customerId"
  1386. where s."organizationId" = $1
  1387. order by s."createdAt" asc
  1388. limit 1`,
  1389. [organizationId]
  1390. )
  1391. const row = result.rows[0]
  1392. if (!row) throw new Error('the seeded workshop has no vehicle job with a customer')
  1393. return row
  1394. })
  1395. }
  1396. export interface PlantedVehicleFiles {
  1397. vehicleImage: string
  1398. jobPhoto: string
  1399. /** A tire set's photo, also on the job as a tire hotel copy. */
  1400. tireSetPhoto: string
  1401. statusVideo: string
  1402. inspectionPhoto?: string
  1403. quoteDocument: string
  1404. /** A URL naming another workshop, as a row restored from its backup can. */
  1405. foreignPhoto: string
  1406. }
  1407. export interface PlantedVehicle {
  1408. vehicleId: string
  1409. serviceRecordId: string
  1410. tireSetId: string
  1411. quoteId: string
  1412. inspected: boolean
  1413. }
  1414. /**
  1415. * A vehicle with every kind of file that can go with it, written straight
  1416. * into the database so a spec knows exactly which rows point at which file:
  1417. * its image; a job with a photo, a status report video and the copy of a tire
  1418. * set's photo; an inspection with a photo on one item (when the workshop has
  1419. * a template to hang it on); and, pointing at the same vehicle but not
  1420. * deleted with it, a stored tire set and a quote with a document.
  1421. */
  1422. export async function plantVehicleWithFiles(
  1423. organizationId: string,
  1424. userId: string,
  1425. files: PlantedVehicleFiles,
  1426. label: string
  1427. ): Promise<PlantedVehicle> {
  1428. return withDb(async (db) => {
  1429. const id = () => randomBytes(12).toString('hex')
  1430. const vehicleId = id()
  1431. const serviceRecordId = id()
  1432. const tireSetId = id()
  1433. const quoteId = id()
  1434. await db.query(
  1435. `insert into vehicles (id, make, model, year, "userId", "organizationId", "imageUrl", "updatedAt")
  1436. values ($1, 'E2E', $2, 2020, $3, $4, $5, now())`,
  1437. [vehicleId, label, userId, organizationId, files.vehicleImage]
  1438. )
  1439. await db.query(
  1440. `insert into service_records (id, title, "vehicleId", "organizationId", "updatedAt")
  1441. values ($1, $2, $3, $4, now())`,
  1442. [serviceRecordId, `${label} job`, vehicleId, organizationId]
  1443. )
  1444. await db.query(
  1445. `insert into tire_sets (id, "organizationId", "userId", "vehicleId", "updatedAt")
  1446. values ($1, $2, $3, $4, now())`,
  1447. [tireSetId, organizationId, userId, vehicleId]
  1448. )
  1449. await db.query(
  1450. `insert into tire_set_attachments (id, "organizationId", "tireSetId", "fileName", "fileUrl", "fileType", "fileSize")
  1451. values ($1, $2, $3, 'rim.jpg', $4, 'image/jpeg', 10)`,
  1452. [id(), organizationId, tireSetId, files.tireSetPhoto]
  1453. )
  1454. for (const [fileUrl, category] of [
  1455. [files.jobPhoto, 'image'],
  1456. [files.tireSetPhoto, 'tire_hotel'],
  1457. [files.foreignPhoto, 'image'],
  1458. ]) {
  1459. await db.query(
  1460. `insert into service_attachments (id, "serviceRecordId", "fileName", "fileUrl", "fileType", "fileSize", category)
  1461. values ($1, $2, 'photo.jpg', $3, 'image/jpeg', 10, $4)`,
  1462. [id(), serviceRecordId, fileUrl, category]
  1463. )
  1464. }
  1465. await db.query(
  1466. `insert into status_reports (id, "publicToken", "organizationId", "serviceRecordId", "videoUrl", "updatedAt")
  1467. values ($1, $2, $3, $4, $5, now())`,
  1468. [id(), id(), organizationId, serviceRecordId, files.statusVideo]
  1469. )
  1470. await db.query(
  1471. `insert into quotes (id, title, "userId", "organizationId", "vehicleId", "updatedAt")
  1472. values ($1, $2, $3, $4, $5, now())`,
  1473. [quoteId, `${label} quote`, userId, organizationId, vehicleId]
  1474. )
  1475. await db.query(
  1476. `insert into quote_attachments (id, "quoteId", "fileName", "fileUrl", "fileType", "fileSize")
  1477. values ($1, $2, 'estimate.pdf', $3, 'application/pdf', 10)`,
  1478. [id(), quoteId, files.quoteDocument]
  1479. )
  1480. let inspected = false
  1481. const template = await db.query<{ id: string }>(
  1482. `select id from inspection_templates where "organizationId" = $1 limit 1`,
  1483. [organizationId]
  1484. )
  1485. if (files.inspectionPhoto && template.rows[0]) {
  1486. const inspectionId = id()
  1487. await db.query(
  1488. `insert into inspections (id, "vehicleId", "organizationId", "templateId", "updatedAt")
  1489. values ($1, $2, $3, $4, now())`,
  1490. [inspectionId, vehicleId, organizationId, template.rows[0].id]
  1491. )
  1492. await db.query(
  1493. `insert into inspection_items (id, "inspectionId", name, section, "imageUrls")
  1494. values ($1, $2, 'Brakes', 'Checks', $3)`,
  1495. [id(), inspectionId, [files.inspectionPhoto]]
  1496. )
  1497. inspected = true
  1498. }
  1499. return { vehicleId, serviceRecordId, tireSetId, quoteId, inspected }
  1500. })
  1501. }
  1502. /** Removes what `plantVehicleWithFiles` made that its spec did not delete. */
  1503. export async function removePlantedVehicle(planted: PlantedVehicle): Promise<void> {
  1504. await withDb(async (db) => {
  1505. await db.query('delete from quotes where id = $1', [planted.quoteId])
  1506. await db.query('delete from tire_sets where id = $1', [planted.tireSetId])
  1507. await db.query('delete from inspections where "vehicleId" = $1', [planted.vehicleId])
  1508. await db.query('delete from vehicles where id = $1', [planted.vehicleId])
  1509. })
  1510. }
  1511. /**
  1512. * Every permission refusal logged for one person since a moment in time.
  1513. *
  1514. * `withAuth` writes an `auth.permissionDenied` row whenever a role is short of
  1515. * what an action asked for, which makes the audit log the one place that says
  1516. * what a page quietly wanted and did not get. A refusal on a page the role is
  1517. * meant to reach is, by definition, a bug: the page renders anyway, falls back
  1518. * to a built-in default, and says nothing about it.
  1519. *
  1520. * The write is fire-and-forget, so give it a moment to land before counting.
  1521. */
  1522. export async function permissionDenialsFor(email: string, since: Date): Promise<string[]> {
  1523. return withDb(async (db) => {
  1524. const result = await db.query<{ message: string }>(
  1525. `select coalesce(a.message, a.action) as message
  1526. from audit_logs a
  1527. join users u on u.id = a."userId"
  1528. where lower(u.email) = lower($1)
  1529. and a.action = 'auth.permissionDenied'
  1530. and a.timestamp >= $2
  1531. order by a.timestamp`,
  1532. [email, since]
  1533. )
  1534. return result.rows.map((row) => row.message)
  1535. })
  1536. }
  1537. /**
  1538. * What the audit log says about one person's sign-in security since a moment:
  1539. * two-factor sign-in turned on or off, a backup code used, a passkey added or
  1540. * removed. Read as the English line the log shows.
  1541. *
  1542. * The writes are fire-and-forget, so poll this rather than read it once.
  1543. */
  1544. export async function accountSecurityEntries(email: string, since: Date): Promise<string[]> {
  1545. return withDb(async (db) => {
  1546. const result = await db.query<{ message: string }>(
  1547. `select coalesce(a.message, a.action) as message
  1548. from audit_logs a
  1549. join users u on u.id = a."userId"
  1550. where lower(u.email) = lower($1)
  1551. and a.action in ('auth.twoFactorEnabled', 'auth.twoFactorDisabled', 'auth.backupCodeUsed',
  1552. 'auth.passkeyAdded', 'auth.passkeyRemoved')
  1553. and a.timestamp >= $2
  1554. order by a.timestamp`,
  1555. [email, since]
  1556. )
  1557. return result.rows.map((row) => row.message)
  1558. })
  1559. }
  1560. /**
  1561. * Sets one of a workshop's settings directly, returning what was there before
  1562. * (null when the key had never been saved), so a spec can put it back.
  1563. *
  1564. * The row needs an owner: `app_settings.userId` is not nullable, so a key the
  1565. * workshop has never saved is attributed to whoever owns the workshop.
  1566. */
  1567. export async function setWorkshopSetting(
  1568. organizationId: string,
  1569. key: string,
  1570. value: string
  1571. ): Promise<string | null> {
  1572. return withDb(async (db) => {
  1573. const before = await db.query<{ value: string }>(
  1574. `select value from app_settings where "organizationId" = $1 and key = $2`,
  1575. [organizationId, key]
  1576. )
  1577. await db.query(
  1578. `insert into app_settings (id, key, value, "userId", "organizationId")
  1579. values (gen_random_uuid()::text, $2, $3,
  1580. (select "userId" from organization_members
  1581. where "organizationId" = $1 and role = 'owner' limit 1),
  1582. $1)
  1583. on conflict ("organizationId", key) do update set value = excluded.value`,
  1584. [organizationId, key, value]
  1585. )
  1586. return before.rows[0]?.value ?? null
  1587. })
  1588. }
  1589. /**
  1590. * A custom field on one kind of record, made here so the spec owns it.
  1591. *
  1592. * `name` is the key the app stores values under and `label` is what a person
  1593. * reads, so both are stamped: the point of the field is that its label shows
  1594. * up on the record, and a name left over from an earlier run would collide on
  1595. * `(organizationId, name, entityType)`.
  1596. */
  1597. export async function plantCustomField(
  1598. organizationId: string,
  1599. entityType: 'service_record' | 'quote',
  1600. name: string
  1601. ): Promise<string> {
  1602. return withDb(async (db) => {
  1603. const result = await db.query<{ id: string }>(
  1604. `insert into custom_field_definitions
  1605. (id, name, label, "fieldType", "entityType", "sortOrder", "isActive",
  1606. "createdAt", "updatedAt", "userId", "organizationId")
  1607. values (gen_random_uuid()::text, $2, $2, 'text', $3, 0, true, now(), now(),
  1608. (select "userId" from organization_members
  1609. where "organizationId" = $1 and role = 'owner' limit 1),
  1610. $1)
  1611. returning id`,
  1612. [organizationId, name, entityType]
  1613. )
  1614. return result.rows[0].id
  1615. })
  1616. }
  1617. /** Removes planted field definitions, and the values written into them. */
  1618. export async function deleteCustomFields(ids: string[]): Promise<void> {
  1619. if (ids.length === 0) return
  1620. await withDb(async (db) => {
  1621. await db.query(`delete from custom_field_values where "fieldId" = any($1::text[])`, [ids])
  1622. await db.query(`delete from custom_field_definitions where id = any($1::text[])`, [ids])
  1623. })
  1624. }
  1625. /**
  1626. * The value stored in one custom field for one record, or null.
  1627. *
  1628. * Read back to prove a save from the browser reached the database rather than
  1629. * only the input it was typed into.
  1630. */
  1631. export async function customFieldValue(fieldId: string, entityId: string): Promise<string | null> {
  1632. return withDb(async (db) => {
  1633. const result = await db.query<{ value: string }>(
  1634. `select value from custom_field_values where "fieldId" = $1 and "entityId" = $2`,
  1635. [fieldId, entityId]
  1636. )
  1637. return result.rows[0]?.value ?? null
  1638. })
  1639. }
  1640. /**
  1641. * A workshop's own role by name, as `createDefaultRoles` made it.
  1642. *
  1643. * The built-in Member role is what the product really hands somebody at the
  1644. * desk, so a spec about that role has to use that row rather than build an
  1645. * equivalent permission list by hand: a list assembled in the test would keep
  1646. * passing after the real role changed underneath it.
  1647. */
  1648. export async function roleIdNamed(organizationId: string, name: string): Promise<string | null> {
  1649. return withDb(async (db) => {
  1650. const result = await db.query<{ id: string }>(
  1651. `select id from roles where "organizationId" = $1 and name = $2 limit 1`,
  1652. [organizationId, name]
  1653. )
  1654. return result.rows[0]?.id ?? null
  1655. })
  1656. }
  1657. // ─── Condition map ───────────────────────────────────────────────────────────
  1658. /** Where a planted mark was drawn: a job's drop-off, or one inspection check. */
  1659. export type MarkSheet =
  1660. | { serviceRecordId: string }
  1661. | { inspectionId: string; inspectionItemId: string }
  1662. export interface PlantedMark {
  1663. view?: 'top' | 'left' | 'right' | 'front' | 'rear'
  1664. panel?: string
  1665. kind?: string
  1666. severity?: 'minor' | 'major'
  1667. note?: string
  1668. /** When it was recorded; an earlier visit's mark is planted in the past. */
  1669. recordedAt?: Date
  1670. bodyType?: string
  1671. }
  1672. /**
  1673. * A job on a vehicle of its own, drawn as a sedan. Each spec plants its own
  1674. * car, so marks from another spec or an earlier run are never on it.
  1675. */
  1676. export async function plantConditionJob(
  1677. organizationId: string,
  1678. userId: string,
  1679. title: string,
  1680. openedAt?: Date
  1681. ): Promise<{ serviceRecordId: string; vehicleId: string }> {
  1682. const job = await plantJob(organizationId, userId, title)
  1683. await withDb(async (db) => {
  1684. await db.query(`update vehicles set "bodyType" = 'sedan' where id = $1`, [job.vehicleId])
  1685. if (openedAt) {
  1686. await db.query(`update service_records set "createdAt" = $2 where id = $1`, [
  1687. job.serviceRecordId,
  1688. openedAt,
  1689. ])
  1690. }
  1691. })
  1692. return job
  1693. }
  1694. /**
  1695. * An inspection on the vehicle with one condition map check, from a template
  1696. * of its own (the seed makes none). With `serviceRecordId` the job is linked to
  1697. * it, the way "Start inspection" links them.
  1698. */
  1699. export async function plantConditionInspection(
  1700. organizationId: string,
  1701. vehicleId: string,
  1702. label: string,
  1703. options: {
  1704. serviceRecordId?: string
  1705. completed?: boolean
  1706. startedAt?: Date
  1707. /** A second condition map check after the first: a hand-back beside the check-in. */
  1708. secondCheck?: boolean
  1709. } = {}
  1710. ): Promise<{ inspectionId: string; inspectionItemId: string; secondItemId: string | null }> {
  1711. return withDb(async (db) => {
  1712. const id = () => randomBytes(12).toString('hex')
  1713. const templateId = id()
  1714. const sectionId = id()
  1715. const inspectionId = id()
  1716. const inspectionItemId = id()
  1717. await db.query(
  1718. `insert into inspection_templates (id, name, "organizationId", "updatedAt")
  1719. values ($1, $2, $3, now())`,
  1720. [templateId, `${label} checklist`, organizationId]
  1721. )
  1722. await db.query(
  1723. `insert into inspection_template_sections (id, name, "templateId") values ($1, 'Body', $2)`,
  1724. [sectionId, templateId]
  1725. )
  1726. await db.query(
  1727. `insert into inspection_template_items (id, name, "inputType", "sectionId")
  1728. values ($1, 'Condition map', 'condition_map', $2)`,
  1729. [id(), sectionId]
  1730. )
  1731. await db.query(
  1732. `insert into inspections (id, "vehicleId", "organizationId", "templateId", status, "completedAt", "createdAt", "updatedAt")
  1733. values ($1, $2, $3, $4, $5, $6, coalesce($7, now()), now())`,
  1734. [
  1735. inspectionId,
  1736. vehicleId,
  1737. organizationId,
  1738. templateId,
  1739. options.completed ? 'completed' : 'in_progress',
  1740. options.completed ? new Date() : null,
  1741. options.startedAt ?? null,
  1742. ]
  1743. )
  1744. await db.query(
  1745. `insert into inspection_items (id, "inspectionId", name, section, "inputType", condition, "sortOrder")
  1746. values ($1, $2, 'Condition map', 'Body', 'condition_map', 'ok', 0)`,
  1747. [inspectionItemId, inspectionId]
  1748. )
  1749. const secondItemId = options.secondCheck ? id() : null
  1750. if (secondItemId) {
  1751. await db.query(
  1752. `insert into inspection_items (id, "inspectionId", name, section, "inputType", condition, "sortOrder")
  1753. values ($1, $2, 'Hand-back map', 'Body', 'condition_map', 'ok', 1)`,
  1754. [secondItemId, inspectionId]
  1755. )
  1756. }
  1757. if (options.serviceRecordId) {
  1758. await db.query(`update service_records set "inspectionId" = $2 where id = $1`, [
  1759. options.serviceRecordId,
  1760. inspectionId,
  1761. ])
  1762. }
  1763. return { inspectionId, inspectionItemId, secondItemId }
  1764. })
  1765. }
  1766. /** One mark written straight into the table, as if drawn on that sheet. */
  1767. export async function plantConditionMark(
  1768. organizationId: string,
  1769. vehicleId: string,
  1770. sheet: MarkSheet,
  1771. mark: PlantedMark = {}
  1772. ): Promise<string> {
  1773. return withDb(async (db) => {
  1774. const markId = randomBytes(12).toString('hex')
  1775. const onJob = 'serviceRecordId' in sheet
  1776. await db.query(
  1777. `insert into condition_marks
  1778. (id, "organizationId", "vehicleId", "serviceRecordId", "inspectionId", "inspectionItemId",
  1779. "bodyType", view, panel, x, y, kind, severity, note, "recordedAt", "updatedAt")
  1780. values ($1, $2, $3, $4, $5, $6, $7, $8, $9, 0.5, 0.5, $10, $11, $12, coalesce($13, now()), now())`,
  1781. [
  1782. markId,
  1783. organizationId,
  1784. vehicleId,
  1785. onJob ? sheet.serviceRecordId : null,
  1786. onJob ? null : sheet.inspectionId,
  1787. onJob ? null : sheet.inspectionItemId,
  1788. mark.bodyType ?? 'sedan',
  1789. mark.view ?? 'left',
  1790. mark.panel ?? 'left_front_door',
  1791. mark.kind ?? 'dent',
  1792. mark.severity ?? 'minor',
  1793. mark.note ?? null,
  1794. mark.recordedAt ?? null,
  1795. ]
  1796. )
  1797. return markId
  1798. })
  1799. }
  1800. export interface ConditionMarkRow {
  1801. id: string
  1802. serviceRecordId: string | null
  1803. inspectionId: string | null
  1804. view: string
  1805. panel: string
  1806. kind: string
  1807. severity: string
  1808. note: string | null
  1809. imageUrls: string[]
  1810. resolvedAt: Date | null
  1811. }
  1812. /** Every mark on the vehicle, oldest first, resolved ones included. */
  1813. export async function conditionMarksOf(vehicleId: string): Promise<ConditionMarkRow[]> {
  1814. return withDb(async (db) => {
  1815. const result = await db.query<ConditionMarkRow>(
  1816. `select id, "serviceRecordId", "inspectionId", view, panel, kind, severity, note,
  1817. "imageUrls", "resolvedAt"
  1818. from condition_marks where "vehicleId" = $1 order by "recordedAt", "createdAt"`,
  1819. [vehicleId]
  1820. )
  1821. return result.rows
  1822. })
  1823. }
  1824. /** Whether the job's invoice was told to carry the map: true, false, or null to follow the design. */
  1825. export async function conditionMapOnInvoice(serviceRecordId: string): Promise<boolean | null> {
  1826. return withDb(async (db) => {
  1827. const result = await db.query<{ on: boolean | null }>(
  1828. `select "conditionMapOnInvoice" as on from service_records where id = $1`,
  1829. [serviceRecordId]
  1830. )
  1831. return result.rows[0]?.on ?? null
  1832. })
  1833. }
  1834. /** Another job on a car that already has one: the next visit. */
  1835. export async function plantJobOnVehicle(
  1836. organizationId: string,
  1837. vehicleId: string,
  1838. title: string,
  1839. openedAt?: Date
  1840. ): Promise<{ serviceRecordId: string; vehicleId: string }> {
  1841. return withDb(async (db) => {
  1842. const job = await db.query<{ id: string }>(
  1843. `insert into service_records (id, title, "vehicleId", "organizationId", "createdAt", "updatedAt")
  1844. values (md5(random()::text || clock_timestamp()::text), $1, $2, $3, coalesce($4, now()), now())
  1845. returning id`,
  1846. [title, vehicleId, organizationId, openedAt ?? null]
  1847. )
  1848. return { serviceRecordId: job.rows[0].id, vehicleId }
  1849. })
  1850. }
  1851. /** A kind of mark of the workshop's own, keyed the way the settings page keys one. */
  1852. export async function plantOwnMarkKind(
  1853. organizationId: string,
  1854. name: string
  1855. ): Promise<{ id: string; key: string; name: string }> {
  1856. return withDb(async (db) => {
  1857. const id = randomBytes(12).toString('hex')
  1858. const key = `own_${id}`
  1859. await db.query(
  1860. `insert into condition_mark_types (id, "organizationId", key, name, shape, color, "sortOrder", hidden, "updatedAt")
  1861. values ($1, $2, $3, $4, 'circle', '#7c3aed', 100, false, now())`,
  1862. [id, organizationId, key, name]
  1863. )
  1864. return { id, key, name }
  1865. })
  1866. }
  1867. export async function removeOwnMarkKind(id: string): Promise<void> {
  1868. await withDb((db) => db.query(`delete from condition_mark_types where id = $1`, [id]))
  1869. }
  1870. // ─── A quote added to an open work order ─────────────────────────────────────
  1871. /**
  1872. * The columns a spec may write on a quote or a work order to make the two
  1873. * disagree, without touching the workshop's own settings (which other specs
  1874. * read at the same time). The stored totals are columns too: a discount or a
  1875. * tax written here leaves them stale until the document is saved or
  1876. * re-totalled, so a spec writes them alongside when it reads them back.
  1877. */
  1878. export interface DocumentFields {
  1879. subtotal?: number
  1880. discountType?: 'percentage' | 'fixed' | null
  1881. discountValue?: number
  1882. discountAmount?: number
  1883. taxRate?: number
  1884. taxInclusive?: boolean
  1885. taxComponents?: { name: string; rate: number }[] | null
  1886. taxAmount?: number
  1887. totalAmount?: number
  1888. warrantyStatus?: 'included' | 'not_included' | null
  1889. warrantyMonths?: number | null
  1890. warrantyMileage?: number | null
  1891. warrantyNotes?: string | null
  1892. }
  1893. export interface ServiceRecordFields extends DocumentFields {
  1894. status?: string
  1895. }
  1896. const DOCUMENT_COLUMNS = new Set([
  1897. 'subtotal',
  1898. 'discountType',
  1899. 'discountValue',
  1900. 'discountAmount',
  1901. 'taxRate',
  1902. 'taxInclusive',
  1903. 'taxComponents',
  1904. 'taxAmount',
  1905. 'totalAmount',
  1906. 'warrantyStatus',
  1907. 'warrantyMonths',
  1908. 'warrantyMileage',
  1909. 'warrantyNotes',
  1910. 'status',
  1911. ])
  1912. /** `"col" = $n, ...` for the given fields, refusing anything not listed above. */
  1913. function assignments(fields: object, offset: number): { sql: string; values: unknown[] } {
  1914. const entries = Object.entries(fields).filter(([, value]) => value !== undefined)
  1915. if (entries.length === 0) throw new Error('nothing to write')
  1916. for (const [column] of entries) {
  1917. if (!DOCUMENT_COLUMNS.has(column)) throw new Error(`not a writable column: ${column}`)
  1918. }
  1919. return {
  1920. sql: entries.map(([column], i) => `"${column}" = $${i + offset}`).join(', '),
  1921. values: entries.map(([column, value]) =>
  1922. column === 'taxComponents' && value !== null ? JSON.stringify(value) : value
  1923. ),
  1924. }
  1925. }
  1926. /** Writes columns on a quote, found by its id or its number. */
  1927. export async function setQuoteFields(
  1928. quoteNumberOrId: string,
  1929. fields: DocumentFields
  1930. ): Promise<void> {
  1931. await withDb(async (db) => {
  1932. const { sql, values } = assignments(fields, 2)
  1933. const result = await db.query(
  1934. `update quotes set ${sql}, "updatedAt" = now() where id = $1 or "quoteNumber" = $1`,
  1935. [quoteNumberOrId, ...values]
  1936. )
  1937. if (result.rowCount !== 1) {
  1938. throw new Error(`expected one quote for ${quoteNumberOrId}, found ${result.rowCount}`)
  1939. }
  1940. })
  1941. }
  1942. /** Writes columns on a work order. */
  1943. export async function setServiceRecordFields(
  1944. serviceRecordId: string,
  1945. fields: ServiceRecordFields
  1946. ): Promise<void> {
  1947. await withDb(async (db) => {
  1948. const { sql, values } = assignments(fields, 2)
  1949. const result = await db.query(
  1950. `update service_records set ${sql}, "updatedAt" = now() where id = $1`,
  1951. [serviceRecordId, ...values]
  1952. )
  1953. if (result.rowCount !== 1) throw new Error(`no work order ${serviceRecordId}`)
  1954. })
  1955. }
  1956. export interface PlantedPartLine {
  1957. name: string
  1958. quantity: number
  1959. unitPrice: number
  1960. }
  1961. export interface PlantedLaborLine {
  1962. description: string
  1963. hours: number
  1964. rate: number
  1965. }
  1966. /**
  1967. * Part and labour lines written onto a work order, priced the way the editor
  1968. * prices them (quantity × unit price, hours × rate). Nothing is re-totalled:
  1969. * the spec writes the stored totals it wants with `setServiceRecordFields`.
  1970. */
  1971. export async function addServiceRecordLines(
  1972. serviceRecordId: string,
  1973. lines: { parts?: PlantedPartLine[]; labor?: PlantedLaborLine[] }
  1974. ): Promise<void> {
  1975. await withDb(async (db) => {
  1976. for (const part of lines.parts ?? []) {
  1977. await db.query(
  1978. `insert into service_parts (id, name, quantity, "unitPrice", total, "serviceRecordId")
  1979. values (md5(random()::text || clock_timestamp()::text), $1, $2, $3, $4, $5)`,
  1980. [part.name, part.quantity, part.unitPrice, part.quantity * part.unitPrice, serviceRecordId]
  1981. )
  1982. }
  1983. for (const labor of lines.labor ?? []) {
  1984. await db.query(
  1985. `insert into service_labor (id, description, hours, rate, total, "serviceRecordId")
  1986. values (md5(random()::text || clock_timestamp()::text), $1, $2, $3, $4, $5)`,
  1987. [labor.description, labor.hours, labor.rate, labor.hours * labor.rate, serviceRecordId]
  1988. )
  1989. }
  1990. })
  1991. }
  1992. /**
  1993. * A draft quote for a vehicle and its owner, with its lines, as if typed into
  1994. * the editor and saved. Its tax, discount and warranty are whatever the spec
  1995. * writes next with `setQuoteFields`; the stored subtotal and total follow the
  1996. * lines here so the quote is consistent before that.
  1997. */
  1998. export async function plantQuote(
  1999. organizationId: string,
  2000. userId: string,
  2001. input: {
  2002. vehicleId: string
  2003. title: string
  2004. parts?: PlantedPartLine[]
  2005. labor?: PlantedLaborLine[]
  2006. }
  2007. ): Promise<string> {
  2008. return withDb(async (db) => {
  2009. const parts = input.parts ?? []
  2010. const labor = input.labor ?? []
  2011. const subtotal =
  2012. parts.reduce((sum, p) => sum + p.quantity * p.unitPrice, 0) +
  2013. labor.reduce((sum, l) => sum + l.hours * l.rate, 0)
  2014. const quote = await db.query<{ id: string }>(
  2015. `insert into quotes (id, title, status, subtotal, "totalAmount", "userId", "organizationId",
  2016. "customerId", "vehicleId", "updatedAt")
  2017. values (md5(random()::text || clock_timestamp()::text), $1, 'draft', $2, $2, $3, $4,
  2018. (select "customerId" from vehicles where id = $5), $5, now())
  2019. returning id`,
  2020. [input.title, subtotal, userId, organizationId, input.vehicleId]
  2021. )
  2022. const quoteId = quote.rows[0].id
  2023. for (const part of parts) {
  2024. await db.query(
  2025. `insert into quote_parts (id, name, quantity, "unitPrice", total, "quoteId")
  2026. values (md5(random()::text || clock_timestamp()::text), $1, $2, $3, $4, $5)`,
  2027. [part.name, part.quantity, part.unitPrice, part.quantity * part.unitPrice, quoteId]
  2028. )
  2029. }
  2030. for (const line of labor) {
  2031. await db.query(
  2032. `insert into quote_labor (id, description, hours, rate, total, "quoteId")
  2033. values (md5(random()::text || clock_timestamp()::text), $1, $2, $3, $4, $5)`,
  2034. [line.description, line.hours, line.rate, line.hours * line.rate, quoteId]
  2035. )
  2036. }
  2037. return quoteId
  2038. })
  2039. }
  2040. export interface StoredServiceRecord {
  2041. status: string
  2042. subtotal: number
  2043. discountType: string | null
  2044. discountValue: number
  2045. discountAmount: number
  2046. taxRate: number
  2047. taxInclusive: boolean
  2048. taxAmount: number
  2049. totalAmount: number
  2050. warrantyStatus: string | null
  2051. warrantyMonths: number | null
  2052. warrantyExpiresAt: Date | null
  2053. }
  2054. /** What a work order stores about its money and its warranty. */
  2055. export async function storedServiceRecord(serviceRecordId: string): Promise<StoredServiceRecord> {
  2056. return withDb(async (db) => {
  2057. const result = await db.query<StoredServiceRecord>(
  2058. `select status, subtotal, "discountType", "discountValue", "discountAmount", "taxRate",
  2059. "taxInclusive", "taxAmount", "totalAmount", "warrantyStatus", "warrantyMonths",
  2060. "warrantyExpiresAt"
  2061. from service_records where id = $1`,
  2062. [serviceRecordId]
  2063. )
  2064. const row = result.rows[0]
  2065. if (!row) throw new Error(`no work order ${serviceRecordId}`)
  2066. return row
  2067. })
  2068. }
  2069. /** The work order's part lines, by name. */
  2070. export async function servicePartLines(
  2071. serviceRecordId: string
  2072. ): Promise<{ name: string; quantity: number; unitPrice: number; total: number }[]> {
  2073. return withDb(async (db) => {
  2074. const result = await db.query<{
  2075. name: string
  2076. quantity: number
  2077. unitPrice: number
  2078. total: number
  2079. }>(
  2080. `select name, quantity, "unitPrice", total from service_parts
  2081. where "serviceRecordId" = $1 order by name`,
  2082. [serviceRecordId]
  2083. )
  2084. return result.rows
  2085. })
  2086. }
  2087. /** A quote's status and the job it went to, if any. */
  2088. export async function quoteConversion(
  2089. quoteId: string
  2090. ): Promise<{ status: string; convertedToId: string | null }> {
  2091. return withDb(async (db) => {
  2092. const result = await db.query<{ status: string; convertedToId: string | null }>(
  2093. `select status, "convertedToId" from quotes where id = $1`,
  2094. [quoteId]
  2095. )
  2096. const row = result.rows[0]
  2097. if (!row) throw new Error(`no quote ${quoteId}`)
  2098. return row
  2099. })
  2100. }
  2101. /** A technician's time off as stored, soonest first. */
  2102. export async function absencesOf(
  2103. technicianId: string
  2104. ): Promise<{ startDate: string; endDate: string; reason: string; startTime: string | null }[]> {
  2105. return withDb(async (db) => {
  2106. const result = await db.query(
  2107. `select to_char("startDate", 'YYYY-MM-DD') as "startDate",
  2108. to_char("endDate", 'YYYY-MM-DD') as "endDate", reason, "startTime"
  2109. from technician_absences where "technicianId" = $1 order by "startDate"`,
  2110. [technicianId]
  2111. )
  2112. return result.rows
  2113. })
  2114. }
  2115. /** The workshop's own closed days with this name, as stored. */
  2116. export async function closuresNamed(
  2117. name: string
  2118. ): Promise<{ startDate: string; endDate: string; repeatsYearly: boolean }[]> {
  2119. return withDb(async (db) => {
  2120. const result = await db.query(
  2121. `select to_char("startDate", 'YYYY-MM-DD') as "startDate",
  2122. to_char("endDate", 'YYYY-MM-DD') as "endDate", "repeatsYearly"
  2123. from workshop_closures where name = $1`,
  2124. [name]
  2125. )
  2126. return result.rows
  2127. })
  2128. }
  2129. export async function deleteClosuresNamed(name: string): Promise<void> {
  2130. await withDb((db) => db.query(`delete from workshop_closures where name = $1`, [name]))
  2131. }
  2132. /**
  2133. * Sets a person's own keyboard shortcut choices (users."keyboardShortcuts"),
  2134. * or clears them with null. The settings page writes the same column.
  2135. */
  2136. export async function setKeyboardShortcuts(
  2137. email: string,
  2138. prefs: Record<string, unknown> | null
  2139. ): Promise<void> {
  2140. await withDb(async (db) => {
  2141. await db.query(
  2142. `update users set "keyboardShortcuts" = $2::jsonb where lower(email) = lower($1)`,
  2143. [email, prefs === null ? null : JSON.stringify(prefs)]
  2144. )
  2145. })
  2146. }
  2147. export interface SharedDocumentFiles {
  2148. quotePhoto: string
  2149. quoteDocument: string
  2150. inspectionPhoto: string
  2151. inspectionOverview: string
  2152. /** On the inspection, kept off the report. */
  2153. inspectionHidden: string
  2154. statusVideo: string
  2155. }
  2156. export interface PlantedSharedDocuments {
  2157. vehicleId: string
  2158. quoteToken: string
  2159. inspectionToken: string
  2160. reportToken: string
  2161. }
  2162. /**
  2163. * A quote, an inspection and a status report, each shared with a link and
  2164. * carrying the files its page shows, on a vehicle of their own. For the
  2165. * spec that checks a share link opens its own document's files and no other.
  2166. */
  2167. export async function plantSharedDocuments(
  2168. organizationId: string,
  2169. userId: string,
  2170. files: SharedDocumentFiles,
  2171. label: string
  2172. ): Promise<PlantedSharedDocuments> {
  2173. return withDb(async (db) => {
  2174. const id = () => randomBytes(12).toString('hex')
  2175. const vehicleId = id()
  2176. const quoteId = id()
  2177. const inspectionId = id()
  2178. const quoteToken = id()
  2179. const inspectionToken = id()
  2180. const reportToken = id()
  2181. await db.query(
  2182. `insert into vehicles (id, make, model, year, "userId", "organizationId", "updatedAt")
  2183. values ($1, 'E2E', $2, 2020, $3, $4, now())`,
  2184. [vehicleId, label, userId, organizationId]
  2185. )
  2186. await db.query(
  2187. `insert into quotes (id, title, "userId", "organizationId", "vehicleId", "publicToken", "sharedAt", "updatedAt")
  2188. values ($1, $2, $3, $4, $5, $6, now(), now())`,
  2189. [quoteId, `${label} quote`, userId, organizationId, vehicleId, quoteToken]
  2190. )
  2191. for (const [fileUrl, fileName, fileType, category] of [
  2192. [files.quotePhoto, 'damage.png', 'image/png', 'image'],
  2193. [files.quoteDocument, 'estimate.pdf', 'application/pdf', 'document'],
  2194. ]) {
  2195. await db.query(
  2196. `insert into quote_attachments (id, "quoteId", "fileName", "fileUrl", "fileType", "fileSize", category)
  2197. values ($1, $2, $3, $4, $5, 10, $6)`,
  2198. [id(), quoteId, fileName, fileUrl, fileType, category]
  2199. )
  2200. }
  2201. const template = await db.query<{ id: string }>(
  2202. `select id from inspection_templates where "organizationId" = $1 limit 1`,
  2203. [organizationId]
  2204. )
  2205. if (!template.rows[0]) throw new Error('The seeded workshop has no inspection template')
  2206. await db.query(
  2207. `insert into inspections (id, "vehicleId", "organizationId", "templateId", status, "publicToken", "sharedAt", "updatedAt")
  2208. values ($1, $2, $3, $4, 'completed', $5, now(), now())`,
  2209. [inspectionId, vehicleId, organizationId, template.rows[0].id, inspectionToken]
  2210. )
  2211. await db.query(
  2212. `insert into inspection_items (id, "inspectionId", name, section, condition, "imageUrls")
  2213. values ($1, $2, 'Brakes', 'Checks', 'fail', $3)`,
  2214. [id(), inspectionId, [files.inspectionPhoto]]
  2215. )
  2216. for (const [fileUrl, fileName, fileType, category, shown] of [
  2217. [files.inspectionOverview, 'overview.png', 'image/png', 'image', true],
  2218. [files.inspectionHidden, 'paperwork.pdf', 'application/pdf', 'document', false],
  2219. ]) {
  2220. await db.query(
  2221. `insert into inspection_attachments (id, "inspectionId", "fileName", "fileUrl", "fileType", "fileSize", category, "includeInReport")
  2222. values ($1, $2, $3, $4, $5, 10, $6, $7)`,
  2223. [id(), inspectionId, fileName, fileUrl, fileType, category, shown]
  2224. )
  2225. }
  2226. await db.query(
  2227. `insert into status_reports (id, "publicToken", "organizationId", "inspectionId", "videoUrl", "videoFileName", status, "updatedAt")
  2228. values ($1, $2, $3, $4, $5, 'walkaround.mp4', 'sent', now())`,
  2229. [id(), reportToken, organizationId, inspectionId, files.statusVideo]
  2230. )
  2231. return { vehicleId, quoteToken, inspectionToken, reportToken }
  2232. })
  2233. }
  2234. /** Removes what `plantSharedDocuments` made. */
  2235. export async function removeSharedDocuments(planted: PlantedSharedDocuments): Promise<void> {
  2236. await withDb(async (db) => {
  2237. await db.query('delete from quotes where "vehicleId" = $1', [planted.vehicleId])
  2238. await db.query('delete from inspections where "vehicleId" = $1', [planted.vehicleId])
  2239. await db.query('delete from vehicles where id = $1', [planted.vehicleId])
  2240. })
  2241. }