sampleData.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import { db } from "@/lib/db";
  2. import { resolveInvoicePrefix } from "@/lib/invoice-utils";
  3. import type { SampleDataIds } from "./onboardingKeys";
  4. import type { Translator } from "./onboardingDefaults";
  5. /** The slice of an inspection template the seed copies items from. */
  6. interface TemplateForSeed {
  7. id: string;
  8. severityScale: string;
  9. country: string | null;
  10. sections: {
  11. name: string;
  12. code: string | null;
  13. items: {
  14. name: string;
  15. description: string | null;
  16. code: string | null;
  17. sortOrder: number;
  18. inputType: string;
  19. unit: string | null;
  20. minValue: number | null;
  21. maxValue: number | null;
  22. choices: string[];
  23. required: boolean;
  24. photoRequired: boolean;
  25. defaultSeverity: string | null;
  26. defectSuggestions: string[];
  27. }[];
  28. }[];
  29. }
  30. const daysAgo = (n: number) => {
  31. const d = new Date();
  32. d.setDate(d.getDate() - n);
  33. return d;
  34. };
  35. const daysAhead = (n: number) => daysAgo(-n);
  36. /**
  37. * Seeds a small, clearly-labelled demo dataset for a brand-new organization:
  38. * three customers, four vehicles, three work orders in different states (one
  39. * completed with parts and labor), one sent quote and one inspection in
  40. * progress. Every name carries the translated sample prefix, and every
  41. * created id is returned so removal can delete exactly this set.
  42. *
  43. * Invoice and quote numbers follow the same default numbering the real
  44. * actions use, so real records created afterwards simply continue the
  45. * sequence.
  46. */
  47. export async function seedSampleData(
  48. organizationId: string,
  49. userId: string,
  50. t: Translator,
  51. template: TemplateForSeed
  52. ): Promise<SampleDataIds> {
  53. const prefix = t("sample.prefix");
  54. const label = (name: string) => `${prefix} ${name}`;
  55. const invoicePrefix = resolveInvoicePrefix("{year}-");
  56. const hourlyRate = 95;
  57. return db.$transaction(async (tx) => {
  58. // ── Customers ────────────────────────────────────────────────────────
  59. const anna = await tx.customer.create({
  60. data: {
  61. name: label("Anna Bergström"),
  62. customerNumber: "1",
  63. email: "anna.sample@example.com",
  64. phone: "+1 555 0101",
  65. userId,
  66. organizationId,
  67. },
  68. });
  69. const marco = await tx.customer.create({
  70. data: {
  71. name: label("Marco Rossi"),
  72. customerNumber: "2",
  73. email: "marco.sample@example.com",
  74. phone: "+1 555 0102",
  75. userId,
  76. organizationId,
  77. },
  78. });
  79. const nordvik = await tx.customer.create({
  80. data: {
  81. name: label("Nordvik Logistics"),
  82. customerNumber: "3",
  83. company: label("Nordvik Logistics"),
  84. email: "fleet.sample@example.com",
  85. phone: "+1 555 0103",
  86. userId,
  87. organizationId,
  88. },
  89. });
  90. // ── Vehicles ─────────────────────────────────────────────────────────
  91. const golf = await tx.vehicle.create({
  92. data: {
  93. make: "Volkswagen",
  94. model: "Golf",
  95. year: 2018,
  96. licensePlate: "SAMPLE-1",
  97. mileage: 86500,
  98. fuelType: "gasoline",
  99. customerId: anna.id,
  100. userId,
  101. organizationId,
  102. },
  103. });
  104. const rav4 = await tx.vehicle.create({
  105. data: {
  106. make: "Toyota",
  107. model: "RAV4",
  108. year: 2020,
  109. licensePlate: "SAMPLE-2",
  110. mileage: 45200,
  111. fuelType: "hybrid",
  112. customerId: marco.id,
  113. userId,
  114. organizationId,
  115. },
  116. });
  117. const transit = await tx.vehicle.create({
  118. data: {
  119. make: "Ford",
  120. model: "Transit",
  121. year: 2016,
  122. licensePlate: "SAMPLE-3",
  123. mileage: 158000,
  124. fuelType: "diesel",
  125. customerId: nordvik.id,
  126. userId,
  127. organizationId,
  128. },
  129. });
  130. const bmw = await tx.vehicle.create({
  131. data: {
  132. make: "BMW",
  133. model: "320d",
  134. year: 2019,
  135. licensePlate: "SAMPLE-4",
  136. mileage: 98400,
  137. fuelType: "diesel",
  138. customerId: anna.id,
  139. userId,
  140. organizationId,
  141. },
  142. });
  143. // ── Work orders ──────────────────────────────────────────────────────
  144. // Completed job with parts + labor, invoiced and paid.
  145. const oilParts = [
  146. { name: t("sample.parts.oilFilter"), quantity: 1, unitPrice: 14.9, total: 14.9 },
  147. { name: t("sample.parts.engineOil"), quantity: 4, unitPrice: 11.5, total: 46 },
  148. ];
  149. const oilLaborTotal = 0.8 * hourlyRate;
  150. const oilSubtotal =
  151. oilParts.reduce((sum, p) => sum + p.total, 0) + oilLaborTotal;
  152. const oilJob = await tx.serviceRecord.create({
  153. data: {
  154. title: label(t("sample.oilService")),
  155. type: "maintenance",
  156. status: "completed",
  157. mileage: 86200,
  158. serviceDate: daysAgo(12),
  159. invoiceDate: daysAgo(12),
  160. invoiceNumber: `${invoicePrefix}1001`,
  161. subtotal: oilSubtotal,
  162. totalAmount: oilSubtotal,
  163. cost: oilSubtotal,
  164. manuallyPaid: true,
  165. vehicleId: golf.id,
  166. organizationId,
  167. partItems: { create: oilParts },
  168. laborItems: {
  169. create: [
  170. {
  171. description: t("sample.oilService"),
  172. hours: 0.8,
  173. rate: hourlyRate,
  174. total: oilLaborTotal,
  175. pricingType: "hourly",
  176. },
  177. ],
  178. },
  179. },
  180. });
  181. // Job on the lift right now.
  182. const brakeLaborTotal = 1.5 * hourlyRate;
  183. const brakeSubtotal = 62 + brakeLaborTotal;
  184. const brakeJob = await tx.serviceRecord.create({
  185. data: {
  186. title: label(t("sample.brakeJob")),
  187. type: "repair",
  188. status: "in-progress",
  189. mileage: 45200,
  190. serviceDate: new Date(),
  191. startDateTime: new Date(),
  192. invoiceNumber: `${invoicePrefix}1002`,
  193. subtotal: brakeSubtotal,
  194. totalAmount: brakeSubtotal,
  195. cost: brakeSubtotal,
  196. vehicleId: rav4.id,
  197. organizationId,
  198. partItems: {
  199. create: [
  200. {
  201. name: t("sample.parts.brakePads"),
  202. quantity: 1,
  203. unitPrice: 62,
  204. total: 62,
  205. },
  206. ],
  207. },
  208. laborItems: {
  209. create: [
  210. {
  211. description: t("sample.brakeJob"),
  212. hours: 1.5,
  213. rate: hourlyRate,
  214. total: brakeLaborTotal,
  215. pricingType: "hourly",
  216. },
  217. ],
  218. },
  219. },
  220. });
  221. // Booked but not started.
  222. const annualJob = await tx.serviceRecord.create({
  223. data: {
  224. title: label(t("sample.annualService")),
  225. type: "maintenance",
  226. status: "pending",
  227. serviceDate: daysAhead(3),
  228. startDateTime: daysAhead(3),
  229. invoiceNumber: `${invoicePrefix}1003`,
  230. vehicleId: transit.id,
  231. organizationId,
  232. },
  233. });
  234. // ── Quote ────────────────────────────────────────────────────────────
  235. const quoteLaborTotal = 2 * hourlyRate;
  236. const quoteSubtotal = 178 + quoteLaborTotal;
  237. const quote = await tx.quote.create({
  238. data: {
  239. quoteNumber: "QT-1001",
  240. title: label(t("sample.quoteTitle")),
  241. status: "sent",
  242. validUntil: daysAhead(30),
  243. subtotal: quoteSubtotal,
  244. totalAmount: quoteSubtotal,
  245. customerId: anna.id,
  246. vehicleId: bmw.id,
  247. userId,
  248. organizationId,
  249. partItems: {
  250. create: [
  251. {
  252. name: t("sample.parts.shockAbsorber"),
  253. quantity: 2,
  254. unitPrice: 89,
  255. total: 178,
  256. },
  257. ],
  258. },
  259. laborItems: {
  260. create: [
  261. {
  262. description: t("sample.quoteTitle"),
  263. hours: 2,
  264. rate: hourlyRate,
  265. total: quoteLaborTotal,
  266. pricingType: "hourly",
  267. },
  268. ],
  269. },
  270. },
  271. });
  272. // ── Inspection ───────────────────────────────────────────────────────
  273. // Items are copied from the installed default template exactly like
  274. // createInspection does; the first few carry results so the inspection
  275. // screen shows what a partially-done checklist looks like.
  276. const inspection = await tx.inspection.create({
  277. data: {
  278. status: "in_progress",
  279. mileage: 86500,
  280. severityScale: template.severityScale,
  281. country: template.country,
  282. vehicleId: golf.id,
  283. templateId: template.id,
  284. organizationId,
  285. },
  286. });
  287. let inspected = 0;
  288. const items = template.sections.flatMap((section, sIdx) =>
  289. section.items.map((item) => {
  290. // Grade the first handful of plain condition checks, leave the rest
  291. // untouched; one gets flagged so the attention state is visible too.
  292. let condition = "not_inspected";
  293. let notes: string | null = null;
  294. if (item.inputType === "condition" && inspected < 5) {
  295. inspected += 1;
  296. if (inspected === 4) {
  297. condition = "attention";
  298. notes = t("sample.inspectionNote");
  299. } else {
  300. condition = "pass";
  301. }
  302. }
  303. return {
  304. name: item.name,
  305. section: section.name,
  306. sectionCode: section.code,
  307. description: item.description,
  308. code: item.code,
  309. sortOrder: sIdx * 1000 + item.sortOrder,
  310. inputType: item.inputType,
  311. unit: item.unit,
  312. minValue: item.minValue,
  313. maxValue: item.maxValue,
  314. choices: item.choices,
  315. required: item.required,
  316. photoRequired: item.photoRequired,
  317. defaultSeverity: item.defaultSeverity,
  318. defectSuggestions: item.defectSuggestions,
  319. condition,
  320. notes,
  321. inspectionId: inspection.id,
  322. };
  323. })
  324. );
  325. if (items.length > 0) {
  326. await tx.inspectionItem.createMany({ data: items });
  327. }
  328. return {
  329. customers: [anna.id, marco.id, nordvik.id],
  330. vehicles: [golf.id, rav4.id, transit.id, bmw.id],
  331. serviceRecords: [oilJob.id, brakeJob.id, annualJob.id],
  332. quotes: [quote.id],
  333. inspections: [inspection.id],
  334. };
  335. });
  336. }