seed_dummy_data.ts 250 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  1. import { PrismaClient } from "../src/generated/prisma/client";
  2. import { PrismaPg } from "@prisma/adapter-pg";
  3. import { randomBytes, scryptSync } from "node:crypto";
  4. import * as fs from "fs";
  5. import * as path from "path";
  6. import * as https from "https";
  7. import * as http from "http";
  8. // Matches better-auth's scrypt params — output is byte-compatible with its hashPassword,
  9. // so the stored hash is verifiable by better-auth at sign-in time.
  10. function hashPassword(password: string): string {
  11. const N = 16384, r = 16, p = 1, dkLen = 64;
  12. const maxmem = 128 * N * r * 2;
  13. const salt = randomBytes(16).toString("hex");
  14. const key = scryptSync(password.normalize("NFKC"), salt, dkLen, { N, r, p, maxmem });
  15. return `${salt}:${key.toString("hex")}`;
  16. }
  17. const prisma = new PrismaClient({
  18. adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
  19. });
  20. // ── Clock ────────────────────────────────────────────────────────────────
  21. // Every date below is derived from the moment the seed runs, so a reset always
  22. // produces a workshop that is busy *today*: jobs on the board this week, quotes
  23. // about to expire, reminders coming due. Nothing is pinned to a calendar date,
  24. // which is what lets demo.torqvoice.com reset on a schedule and still look live.
  25. const NOW = new Date();
  26. const TODAY = (() => { const d = new Date(NOW); d.setHours(0, 0, 0, 0); return d; })();
  27. /** Midnight, `n` days from today. Negative is the past. */
  28. function days(n: number): Date {
  29. const d = new Date(TODAY);
  30. d.setDate(d.getDate() + n);
  31. return d;
  32. }
  33. /** `n` days from today at a wall-clock time. */
  34. function at(n: number, hour: number, minute = 0): Date {
  35. const d = days(n);
  36. d.setHours(hour, minute, 0, 0);
  37. return d;
  38. }
  39. /** Offsets from the current instant - for message and chat timelines. */
  40. function hoursAgo(n: number): Date { return new Date(NOW.getTime() - n * 3600_000); }
  41. function minutesAgo(n: number): Date { return new Date(NOW.getTime() - n * 60_000); }
  42. /** Same day-of-month, `n` months out. Used for recurring schedules. */
  43. function months(n: number): Date {
  44. const d = new Date(TODAY);
  45. d.setMonth(d.getMonth() + n);
  46. return d;
  47. }
  48. /**
  49. * Monday of the week the work board showcases. On a weekday that is this
  50. * week's Monday, so the board's day view lands on a busy day. Run over a
  51. * weekend it rolls to the coming Monday rather than showing a spent week.
  52. */
  53. function weekMonday(): Date {
  54. const dow = NOW.getDay(); // 0 = Sunday
  55. const toMonday = dow === 0 ? 1 : dow === 6 ? 2 : 1 - dow;
  56. return days(toMonday);
  57. }
  58. /** Day offset from today to the board's Monday - for spreading other data. */
  59. const MONDAY_OFFSET = Math.round((weekMonday().getTime() - TODAY.getTime()) / 86_400_000);
  60. const YEAR = TODAY.getFullYear();
  61. const USER_ID = "IqcAL6GKoedJNO8Xi6UJkCM5YZqgS9uU";
  62. const ORG_ID = "cmmh0vczm0000oiyan37vuyqf";
  63. const DEMO_EMAIL = process.env.DEMO_USER_EMAIL || "demo@torqvoice.com";
  64. const DEMO_PASSWORD = process.env.DEMO_USER_PASSWORD || "demo";
  65. const DEMO_ORG_NAME = process.env.DEMO_ORG_NAME || "Demo Auto Workshop";
  66. const DATA_ROOT = process.env.DATA_ROOT || path.join(process.cwd(), "data");
  67. const UPLOAD_DIR = path.join(DATA_ROOT, "uploads", ORG_ID, "vehicles");
  68. // Image assets bundled with the repo — preferred over live URL downloads so
  69. // the seed never fails when an Unsplash photo gets removed.
  70. const BUNDLED_IMAGE_DIR = path.join(process.cwd(), "prisma", "seed-assets", "vehicles");
  71. // All CDN URLs verified: extracted from Unsplash photo pages via curl, all return HTTP 200
  72. const vehicleImages: Record<string, string> = {
  73. // Cars
  74. "toyota-camry.jpg": "https://images.unsplash.com/photo-1621007947382-bb3c3994e3fb?w=800&q=80",
  75. "ford-f150-white.jpg": "https://images.unsplash.com/photo-1605152322346-bd2391778772?w=800&q=80",
  76. "ford-f150-grey.jpg": "https://images.unsplash.com/photo-1614218110929-caa460524fc1?w=800&q=80",
  77. "ford-f150-black.jpg": "https://images.unsplash.com/photo-1691809158613-1e4d51ad086f?w=800&q=80",
  78. "bmw-3series.jpg": "https://images.unsplash.com/photo-1629994562870-75d504fc02a1?w=800&q=80",
  79. "honda-civic.jpg": "https://images.unsplash.com/photo-1636915873177-a0c1a48d84eb?w=800&q=80",
  80. "tesla-model3.jpg": "https://images.unsplash.com/photo-1610470832703-95d40c3fad55?w=800&q=80",
  81. "tesla-modely.jpg": "https://images.unsplash.com/photo-1504507926084-34cf0b939964?w=800&q=80",
  82. "chevy-silverado.jpg": "https://images.unsplash.com/photo-1601919652576-41bad7c8ccbd?w=800&q=80",
  83. "mercedes-sprinter.jpg": "https://images.unsplash.com/photo-1535655685871-dc8158ff167e?w=800&q=80",
  84. "audi-a4.jpg": "https://images.unsplash.com/photo-1619732569416-83a8adfd8ac4?w=800&q=80",
  85. "jeep-wrangler.jpg": "https://images.unsplash.com/photo-1579097647275-16b002cced9e?w=800&q=80",
  86. "jeep-wrangler-orange.jpg": "https://images.unsplash.com/photo-1622364631585-831e11682a67?w=800&q=80",
  87. "porsche-911.jpg": "https://images.unsplash.com/photo-1624880056652-c7993c99190f?w=800&q=80",
  88. "vw-golf-gti-red.jpg": "https://images.unsplash.com/photo-1560282105-222992ffb774?w=800&q=80",
  89. "vw-golf-gti-grey.jpg": "https://images.unsplash.com/photo-1746184842826-73fd144a4587?w=800&q=80",
  90. "ram-1500.jpg": "https://images.unsplash.com/photo-1649793395985-967862a3b73f?w=800&q=80",
  91. "ram-1500-black.jpg": "https://images.unsplash.com/photo-1678492861610-0bd650a846fe?w=800&q=80",
  92. "toyota-tacoma.jpg": "https://images.unsplash.com/photo-1509510779868-337c9f58ad54?w=800&q=80",
  93. "subaru-outback.jpg": "https://images.unsplash.com/photo-1681680061152-d3fc0b999a8e?w=800&q=80",
  94. "subaru-forester.jpg": "https://images.unsplash.com/photo-1687048988997-ec57f83ea3bd?w=800&q=80",
  95. // Trucks
  96. "kenworth-t680.jpg": "https://images.unsplash.com/photo-1586191552066-d52dd1e3af86?w=800&q=80",
  97. "freightliner-cascadia.jpg": "https://images.unsplash.com/photo-1616432043562-3671ea2e5242?w=800&q=80",
  98. "volvo-fh640.jpg": "https://images.unsplash.com/photo-1633966100013-25a16d17b43d?w=800&q=80",
  99. "mack-granite.jpg": "https://images.unsplash.com/photo-1746349086423-06ea6b4d73f7?w=800&q=80",
  100. "concrete-mixer.jpg": "https://images.unsplash.com/photo-1530139675202-8c52bb810762?w=800&q=80",
  101. "dump-truck.jpg": "https://images.unsplash.com/photo-1686945127938-0296f10937ed?w=800&q=80",
  102. // Tractors
  103. "john-deere-6r.jpg": "https://images.unsplash.com/photo-1604923757148-f6e6957199c3?w=800&q=80",
  104. "fendt-942.jpg": "https://images.unsplash.com/photo-1629818572083-3ceb38e34322?w=800&q=80",
  105. "massey-ferguson.jpg": "https://images.unsplash.com/photo-1635351461882-9ffff1ce323c?w=800&q=80",
  106. "tractor-wheat.jpg": "https://images.unsplash.com/photo-1720273071277-190dd8f0a05a?w=800&q=80",
  107. "tractor-field.jpg": "https://images.unsplash.com/photo-1633554587766-ffc8151e31c0?w=800&q=80",
  108. "combine-harvester.jpg": "https://images.unsplash.com/photo-1754893889385-6c5a2d675524?w=800&q=80",
  109. "combine-jd.jpg": "https://images.unsplash.com/photo-1635174815612-fd9636f70146?w=800&q=80",
  110. // Heavy Machinery
  111. "cat-d6-bulldozer.jpg": "https://images.unsplash.com/photo-1621922688758-359fc864071e?w=800&q=80",
  112. "bulldozer-rocks.jpg": "https://images.unsplash.com/photo-1710669430606-30a8ceeb6e71?w=800&q=80",
  113. "komatsu-excavator.jpg": "https://images.unsplash.com/photo-1649807533255-bbc9c9fb7d77?w=800&q=80",
  114. "excavator-soil.jpg": "https://images.unsplash.com/photo-1622082679766-c5912d9416eb?w=800&q=80",
  115. "volvo-ec220e.jpg": "https://images.unsplash.com/photo-1568678453977-a90de6812e7a?w=800&q=80",
  116. "mini-excavator.jpg": "https://images.unsplash.com/photo-1722925837890-0fa0f0c9a356?w=800&q=80",
  117. "wheel-loader.jpg": "https://images.unsplash.com/photo-1630288214032-2c4cc2c080ca?w=800&q=80",
  118. "bulldozer-road.jpg": "https://images.unsplash.com/photo-1684431438566-6ff4a0df9190?w=800&q=80",
  119. "loader-field.jpg": "https://images.unsplash.com/photo-1727863526509-7670e063f308?w=800&q=80",
  120. "liebherr-crane.jpg": "https://images.unsplash.com/photo-1685305934074-3a7c37614c29?w=800&q=80",
  121. "crane-yellow.jpg": "https://images.unsplash.com/photo-1725882176928-de328f0d485a?w=800&q=80",
  122. "forklift.jpg": "https://images.unsplash.com/photo-1740914994657-f1cdffdc418e?w=800&q=80",
  123. // Additional vehicles
  124. "corvette-c8.jpg": "https://images.unsplash.com/photo-1750050677183-4e68b1d21b65?w=800&q=80",
  125. "land-rover-defender.jpg": "https://images.unsplash.com/photo-1741905358583-1999b08d6e2e?w=800&q=80",
  126. "dodge-charger.jpg": "https://images.unsplash.com/photo-1674520669939-1a8dbcdc2f6b?w=800&q=80",
  127. "subaru-wrx.jpg": "https://images.unsplash.com/photo-1747000586906-c451da789b62?w=800&q=80",
  128. };
  129. // ── Inspection templates ─────────────────────────────────────────────────
  130. // Deliberately duplicated rather than imported from
  131. // src/features/inspections/Lib/templatePresets: the production image ships only
  132. // prisma/ and src/generated (see Dockerfile), so anything the seed imports from
  133. // src/features breaks the deploy job with MODULE_NOT_FOUND.
  134. //
  135. // The periodic-inspection checklist below is a subset of that preset, codes and
  136. // limit values included — they are the common Union figures from Annex I of
  137. // Directive 2014/45/EU. Do not invent codes or thresholds here; copy them from
  138. // the preset, which is where they are maintained.
  139. type SeedItem = {
  140. name: string;
  141. code?: string;
  142. description?: string;
  143. inputType?: string;
  144. unit?: string;
  145. minValue?: number;
  146. maxValue?: number;
  147. choices?: string[];
  148. required?: boolean;
  149. photoRequired?: boolean;
  150. defaultSeverity?: string;
  151. };
  152. type SeedSection = { name: string; code?: string; description?: string; items: SeedItem[] };
  153. type SeedTemplate = {
  154. name: string;
  155. description: string;
  156. standard: string;
  157. country: string | null;
  158. severityScale: string;
  159. sections: SeedSection[];
  160. };
  161. const SEED_TEMPLATES: SeedTemplate[] = [
  162. {
  163. name: "Standard multi-point inspection",
  164. description: "The general service check every vehicle gets on the ramp, graded pass / attention / fail.",
  165. standard: "custom",
  166. country: null,
  167. severityScale: "basic",
  168. sections: [
  169. {
  170. name: "Under the hood",
  171. items: [
  172. { name: "Engine oil level and condition", required: true },
  173. { name: "Coolant level and strength" },
  174. { name: "Brake fluid level and moisture content" },
  175. { name: "Power steering and transmission fluid" },
  176. { name: "Drive belts and hoses" },
  177. { name: "Air filter" },
  178. { name: "Battery condition", description: "Terminals, mounting and load test result." },
  179. { name: "Battery load test", inputType: "measurement", unit: "%", minValue: 70, defaultSeverity: "attention" },
  180. ],
  181. },
  182. {
  183. name: "Brakes",
  184. items: [
  185. { name: "Front pad thickness", inputType: "measurement", unit: "mm", minValue: 3, required: true, defaultSeverity: "fail" },
  186. { name: "Rear pad thickness", inputType: "measurement", unit: "mm", minValue: 3, required: true, defaultSeverity: "fail" },
  187. { name: "Discs and drums" },
  188. { name: "Calipers, slides and hardware" },
  189. { name: "Brake lines and hoses" },
  190. { name: "Parking brake operation" },
  191. ],
  192. },
  193. {
  194. name: "Tires and wheels",
  195. items: [
  196. { name: "Tread depth - front left", inputType: "measurement", unit: "mm", minValue: 1.6, required: true, defaultSeverity: "fail" },
  197. { name: "Tread depth - front right", inputType: "measurement", unit: "mm", minValue: 1.6, required: true, defaultSeverity: "fail" },
  198. { name: "Tread depth - rear left", inputType: "measurement", unit: "mm", minValue: 1.6, required: true, defaultSeverity: "fail" },
  199. { name: "Tread depth - rear right", inputType: "measurement", unit: "mm", minValue: 1.6, required: true, defaultSeverity: "fail" },
  200. { name: "Tire condition and age", description: "Sidewall damage, uneven wear, load and speed rating." },
  201. { name: "Wheel and hub condition" },
  202. { name: "Tire pressures set to placard" },
  203. ],
  204. },
  205. {
  206. name: "Steering and suspension",
  207. items: [
  208. { name: "Shock absorbers and struts" },
  209. { name: "Springs and mounts" },
  210. { name: "Ball joints and track rod ends" },
  211. { name: "Wheel bearings" },
  212. { name: "CV boots and driveshafts" },
  213. { name: "Steering rack and linkage" },
  214. ],
  215. },
  216. {
  217. name: "Lights and electrical",
  218. items: [
  219. { name: "Headlights, main and dipped" },
  220. { name: "Brake lights and indicators" },
  221. { name: "Reverse and fog lights" },
  222. { name: "Interior lights and dash warnings" },
  223. { name: "Wipers and washers" },
  224. { name: "Horn" },
  225. ],
  226. },
  227. {
  228. name: "Under the vehicle",
  229. items: [
  230. { name: "Oil and fluid leaks", photoRequired: true },
  231. { name: "Exhaust system and mountings" },
  232. { name: "Fuel lines and tank" },
  233. { name: "Subframe and underbody corrosion" },
  234. { name: "Transmission and differential" },
  235. ],
  236. },
  237. ],
  238. },
  239. {
  240. name: "Periodic technical inspection",
  241. description:
  242. "Subset of the Annex I checklist from Directive 2014/45/EU, graded on the minor / major / dangerous defect scale. Thresholds are the common Union figures - adjust them to your national test.",
  243. standard: "eu-2014-45",
  244. country: null,
  245. severityScale: "eu",
  246. sections: [
  247. {
  248. name: "Identification of the vehicle",
  249. code: "0",
  250. description: "Annex I, item 0. Confirms the vehicle presented matches its papers.",
  251. items: [
  252. { name: "Registration plates", code: "0.1", required: true },
  253. { name: "Vehicle identification / chassis number", code: "0.2", description: "VIN present, legible and matching the registration document.", required: true },
  254. ],
  255. },
  256. {
  257. name: "Braking equipment",
  258. code: "1",
  259. description: "Annex I, item 1. Mechanical condition, then measured performance.",
  260. items: [
  261. { name: "Service brake pedal / hand lever pivot", code: "1.1.1" },
  262. { name: "Pedal / lever condition and travel", code: "1.1.2" },
  263. { name: "Brake servo unit and master cylinder", code: "1.1.10" },
  264. { name: "Rigid brake pipes", code: "1.1.11" },
  265. { name: "Flexible brake hoses", code: "1.1.12" },
  266. { name: "Brake linings and pads", code: "1.1.13", description: "Remaining friction material at the thinnest point.", inputType: "measurement", unit: "mm", minValue: 3, defaultSeverity: "fail" },
  267. { name: "Brake drums and discs", code: "1.1.14" },
  268. { name: "Complete braking system", code: "1.1.21" },
  269. { name: "Service brake efficiency", code: "1.2.2", description: "Braking rate as a percentage of the maximum authorised mass.", inputType: "measurement", unit: "%", minValue: 50, required: true, defaultSeverity: "fail" },
  270. { name: "Service brake imbalance across an axle", code: "1.2.1", inputType: "measurement", unit: "%", maxValue: 30, defaultSeverity: "fail" },
  271. { name: "Parking brake efficiency", code: "1.4.2", inputType: "measurement", unit: "%", minValue: 16, required: true, defaultSeverity: "fail" },
  272. { name: "Anti-lock braking system (ABS)", code: "1.6" },
  273. { name: "Brake fluid", code: "1.8", description: "Contamination and boiling point." },
  274. ],
  275. },
  276. {
  277. name: "Steering",
  278. code: "2",
  279. description: "Annex I, item 2.",
  280. items: [
  281. { name: "Mechanical condition of the steering", code: "2.1" },
  282. { name: "Steering wheel, column and handlebars", code: "2.2" },
  283. { name: "Steering play", code: "2.3", description: "Free movement at the rim before the road wheels respond.", inputType: "measurement", unit: "mm", maxValue: 120, defaultSeverity: "fail" },
  284. { name: "Wheel alignment", code: "2.4" },
  285. { name: "Power steering", code: "2.6" },
  286. ],
  287. },
  288. {
  289. name: "Visibility",
  290. code: "3",
  291. description: "Annex I, item 3.",
  292. items: [
  293. { name: "Field of vision", code: "3.1" },
  294. { name: "Condition of the glass", code: "3.2", description: "Chips and cracks in the swept area of the windscreen." },
  295. { name: "Rear-view mirrors or devices", code: "3.3" },
  296. { name: "Windscreen wipers", code: "3.4" },
  297. { name: "Windscreen washers", code: "3.5" },
  298. ],
  299. },
  300. {
  301. name: "Lamps, reflectors and electrical equipment",
  302. code: "4",
  303. description: "Annex I, item 4.",
  304. items: [
  305. { name: "Headlamps - condition and operation", code: "4.1.1" },
  306. { name: "Headlamp aim", code: "4.1.2", description: "Downward inclination of the dipped beam.", inputType: "measurement", unit: "%", minValue: -2.5, maxValue: -0.5, defaultSeverity: "attention" },
  307. { name: "Position, side marker and daytime running lamps", code: "4.2" },
  308. { name: "Stop lamps", code: "4.3", required: true },
  309. { name: "Direction indicator and hazard warning lamps", code: "4.4" },
  310. { name: "Rear registration plate lamp", code: "4.7" },
  311. { name: "Electrical wiring", code: "4.11" },
  312. { name: "Battery", code: "4.13" },
  313. ],
  314. },
  315. {
  316. name: "Axles, wheels, tires and suspension",
  317. code: "5",
  318. description: "Annex I, item 5. Tread depth is recorded per wheel.",
  319. items: [
  320. { name: "Axles", code: "5.1.1" },
  321. { name: "Stub axles and wheel bearings", code: "5.1.3" },
  322. { name: "Wheels", code: "5.2.1" },
  323. { name: "Tire condition - sidewalls, load and speed rating", code: "5.2.3" },
  324. { name: "Tread depth - front left", code: "5.2.3", inputType: "measurement", unit: "mm", minValue: 1.6, required: true, defaultSeverity: "fail" },
  325. { name: "Tread depth - front right", code: "5.2.3", inputType: "measurement", unit: "mm", minValue: 1.6, required: true, defaultSeverity: "fail" },
  326. { name: "Tread depth - rear left", code: "5.2.3", inputType: "measurement", unit: "mm", minValue: 1.6, required: true, defaultSeverity: "fail" },
  327. { name: "Tread depth - rear right", code: "5.2.3", inputType: "measurement", unit: "mm", minValue: 1.6, required: true, defaultSeverity: "fail" },
  328. { name: "Springs and stabiliser", code: "5.3.1" },
  329. { name: "Shock absorbers", code: "5.3.2" },
  330. { name: "Suspension arms, rods and joints", code: "5.3.4" },
  331. ],
  332. },
  333. {
  334. name: "Chassis and chassis attachments",
  335. code: "6",
  336. description: "Annex I, item 6.",
  337. items: [
  338. { name: "Chassis or frame and attachments", code: "6.1.1" },
  339. { name: "Exhaust pipes and silencer", code: "6.1.2" },
  340. { name: "Fuel tank and pipes", code: "6.1.3" },
  341. { name: "Coupling device and towing equipment", code: "6.1.7" },
  342. { name: "Cab and bodywork condition", code: "6.2.1" },
  343. { name: "Doors and door catches", code: "6.2.3" },
  344. { name: "Driver seat and seats", code: "6.2.5" },
  345. { name: "Mudguards and spray suppression", code: "6.2.11" },
  346. ],
  347. },
  348. {
  349. name: "Other equipment",
  350. code: "7",
  351. description: "Annex I, item 7. Some checks apply only to certain vehicle categories.",
  352. items: [
  353. { name: "Safety belts, buckles and restraint systems", code: "7.1", required: true },
  354. { name: "Locks and anti-theft device", code: "7.3" },
  355. { name: "Audible warning device", code: "7.7" },
  356. { name: "Speedometer", code: "7.8" },
  357. { name: "Odometer reading", code: "7.11", description: "Reading at the time of the test. Annex IV requires this on the certificate.", inputType: "measurement", unit: "km", required: true },
  358. ],
  359. },
  360. ],
  361. },
  362. {
  363. name: "Pre-purchase inspection",
  364. description: "What a buyer wants to know before the money moves: condition, history and anything about to need spending on.",
  365. standard: "custom",
  366. country: null,
  367. severityScale: "basic",
  368. sections: [
  369. {
  370. name: "Paperwork and identity",
  371. items: [
  372. { name: "VIN matches the documents", required: true },
  373. { name: "Service history present and consistent" },
  374. { name: "Odometer reading plausible against wear", inputType: "measurement", unit: "mi", required: true },
  375. { name: "Outstanding recalls" },
  376. ],
  377. },
  378. {
  379. name: "Body and paint",
  380. items: [
  381. { name: "Panel gaps and alignment", photoRequired: true },
  382. { name: "Paint depth and repair evidence" },
  383. { name: "Corrosion, sills and arches" },
  384. { name: "Glass, lamps and trim" },
  385. ],
  386. },
  387. {
  388. name: "Mechanical",
  389. items: [
  390. { name: "Cold start and idle quality" },
  391. { name: "Oil condition and leaks" },
  392. { name: "Cooling system and head gasket check" },
  393. { name: "Transmission and clutch under load" },
  394. { name: "Diagnostic scan - stored and pending codes" },
  395. ],
  396. },
  397. {
  398. name: "Road test",
  399. items: [
  400. { name: "Braking under load" },
  401. { name: "Steering and tracking" },
  402. { name: "Suspension noise over bumps" },
  403. { name: "Driver assistance systems" },
  404. ],
  405. },
  406. ],
  407. },
  408. ];
  409. function downloadFile(url: string, dest: string): Promise<void> {
  410. return new Promise((resolve, reject) => {
  411. const dir = path.dirname(dest);
  412. if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  413. const follow = (u: string, r = 0) => {
  414. if (r > 5) return reject(new Error("Too many redirects"));
  415. const mod = u.startsWith("https") ? https : http;
  416. mod.get(u, { headers: { "User-Agent": "Seed/1.0" } }, (res) => {
  417. if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) return follow(res.headers.location, r + 1);
  418. if (res.statusCode !== 200) return reject(new Error(`HTTP ${res.statusCode}`));
  419. const f = fs.createWriteStream(dest);
  420. res.pipe(f);
  421. f.on("finish", () => { f.close(); resolve(); });
  422. f.on("error", (e) => { fs.unlinkSync(dest); reject(e); });
  423. }).on("error", reject);
  424. };
  425. follow(url);
  426. });
  427. }
  428. function img(cat: string, file: string) { return `/api/files/${ORG_ID}/${cat}/${file}`; }
  429. async function provisionDemoAccount() {
  430. console.log("Provisioning demo user + organization...");
  431. // Owner user (idempotent — safe to re-run)
  432. await prisma.user.upsert({
  433. where: { id: USER_ID },
  434. create: {
  435. id: USER_ID,
  436. email: DEMO_EMAIL,
  437. name: "Demo Owner",
  438. emailVerified: true,
  439. termsAcceptedAt: new Date(),
  440. },
  441. update: { email: DEMO_EMAIL, name: "Demo Owner" },
  442. });
  443. // Credential account — wipe + recreate so the password always matches env
  444. const hashedPassword = hashPassword(DEMO_PASSWORD);
  445. await prisma.account.deleteMany({ where: { userId: USER_ID, providerId: "credential" } });
  446. await prisma.account.create({
  447. data: { accountId: USER_ID, providerId: "credential", userId: USER_ID, password: hashedPassword },
  448. });
  449. // Organization
  450. await prisma.organization.upsert({
  451. where: { id: ORG_ID },
  452. create: { id: ORG_ID, name: DEMO_ORG_NAME, portalSlug: "demo-workshop" },
  453. update: { name: DEMO_ORG_NAME, portalSlug: "demo-workshop" },
  454. });
  455. // Belt and braces alongside the demoGuard on org creation: purge any
  456. // foreign organizations so the reset always converges on a single org.
  457. // Org-scoped rows go with them via ON DELETE CASCADE, and stale
  458. // active-org cookies fall back to the demo org membership.
  459. // inspections.templateId is ON DELETE RESTRICT, so the cascade cannot
  460. // resolve templates and inspections in one statement; clear inspections
  461. // first. (The only other RESTRICT in the schema, subscriptions.planId,
  462. // guards global plans the purge never deletes.)
  463. await prisma.inspection.deleteMany({
  464. where: { organizationId: { not: ORG_ID } },
  465. });
  466. const foreignOrgs = await prisma.organization.deleteMany({
  467. where: { id: { not: ORG_ID } },
  468. });
  469. if (foreignOrgs.count > 0) {
  470. console.log(` Removed ${foreignOrgs.count} visitor-created organization(s).`);
  471. }
  472. // Owner membership
  473. await prisma.organizationMember.upsert({
  474. where: { userId_organizationId: { userId: USER_ID, organizationId: ORG_ID } },
  475. create: { userId: USER_ID, organizationId: ORG_ID, role: "owner" },
  476. update: { role: "owner" },
  477. });
  478. console.log(` Owner: ${DEMO_EMAIL} (org: ${DEMO_ORG_NAME})\n`);
  479. }
  480. /**
  481. * Remove files a demo visitor uploaded, while preserving the seed's own cached
  482. * vehicle images. `prisma/seed-assets/vehicles/` ships empty, so those images
  483. * were fetched from Unsplash once and cached in the data volume — deleting them
  484. * would trigger a full re-download on every 3-hourly reset.
  485. */
  486. function cleanupUploads() {
  487. const orgRoot = path.join(DATA_ROOT, "uploads", ORG_ID);
  488. if (!fs.existsSync(orgRoot)) return;
  489. const keep = new Set(Object.keys(vehicleImages));
  490. let removed = 0;
  491. const walk = (dir: string) => {
  492. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  493. const full = path.join(dir, entry.name);
  494. if (entry.isDirectory()) {
  495. walk(full);
  496. // Drop directories that are now empty (e.g. documents/, diagnostics/).
  497. if (fs.readdirSync(full).length === 0) fs.rmdirSync(full);
  498. continue;
  499. }
  500. // Preserve the cached seed images living in uploads/<org>/vehicles/.
  501. if (dir === UPLOAD_DIR && keep.has(entry.name)) continue;
  502. fs.unlinkSync(full);
  503. removed++;
  504. }
  505. };
  506. try {
  507. walk(orgRoot);
  508. console.log(` Removed ${removed} visitor-uploaded file(s).`);
  509. } catch (err) {
  510. console.warn(" Upload cleanup failed:", err);
  511. }
  512. }
  513. async function cleanup() {
  514. console.log("Cleaning existing data...");
  515. // Config/state a visitor can change that would otherwise survive every reset:
  516. // branding, invoice templates, webhooks pointing at external URLs, schedules,
  517. // custom presets. Deleting a Webhook cascades its WebhookDelivery rows.
  518. await prisma.webhook.deleteMany({ where: { organizationId: ORG_ID } });
  519. await prisma.reportSchedule.deleteMany({ where: { organizationId: ORG_ID } });
  520. // Customer and vehicle are both SetNull here, so these outlive the core
  521. // wipe below and have to go explicitly.
  522. await prisma.scheduledMessage.deleteMany({ where: { organizationId: ORG_ID } });
  523. // organizationId is a plain column on these two, so no cascade reaches them.
  524. await prisma.dashboardWidget.deleteMany({ where: { organizationId: ORG_ID } });
  525. await prisma.serviceRequest.deleteMany({ where: { organizationId: ORG_ID } });
  526. await prisma.teamInvitation.deleteMany({ where: { organizationId: ORG_ID } });
  527. await prisma.laborPreset.deleteMany({ where: { organizationId: ORG_ID } });
  528. // Inspection.template is a required relation with no onDelete, so Postgres
  529. // restricts the template delete while any inspection still points at it.
  530. // Vehicle deletion further down would cascade these away, but that runs too
  531. // late — drop them here first. InspectionItem and InspectionQuoteRequest
  532. // cascade from Inspection, and Quote.inspectionId is SetNull.
  533. await prisma.inspection.deleteMany({ where: { organizationId: ORG_ID } });
  534. await prisma.inspectionTemplate.deleteMany({ where: { organizationId: ORG_ID } });
  535. await prisma.customFieldDefinition.deleteMany({ where: { organizationId: ORG_ID } });
  536. await prisma.subscription.deleteMany({ where: { organizationId: ORG_ID } });
  537. // Wipes branding, logo, invoice layout, localization, tax config. The
  538. // maintenance.* keys are re-upserted later in the seed.
  539. await prisma.appSetting.deleteMany({ where: { organizationId: ORG_ID } });
  540. // Transient/accumulating records.
  541. await prisma.aiChat.deleteMany({ where: { organizationId: ORG_ID } });
  542. await prisma.notification.deleteMany({ where: { organizationId: ORG_ID } });
  543. await prisma.telegramMessage.deleteMany({ where: { organizationId: ORG_ID } });
  544. await prisma.customerMagicLink.deleteMany({ where: { organizationId: ORG_ID } });
  545. await prisma.customerSmsCode.deleteMany({ where: { organizationId: ORG_ID } });
  546. await prisma.auditLog.deleteMany({ where: { organizationId: ORG_ID } });
  547. // Any team member a visitor added — but never the demo owner, which
  548. // provisionDemoAccount() upserts just before this runs.
  549. await prisma.organizationMember.deleteMany({
  550. where: { organizationId: ORG_ID, userId: { not: USER_ID } },
  551. });
  552. // Custom roles; OrganizationMember.roleId is onDelete: SetNull, so safe.
  553. await prisma.role.deleteMany({ where: { organizationId: ORG_ID } });
  554. // Core CRUD data. ServiceRequest, CustomerSession and StatusReport cascade
  555. // from Vehicle/Customer/ServiceRecord. Inspections are already gone above.
  556. await prisma.technician.deleteMany({ where: { organizationId: ORG_ID } });
  557. await prisma.smsMessage.deleteMany({ where: { organizationId: ORG_ID } });
  558. await prisma.quote.deleteMany({ where: { organizationId: ORG_ID } });
  559. await prisma.serviceRecord.deleteMany({ where: { vehicle: { organizationId: ORG_ID } } });
  560. await prisma.fuelLog.deleteMany({ where: { vehicle: { organizationId: ORG_ID } } });
  561. // A reminder can hang off a vehicle, a customer or nothing at all, so the
  562. // vehicle cascade alone would leave workshop-level ones behind to pile up
  563. // on every reset. organizationId covers all three; the vehicle clause stays
  564. // for any older row that predates it.
  565. await prisma.reminder.deleteMany({
  566. where: { OR: [{ organizationId: ORG_ID }, { vehicle: { organizationId: ORG_ID } }] },
  567. });
  568. await prisma.note.deleteMany({ where: { vehicle: { organizationId: ORG_ID } } });
  569. await prisma.vehicle.deleteMany({ where: { organizationId: ORG_ID } });
  570. await prisma.customer.deleteMany({ where: { organizationId: ORG_ID } });
  571. await prisma.inventoryPart.deleteMany({ where: { organizationId: ORG_ID } });
  572. cleanupUploads();
  573. console.log(" Done.\n");
  574. }
  575. async function seed() {
  576. console.log("\nStarting seed...\n");
  577. await provisionDemoAccount();
  578. await cleanup();
  579. // Populate vehicle images: prefer bundled assets → fall back to cached copy
  580. // in data volume → fall back to live download.
  581. console.log("Populating vehicle images...");
  582. if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR, { recursive: true });
  583. for (const [file, url] of Object.entries(vehicleImages)) {
  584. const dest = path.join(UPLOAD_DIR, file);
  585. const bundled = path.join(BUNDLED_IMAGE_DIR, file);
  586. if (fs.existsSync(bundled)) {
  587. fs.copyFileSync(bundled, dest);
  588. console.log(` [bundled] ${file}`);
  589. continue;
  590. }
  591. if (fs.existsSync(dest)) { console.log(` [cached] ${file}`); continue; }
  592. try { await downloadFile(url, dest); console.log(` [downloaded] ${file}`); }
  593. catch { console.warn(` [fail] ${file}`); }
  594. }
  595. // -- Workshop settings --
  596. // cleanup() wipes every AppSetting, so without this the demo would run with
  597. // no address, no currency and no invoice numbering - the settings pages and
  598. // every invoice PDF would render blank.
  599. console.log("\nApplying workshop settings...");
  600. const settings: Record<string, string> = {
  601. "workshop.address": "1450 Foundry Road, Denver, CO 80216",
  602. "workshop.phone": "+1 (555) 555-0100",
  603. "workshop.email": "service@egelandauto.example.com",
  604. "workshop.serviceType": "automotive",
  605. "workshop.unitSystem": "imperial",
  606. "workshop.defaultLaborRate": "110",
  607. "workshop.defaultTechnician": "Jake Wilson",
  608. "workshop.taxEnabled": "true",
  609. "workshop.taxInclusive": "false",
  610. "workshop.taxLabel": "Sales Tax",
  611. "workshop.defaultTaxRate": "8",
  612. "workshop.currencyCode": "USD",
  613. "workshop.currencySymbol": "$",
  614. "workshop.currencyFormat": "symbol",
  615. "workshop.invoicePrefix": "{year}-",
  616. "workshop.invoiceStartNumber": "1001",
  617. "workshop.quotePrefix": "Q-{year}-",
  618. "workshop.quoteValidDays": "30",
  619. "workshop.dateFormat": "MM/dd/yyyy",
  620. "workshop.timeFormat": "12h",
  621. "invoice.dueDays": "14",
  622. "invoice.paymentTerms": "Net 14 days from invoice date.",
  623. "invoice.footerNote": "Thank you for your business. All work carries a 12-month parts and labor warranty.",
  624. "invoice.orgNumber": "US-84-2210997",
  625. "invoice.bankAccount": "Front Range Bank · 1120 4455 8890",
  626. "invoice.showOrgNumber": "true",
  627. "invoice.showBankAccount": "true",
  628. "email.fromName": "Egeland Auto",
  629. "defaultWarrantyMonths": "12",
  630. "defaultWarrantyMileage": "12000",
  631. "workboard.weekStartDay": "1",
  632. "workboard.workDayStart": "07:00",
  633. "workboard.workDayEnd": "17:00",
  634. "inventory.lowStockAlerts.enabled": "true",
  635. "inventory.lowStockAlerts.inApp": "true",
  636. "parts.defaultMarkupPercent": "35",
  637. "portal.enabled": "true",
  638. "portal.description": "Book a service, follow your repair and read your invoices online.",
  639. "portal.hours": "Mon-Fri 07:00-17:00 · Sat 09:00-13:00 · Closed Sunday",
  640. // Placeholder provider config so the messages and Telegram pages render as
  641. // a configured workshop rather than an empty setup prompt. The credentials
  642. // are deliberately not real, and nothing can send from the demo anyway:
  643. // assertOutboundAllowed() in lib/email, lib/sms and lib/telegram refuses
  644. // every outbound call while DEMO_MODE=true.
  645. "sms.provider": "twilio",
  646. "sms.phoneNumber": "+15555550100",
  647. "sms.twilio.accountSid": "ACdemo0000000000000000000000000000",
  648. "sms.twilio.authToken": "demo-token-not-a-real-credential",
  649. "telegram.botToken": "0000000000:DEMO-not-a-real-bot-token",
  650. "telegram.botUsername": "EgelandAutoDemoBot",
  651. };
  652. await Promise.all(
  653. Object.entries(settings).map(([key, value]) =>
  654. prisma.appSetting.upsert({
  655. where: { organizationId_key: { organizationId: ORG_ID, key } },
  656. create: { organizationId: ORG_ID, key, value, userId: USER_ID },
  657. update: { value },
  658. }),
  659. ),
  660. );
  661. console.log(` Applied ${Object.keys(settings).length} settings`);
  662. // -- Customers (20) --
  663. console.log("\nCreating customers...");
  664. const customers = await Promise.all([
  665. /* 0 */ prisma.customer.create({ data: { customerNumber: "1001", name: "Summit Construction Inc.", email: "fleet@summitconstruction.example.com", phone: "+1 (555) 555-0101", address: "742 Industrial Pkwy, Denver, CO 80216", company: "Summit Construction Inc.", notes: "Major fleet customer. 15 vehicles + heavy machinery. Net-30 terms.", userId: USER_ID, organizationId: ORG_ID } }),
  666. /* 1 */ prisma.customer.create({ data: { customerNumber: "1002", name: "James Mitchell", email: "james.mitchell@example.com", phone: "+1 (555) 555-0102", address: "1824 Maple Ave, Austin, TX 78701", notes: "Personal vehicles. Prefers synthetic oil.", userId: USER_ID, organizationId: ORG_ID } }),
  667. /* 2 */ prisma.customer.create({ data: { customerNumber: "1003", name: "Pacific Freight Lines", email: "service@pacificfreight.example.com", phone: "+1 (555) 555-0103", address: "9100 Logistics Blvd, Portland, OR 97201", company: "Pacific Freight Lines LLC", notes: "Long-haul trucking company. 8 semi-trucks. Priority service.", userId: USER_ID, organizationId: ORG_ID } }),
  668. /* 3 */ prisma.customer.create({ data: { customerNumber: "1004", name: "Sarah Coleman", email: "sarah.coleman@example.com", phone: "+1 (555) 555-0104", address: "567 Oak Street, Nashville, TN 37203", notes: "BMW and Porsche owner. Always requests OEM parts.", userId: USER_ID, organizationId: ORG_ID } }),
  669. /* 4 */ prisma.customer.create({ data: { customerNumber: "1005", name: "Metro City Services", email: "fleet@metrocityservices.example.com", phone: "+1 (555) 555-0105", address: "100 City Hall Plaza, Boston, MA 02108", company: "Metro City Services", notes: "Municipal fleet contract. Quarterly invoicing. Purchase order required.", userId: USER_ID, organizationId: ORG_ID } }),
  670. /* 5 */ prisma.customer.create({ data: { customerNumber: "1006", name: "Ryan Parker", email: "ryan.parker@example.com", phone: "+1 (555) 555-0106", address: "2250 Cedar Lane, Seattle, WA 98101", notes: "Tesla and Subaru owner. Tech-savvy.", userId: USER_ID, organizationId: ORG_ID } }),
  671. /* 6 */ prisma.customer.create({ data: { customerNumber: "1007", name: "Ironclad Equipment Co.", email: "parts@ironcladequip.example.com", phone: "+1 (555) 555-0107", address: "4500 Heavy Machinery Rd, Houston, TX 77001", company: "Ironclad Equipment Co.", notes: "Heavy equipment dealer. Sends us overflow work. Good referral source.", userId: USER_ID, organizationId: ORG_ID } }),
  672. /* 7 */ prisma.customer.create({ data: { customerNumber: "1008", name: "David Chen", email: "david.chen@example.com", phone: "+1 (555) 555-0108", address: "890 Pine Street, San Francisco, CA 94102", notes: "Audi and VW owner. Referred by James Mitchell.", userId: USER_ID, organizationId: ORG_ID } }),
  673. /* 8 */ prisma.customer.create({ data: { customerNumber: "1009", name: "Ridgeline Excavation LLC", email: "ops@ridgelineexcavation.example.com", phone: "+1 (555) 555-0109", address: "1200 Quarry Rd, Salt Lake City, UT 84101", company: "Ridgeline Excavation LLC", notes: "5 excavators, 2 wheel loaders, 3 dump trucks. Monthly maintenance contract.", userId: USER_ID, organizationId: ORG_ID } }),
  674. /* 9 */ prisma.customer.create({ data: { customerNumber: "1010", name: "Amanda Foster", email: "amanda.foster@example.com", phone: "+1 (555) 555-0110", address: "334 Birch Drive, Charlotte, NC 28202", notes: "Honda Civic owner. Budget-conscious, prefers aftermarket.", userId: USER_ID, organizationId: ORG_ID } }),
  675. /* 10 */ prisma.customer.create({ data: { customerNumber: "1011", name: "Prairie Farms Co-op", email: "maintenance@prairiefarms.example.com", phone: "+1 (555) 555-0111", address: "Route 66 Farm Road, Omaha, NE 68101", company: "Prairie Farms Co-op", notes: "Agricultural equipment. Tractors, harvesters. Seasonal peaks spring/fall.", userId: USER_ID, organizationId: ORG_ID } }),
  676. /* 11 */ prisma.customer.create({ data: { customerNumber: "1012", name: "Mike Thompson", email: "mike.thompson@example.com", phone: "+1 (555) 555-0112", address: "445 Elm Court, Minneapolis, MN 55401", notes: "Ford F-150 and Jeep owner. Off-road enthusiast.", userId: USER_ID, organizationId: ORG_ID } }),
  677. /* 12 */ prisma.customer.create({ data: { customerNumber: "1013", name: "Apex Contractors Group", email: "service@apexcontractors.example.com", phone: "+1 (555) 555-0113", address: "2800 Builder's Row, Atlanta, GA 30301", company: "Apex Contractors Group", notes: "Small contractor. 2 excavators, 1 dump truck, 2 vans.", userId: USER_ID, organizationId: ORG_ID } }),
  678. /* 13 */ prisma.customer.create({ data: { customerNumber: "1014", name: "Jessica Rivera", email: "jessica.r@example.com", phone: "+1 (555) 555-0114", address: "1100 Sunset Blvd, Miami, FL 33101", notes: "Tesla Model Y owner. Referred by Ryan Parker.", userId: USER_ID, organizationId: ORG_ID } }),
  679. /* 14 */ prisma.customer.create({ data: { customerNumber: "1015", name: "Titan Building Corp.", email: "projects@titanbuildingcorp.example.com", phone: "+1 (555) 555-0115", address: "5000 Commerce Dr, Dallas, TX 75201", company: "Titan Building Corp.", notes: "Large construction firm. 20+ pieces of equipment. Net-45 terms.", userId: USER_ID, organizationId: ORG_ID } }),
  680. /* 15 */ prisma.customer.create({ data: { customerNumber: "1016", name: "Kevin O'Brien", email: "kevin.obrien@example.com", phone: "+1 (555) 555-0116", address: "678 Market Street, Philadelphia, PA 19101", notes: "Mercedes Sprinter van for his catering business.", userId: USER_ID, organizationId: ORG_ID } }),
  681. /* 16 */ prisma.customer.create({ data: { customerNumber: "1017", name: "Greenfield Waste Management", email: "dispatch@greenfieldwaste.example.com", phone: "+1 (555) 555-0117", address: "7700 Recycling Way, Phoenix, AZ 85001", company: "Greenfield Waste Management", notes: "Waste management fleet. 12 trucks. Quarterly PM schedule.", userId: USER_ID, organizationId: ORG_ID } }),
  682. /* 17 */ prisma.customer.create({ data: { customerNumber: "1018", name: "Robert Hughes", email: "robert.hughes@example.com", phone: "+1 (555) 555-0118", address: "2100 Lakeview Ave, Detroit, MI 48201", notes: "Ram truck and VW Golf owner. Weekend car guy.", userId: USER_ID, organizationId: ORG_ID } }),
  683. /* 17 */ prisma.customer.create({ data: { customerNumber: "1019", name: "Heartland Grain Co.", email: "ops@heartlandgrain.example.com", phone: "+1 (555) 555-0119", address: "4400 Harvest Rd, Des Moines, IA 50301", company: "Heartland Grain Co.", notes: "Large-scale farming. 6 tractors, 2 combines. Seasonal rush spring and fall.", userId: USER_ID, organizationId: ORG_ID } }),
  684. /* 19 */ prisma.customer.create({ data: { customerNumber: "1020", name: "Lisa Martinez", email: "lisa.martinez@example.com", phone: "+1 (555) 555-0120", address: "425 Ranch Road, San Antonio, TX 78201", notes: "Chevy Silverado and Toyota Tacoma. Ranch use.", userId: USER_ID, organizationId: ORG_ID } }),
  685. // The one address on a domain we own, for checking a send end to end
  686. // without it ever leaving Torqvoice. Everyone else sits on example.com.
  687. /* 20 */ prisma.customer.create({ data: { customerNumber: "1021", name: "Jennifer Hayes", email: "jennifer@torqvoice.com", phone: "+1 (555) 555-0121", address: "88 Copper Lane, Boulder, CO 80301", notes: "Test account for message delivery checks.", userId: USER_ID, organizationId: ORG_ID } }),
  688. ]);
  689. console.log(` Created ${customers.length} customers`);
  690. // -- Vehicles (40) --
  691. console.log("\nCreating vehicles...");
  692. const vehicles = await Promise.all([
  693. // === Cars (0-17) ===
  694. /* 0 */ prisma.vehicle.create({ data: { make: "Toyota", model: "Camry XSE", year: 2023, vin: "4T1K61AK5PU083241", licensePlate: "TX-8821", color: "Midnight Black", mileage: 18500, fuelType: "gasoline", transmission: "automatic", engineSize: "2.5L", purchaseDate: new Date("2023-03-15"), purchasePrice: 35500, imageUrl: img("vehicles","toyota-camry.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[1].id } }),
  695. /* 1 */ prisma.vehicle.create({ data: { make: "Ford", model: "F-150 Lariat", year: 2022, vin: "1FTFW1E88NFC12345", licensePlate: "CO-4455", color: "Oxford White", mileage: 42300, fuelType: "gasoline", transmission: "automatic", engineSize: "3.5L EcoBoost", purchaseDate: new Date("2022-06-20"), purchasePrice: 58000, imageUrl: img("vehicles","ford-f150-white.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[0].id } }),
  696. /* 2 */ prisma.vehicle.create({ data: { make: "Ford", model: "F-150 XLT", year: 2021, vin: "1FTEW1EP5MKD56789", licensePlate: "MN-7766", color: "Carbonized Gray", mileage: 55000, fuelType: "gasoline", transmission: "automatic", engineSize: "2.7L EcoBoost", purchaseDate: new Date("2021-04-10"), purchasePrice: 45000, imageUrl: img("vehicles","ford-f150-grey.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[11].id } }),
  697. /* 3 */ prisma.vehicle.create({ data: { make: "Ford", model: "F-150 Platinum", year: 2024, vin: "1FTFW1E55RFA98765", licensePlate: "TX-1199", color: "Agate Black", mileage: 12000, fuelType: "gasoline", transmission: "automatic", engineSize: "3.5L EcoBoost V6", purchaseDate: new Date("2024-02-14"), purchasePrice: 72000, imageUrl: img("vehicles","ford-f150-black.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[4].id } }),
  698. /* 4 */ prisma.vehicle.create({ data: { make: "BMW", model: "330i xDrive", year: 2021, vin: "WBA5R1C55M7B98765", licensePlate: "TN-2233", color: "Alpine White", mileage: 55200, fuelType: "gasoline", transmission: "automatic", engineSize: "2.0L Turbo", purchaseDate: new Date("2021-01-10"), purchasePrice: 46000, imageUrl: img("vehicles","bmw-3series.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[3].id } }),
  699. /* 5 */ prisma.vehicle.create({ data: { make: "Honda", model: "Civic Sport", year: 2020, vin: "2HGFC2F63LH567890", licensePlate: "NC-6677", color: "Rallye Red", mileage: 67800, fuelType: "gasoline", transmission: "manual", engineSize: "2.0L", purchaseDate: new Date("2020-08-05"), purchasePrice: 26000, imageUrl: img("vehicles","honda-civic.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[9].id } }),
  700. /* 6 */ prisma.vehicle.create({ data: { make: "Tesla", model: "Model 3 Long Range", year: 2024, vin: "5YJ3E1EA3RF123456", licensePlate: "WA-9901", color: "Pearl White", mileage: 8200, fuelType: "electric", transmission: "automatic", engineSize: "Dual Motor", purchaseDate: new Date("2024-01-20"), purchasePrice: 47000, imageUrl: img("vehicles","tesla-model3.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[5].id } }),
  701. /* 7 */ prisma.vehicle.create({ data: { make: "Tesla", model: "Model Y Long Range", year: 2025, vin: "7SAYGDEE3SF123456", licensePlate: "FL-7720", color: "Quicksilver", mileage: 3200, fuelType: "electric", transmission: "automatic", engineSize: "Dual Motor AWD", purchaseDate: new Date("2025-06-10"), purchasePrice: 52000, imageUrl: img("vehicles","tesla-modely.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[13].id } }),
  702. /* 8 */ prisma.vehicle.create({ data: { make: "Chevrolet", model: "Silverado 2500HD", year: 2019, vin: "1GC4YREY5KF234567", licensePlate: "TX-3344", color: "Shadow Gray", mileage: 98400, fuelType: "diesel", transmission: "automatic", engineSize: "6.6L Duramax", purchaseDate: new Date("2019-04-12"), purchasePrice: 52000, imageUrl: img("vehicles","chevy-silverado.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[19].id } }),
  703. /* 9 */ prisma.vehicle.create({ data: { make: "Mercedes-Benz", model: "Sprinter 316 CDI", year: 2022, vin: "WDB9066331S789012", licensePlate: "PA-1122", color: "Arctic White", mileage: 35600, fuelType: "diesel", transmission: "automatic", engineSize: "2.1L CDI", purchaseDate: new Date("2022-09-01"), purchasePrice: 55000, imageUrl: img("vehicles","mercedes-sprinter.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[15].id } }),
  704. /* 10 */ prisma.vehicle.create({ data: { make: "Audi", model: "A4 Quattro", year: 2023, vin: "WAUDNAF44PN345678", licensePlate: "CA-5566", color: "Navarra Blue", mileage: 22100, fuelType: "gasoline", transmission: "automatic", engineSize: "2.0L TFSI", purchaseDate: new Date("2023-07-14"), purchasePrice: 45000, imageUrl: img("vehicles","audi-a4.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[7].id } }),
  705. /* 11 */ prisma.vehicle.create({ data: { make: "Jeep", model: "Wrangler Rubicon", year: 2022, vin: "1C4HJXFN3NW234567", licensePlate: "CO-8800", color: "Black", mileage: 28500, fuelType: "gasoline", transmission: "manual", engineSize: "3.6L Pentastar V6", purchaseDate: new Date("2022-05-18"), purchasePrice: 52000, imageUrl: img("vehicles","jeep-wrangler.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[11].id } }),
  706. /* 12 */ prisma.vehicle.create({ data: { make: "Jeep", model: "Wrangler Sport S", year: 2023, vin: "1C4GJXAG4PW345678", licensePlate: "GA-5511", color: "Punk'n Orange", mileage: 15200, fuelType: "gasoline", transmission: "automatic", engineSize: "2.0L Turbo", purchaseDate: new Date("2023-08-22"), purchasePrice: 42000, imageUrl: img("vehicles","jeep-wrangler-orange.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[12].id } }),
  707. /* 13 */ prisma.vehicle.create({ data: { make: "Porsche", model: "911 Carrera S", year: 2022, vin: "WP0AB2A94NS234567", licensePlate: "TN-9911", color: "White", mileage: 12800, fuelType: "gasoline", transmission: "automatic", engineSize: "3.0L Twin-Turbo Flat-6", purchaseDate: new Date("2022-11-05"), purchasePrice: 128000, imageUrl: img("vehicles","porsche-911.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[3].id } }),
  708. /* 14 */ prisma.vehicle.create({ data: { make: "Volkswagen", model: "Golf GTI", year: 2021, vin: "3VW6T7AU5MM123456", licensePlate: "CA-4422", color: "Tornado Red", mileage: 38500, fuelType: "gasoline", transmission: "manual", engineSize: "2.0L TSI", purchaseDate: new Date("2021-06-15"), purchasePrice: 32000, imageUrl: img("vehicles","vw-golf-gti-red.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[7].id } }),
  709. /* 15 */ prisma.vehicle.create({ data: { make: "Ram", model: "1500 Laramie", year: 2023, vin: "1C6SRFJT4PN456789", licensePlate: "MI-3322", color: "Billet Silver", mileage: 19800, fuelType: "gasoline", transmission: "automatic", engineSize: "5.7L HEMI V8", purchaseDate: new Date("2023-03-28"), purchasePrice: 62000, imageUrl: img("vehicles","ram-1500.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[17].id } }),
  710. /* 16 */ prisma.vehicle.create({ data: { make: "Toyota", model: "Tacoma TRD Off-Road", year: 2022, vin: "3TMCZ5AN5NM567890", licensePlate: "TX-6644", color: "Super White", mileage: 31200, fuelType: "gasoline", transmission: "automatic", engineSize: "3.5L V6", purchaseDate: new Date("2022-10-01"), purchasePrice: 42000, imageUrl: img("vehicles","toyota-tacoma.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[19].id } }),
  711. // === Trucks (17-21) ===
  712. /* 17 */ prisma.vehicle.create({ data: { make: "Kenworth", model: "T680 Next Gen", year: 2022, vin: "1XKYD49X4NJ456789", licensePlate: "OR-8899", color: "Red", mileage: 185000, fuelType: "diesel", transmission: "automatic", engineSize: "12.9L PACCAR MX-13", purchaseDate: new Date("2022-02-15"), purchasePrice: 175000, imageUrl: img("vehicles","kenworth-t680.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[2].id } }),
  713. /* 18 */ prisma.vehicle.create({ data: { make: "Volvo", model: "FH 640", year: 2023, vin: "YV2RT40A5PB567890", licensePlate: "IL-5567", color: "Blue", mileage: 92000, fuelType: "diesel", transmission: "automatic", engineSize: "12.8L D13TC", purchaseDate: new Date("2023-01-10"), purchasePrice: 210000, imageUrl: img("vehicles","volvo-fh640.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[2].id } }),
  714. /* 19 */ prisma.vehicle.create({ data: { make: "Mack", model: "Granite GR64F", year: 2020, vin: "1M2AX04C5LM012345", licensePlate: "AZ-9901", color: "Yellow", mileage: 156000, fuelType: "diesel", transmission: "automatic", engineSize: "13.0L MP7", purchaseDate: new Date("2020-11-08"), purchasePrice: 140000, imageUrl: img("vehicles","mack-granite.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[0].id } }),
  715. /* 20 */ prisma.vehicle.create({ data: { make: "Peterbilt", model: "567 Mixer", year: 2021, vin: "1NPCD49X1MD678901", licensePlate: "TX-7788", color: "White/Blue", mileage: 68000, fuelType: "diesel", transmission: "automatic", engineSize: "10.8L PACCAR MX-11", purchaseDate: new Date("2021-07-20"), purchasePrice: 165000, imageUrl: img("vehicles","concrete-mixer.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[14].id } }),
  716. /* 21 */ prisma.vehicle.create({ data: { make: "Kenworth", model: "T880 Dump Truck", year: 2022, vin: "1NKZX4TX8NJ789012", licensePlate: "CO-5544", color: "Yellow", mileage: 82000, fuelType: "diesel", transmission: "automatic", engineSize: "12.9L PACCAR MX-13", purchaseDate: new Date("2022-04-15"), purchasePrice: 185000, imageUrl: img("vehicles","dump-truck.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[8].id } }),
  717. // === Tractors (22-28) ===
  718. /* 22 */ prisma.vehicle.create({ data: { make: "John Deere", model: "6R 250", year: 2022, vin: "1L06250RCNR012345", licensePlate: "N/A", color: "John Deere Green", mileage: 2800, fuelType: "diesel", transmission: "powershift", engineSize: "6.8L PowerTech PVS", purchaseDate: new Date("2022-03-01"), purchasePrice: 185000, imageUrl: img("vehicles","john-deere-6r.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[10].id } }),
  719. /* 23 */ prisma.vehicle.create({ data: { make: "Fendt", model: "942 Vario", year: 2023, vin: "FEN942VARIO3N56789", licensePlate: "N/A", color: "Fendt Green", mileage: 1200, fuelType: "diesel", transmission: "CVT (Vario)", engineSize: "12.4L MAN D2676", purchaseDate: new Date("2023-06-15"), purchasePrice: 420000, imageUrl: img("vehicles","fendt-942.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[18].id } }),
  720. /* 24 */ prisma.vehicle.create({ data: { make: "Massey Ferguson", model: "8S.265", year: 2021, vin: "MF8S265A1LM234567", licensePlate: "N/A", color: "Red", mileage: 3600, fuelType: "diesel", transmission: "Dyna-VT CVT", engineSize: "8.4L AGCO Power", purchaseDate: new Date("2021-09-10"), purchasePrice: 245000, imageUrl: img("vehicles","massey-ferguson.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[10].id } }),
  721. /* 25 */ prisma.vehicle.create({ data: { make: "John Deere", model: "8R 410", year: 2024, vin: "1RW8410RPEN345678", licensePlate: "N/A", color: "Green/Yellow", mileage: 800, fuelType: "diesel", transmission: "e23 PowerShift", engineSize: "9.0L PowerTech PSS", purchaseDate: new Date("2024-01-20"), purchasePrice: 380000, imageUrl: img("vehicles","tractor-wheat.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[18].id } }),
  722. /* 26 */ prisma.vehicle.create({ data: { make: "New Holland", model: "T7.315", year: 2022, vin: "NH7315ACLM456789", licensePlate: "N/A", color: "New Holland Blue", mileage: 2100, fuelType: "diesel", transmission: "Auto Command CVT", engineSize: "6.7L NEF", purchaseDate: new Date("2022-08-05"), purchasePrice: 210000, imageUrl: img("vehicles","tractor-field.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[10].id } }),
  723. /* 27 */ prisma.vehicle.create({ data: { make: "John Deere", model: "S780 Combine", year: 2023, vin: "1H0S780SPN567890", licensePlate: "N/A", color: "Green/Yellow", mileage: 600, fuelType: "diesel", transmission: "hydrostatic", engineSize: "13.5L PowerTech PSS", purchaseDate: new Date("2023-05-10"), purchasePrice: 520000, imageUrl: img("vehicles","combine-harvester.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[18].id } }),
  724. /* 28 */ prisma.vehicle.create({ data: { make: "John Deere", model: "X9 1100 Combine", year: 2024, vin: "1H0X91100RN678901", licensePlate: "N/A", color: "Green/Yellow", mileage: 350, fuelType: "diesel", transmission: "hydrostatic", engineSize: "13.6L PowerTech", purchaseDate: new Date("2024-03-15"), purchasePrice: 680000, imageUrl: img("vehicles","combine-jd.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[18].id } }),
  725. // === Heavy Machinery (29-37) ===
  726. /* 29 */ prisma.vehicle.create({ data: { make: "Caterpillar", model: "D6 XE Bulldozer", year: 2021, vin: "CAT0D6XE2LM012345", licensePlate: "N/A", color: "CAT Yellow", mileage: 4200, fuelType: "diesel", transmission: "automatic", engineSize: "9.3L C9.3B", purchaseDate: new Date("2021-03-25"), purchasePrice: 320000, imageUrl: img("vehicles","cat-d6-bulldozer.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[0].id } }),
  727. /* 30 */ prisma.vehicle.create({ data: { make: "Caterpillar", model: "D8T Bulldozer", year: 2020, vin: "CAT0D8T2KM234567", licensePlate: "N/A", color: "CAT Yellow", mileage: 5800, fuelType: "diesel", transmission: "automatic", engineSize: "15.2L C15", purchaseDate: new Date("2020-06-10"), purchasePrice: 480000, imageUrl: img("vehicles","bulldozer-rocks.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[14].id } }),
  728. /* 31 */ prisma.vehicle.create({ data: { make: "Komatsu", model: "PC210LC-11 Excavator", year: 2022, vin: "KMTPC210LCN234567", licensePlate: "N/A", color: "Komatsu Blue/White", mileage: 3100, fuelType: "diesel", transmission: "hydraulic", engineSize: "6.7L SAA6D107E-3", purchaseDate: new Date("2022-07-12"), purchasePrice: 265000, imageUrl: img("vehicles","komatsu-excavator.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[8].id } }),
  729. /* 32 */ prisma.vehicle.create({ data: { make: "Komatsu", model: "PC490LC-11 Excavator", year: 2023, vin: "KMTPC490LCN345678", licensePlate: "N/A", color: "Komatsu Yellow", mileage: 1800, fuelType: "diesel", transmission: "hydraulic", engineSize: "15.2L SAA6D170E-7", purchaseDate: new Date("2023-01-20"), purchasePrice: 450000, imageUrl: img("vehicles","excavator-soil.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[8].id } }),
  730. /* 33 */ prisma.vehicle.create({ data: { make: "Volvo", model: "EC220E Excavator", year: 2023, vin: "VOLEC220EN3M345678", licensePlate: "N/A", color: "Volvo Yellow", mileage: 1500, fuelType: "diesel", transmission: "hydraulic", engineSize: "5.7L D6J", purchaseDate: new Date("2023-02-20"), purchasePrice: 280000, imageUrl: img("vehicles","volvo-ec220e.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[8].id } }),
  731. /* 34 */ prisma.vehicle.create({ data: { make: "Kubota", model: "KX040-4 Mini Excavator", year: 2023, vin: "KUB040KX4N3456789", licensePlate: "N/A", color: "Orange", mileage: 900, fuelType: "diesel", transmission: "hydraulic", engineSize: "1.8L D1803-CR-TE4", purchaseDate: new Date("2023-09-15"), purchasePrice: 62000, imageUrl: img("vehicles","mini-excavator.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[12].id } }),
  732. /* 35 */ prisma.vehicle.create({ data: { make: "Case", model: "621G Wheel Loader", year: 2023, vin: "CASE621GN3M456789", licensePlate: "N/A", color: "Power Tan", mileage: 1800, fuelType: "diesel", transmission: "automatic", engineSize: "6.7L FPT", purchaseDate: new Date("2023-04-18"), purchasePrice: 185000, imageUrl: img("vehicles","wheel-loader.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[4].id } }),
  733. /* 36 */ prisma.vehicle.create({ data: { make: "Liebherr", model: "LTM 1100-4.2 Crane", year: 2019, vin: "LBH1100LTM9K12345", licensePlate: "GA-2233", color: "Yellow", mileage: 12500, fuelType: "diesel", transmission: "automatic", engineSize: "10.7L D936", purchaseDate: new Date("2019-08-14"), purchasePrice: 850000, imageUrl: img("vehicles","liebherr-crane.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[14].id } }),
  734. /* 37 */ prisma.vehicle.create({ data: { make: "Toyota", model: "8FBE18 Forklift", year: 2022, vin: "TYT8FBE18N2M56789", licensePlate: "N/A", color: "Orange/Black", mileage: 4200, fuelType: "electric", transmission: "automatic", engineSize: "48V AC Motor", purchaseDate: new Date("2022-11-01"), purchasePrice: 35000, imageUrl: img("vehicles","forklift.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[6].id } }),
  735. // === Additional Vehicles (38-41) ===
  736. /* 38 */ prisma.vehicle.create({ data: { make: "Chevrolet", model: "Corvette Stingray", year: 2024, vin: "1G1YB2D48R5100234", licensePlate: "TN-0038", color: "Black", mileage: 6200, fuelType: "gasoline", transmission: "automatic", engineSize: "6.2L LT2 V8", purchaseDate: new Date("2024-05-10"), purchasePrice: 68000, imageUrl: img("vehicles","corvette-c8.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[3].id } }),
  737. /* 39 */ prisma.vehicle.create({ data: { make: "Land Rover", model: "Defender 110 S", year: 2023, vin: "SALE7EEU5P1234567", licensePlate: "CO-3911", color: "Santorini Black", mileage: 28500, fuelType: "gasoline", transmission: "automatic", engineSize: "3.0L I6 Turbo", purchaseDate: new Date("2023-06-22"), purchasePrice: 62000, imageUrl: img("vehicles","land-rover-defender.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[11].id } }),
  738. /* 40 */ prisma.vehicle.create({ data: { make: "Dodge", model: "Charger R/T", year: 2022, vin: "2C3CDXCT5NH234567", licensePlate: "MI-4022", color: "Go Mango Orange", mileage: 34800, fuelType: "gasoline", transmission: "automatic", engineSize: "5.7L HEMI V8", purchaseDate: new Date("2022-08-15"), purchasePrice: 45000, imageUrl: img("vehicles","dodge-charger.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[17].id } }),
  739. /* 41 */ prisma.vehicle.create({ data: { make: "Subaru", model: "WRX Premium", year: 2024, vin: "JF1VA1E68R9234567", licensePlate: "CA-4124", color: "WR Blue Pearl", mileage: 12400, fuelType: "gasoline", transmission: "manual", engineSize: "2.4L Turbo Boxer", purchaseDate: new Date("2024-03-01"), purchasePrice: 35000, imageUrl: img("vehicles","subaru-wrx.jpg"), userId: USER_ID, organizationId: ORG_ID, customerId: customers[7].id } }),
  740. ]);
  741. console.log(` Created ${vehicles.length} vehicles`);
  742. // -- Service Records (20) --
  743. console.log("\nCreating service records...");
  744. const svcData = [
  745. { vehicleId: vehicles[0].id, title: "Oil Change & Tire Rotation", description: "Regular 10,000 mi service. Synthetic 0W-20 oil. Rotated tires front to back.", type: "maintenance", status: "completed", serviceDate: days(-114), mileage: 15000, techName: "Jake Wilson", shopName: "Egeland Auto",
  746. partItems: [{ name: "Synthetic Oil 0W-20 (5qt)", partNumber: "TOY-0W20-5Q", quantity: 1, unitPrice: 42, total: 42 }, { name: "Oil Filter", partNumber: "TOY-OF-2023", quantity: 1, unitPrice: 12, total: 12 }],
  747. laborItems: [{ description: "Oil change and filter replacement", hours: 0.5, rate: 95, total: 47.50 }, { description: "Tire rotation and pressure check", hours: 0.3, rate: 95, total: 28.50 }],
  748. subtotal: 130, taxRate: 8, taxAmount: 10.40, totalAmount: 140.40 },
  749. { vehicleId: vehicles[4].id, title: "50,000 Mile Major Service", description: "Major service interval. Replaced brake pads, rotors, spark plugs. Full inspection.", type: "maintenance", status: "completed", serviceDate: days(-140), mileage: 50000, techName: "Chris Taylor", shopName: "Egeland Auto",
  750. partItems: [{ name: "Front Brake Pad Set", partNumber: "BMW-BP-F34", quantity: 1, unitPrice: 185, total: 185 }, { name: "Front Brake Rotors (pair)", partNumber: "BMW-BR-F34", quantity: 1, unitPrice: 320, total: 320 }, { name: "Spark Plugs (set of 4)", partNumber: "BMW-SP-N20", quantity: 1, unitPrice: 68, total: 68 }, { name: "Engine Oil 5W-30 (7qt)", partNumber: "BMW-5W30-7Q", quantity: 1, unitPrice: 89, total: 89 }],
  751. laborItems: [{ description: "Front brake pad and rotor replacement", hours: 2.0, rate: 110, total: 220 }, { description: "Spark plug replacement", hours: 1.0, rate: 110, total: 110 }, { description: "Oil change and multi-point inspection", hours: 1.0, rate: 110, total: 110 }],
  752. subtotal: 1102, taxRate: 8, taxAmount: 88.16, totalAmount: 1190.16 },
  753. { vehicleId: vehicles[6].id, title: "Tire Replacement - All Four", description: "Replaced all four tires. Michelin Pilot Sport 4S. Alignment check passed.", type: "repair", status: "completed", serviceDate: days(-60), mileage: 7800, techName: "Jake Wilson", shopName: "Egeland Auto",
  754. partItems: [{ name: "Michelin Pilot Sport 4S 235/40R19", partNumber: "MICH-PS4S-2354019", quantity: 4, unitPrice: 310, total: 1240 }],
  755. laborItems: [{ description: "Mount and balance 4 tires", hours: 1.5, rate: 95, total: 142.50 }, { description: "Wheel alignment check", hours: 0.5, rate: 95, total: 47.50 }],
  756. subtotal: 1430, taxRate: 8, taxAmount: 114.40, totalAmount: 1544.40 },
  757. { vehicleId: vehicles[13].id, title: "Porsche 911 - Annual Service", description: "Annual service. Oil change, brake fluid flush, cabin filter. Full inspection.", type: "maintenance", status: "completed", serviceDate: days(-53), mileage: 12500, techName: "Chris Taylor", shopName: "Egeland Auto",
  758. partItems: [{ name: "Porsche Approved Oil 0W-40 (9qt)", partNumber: "POR-0W40-9Q", quantity: 1, unitPrice: 165, total: 165 }, { name: "Oil Filter", partNumber: "POR-OF-992", quantity: 1, unitPrice: 28, total: 28 }, { name: "Brake Fluid DOT4 (1L)", partNumber: "POR-BF-DOT4", quantity: 2, unitPrice: 35, total: 70 }],
  759. laborItems: [{ description: "Oil and filter change", hours: 1.0, rate: 145, total: 145 }, { description: "Brake fluid flush all 4 corners", hours: 1.5, rate: 145, total: 217.50 }, { description: "Multi-point inspection", hours: 1.0, rate: 145, total: 145 }],
  760. subtotal: 770.50, taxRate: 8, taxAmount: 61.64, totalAmount: 832.14 },
  761. { vehicleId: vehicles[17].id, title: "150K Mile Engine Service - Kenworth", description: "Major engine service. Replaced fuel filters, air filters, coolant flush. DPF regen.", type: "maintenance", status: "completed", serviceDate: days(-94), mileage: 180000, techName: "Marcus Reed", shopName: "Egeland Auto",
  762. partItems: [{ name: "PACCAR MX-13 Fuel Filter Kit", partNumber: "PAC-FF-MX13", quantity: 1, unitPrice: 125, total: 125 }, { name: "Air Filter Element", partNumber: "PAC-AF-MX13", quantity: 1, unitPrice: 85, total: 85 }, { name: "Coolant (5gal)", partNumber: "PAC-COOL-5G", quantity: 2, unitPrice: 65, total: 130 }, { name: "Engine Oil 15W-40 (10gal)", partNumber: "PAC-15W40-10G", quantity: 1, unitPrice: 280, total: 280 }],
  763. laborItems: [{ description: "Engine oil and filter change", hours: 2.0, rate: 125, total: 250 }, { description: "Fuel filter replacement", hours: 1.0, rate: 125, total: 125 }, { description: "Coolant flush and refill", hours: 1.5, rate: 125, total: 187.50 }, { description: "DPF regeneration and diagnostic", hours: 1.5, rate: 125, total: 187.50 }],
  764. subtotal: 1370, taxRate: 8, taxAmount: 109.60, totalAmount: 1479.60 },
  765. { vehicleId: vehicles[18].id, title: "Volvo FH 640 - DOT Inspection", description: "Full annual inspection per DOT regulations. Brake test, emissions, lights, safety.", type: "inspection", status: "in_progress", serviceDate: days(-19), mileage: 92000, techName: "Marcus Reed", shopName: "Egeland Auto",
  766. partItems: [{ name: "Marker Light Bulbs (pack of 10)", partNumber: "VOL-MLB-10", quantity: 1, unitPrice: 35, total: 35 }, { name: "Wiper Blades (pair)", partNumber: "VOL-WB-FH", quantity: 1, unitPrice: 52, total: 52 }],
  767. laborItems: [{ description: "Full DOT inspection and documentation", hours: 4.0, rate: 125, total: 500 }, { description: "Minor repairs and adjustments", hours: 2.0, rate: 125, total: 250 }],
  768. subtotal: 837, taxRate: 8, taxAmount: 66.96, totalAmount: 903.96 },
  769. { vehicleId: vehicles[22].id, title: "John Deere 6R 250 - 500hr Service", description: "Scheduled 500-hour service. Engine oil, all filters, hydraulic fluid sample, PTO check.", type: "maintenance", status: "completed", serviceDate: days(-48), mileage: 2500, techName: "Marcus Reed", shopName: "Egeland Auto",
  770. partItems: [{ name: "Engine Oil 15W-40 (5gal)", partNumber: "JD-15W40-5G", quantity: 1, unitPrice: 185, total: 185 }, { name: "Oil Filter", partNumber: "JD-OF-6R", quantity: 1, unitPrice: 32, total: 32 }, { name: "Fuel Filter Kit", partNumber: "JD-FFK-6R", quantity: 1, unitPrice: 68, total: 68 }, { name: "Hydraulic Filter", partNumber: "JD-HF-6R", quantity: 1, unitPrice: 55, total: 55 }, { name: "Air Filter Inner+Outer", partNumber: "JD-AF-6R", quantity: 1, unitPrice: 78, total: 78 }],
  771. laborItems: [{ description: "Engine oil and all filter replacement", hours: 2.0, rate: 140, total: 280 }, { description: "Hydraulic fluid sampling and analysis", hours: 0.5, rate: 140, total: 70 }, { description: "PTO and 3-point hitch inspection", hours: 1.0, rate: 140, total: 140 }, { description: "Grease all fittings (32 points)", hours: 1.5, rate: 140, total: 210 }],
  772. subtotal: 1118, taxRate: 8, taxAmount: 89.44, totalAmount: 1207.44 },
  773. { vehicleId: vehicles[23].id, title: "Fendt 942 - CVT Transmission Service", description: "CVT transmission fluid and filter change. Vario calibration and function test.", type: "maintenance", status: "completed", serviceDate: days(-119), mileage: 1100, techName: "Chris Taylor", shopName: "Egeland Auto",
  774. partItems: [{ name: "Vario CVT Fluid (10gal)", partNumber: "FENDT-CVT-10G", quantity: 1, unitPrice: 420, total: 420 }, { name: "CVT Filter Kit", partNumber: "FENDT-CVTF-942", quantity: 1, unitPrice: 165, total: 165 }],
  775. laborItems: [{ description: "CVT transmission fluid drain and refill", hours: 3.0, rate: 150, total: 450 }, { description: "CVT filter replacement", hours: 1.5, rate: 150, total: 225 }, { description: "Vario transmission calibration", hours: 2.0, rate: 150, total: 300 }],
  776. subtotal: 1560, taxRate: 8, taxAmount: 124.80, totalAmount: 1684.80 },
  777. { vehicleId: vehicles[29].id, title: "CAT D6 - Hydraulic System Overhaul", description: "Complete hydraulic system service. Replaced main pump seals, flushed system, new filters.", type: "repair", status: "completed", serviceDate: days(-172), mileage: 4000, techName: "Marcus Reed", shopName: "Egeland Auto",
  778. partItems: [{ name: "Hydraulic Pump Seal Kit", partNumber: "CAT-HPS-D6", quantity: 1, unitPrice: 450, total: 450 }, { name: "Hydraulic Oil (55gal drum)", partNumber: "CAT-HO-55G", quantity: 1, unitPrice: 850, total: 850 }, { name: "Hydraulic Filter Set", partNumber: "CAT-HF-D6", quantity: 2, unitPrice: 120, total: 240 }],
  779. laborItems: [{ description: "Hydraulic pump disassembly and seal replacement", hours: 6.0, rate: 140, total: 840 }, { description: "System flush and refill", hours: 3.0, rate: 140, total: 420 }, { description: "Pressure testing and calibration", hours: 2.0, rate: 140, total: 280 }],
  780. subtotal: 3080, taxRate: 8, taxAmount: 246.40, totalAmount: 3326.40 },
  781. { vehicleId: vehicles[31].id, title: "Komatsu PC210 - Track Chain Replacement", description: "Replaced both track chains and sprockets. Undercarriage inspection completed.", type: "repair", status: "completed", serviceDate: days(-46), mileage: 3000, techName: "Chris Taylor", shopName: "Egeland Auto",
  782. partItems: [{ name: "Track Chain Assembly (left)", partNumber: "KOM-TC-PC210L", quantity: 1, unitPrice: 2800, total: 2800 }, { name: "Track Chain Assembly (right)", partNumber: "KOM-TC-PC210R", quantity: 1, unitPrice: 2800, total: 2800 }, { name: "Track Sprocket (pair)", partNumber: "KOM-TS-PC210", quantity: 1, unitPrice: 1200, total: 1200 }],
  783. laborItems: [{ description: "Track chain removal and installation (both sides)", hours: 8.0, rate: 140, total: 1120 }, { description: "Sprocket replacement", hours: 3.0, rate: 140, total: 420 }, { description: "Undercarriage inspection", hours: 2.0, rate: 140, total: 280 }],
  784. subtotal: 8620, taxRate: 8, taxAmount: 689.60, totalAmount: 9309.60 },
  785. { vehicleId: vehicles[33].id, title: "Volvo EC220E - 1000hr Full Service", description: "All fluids, filters, track tension, swing bearing inspection.", type: "maintenance", status: "in_progress", serviceDate: days(-12), mileage: 1500, techName: "Chris Taylor", shopName: "Egeland Auto",
  786. partItems: [{ name: "Engine Oil 15W-40 (5gal)", partNumber: "VOL-15W40-5G", quantity: 1, unitPrice: 185, total: 185 }, { name: "Hydraulic Filter Set", partNumber: "VOL-HFS-EC220", quantity: 1, unitPrice: 120, total: 120 }, { name: "Fuel Filter Kit", partNumber: "VOL-FFK-EC220", quantity: 1, unitPrice: 58, total: 58 }],
  787. laborItems: [{ description: "Engine oil and all filter replacement", hours: 2.5, rate: 140, total: 350 }, { description: "Track tension adjustment", hours: 1.0, rate: 140, total: 140 }, { description: "Full grease service (48 points)", hours: 2.0, rate: 140, total: 280 }],
  788. subtotal: 1133, taxRate: 8, taxAmount: 90.64, totalAmount: 1223.64 },
  789. { vehicleId: vehicles[11].id, title: "Jeep Wrangler - Lift Kit Install", description: "2.5\" suspension lift, new shocks, extended brake lines. Alignment after.", type: "repair", status: "completed", serviceDate: days(-27), mileage: 28000, techName: "Jake Wilson", shopName: "Egeland Auto",
  790. partItems: [{ name: "Mopar 2.5\" Lift Kit", partNumber: "JEEP-LK-25", quantity: 1, unitPrice: 1200, total: 1200 }, { name: "Bilstein 5100 Shocks (set of 4)", partNumber: "BIL-5100-JL4", quantity: 1, unitPrice: 680, total: 680 }, { name: "Extended Brake Lines", partNumber: "JEEP-EBL-JL", quantity: 1, unitPrice: 120, total: 120 }],
  791. laborItems: [{ description: "Suspension lift installation", hours: 6.0, rate: 110, total: 660 }, { description: "Brake line routing and bleed", hours: 1.0, rate: 110, total: 110 }, { description: "4-wheel alignment", hours: 1.5, rate: 110, total: 165 }],
  792. subtotal: 2935, taxRate: 8, taxAmount: 234.80, totalAmount: 3169.80 },
  793. { vehicleId: vehicles[9].id, title: "Sprinter - Turbocharger Replacement", description: "Turbo shaft play detected. Black smoke under boost. Replaced turbo assembly.", type: "repair", status: "in_progress", serviceDate: days(-18), mileage: 35400, techName: "Chris Taylor", shopName: "Egeland Auto",
  794. partItems: [{ name: "Turbocharger Assembly - OM651", partNumber: "MB-TURBO-OM651", quantity: 1, unitPrice: 1280, total: 1280 }, { name: "Turbo Oil Feed Line", partNumber: "MB-TOFL-OM651", quantity: 1, unitPrice: 68, total: 68 }, { name: "Turbo Gasket Kit", partNumber: "MB-TGK-OM651", quantity: 1, unitPrice: 42, total: 42 }],
  795. laborItems: [{ description: "Turbocharger removal", hours: 3.0, rate: 125, total: 375 }, { description: "New turbo installation and oil line", hours: 2.5, rate: 125, total: 312.50 }],
  796. subtotal: 2077.50, taxRate: 8, taxAmount: 166.20, totalAmount: 2243.70 },
  797. { vehicleId: vehicles[24].id, title: "Massey Ferguson 8S - Hydraulic Pump", description: "Low hydraulic pressure. Replaced main pump and flushed system.", type: "repair", status: "completed", serviceDate: days(-32), mileage: 3500, techName: "Marcus Reed", shopName: "Egeland Auto",
  798. partItems: [{ name: "Main Hydraulic Pump Assembly", partNumber: "MF-HPA-8S", quantity: 1, unitPrice: 1650, total: 1650 }, { name: "Hydraulic Oil (15gal)", partNumber: "HYD-ISO46-15G", quantity: 1, unitPrice: 280, total: 280 }, { name: "Hydraulic Filter Set", partNumber: "MF-HFS-8S", quantity: 1, unitPrice: 95, total: 95 }],
  799. laborItems: [{ description: "Hydraulic pump removal", hours: 4.0, rate: 140, total: 560 }, { description: "New pump installation", hours: 3.0, rate: 140, total: 420 }, { description: "System flush and pressure test", hours: 2.0, rate: 140, total: 280 }],
  800. subtotal: 3285, taxRate: 8, taxAmount: 262.80, totalAmount: 3547.80 },
  801. { vehicleId: vehicles[15].id, title: "Ram 1500 - Brake Service", description: "Front and rear brake pad replacement. Rotor resurface. Fluid flush.", type: "maintenance", status: "completed", serviceDate: days(-40), mileage: 19500, techName: "Jake Wilson", shopName: "Egeland Auto",
  802. partItems: [{ name: "Front Brake Pad Set", partNumber: "RAM-BP-F-DS", quantity: 1, unitPrice: 145, total: 145 }, { name: "Rear Brake Pad Set", partNumber: "RAM-BP-R-DS", quantity: 1, unitPrice: 125, total: 125 }, { name: "Brake Fluid DOT4 (1L)", partNumber: "BF-DOT4-1L", quantity: 2, unitPrice: 18, total: 36 }],
  803. laborItems: [{ description: "Front brake pad replacement", hours: 1.5, rate: 110, total: 165 }, { description: "Rear brake pad replacement", hours: 1.0, rate: 110, total: 110 }, { description: "Rotor resurface (all 4)", hours: 1.0, rate: 110, total: 110 }, { description: "Brake fluid flush", hours: 0.5, rate: 110, total: 55 }],
  804. subtotal: 746, taxRate: 8, taxAmount: 59.68, totalAmount: 805.68 },
  805. { vehicleId: vehicles[14].id, title: "VW Golf GTI - DSG Service + Oil", description: "DSG transmission fluid/filter. Engine oil change. Cabin filter.", type: "maintenance", status: "completed", serviceDate: days(-79), mileage: 38000, techName: "Jake Wilson", shopName: "Egeland Auto",
  806. partItems: [{ name: "DSG Fluid (7qt)", partNumber: "VW-DSG-7Q", quantity: 1, unitPrice: 145, total: 145 }, { name: "DSG Filter", partNumber: "VW-DSGF", quantity: 1, unitPrice: 52, total: 52 }, { name: "Engine Oil 5W-40 (5qt)", partNumber: "VW-5W40-5Q", quantity: 1, unitPrice: 58, total: 58 }],
  807. laborItems: [{ description: "DSG fluid and filter change", hours: 1.5, rate: 110, total: 165 }, { description: "Engine oil and filter change", hours: 0.5, rate: 110, total: 55 }],
  808. subtotal: 475, taxRate: 8, taxAmount: 38, totalAmount: 513 },
  809. { vehicleId: vehicles[19].id, title: "Mack Granite - PTO Pump Replacement", description: "PTO pump failed. No hydraulic pressure for dump body. Replaced and tested.", type: "repair", status: "completed", serviceDate: days(-71), mileage: 154000, techName: "Marcus Reed", shopName: "Egeland Auto",
  810. partItems: [{ name: "PTO Hydraulic Pump", partNumber: "MACK-PTO-GR64", quantity: 1, unitPrice: 1450, total: 1450 }, { name: "PTO Mounting Gasket Kit", partNumber: "MACK-PTO-GK", quantity: 1, unitPrice: 85, total: 85 }, { name: "Hydraulic Oil (10gal)", partNumber: "HYD-ISO46-10G", quantity: 1, unitPrice: 180, total: 180 }],
  811. laborItems: [{ description: "PTO pump removal", hours: 3.0, rate: 140, total: 420 }, { description: "New pump installation", hours: 2.5, rate: 140, total: 350 }, { description: "System prime and dump cycle test", hours: 1.5, rate: 140, total: 210 }],
  812. subtotal: 2695, taxRate: 8, taxAmount: 215.60, totalAmount: 2910.60 },
  813. { vehicleId: vehicles[35].id, title: "Case 621G - Bucket Cylinder Reseal", description: "Bucket cylinder leaking. Resealed both cylinders. Tested under load.", type: "repair", status: "completed", serviceDate: days(-101), mileage: 1700, techName: "Chris Taylor", shopName: "Egeland Auto",
  814. partItems: [{ name: "Bucket Cylinder Seal Kit (pair)", partNumber: "CASE-BCSK-621G", quantity: 1, unitPrice: 380, total: 380 }, { name: "Hydraulic Oil (5gal)", partNumber: "HYD-ISO46-5G", quantity: 2, unitPrice: 95, total: 190 }],
  815. laborItems: [{ description: "Cylinder removal and disassembly", hours: 3.0, rate: 140, total: 420 }, { description: "Reseal and reassembly", hours: 2.5, rate: 140, total: 350 }, { description: "System bleed and pressure test", hours: 1.5, rate: 140, total: 210 }],
  816. subtotal: 1550, taxRate: 8, taxAmount: 124, totalAmount: 1674 },
  817. { vehicleId: vehicles[1].id, title: "F-150 Transmission Fluid Flush", description: "Customer reported rough shifting. Flushed transmission fluid, replaced filter.", type: "repair", status: "completed", serviceDate: days(-36), mileage: 41500, techName: "Jake Wilson", shopName: "Egeland Auto",
  818. partItems: [{ name: "Mercon ULV ATF (12qt)", partNumber: "FORD-ATF-ULV", quantity: 1, unitPrice: 185, total: 185 }, { name: "Transmission Filter Kit", partNumber: "FORD-TFK-10R80", quantity: 1, unitPrice: 68, total: 68 }],
  819. laborItems: [{ description: "Transmission fluid flush", hours: 2.0, rate: 110, total: 220 }, { description: "Filter and gasket replacement", hours: 1.5, rate: 110, total: 165 }],
  820. subtotal: 638, taxRate: 8, taxAmount: 51.04, totalAmount: 689.04 },
  821. { vehicleId: vehicles[38].id, title: "Corvette C8 - First Annual Service", description: "Annual oil change with performance inspection. Checked brake wear, tire depth, and suspension.", type: "maintenance", status: "completed", serviceDate: days(-46), mileage: 5800, techName: "Chris Taylor", shopName: "Egeland Auto",
  822. partItems: [{ name: "Mobil 1 0W-40 Full Synthetic (8qt)", partNumber: "CHV-0W40-8Q", quantity: 1, unitPrice: 95, total: 95 }, { name: "Oil Filter (OEM)", partNumber: "CHV-OF-LT2", quantity: 1, unitPrice: 18, total: 18 }, { name: "Cabin Air Filter", partNumber: "CHV-CAF-C8", quantity: 1, unitPrice: 28, total: 28 }],
  823. laborItems: [{ description: "Oil and filter change (dry sump)", hours: 1.0, rate: 130, total: 130 }, { description: "Performance multi-point inspection", hours: 1.0, rate: 130, total: 130 }],
  824. subtotal: 401, taxRate: 8, taxAmount: 32.08, totalAmount: 433.08 },
  825. { vehicleId: vehicles[39].id, title: "Defender 110 - 30K Service + Off-Road Inspection", description: "30K mile service. Oil change, all filters, diff fluids. Extra inspection for off-road wear.", type: "maintenance", status: "completed", serviceDate: days(-89), mileage: 27000, techName: "Erik Haugen", shopName: "Egeland Auto",
  826. partItems: [{ name: "Engine Oil 0W-20 (7qt)", partNumber: "LR-0W20-7Q", quantity: 1, unitPrice: 78, total: 78 }, { name: "Oil Filter", partNumber: "LR-OF-DEF", quantity: 1, unitPrice: 22, total: 22 }, { name: "Air Filter", partNumber: "LR-AF-DEF", quantity: 1, unitPrice: 45, total: 45 }, { name: "Front Diff Fluid (2qt)", partNumber: "LR-FDF-2Q", quantity: 1, unitPrice: 42, total: 42 }, { name: "Rear Diff Fluid (2.5qt)", partNumber: "LR-RDF-25Q", quantity: 1, unitPrice: 48, total: 48 }],
  827. laborItems: [{ description: "Oil and filter change", hours: 0.5, rate: 110, total: 55 }, { description: "Air filter replacement", hours: 0.3, rate: 110, total: 33 }, { description: "Front and rear differential fluid change", hours: 1.5, rate: 110, total: 165 }, { description: "Off-road undercarriage inspection", hours: 1.0, rate: 110, total: 110 }],
  828. subtotal: 598, taxRate: 8, taxAmount: 47.84, totalAmount: 645.84 },
  829. { vehicleId: vehicles[40].id, title: "Charger R/T - Brake Rotor Replacement", description: "Front rotors warped from aggressive driving. Replace rotors and pads.", type: "repair", status: "completed", serviceDate: days(-32), mileage: 33500, techName: "Jake Wilson", shopName: "Egeland Auto",
  830. partItems: [{ name: "Front Brake Rotors (pair)", partNumber: "DOD-BR-CHG-F", quantity: 1, unitPrice: 280, total: 280 }, { name: "Front Brake Pad Set (performance)", partNumber: "DOD-BP-CHG-F", quantity: 1, unitPrice: 145, total: 145 }],
  831. laborItems: [{ description: "Front brake rotor and pad replacement", hours: 2.0, rate: 110, total: 220 }, { description: "Brake system bleed and road test", hours: 0.5, rate: 110, total: 55 }],
  832. subtotal: 700, taxRate: 8, taxAmount: 56, totalAmount: 756 },
  833. { vehicleId: vehicles[41].id, title: "WRX - Turbo Boost Leak Repair", description: "Customer reported loss of power under boost. Found cracked intercooler pipe.", type: "repair", status: "completed", serviceDate: days(-38), mileage: 11800, techName: "Chris Taylor", shopName: "Egeland Auto",
  834. partItems: [{ name: "Intercooler Pipe + Couplers", partNumber: "SUB-ICP-WRX", quantity: 1, unitPrice: 165, total: 165 }, { name: "T-Bolt Clamps (set of 4)", partNumber: "SUB-TBC-4", quantity: 1, unitPrice: 28, total: 28 }],
  835. laborItems: [{ description: "Boost leak diagnosis and smoke test", hours: 1.0, rate: 120, total: 120 }, { description: "Intercooler pipe replacement", hours: 1.5, rate: 120, total: 180 }],
  836. subtotal: 493, taxRate: 8, taxAmount: 39.44, totalAmount: 532.44 },
  837. ];
  838. const serviceRecords = [];
  839. for (const sr of svcData) {
  840. const { partItems, laborItems, ...data } = sr;
  841. const record = await prisma.serviceRecord.create({ data: { ...data, organizationId: ORG_ID, cost: data.totalAmount, partItems: { create: partItems }, laborItems: { create: laborItems } } });
  842. serviceRecords.push(record);
  843. }
  844. console.log(` Created ${serviceRecords.length} service records`);
  845. // -- Quotes (15) --
  846. console.log("\nCreating quotes...");
  847. const qData = [
  848. { quoteNumber: `Q-${YEAR}-001`, title: "Full Brake Overhaul - BMW 330i", status: "sent", validUntil: days(6), customerId: customers[3].id, vehicleId: vehicles[4].id,
  849. partItems: [{ name: "Front Brake Rotor Set (OEM)", partNumber: "BMW-BR-F34-OEM", quantity: 1, unitPrice: 480, total: 480 }, { name: "Rear Brake Rotor Set (OEM)", partNumber: "BMW-BR-R34-OEM", quantity: 1, unitPrice: 390, total: 390 }, { name: "Front Brake Pad Set (OEM)", partNumber: "BMW-BP-F34-OEM", quantity: 1, unitPrice: 220, total: 220 }],
  850. laborItems: [{ description: "Front brake rotor and pad replacement", hours: 2.5, rate: 110, total: 275 }, { description: "Rear brake rotor replacement", hours: 2.0, rate: 110, total: 220 }],
  851. subtotal: 1585, taxRate: 8, taxAmount: 126.80, totalAmount: 1711.80 },
  852. { quoteNumber: `Q-${YEAR}-002`, title: "200K Engine Service - Kenworth T680", status: "accepted", validUntil: days(-8), customerId: customers[2].id, vehicleId: vehicles[17].id,
  853. partItems: [{ name: "PACCAR MX-13 Overhaul Kit", partNumber: "PAC-OHK-MX13", quantity: 1, unitPrice: 850, total: 850 }, { name: "Injector Set (6)", partNumber: "PAC-INJ-MX13-6", quantity: 1, unitPrice: 1420, total: 1420 }],
  854. laborItems: [{ description: "Injector replacement (6 cylinders)", hours: 8.0, rate: 140, total: 1120 }, { description: "Valve adjustment", hours: 4.0, rate: 140, total: 560 }],
  855. subtotal: 3950, taxRate: 8, taxAmount: 316, totalAmount: 4266 },
  856. { quoteNumber: `Q-${YEAR}-003`, title: "CAT D6 Undercarriage Rebuild", status: "sent", validUntil: days(21), customerId: customers[0].id, vehicleId: vehicles[29].id,
  857. partItems: [{ name: "Track Chain Assembly (pair)", partNumber: "CAT-TCA-D6", quantity: 1, unitPrice: 6500, total: 6500 }, { name: "Track Roller Set (14 pcs)", partNumber: "CAT-TR-D6-14", quantity: 1, unitPrice: 4200, total: 4200 }, { name: "Sprocket Set (pair)", partNumber: "CAT-SS-D6", quantity: 1, unitPrice: 1500, total: 1500 }],
  858. laborItems: [{ description: "Complete undercarriage disassembly", hours: 12.0, rate: 140, total: 1680 }, { description: "Component installation", hours: 16.0, rate: 140, total: 2240 }],
  859. subtotal: 16120, taxRate: 8, taxAmount: 1289.60, totalAmount: 17409.60 },
  860. { quoteNumber: `Q-${YEAR}-004`, title: "John Deere 6R - Front Axle Overhaul", status: "sent", validUntil: days(37), customerId: customers[10].id, vehicleId: vehicles[22].id,
  861. partItems: [{ name: "Front Axle Bearing Kit", partNumber: "JD-FABK-6R", quantity: 1, unitPrice: 520, total: 520 }, { name: "CV Joint Assembly (pair)", partNumber: "JD-CVJ-6R", quantity: 1, unitPrice: 850, total: 850 }],
  862. laborItems: [{ description: "Front axle removal", hours: 5.0, rate: 140, total: 700 }, { description: "Bearing and CV replacement", hours: 4.0, rate: 140, total: 560 }],
  863. subtotal: 2630, taxRate: 8, taxAmount: 210.40, totalAmount: 2840.40 },
  864. { quoteNumber: `Q-${YEAR}-005`, title: "Honda Civic - Clutch Replacement", status: "accepted", validUntil: days(1), customerId: customers[9].id, vehicleId: vehicles[5].id,
  865. partItems: [{ name: "Clutch Kit (disc, plate, bearing)", partNumber: "HON-CLK-FK7", quantity: 1, unitPrice: 380, total: 380 }],
  866. laborItems: [{ description: "Transmission removal and clutch replacement", hours: 5.0, rate: 110, total: 550 }, { description: "Reinstallation and test drive", hours: 2.0, rate: 110, total: 220 }],
  867. subtotal: 1150, taxRate: 8, taxAmount: 92, totalAmount: 1242 },
  868. { quoteNumber: `Q-${YEAR}-006`, title: "Volvo FH 640 - Air Suspension Repair", status: "accepted", validUntil: days(1), customerId: customers[2].id, vehicleId: vehicles[18].id,
  869. partItems: [{ name: "Rear Air Spring (pair)", partNumber: "VOL-RAS-FH", quantity: 1, unitPrice: 560, total: 560 }, { name: "Height Sensor", partNumber: "VOL-HS-FH", quantity: 1, unitPrice: 240, total: 240 }],
  870. laborItems: [{ description: "Air bag replacement (both sides)", hours: 3.0, rate: 140, total: 420 }, { description: "Sensor replacement and calibration", hours: 1.5, rate: 140, total: 210 }],
  871. subtotal: 1430, taxRate: 8, taxAmount: 114.40, totalAmount: 1544.40 },
  872. { quoteNumber: `Q-${YEAR}-007`, title: "Fendt 942 - A/C Compressor Repair", status: "draft", validUntil: days(32), customerId: customers[18].id, vehicleId: vehicles[23].id,
  873. partItems: [{ name: "A/C Compressor - Fendt 942", partNumber: "FENDT-ACC-942", quantity: 1, unitPrice: 890, total: 890 }, { name: "Condenser Assembly", partNumber: "FENDT-COND-942", quantity: 1, unitPrice: 450, total: 450 }],
  874. laborItems: [{ description: "Cab disassembly for A/C access", hours: 3.0, rate: 150, total: 450 }, { description: "Compressor and condenser replacement", hours: 4.0, rate: 150, total: 600 }],
  875. subtotal: 2390, taxRate: 8, taxAmount: 191.20, totalAmount: 2581.20 },
  876. { quoteNumber: `Q-${YEAR}-008`, title: "Komatsu PC210 - Boom Cylinder Reseal", status: "sent", validUntil: days(16), customerId: customers[8].id, vehicleId: vehicles[31].id,
  877. partItems: [{ name: "Boom Cylinder Seal Kit (pair)", partNumber: "KOM-BCSK-PC210", quantity: 1, unitPrice: 520, total: 520 }, { name: "Hydraulic Oil (10gal)", partNumber: "HYD-ISO46-10G", quantity: 1, unitPrice: 180, total: 180 }],
  878. laborItems: [{ description: "Boom cylinder removal", hours: 4.0, rate: 140, total: 560 }, { description: "Disassembly and reseal", hours: 3.0, rate: 140, total: 420 }],
  879. subtotal: 1680, taxRate: 8, taxAmount: 134.40, totalAmount: 1814.40 },
  880. { quoteNumber: `Q-${YEAR}-009`, title: "Liebherr Crane - Annual Certification", status: "sent", validUntil: days(53), customerId: customers[14].id, vehicleId: vehicles[36].id,
  881. partItems: [{ name: "Wire Rope Inspection Kit", partNumber: "LBH-WRIK", quantity: 1, unitPrice: 250, total: 250 }, { name: "Hydraulic Hose Set (safety critical)", partNumber: "LBH-HHS-SC", quantity: 1, unitPrice: 850, total: 850 }],
  882. laborItems: [{ description: "Full crane inspection per OSHA", hours: 8.0, rate: 160, total: 1280 }, { description: "Hydraulic hose replacement", hours: 4.0, rate: 160, total: 640 }, { description: "Load test and certification", hours: 4.0, rate: 160, total: 640 }],
  883. subtotal: 3660, taxRate: 8, taxAmount: 292.80, totalAmount: 3952.80 },
  884. { quoteNumber: `Q-${YEAR}-010`, title: "Porsche 911 - Suspension Refresh", status: "draft", validUntil: days(23), customerId: customers[3].id, vehicleId: vehicles[13].id,
  885. partItems: [{ name: "Bilstein B8 Dampers (set of 4)", partNumber: "POR-BIL-B8-4", quantity: 1, unitPrice: 1800, total: 1800 }, { name: "H&R Sport Springs", partNumber: "POR-HR-SS-992", quantity: 1, unitPrice: 650, total: 650 }],
  886. laborItems: [{ description: "Suspension removal and install", hours: 5.0, rate: 145, total: 725 }, { description: "4-corner alignment", hours: 1.5, rate: 145, total: 217.50 }],
  887. subtotal: 3392.50, taxRate: 8, taxAmount: 271.40, totalAmount: 3663.90 },
  888. { quoteNumber: `Q-${YEAR}-011`, title: "Jeep Wrangler - Winch Install", status: "accepted", validUntil: days(11), customerId: customers[11].id, vehicleId: vehicles[11].id,
  889. partItems: [{ name: "Warn VR EVO 10-S Winch", partNumber: "WARN-VR10S", quantity: 1, unitPrice: 850, total: 850 }, { name: "Winch Mounting Plate", partNumber: "JEEP-WMP-JL", quantity: 1, unitPrice: 220, total: 220 }],
  890. laborItems: [{ description: "Winch and plate installation", hours: 3.0, rate: 110, total: 330 }, { description: "Wiring and relay setup", hours: 1.5, rate: 110, total: 165 }],
  891. subtotal: 1565, taxRate: 8, taxAmount: 125.20, totalAmount: 1690.20 },
  892. { quoteNumber: `Q-${YEAR}-012`, title: "Fleet Oil Change Package - 10 Trucks", status: "sent", validUntil: days(6), customerId: customers[16].id, notes: "Bulk fleet pricing. Drop off in batches of 3-4.",
  893. partItems: [{ name: "Synthetic Oil 5W-30 (5qt) x10", partNumber: "OIL-5W30-BULK", quantity: 10, unitPrice: 38, total: 380 }, { name: "Oil Filter Assorted x10", partNumber: "OF-ASSORTED-10", quantity: 10, unitPrice: 9.50, total: 95 }],
  894. laborItems: [{ description: "Oil change service x10 vehicles", hours: 5.0, rate: 85, total: 425 }],
  895. subtotal: 900, taxRate: 8, taxAmount: 72, totalAmount: 972 },
  896. { quoteNumber: `Q-${YEAR}-013`, title: "S780 Combine - Pre-Season Check", status: "accepted", validUntil: days(37), customerId: customers[18].id, vehicleId: vehicles[27].id,
  897. partItems: [{ name: "Combine Service Kit (all filters)", partNumber: "JD-CSK-S780", quantity: 1, unitPrice: 420, total: 420 }, { name: "Sickle Blade Set", partNumber: "JD-SBS-S780", quantity: 1, unitPrice: 380, total: 380 }, { name: "Feeder Chain", partNumber: "JD-FC-S780", quantity: 1, unitPrice: 650, total: 650 }],
  898. laborItems: [{ description: "Full filter service and oil change", hours: 3.0, rate: 140, total: 420 }, { description: "Sickle replacement and header setup", hours: 4.0, rate: 140, total: 560 }, { description: "Feeder chain replacement", hours: 3.0, rate: 140, total: 420 }],
  899. subtotal: 2850, taxRate: 8, taxAmount: 228, totalAmount: 3078 },
  900. { quoteNumber: `Q-${YEAR}-015`, title: "Toyota Tacoma - Suspension Upgrade", status: "sent", validUntil: days(23), customerId: customers[19].id, vehicleId: vehicles[16].id,
  901. partItems: [{ name: "Bilstein 5100 Front (pair)", partNumber: "BIL-5100-TAC-F", quantity: 1, unitPrice: 340, total: 340 }, { name: "Bilstein 5100 Rear (pair)", partNumber: "BIL-5100-TAC-R", quantity: 1, unitPrice: 280, total: 280 }, { name: "OME Leaf Springs", partNumber: "OME-LS-TAC", quantity: 1, unitPrice: 450, total: 450 }],
  902. laborItems: [{ description: "Front strut replacement", hours: 2.5, rate: 110, total: 275 }, { description: "Rear shock and leaf spring install", hours: 3.0, rate: 110, total: 330 }, { description: "Alignment", hours: 1.0, rate: 110, total: 110 }],
  903. subtotal: 1785, taxRate: 8, taxAmount: 142.80, totalAmount: 1927.80 },
  904. ];
  905. const quotes = [];
  906. for (const q of qData) {
  907. const { partItems, laborItems, customerId, vehicleId, ...fields } = q;
  908. const quote = await prisma.quote.create({ data: { ...fields, userId: USER_ID, organizationId: ORG_ID, ...(customerId ? { customerId } : {}), ...(vehicleId ? { vehicleId } : {}), partItems: { create: partItems }, laborItems: { create: laborItems } } });
  909. quotes.push(quote);
  910. }
  911. console.log(` Created ${quotes.length} quotes`);
  912. // -- Inventory Parts (25) --
  913. console.log("\nCreating inventory parts...");
  914. const invData = [
  915. { name: "Synthetic Engine Oil 5W-30 (5qt)", partNumber: "OIL-5W30-5Q", category: "Fluids & Lubricants", quantity: 24, minQuantity: 10, unitCost: 28, sellPrice: 45, supplier: "AutoZone Commercial", location: "Shelf A-1" },
  916. { name: "Synthetic Engine Oil 0W-20 (5qt)", partNumber: "OIL-0W20-5Q", category: "Fluids & Lubricants", quantity: 18, minQuantity: 8, unitCost: 31, sellPrice: 49, supplier: "AutoZone Commercial", location: "Shelf A-1" },
  917. { name: "Heavy Duty Engine Oil 15W-40 (5gal)", partNumber: "OIL-15W40-5G", category: "Fluids & Lubricants", quantity: 8, minQuantity: 4, unitCost: 120, sellPrice: 185, supplier: "Shell Fleet", location: "Shelf A-2" },
  918. { name: "Hydraulic Oil ISO 46 (55gal)", partNumber: "HYD-ISO46-55G", category: "Fluids & Lubricants", quantity: 3, minQuantity: 2, unitCost: 580, sellPrice: 850, supplier: "Shell Fleet", location: "Floor A-3" },
  919. { name: "Brake Pad Set - Universal Light Vehicle", partNumber: "BP-UNI-LV", category: "Brakes", quantity: 14, minQuantity: 6, unitCost: 38, sellPrice: 68, supplier: "NAPA Auto Parts", location: "Shelf B-1" },
  920. { name: "Brake Pad Set - Heavy Duty Truck", partNumber: "BP-HD-TRUCK", category: "Brakes", quantity: 6, minQuantity: 4, unitCost: 180, sellPrice: 320, supplier: "FleetPride", location: "Shelf B-2" },
  921. { name: "Oil Filter - European Vehicles", partNumber: "OF-EUR-01", category: "Filters", quantity: 30, minQuantity: 10, unitCost: 6.50, sellPrice: 15.50, supplier: "Mann-Filter USA", location: "Shelf C-1" },
  922. { name: "Oil Filter - Asian Vehicles", partNumber: "OF-ASN-01", category: "Filters", quantity: 25, minQuantity: 10, unitCost: 4.50, sellPrice: 12, supplier: "Mann-Filter USA", location: "Shelf C-1" },
  923. { name: "Hydraulic Filter - CAT/Komatsu", partNumber: "HF-CAT-KOM", category: "Filters", quantity: 5, minQuantity: 3, unitCost: 65, sellPrice: 120, supplier: "Cat Parts Direct", location: "Shelf C-3" },
  924. { name: "Spark Plug - Iridium (each)", partNumber: "SP-IRID-01", category: "Ignition", quantity: 40, minQuantity: 16, unitCost: 9.50, sellPrice: 17.50, supplier: "NGK USA", location: "Shelf D-1" },
  925. { name: "Car Battery 12V 700CCA", partNumber: "BAT-12V-700CCA", category: "Electrical", quantity: 6, minQuantity: 3, unitCost: 95, sellPrice: 165, supplier: "Interstate Batteries", location: "Floor D-2" },
  926. { name: "Truck Battery 12V 1000CCA", partNumber: "BAT-12V-1000CCA", category: "Electrical", quantity: 4, minQuantity: 2, unitCost: 240, sellPrice: 380, supplier: "Interstate Batteries", location: "Floor D-2" },
  927. { name: "Coolant Concentrate (1gal)", partNumber: "COOL-CONC-1G", category: "Fluids & Lubricants", quantity: 15, minQuantity: 6, unitCost: 18, sellPrice: 32, supplier: "AutoZone Commercial", location: "Shelf A-2" },
  928. { name: "ATF Transmission Fluid (1qt)", partNumber: "ATF-DEXVI-1Q", category: "Fluids & Lubricants", quantity: 20, minQuantity: 8, unitCost: 12, sellPrice: 22, supplier: "AutoZone Commercial", location: "Shelf A-2" },
  929. { name: "Serpentine Belt - Universal", partNumber: "SB-UNI-6PK", category: "Engine", quantity: 8, minQuantity: 4, unitCost: 22, sellPrice: 42, supplier: "Gates Corp", location: "Shelf D-3" },
  930. { name: "Hydraulic Hose - 1/2\" x 10ft", partNumber: "HH-12-10FT", category: "Hydraulics", quantity: 10, minQuantity: 4, unitCost: 45, sellPrice: 85, supplier: "Parker Hannifin", location: "Rack G-1" },
  931. { name: "Track Shoe Bolt Kit (set of 50)", partNumber: "TSB-KIT-50", category: "Undercarriage", quantity: 4, minQuantity: 2, unitCost: 180, sellPrice: 320, supplier: "Cat Parts Direct", location: "Floor G-2" },
  932. { name: "R-134a Refrigerant (30oz can)", partNumber: "R134A-30OZ", category: "HVAC", quantity: 8, minQuantity: 4, unitCost: 18, sellPrice: 32, supplier: "AutoZone Commercial", location: "Shelf H-1" },
  933. { name: "Fuel Filter - Diesel Universal", partNumber: "FF-DSL-UNI", category: "Filters", quantity: 12, minQuantity: 5, unitCost: 14, sellPrice: 29, supplier: "Mann-Filter USA", location: "Shelf C-2" },
  934. { name: "Air Filter - Heavy Equipment", partNumber: "AF-HE-UNI", category: "Filters", quantity: 6, minQuantity: 3, unitCost: 48, sellPrice: 85, supplier: "Cat Parts Direct", location: "Shelf C-3" },
  935. { name: "Tractor PTO Shaft Guard", partNumber: "PTO-SG-UNI", category: "Safety", quantity: 3, minQuantity: 2, unitCost: 85, sellPrice: 150, supplier: "Agri Supply Co.", location: "Rack G-3" },
  936. { name: "DPF Pressure Sensor", partNumber: "DPF-PS-UNI", category: "Emissions", quantity: 1, minQuantity: 3, unitCost: 65, sellPrice: 120, supplier: "Bosch USA", location: "Shelf D-5" },
  937. { name: "Grease Cartridge EP2 (box of 10)", partNumber: "GREASE-EP2-10", category: "Fluids & Lubricants", quantity: 12, minQuantity: 5, unitCost: 28, sellPrice: 48, supplier: "Shell Fleet", location: "Shelf A-3" },
  938. { name: "Combine Sickle Section (box of 25)", partNumber: "CSS-UNI-25", category: "Harvest Parts", quantity: 4, minQuantity: 2, unitCost: 65, sellPrice: 110, supplier: "Agri Supply Co.", location: "Rack G-4" },
  939. { name: "Wiper Blade 24\" Universal", partNumber: "WB-24-UNI", category: "Body & Exterior", quantity: 12, minQuantity: 6, unitCost: 11, sellPrice: 25, supplier: "Bosch USA", location: "Shelf E-1" },
  940. ];
  941. const inventoryParts = await Promise.all(invData.map(p => prisma.inventoryPart.create({ data: { ...p, userId: USER_ID, organizationId: ORG_ID } })));
  942. console.log(` Created ${inventoryParts.length} inventory parts`);
  943. // -- Fuel Logs --
  944. console.log("\nCreating fuel logs...");
  945. await Promise.all([
  946. prisma.fuelLog.create({ data: { vehicleId: vehicles[1].id, date: days(-63), mileage: 40200, gallons: 26, pricePerGallon: 3.45, totalCost: 89.70, station: "Shell - I-25 & Hampden" } }),
  947. prisma.fuelLog.create({ data: { vehicleId: vehicles[1].id, date: days(-35), mileage: 41500, gallons: 24, pricePerGallon: 3.48, totalCost: 83.52, station: "Costco Gas - Arvada" } }),
  948. prisma.fuelLog.create({ data: { vehicleId: vehicles[17].id, date: days(-58), mileage: 182000, gallons: 120, pricePerGallon: 3.85, totalCost: 462.00, station: "Pilot Travel Center - Portland" } }),
  949. prisma.fuelLog.create({ data: { vehicleId: vehicles[8].id, date: days(-27), mileage: 98000, gallons: 28, pricePerGallon: 3.65, totalCost: 102.20, station: "Buc-ee's - San Antonio" } }),
  950. prisma.fuelLog.create({ data: { vehicleId: vehicles[22].id, date: days(-22), mileage: 2700, gallons: 35, pricePerGallon: 3.78, totalCost: 132.30, station: "Co-op Fuel - Omaha" } }),
  951. prisma.fuelLog.create({ data: { vehicleId: vehicles[23].id, date: days(-40), mileage: 1180, gallons: 80, pricePerGallon: 3.82, totalCost: 305.60, station: "Farm Bureau Fuel - Des Moines" } }),
  952. prisma.fuelLog.create({ data: { vehicleId: vehicles[15].id, date: days(-17), mileage: 19500, gallons: 22, pricePerGallon: 3.55, totalCost: 78.10, station: "Speedway - Detroit" } }),
  953. prisma.fuelLog.create({ data: { vehicleId: vehicles[11].id, date: days(-46), mileage: 28200, gallons: 18, pricePerGallon: 3.62, totalCost: 65.16, station: "Shell - I-70 & Morrison" } }),
  954. ]);
  955. console.log(" Created 8 fuel logs");
  956. // -- Reminders --
  957. // Spread deliberately around today: a few overdue, several due today and this
  958. // week, then a tail running out a few months. That is what makes the reminders
  959. // page, the dashboard counters and the calendar all look alive at once.
  960. // organizationId is required - getReminders() and the calendar both scope by
  961. // it, so a reminder without one is invisible in the app.
  962. console.log("\nCreating reminders...");
  963. const coreReminders = await Promise.all([
  964. // Overdue - the cron has already notified on the older ones
  965. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[17].id, title: "Annual DOT Inspection", description: "Kenworth T680 - annual inspection is past due, Pacific Freight notified twice", dueDate: days(-12), notifyInApp: true, notifyEmail: true, notifiedAt: days(-12) } }),
  966. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[5].id, title: "CV boot replacement", description: "Torn boot found at last service. Customer has not booked yet.", dueDate: days(-8), notifyInApp: true, notifiedAt: days(-8) } }),
  967. prisma.reminder.create({ data: { organizationId: ORG_ID, customerId: customers[16].id, title: "Chase fleet PM schedule", description: "Greenfield Waste has not confirmed the quarterly PM slots for 12 trucks.", dueDate: days(-5), notifyInApp: true, notifiedAt: days(-5) } }),
  968. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[8].id, title: "Battery replacement", description: "Load test showed 78% capacity. Replace before winter.", dueDate: days(-3), notifyInApp: true } }),
  969. prisma.reminder.create({ data: { organizationId: ORG_ID, title: "Order brake pad stock", description: "Heavy duty truck pads down to 6 sets. Reorder from FleetPride.", dueDate: days(-1), notifyInApp: true } }),
  970. // Due today
  971. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[18].id, title: "Volvo FH 640 - brake inspection", description: "Check brakes before the next long-haul run to Chicago.", dueDate: days(0), notifyInApp: true, notifyEmail: true } }),
  972. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[9].id, title: "Call Kevin about the Sprinter", description: "Turbo job finished - confirm pickup time before his catering event.", dueDate: days(0), notifyInApp: true } }),
  973. prisma.reminder.create({ data: { organizationId: ORG_ID, title: "Weekly parts order cut-off", description: "Submit the NAPA order before 15:00 or it ships Monday.", dueDate: days(0), notifyInApp: true } }),
  974. // This week
  975. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[0].id, title: "Next oil change", description: "Due at 25,000 mi. Customer wants Mobil 1 0W-20.", dueDate: days(1), dueMileage: 25000, notifyInApp: true } }),
  976. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[31].id, title: "Order boom cylinder seal kit", description: "Komatsu PC210 reseal cannot start until the kit lands.", dueDate: days(2), notifyInApp: true } }),
  977. prisma.reminder.create({ data: { organizationId: ORG_ID, customerId: customers[0].id, title: "Summit Construction - Net-30 invoices", description: "Three invoices approaching terms. Send a statement.", dueDate: days(3), notifyInApp: true, notifyEmail: true } }),
  978. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[36].id, title: "Book crane load test", description: "Liebherr LTM 1100 annual certification needs an external inspector.", dueDate: days(4), notifyInApp: true } }),
  979. prisma.reminder.create({ data: { organizationId: ORG_ID, title: "Calibrate brake tester", description: "Roller brake tester calibration certificate expires this month.", dueDate: days(5), notifyInApp: true, notifyEmail: true } }),
  980. // Next two weeks
  981. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[13].id, title: "Porsche 911 - track day prep", description: "Brake pads, fluid and tire pressure before the customer's HPDE weekend.", dueDate: days(9), notifyInApp: true } }),
  982. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[24].id, title: "Massey Ferguson - radiator deep clean", description: "Chaff blockage caused overheating. Pull the radiator when the tractor is back.", dueDate: days(11), notifyInApp: true } }),
  983. prisma.reminder.create({ data: { organizationId: ORG_ID, customerId: customers[10].id, title: "Prairie Farms - pre-planting check-in", description: "Book both tractors before the seasonal rush fills the board.", dueDate: days(13), notifyInApp: true } }),
  984. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[19].id, title: "Dump body weld repair", description: "Stress cracks near the rear hinge. Do not let it run past 10,000 more miles.", dueDate: days(16), notifyInApp: true } }),
  985. prisma.reminder.create({ data: { organizationId: ORG_ID, title: "Shop lift annual inspection", description: "Both two-post lifts are due for their yearly certification.", dueDate: days(18), notifyInApp: true, notifyEmail: true } }),
  986. // Later
  987. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[23].id, title: "Fendt 942 - season prep", description: "Full check before the field season starts.", dueDate: days(26), notifyInApp: true } }),
  988. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[4].id, title: "Brake fluid flush", description: "BMW recommends every 2 years.", dueDate: days(48), notifyInApp: true } }),
  989. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[27].id, title: "S780 combine - pre-harvest inspection", description: "Critical unit. Everything must be done before harvest starts.", dueDate: days(72), notifyInApp: true, notifyEmail: true } }),
  990. prisma.reminder.create({ data: { organizationId: ORG_ID, customerId: customers[14].id, title: "Titan Building - contract renewal", description: "Annual maintenance agreement for 20+ machines comes up for renewal.", dueDate: days(95), notifyInApp: true } }),
  991. // Mileage/hour based, no date
  992. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[29].id, title: "Track tension check", description: "CAT D6 - check after 100 hours.", dueMileage: 4500, notifyInApp: true } }),
  993. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[22].id, title: "1000hr service", description: "John Deere 6R 250 - scheduled interval service.", dueMileage: 3500, notifyInApp: true } }),
  994. // Already handled
  995. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[11].id, title: "Post-lift alignment check", description: "Done at the same visit as the lift kit install.", dueDate: days(-20), isCompleted: true } }),
  996. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[15].id, title: "Brake service follow-up", description: "Customer confirmed no more noise after the pad replacement.", dueDate: days(-14), isCompleted: true } }),
  997. prisma.reminder.create({ data: { organizationId: ORG_ID, customerId: customers[3].id, title: "Send Sarah the BMW brake quote", description: "Quote sent and accepted.", dueDate: days(-6), isCompleted: true } }),
  998. ]);
  999. console.log(` Created ${coreReminders.length} reminders`);
  1000. // -- Vehicle Notes --
  1001. console.log("\nCreating vehicle notes...");
  1002. await Promise.all([
  1003. prisma.note.create({ data: { vehicleId: vehicles[4].id, title: "Customer preference", content: "Sarah always requests OEM BMW parts. No aftermarket. She prefers to wait while service is done.", isPinned: true } }),
  1004. prisma.note.create({ data: { vehicleId: vehicles[29].id, title: "Hydraulic leak history", content: "This D6 has had recurring hydraulic leaks on the left blade cylinder. Last repaired Sept 2025. Monitor closely.", isPinned: true } }),
  1005. prisma.note.create({ data: { vehicleId: vehicles[17].id, title: "Fleet note", content: "Pacific Freight unit #3. Driver: Tom Bradley. Call dispatch at (555) 302-5566 for scheduling.", isPinned: false } }),
  1006. prisma.note.create({ data: { vehicleId: vehicles[6].id, title: "Charging note", content: "Customer reports occasional slow charging at home. Suggested checking home charger firmware. Not a vehicle issue.", isPinned: false } }),
  1007. prisma.note.create({ data: { vehicleId: vehicles[36].id, title: "Outrigger issue", content: "Right rear outrigger cylinder slow to extend. May need seal replacement at next service.", isPinned: true } }),
  1008. prisma.note.create({ data: { vehicleId: vehicles[22].id, title: "Warranty info", content: "John Deere 6R 250 still under manufacturer warranty until March 2027. Contact JD dealer for warranty claims.", isPinned: true } }),
  1009. prisma.note.create({ data: { vehicleId: vehicles[23].id, title: "Operator preference", content: "Fendt 942 - Operator prefers front linkage set to position control, not draft. Do not change settings after service.", isPinned: true } }),
  1010. prisma.note.create({ data: { vehicleId: vehicles[18].id, title: "Volvo FH 640 fleet note", content: "Pacific Freight unit #5. Long-haul Portland to Chicago route. D13TC engine with I-Shift dual clutch.", isPinned: true } }),
  1011. prisma.note.create({ data: { vehicleId: vehicles[11].id, title: "Lift kit installed", content: "2.5\" Mopar lift with Bilstein 5100 shocks installed Feb 2026. Customer plans to add 35\" tires next.", isPinned: false } }),
  1012. ]);
  1013. console.log(" Created 9 vehicle notes");
  1014. // -- Additional vehicle notes (customer preferences, reminders, history) --
  1015. console.log("\nCreating additional vehicle notes...");
  1016. const additionalNotes = await Promise.all([
  1017. prisma.note.create({ data: { vehicleId: vehicles[0].id, title: "Customer preference", content: "James prefers Mobil 1 full synthetic 0W-20 on every oil change. Do not substitute.", isPinned: true } }),
  1018. prisma.note.create({ data: { vehicleId: vehicles[0].id, title: "Key location", content: "Spare key in lockbox #4 (code 4412). Customer drops off after hours sometimes.", isPinned: false } }),
  1019. prisma.note.create({ data: { vehicleId: vehicles[1].id, title: "Fleet maintenance policy", content: "Summit Construction requires photo documentation of all brake and tire work. Upload to service record.", isPinned: true } }),
  1020. prisma.note.create({ data: { vehicleId: vehicles[1].id, title: "Aftermarket bed liner", content: "Spray-in bed liner installed 2023. Don't pressure wash interior of bed at close range.", isPinned: false } }),
  1021. prisma.note.create({ data: { vehicleId: vehicles[2].id, title: "Off-road use", content: "Mike uses this for hunting trips. Undercarriage gets a lot of mud - always inspect skid plates.", isPinned: false } }),
  1022. prisma.note.create({ data: { vehicleId: vehicles[3].id, title: "Municipal contract vehicle", content: "Metro City Services - invoicing via purchase order only. PO required before work starts.", isPinned: true } }),
  1023. prisma.note.create({ data: { vehicleId: vehicles[5].id, title: "Budget-conscious customer", content: "Amanda prefers aftermarket parts where safe. Always provide OEM vs aftermarket pricing options.", isPinned: true } }),
  1024. prisma.note.create({ data: { vehicleId: vehicles[5].id, title: "Check AC vents", content: "Musty smell reported last visit. Recommended cabin filter + evaporator clean at next service.", isPinned: false } }),
  1025. prisma.note.create({ data: { vehicleId: vehicles[7].id, title: "Referral source", content: "Jessica was referred by Ryan Parker. Offer referral discount on next service.", isPinned: false } }),
  1026. prisma.note.create({ data: { vehicleId: vehicles[8].id, title: "Ranch use", content: "Silverado used for cattle hauling. Check hitch and trailer plug every visit.", isPinned: false } }),
  1027. prisma.note.create({ data: { vehicleId: vehicles[9].id, title: "Commercial use", content: "Kevin uses this daily for catering. Needs quick turnaround - try to get him in/out same day.", isPinned: true } }),
  1028. prisma.note.create({ data: { vehicleId: vehicles[10].id, title: "OEM parts only", content: "David insists on genuine Audi parts. No VAG knockoffs. He'll ask to see part numbers.", isPinned: true } }),
  1029. prisma.note.create({ data: { vehicleId: vehicles[12].id, title: "Soft top care", content: "Customer has both hard and soft top. Store removed top carefully, document any scratches.", isPinned: false } }),
  1030. prisma.note.create({ data: { vehicleId: vehicles[14].id, title: "Manual transmission", content: "David is the primary driver. Wife drives occasionally but doesn't like manual - clutch wear expected.", isPinned: false } }),
  1031. prisma.note.create({ data: { vehicleId: vehicles[15].id, title: "Weekend vehicle", content: "Robert uses this mainly weekends for towing his boat. Look at trailer brakes in spring.", isPinned: false } }),
  1032. prisma.note.create({ data: { vehicleId: vehicles[16].id, title: "TRD package notes", content: "TRD Off-Road suspension - use correct alignment specs (different from base Tacoma).", isPinned: true } }),
  1033. prisma.note.create({ data: { vehicleId: vehicles[19].id, title: "Dump body maintenance", content: "Body floor develops cracks at 150k+ mi. Inspect weld seams during every service.", isPinned: false } }),
  1034. prisma.note.create({ data: { vehicleId: vehicles[20].id, title: "Concrete mixer drum", content: "Drum drive motor is a known weak point on this unit. Monitor for sluggish rotation.", isPinned: true } }),
  1035. prisma.note.create({ data: { vehicleId: vehicles[24].id, title: "Seasonal use", content: "Massey Ferguson is the backup tractor for Prairie Farms. Heavy use spring/fall only.", isPinned: false } }),
  1036. prisma.note.create({ data: { vehicleId: vehicles[25].id, title: "Warranty active", content: "John Deere 8R 410 still under warranty until Jan 2027. Contact JD dealer for anything covered.", isPinned: true } }),
  1037. prisma.note.create({ data: { vehicleId: vehicles[27].id, title: "Harvest critical", content: "S780 combine is CRITICAL for fall harvest. Any work needs to be done before September.", isPinned: true } }),
  1038. prisma.note.create({ data: { vehicleId: vehicles[30].id, title: "D8T parts lead time", content: "CAT D8T parts often take 2-3 weeks. Order ahead. Titan Building will wait if told up front.", isPinned: false } }),
  1039. prisma.note.create({ data: { vehicleId: vehicles[32].id, title: "Undercarriage wear", content: "Track chains due for replacement around 2000hr. Currently at 1800hr — budget planning.", isPinned: false } }),
  1040. prisma.note.create({ data: { vehicleId: vehicles[35].id, title: "Metro City asset tag", content: "City asset tag #WL-014. Include in all invoices for their records.", isPinned: false } }),
  1041. prisma.note.create({ data: { vehicleId: vehicles[37].id, title: "Indoor use only", content: "Electric forklift used indoors at Ironclad warehouse. Tire compound is non-marking.", isPinned: false } }),
  1042. prisma.note.create({ data: { vehicleId: vehicles[38].id, title: "Track car", content: "Sarah takes this to HPDE track days 3-4 times a year. Always check brake pads and fluid before/after.", isPinned: true } }),
  1043. prisma.note.create({ data: { vehicleId: vehicles[38].id, title: "Dry sump oil system", content: "C8 Corvette has a dry sump system. Takes 8 quarts of 0W-40. Use GM-approved Mobil 1 only.", isPinned: false } }),
  1044. prisma.note.create({ data: { vehicleId: vehicles[39].id, title: "Heavy off-road use", content: "Mike takes this on trails every weekend. Always inspect skid plates, check for rock damage underneath.", isPinned: true } }),
  1045. prisma.note.create({ data: { vehicleId: vehicles[40].id, title: "Mopar parts preference", content: "Robert wants Mopar or performance-equivalent parts. No economy parts on this car.", isPinned: true } }),
  1046. prisma.note.create({ data: { vehicleId: vehicles[41].id, title: "Modified intake", content: "Customer installed aftermarket cold air intake. Note: may trigger P0171 lean code - not a fault. Recheck with stock intake if persistent.", isPinned: true } }),
  1047. prisma.note.create({ data: { vehicleId: vehicles[41].id, title: "Catback exhaust", content: "Invidia Q300 catback exhaust installed by customer. Stock exhaust stored at his garage.", isPinned: false } }),
  1048. ]);
  1049. console.log(` Created ${additionalNotes.length} additional vehicle notes`);
  1050. // -- Additional reminders --
  1051. console.log("\nCreating additional reminders...");
  1052. const additionalReminders = await Promise.all([
  1053. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[1].id, title: "Timing belt replacement", description: "Interval-based - EcoBoost timing chain inspection due", dueMileage: 60000 } }),
  1054. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[2].id, title: "Annual inspection", description: "Minnesota state safety inspection", dueDate: days(67) } }),
  1055. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[5].id, title: "Brake fluid flush", description: "Honda recommends every 3 years", dueMileage: 72000, dueDate: days(84) } }),
  1056. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[8].id, title: "Registration renewal", description: "Texas registration expires June 2026", dueDate: days(113) } }),
  1057. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[9].id, title: "Next oil change", description: "Sprinter service B interval", dueMileage: 40000 } }),
  1058. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[10].id, title: "Haldex service", description: "Quattro rear diff fluid change - 40K interval", dueMileage: 40000, isCompleted: true } }),
  1059. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[11].id, title: "Front diff fluid", description: "After lift kit, recommend fluid change at 35K", dueMileage: 35000 } }),
  1060. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[12].id, title: "Annual inspection", description: "Georgia annual safety inspection", dueDate: days(166) } }),
  1061. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[14].id, title: "DSG service interval", description: "Next DSG fluid/filter at 78K", dueMileage: 78000 } }),
  1062. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[17].id, title: "CVT fluid check", description: "Subaru CVT recommended drain/fill", dueMileage: 30000 } }),
  1063. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[20].id, title: "Mixer drum inspection", description: "Annual drum wear/bolt check", dueDate: days(114) } }),
  1064. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[25].id, title: "250hr service", description: "John Deere 8R scheduled interval", dueMileage: 1000 } }),
  1065. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[28].id, title: "Pre-harvest prep", description: "X9 1100 combine full inspection before harvest", dueDate: days(159) } }),
  1066. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[30].id, title: "Blade edge replacement", description: "Check wear on cutting edge", dueMileage: 6500, isCompleted: true } }),
  1067. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[32].id, title: "Undercarriage inspection", description: "2000hr interval for track chain inspection", dueMileage: 2000 } }),
  1068. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[36].id, title: "OSHA crane certification", description: "Annual load test and certification due", dueDate: days(53) } }),
  1069. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[38].id, title: "Corvette annual service", description: "GM recommended annual service with performance inspection", dueDate: days(319) } }),
  1070. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[39].id, title: "Transfer case fluid", description: "Land Rover recommends 40K interval for transfer case fluid", dueMileage: 40000 } }),
  1071. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[40].id, title: "Transmission fluid change", description: "8-speed auto - ZF recommends fluid change at 50K", dueMileage: 50000 } }),
  1072. prisma.reminder.create({ data: { organizationId: ORG_ID, vehicleId: vehicles[41].id, title: "Timing belt inspection", description: "FA24 engine - inspect timing chain tensioner at 60K", dueMileage: 60000 } }),
  1073. ]);
  1074. console.log(` Created ${additionalReminders.length} additional reminders`);
  1075. // -- Vehicle Findings (observations from service) --
  1076. console.log("\nCreating vehicle findings...");
  1077. const findings = await Promise.all([
  1078. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[4].id, description: "Front brake pads at 3mm, recommend replacement within 5,000 miles", severity: "needs_work", status: "open", serviceRecordId: serviceRecords[1].id, notes: "Customer informed during 50K service. Quoted separately.", imageUrls: [] } }),
  1079. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[5].id, description: "CV boot torn on driver side, grease leaking onto suspension components", severity: "urgent", status: "open", notes: "Needs attention soon - will fail CV joint if not addressed.", imageUrls: [] } }),
  1080. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[1].id, description: "Slight oil seepage from valve cover gasket, monitor at next service", severity: "monitor", status: "open", serviceRecordId: serviceRecords[18].id, notes: "Not dripping yet - just damp. Re-check in 6 months.", imageUrls: [] } }),
  1081. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[8].id, description: "Battery testing at 78% capacity, recommend replacement before winter", severity: "monitor", status: "open", notes: "Still starts reliably. Load test shows degraded CCA.", imageUrls: [] } }),
  1082. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[2].id, description: "Tire tread below 4/32 on front tires, will need replacement soon", severity: "needs_work", status: "open", notes: "Rears still have 6/32. Recommend rotating and planning fronts soon.", imageUrls: [] } }),
  1083. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[9].id, description: "Coolant appears contaminated with oil traces, consider flush and inspection", severity: "needs_work", status: "open", serviceRecordId: serviceRecords[13].id, notes: "Found during turbo job. May be related to oil cooler seal.", imageUrls: [] } }),
  1084. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[11].id, description: "Death wobble symptoms reported - track bar bushings worn", severity: "urgent", status: "resolved", notes: "Customer reported highway death wobble. Replaced steering stabilizer and tie rods.", imageUrls: [] } }),
  1085. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[13].id, description: "Rear tire wear uneven - alignment suspected after track use", severity: "needs_work", status: "open", serviceRecordId: serviceRecords[3].id, notes: "Right rear shows inner edge wear consistent with toe-out.", imageUrls: [] } }),
  1086. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[17].id, description: "DEF tank heater intermittent - low DEF temperature warning in cold weather", severity: "monitor", status: "open", serviceRecordId: serviceRecords[4].id, notes: "Only acts up below 20F. Monitor and replace if it fails completely.", imageUrls: [] } }),
  1087. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[18].id, description: "Charge air cooler pipe cracked, boost leak confirmed", severity: "urgent", status: "open", notes: "Part ordered. Causing low-power complaint from driver.", imageUrls: [] } }),
  1088. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[19].id, description: "Dump body floor showing stress cracks near rear hinge", severity: "needs_work", status: "open", notes: "Will need weld repair within 10,000 miles to avoid structural failure.", imageUrls: [] } }),
  1089. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[22].id, description: "Front loader pins showing excessive play, bushings worn", severity: "needs_work", status: "open", notes: "Noticeable play when boom is fully extended. Replace at next service.", imageUrls: [] } }),
  1090. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[23].id, description: "A/C condenser fins damaged, reduced cooling efficiency", severity: "monitor", status: "open", notes: "Fins bent from field debris. Combing/straightening recommended.", imageUrls: [] } }),
  1091. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[29].id, description: "Left blade cylinder showing slow seepage at rod seal", severity: "monitor", status: "resolved", serviceRecordId: serviceRecords[8].id, resolvedServiceRecordId: serviceRecords[8].id, notes: "Resealed during Sept 2025 hydraulic overhaul.", imageUrls: [] } }),
  1092. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[31].id, description: "Boom cylinder showing 2 inch drift over 10 minutes under load", severity: "needs_work", status: "open", notes: "Cylinder reseal scheduled in unassigned work.", imageUrls: [] } }),
  1093. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[32].id, description: "Track shoe bolts loosening, retorque recommended", severity: "monitor", status: "open", notes: "Checked 8 of 42 shoes - 3 required retorque. Full inspection next service.", imageUrls: [] } }),
  1094. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[36].id, description: "Right rear outrigger extending slower than left", severity: "needs_work", status: "open", notes: "Likely valve or cylinder seal. Scheduled for inspection.", imageUrls: [] } }),
  1095. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[24].id, description: "Overheating under heavy PTO load - radiator partially blocked with chaff", severity: "needs_work", status: "open", notes: "Cleaned out what we could. Recommend pull radiator for deep clean.", imageUrls: [] } }),
  1096. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[34].id, description: "Hydraulic hose chafing against frame rail near pivot point", severity: "needs_work", status: "open", notes: "Protective sleeve worn through. Will fail if not rerouted.", imageUrls: [] } }),
  1097. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[16].id, description: "Leaf spring bushings dry and cracking, suspension noise reported", severity: "needs_work", status: "open", notes: "Customer scheduled for leaf spring replacement.", imageUrls: [] } }),
  1098. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[38].id, description: "Rear brake pads showing uneven wear from track use, inner pad thinner than outer", severity: "needs_work", status: "open", notes: "Likely caliper slide pins need cleaning and relubing. Recommend high-performance pads for track use.", imageUrls: [] } }),
  1099. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[39].id, description: "Front left CV boot starting to crack, no grease leaking yet", severity: "monitor", status: "open", notes: "Off-road flex likely contributing. Replace before it tears and contaminates the joint.", imageUrls: [] } }),
  1100. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[40].id, description: "Rear tires wearing faster on inside edge, alignment needed", severity: "needs_work", status: "open", notes: "Aggressive driving habit. Rear camber may be out of spec after pothole.", imageUrls: [] } }),
  1101. prisma.vehicleFinding.create({ data: { vehicleId: vehicles[41].id, description: "Exhaust manifold stud #3 showing early surface corrosion", severity: "monitor", status: "open", notes: "Not leaking yet. Anti-seize on next service. Watch for exhaust tick on cold start.", imageUrls: [] } }),
  1102. ]);
  1103. console.log(` Created ${findings.length} vehicle findings`);
  1104. // -- Repeat service history for predicted maintenance --
  1105. // Pick 6 vehicles, give each 3-4 completed service records with increasing mileage
  1106. // spanning 2-3 years so the predictedMaintenanceActions has regression data.
  1107. console.log("\nCreating repeat service history for predicted maintenance...");
  1108. type HistEntry = { offsetDays: number; mileage: number; title: string; desc: string; type: string; techName: string };
  1109. const predMaintHistory: { vehicleId: string; entries: HistEntry[] }[] = [
  1110. {
  1111. vehicleId: vehicles[1].id, // Ford F-150 Lariat white (Summit Construction, current 42300)
  1112. entries: [
  1113. { offsetDays: -820, mileage: 10500, title: "F-150 - 10K Oil Change", desc: "First service. Synthetic 5W-30, oil filter, tire rotation.", type: "maintenance", techName: "Jake Wilson" },
  1114. { offsetDays: -540, mileage: 20200, title: "F-150 - 20K Service", desc: "Oil change, cabin filter, brake inspection, tire rotation.", type: "maintenance", techName: "Jake Wilson" },
  1115. { offsetDays: -280, mileage: 30100, title: "F-150 - 30K Major Service", desc: "Full fluid service, spark plugs, transfer case fluid.", type: "maintenance", techName: "Chris Taylor" },
  1116. { offsetDays: -90, mileage: 40800, title: "F-150 - 40K Service", desc: "Oil change, brake fluid flush, differential service.", type: "maintenance", techName: "Jake Wilson" },
  1117. ],
  1118. },
  1119. {
  1120. vehicleId: vehicles[4].id, // BMW 330i xDrive (Sarah Coleman, current 55200)
  1121. entries: [
  1122. { offsetDays: -900, mileage: 22000, title: "BMW 330i - 22K Oil Service", desc: "OEM oil, filter, inspection. OEM parts only per customer.", type: "maintenance", techName: "Chris Taylor" },
  1123. { offsetDays: -600, mileage: 32500, title: "BMW 330i - 32K Service", desc: "Oil, cabin filter, brake inspection. All OEM BMW parts.", type: "maintenance", techName: "Chris Taylor" },
  1124. { offsetDays: -300, mileage: 43800, title: "BMW 330i - 43K Service", desc: "Oil change, tire rotation, 4-wheel alignment.", type: "maintenance", techName: "Chris Taylor" },
  1125. ],
  1126. },
  1127. {
  1128. vehicleId: vehicles[5].id, // Honda Civic Sport (Amanda Foster, current 67800)
  1129. entries: [
  1130. { offsetDays: -960, mileage: 28500, title: "Civic - 28K Oil Change", desc: "Synthetic oil, filter, tire rotation.", type: "maintenance", techName: "Jake Wilson" },
  1131. { offsetDays: -680, mileage: 39200, title: "Civic - 39K Service", desc: "Oil change, cabin filter, engine air filter.", type: "maintenance", techName: "Jake Wilson" },
  1132. { offsetDays: -360, mileage: 52000, title: "Civic - 52K Major Service", desc: "Oil, coolant flush, transmission fluid, belt inspection.", type: "maintenance", techName: "Sofia Andersen" },
  1133. { offsetDays: -110, mileage: 64500, title: "Civic - 64K Service", desc: "Oil change, brake pad inspection, alignment check.", type: "maintenance", techName: "Jake Wilson" },
  1134. ],
  1135. },
  1136. {
  1137. vehicleId: vehicles[8].id, // Silverado 2500HD (Lisa Martinez, current 98400)
  1138. entries: [
  1139. { offsetDays: -850, mileage: 62000, title: "Silverado - 62K Oil Service", desc: "Duramax diesel oil, fuel filters, DEF top-off.", type: "maintenance", techName: "Marcus Reed" },
  1140. { offsetDays: -560, mileage: 75500, title: "Silverado - 75K Service", desc: "Oil, fuel filters, DEF fluid, tire rotation.", type: "maintenance", techName: "Marcus Reed" },
  1141. { offsetDays: -290, mileage: 87200, title: "Silverado - 87K Major Service", desc: "Oil, coolant flush, transmission service, DPF regen.", type: "maintenance", techName: "Marcus Reed" },
  1142. { offsetDays: -60, mileage: 96100, title: "Silverado - 96K Service", desc: "Oil change, fuel filter, brake inspection.", type: "maintenance", techName: "Jake Wilson" },
  1143. ],
  1144. },
  1145. {
  1146. vehicleId: vehicles[17].id, // Kenworth T680 (Pacific Freight, current 185000)
  1147. entries: [
  1148. { offsetDays: -780, mileage: 92000, title: "Kenworth - 92K PM", desc: "Full PM - oil, fuel filters, air filters, inspection.", type: "maintenance", techName: "Marcus Reed" },
  1149. { offsetDays: -520, mileage: 118000, title: "Kenworth - 118K PM", desc: "Engine oil, all filters, DEF, grease service.", type: "maintenance", techName: "Marcus Reed" },
  1150. { offsetDays: -260, mileage: 148000, title: "Kenworth - 148K PM", desc: "Engine oil, all filters, coolant check, brake adjust.", type: "maintenance", techName: "Marcus Reed" },
  1151. ],
  1152. },
  1153. {
  1154. vehicleId: vehicles[16].id, // Tacoma TRD Off-Road (Lisa Martinez, current 31200)
  1155. entries: [
  1156. { offsetDays: -790, mileage: 8500, title: "Tacoma - 8K Oil Change", desc: "First service. Synthetic oil, filter, tire rotation.", type: "maintenance", techName: "Jake Wilson" },
  1157. { offsetDays: -520, mileage: 15800, title: "Tacoma - 15K Service", desc: "Oil change, cabin filter, brake inspection.", type: "maintenance", techName: "Jake Wilson" },
  1158. { offsetDays: -250, mileage: 24200, title: "Tacoma - 24K Service", desc: "Oil, tire rotation, differential fluid check.", type: "maintenance", techName: "Erik Haugen" },
  1159. ],
  1160. },
  1161. ];
  1162. const today = TODAY;
  1163. const predMaintRecords = [];
  1164. for (const hist of predMaintHistory) {
  1165. for (const entry of hist.entries) {
  1166. const serviceDate = new Date(today);
  1167. serviceDate.setDate(serviceDate.getDate() + entry.offsetDays);
  1168. const rec = await prisma.serviceRecord.create({
  1169. data: {
  1170. vehicleId: hist.vehicleId,
  1171. organizationId: ORG_ID,
  1172. title: entry.title,
  1173. description: entry.desc,
  1174. type: entry.type,
  1175. status: "completed",
  1176. serviceDate,
  1177. mileage: entry.mileage,
  1178. techName: entry.techName,
  1179. shopName: "Egeland Auto",
  1180. subtotal: 180,
  1181. taxRate: 8,
  1182. taxAmount: 14.40,
  1183. totalAmount: 194.40,
  1184. cost: 194.40,
  1185. partItems: { create: [{ name: "Synthetic Oil (5qt)", partNumber: "OIL-SYN-5Q", quantity: 1, unitPrice: 45, total: 45 }, { name: "Oil Filter", partNumber: "OF-UNI", quantity: 1, unitPrice: 12, total: 12 }] },
  1186. laborItems: { create: [{ description: "Service and inspection", hours: 1.2, rate: 102.50, total: 123 }] },
  1187. },
  1188. });
  1189. predMaintRecords.push(rec);
  1190. }
  1191. }
  1192. console.log(` Created ${predMaintRecords.length} historical service records across ${predMaintHistory.length} vehicles`);
  1193. // Enable predicted maintenance feature setting
  1194. console.log("\nEnabling predicted maintenance feature...");
  1195. await Promise.all([
  1196. prisma.appSetting.upsert({
  1197. where: { organizationId_key: { organizationId: ORG_ID, key: "maintenance.enabled" } },
  1198. create: { organizationId: ORG_ID, key: "maintenance.enabled", value: "true", userId: USER_ID },
  1199. update: { value: "true" },
  1200. }),
  1201. prisma.appSetting.upsert({
  1202. where: { organizationId_key: { organizationId: ORG_ID, key: "maintenance.serviceInterval" } },
  1203. create: { organizationId: ORG_ID, key: "maintenance.serviceInterval", value: "15000", userId: USER_ID },
  1204. update: { value: "15000" },
  1205. }),
  1206. prisma.appSetting.upsert({
  1207. where: { organizationId_key: { organizationId: ORG_ID, key: "maintenance.approachingThreshold" } },
  1208. create: { organizationId: ORG_ID, key: "maintenance.approachingThreshold", value: "1000", userId: USER_ID },
  1209. update: { value: "1000" },
  1210. }),
  1211. ]);
  1212. console.log(" Enabled predicted maintenance (interval: 15,000 mi, approaching: 1,000 mi)");
  1213. // -- SMS Messages --
  1214. console.log("\nCreating SMS messages...");
  1215. const shopNumber = "+15555550100";
  1216. await Promise.all([
  1217. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550101", body: "Hi Summit Construction, your Ford F-150 (CO-4455) transmission flush is complete. Total: $689.04. Ready for pickup.", status: "delivered", organizationId: ORG_ID, customerId: customers[0].id } }),
  1218. prisma.smsMessage.create({ data: { direction: "inbound", fromNumber: "+15555550101", toNumber: shopNumber, body: "Thanks! We'll send someone before 4pm. Can you look at the D6 bulldozer next week? Blade cylinder is leaking again.", status: "received", organizationId: ORG_ID, customerId: customers[0].id, createdAt: new Date(Date.now() - 3500000) } }),
  1219. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550101", body: "Absolutely, we can fit the D6 in on Tuesday. We'll order the seal kit ahead of time.", status: "delivered", organizationId: ORG_ID, customerId: customers[0].id, createdAt: new Date(Date.now() - 3400000) } }),
  1220. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550102", body: "Hi James, your Toyota Camry is due for its 30K service. We have Thursday or Friday availability.", status: "delivered", organizationId: ORG_ID, customerId: customers[1].id, createdAt: new Date(Date.now() - 86400000) } }),
  1221. prisma.smsMessage.create({ data: { direction: "inbound", fromNumber: "+15555550102", toNumber: shopNumber, body: "Thursday morning works. Synthetic oil like last time please.", status: "received", organizationId: ORG_ID, customerId: customers[1].id, createdAt: new Date(Date.now() - 82800000) } }),
  1222. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550102", body: "Thursday 8am confirmed. Full synthetic 0W-20 as always. See you then!", status: "delivered", organizationId: ORG_ID, customerId: customers[1].id, createdAt: new Date(Date.now() - 82000000) } }),
  1223. prisma.smsMessage.create({ data: { direction: "inbound", fromNumber: "+15555550103", toNumber: shopNumber, body: "Our Volvo FH 640 (unit #5) is showing a check engine light. Can you get it in ASAP?", status: "received", organizationId: ORG_ID, customerId: customers[2].id, createdAt: new Date(Date.now() - 172800000) } }),
  1224. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550103", body: "We can take the Volvo FH 640 first thing tomorrow. Have the driver bring it in by 7am.", status: "delivered", organizationId: ORG_ID, customerId: customers[2].id, createdAt: new Date(Date.now() - 172000000) } }),
  1225. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550103", body: "Update on the Volvo FH 640: DOT inspection in progress. Minor issues with marker lights and wipers. Done by 3pm.", status: "delivered", organizationId: ORG_ID, customerId: customers[2].id, createdAt: new Date(Date.now() - 86400000) } }),
  1226. prisma.smsMessage.create({ data: { direction: "inbound", fromNumber: "+15555550111", toNumber: shopNumber, body: "Our John Deere 6R is running rough and hydraulics feel sluggish. Planting season starts in 3 weeks!", status: "received", organizationId: ORG_ID, customerId: customers[10].id, createdAt: new Date(Date.now() - 432000000) } }),
  1227. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550111", body: "Bring the John Deere 6R in this week, we'll bump it to priority. Likely needs 500hr service + hydraulic analysis.", status: "delivered", organizationId: ORG_ID, customerId: customers[10].id, createdAt: new Date(Date.now() - 428400000) } }),
  1228. prisma.smsMessage.create({ data: { direction: "inbound", fromNumber: "+15555550111", toNumber: shopNumber, body: "Great. The Massey Ferguson 8S has low hydraulic pressure too. Can you look at both?", status: "received", organizationId: ORG_ID, customerId: customers[10].id, createdAt: new Date(Date.now() - 424800000) } }),
  1229. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550111", body: "Bring both Wednesday. JD done same day, Massey Thursday. Both ready before planting.", status: "delivered", organizationId: ORG_ID, customerId: customers[10].id, createdAt: new Date(Date.now() - 421200000) } }),
  1230. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550116", body: "Kevin, your Sprinter turbo has excessive shaft play causing black smoke. Replacement: $1,280 + labor. Proceed?", status: "delivered", organizationId: ORG_ID, customerId: customers[15].id, createdAt: new Date(Date.now() - 345600000) } }),
  1231. prisma.smsMessage.create({ data: { direction: "inbound", fromNumber: "+15555550116", toNumber: shopNumber, body: "Ouch. Yeah go ahead, I need the van for catering events next week.", status: "received", organizationId: ORG_ID, customerId: customers[15].id, createdAt: new Date(Date.now() - 342000000) } }),
  1232. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550116", body: "Parts arrive Thursday, done Friday afternoon. Total: $2,243.70 including oil change.", status: "delivered", organizationId: ORG_ID, customerId: customers[15].id, createdAt: new Date(Date.now() - 338400000) } }),
  1233. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550109", body: "Ridgeline, the Komatsu PC210 track chains are done. Both sides + new sprockets. Total: $9,309.60. Ready for transport.", status: "delivered", organizationId: ORG_ID, customerId: customers[8].id, createdAt: new Date(Date.now() - 604800000) } }),
  1234. prisma.smsMessage.create({ data: { direction: "inbound", fromNumber: "+15555550109", toNumber: shopNumber, body: "Excellent work. Sending the lowboy tomorrow. Also sending the Volvo EC220E for 1000hr service.", status: "received", organizationId: ORG_ID, customerId: customers[8].id, createdAt: new Date(Date.now() - 601200000) } }),
  1235. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550109", body: "We have Volvo EC220E filters in stock. 1-2 day turnaround once it arrives.", status: "delivered", organizationId: ORG_ID, customerId: customers[8].id, createdAt: new Date(Date.now() - 597600000) } }),
  1236. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550104", body: "Hi Sarah, your Porsche 911 annual service is complete. Total: $832.14. All OEM parts as always.", status: "delivered", organizationId: ORG_ID, customerId: customers[3].id, createdAt: new Date(Date.now() - 259200000) } }),
  1237. prisma.smsMessage.create({ data: { direction: "inbound", fromNumber: "+15555550104", toNumber: shopNumber, body: "Perfect, thank you. I also want to get a quote on the BMW brake job with OEM rotors.", status: "received", organizationId: ORG_ID, customerId: customers[3].id, createdAt: new Date(Date.now() - 255600000) } }),
  1238. prisma.smsMessage.create({ data: { direction: "outbound", fromNumber: shopNumber, toNumber: "+15555550104", body: "Quote sent to your email - $1,711.80 for the full brake overhaul with OEM rotors and pads. Valid until March 15.", status: "delivered", organizationId: ORG_ID, customerId: customers[3].id, createdAt: new Date(Date.now() - 254000000) } }),
  1239. ]);
  1240. console.log(" Created 22 SMS messages");
  1241. // -- Technicians & Work Board --
  1242. console.log("\nCreating technicians...");
  1243. // Clean up existing workboard data
  1244. await prisma.technician.deleteMany({ where: { organizationId: ORG_ID } });
  1245. const technicians = await Promise.all([
  1246. prisma.technician.create({ data: { name: "Jake Wilson", color: "#3b82f6", sortOrder: 0, organizationId: ORG_ID } }),
  1247. prisma.technician.create({ data: { name: "Chris Taylor", color: "#22c55e", sortOrder: 1, organizationId: ORG_ID } }),
  1248. prisma.technician.create({ data: { name: "Marcus Reed", color: "#f59e0b", sortOrder: 2, organizationId: ORG_ID } }),
  1249. prisma.technician.create({ data: { name: "Sofia Andersen", color: "#ec4899", sortOrder: 3, organizationId: ORG_ID } }),
  1250. prisma.technician.create({ data: { name: "Erik Haugen", color: "#8b5cf6", sortOrder: 4, organizationId: ORG_ID } }),
  1251. prisma.technician.create({ data: { name: "Lars Johansen", color: "#06b6d4", sortOrder: 5, organizationId: ORG_ID } }),
  1252. prisma.technician.create({ data: { name: "Nina Berglund", color: "#f97316", sortOrder: 6, organizationId: ORG_ID } }),
  1253. prisma.technician.create({ data: { name: "Tom Bradley", color: "#14b8a6", sortOrder: 7, organizationId: ORG_ID } }),
  1254. prisma.technician.create({ data: { name: "Kari Moen", color: "#a855f7", sortOrder: 8, organizationId: ORG_ID } }),
  1255. prisma.technician.create({ data: { name: "Daniel Eriksen", color: "#ef4444", sortOrder: 9, organizationId: ORG_ID } }),
  1256. // Demo Owner (index 10) — linked to the demo user so dashboard "My Active Jobs" populates
  1257. prisma.technician.create({ data: { name: "Demo Owner", color: "#0ea5e9", sortOrder: 10, organizationId: ORG_ID, userId: USER_ID } }),
  1258. ]);
  1259. console.log(` Created ${technicians.length} technicians`);
  1260. // Board assignments - spread across the current week
  1261. console.log("\nCreating board assignments...");
  1262. // Monday of the week the board showcases - see weekMonday().
  1263. const monday = weekMonday();
  1264. const day = (offset: number) => {
  1265. const d = new Date(monday);
  1266. d.setDate(d.getDate() + offset);
  1267. return d;
  1268. };
  1269. // Helper: create a datetime on a given day offset at a specific hour:minute
  1270. const dt = (dayOffset: number, hour: number, minute = 0) => {
  1271. const d = new Date(monday);
  1272. d.setDate(d.getDate() + dayOffset);
  1273. d.setHours(hour, minute, 0, 0);
  1274. return d;
  1275. };
  1276. // Helper to create service record with parts + labor
  1277. const sr = (base: Record<string, unknown>, parts: { name: string; partNumber: string; quantity: number; unitPrice: number; total: number }[], labor: { description: string; hours: number; rate: number; total: number }[], notes?: string) => {
  1278. const subtotal = parts.reduce((s, p) => s + p.total, 0) + labor.reduce((s, l) => s + l.total, 0);
  1279. const taxAmount = Math.round(subtotal * 0.08 * 100) / 100;
  1280. return prisma.serviceRecord.create({ data: { ...base, organizationId: ORG_ID, subtotal, taxRate: 8, taxAmount, totalAmount: subtotal + taxAmount, cost: subtotal + taxAmount, diagnosticNotes: notes || null, partItems: { create: parts }, laborItems: { create: labor } } as never });
  1281. };
  1282. // Create service records for the board (assigned ones)
  1283. const boardServiceRecords = await Promise.all([
  1284. // 0: Honda Civic AC
  1285. sr({ vehicleId: vehicles[5].id, title: "Honda Civic - AC Compressor", description: "AC not blowing cold. Compressor clutch not engaging.", type: "repair", status: "pending", serviceDate: day(0), mileage: 45200, techName: "Jake Wilson", shopName: "Egeland Auto" },
  1286. [{ name: "AC Compressor Assembly", partNumber: "HON-ACC-10G", quantity: 1, unitPrice: 480, total: 480 }, { name: "Refrigerant R-134a (2 cans)", partNumber: "REF-134A-2", quantity: 1, unitPrice: 45, total: 45 }],
  1287. [{ description: "AC compressor removal and replacement", hours: 2.5, rate: 110, total: 275 }, { description: "System evacuate, recharge and leak test", hours: 1.0, rate: 110, total: 110 }],
  1288. "Compressor clutch not engaging. Checked voltage at clutch connector - 12V present. Clutch coil resistance out of spec. Replace compressor assembly."),
  1289. // 1: Audi A4 timing belt
  1290. sr({ vehicleId: vehicles[10].id, title: "Audi A4 - Timing Belt Service", description: "Scheduled timing belt and water pump replacement at 60K miles.", type: "maintenance", status: "scheduled", serviceDate: day(0), mileage: 60000, techName: "Chris Taylor", shopName: "Egeland Auto" },
  1291. [{ name: "Timing Belt Kit w/ Water Pump", partNumber: "AUD-TBK-A4", quantity: 1, unitPrice: 385, total: 385 }, { name: "Thermostat Assembly", partNumber: "AUD-TH-A4", quantity: 1, unitPrice: 65, total: 65 }, { name: "Coolant G13 (5L)", partNumber: "AUD-COOL-G13", quantity: 1, unitPrice: 42, total: 42 }],
  1292. [{ description: "Timing belt and water pump replacement", hours: 4.5, rate: 120, total: 540 }, { description: "Coolant flush and bleed", hours: 1.0, rate: 120, total: 120 }]),
  1293. // 2: Tesla Model Y suspension
  1294. sr({ vehicleId: vehicles[7].id, title: "Tesla Model Y - Suspension Noise", description: "Customer reports clunking from front left over bumps.", type: "repair", status: "pending", serviceDate: day(1), mileage: 32000, techName: "Sofia Andersen", shopName: "Egeland Auto" },
  1295. [{ name: "Front Lower Control Arm (L)", partNumber: "TES-LCA-MY-L", quantity: 1, unitPrice: 290, total: 290 }],
  1296. [{ description: "Diagnose suspension noise", hours: 0.5, rate: 110, total: 55 }, { description: "Control arm replacement and alignment", hours: 2.0, rate: 110, total: 220 }],
  1297. "Play found in front left lower control arm ball joint. No other issues found. Recommend alignment after replacement."),
  1298. // 3: Silverado 60K
  1299. sr({ vehicleId: vehicles[8].id, title: "Silverado - 60K Service", description: "60,000 mile major service. Transmission fluid, spark plugs, coolant flush.", type: "maintenance", status: "scheduled", serviceDate: day(1), mileage: 60000, techName: "Jake Wilson", shopName: "Egeland Auto" },
  1300. [{ name: "ATF Dexron VI (12qt)", partNumber: "GM-ATF-DEX6", quantity: 1, unitPrice: 120, total: 120 }, { name: "Spark Plugs ACDelco (8)", partNumber: "ACD-SP-53", quantity: 8, unitPrice: 12, total: 96 }, { name: "Coolant Dex-Cool (2gal)", partNumber: "GM-COOL-DC", quantity: 1, unitPrice: 38, total: 38 }],
  1301. [{ description: "Transmission fluid exchange", hours: 1.5, rate: 110, total: 165 }, { description: "Spark plug replacement (V8)", hours: 1.5, rate: 110, total: 165 }, { description: "Coolant flush and refill", hours: 1.0, rate: 110, total: 110 }]),
  1302. // 4: Tacoma leaf springs
  1303. sr({ vehicleId: vehicles[16].id, title: "Toyota Tacoma - Leaf Spring Replacement", description: "Rear leaf springs sagging. Replace with upgraded OEM springs.", type: "repair", status: "pending", serviceDate: day(1), mileage: 55000, techName: "Erik Haugen", shopName: "Egeland Auto" },
  1304. [{ name: "Rear Leaf Spring Pack (pair)", partNumber: "TOY-LS-TAC", quantity: 1, unitPrice: 520, total: 520 }, { name: "U-Bolt Kit", partNumber: "TOY-UB-TAC", quantity: 1, unitPrice: 85, total: 85 }],
  1305. [{ description: "Leaf spring removal and installation (both sides)", hours: 3.5, rate: 110, total: 385 }]),
  1306. // 5: Bobcat S650 annual
  1307. sr({ vehicleId: vehicles[32].id, title: "Bobcat S650 - Annual Service", description: "Full annual service. Engine oil, hydraulic filters, drive belt.", type: "maintenance", status: "scheduled", serviceDate: day(2), mileage: 2200, techName: "Marcus Reed", shopName: "Egeland Auto" },
  1308. [{ name: "Engine Oil 15W-40 (2gal)", partNumber: "BOB-15W40-2G", quantity: 1, unitPrice: 68, total: 68 }, { name: "Oil Filter", partNumber: "BOB-OF-S650", quantity: 1, unitPrice: 22, total: 22 }, { name: "Hydraulic Filter Set", partNumber: "BOB-HFS-S650", quantity: 1, unitPrice: 95, total: 95 }, { name: "Drive Belt", partNumber: "BOB-DB-S650", quantity: 1, unitPrice: 48, total: 48 }],
  1309. [{ description: "Engine oil and filter change", hours: 1.0, rate: 130, total: 130 }, { description: "Hydraulic filter replacement", hours: 1.0, rate: 130, total: 130 }, { description: "Drive belt inspection and replacement", hours: 0.5, rate: 130, total: 65 }]),
  1310. // 6: CAT 745 transmission rebuild
  1311. sr({ vehicleId: vehicles[34].id, title: "CAT 745 - Transmission Rebuild", description: "Slipping in 3rd gear under load. Full transmission rebuild.", type: "repair", status: "in_progress", serviceDate: day(0), mileage: 8500, techName: "Marcus Reed", shopName: "Egeland Auto" },
  1312. [{ name: "Transmission Rebuild Kit", partNumber: "CAT-TRK-745", quantity: 1, unitPrice: 4200, total: 4200 }, { name: "Torque Converter", partNumber: "CAT-TC-745", quantity: 1, unitPrice: 2800, total: 2800 }, { name: "Transmission Oil (20gal)", partNumber: "CAT-TO-20G", quantity: 1, unitPrice: 480, total: 480 }],
  1313. [{ description: "Transmission removal", hours: 8.0, rate: 150, total: 1200 }, { description: "Rebuild and reassembly", hours: 16.0, rate: 150, total: 2400 }, { description: "Installation and calibration", hours: 6.0, rate: 150, total: 900 }],
  1314. "3rd gear clutch pack worn beyond spec. Torque converter showing excessive slip. Full rebuild recommended over clutch pack only due to hours on unit."),
  1315. // 7: F-150 exhaust
  1316. sr({ vehicleId: vehicles[3].id, title: "Ford F-150 - Exhaust Leak Repair", description: "Exhaust manifold gasket leak. Replace gasket and inspect cat.", type: "repair", status: "pending", serviceDate: day(2), mileage: 52000, techName: "Jake Wilson", shopName: "Egeland Auto" },
  1317. [{ name: "Exhaust Manifold Gasket Set", partNumber: "FORD-EMG-5L", quantity: 1, unitPrice: 85, total: 85 }, { name: "Exhaust Manifold Bolts (set)", partNumber: "FORD-EMB-5L", quantity: 1, unitPrice: 42, total: 42 }],
  1318. [{ description: "Manifold removal and gasket replacement", hours: 2.5, rate: 110, total: 275 }, { description: "Cat converter inspection", hours: 0.5, rate: 110, total: 55 }]),
  1319. // 8: Ram transfer case
  1320. sr({ vehicleId: vehicles[16].id, title: "Ram 1500 - Transfer Case Service", description: "Transfer case fluid change. Customer reports 4WD engagement delay.", type: "maintenance", status: "pending", serviceDate: day(3), mileage: 45000, techName: "Sofia Andersen", shopName: "Egeland Auto" },
  1321. [{ name: "Transfer Case Fluid (2qt)", partNumber: "RAM-TCF-2Q", quantity: 1, unitPrice: 48, total: 48 }, { name: "Transfer Case Drain Plug Gasket", partNumber: "RAM-DPG-TC", quantity: 1, unitPrice: 8, total: 8 }],
  1322. [{ description: "Transfer case fluid drain and refill", hours: 1.0, rate: 110, total: 110 }, { description: "4WD engagement test and inspection", hours: 0.5, rate: 110, total: 55 }],
  1323. "Fluid was dark and slightly burnt. Delay was from low fluid level. Refilled and tested - engages promptly now. Monitor."),
  1324. // 9: Combine pre-season
  1325. sr({ vehicleId: vehicles[27].id, title: "Combine Harvester - Pre-Season Prep", description: "Full pre-season inspection. Header, feeder chain, sieve adjustments, all fluids.", type: "maintenance", status: "scheduled", serviceDate: day(4), mileage: 2800, techName: "Marcus Reed", shopName: "Egeland Auto" },
  1326. [{ name: "Engine Oil 15W-40 (5gal)", partNumber: "CMB-15W40-5G", quantity: 1, unitPrice: 185, total: 185 }, { name: "Hydraulic Filter Set", partNumber: "CMB-HFS", quantity: 1, unitPrice: 110, total: 110 }, { name: "Feeder Chain", partNumber: "CMB-FC-1", quantity: 1, unitPrice: 380, total: 380 }, { name: "Sieve Section (2)", partNumber: "CMB-SS-2", quantity: 2, unitPrice: 145, total: 290 }],
  1327. [{ description: "Engine oil and filter change", hours: 1.5, rate: 140, total: 210 }, { description: "Feeder chain replacement", hours: 2.5, rate: 140, total: 350 }, { description: "Sieve adjustment and replacement", hours: 2.0, rate: 140, total: 280 }, { description: "Full system inspection and grease", hours: 2.0, rate: 140, total: 280 }]),
  1328. // 10: Jeep axle seal
  1329. sr({ vehicleId: vehicles[12].id, title: "Jeep Wrangler - Axle Seal Replacement", description: "Rear axle seal leaking. Replace seals and check diff fluid.", type: "repair", status: "pending", serviceDate: day(4), mileage: 62000, techName: "Chris Taylor", shopName: "Egeland Auto" },
  1330. [{ name: "Rear Axle Seal Kit", partNumber: "JEEP-ASK-JL", quantity: 1, unitPrice: 65, total: 65 }, { name: "Differential Fluid 75W-140 (2.5qt)", partNumber: "JEEP-DF-75W", quantity: 1, unitPrice: 52, total: 52 }],
  1331. [{ description: "Axle seal replacement (both sides)", hours: 2.5, rate: 110, total: 275 }, { description: "Differential fluid top-off and inspection", hours: 0.5, rate: 110, total: 55 }]),
  1332. // 11: Ram oil change (Lars)
  1333. sr({ vehicleId: vehicles[15].id, title: "Ram 1500 - Oil Change & Inspection", description: "Regular 10K mile service. Check brakes and tires.", type: "maintenance", status: "scheduled", serviceDate: day(0), mileage: 30000, techName: "Lars Johansen", shopName: "Egeland Auto" },
  1334. [{ name: "Engine Oil 5W-20 (7qt)", partNumber: "RAM-5W20-7Q", quantity: 1, unitPrice: 52, total: 52 }, { name: "Oil Filter", partNumber: "RAM-OF-HEMI", quantity: 1, unitPrice: 14, total: 14 }],
  1335. [{ description: "Oil and filter change", hours: 0.5, rate: 110, total: 55 }, { description: "Brake and tire inspection", hours: 0.5, rate: 110, total: 55 }]),
  1336. // 12: F-150 wheel bearing (Nina)
  1337. sr({ vehicleId: vehicles[2].id, title: "Ford F-150 - Wheel Bearing", description: "Front left wheel bearing noise. Replace bearing assembly.", type: "repair", status: "pending", serviceDate: day(1), mileage: 68000, techName: "Nina Berglund", shopName: "Egeland Auto" },
  1338. [{ name: "Front Wheel Bearing Hub Assembly", partNumber: "FORD-WBH-F150", quantity: 1, unitPrice: 285, total: 285 }],
  1339. [{ description: "Wheel bearing hub replacement", hours: 2.0, rate: 110, total: 220 }, { description: "Road test and verify", hours: 0.5, rate: 110, total: 55 }],
  1340. "Confirmed bearing noise from front left. Bearing has play when checked on lift. Right side OK for now."),
  1341. // 13: Concrete mixer (Tom)
  1342. sr({ vehicleId: vehicles[20].id, title: "Concrete Mixer - Drum Motor Service", description: "Hydraulic motor service for drum rotation. Sluggish under load.", type: "repair", status: "in_progress", serviceDate: day(0), mileage: 75000, techName: "Tom Bradley", shopName: "Egeland Auto" },
  1343. [{ name: "Hydraulic Motor Seal Kit", partNumber: "MIX-HMSK", quantity: 1, unitPrice: 280, total: 280 }, { name: "Hydraulic Oil ISO 46 (10gal)", partNumber: "HYD-ISO46-10G", quantity: 1, unitPrice: 180, total: 180 }, { name: "Hydraulic Hose Assembly", partNumber: "MIX-HHA-12", quantity: 2, unitPrice: 95, total: 190 }],
  1344. [{ description: "Hydraulic motor removal and reseal", hours: 4.0, rate: 140, total: 560 }, { description: "Hose replacement and system flush", hours: 2.0, rate: 140, total: 280 }, { description: "Load test drum rotation", hours: 1.0, rate: 140, total: 140 }]),
  1345. // 14: Tractor PTO (Kari)
  1346. sr({ vehicleId: vehicles[25].id, title: "Tractor - PTO Clutch Adjustment", description: "PTO slipping under heavy load. Adjust clutch pack and inspect.", type: "repair", status: "pending", serviceDate: day(2), mileage: 3200, techName: "Kari Moen", shopName: "Egeland Auto" },
  1347. [{ name: "PTO Clutch Friction Disc Set", partNumber: "TRC-PTO-FDS", quantity: 1, unitPrice: 165, total: 165 }],
  1348. [{ description: "PTO clutch pack inspection and adjustment", hours: 2.0, rate: 130, total: 260 }],
  1349. "Clutch pack within adjustment range. Adjusted gap to spec. If slipping persists, full clutch pack replacement needed."),
  1350. // 15: Dump truck tailgate (Daniel)
  1351. sr({ vehicleId: vehicles[21].id, title: "Dump Truck - Tailgate Cylinder", description: "Tailgate cylinder leaking. Reseal and test.", type: "repair", status: "scheduled", serviceDate: day(1), mileage: 120000, techName: "Daniel Eriksen", shopName: "Egeland Auto" },
  1352. [{ name: "Tailgate Cylinder Seal Kit", partNumber: "DMP-TCSK", quantity: 1, unitPrice: 145, total: 145 }, { name: "Hydraulic Oil ISO 46 (5gal)", partNumber: "HYD-ISO46-5G", quantity: 1, unitPrice: 95, total: 95 }],
  1353. [{ description: "Cylinder removal and reseal", hours: 3.0, rate: 130, total: 390 }, { description: "Reinstall and cycle test", hours: 1.0, rate: 130, total: 130 }]),
  1354. // 16: Forklift mast chain (Lars)
  1355. sr({ vehicleId: vehicles[37].id, title: "Forklift - Mast Chain Replace", description: "Mast chain stretched beyond spec. Replace chains and adjust.", type: "repair", status: "pending", serviceDate: day(3), mileage: 5500, techName: "Lars Johansen", shopName: "Egeland Auto" },
  1356. [{ name: "Mast Chain (pair)", partNumber: "FRK-MC-PAIR", quantity: 1, unitPrice: 420, total: 420 }, { name: "Chain Anchor Pins", partNumber: "FRK-CAP-4", quantity: 1, unitPrice: 35, total: 35 }],
  1357. [{ description: "Mast chain removal and replacement", hours: 2.5, rate: 120, total: 300 }, { description: "Chain tension adjustment and mast alignment", hours: 1.0, rate: 120, total: 120 }]),
  1358. // 17: VW Golf clutch (Nina)
  1359. sr({ vehicleId: vehicles[14].id, title: "VW Golf GTI - Clutch Replace", description: "Clutch slipping at high RPM. Replace disc, pressure plate, throwout bearing.", type: "repair", status: "scheduled", serviceDate: day(2), mileage: 72000, techName: "Nina Berglund", shopName: "Egeland Auto" },
  1360. [{ name: "Clutch Kit (disc, plate, bearing)", partNumber: "VW-CK-GTI", quantity: 1, unitPrice: 480, total: 480 }, { name: "Flywheel Bolts (set)", partNumber: "VW-FWB-GTI", quantity: 1, unitPrice: 32, total: 32 }],
  1361. [{ description: "Transmission removal", hours: 3.5, rate: 120, total: 420 }, { description: "Clutch replacement and installation", hours: 2.5, rate: 120, total: 300 }, { description: "Bleed hydraulic clutch and road test", hours: 1.0, rate: 120, total: 120 }]),
  1362. // 18: Combine header knives (Tom)
  1363. sr({ vehicleId: vehicles[28].id, title: "Combine - Header Knife Sharpen", description: "Sharpen and replace worn header knives. 4 sections need new blades.", type: "maintenance", status: "pending", serviceDate: day(4), mileage: 2900, techName: "Tom Bradley", shopName: "Egeland Auto" },
  1364. [{ name: "Header Knife Sections (pack of 10)", partNumber: "CMB-HKS-10", quantity: 1, unitPrice: 85, total: 85 }, { name: "Knife Rivets (50-pack)", partNumber: "CMB-KR-50", quantity: 1, unitPrice: 22, total: 22 }],
  1365. [{ description: "Remove header knives", hours: 1.0, rate: 120, total: 120 }, { description: "Sharpen and replace worn sections", hours: 2.0, rate: 120, total: 240 }, { description: "Reinstall and test", hours: 1.0, rate: 120, total: 120 }]),
  1366. // 19: Kenworth clutch (Kari)
  1367. sr({ vehicleId: vehicles[17].id, title: "Kenworth T680 - Clutch Adjustment", description: "Driver reports clutch engagement point too high. Adjust and inspect.", type: "repair", status: "pending", serviceDate: day(3), mileage: 185000, techName: "Kari Moen", shopName: "Egeland Auto" },
  1368. [{ name: "Clutch Adjustment Hardware", partNumber: "KW-CAH-T680", quantity: 1, unitPrice: 45, total: 45 }],
  1369. [{ description: "Clutch linkage inspection and adjustment", hours: 1.5, rate: 140, total: 210 }, { description: "Road test under load", hours: 0.5, rate: 140, total: 70 }]),
  1370. // 20: Jeep steering stabilizer (Daniel)
  1371. sr({ vehicleId: vehicles[11].id, title: "Jeep Wrangler - Steering Stabilizer", description: "Death wobble at highway speed. Replace stabilizer and check tie rods.", type: "repair", status: "scheduled", serviceDate: day(4), mileage: 31000, techName: "Daniel Eriksen", shopName: "Egeland Auto" },
  1372. [{ name: "Steering Stabilizer", partNumber: "JEEP-SS-JL", quantity: 1, unitPrice: 125, total: 125 }, { name: "Tie Rod End (pair)", partNumber: "JEEP-TRE-JL", quantity: 1, unitPrice: 140, total: 140 }],
  1373. [{ description: "Steering stabilizer replacement", hours: 0.5, rate: 110, total: 55 }, { description: "Tie rod end inspection and replacement", hours: 1.5, rate: 110, total: 165 }]),
  1374. // Friday extras (20–29)
  1375. // 21: Camry cabin filter (Jake)
  1376. sr({ vehicleId: vehicles[0].id, title: "Toyota Camry - Cabin Filter + Wipers", description: "Replace cabin air filter and wiper blades. Quick service.", type: "maintenance", status: "scheduled", serviceDate: day(4), mileage: 16500, techName: "Jake Wilson", shopName: "Egeland Auto" },
  1377. [{ name: "Cabin Air Filter", partNumber: "TOY-CAF-CAM", quantity: 1, unitPrice: 22, total: 22 }, { name: "Wiper Blade Set (front)", partNumber: "TOY-WB-CAM", quantity: 1, unitPrice: 38, total: 38 }],
  1378. [{ description: "Cabin filter and wiper replacement", hours: 0.3, rate: 95, total: 28.50 }]),
  1379. // 22: Honda brakes (Jake)
  1380. sr({ vehicleId: vehicles[5].id, title: "Honda Civic - Brake Pad Replace", description: "Front pads worn to 2mm. Replace front brake pads.", type: "repair", status: "pending", serviceDate: day(4), mileage: 46000, techName: "Jake Wilson", shopName: "Egeland Auto" },
  1381. [{ name: "Front Brake Pad Set", partNumber: "HON-BP-CIV", quantity: 1, unitPrice: 85, total: 85 }, { name: "Brake Cleaner (2 cans)", partNumber: "BC-CLEAN-2", quantity: 1, unitPrice: 12, total: 12 }],
  1382. [{ description: "Front brake pad replacement", hours: 1.0, rate: 95, total: 95 }, { description: "Brake inspection and road test", hours: 0.3, rate: 95, total: 28.50 }]),
  1383. // 23: Silverado taillight (Jake)
  1384. sr({ vehicleId: vehicles[8].id, title: "Silverado - Taillight Assembly", description: "Cracked right taillight from parking lot bump. Replace assembly.", type: "repair", status: "pending", serviceDate: day(4), mileage: 60500, techName: "Jake Wilson", shopName: "Egeland Auto" },
  1385. [{ name: "Taillight Assembly (right)", partNumber: "GM-TLA-SIL-R", quantity: 1, unitPrice: 125, total: 125 }],
  1386. [{ description: "Taillight assembly replacement", hours: 0.5, rate: 95, total: 47.50 }]),
  1387. // 24: Sprinter oil (Chris)
  1388. sr({ vehicleId: vehicles[9].id, title: "Sprinter - Oil Service + Inspection", description: "Regular oil change with full inspection. Check brake wear sensors.", type: "maintenance", status: "scheduled", serviceDate: day(4), mileage: 37000, techName: "Chris Taylor", shopName: "Egeland Auto" },
  1389. [{ name: "Engine Oil 5W-30 (8qt)", partNumber: "MB-5W30-8Q", quantity: 1, unitPrice: 78, total: 78 }, { name: "Oil Filter", partNumber: "MB-OF-SPR", quantity: 1, unitPrice: 18, total: 18 }],
  1390. [{ description: "Oil and filter change", hours: 0.5, rate: 110, total: 55 }, { description: "Multi-point inspection", hours: 1.0, rate: 110, total: 110 }]),
  1391. // 25: BMW coolant (Chris)
  1392. sr({ vehicleId: vehicles[4].id, title: "BMW 330i - Coolant Flush", description: "Coolant due. Flush and refill with BMW-approved coolant.", type: "maintenance", status: "scheduled", serviceDate: day(4), mileage: 52000, techName: "Chris Taylor", shopName: "Egeland Auto" },
  1393. [{ name: "BMW Coolant Concentrate (2L)", partNumber: "BMW-COOL-2L", quantity: 2, unitPrice: 32, total: 64 }, { name: "Thermostat Gasket", partNumber: "BMW-TG-N20", quantity: 1, unitPrice: 12, total: 12 }],
  1394. [{ description: "Coolant flush and refill", hours: 1.0, rate: 120, total: 120 }, { description: "Bleed cooling system", hours: 0.5, rate: 120, total: 60 }]),
  1395. // 26: Ram alignment (Sofia)
  1396. sr({ vehicleId: vehicles[15].id, title: "Ram 1500 - Alignment Check", description: "Pulling to the right after pothole. Full 4-wheel alignment.", type: "maintenance", status: "pending", serviceDate: day(4), mileage: 20000, techName: "Sofia Andersen", shopName: "Egeland Auto" },
  1397. [],
  1398. [{ description: "4-wheel alignment", hours: 1.0, rate: 110, total: 110 }]),
  1399. // 27: Audi spark plugs (Sofia)
  1400. sr({ vehicleId: vehicles[10].id, title: "Audi A4 - Spark Plug Replace", description: "Misfire on cylinder 2. Replace all 4 spark plugs.", type: "repair", status: "pending", serviceDate: day(4), mileage: 62000, techName: "Sofia Andersen", shopName: "Egeland Auto" },
  1401. [{ name: "Spark Plugs NGK (set of 4)", partNumber: "AUD-SP-NGK4", quantity: 1, unitPrice: 68, total: 68 }, { name: "Ignition Coil (cyl 2)", partNumber: "AUD-IC-A4", quantity: 1, unitPrice: 52, total: 52 }],
  1402. [{ description: "Spark plug replacement (4 cyl)", hours: 1.0, rate: 120, total: 120 }, { description: "Diagnose misfire and replace coil", hours: 0.5, rate: 120, total: 60 }],
  1403. "P0302 - misfire cyl 2. Coil swap test confirmed faulty coil on cyl 2. Replace coil and all 4 plugs."),
  1404. // 28: Tesla tire rotation (Sofia)
  1405. sr({ vehicleId: vehicles[7].id, title: "Tesla Model Y - Tire Rotation", description: "Rotate tires front to rear. Check tread depth and tire pressure.", type: "maintenance", status: "scheduled", serviceDate: day(4), mileage: 33000, techName: "Sofia Andersen", shopName: "Egeland Auto" },
  1406. [],
  1407. [{ description: "Tire rotation front to rear", hours: 0.5, rate: 95, total: 47.50 }, { description: "Tread depth measurement and pressure set", hours: 0.2, rate: 95, total: 19 }]),
  1408. // 29: Massey Ferguson radiator (Erik)
  1409. sr({ vehicleId: vehicles[24].id, title: "Massey Ferguson - Radiator Flush", description: "Overheating under load. Flush radiator and check thermostat.", type: "maintenance", status: "pending", serviceDate: day(4), mileage: 3800, techName: "Erik Haugen", shopName: "Egeland Auto" },
  1410. [{ name: "Coolant (5gal)", partNumber: "MF-COOL-5G", quantity: 1, unitPrice: 65, total: 65 }, { name: "Thermostat", partNumber: "MF-TH-8S", quantity: 1, unitPrice: 48, total: 48 }],
  1411. [{ description: "Radiator flush and refill", hours: 1.5, rate: 130, total: 195 }, { description: "Thermostat replacement", hours: 1.0, rate: 130, total: 130 }]),
  1412. // 30: Mack mirror (Nina)
  1413. sr({ vehicleId: vehicles[19].id, title: "Mack Granite - Mirror Replacement", description: "Left side mirror housing cracked. Replace complete mirror assembly.", type: "repair", status: "pending", serviceDate: day(4), mileage: 157000, techName: "Nina Berglund", shopName: "Egeland Auto" },
  1414. [{ name: "Complete Mirror Assembly (left)", partNumber: "MACK-MA-L-GR", quantity: 1, unitPrice: 285, total: 285 }],
  1415. [{ description: "Mirror assembly replacement", hours: 1.0, rate: 120, total: 120 }]),
  1416. // 31: Ram battery (Kari)
  1417. sr({ vehicleId: vehicles[16].id, title: "Ram 1500 - Battery Replace", description: "Slow cranking. Battery tested bad. Replace with OEM spec.", type: "repair", status: "pending", serviceDate: day(4), mileage: 45500, techName: "Kari Moen", shopName: "Egeland Auto" },
  1418. [{ name: "Battery Group 65 AGM", partNumber: "BAT-G65-AGM", quantity: 1, unitPrice: 185, total: 185 }],
  1419. [{ description: "Battery replacement and terminal cleaning", hours: 0.5, rate: 95, total: 47.50 }, { description: "Charging system test", hours: 0.2, rate: 95, total: 19 }]),
  1420. // === Monday extras to fill the timeline ===
  1421. // 32: Erik - Porsche oil change (Monday)
  1422. sr({ vehicleId: vehicles[13].id, title: "Porsche 911 - Oil Change", description: "Synthetic oil change with OEM filter. Check brake wear sensors.", type: "maintenance", status: "scheduled", serviceDate: day(0), mileage: 13200, techName: "Erik Haugen", shopName: "Egeland Auto" },
  1423. [{ name: "Porsche Approved Oil 0W-40 (9qt)", partNumber: "POR-0W40-9Q", quantity: 1, unitPrice: 165, total: 165 }, { name: "Oil Filter", partNumber: "POR-OF-992", quantity: 1, unitPrice: 28, total: 28 }],
  1424. [{ description: "Oil and filter change", hours: 1.0, rate: 145, total: 145 }, { description: "Multi-point inspection", hours: 0.5, rate: 145, total: 72.50 }]),
  1425. // 33: Nina - BMW coolant hose (Monday)
  1426. sr({ vehicleId: vehicles[4].id, title: "BMW 330i - Coolant Hose Replacement", description: "Upper radiator hose cracked. Replace hose and top off coolant.", type: "repair", status: "pending", serviceDate: day(0), mileage: 56000, techName: "Nina Berglund", shopName: "Egeland Auto" },
  1427. [{ name: "Upper Radiator Hose", partNumber: "BMW-URH-N20", quantity: 1, unitPrice: 85, total: 85 }, { name: "Coolant G13 (1L)", partNumber: "BMW-COOL-1L", quantity: 2, unitPrice: 18, total: 36 }],
  1428. [{ description: "Radiator hose replacement", hours: 1.5, rate: 120, total: 180 }, { description: "Coolant bleed and pressure test", hours: 0.5, rate: 120, total: 60 }]),
  1429. // 34: Nina - Jeep brake inspection (Monday)
  1430. sr({ vehicleId: vehicles[11].id, title: "Jeep Wrangler - Brake Inspection", description: "Customer reports squealing. Inspect pads, rotors, and calipers.", type: "inspection", status: "scheduled", serviceDate: day(0), mileage: 29000, techName: "Nina Berglund", shopName: "Egeland Auto" },
  1431. [],
  1432. [{ description: "Full brake system inspection", hours: 1.0, rate: 110, total: 110 }, { description: "Document findings and recommend", hours: 0.5, rate: 110, total: 55 }]),
  1433. // 35: Kari - Fendt hydraulic filter (Monday)
  1434. sr({ vehicleId: vehicles[23].id, title: "Fendt 942 - Hydraulic Filter Service", description: "Scheduled hydraulic filter change. Check system pressure.", type: "maintenance", status: "scheduled", serviceDate: day(0), mileage: 1250, techName: "Kari Moen", shopName: "Egeland Auto" },
  1435. [{ name: "Hydraulic Filter Set", partNumber: "FENDT-HFS-942", quantity: 1, unitPrice: 165, total: 165 }, { name: "Hydraulic Oil Sample Kit", partNumber: "OIL-SAMPLE", quantity: 1, unitPrice: 15, total: 15 }],
  1436. [{ description: "Hydraulic filter replacement", hours: 1.5, rate: 150, total: 225 }, { description: "Pressure test and oil sample", hours: 1.0, rate: 150, total: 150 }]),
  1437. // 36: Kari - Excavator grease service (Monday)
  1438. sr({ vehicleId: vehicles[31].id, title: "Komatsu PC210 - Full Grease Service", description: "Complete grease service all 24 fittings. Check pin play.", type: "maintenance", status: "scheduled", serviceDate: day(0), mileage: 3150, techName: "Kari Moen", shopName: "Egeland Auto" },
  1439. [{ name: "Grease Cartridges (box of 10)", partNumber: "GRZ-EP2-10", quantity: 1, unitPrice: 42, total: 42 }],
  1440. [{ description: "Grease all fittings (24 points)", hours: 2.0, rate: 130, total: 260 }, { description: "Pin and bushing play inspection", hours: 0.5, rate: 130, total: 65 }]),
  1441. // 37: Daniel - Volvo FH brake adjustment (Monday)
  1442. sr({ vehicleId: vehicles[18].id, title: "Volvo FH 640 - Brake Adjustment", description: "Annual brake adjustment. Check linings and drums.", type: "maintenance", status: "scheduled", serviceDate: day(0), mileage: 93000, techName: "Daniel Eriksen", shopName: "Egeland Auto" },
  1443. [{ name: "Brake Lining Wear Indicators (set)", partNumber: "VOL-BLWI-FH", quantity: 1, unitPrice: 45, total: 45 }],
  1444. [{ description: "Brake adjustment all axles", hours: 2.5, rate: 140, total: 350 }, { description: "Lining measurement and documentation", hours: 1.0, rate: 140, total: 140 }]),
  1445. // 38: Daniel - Dump truck hydraulic hose (Monday)
  1446. sr({ vehicleId: vehicles[21].id, title: "Dump Truck - Hydraulic Hose Replace", description: "Hose bulging near fitting. Replace before failure.", type: "repair", status: "pending", serviceDate: day(0), mileage: 83000, techName: "Daniel Eriksen", shopName: "Egeland Auto" },
  1447. [{ name: "Hydraulic Hose Assembly 3/4\"", partNumber: "HYD-HA-34", quantity: 2, unitPrice: 120, total: 240 }, { name: "Hose Fittings (4-pack)", partNumber: "HYD-FIT-4", quantity: 1, unitPrice: 65, total: 65 }],
  1448. [{ description: "Hose removal and replacement", hours: 2.0, rate: 130, total: 260 }, { description: "System bleed and pressure test", hours: 0.5, rate: 130, total: 65 }]),
  1449. // 39: Lars - Kenworth air filter (Monday)
  1450. sr({ vehicleId: vehicles[17].id, title: "Kenworth T680 - Air Filter Service", description: "Replace primary and secondary air filters. Clean intake ducting.", type: "maintenance", status: "scheduled", serviceDate: day(0), mileage: 186500, techName: "Lars Johansen", shopName: "Egeland Auto" },
  1451. [{ name: "Primary Air Filter", partNumber: "KW-PAF-T680", quantity: 1, unitPrice: 85, total: 85 }, { name: "Secondary Air Filter", partNumber: "KW-SAF-T680", quantity: 1, unitPrice: 55, total: 55 }],
  1452. [{ description: "Air filter replacement (both)", hours: 0.5, rate: 130, total: 65 }, { description: "Intake system inspection and clean", hours: 0.5, rate: 130, total: 65 }]),
  1453. // 40: Sofia - Honda Civic tire rotation (Monday)
  1454. sr({ vehicleId: vehicles[5].id, title: "Honda Civic - Tire Rotation + Check", description: "Rotate tires. Customer also reports slight vibration at highway speed.", type: "maintenance", status: "pending", serviceDate: day(0), mileage: 68500, techName: "Sofia Andersen", shopName: "Egeland Auto" },
  1455. [],
  1456. [{ description: "Tire rotation", hours: 0.5, rate: 95, total: 47.50 }, { description: "Wheel balance check (4 wheels)", hours: 0.5, rate: 95, total: 47.50 }, { description: "Road test for vibration", hours: 0.3, rate: 95, total: 28.50 }]),
  1457. ]);
  1458. // Unassigned jobs (NOT on the board - will show in unassigned panel)
  1459. console.log("\nCreating unassigned service records...");
  1460. const unassignedRecords = await Promise.all([
  1461. sr({ vehicleId: vehicles[0].id, title: "Toyota Camry - Check Engine Light", description: "P0171 - System Too Lean. Diagnose and repair. Customer reports rough idle.", type: "repair", status: "pending", mileage: 16200, shopName: "Egeland Auto" },
  1462. [{ name: "MAF Sensor", partNumber: "TOY-MAF-CAM", quantity: 1, unitPrice: 145, total: 145 }, { name: "Air Filter", partNumber: "TOY-AF-CAM", quantity: 1, unitPrice: 18, total: 18 }],
  1463. [{ description: "Diagnostic scan and smoke test", hours: 1.0, rate: 110, total: 110 }, { description: "MAF sensor replacement", hours: 0.5, rate: 110, total: 55 }],
  1464. "P0171 lean code. Inspected intake for vacuum leaks - none found. MAF sensor reading low. Suspect contaminated MAF."),
  1465. sr({ vehicleId: vehicles[9].id, title: "Sprinter - Sliding Door Repair", description: "Sliding door sticking halfway. Roller mechanism needs replacement.", type: "repair", status: "pending", mileage: 36500, shopName: "Egeland Auto" },
  1466. [{ name: "Sliding Door Roller Assembly", partNumber: "MB-SDRA-SPR", quantity: 1, unitPrice: 220, total: 220 }, { name: "Door Track Lubricant", partNumber: "LUB-DTL-1", quantity: 1, unitPrice: 15, total: 15 }],
  1467. [{ description: "Roller mechanism removal and replacement", hours: 2.0, rate: 110, total: 220 }]),
  1468. sr({ vehicleId: vehicles[13].id, title: "Porsche 911 - Pre-Track Inspection", description: "Full safety inspection before April track day. Brakes, fluids, suspension, tires.", type: "inspection", status: "pending", mileage: 13000, shopName: "Egeland Auto" },
  1469. [{ name: "Brake Fluid DOT4 Racing (1L)", partNumber: "POR-BF-R-1L", quantity: 2, unitPrice: 48, total: 96 }],
  1470. [{ description: "Full multi-point track safety inspection", hours: 2.0, rate: 145, total: 290 }, { description: "Brake fluid flush with racing fluid", hours: 1.5, rate: 145, total: 217.50 }]),
  1471. sr({ vehicleId: vehicles[19].id, title: "Mack Granite - Dump Body Weld Repair", description: "Cracks in dump body floor. Weld repair and reinforce high-stress areas.", type: "repair", status: "pending", mileage: 156000, shopName: "Egeland Auto" },
  1472. [{ name: "Steel Plate 3/8\" (2 sheets)", partNumber: "STL-PLT-38", quantity: 2, unitPrice: 120, total: 240 }, { name: "Welding Wire (10lb)", partNumber: "WLD-WIRE-10", quantity: 1, unitPrice: 45, total: 45 }],
  1473. [{ description: "Grind and prep crack areas", hours: 2.0, rate: 130, total: 260 }, { description: "Weld repair and reinforce", hours: 4.0, rate: 130, total: 520 }]),
  1474. sr({ vehicleId: vehicles[22].id, title: "John Deere 6R - Front Loader Pins", description: "Excessive play in front loader attachment pins. Replace pins and bushings.", type: "repair", status: "pending", mileage: 2800, shopName: "Egeland Auto" },
  1475. [{ name: "Loader Pin Kit", partNumber: "JD-LPK-6R", quantity: 1, unitPrice: 185, total: 185 }, { name: "Bronze Bushings (set of 4)", partNumber: "JD-BB-6R-4", quantity: 1, unitPrice: 120, total: 120 }],
  1476. [{ description: "Pin and bushing removal", hours: 2.0, rate: 140, total: 280 }, { description: "New bushing press-in and pin installation", hours: 2.0, rate: 140, total: 280 }]),
  1477. sr({ vehicleId: vehicles[31].id, title: "Komatsu PC210 - Boom Cylinder Reseal", description: "Slow drift on boom cylinder. Reseal required.", type: "repair", status: "pending", mileage: 3200, shopName: "Egeland Auto" },
  1478. [{ name: "Boom Cylinder Seal Kit", partNumber: "KOM-BCSK-PC210", quantity: 1, unitPrice: 320, total: 320 }, { name: "Hydraulic Oil (5gal)", partNumber: "HYD-ISO46-5G", quantity: 1, unitPrice: 95, total: 95 }],
  1479. [{ description: "Boom cylinder removal", hours: 3.0, rate: 140, total: 420 }, { description: "Reseal and reinstall", hours: 2.5, rate: 140, total: 350 }]),
  1480. sr({ vehicleId: vehicles[36].id, title: "Liebherr LTM 1100 - Outrigger Service", description: "Right rear outrigger slow to extend. Inspect valve and cylinder seals.", type: "repair", status: "pending", mileage: 4200, shopName: "Egeland Auto" },
  1481. [{ name: "Outrigger Cylinder Seal Kit", partNumber: "LIE-OCSK-1100", quantity: 1, unitPrice: 450, total: 450 }, { name: "Outrigger Control Valve", partNumber: "LIE-OCV-1100", quantity: 1, unitPrice: 680, total: 680 }],
  1482. [{ description: "Diagnose outrigger hydraulic circuit", hours: 2.0, rate: 150, total: 300 }, { description: "Cylinder reseal or valve replacement", hours: 4.0, rate: 150, total: 600 }]),
  1483. sr({ vehicleId: vehicles[6].id, title: "Tesla Model 3 - 12V Battery Replace", description: "Low voltage warning. Replace 12V auxiliary battery.", type: "repair", status: "pending", mileage: 8200, shopName: "Egeland Auto" },
  1484. [{ name: "12V Lithium Battery (Tesla OEM)", partNumber: "TES-12V-M3", quantity: 1, unitPrice: 110, total: 110 }],
  1485. [{ description: "12V battery replacement", hours: 0.5, rate: 110, total: 55 }]),
  1486. sr({ vehicleId: vehicles[23].id, title: "Fendt 942 - GPS Autosteer Calibration", description: "Autosteer drifting right by 6 inches. Recalibrate GPS receiver and steering controller.", type: "maintenance", status: "scheduled", mileage: 1200, shopName: "Egeland Auto" },
  1487. [],
  1488. [{ description: "GPS receiver calibration", hours: 1.5, rate: 150, total: 225 }, { description: "Steering controller calibration and field test", hours: 2.0, rate: 150, total: 300 }],
  1489. "RTK base station signal verified. GPS receiver antenna checked - mounting bracket slightly loose causing drift. Tighten and recalibrate."),
  1490. sr({ vehicleId: vehicles[33].id, title: "Volvo EC220E - Bucket Teeth Replace", description: "3 worn bucket teeth. Replace full set of 5 for even wear.", type: "maintenance", status: "pending", mileage: 1600, shopName: "Egeland Auto" },
  1491. [{ name: "Bucket Teeth Set (5)", partNumber: "VOL-BTS-EC220", quantity: 1, unitPrice: 340, total: 340 }, { name: "Retainer Pins (5-pack)", partNumber: "VOL-RP-5", quantity: 1, unitPrice: 45, total: 45 }],
  1492. [{ description: "Bucket teeth removal and replacement", hours: 1.5, rate: 130, total: 195 }]),
  1493. sr({ vehicleId: vehicles[18].id, title: "Volvo FH 640 - Turbo Boost Leak", description: "Low power complaint. Suspect charge air cooler pipe leak. Diagnose.", type: "repair", status: "pending", mileage: 93500, shopName: "Egeland Auto" },
  1494. [{ name: "Charge Air Cooler Pipe + Clamps", partNumber: "VOL-CACP-FH", quantity: 1, unitPrice: 185, total: 185 }],
  1495. [{ description: "Boost leak diagnosis and smoke test", hours: 1.5, rate: 140, total: 210 }, { description: "Pipe replacement and clamp tightening", hours: 1.0, rate: 140, total: 140 }],
  1496. "Smoke test confirmed leak at charge air cooler pipe connection. Clamp was loose and pipe boot cracked."),
  1497. sr({ vehicleId: vehicles[17].id, title: "Kenworth T680 - Sleeper AC Repair", description: "Sleeper AC not cooling. Likely low refrigerant or compressor issue.", type: "repair", status: "waiting-parts", mileage: 186000, shopName: "Egeland Auto" },
  1498. [{ name: "Sleeper AC Compressor", partNumber: "KW-SAC-T680", quantity: 1, unitPrice: 580, total: 580 }, { name: "Refrigerant R-134a (3 cans)", partNumber: "REF-134A-3", quantity: 1, unitPrice: 65, total: 65 }, { name: "AC Condenser", partNumber: "KW-COND-T680", quantity: 1, unitPrice: 320, total: 320 }],
  1499. [{ description: "Sleeper AC system diagnosis", hours: 1.5, rate: 140, total: 210 }, { description: "Compressor and condenser replacement", hours: 3.5, rate: 140, total: 490 }, { description: "Evacuate, recharge and leak test", hours: 1.0, rate: 140, total: 140 }],
  1500. "Compressor seized. Condenser contaminated with metal debris from failed compressor. Both need replacement. Parts on order - ETA Wednesday."),
  1501. sr({ vehicleId: vehicles[38].id, title: "Corvette C8 - Pre-Track Brake Service", description: "Customer has track day in 2 weeks. Flush brake fluid, inspect pads, check tire wear.", type: "maintenance", status: "pending", mileage: 6200, shopName: "Egeland Auto" },
  1502. [{ name: "Brake Fluid DOT4 Racing (1L)", partNumber: "BF-DOT4R-1L", quantity: 3, unitPrice: 48, total: 144 }],
  1503. [{ description: "Brake fluid flush all 4 corners", hours: 1.5, rate: 130, total: 195 }, { description: "Brake pad measurement and inspection", hours: 0.5, rate: 130, total: 65 }, { description: "Tire tread depth and pressure check", hours: 0.3, rate: 130, total: 39 }]),
  1504. sr({ vehicleId: vehicles[39].id, title: "Defender 110 - Air Suspension Warning", description: "Dashboard warning light for air suspension. Possible compressor or height sensor issue.", type: "repair", status: "pending", mileage: 28500, shopName: "Egeland Auto" },
  1505. [{ name: "Air Suspension Height Sensor", partNumber: "LR-ASHS-DEF", quantity: 1, unitPrice: 210, total: 210 }],
  1506. [{ description: "Diagnose air suspension fault codes", hours: 1.0, rate: 120, total: 120 }, { description: "Height sensor replacement and calibration", hours: 1.5, rate: 120, total: 180 }]),
  1507. sr({ vehicleId: vehicles[40].id, title: "Charger R/T - Rear Alignment + Tire Replace", description: "Inner edge tire wear on rears. Alignment and new rear tires needed.", type: "repair", status: "pending", mileage: 35000, shopName: "Egeland Auto" },
  1508. [{ name: "Firestone Firehawk Indy 500 275/40R20 (pair)", partNumber: "FS-FH500-27540-2", quantity: 1, unitPrice: 380, total: 380 }],
  1509. [{ description: "Rear tire mount and balance (2)", hours: 0.5, rate: 95, total: 47.50 }, { description: "4-wheel alignment", hours: 1.0, rate: 110, total: 110 }]),
  1510. sr({ vehicleId: vehicles[41].id, title: "WRX - Clutch Adjustment + Inspection", description: "Customer reports high clutch engagement point. Inspect clutch wear and adjust.", type: "repair", status: "pending", mileage: 12400, shopName: "Egeland Auto" },
  1511. [{ name: "Clutch Master Cylinder Fluid", partNumber: "SUB-CMF-DOT4", quantity: 1, unitPrice: 15, total: 15 }],
  1512. [{ description: "Clutch pedal adjustment and bleed", hours: 0.5, rate: 110, total: 55 }, { description: "Clutch wear inspection via inspection port", hours: 0.5, rate: 110, total: 55 }],
  1513. "Clutch engagement point higher than normal but disc still within spec. Bled hydraulic line - air found. Pedal feel improved. Monitor."),
  1514. ]);
  1515. console.log(` Created ${unassignedRecords.length} unassigned service records`);
  1516. const jobUpdates = await Promise.all([
  1517. // ============ MONDAY (day 0) - 2026-03-09 - Primary showcase day ============
  1518. // Jake Wilson [0]: Honda AC (8:00-11:30) + F-150 trans flush (12:30-15:00)
  1519. prisma.serviceRecord.update({ where: { id: boardServiceRecords[0].id }, data: { technicianId: technicians[0].id, sortOrder: 0, startDateTime: dt(0, 8, 0), endDateTime: dt(0, 11, 30) } }),
  1520. prisma.serviceRecord.update({ where: { id: serviceRecords[18].id }, data: { technicianId: technicians[0].id, sortOrder: 1, startDateTime: dt(0, 12, 30), endDateTime: dt(0, 15, 0) } }),
  1521. // Chris Taylor [1]: Audi timing belt (7:30-13:00)
  1522. prisma.serviceRecord.update({ where: { id: boardServiceRecords[1].id }, data: { technicianId: technicians[1].id, sortOrder: 0, startDateTime: dt(0, 7, 30), endDateTime: dt(0, 13, 0) } }),
  1523. // Marcus Reed [2]: CAT 745 transmission rebuild (7:00-16:00, multi-day spans Mon-Wed)
  1524. prisma.serviceRecord.update({ where: { id: boardServiceRecords[6].id }, data: { technicianId: technicians[2].id, sortOrder: 0, startDateTime: dt(0, 7, 0), endDateTime: dt(2, 16, 0) } }),
  1525. // Sofia Andersen [3]: Tesla suspension (9:00-11:30)
  1526. prisma.serviceRecord.update({ where: { id: boardServiceRecords[2].id }, data: { technicianId: technicians[3].id, sortOrder: 0, startDateTime: dt(0, 9, 0), endDateTime: dt(0, 11, 30) } }),
  1527. // Lars Johansen [5]: Ram oil change (8:00-9:00)
  1528. prisma.serviceRecord.update({ where: { id: boardServiceRecords[11].id }, data: { technicianId: technicians[5].id, sortOrder: 0, startDateTime: dt(0, 8, 0), endDateTime: dt(0, 9, 0) } }),
  1529. // Tom Bradley [7]: Concrete mixer drum motor (7:30-14:30)
  1530. prisma.serviceRecord.update({ where: { id: boardServiceRecords[13].id }, data: { technicianId: technicians[7].id, sortOrder: 0, startDateTime: dt(0, 7, 30), endDateTime: dt(0, 14, 30) } }),
  1531. prisma.serviceRecord.update({ where: { id: boardServiceRecords[32].id }, data: { technicianId: technicians[4].id, sortOrder: 1, startDateTime: dt(0, 11, 0), endDateTime: dt(0, 12, 30) } }),
  1532. // Nina Berglund [6]: BMW coolant hose (7:30-9:30) + Jeep brake inspection (10:00-11:30)
  1533. prisma.serviceRecord.update({ where: { id: boardServiceRecords[33].id }, data: { technicianId: technicians[6].id, sortOrder: 0, startDateTime: dt(0, 7, 30), endDateTime: dt(0, 9, 30) } }),
  1534. prisma.serviceRecord.update({ where: { id: boardServiceRecords[34].id }, data: { technicianId: technicians[6].id, sortOrder: 1, startDateTime: dt(0, 10, 0), endDateTime: dt(0, 11, 30) } }),
  1535. // Kari Moen [8]: Fendt hydraulic filter (8:00-10:30) + Komatsu grease (11:00-13:30)
  1536. prisma.serviceRecord.update({ where: { id: boardServiceRecords[35].id }, data: { technicianId: technicians[8].id, sortOrder: 0, startDateTime: dt(0, 8, 0), endDateTime: dt(0, 10, 30) } }),
  1537. prisma.serviceRecord.update({ where: { id: boardServiceRecords[36].id }, data: { technicianId: technicians[8].id, sortOrder: 1, startDateTime: dt(0, 11, 0), endDateTime: dt(0, 13, 30) } }),
  1538. // Daniel Eriksen [9]: Volvo brake adjustment (7:30-11:00) + Dump truck hose (11:30-14:00)
  1539. prisma.serviceRecord.update({ where: { id: boardServiceRecords[37].id }, data: { technicianId: technicians[9].id, sortOrder: 0, startDateTime: dt(0, 7, 30), endDateTime: dt(0, 11, 0) } }),
  1540. prisma.serviceRecord.update({ where: { id: boardServiceRecords[38].id }, data: { technicianId: technicians[9].id, sortOrder: 1, startDateTime: dt(0, 11, 30), endDateTime: dt(0, 14, 0) } }),
  1541. prisma.serviceRecord.update({ where: { id: boardServiceRecords[39].id }, data: { technicianId: technicians[5].id, sortOrder: 2, startDateTime: dt(0, 10, 30), endDateTime: dt(0, 11, 30) } }),
  1542. // Sofia Andersen [3]: (already has Tesla 9-11:30) + Honda tire rotation (12:00-13:15)
  1543. prisma.serviceRecord.update({ where: { id: boardServiceRecords[40].id }, data: { technicianId: technicians[3].id, sortOrder: 1, startDateTime: dt(0, 12, 0), endDateTime: dt(0, 13, 15) } }),
  1544. // ============ TUESDAY (day 1) ============
  1545. // Jake [0]: Silverado 60K (8:00-11:30)
  1546. prisma.serviceRecord.update({ where: { id: boardServiceRecords[3].id }, data: { technicianId: technicians[0].id, sortOrder: 0, startDateTime: dt(1, 8, 0), endDateTime: dt(1, 11, 30) } }),
  1547. // Chris [1]: Sprinter turbo (7:30-13:00)
  1548. prisma.serviceRecord.update({ where: { id: serviceRecords[12].id }, data: { technicianId: technicians[1].id, sortOrder: 0, startDateTime: dt(1, 7, 30), endDateTime: dt(1, 13, 0) } }),
  1549. // Marcus [2]: CAT 745 continued (multi-day job spans from Monday)
  1550. // Erik [4]: Tacoma leaf springs (8:00-11:30)
  1551. prisma.serviceRecord.update({ where: { id: boardServiceRecords[4].id }, data: { technicianId: technicians[4].id, sortOrder: 0, startDateTime: dt(1, 8, 0), endDateTime: dt(1, 11, 30) } }),
  1552. // Nina [6]: F-150 wheel bearing (9:00-11:30)
  1553. prisma.serviceRecord.update({ where: { id: boardServiceRecords[12].id }, data: { technicianId: technicians[6].id, sortOrder: 0, startDateTime: dt(1, 9, 0), endDateTime: dt(1, 11, 30) } }),
  1554. // Daniel [9]: Dump truck tailgate (8:00-12:00)
  1555. prisma.serviceRecord.update({ where: { id: boardServiceRecords[15].id }, data: { technicianId: technicians[9].id, sortOrder: 0, startDateTime: dt(1, 8, 0), endDateTime: dt(1, 12, 0) } }),
  1556. // ============ WEDNESDAY (day 2) ============
  1557. // Jake [0]: F-150 exhaust (8:00-11:00)
  1558. prisma.serviceRecord.update({ where: { id: boardServiceRecords[7].id }, data: { technicianId: technicians[0].id, sortOrder: 0, startDateTime: dt(2, 8, 0), endDateTime: dt(2, 11, 0) } }),
  1559. // Marcus [2]: Bobcat annual (13:00-15:30, after CAT 745 wraps up)
  1560. prisma.serviceRecord.update({ where: { id: boardServiceRecords[5].id }, data: { technicianId: technicians[2].id, sortOrder: 1, startDateTime: dt(2, 13, 0), endDateTime: dt(2, 15, 30) } }),
  1561. // Chris [1]: Volvo EC220E (7:30-13:00)
  1562. prisma.serviceRecord.update({ where: { id: serviceRecords[10].id }, data: { technicianId: technicians[1].id, sortOrder: 0, startDateTime: dt(2, 7, 30), endDateTime: dt(2, 13, 0) } }),
  1563. // Kari [8]: Tractor PTO clutch (8:30-10:30)
  1564. prisma.serviceRecord.update({ where: { id: boardServiceRecords[14].id }, data: { technicianId: technicians[8].id, sortOrder: 0, startDateTime: dt(2, 8, 30), endDateTime: dt(2, 10, 30) } }),
  1565. // Nina [6]: VW Golf clutch (7:30-14:30)
  1566. prisma.serviceRecord.update({ where: { id: boardServiceRecords[17].id }, data: { technicianId: technicians[6].id, sortOrder: 0, startDateTime: dt(2, 7, 30), endDateTime: dt(2, 14, 30) } }),
  1567. // ============ THURSDAY (day 3) ============
  1568. // Sofia [3]: Ram transfer case (9:00-10:30)
  1569. prisma.serviceRecord.update({ where: { id: boardServiceRecords[8].id }, data: { technicianId: technicians[3].id, sortOrder: 0, startDateTime: dt(3, 9, 0), endDateTime: dt(3, 10, 30) } }),
  1570. // Jake [0]: Volvo FH DOT inspection (7:30-13:30)
  1571. prisma.serviceRecord.update({ where: { id: serviceRecords[5].id }, data: { technicianId: technicians[0].id, sortOrder: 0, startDateTime: dt(3, 7, 30), endDateTime: dt(3, 13, 30) } }),
  1572. // Lars [5]: Forklift mast chain (8:00-11:30)
  1573. prisma.serviceRecord.update({ where: { id: boardServiceRecords[16].id }, data: { technicianId: technicians[5].id, sortOrder: 0, startDateTime: dt(3, 8, 0), endDateTime: dt(3, 11, 30) } }),
  1574. // Kari [8]: Kenworth clutch adjust (8:00-10:00)
  1575. prisma.serviceRecord.update({ where: { id: boardServiceRecords[19].id }, data: { technicianId: technicians[8].id, sortOrder: 0, startDateTime: dt(3, 8, 0), endDateTime: dt(3, 10, 0) } }),
  1576. // ============ FRIDAY (day 4) ============
  1577. // Jake [0] (3 jobs): Camry cabin filter (8:00-8:30), Honda brakes (8:45-10:00), Silverado taillight (10:15-10:45)
  1578. prisma.serviceRecord.update({ where: { id: boardServiceRecords[21].id }, data: { technicianId: technicians[0].id, sortOrder: 0, startDateTime: dt(4, 8, 0), endDateTime: dt(4, 8, 30) } }),
  1579. prisma.serviceRecord.update({ where: { id: boardServiceRecords[22].id }, data: { technicianId: technicians[0].id, sortOrder: 1, startDateTime: dt(4, 8, 45), endDateTime: dt(4, 10, 0) } }),
  1580. prisma.serviceRecord.update({ where: { id: boardServiceRecords[23].id }, data: { technicianId: technicians[0].id, sortOrder: 2, startDateTime: dt(4, 10, 15), endDateTime: dt(4, 10, 45) } }),
  1581. // Chris [1] (3 jobs): Jeep axle seal (7:30-10:30), Sprinter oil (11:00-12:30), BMW coolant (13:00-14:30)
  1582. prisma.serviceRecord.update({ where: { id: boardServiceRecords[10].id }, data: { technicianId: technicians[1].id, sortOrder: 0, startDateTime: dt(4, 7, 30), endDateTime: dt(4, 10, 30) } }),
  1583. prisma.serviceRecord.update({ where: { id: boardServiceRecords[24].id }, data: { technicianId: technicians[1].id, sortOrder: 1, startDateTime: dt(4, 11, 0), endDateTime: dt(4, 12, 30) } }),
  1584. prisma.serviceRecord.update({ where: { id: boardServiceRecords[25].id }, data: { technicianId: technicians[1].id, sortOrder: 2, startDateTime: dt(4, 13, 0), endDateTime: dt(4, 14, 30) } }),
  1585. // Marcus [2]: Combine pre-season (7:00-15:00)
  1586. prisma.serviceRecord.update({ where: { id: boardServiceRecords[9].id }, data: { technicianId: technicians[2].id, sortOrder: 0, startDateTime: dt(4, 7, 0), endDateTime: dt(4, 15, 0) } }),
  1587. // Sofia [3] (3 jobs): Ram alignment (8:00-9:00), Audi spark plugs (9:30-11:00), Tesla tire rotation (11:30-12:15)
  1588. prisma.serviceRecord.update({ where: { id: boardServiceRecords[26].id }, data: { technicianId: technicians[3].id, sortOrder: 0, startDateTime: dt(4, 8, 0), endDateTime: dt(4, 9, 0) } }),
  1589. prisma.serviceRecord.update({ where: { id: boardServiceRecords[27].id }, data: { technicianId: technicians[3].id, sortOrder: 1, startDateTime: dt(4, 9, 30), endDateTime: dt(4, 11, 0) } }),
  1590. prisma.serviceRecord.update({ where: { id: boardServiceRecords[28].id }, data: { technicianId: technicians[3].id, sortOrder: 2, startDateTime: dt(4, 11, 30), endDateTime: dt(4, 12, 15) } }),
  1591. // Erik [4]: Massey Ferguson radiator (8:00-10:30)
  1592. prisma.serviceRecord.update({ where: { id: boardServiceRecords[29].id }, data: { technicianId: technicians[4].id, sortOrder: 0, startDateTime: dt(4, 8, 0), endDateTime: dt(4, 10, 30) } }),
  1593. // Nina [6]: Mack mirror replacement (9:00-10:00)
  1594. prisma.serviceRecord.update({ where: { id: boardServiceRecords[30].id }, data: { technicianId: technicians[6].id, sortOrder: 0, startDateTime: dt(4, 9, 0), endDateTime: dt(4, 10, 0) } }),
  1595. // Tom [7]: Combine header knives (7:30-11:30)
  1596. prisma.serviceRecord.update({ where: { id: boardServiceRecords[18].id }, data: { technicianId: technicians[7].id, sortOrder: 0, startDateTime: dt(4, 7, 30), endDateTime: dt(4, 11, 30) } }),
  1597. // Kari [8]: Ram battery replace (8:00-8:45)
  1598. prisma.serviceRecord.update({ where: { id: boardServiceRecords[31].id }, data: { technicianId: technicians[8].id, sortOrder: 0, startDateTime: dt(4, 8, 0), endDateTime: dt(4, 8, 45) } }),
  1599. // Daniel [9]: Jeep steering stabilizer (8:00-10:00)
  1600. prisma.serviceRecord.update({ where: { id: boardServiceRecords[20].id }, data: { technicianId: technicians[9].id, sortOrder: 0, startDateTime: dt(4, 8, 0), endDateTime: dt(4, 10, 0) } }),
  1601. ]);
  1602. console.log(` Updated ${jobUpdates.length} service records with technician assignments and time slots`);
  1603. // -- Assign the Demo Owner a few active jobs so the dashboard "My Active Jobs" populates --
  1604. console.log("\nAssigning active jobs to the Demo Owner technician...");
  1605. const demoOwnerTech = technicians[10]; // Demo Owner
  1606. const demoOwnerJobs = await Promise.all([
  1607. // Tesla Model Y suspension (pending) — reassign from Sofia
  1608. prisma.serviceRecord.update({ where: { id: boardServiceRecords[2].id }, data: { technicianId: demoOwnerTech.id } }),
  1609. // F-150 exhaust leak repair (pending) — reassign from Jake
  1610. prisma.serviceRecord.update({ where: { id: boardServiceRecords[7].id }, data: { technicianId: demoOwnerTech.id } }),
  1611. // Jeep axle seal replacement (pending) — reassign from Chris
  1612. prisma.serviceRecord.update({ where: { id: boardServiceRecords[10].id }, data: { technicianId: demoOwnerTech.id } }),
  1613. // Kenworth T680 Sleeper AC repair (waiting-parts) — previously unassigned
  1614. prisma.serviceRecord.update({ where: { id: unassignedRecords[11].id }, data: { technicianId: demoOwnerTech.id } }),
  1615. // Porsche 911 Pre-Track Inspection (pending) — previously unassigned
  1616. prisma.serviceRecord.update({ where: { id: unassignedRecords[2].id }, data: { technicianId: demoOwnerTech.id } }),
  1617. ]);
  1618. console.log(` Assigned ${demoOwnerJobs.length} active jobs to ${demoOwnerTech.name}`);
  1619. // -- Jobs either side of the board week --
  1620. // The showcase week is dense on purpose, but the calendar's month view, the
  1621. // revenue chart and every "this month" counter need work before and after it
  1622. // too. `wd` keeps each job on a weekday by counting from the board's Monday.
  1623. console.log("\nCreating jobs across the surrounding weeks...");
  1624. const wd = (weekOffset: number, dayIdx: number) => MONDAY_OFFSET + weekOffset * 7 + dayIdx;
  1625. type SpreadJob = { w: number; d: number; v: number; tech: number; title: string; desc: string; type: string; hour: number; hours: number; mileage: number; rate: number; parts: { name: string; partNumber: string; quantity: number; unitPrice: number; total: number }[] };
  1626. const spreadJobs: SpreadJob[] = [
  1627. // ── Three weeks back ──
  1628. { w: -3, d: 0, v: 0, tech: 0, title: "Toyota Camry - Wheel Alignment", desc: "Pulling left after kerb strike. Four-wheel alignment.", type: "maintenance", hour: 8, hours: 1.0, mileage: 17800, rate: 95, parts: [] },
  1629. { w: -3, d: 1, v: 12, tech: 4, title: "Jeep Wrangler - Soft Top Swap", desc: "Seasonal swap from hard top to soft top. Inspect seals.", type: "maintenance", hour: 9, hours: 1.5, mileage: 14800, rate: 95, parts: [{ name: "Top Seal Kit", partNumber: "JEEP-TSK-JL", quantity: 1, unitPrice: 65, total: 65 }] },
  1630. { w: -3, d: 2, v: 21, tech: 2, title: "Dump Truck - Annual DOT Inspection", desc: "Full DOT annual. Brakes, lights, suspension, documentation.", type: "inspection", hour: 7, hours: 5.0, mileage: 80500, rate: 140, parts: [{ name: "Marker Light Bulbs (pack of 10)", partNumber: "DMP-MLB-10", quantity: 1, unitPrice: 35, total: 35 }] },
  1631. { w: -3, d: 3, v: 6, tech: 3, title: "Tesla Model 3 - Cabin Filter", desc: "HEPA cabin filter replacement and A/C system check.", type: "maintenance", hour: 10, hours: 1.0, mileage: 7900, rate: 110, parts: [{ name: "HEPA Cabin Filter", partNumber: "TES-CF-M3", quantity: 1, unitPrice: 78, total: 78 }] },
  1632. { w: -3, d: 4, v: 30, tech: 2, title: "CAT D8T - Final Drive Oil Change", desc: "Both final drives drained, flushed and refilled.", type: "maintenance", hour: 7, hours: 4.0, mileage: 5700, rate: 150, parts: [{ name: "Final Drive Oil (15gal)", partNumber: "CAT-FDO-15G", quantity: 1, unitPrice: 420, total: 420 }] },
  1633. // ── Two weeks back ──
  1634. { w: -2, d: 0, v: 5, tech: 0, title: "Honda Civic - Cabin Filter + A/C Clean", desc: "Musty smell reported. Evaporator clean and new cabin filter.", type: "maintenance", hour: 8, hours: 1.5, mileage: 67200, rate: 95, parts: [{ name: "Cabin Filter", partNumber: "HON-CF-CIV", quantity: 1, unitPrice: 24, total: 24 }, { name: "Evaporator Cleaner", partNumber: "AC-EVAP-CLN", quantity: 1, unitPrice: 32, total: 32 }] },
  1635. { w: -2, d: 1, v: 26, tech: 8, title: "New Holland T7 - 500hr Service", desc: "Scheduled interval. Engine oil, filters, hydraulic sample.", type: "maintenance", hour: 8, hours: 3.5, mileage: 2050, rate: 140, parts: [{ name: "Filter Kit T7", partNumber: "NH-FK-T7", quantity: 1, unitPrice: 240, total: 240 }, { name: "Engine Oil 15W-40 (5gal)", partNumber: "NH-15W40-5G", quantity: 1, unitPrice: 185, total: 185 }] },
  1636. { w: -2, d: 2, v: 10, tech: 1, title: "Audi A4 - Haldex Service", desc: "Quattro rear differential fluid and filter at 40K interval.", type: "maintenance", hour: 9, hours: 1.5, mileage: 21600, rate: 120, parts: [{ name: "Haldex Fluid + Filter", partNumber: "AUD-HLD-KIT", quantity: 1, unitPrice: 145, total: 145 }] },
  1637. { w: -2, d: 3, v: 33, tech: 2, title: "Volvo EC220E - Swing Bearing Grease", desc: "Swing bearing and slew ring service, play measured.", type: "maintenance", hour: 7, hours: 2.5, mileage: 1450, rate: 140, parts: [{ name: "Grease Cartridges (box of 10)", partNumber: "GRZ-EP2-10", quantity: 2, unitPrice: 42, total: 84 }] },
  1638. { w: -2, d: 4, v: 1, tech: 0, title: "F-150 - Tire Rotation + Balance", desc: "Rotation, balance and pressure set on all four.", type: "maintenance", hour: 13, hours: 1.0, mileage: 42100, rate: 95, parts: [] },
  1639. // ── Last week ──
  1640. { w: -1, d: 0, v: 39, tech: 4, title: "Defender 110 - Diff Fluid Service", desc: "Front and rear differential fluid after heavy off-road use.", type: "maintenance", hour: 8, hours: 2.0, mileage: 28300, rate: 120, parts: [{ name: "Diff Fluid 75W-90 (4qt)", partNumber: "LR-DF-7590", quantity: 1, unitPrice: 96, total: 96 }] },
  1641. { w: -1, d: 1, v: 20, tech: 7, title: "Concrete Mixer - Water Pump Repair", desc: "Water system pump leaking at the seal. Rebuilt and tested.", type: "repair", hour: 7, hours: 3.0, mileage: 67500, rate: 140, parts: [{ name: "Water Pump Rebuild Kit", partNumber: "MIX-WPK", quantity: 1, unitPrice: 185, total: 185 }] },
  1642. { w: -1, d: 2, v: 3, tech: 6, title: "F-150 Platinum - Brake Fluid Flush", desc: "Two-year brake fluid service for the municipal fleet.", type: "maintenance", hour: 9, hours: 1.5, mileage: 11800, rate: 110, parts: [{ name: "Brake Fluid DOT4 (1L)", partNumber: "BF-DOT4-1L", quantity: 2, unitPrice: 22, total: 44 }] },
  1643. { w: -1, d: 3, v: 37, tech: 5, title: "Forklift - Battery Watering + Load Test", desc: "Traction battery watered, cells load tested and logged.", type: "maintenance", hour: 8, hours: 2.0, mileage: 4150, rate: 120, parts: [{ name: "Distilled Water (5gal)", partNumber: "FRK-DW-5G", quantity: 1, unitPrice: 18, total: 18 }] },
  1644. { w: -1, d: 4, v: 16, tech: 3, title: "Tacoma - Front Brake Service", desc: "Front pads and rotors replaced, calipers cleaned.", type: "repair", hour: 10, hours: 2.0, mileage: 31000, rate: 110, parts: [{ name: "Front Pads + Rotors", partNumber: "TOY-BPR-TAC", quantity: 1, unitPrice: 285, total: 285 }] },
  1645. // ── Next week ──
  1646. { w: 1, d: 0, v: 7, tech: 3, title: "Tesla Model Y - Brake Fluid Test", desc: "Two-year brake fluid moisture test and flush if needed.", type: "maintenance", hour: 8, hours: 1.5, mileage: 3400, rate: 110, parts: [{ name: "Brake Fluid DOT4 (1L)", partNumber: "BF-DOT4-1L", quantity: 1, unitPrice: 22, total: 22 }] },
  1647. { w: 1, d: 1, v: 29, tech: 2, title: "CAT D6 - Undercarriage Measurement", desc: "Wear measurement on chains, rollers and idlers ahead of the rebuild quote.", type: "inspection", hour: 7, hours: 3.0, mileage: 4300, rate: 150, parts: [] },
  1648. { w: 1, d: 2, v: 14, tech: 6, title: "VW Golf GTI - Haldex + Oil Service", desc: "Oil change and rear diff service ahead of a road trip.", type: "maintenance", hour: 9, hours: 2.0, mileage: 38900, rate: 120, parts: [{ name: "Engine Oil 5W-40 (6qt)", partNumber: "VW-5W40-6Q", quantity: 1, unitPrice: 72, total: 72 }] },
  1649. { w: 1, d: 3, v: 2, tech: 0, title: "F-150 XLT - State Safety Inspection", desc: "Minnesota annual safety inspection with documentation.", type: "inspection", hour: 8, hours: 1.5, mileage: 55400, rate: 95, parts: [] },
  1650. { w: 1, d: 4, v: 27, tech: 2, title: "S780 Combine - Header Inspection", desc: "Pre-season header check: knives, auger, feeder chain.", type: "inspection", hour: 7, hours: 4.0, mileage: 640, rate: 140, parts: [] },
  1651. // ── The week after ──
  1652. { w: 2, d: 0, v: 4, tech: 1, title: "BMW 330i - Front Brake Overhaul", desc: "Accepted quote: OEM pads, rotors and wear sensors.", type: "repair", hour: 8, hours: 3.0, mileage: 56400, rate: 120, parts: [{ name: "OEM Pads + Rotors (front)", partNumber: "BMW-BPR-F34", quantity: 1, unitPrice: 505, total: 505 }] },
  1653. { w: 2, d: 1, v: 18, tech: 9, title: "Volvo FH 640 - Air Suspension Repair", desc: "Accepted quote: replace failed air bag and levelling valve.", type: "repair", hour: 7, hours: 4.0, mileage: 93800, rate: 140, parts: [{ name: "Air Bag + Levelling Valve", partNumber: "VOL-ASK-FH", quantity: 1, unitPrice: 690, total: 690 }] },
  1654. { w: 2, d: 2, v: 11, tech: 9, title: "Jeep Wrangler - Winch Install", desc: "Accepted quote: bumper-mounted winch with isolator and wiring.", type: "repair", hour: 8, hours: 4.0, mileage: 29200, rate: 110, parts: [{ name: "12,000 lb Winch + Wiring Kit", partNumber: "JEEP-WIN-12K", quantity: 1, unitPrice: 880, total: 880 }] },
  1655. { w: 2, d: 3, v: 5, tech: 0, title: "Honda Civic - Clutch Replacement", desc: "Accepted quote: clutch kit, flywheel resurface, hydraulic bleed.", type: "repair", hour: 7, hours: 5.5, mileage: 68200, rate: 95, parts: [{ name: "Clutch Kit", partNumber: "HON-CK-CIV", quantity: 1, unitPrice: 420, total: 420 }] },
  1656. { w: 2, d: 4, v: 34, tech: 8, title: "Kubota KX040 - Hose Reroute", desc: "Reroute the chafing hydraulic hose and fit a protective sleeve.", type: "repair", hour: 9, hours: 2.0, mileage: 950, rate: 130, parts: [{ name: "Hydraulic Hose + Sleeve", partNumber: "KUB-HHS-040", quantity: 1, unitPrice: 145, total: 145 }] },
  1657. ];
  1658. const spreadRecords = [];
  1659. for (const job of spreadJobs) {
  1660. const offset = wd(job.w, job.d);
  1661. const past = offset < 0;
  1662. const labor = [{ description: job.title.split(" - ")[1] || "Workshop labor", hours: job.hours, rate: job.rate, total: Math.round(job.hours * job.rate * 100) / 100 }];
  1663. const endMinutes = job.hour * 60 + Math.round(job.hours * 60);
  1664. const rec = await sr(
  1665. {
  1666. vehicleId: vehicles[job.v].id,
  1667. title: job.title,
  1668. description: job.desc,
  1669. type: job.type,
  1670. status: past ? "completed" : "scheduled",
  1671. serviceDate: days(offset),
  1672. startDateTime: at(offset, job.hour),
  1673. endDateTime: at(offset, Math.floor(endMinutes / 60), endMinutes % 60),
  1674. mileage: job.mileage,
  1675. technicianId: technicians[job.tech].id,
  1676. techName: technicians[job.tech].name,
  1677. shopName: "Egeland Auto",
  1678. },
  1679. job.parts,
  1680. labor,
  1681. );
  1682. spreadRecords.push(rec);
  1683. }
  1684. console.log(` Created ${spreadRecords.length} jobs across ${new Set(spreadJobs.map(j => j.w)).size} weeks`);
  1685. // -- Invoices & payments --
  1686. // Every completed job gets a number from the same sequence the app would use
  1687. // (workshop.invoiceStartNumber = 1001, prefix "{year}-"), then most of them
  1688. // get paid. Without this the sales page, the revenue report and the past-due
  1689. // list all read zero.
  1690. console.log("\nNumbering invoices and recording payments...");
  1691. const completed = await prisma.serviceRecord.findMany({
  1692. where: { organizationId: ORG_ID, status: "completed" },
  1693. orderBy: { serviceDate: "asc" },
  1694. select: { id: true, serviceDate: true, totalAmount: true, mileage: true },
  1695. });
  1696. const methods = ["card", "transfer", "cash", "card", "transfer"];
  1697. let invoiceSeq = 1001;
  1698. let paidFull = 0, paidPartial = 0, outstanding = 0;
  1699. for (const [i, rec] of completed.entries()) {
  1700. const invoiceDate = rec.serviceDate;
  1701. const dueDate = new Date(invoiceDate);
  1702. dueDate.setDate(dueDate.getDate() + 14);
  1703. const warrantyExpires = new Date(invoiceDate);
  1704. warrantyExpires.setMonth(warrantyExpires.getMonth() + 12);
  1705. await prisma.serviceRecord.update({
  1706. where: { id: rec.id },
  1707. data: {
  1708. invoiceNumber: `${YEAR}-${invoiceSeq++}`,
  1709. invoiceDate,
  1710. invoiceDueDate: dueDate,
  1711. warrantyMonths: 12,
  1712. warrantyMileage: 12000,
  1713. warrantyExpiresAt: warrantyExpires,
  1714. },
  1715. });
  1716. // 7 in 10 settled, 1 part-paid, 2 still open - enough of a spread that the
  1717. // past-due list and the outstanding total are both non-empty.
  1718. const bucket = i % 10;
  1719. if (bucket < 7) {
  1720. const paidOn = new Date(invoiceDate);
  1721. paidOn.setDate(paidOn.getDate() + (i % 9));
  1722. await prisma.payment.create({ data: { serviceRecordId: rec.id, amount: rec.totalAmount, date: paidOn > NOW ? NOW : paidOn, method: methods[i % methods.length], note: "Paid in full" } });
  1723. paidFull++;
  1724. } else if (bucket === 7) {
  1725. const paidOn = new Date(invoiceDate);
  1726. paidOn.setDate(paidOn.getDate() + 2);
  1727. await prisma.payment.create({ data: { serviceRecordId: rec.id, amount: Math.round(rec.totalAmount * 0.5 * 100) / 100, date: paidOn > NOW ? NOW : paidOn, method: "transfer", note: "Deposit - balance on collection" } });
  1728. paidPartial++;
  1729. } else {
  1730. outstanding++;
  1731. }
  1732. }
  1733. console.log(` ${completed.length} invoices numbered - ${paidFull} paid, ${paidPartial} part-paid, ${outstanding} outstanding`);
  1734. // -- Stock movements --
  1735. // Inventory quantities without a history read as if they were typed in once.
  1736. // These are the consumption and restock entries behind the current counts.
  1737. console.log("\nCreating stock movements...");
  1738. const movementPlan: { part: number; entries: { delta: number; reason: string; day: number; note?: string }[] }[] = [
  1739. { part: 0, entries: [{ delta: 24, reason: "manual_adjustment", day: -46, note: "Pallet delivery from AutoZone Commercial" }, { delta: -4, reason: "service_record", day: -21 }, { delta: -2, reason: "service_record", day: -12 }, { delta: -3, reason: "service_record", day: -4 }] },
  1740. { part: 1, entries: [{ delta: 20, reason: "manual_adjustment", day: -40, note: "Restock" }, { delta: -2, reason: "service_record", day: -18 }, { delta: -1, reason: "service_record", day: -6 }] },
  1741. { part: 4, entries: [{ delta: 18, reason: "manual_adjustment", day: -52, note: "Quarterly brake stock order" }, { delta: -2, reason: "service_record", day: -25 }, { delta: -1, reason: "quote_conversion", day: -9 }, { delta: -1, reason: "service_record", day: -2 }] },
  1742. { part: 6, entries: [{ delta: 36, reason: "manual_adjustment", day: -60, note: "Bulk filter order" }, { delta: -3, reason: "service_record", day: -30 }, { delta: -2, reason: "service_record", day: -11 }, { delta: -1, reason: "service_record", day: -1 }] },
  1743. { part: 10, entries: [{ delta: 8, reason: "manual_adjustment", day: -35, note: "Interstate Batteries delivery" }, { delta: -1, reason: "service_record", day: -16 }, { delta: -1, reason: "service_record", day: -3 }] },
  1744. { part: 21, entries: [{ delta: 4, reason: "manual_adjustment", day: -50, note: "Bosch order" }, { delta: -2, reason: "service_record", day: -28 }, { delta: -1, reason: "service_record", day: -7, note: "Kenworth DPF fault" }] },
  1745. { part: 15, entries: [{ delta: 12, reason: "manual_adjustment", day: -44 }, { delta: -1, reason: "service_record", day: -20 }, { delta: -1, reason: "service_record", day: -5 }] },
  1746. { part: 24, entries: [{ delta: 16, reason: "manual_adjustment", day: -38 }, { delta: -2, reason: "service_record", day: -19 }, { delta: -2, reason: "bulk_markup", day: -8, note: "Counter sale" }] },
  1747. ];
  1748. let movementCount = 0;
  1749. for (const plan of movementPlan) {
  1750. const part = inventoryParts[plan.part];
  1751. // Walk backwards from today's quantity so the running balance ends on it.
  1752. const total = plan.entries.reduce((sum, e) => sum + e.delta, 0);
  1753. let balance = part.quantity - total;
  1754. for (const entry of plan.entries) {
  1755. balance += entry.delta;
  1756. await prisma.stockMovement.create({
  1757. data: {
  1758. inventoryPartId: part.id,
  1759. delta: entry.delta,
  1760. quantityAfter: balance,
  1761. reason: entry.reason,
  1762. note: entry.note ?? null,
  1763. serviceRecordLabel: entry.reason === "service_record" ? "Workshop job" : null,
  1764. userId: USER_ID,
  1765. organizationId: ORG_ID,
  1766. createdAt: at(entry.day, 9, 30),
  1767. },
  1768. });
  1769. movementCount++;
  1770. }
  1771. }
  1772. console.log(` Created ${movementCount} stock movements across ${movementPlan.length} parts`);
  1773. // -- Inspection templates & inspections --
  1774. // The templates page syncs the built-in presets on first load, but nothing
  1775. // creates inspections, so the feature reads as unused. These build the same
  1776. // templates the library would install, then run vehicles through them.
  1777. console.log("\nCreating inspection templates...");
  1778. // Written as the workshop's own checklists (no packageId), so the built-in
  1779. // preset library still installs its copies when the templates page first
  1780. // loads rather than treating these as an already-installed package.
  1781. const toTemplateCreate = (preset: SeedTemplate, isDefault: boolean) => ({
  1782. name: preset.name,
  1783. description: preset.description,
  1784. isDefault,
  1785. country: preset.country,
  1786. standard: preset.standard,
  1787. severityScale: preset.severityScale,
  1788. organizationId: ORG_ID,
  1789. sections: {
  1790. create: preset.sections.map((section, sIdx) => ({
  1791. name: section.name,
  1792. description: section.description || null,
  1793. code: section.code || null,
  1794. sortOrder: sIdx,
  1795. items: {
  1796. create: section.items.map((item, iIdx) => ({
  1797. name: item.name,
  1798. description: item.description || null,
  1799. code: item.code || null,
  1800. sortOrder: iIdx,
  1801. inputType: item.inputType ?? "condition",
  1802. unit: item.unit || null,
  1803. minValue: item.minValue ?? null,
  1804. maxValue: item.maxValue ?? null,
  1805. choices: item.choices ?? [],
  1806. required: item.required ?? false,
  1807. photoRequired: item.photoRequired ?? false,
  1808. defaultSeverity: item.defaultSeverity ?? null,
  1809. defectSuggestions: [],
  1810. })),
  1811. },
  1812. })),
  1813. },
  1814. });
  1815. const templates = [];
  1816. for (const [i, preset] of SEED_TEMPLATES.entries()) {
  1817. const template = await prisma.inspectionTemplate.create({
  1818. data: toTemplateCreate(preset, i === 0),
  1819. include: { sections: { include: { items: { orderBy: { sortOrder: "asc" } } }, orderBy: { sortOrder: "asc" } } },
  1820. });
  1821. templates.push(template);
  1822. }
  1823. console.log(` Created ${templates.length} templates`);
  1824. console.log("\nCreating inspections...");
  1825. type TemplateWithSections = (typeof templates)[number];
  1826. type Defect = { at: number; condition: string; notes: string };
  1827. /**
  1828. * Copies a template's checks onto an inspection. Everything grades `pass`
  1829. * unless it is listed in `defects`, and an in-progress inspection leaves the
  1830. * checks past `graded` untouched - which is what the completion blockers and
  1831. * the progress bar in the UI read.
  1832. */
  1833. const buildInspection = async (opts: {
  1834. template: TemplateWithSections;
  1835. vehicleIdx: number;
  1836. techIdx: number;
  1837. dayOffset: number;
  1838. hour: number;
  1839. mileage: number;
  1840. status: "in_progress" | "completed";
  1841. defects?: Defect[];
  1842. graded?: number;
  1843. category?: string;
  1844. certificate?: string;
  1845. notes?: string;
  1846. nextTestMonths?: number;
  1847. }) => {
  1848. const flat = opts.template.sections.flatMap((s) => s.items.map((item) => ({ item, section: s })));
  1849. const defects = new Map((opts.defects ?? []).map((d) => [d.at % flat.length, d]));
  1850. const graded = opts.graded ?? flat.length;
  1851. const completedAt = opts.status === "completed" ? at(opts.dayOffset, opts.hour + 2) : null;
  1852. const nextTest = opts.nextTestMonths ? months(opts.nextTestMonths) : null;
  1853. return prisma.inspection.create({
  1854. data: {
  1855. status: opts.status,
  1856. mileage: opts.mileage,
  1857. notes: opts.notes ?? null,
  1858. startDateTime: at(opts.dayOffset, opts.hour),
  1859. endDateTime: completedAt,
  1860. completedAt,
  1861. createdAt: at(opts.dayOffset, opts.hour),
  1862. publicToken: randomBytes(16).toString("hex"),
  1863. vehicleId: vehicles[opts.vehicleIdx].id,
  1864. templateId: opts.template.id,
  1865. technicianId: technicians[opts.techIdx].id,
  1866. organizationId: ORG_ID,
  1867. severityScale: opts.template.severityScale,
  1868. country: opts.template.country,
  1869. vehicleCategory: opts.category ?? null,
  1870. nextTestDue: nextTest,
  1871. certificateNumber: opts.certificate ?? null,
  1872. inspectorName: opts.status === "completed" ? technicians[opts.techIdx].name : null,
  1873. testLocation: opts.status === "completed" ? "Egeland Auto, Denver CO" : null,
  1874. items: {
  1875. create: flat.map(({ item, section }, idx) => {
  1876. const defect = defects.get(idx);
  1877. const inspected = idx < graded;
  1878. const condition = defect ? defect.condition : inspected ? "pass" : "not_inspected";
  1879. const measured =
  1880. item.inputType === "measurement" && inspected
  1881. ? defect
  1882. ? (item.minValue ?? 0) * 0.6
  1883. : item.minValue != null && item.maxValue != null
  1884. ? Math.round(((item.minValue + item.maxValue) / 2) * 10) / 10
  1885. : (item.minValue ?? item.maxValue ?? 0)
  1886. : null;
  1887. return {
  1888. name: item.name,
  1889. section: section.name,
  1890. sortOrder: idx,
  1891. condition,
  1892. notes: defect?.notes ?? null,
  1893. description: item.description,
  1894. code: item.code,
  1895. sectionCode: section.code,
  1896. inputType: item.inputType,
  1897. unit: item.unit,
  1898. minValue: item.minValue,
  1899. maxValue: item.maxValue,
  1900. choices: item.choices,
  1901. required: item.required,
  1902. photoRequired: item.photoRequired,
  1903. defaultSeverity: item.defaultSeverity,
  1904. measuredValue: measured,
  1905. textValue: item.inputType === "text" && inspected ? "No remarks" : null,
  1906. };
  1907. }),
  1908. },
  1909. },
  1910. });
  1911. };
  1912. const multipoint = templates[0];
  1913. const roadworthiness = templates.find((t) => t.standard === "eu-2014-45") ?? multipoint;
  1914. const prePurchase = templates[2] ?? multipoint;
  1915. const inspections = [
  1916. // Completed, clean
  1917. await buildInspection({ template: multipoint, vehicleIdx: 0, techIdx: 0, dayOffset: wd(-2, 1), hour: 9, mileage: 17900, status: "completed", category: "M1", notes: "Everything within spec. Customer wants a call before the next service." }),
  1918. await buildInspection({ template: multipoint, vehicleIdx: 6, techIdx: 3, dayOffset: wd(-1, 2), hour: 11, mileage: 8100, status: "completed", category: "M1" }),
  1919. // Completed with defects
  1920. await buildInspection({ template: multipoint, vehicleIdx: 5, techIdx: 0, dayOffset: wd(-1, 0), hour: 8, mileage: 67500, status: "completed", category: "M1", notes: "Two items need booking in. Quote requested by the customer.", defects: [{ at: 3, condition: "fail", notes: "CV boot torn, grease thrown onto the suspension arm." }, { at: 7, condition: "attention", notes: "Front pads at 3mm - plan replacement within 5,000 miles." }] }),
  1921. await buildInspection({ template: multipoint, vehicleIdx: 8, techIdx: 2, dayOffset: wd(-1, 3), hour: 13, mileage: 98200, status: "completed", category: "N2", defects: [{ at: 5, condition: "attention", notes: "Battery load tests at 78% of rated CCA." }] }),
  1922. // Roadworthiness tests with certificates
  1923. await buildInspection({ template: roadworthiness, vehicleIdx: 18, techIdx: 2, dayOffset: wd(-2, 3), hour: 7, mileage: 92400, status: "completed", category: "N3", certificate: `PTI-${YEAR}-0418`, nextTestMonths: 12, notes: "Passed after the marker lights and wipers were replaced during the test.", defects: [{ at: 11, condition: "attention", notes: "Nearside marker lens cracked - replaced during the test." }] }),
  1924. await buildInspection({ template: roadworthiness, vehicleIdx: 4, techIdx: 1, dayOffset: wd(-1, 4), hour: 9, mileage: 56100, status: "completed", category: "M1", certificate: `PTI-${YEAR}-0431`, nextTestMonths: 24 }),
  1925. await buildInspection({ template: roadworthiness, vehicleIdx: 9, techIdx: 1, dayOffset: wd(0, 1), hour: 8, mileage: 35700, status: "completed", category: "N1", certificate: `PTI-${YEAR}-0447`, nextTestMonths: 12, notes: "Retest after the turbo replacement. Passed.", defects: [{ at: 2, condition: "attention", notes: "Slight play in the offside track rod end - monitor." }] }),
  1926. // Failed test - dangerous defect, vehicle held
  1927. await buildInspection({ template: roadworthiness, vehicleIdx: 19, techIdx: 2, dayOffset: wd(0, 0), hour: 10, mileage: 156200, status: "completed", category: "N3", certificate: `PTI-${YEAR}-0452`, notes: "Fails on the dump body cracking. Vehicle not to be loaded until welded.", defects: [{ at: 4, condition: "dangerous", notes: "Structural cracks in the dump body floor near the rear hinge." }, { at: 9, condition: "fail", notes: "Offside rear brake lining below the minimum thickness." }] }),
  1928. // In progress on the board right now
  1929. await buildInspection({ template: multipoint, vehicleIdx: 13, techIdx: 10, dayOffset: 0, hour: 9, mileage: 13000, status: "in_progress", graded: 6, category: "M1", notes: "Pre-track inspection for the customer's HPDE weekend." }),
  1930. await buildInspection({ template: roadworthiness, vehicleIdx: 2, techIdx: 6, dayOffset: 0, hour: 13, mileage: 55300, status: "in_progress", graded: 14, category: "N1" }),
  1931. await buildInspection({ template: prePurchase, vehicleIdx: 40, techIdx: 0, dayOffset: wd(0, 2), hour: 10, mileage: 34900, status: "in_progress", graded: 4, category: "M1", notes: "Buyer is paying for the inspection. Report goes to them, not the seller." }),
  1932. ];
  1933. console.log(` Created ${inspections.length} inspections`);
  1934. // A customer asking for a quote off the back of a failed check.
  1935. await prisma.inspectionQuoteRequest.create({
  1936. data: {
  1937. inspectionId: inspections[2].id,
  1938. organizationId: ORG_ID,
  1939. status: "pending",
  1940. message: "Please quote both items. I can leave the car with you next week.",
  1941. selectedItemIds: [],
  1942. createdAt: hoursAgo(30),
  1943. },
  1944. });
  1945. await prisma.inspectionQuoteRequest.create({
  1946. data: {
  1947. inspectionId: inspections[7].id,
  1948. organizationId: ORG_ID,
  1949. status: "quoted",
  1950. message: "Send the weld repair cost to ops@ridgelineexcavation.example.com.",
  1951. selectedItemIds: [],
  1952. createdAt: hoursAgo(52),
  1953. },
  1954. });
  1955. // -- Scheduled messages --
  1956. // The messages page and the calendar's message events both read these. The
  1957. // mix is deliberate: sent history behind us, a queue in front, a couple of
  1958. // recurring ones that keep rescheduling, plus one failure and one cancelled
  1959. // so the status filters have something in every bucket.
  1960. console.log("\nCreating scheduled messages...");
  1961. const scheduledMessages = await Promise.all([
  1962. // Already sent
  1963. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "sms", body: "Hi James, your Toyota Camry is booked in for Thursday at 08:00. Reply STOP to opt out.", customerId: customers[1].id, vehicleId: vehicles[0].id, status: "sent", sendAt: at(-9, 9), sentAt: at(-9, 9), lastRunAt: at(-9, 9), runCount: 1 } }),
  1964. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "email", subject: "Your invoice from Egeland Auto", body: "Hi Sarah,\n\nThe annual service on your Porsche 911 is complete and the invoice is attached. All OEM parts as always.\n\nEgeland Auto", customerId: customers[3].id, vehicleId: vehicles[13].id, status: "sent", sendAt: at(-6, 16), sentAt: at(-6, 16), lastRunAt: at(-6, 16), runCount: 1 } }),
  1965. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "sms", body: "Ridgeline: the Komatsu PC210 is ready for transport. Track chains and sprockets both replaced.", customerId: customers[8].id, vehicleId: vehicles[31].id, status: "sent", sendAt: at(-3, 15, 30), sentAt: at(-3, 15, 30), lastRunAt: at(-3, 15, 30), runCount: 1 } }),
  1966. // Queued for today and this week
  1967. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "sms", body: "Kevin, the Sprinter is finished and ready for collection any time before 17:00 today.", customerId: customers[15].id, vehicleId: vehicles[9].id, status: "scheduled", sendAt: at(0, 15) } }),
  1968. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "in_app", body: "Chase Metro City Services for the purchase order before starting the F-150 exhaust job.", status: "scheduled", sendAt: at(0, 16, 30) } }),
  1969. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "email", subject: `Quote Q-${YEAR}-003 - CAT D6 undercarriage`, body: "Hi,\n\nA reminder that the undercarriage rebuild quote for the CAT D6 expires in three weeks. Happy to walk through the wear measurements if that helps.\n\nEgeland Auto", customerId: customers[0].id, vehicleId: vehicles[29].id, status: "scheduled", sendAt: at(1, 9) } }),
  1970. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "sms", body: "Reminder: your Volvo FH 640 brake inspection is booked for tomorrow at 07:30.", customerId: customers[2].id, vehicleId: vehicles[18].id, status: "scheduled", sendAt: at(2, 8) } }),
  1971. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "email", subject: "Pre-planting service slots", body: "Hi,\n\nWe are holding two slots for the John Deere 6R and the Massey Ferguson ahead of planting. Let us know which week suits.\n\nEgeland Auto", customerId: customers[10].id, status: "scheduled", sendAt: at(3, 10) } }),
  1972. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "telegram", body: "Your Tesla Model Y is booked for a brake fluid test on Monday at 08:00.", customerId: customers[13].id, vehicleId: vehicles[7].id, status: "scheduled", sendAt: at(4, 9) } }),
  1973. // Further out
  1974. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "email", subject: "Track day prep - Porsche 911", body: "Hi Sarah,\n\nBooking your 911 in for brake pads, fluid and tire pressures the week before the track day. Reply with a day that suits.\n\nEgeland Auto", customerId: customers[3].id, vehicleId: vehicles[13].id, status: "scheduled", sendAt: at(9, 11) } }),
  1975. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "sms", body: "Titan Building: the Liebherr crane certification is due. Shall we book the external inspector?", customerId: customers[14].id, vehicleId: vehicles[36].id, status: "scheduled", sendAt: at(12, 10) } }),
  1976. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "email", subject: "Pre-harvest booking", body: "Hi,\n\nHarvest is close enough that the combine slots are filling. Reply to hold a week for the S780 and the X9.\n\nEgeland Auto", customerId: customers[18].id, status: "scheduled", sendAt: at(21, 9) } }),
  1977. // Recurring
  1978. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "email", subject: "Monthly fleet maintenance statement", body: "Attached is this month's statement across all Summit Construction units.\n\nEgeland Auto", customerId: customers[0].id, status: "scheduled", frequency: "monthly", sendAt: at(6, 8), endDate: months(12), lastRunAt: at(-24, 8), runCount: 4 } }),
  1979. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "sms", body: "Greenfield: quarterly PM window opens next week. Reply with the trucks you want in first.", customerId: customers[16].id, status: "scheduled", frequency: "monthly", sendAt: at(8, 9), lastRunAt: at(-22, 9), runCount: 2 } }),
  1980. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "in_app", body: "Weekly check: any job on the board still waiting on parts?", status: "scheduled", frequency: "weekly", sendAt: at(MONDAY_OFFSET + 4, 15), lastRunAt: at(MONDAY_OFFSET - 3, 15), runCount: 9 } }),
  1981. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "email", subject: "Annual roadworthiness test due", body: "Hi,\n\nYour vehicle's periodic technical inspection is due within the month. Reply to book a slot.\n\nEgeland Auto", customerId: customers[2].id, vehicleId: vehicles[17].id, status: "scheduled", frequency: "yearly", sendAt: at(30, 9), runCount: 1, lastRunAt: at(-335, 9) } }),
  1982. // The unhappy paths
  1983. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "sms", body: "Amanda, your Civic clutch quote is ready to view.", customerId: customers[9].id, vehicleId: vehicles[5].id, status: "failed", sendAt: at(-2, 11), lastRunAt: at(-2, 11), runCount: 1, errorMessage: "Carrier rejected the message: unknown destination number" } }),
  1984. prisma.scheduledMessage.create({ data: { organizationId: ORG_ID, createdById: USER_ID, channel: "email", subject: "Winter tire changeover", body: "Booking opens next week for the winter changeover.", customerId: customers[11].id, status: "cancelled", sendAt: at(5, 9) } }),
  1985. ]);
  1986. console.log(` Created ${scheduledMessages.length} scheduled messages`);
  1987. // -- Telegram --
  1988. console.log("\nCreating Telegram messages...");
  1989. await prisma.customer.update({ where: { id: customers[13].id }, data: { telegramChatId: "784512996" } });
  1990. await prisma.customer.update({ where: { id: customers[5].id }, data: { telegramChatId: "612447803" } });
  1991. const telegram = await Promise.all([
  1992. prisma.telegramMessage.create({ data: { organizationId: ORG_ID, customerId: customers[13].id, direction: "outbound", chatId: "784512996", body: "Hi Jessica, your Tesla Model Y is booked for a brake fluid test on Monday at 08:00.", status: "delivered", createdAt: hoursAgo(72) } }),
  1993. prisma.telegramMessage.create({ data: { organizationId: ORG_ID, customerId: customers[13].id, direction: "inbound", chatId: "784512996", body: "Perfect. Can you check the tire wear at the same time?", status: "received", createdAt: hoursAgo(71) } }),
  1994. prisma.telegramMessage.create({ data: { organizationId: ORG_ID, customerId: customers[13].id, direction: "outbound", chatId: "784512996", body: "Will do - we'll measure all four and send the numbers with the report.", status: "delivered", createdAt: hoursAgo(70) } }),
  1995. prisma.telegramMessage.create({ data: { organizationId: ORG_ID, customerId: customers[5].id, direction: "outbound", chatId: "612447803", body: "Ryan, the 12V auxiliary battery for the Model 3 is in stock. Want it done this week?", status: "delivered", createdAt: hoursAgo(26) } }),
  1996. prisma.telegramMessage.create({ data: { organizationId: ORG_ID, customerId: customers[5].id, direction: "inbound", chatId: "612447803", body: "Yes please. Thursday afternoon if you have it.", status: "received", createdAt: hoursAgo(25) } }),
  1997. prisma.telegramMessage.create({ data: { organizationId: ORG_ID, customerId: customers[5].id, direction: "outbound", chatId: "612447803", body: "Thursday 13:00 booked. It's a 30 minute job, you can wait if you like.", status: "delivered", createdAt: hoursAgo(24) } }),
  1998. ]);
  1999. console.log(` Created ${telegram.length} Telegram messages`);
  2000. // -- Notifications --
  2001. // The bell is empty on a fresh reset, which makes the app look idle.
  2002. console.log("\nCreating notifications...");
  2003. const notifications = await Promise.all([
  2004. prisma.notification.create({ data: { organizationId: ORG_ID, type: "sms_inbound", title: "New SMS from Summit Construction", message: "Thanks! We'll send someone before 4pm. Can you look at the D6 bulldozer next week?", entityType: "customer", entityId: customers[0].id, entityUrl: `/customers/${customers[0].id}`, read: false, createdAt: minutesAgo(58) } }),
  2005. prisma.notification.create({ data: { organizationId: ORG_ID, type: "inspection_quote_request", title: "Quote requested from an inspection", message: "Amanda Foster asked for a quote on two items from the Honda Civic inspection.", entityType: "inspection", entityId: inspections[2].id, entityUrl: `/inspections/${inspections[2].id}`, read: false, createdAt: hoursAgo(3) } }),
  2006. prisma.notification.create({ data: { organizationId: ORG_ID, type: "inventory.lowStock", title: "Low stock: DPF Pressure Sensor", message: "1 in stock, reorder point is 3.", entityType: "inventory", entityId: inventoryParts[21].id, entityUrl: `/inventory`, read: false, createdAt: hoursAgo(6) } }),
  2007. prisma.notification.create({ data: { organizationId: ORG_ID, type: "reminder.due", title: "Reminder due today", message: "Volvo FH 640 - brake inspection before the next long-haul run.", entityType: "reminder", entityId: coreReminders[5].id, entityUrl: `/reminders`, read: false, createdAt: at(0, 7) } }),
  2008. prisma.notification.create({ data: { organizationId: ORG_ID, type: "service_request", title: "New service request", message: "Mike Thompson asked for a booking for the Jeep Wrangler Rubicon.", entityType: "service_request", entityId: vehicles[11].id, entityUrl: `/work-orders`, read: false, createdAt: hoursAgo(19) } }),
  2009. prisma.notification.create({ data: { organizationId: ORG_ID, type: "quote_response", title: "Quote accepted", message: `Jeep Wrangler - Winch Install (Q-${YEAR}-011) was accepted by Mike Thompson.`, entityType: "quote", entityId: quotes[10].id, entityUrl: `/quotes/${quotes[10].id}`, read: true, createdAt: hoursAgo(30) } }),
  2010. prisma.notification.create({ data: { organizationId: ORG_ID, type: "invoice_payment", title: "Payment received", message: "Pacific Freight Lines settled the Kenworth T680 engine service invoice.", entityType: "invoice", entityId: serviceRecords[4].id, entityUrl: `/work-orders/${serviceRecords[4].id}`, read: true, createdAt: hoursAgo(50) } }),
  2011. prisma.notification.create({ data: { organizationId: ORG_ID, type: "telegram_inbound", title: "New Telegram message", message: "Jessica Rivera: Can you check the tire wear at the same time?", entityType: "customer", entityId: customers[13].id, entityUrl: `/customers/${customers[13].id}`, read: true, createdAt: hoursAgo(71) } }),
  2012. prisma.notification.create({ data: { organizationId: ORG_ID, type: "status_report_feedback", title: "Customer replied to a status report", message: "Lisa Martinez: \"Thanks for the video, that makes sense. Go ahead.\"", entityType: "service_record", entityId: serviceRecords[0].id, entityUrl: `/work-orders/${serviceRecords[0].id}`, read: true, createdAt: hoursAgo(96) } }),
  2013. ]);
  2014. console.log(` Created ${notifications.length} notifications`);
  2015. // -- Labor presets --
  2016. // cleanup() drops these on every reset, so the page is otherwise empty.
  2017. console.log("\nCreating labor presets...");
  2018. const laborPresets = await Promise.all([
  2019. prisma.laborPreset.create({ data: { organizationId: ORG_ID, userId: USER_ID, name: "Oil service - light vehicle", description: "Standard oil and filter change with a multi-point check.",
  2020. items: { create: [{ description: "Oil and filter change", hours: 0.5, rate: 110, sortOrder: 0 }, { description: "Multi-point inspection", hours: 0.5, rate: 110, sortOrder: 1 }] },
  2021. parts: { create: [{ name: "Synthetic Engine Oil 5W-30 (5qt)", partNumber: "OIL-5W30-5Q", quantity: 1, unitPrice: 45, sortOrder: 0, inventoryPartId: inventoryParts[0].id }, { name: "Oil Filter - European Vehicles", partNumber: "OF-EUR-01", quantity: 1, unitPrice: 15.5, sortOrder: 1, inventoryPartId: inventoryParts[6].id }] } } }),
  2022. prisma.laborPreset.create({ data: { organizationId: ORG_ID, userId: USER_ID, name: "Front brake service", description: "Pads and rotors front axle, including road test.",
  2023. items: { create: [{ description: "Front pad and rotor replacement", hours: 2, rate: 110, sortOrder: 0 }, { description: "Brake road test", hours: 0.3, rate: 110, sortOrder: 1 }] },
  2024. parts: { create: [{ name: "Brake Pad Set - Universal Light Vehicle", partNumber: "BP-UNI-LV", quantity: 1, unitPrice: 68, sortOrder: 0, inventoryPartId: inventoryParts[4].id }] } } }),
  2025. prisma.laborPreset.create({ data: { organizationId: ORG_ID, userId: USER_ID, name: "Heavy truck PM service", description: "Full preventive maintenance for a class 8 tractor unit.",
  2026. items: { create: [{ description: "Engine oil and all filters", hours: 2.5, rate: 140, sortOrder: 0 }, { description: "Grease service, all points", hours: 1, rate: 140, sortOrder: 1 }, { description: "Brake adjustment and lining measurement", hours: 1.5, rate: 140, sortOrder: 2 }] },
  2027. parts: { create: [{ name: "Heavy Duty Engine Oil 15W-40 (5gal)", partNumber: "OIL-15W40-5G", quantity: 2, unitPrice: 185, sortOrder: 0, inventoryPartId: inventoryParts[2].id }, { name: "Fuel Filter - Diesel Universal", partNumber: "FF-DSL-UNI", quantity: 2, unitPrice: 29, sortOrder: 1, inventoryPartId: inventoryParts[18].id }] } } }),
  2028. prisma.laborPreset.create({ data: { organizationId: ORG_ID, userId: USER_ID, name: "Excavator 1000hr service", description: "Fluids, filters, undercarriage and pin play check.",
  2029. items: { create: [{ description: "All fluids and filters", hours: 3, rate: 140, sortOrder: 0 }, { description: "Undercarriage and pin play inspection", hours: 1.5, rate: 140, sortOrder: 1 }] },
  2030. parts: { create: [{ name: "Hydraulic Filter - CAT/Komatsu", partNumber: "HF-CAT-KOM", quantity: 2, unitPrice: 120, sortOrder: 0, inventoryPartId: inventoryParts[8].id }, { name: "Air Filter - Heavy Equipment", partNumber: "AF-HE-UNI", quantity: 1, unitPrice: 85, sortOrder: 1, inventoryPartId: inventoryParts[19].id }] } } }),
  2031. prisma.laborPreset.create({ data: { organizationId: ORG_ID, userId: USER_ID, name: "Seasonal tire changeover", description: "Wheel swap, balance and pressure set, four wheels.",
  2032. items: { create: [{ description: "Wheel swap and balance (4)", hours: 1, rate: 95, sortOrder: 0 }, { description: "Pressure set and torque check", hours: 0.2, rate: 95, sortOrder: 1 }] },
  2033. parts: { create: [] } } }),
  2034. ]);
  2035. console.log(` Created ${laborPresets.length} labor presets`);
  2036. // -- Report schedules --
  2037. console.log("\nCreating report schedules...");
  2038. const reportSchedules = await Promise.all([
  2039. prisma.reportSchedule.create({ data: { organizationId: ORG_ID, createdById: USER_ID, name: "Monday morning summary", frequency: "weekly", dateRange: "last7d", sections: JSON.stringify(["revenue", "services", "technicians", "pastDue"]), recipients: JSON.stringify([USER_ID]), nextRunDate: at(MONDAY_OFFSET + 7, 7), lastRunAt: at(MONDAY_OFFSET, 7), runCount: 12, isActive: true } }),
  2040. prisma.reportSchedule.create({ data: { organizationId: ORG_ID, createdById: USER_ID, name: "Month-end financials", frequency: "monthly", dateRange: "last30d", sections: JSON.stringify(["revenue", "tax", "parts", "inventory"]), recipients: JSON.stringify([USER_ID]), nextRunDate: months(1), lastRunAt: months(-1), runCount: 5, isActive: true } }),
  2041. prisma.reportSchedule.create({ data: { organizationId: ORG_ID, createdById: USER_ID, name: "Quarterly customer retention", frequency: "quarterly", dateRange: "last90d", sections: JSON.stringify(["customers", "retention", "jobAnalytics"]), recipients: JSON.stringify([USER_ID]), nextRunDate: months(2), runCount: 0, isActive: false } }),
  2042. ]);
  2043. console.log(` Created ${reportSchedules.length} report schedules`);
  2044. // -- Recurring invoices --
  2045. console.log("\nCreating recurring invoices...");
  2046. const recurring = await Promise.all([
  2047. prisma.recurringInvoice.create({ data: { vehicleId: vehicles[17].id, title: "Kenworth T680 - monthly PM", description: "Contracted monthly preventive maintenance for Pacific Freight unit #3.", frequency: "monthly", type: "maintenance", taxRate: 8, nextRunDate: days(11), lastRunAt: days(-19), runCount: 7, invoiceNotes: "Fleet contract rate. Net-30.",
  2048. templateParts: { create: [{ name: "Heavy Duty Engine Oil 15W-40 (5gal)", partNumber: "OIL-15W40-5G", quantity: 2, unitPrice: 185 }, { name: "Fuel Filter - Diesel Universal", partNumber: "FF-DSL-UNI", quantity: 2, unitPrice: 29 }] },
  2049. templateLabor: { create: [{ description: "Full PM service", hours: 4, rate: 140 }] } } }),
  2050. prisma.recurringInvoice.create({ data: { vehicleId: vehicles[3].id, title: "Metro City F-150 - quarterly service", description: "Municipal contract. PO number required on every invoice.", frequency: "quarterly", type: "maintenance", taxRate: 8, nextRunDate: days(34), lastRunAt: days(-57), runCount: 3, invoiceNotes: "Quote the city asset tag on the invoice.",
  2051. templateParts: { create: [{ name: "Synthetic Engine Oil 5W-30 (5qt)", partNumber: "OIL-5W30-5Q", quantity: 2, unitPrice: 45 }] },
  2052. templateLabor: { create: [{ description: "Quarterly service and inspection", hours: 2, rate: 110 }] } } }),
  2053. prisma.recurringInvoice.create({ data: { vehicleId: vehicles[36].id, title: "Liebherr crane - annual certification", description: "Annual load test and certification for Titan Building.", frequency: "yearly", type: "inspection", taxRate: 8, nextRunDate: days(53), runCount: 1, lastRunAt: days(-312),
  2054. templateParts: { create: [] },
  2055. templateLabor: { create: [{ description: "Load test, certification and paperwork", hours: 8, rate: 150 }] } } }),
  2056. ]);
  2057. console.log(` Created ${recurring.length} recurring invoices`);
  2058. // -- Custom fields --
  2059. console.log("\nCreating custom fields...");
  2060. const customFields = await Promise.all([
  2061. prisma.customFieldDefinition.create({ data: { organizationId: ORG_ID, userId: USER_ID, name: "purchase_order", label: "Purchase order number", fieldType: "text", entityType: "service_record", sortOrder: 0, required: false } }),
  2062. prisma.customFieldDefinition.create({ data: { organizationId: ORG_ID, userId: USER_ID, name: "bay", label: "Workshop bay", fieldType: "select", options: JSON.stringify(["Bay 1", "Bay 2", "Bay 3", "Heavy bay", "Outside"]), entityType: "service_record", sortOrder: 1, required: false } }),
  2063. prisma.customFieldDefinition.create({ data: { organizationId: ORG_ID, userId: USER_ID, name: "courtesy_vehicle", label: "Courtesy vehicle issued", fieldType: "checkbox", entityType: "service_record", sortOrder: 2, required: false } }),
  2064. prisma.customFieldDefinition.create({ data: { organizationId: ORG_ID, userId: USER_ID, name: "site_contact", label: "Site contact", fieldType: "text", entityType: "quote", sortOrder: 0, required: false } }),
  2065. ]);
  2066. await Promise.all([
  2067. prisma.customFieldValue.create({ data: { fieldId: customFields[0].id, entityId: serviceRecords[5].id, entityType: "service_record", value: "PO-44821" } }),
  2068. prisma.customFieldValue.create({ data: { fieldId: customFields[1].id, entityId: serviceRecords[5].id, entityType: "service_record", value: "Heavy bay" } }),
  2069. prisma.customFieldValue.create({ data: { fieldId: customFields[1].id, entityId: serviceRecords[0].id, entityType: "service_record", value: "Bay 2" } }),
  2070. prisma.customFieldValue.create({ data: { fieldId: customFields[2].id, entityId: serviceRecords[12].id, entityType: "service_record", value: "true" } }),
  2071. prisma.customFieldValue.create({ data: { fieldId: customFields[3].id, entityId: quotes[2].id, entityType: "quote", value: "Dave Ruiz, site foreman - (555) 100-2044" } }),
  2072. ]);
  2073. console.log(` Created ${customFields.length} custom fields`);
  2074. // -- Service requests from the customer portal --
  2075. console.log("\nCreating portal service requests...");
  2076. const serviceRequests = await Promise.all([
  2077. prisma.serviceRequest.create({ data: { organizationId: ORG_ID, customerId: customers[11].id, vehicleId: vehicles[11].id, description: "Steering feels loose above 55 mph and there's a shimmy over expansion joints. Can you look before the weekend?", preferredDate: days(2), status: "pending", createdAt: hoursAgo(19) } }),
  2078. prisma.serviceRequest.create({ data: { organizationId: ORG_ID, customerId: customers[9].id, vehicleId: vehicles[5].id, description: "Clutch is slipping in third and fourth. I'd like the quote you mentioned turned into a booking.", preferredDate: days(6), status: "pending", createdAt: hoursAgo(41) } }),
  2079. prisma.serviceRequest.create({ data: { organizationId: ORG_ID, customerId: customers[19].id, vehicleId: vehicles[8].id, description: "Due for an oil change and the trailer plug is intermittent. Ranch use, so any weekday works.", preferredDate: days(9), status: "scheduled", adminNotes: "Booked for Tuesday 09:00 with Jake.", createdAt: hoursAgo(70) } }),
  2080. prisma.serviceRequest.create({ data: { organizationId: ORG_ID, customerId: customers[5].id, vehicleId: vehicles[6].id, description: "Low voltage warning on the Model 3 again. I think it's the 12V battery.", status: "completed", adminNotes: "12V battery replaced, tested good.", createdAt: hoursAgo(150) } }),
  2081. ]);
  2082. console.log(` Created ${serviceRequests.length} service requests`);
  2083. // -- Status reports --
  2084. console.log("\nCreating status reports...");
  2085. const statusReports = await Promise.all([
  2086. prisma.statusReport.create({ data: { organizationId: ORG_ID, serviceRecordId: serviceRecords[12].id, technicianId: technicians[1].id, title: "Sprinter turbo - what we found", message: "Shaft play was well past spec and the compressor wheel had contacted the housing. Replacement turbo is fitted and the oil feed line was flushed. Road tested, no smoke under boost.", status: "viewed", sentVia: "sms", publicToken: randomBytes(16).toString("hex"), sentAt: hoursAgo(52), viewedAt: hoursAgo(50), expiresAt: days(60) } }),
  2087. prisma.statusReport.create({ data: { organizationId: ORG_ID, serviceRecordId: serviceRecords[1].id, technicianId: technicians[1].id, title: "BMW 330i - 50,000 mile service", message: "Everything on the schedule is done: pads, rotors, plugs and a full inspection. Front tires have about 8,000 miles left in them.", status: "viewed", sentVia: "email", publicToken: randomBytes(16).toString("hex"), sentAt: hoursAgo(120), viewedAt: hoursAgo(117), customerFeedback: "Thanks, that's clear. Book me in when the tires get close.", feedbackAt: hoursAgo(116), expiresAt: days(45) } }),
  2088. prisma.statusReport.create({ data: { organizationId: ORG_ID, serviceRecordId: serviceRecords[0].id, technicianId: technicians[0].id, title: "Camry - oil service done", message: "Oil and filter changed, tires rotated. Nothing else to report.", status: "sent", sentVia: "sms,email", publicToken: randomBytes(16).toString("hex"), sentAt: hoursAgo(96), expiresAt: days(30) } }),
  2089. prisma.statusReport.create({ data: { organizationId: ORG_ID, serviceRecordId: unassignedRecords[11].id, technicianId: technicians[10].id, title: "Kenworth sleeper A/C - parts on order", message: "The compressor has seized and put debris through the condenser, so both need replacing. Parts land Wednesday and we'll have it back to you Thursday.", status: "draft", publicToken: randomBytes(16).toString("hex") } }),
  2090. ]);
  2091. console.log(` Created ${statusReports.length} status reports`);
  2092. // -- Audit log --
  2093. // Written by the app in normal use; seeded here so the page is not blank.
  2094. console.log("\nCreating audit log entries...");
  2095. const auditEntries: { action: string; entity: string; entityId: string; message: string; day: number; hour: number }[] = [
  2096. { action: "serviceRecord.create", entity: "serviceRecord", entityId: boardServiceRecords[0].id, message: "Created work order \"Honda Civic - AC Compressor\"", day: MONDAY_OFFSET, hour: 7 },
  2097. { action: "serviceRecord.update", entity: "serviceRecord", entityId: boardServiceRecords[6].id, message: "Moved \"CAT 745 - Transmission Rebuild\" to in progress", day: MONDAY_OFFSET, hour: 8 },
  2098. { action: "quote.send", entity: "quote", entityId: quotes[0].id, message: "Sent quote to Sarah Coleman", day: -6, hour: 14 },
  2099. { action: "quote.accept", entity: "quote", entityId: quotes[10].id, message: "Quote accepted by Mike Thompson", day: -2, hour: 11 },
  2100. { action: "payment.create", entity: "serviceRecord", entityId: serviceRecords[4].id, message: "Recorded a payment against the Kenworth engine service", day: -3, hour: 16 },
  2101. { action: "inventoryPart.update", entity: "inventoryPart", entityId: inventoryParts[21].id, message: "Adjusted stock for DPF Pressure Sensor", day: -7, hour: 10 },
  2102. { action: "inspection.complete", entity: "inspection", entityId: inspections[4].id, message: "Completed a periodic technical inspection on the Volvo FH 640", day: wd(-2, 3), hour: 11 },
  2103. { action: "inspection.complete", entity: "inspection", entityId: inspections[7].id, message: "Recorded a dangerous defect on the Mack Granite", day: wd(0, 0), hour: 12 },
  2104. { action: "customer.create", entity: "customer", entityId: customers[19].id, message: "Added customer Lisa Martinez", day: -34, hour: 9 },
  2105. { action: "vehicle.create", entity: "vehicle", entityId: vehicles[41].id, message: "Added vehicle Subaru WRX Premium", day: -34, hour: 9 },
  2106. { action: "reminder.create", entity: "reminder", entityId: coreReminders[0].id, message: "Created reminder \"Annual DOT Inspection\"", day: -30, hour: 15 },
  2107. { action: "scheduledMessage.create", entity: "scheduledMessage", entityId: scheduledMessages[12].id, message: "Scheduled a monthly fleet statement for Summit Construction", day: -24, hour: 8 },
  2108. { action: "settings.update", entity: "appSetting", entityId: ORG_ID, message: "Updated invoice layout settings", day: -12, hour: 13 },
  2109. { action: "laborPreset.create", entity: "laborPreset", entityId: laborPresets[2].id, message: "Created labor preset \"Heavy truck PM service\"", day: -18, hour: 10 },
  2110. { action: "technician.create", entity: "technician", entityId: technicians[9].id, message: "Added technician Daniel Eriksen", day: -60, hour: 9 },
  2111. { action: "user.login", entity: "user", entityId: USER_ID, message: "Signed in", day: 0, hour: 7 },
  2112. ];
  2113. await Promise.all(
  2114. auditEntries.map((e) =>
  2115. prisma.auditLog.create({
  2116. data: {
  2117. organizationId: ORG_ID,
  2118. userId: USER_ID,
  2119. action: e.action,
  2120. entity: e.entity,
  2121. entityId: e.entityId,
  2122. message: e.message,
  2123. timestamp: at(e.day, e.hour),
  2124. ip: "203.0.113.42",
  2125. userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/140.0 Safari/537.36",
  2126. },
  2127. }),
  2128. ),
  2129. );
  2130. console.log(` Created ${auditEntries.length} audit log entries`);
  2131. // -- Summary --
  2132. console.log("\n" + "=".repeat(50));
  2133. console.log("Seed completed!");
  2134. console.log("=".repeat(50));
  2135. console.log(` Seed date: ${TODAY.toDateString()} (board week starts ${weekMonday().toDateString()})`);
  2136. console.log(` Customers: ${customers.length}`);
  2137. console.log(` Vehicles: ${vehicles.length}`);
  2138. console.log(` Service Records: ${serviceRecords.length + boardServiceRecords.length + unassignedRecords.length + predMaintRecords.length + spreadRecords.length}`);
  2139. console.log(` Invoices / paid: ${completed.length} / ${paidFull + paidPartial}`);
  2140. console.log(` Quotes: ${quotes.length}`);
  2141. console.log(` Inventory Parts: ${inventoryParts.length}`);
  2142. console.log(` Stock Movements: ${movementCount}`);
  2143. console.log(` Technicians: ${technicians.length}`);
  2144. console.log(` Unassigned Jobs: ${unassignedRecords.length}`);
  2145. console.log(` Notes: ${9 + additionalNotes.length}`);
  2146. console.log(` Reminders: ${coreReminders.length + additionalReminders.length}`);
  2147. console.log(` Findings: ${findings.length}`);
  2148. console.log(` Inspections: ${inspections.length} (${templates.length} templates)`);
  2149. console.log(` SMS Messages: 22`);
  2150. console.log(` Telegram Messages: ${telegram.length}`);
  2151. console.log(` Scheduled Messages: ${scheduledMessages.length}`);
  2152. console.log(` Notifications: ${notifications.length}`);
  2153. console.log(` Labor Presets: ${laborPresets.length}`);
  2154. console.log(` Report Schedules: ${reportSchedules.length}`);
  2155. console.log(` Recurring Invoices: ${recurring.length}`);
  2156. console.log(` Custom Fields: ${customFields.length}`);
  2157. console.log(` Service Requests: ${serviceRequests.length}`);
  2158. console.log(` Status Reports: ${statusReports.length}`);
  2159. console.log(` Audit Entries: ${auditEntries.length}`);
  2160. console.log("=".repeat(50));
  2161. }
  2162. seed()
  2163. .then(async () => { await prisma.$disconnect(); process.exit(0); })
  2164. .catch(async (e) => { console.error("Seed failed:", e); await prisma.$disconnect(); process.exit(1); });