db.ts 85 KB

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