db.ts 82 KB

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