@omersx/bemms 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (335) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +203 -2
  3. package/drizzle.config.ts +11 -0
  4. package/next.config.ts +51 -0
  5. package/package.json +99 -3
  6. package/postcss.config.mjs +7 -0
  7. package/public/hospital_demo_devices.csv +32 -0
  8. package/public/icons/icon-192.png +0 -0
  9. package/public/icons/icon-512.png +0 -0
  10. package/public/icons/icon-maskable-512.png +0 -0
  11. package/public/manifest.webmanifest +31 -0
  12. package/public/sw.js +177 -0
  13. package/src/app/(auth)/layout.tsx +20 -0
  14. package/src/app/(auth)/login/page.tsx +135 -0
  15. package/src/app/(dashboard)/admin/audit-logs/page.tsx +178 -0
  16. package/src/app/(dashboard)/admin/data/page.tsx +37 -0
  17. package/src/app/(dashboard)/admin/departments/[deptId]/edit/page.tsx +206 -0
  18. package/src/app/(dashboard)/admin/departments/[deptId]/page.tsx +71 -0
  19. package/src/app/(dashboard)/admin/departments/new/page.tsx +6 -0
  20. package/src/app/(dashboard)/admin/departments/page.tsx +6 -0
  21. package/src/app/(dashboard)/admin/general/page.tsx +374 -0
  22. package/src/app/(dashboard)/admin/hospitals/[hospitalId]/edit/page.tsx +304 -0
  23. package/src/app/(dashboard)/admin/hospitals/[hospitalId]/page.tsx +94 -0
  24. package/src/app/(dashboard)/admin/hospitals/new/page.tsx +302 -0
  25. package/src/app/(dashboard)/admin/hospitals/page.tsx +6 -0
  26. package/src/app/(dashboard)/admin/layout.tsx +49 -0
  27. package/src/app/(dashboard)/admin/organizations/[orgId]/edit/page.tsx +172 -0
  28. package/src/app/(dashboard)/admin/organizations/[orgId]/page.tsx +82 -0
  29. package/src/app/(dashboard)/admin/organizations/new/page.tsx +150 -0
  30. package/src/app/(dashboard)/admin/organizations/page.tsx +6 -0
  31. package/src/app/(dashboard)/admin/page.tsx +258 -0
  32. package/src/app/(dashboard)/admin/roles/page.tsx +153 -0
  33. package/src/app/(dashboard)/admin/settings/page.tsx +69 -0
  34. package/src/app/(dashboard)/admin/users/[userId]/edit/page.tsx +153 -0
  35. package/src/app/(dashboard)/admin/users/[userId]/page.tsx +317 -0
  36. package/src/app/(dashboard)/admin/users/invite/page.tsx +3 -0
  37. package/src/app/(dashboard)/admin/users/new/page.tsx +5 -0
  38. package/src/app/(dashboard)/admin/users/page.tsx +23 -0
  39. package/src/app/(dashboard)/dashboard/page.tsx +462 -0
  40. package/src/app/(dashboard)/departments/[deptId]/page.tsx +39 -0
  41. package/src/app/(dashboard)/departments/new/page.tsx +330 -0
  42. package/src/app/(dashboard)/departments/page.tsx +52 -0
  43. package/src/app/(dashboard)/devices/[id]/edit/page.tsx +131 -0
  44. package/src/app/(dashboard)/devices/[id]/page.tsx +408 -0
  45. package/src/app/(dashboard)/devices/[id]/qr/page.tsx +54 -0
  46. package/src/app/(dashboard)/devices/new/page.tsx +382 -0
  47. package/src/app/(dashboard)/devices/page.tsx +80 -0
  48. package/src/app/(dashboard)/engineering-team/page.tsx +41 -0
  49. package/src/app/(dashboard)/layout.tsx +43 -0
  50. package/src/app/(dashboard)/maintenance/checklists/page.tsx +57 -0
  51. package/src/app/(dashboard)/maintenance/page.tsx +231 -0
  52. package/src/app/(dashboard)/maintenance/plans/page.tsx +142 -0
  53. package/src/app/(dashboard)/maintenance/tasks/[id]/page.tsx +997 -0
  54. package/src/app/(dashboard)/maintenance/tasks/page.tsx +119 -0
  55. package/src/app/(dashboard)/more/page.tsx +310 -0
  56. package/src/app/(dashboard)/my-department/page.tsx +151 -0
  57. package/src/app/(dashboard)/notifications/notification-list.tsx +103 -0
  58. package/src/app/(dashboard)/notifications/page.tsx +59 -0
  59. package/src/app/(dashboard)/profile/page.tsx +27 -0
  60. package/src/app/(dashboard)/reports/costs/page.tsx +127 -0
  61. package/src/app/(dashboard)/reports/history/page.tsx +105 -0
  62. package/src/app/(dashboard)/reports/inventory/page.tsx +116 -0
  63. package/src/app/(dashboard)/reports/maintenance/page.tsx +136 -0
  64. package/src/app/(dashboard)/reports/page.tsx +120 -0
  65. package/src/app/(dashboard)/reports/tickets/page.tsx +139 -0
  66. package/src/app/(dashboard)/reports/workload/page.tsx +135 -0
  67. package/src/app/(dashboard)/rounds/[id]/page.tsx +197 -0
  68. package/src/app/(dashboard)/rounds/history/page.tsx +82 -0
  69. package/src/app/(dashboard)/rounds/page.tsx +107 -0
  70. package/src/app/(dashboard)/scan/[code]/page.tsx +154 -0
  71. package/src/app/(dashboard)/scan/page.tsx +73 -0
  72. package/src/app/(dashboard)/team/page.tsx +42 -0
  73. package/src/app/(dashboard)/tickets/[id]/page.tsx +465 -0
  74. package/src/app/(dashboard)/tickets/create/page.tsx +722 -0
  75. package/src/app/(dashboard)/tickets/page.tsx +55 -0
  76. package/src/app/(dashboard)/tickets/triage/page.tsx +161 -0
  77. package/src/app/api/admin/data/export/route.ts +316 -0
  78. package/src/app/api/auth/[...nextauth]/route.ts +3 -0
  79. package/src/app/api/health/route.ts +46 -0
  80. package/src/app/api/notifications/sse/route.ts +91 -0
  81. package/src/app/api/notifications/subscribe/route.ts +54 -0
  82. package/src/app/api/notifications/vapid-key/route.ts +7 -0
  83. package/src/app/api/reports/export/route.ts +102 -0
  84. package/src/app/api/tickets/[id]/attachments/route.ts +129 -0
  85. package/src/app/api/tickets/[id]/live-sync/route.ts +52 -0
  86. package/src/app/error.tsx +54 -0
  87. package/src/app/globals.css +89 -0
  88. package/src/app/layout.tsx +59 -0
  89. package/src/app/not-found.tsx +32 -0
  90. package/src/app/page.tsx +5 -0
  91. package/src/components/admin/add-department-user-dialog.tsx +759 -0
  92. package/src/components/admin/add-engineer-dialog.tsx +773 -0
  93. package/src/components/admin/add-user-type-dialog.tsx +89 -0
  94. package/src/components/admin/audit-log-export.tsx +113 -0
  95. package/src/components/admin/audit-log-filters.tsx +255 -0
  96. package/src/components/admin/audit-log-table.tsx +383 -0
  97. package/src/components/admin/data-management/danger-zone.tsx +301 -0
  98. package/src/components/admin/data-management/data-management-tabs.tsx +61 -0
  99. package/src/components/admin/data-management/export-center.tsx +301 -0
  100. package/src/components/admin/data-management/import-wizard.tsx +558 -0
  101. package/src/components/admin/settings-forms/features-form.tsx +115 -0
  102. package/src/components/admin/settings-forms/health-panel.tsx +182 -0
  103. package/src/components/admin/settings-forms/localization-form.tsx +203 -0
  104. package/src/components/admin/settings-forms/retention-form.tsx +164 -0
  105. package/src/components/admin/settings-forms/security-form.tsx +186 -0
  106. package/src/components/admin/system-settings-tabs.tsx +88 -0
  107. package/src/components/admin/user-role-dialog.tsx +293 -0
  108. package/src/components/admin/user-status-dialog.tsx +166 -0
  109. package/src/components/admin/users-page-client.tsx +514 -0
  110. package/src/components/dashboard/action-buttons.tsx +93 -0
  111. package/src/components/dashboard/admin-alerts.tsx +86 -0
  112. package/src/components/dashboard/availability-alerts.tsx +65 -0
  113. package/src/components/dashboard/maintenance-due-list.tsx +87 -0
  114. package/src/components/dashboard/round-widget.tsx +110 -0
  115. package/src/components/dashboard/stat-card.tsx +38 -0
  116. package/src/components/dashboard/ticket-list-compact.tsx +86 -0
  117. package/src/components/departments/department-cards-view.tsx +244 -0
  118. package/src/components/departments/department-detail-view.tsx +467 -0
  119. package/src/components/departments/department-visuals.tsx +190 -0
  120. package/src/components/departments/my-department-view.tsx +333 -0
  121. package/src/components/devices/change-status-dialog.tsx +146 -0
  122. package/src/components/devices/device-action-buttons.tsx +125 -0
  123. package/src/components/devices/device-availability-banner.tsx +59 -0
  124. package/src/components/devices/device-badges.tsx +55 -0
  125. package/src/components/devices/device-documents-tab.tsx +93 -0
  126. package/src/components/devices/device-maintenance-tab.tsx +113 -0
  127. package/src/components/devices/device-mini-qr.tsx +109 -0
  128. package/src/components/devices/device-qr-card.tsx +187 -0
  129. package/src/components/devices/device-signatures-tab.tsx +607 -0
  130. package/src/components/devices/device-tickets-tab.tsx +139 -0
  131. package/src/components/devices/device-timelines.tsx +124 -0
  132. package/src/components/devices/qr-camera-scanner.tsx +167 -0
  133. package/src/components/devices/qr-code-display.tsx +139 -0
  134. package/src/components/devices/quick-add-category-dialog.tsx +135 -0
  135. package/src/components/devices/quick-add-manufacturer-dialog.tsx +212 -0
  136. package/src/components/devices/transfer-device-dialog.tsx +190 -0
  137. package/src/components/layout/header.tsx +80 -0
  138. package/src/components/layout/mobile-nav.tsx +91 -0
  139. package/src/components/layout/more-item-badge.tsx +15 -0
  140. package/src/components/layout/nav-badge.tsx +72 -0
  141. package/src/components/layout/sidebar.tsx +297 -0
  142. package/src/components/maintenance/maintenance-badges.tsx +579 -0
  143. package/src/components/maintenance/maintenance-nav.tsx +107 -0
  144. package/src/components/maintenance/parts-costs-manager.tsx +909 -0
  145. package/src/components/maintenance/signature-card.tsx +413 -0
  146. package/src/components/maintenance/task-action-bar.tsx +955 -0
  147. package/src/components/notifications/notification-bell.tsx +367 -0
  148. package/src/components/notifications/notification-item.tsx +93 -0
  149. package/src/components/notifications/notification-preferences.tsx +182 -0
  150. package/src/components/profile/user-profile-view.tsx +626 -0
  151. package/src/components/providers/nav-counts-provider.tsx +235 -0
  152. package/src/components/providers/session-provider.tsx +7 -0
  153. package/src/components/providers/theme-provider.tsx +124 -0
  154. package/src/components/pwa/install-prompt.tsx +82 -0
  155. package/src/components/pwa/sw-register.tsx +43 -0
  156. package/src/components/reports/export-button.tsx +62 -0
  157. package/src/components/reports/filter-chips.tsx +47 -0
  158. package/src/components/reports/summary-cards.tsx +40 -0
  159. package/src/components/reports/transparency-header.tsx +54 -0
  160. package/src/components/rounds/department-visit-sheet.tsx +199 -0
  161. package/src/components/rounds/mention-textarea.tsx +187 -0
  162. package/src/components/rounds/round-calendar.tsx +233 -0
  163. package/src/components/rounds/round-department-list.tsx +281 -0
  164. package/src/components/rounds/round-history-client.tsx +218 -0
  165. package/src/components/rounds/start-round-card.tsx +184 -0
  166. package/src/components/shared/confirm-dialog.tsx +67 -0
  167. package/src/components/shared/data-table.tsx +104 -0
  168. package/src/components/shared/page-header.tsx +20 -0
  169. package/src/components/shared/sign-out-button.tsx +52 -0
  170. package/src/components/shared/status-badge.tsx +42 -0
  171. package/src/components/shared/table-search.tsx +55 -0
  172. package/src/components/signatures/sign-action-dialog.tsx +253 -0
  173. package/src/components/signatures/signature-history.tsx +121 -0
  174. package/src/components/signatures/signature-status-panel.tsx +164 -0
  175. package/src/components/team/department-coverage.tsx +141 -0
  176. package/src/components/team/edit-engineer-dialog.tsx +242 -0
  177. package/src/components/team/engineer-card.tsx +180 -0
  178. package/src/components/team/engineer-details-dialog.tsx +432 -0
  179. package/src/components/team/schedule-calendar.tsx +204 -0
  180. package/src/components/team/staff-engineer-team-view.tsx +368 -0
  181. package/src/components/team/team-header-stats.tsx +88 -0
  182. package/src/components/team/team-page-client.tsx +216 -0
  183. package/src/components/theme/theme-selector-card.tsx +63 -0
  184. package/src/components/theme/theme-toggle.tsx +65 -0
  185. package/src/components/tickets/staff-status-label.tsx +58 -0
  186. package/src/components/tickets/staff-ticket-card.tsx +109 -0
  187. package/src/components/tickets/staff-ticket-progress-tracker.tsx +405 -0
  188. package/src/components/tickets/staff-tickets-view.tsx +182 -0
  189. package/src/components/tickets/ticket-action-buttons.tsx +873 -0
  190. package/src/components/tickets/ticket-auto-refresh.tsx +197 -0
  191. package/src/components/tickets/ticket-badges.tsx +43 -0
  192. package/src/components/tickets/ticket-card.tsx +197 -0
  193. package/src/components/tickets/ticket-cards-view.tsx +395 -0
  194. package/src/components/tickets/ticket-comment-section.tsx +684 -0
  195. package/src/components/tickets/ticket-dispatch-status.tsx +184 -0
  196. package/src/components/tickets/ticket-list-auto-refresh.tsx +55 -0
  197. package/src/components/tickets/ticket-reporter-profile.tsx +235 -0
  198. package/src/components/tickets/ticket-signatures-panel.tsx +32 -0
  199. package/src/components/tickets/ticket-timeline.tsx +131 -0
  200. package/src/components/tickets/ticket-triage-panel.tsx +124 -0
  201. package/src/components/tickets/tickets-nav.tsx +107 -0
  202. package/src/components/ui/avatar.tsx +43 -0
  203. package/src/components/ui/badge.tsx +34 -0
  204. package/src/components/ui/button.tsx +58 -0
  205. package/src/components/ui/card.tsx +77 -0
  206. package/src/components/ui/checkbox.tsx +31 -0
  207. package/src/components/ui/dialog.tsx +123 -0
  208. package/src/components/ui/dropdown-menu.tsx +126 -0
  209. package/src/components/ui/form.tsx +179 -0
  210. package/src/components/ui/input.tsx +24 -0
  211. package/src/components/ui/label.tsx +27 -0
  212. package/src/components/ui/popover.tsx +34 -0
  213. package/src/components/ui/progress.tsx +36 -0
  214. package/src/components/ui/scroll-area.tsx +47 -0
  215. package/src/components/ui/select.tsx +160 -0
  216. package/src/components/ui/separator.tsx +25 -0
  217. package/src/components/ui/sheet.tsx +131 -0
  218. package/src/components/ui/switch.tsx +30 -0
  219. package/src/components/ui/table.tsx +121 -0
  220. package/src/components/ui/tabs.tsx +62 -0
  221. package/src/components/ui/textarea.tsx +23 -0
  222. package/src/components/ui/tooltip.tsx +27 -0
  223. package/src/lib/actions/__tests__/devices.test.ts +176 -0
  224. package/src/lib/actions/__tests__/signatures.test.ts +303 -0
  225. package/src/lib/actions/__tests__/tickets.test.ts +243 -0
  226. package/src/lib/actions/audit-logs.ts +298 -0
  227. package/src/lib/actions/checklists.ts +429 -0
  228. package/src/lib/actions/dashboard.ts +358 -0
  229. package/src/lib/actions/data-management.ts +723 -0
  230. package/src/lib/actions/departments.ts +369 -0
  231. package/src/lib/actions/device-categories.ts +117 -0
  232. package/src/lib/actions/devices.ts +748 -0
  233. package/src/lib/actions/engineer-rounds.ts +973 -0
  234. package/src/lib/actions/engineers.ts +285 -0
  235. package/src/lib/actions/hospitals.ts +148 -0
  236. package/src/lib/actions/locations.ts +115 -0
  237. package/src/lib/actions/maintenance-plans.ts +316 -0
  238. package/src/lib/actions/maintenance-tasks.ts +415 -0
  239. package/src/lib/actions/manufacturers.ts +132 -0
  240. package/src/lib/actions/nav-counts.ts +144 -0
  241. package/src/lib/actions/notifications.ts +136 -0
  242. package/src/lib/actions/organizations.ts +99 -0
  243. package/src/lib/actions/qr.ts +147 -0
  244. package/src/lib/actions/report-history.ts +77 -0
  245. package/src/lib/actions/reports.ts +192 -0
  246. package/src/lib/actions/roles.ts +32 -0
  247. package/src/lib/actions/signature-auth.ts +377 -0
  248. package/src/lib/actions/signatures.ts +532 -0
  249. package/src/lib/actions/system-settings.ts +274 -0
  250. package/src/lib/actions/tickets.ts +1445 -0
  251. package/src/lib/actions/users.ts +740 -0
  252. package/src/lib/audit/index.ts +103 -0
  253. package/src/lib/auth/__tests__/rbac.test.ts +33 -0
  254. package/src/lib/auth/index.ts +338 -0
  255. package/src/lib/auth/password.ts +10 -0
  256. package/src/lib/auth/rbac.ts +103 -0
  257. package/src/lib/auth/types.ts +57 -0
  258. package/src/lib/constants/departments.ts +16 -0
  259. package/src/lib/constants/manufacturers.ts +32 -0
  260. package/src/lib/db/index.ts +23 -0
  261. package/src/lib/db/schema/audit-logs.ts +42 -0
  262. package/src/lib/db/schema/departments.ts +39 -0
  263. package/src/lib/db/schema/device-categories.ts +38 -0
  264. package/src/lib/db/schema/devices.ts +195 -0
  265. package/src/lib/db/schema/engineer-profiles.ts +63 -0
  266. package/src/lib/db/schema/engineer-rounds.ts +115 -0
  267. package/src/lib/db/schema/enums.ts +148 -0
  268. package/src/lib/db/schema/hospitals.ts +34 -0
  269. package/src/lib/db/schema/index.ts +24 -0
  270. package/src/lib/db/schema/locations.ts +46 -0
  271. package/src/lib/db/schema/maintenance-plans.ts +99 -0
  272. package/src/lib/db/schema/maintenance-records.ts +161 -0
  273. package/src/lib/db/schema/maintenance-tasks.ts +196 -0
  274. package/src/lib/db/schema/manufacturers.ts +60 -0
  275. package/src/lib/db/schema/notifications.ts +48 -0
  276. package/src/lib/db/schema/organizations.ts +24 -0
  277. package/src/lib/db/schema/report-history.ts +28 -0
  278. package/src/lib/db/schema/roles.ts +59 -0
  279. package/src/lib/db/schema/sessions.ts +46 -0
  280. package/src/lib/db/schema/signature-events.ts +48 -0
  281. package/src/lib/db/schema/signature-policies.ts +60 -0
  282. package/src/lib/db/schema/signatures.ts +87 -0
  283. package/src/lib/db/schema/tickets.ts +169 -0
  284. package/src/lib/db/schema/user-assignments.ts +85 -0
  285. package/src/lib/db/schema/users.ts +39 -0
  286. package/src/lib/db/seed.ts +131 -0
  287. package/src/lib/logger/__tests__/logger.test.ts +154 -0
  288. package/src/lib/logger/formatters.ts +159 -0
  289. package/src/lib/logger/index.ts +184 -0
  290. package/src/lib/logger/types.ts +48 -0
  291. package/src/lib/notifications/create.ts +71 -0
  292. package/src/lib/notifications/dispatcher.ts +490 -0
  293. package/src/lib/notifications/index.ts +7 -0
  294. package/src/lib/notifications/push-sender.ts +128 -0
  295. package/src/lib/notifications/push.ts +64 -0
  296. package/src/lib/notifications/triggers.ts +166 -0
  297. package/src/lib/utils/__tests__/crypto.test.ts +30 -0
  298. package/src/lib/utils/__tests__/export.test.ts +55 -0
  299. package/src/lib/utils/__tests__/nav-badge.test.ts +147 -0
  300. package/src/lib/utils/__tests__/staff-status.test.ts +50 -0
  301. package/src/lib/utils/attestations.ts +19 -0
  302. package/src/lib/utils/crypto.ts +18 -0
  303. package/src/lib/utils/csv-parser.ts +181 -0
  304. package/src/lib/utils/export.ts +45 -0
  305. package/src/lib/utils/nav-badge.ts +225 -0
  306. package/src/lib/utils/sound.ts +152 -0
  307. package/src/lib/utils/staff-status.ts +115 -0
  308. package/src/lib/utils.ts +6 -0
  309. package/src/lib/validators/__tests__/auth.test.ts +127 -0
  310. package/src/lib/validators/__tests__/data-management.test.ts +182 -0
  311. package/src/lib/validators/__tests__/devices-profile.test.ts +129 -0
  312. package/src/lib/validators/__tests__/devices.test.ts +98 -0
  313. package/src/lib/validators/__tests__/engineer-rounds.test.ts +170 -0
  314. package/src/lib/validators/__tests__/maintenance.test.ts +178 -0
  315. package/src/lib/validators/__tests__/signatures.test.ts +154 -0
  316. package/src/lib/validators/__tests__/system-settings.test.ts +119 -0
  317. package/src/lib/validators/__tests__/tickets.test.ts +176 -0
  318. package/src/lib/validators/__tests__/users.test.ts +92 -0
  319. package/src/lib/validators/auth.ts +32 -0
  320. package/src/lib/validators/data-management.ts +67 -0
  321. package/src/lib/validators/departments.ts +14 -0
  322. package/src/lib/validators/devices.ts +94 -0
  323. package/src/lib/validators/engineer-rounds.ts +70 -0
  324. package/src/lib/validators/hospitals.ts +17 -0
  325. package/src/lib/validators/locations.ts +15 -0
  326. package/src/lib/validators/maintenance.ts +211 -0
  327. package/src/lib/validators/organizations.ts +11 -0
  328. package/src/lib/validators/reports.ts +31 -0
  329. package/src/lib/validators/signatures.ts +49 -0
  330. package/src/lib/validators/system-settings.ts +55 -0
  331. package/src/lib/validators/tickets.ts +125 -0
  332. package/src/lib/validators/users.ts +43 -0
  333. package/src/middleware.ts +45 -0
  334. package/tailwind.config.ts +76 -0
  335. package/tsconfig.json +28 -0
@@ -0,0 +1,32 @@
1
+ export interface DefaultManufacturerTemplate {
2
+ name: string;
3
+ code: string;
4
+ country: string;
5
+ website?: string;
6
+ }
7
+
8
+ export const DEFAULT_MANUFACTURERS: DefaultManufacturerTemplate[] = [
9
+ { name: 'B. Braun', code: 'BBRAUN', country: 'Germany', website: 'https://www.bbraun.com' },
10
+ { name: 'Baxter International', code: 'BAXTER', country: 'United States', website: 'https://www.baxter.com' },
11
+ { name: 'Beckman Coulter', code: 'BECKMAN', country: 'United States', website: 'https://www.beckmancoulter.com' },
12
+ { name: 'Canon Medical Systems', code: 'CANON', country: 'Japan', website: 'https://global.medical.canon' },
13
+ { name: 'Dentsply Sirona', code: 'SIRONA', country: 'United States', website: 'https://www.dentsplysirona.com' },
14
+ { name: 'Dräger (Draeger)', code: 'DRAEGER', country: 'Germany', website: 'https://www.draeger.com' },
15
+ { name: 'Fresenius Medical Care', code: 'FRESENIUS', country: 'Germany', website: 'https://www.freseniusmedicalcare.com' },
16
+ { name: 'Fujifilm Healthcare', code: 'FUJIFILM', country: 'Japan', website: 'https://healthcaresolutions-us.fujifilm.com' },
17
+ { name: 'GE HealthCare', code: 'GE', country: 'United States', website: 'https://www.gehealthcare.com' },
18
+ { name: 'Getinge / Maquet', code: 'GETINGE', country: 'Sweden', website: 'https://www.getinge.com' },
19
+ { name: 'Hamilton Medical', code: 'HAMILTON', country: 'Switzerland', website: 'https://www.hamilton-medical.com' },
20
+ { name: 'Medtronic', code: 'MEDTRONIC', country: 'United States', website: 'https://www.medtronic.com' },
21
+ { name: 'Mindray', code: 'MINDRAY', country: 'China', website: 'https://www.mindray.com' },
22
+ { name: 'Nihon Kohden', code: 'NIHON_KOHDEN', country: 'Japan', website: 'https://www.nihonkohden.com' },
23
+ { name: 'Olympus', code: 'OLYMPUS', country: 'Japan', website: 'https://www.olympus-global.com' },
24
+ { name: 'Philips Healthcare', code: 'PHILIPS', country: 'Netherlands', website: 'https://www.philips.com/healthcare' },
25
+ { name: 'Planmeca', code: 'PLANMECA', country: 'Finland', website: 'https://www.planmeca.com' },
26
+ { name: 'Roche Diagnostics', code: 'ROCHE', country: 'Switzerland', website: 'https://diagnostics.roche.com' },
27
+ { name: 'Schiller', code: 'SCHILLER', country: 'Switzerland', website: 'https://www.schiller.ch' },
28
+ { name: 'Siemens Healthineers', code: 'SIEMENS', country: 'Germany', website: 'https://www.siemens-healthineers.com' },
29
+ { name: 'Stryker', code: 'STRYKER', country: 'United States', website: 'https://www.stryker.com' },
30
+ { name: 'Zoll Medical', code: 'ZOLL', country: 'United States', website: 'https://www.zoll.com' },
31
+ ];
32
+
@@ -0,0 +1,23 @@
1
+ import { Pool } from 'pg';
2
+ import { drizzle } from 'drizzle-orm/node-postgres';
3
+ import * as schema from './schema';
4
+ import { getLogger } from '@/lib/logger';
5
+
6
+ const log = getLogger('db');
7
+
8
+ const pool = new Pool({
9
+ connectionString: process.env.DATABASE_URL,
10
+ max: parseInt(process.env.DB_POOL_MAX || '20', 10),
11
+ idleTimeoutMillis: 30000,
12
+ connectionTimeoutMillis: 5000,
13
+ ...(process.env.NODE_ENV === 'production' && process.env.DB_SSL !== 'false'
14
+ ? { ssl: { rejectUnauthorized: false } }
15
+ : {}),
16
+ });
17
+
18
+ // Handle unexpected pool errors to prevent crashes
19
+ pool.on('error', (err) => {
20
+ log.error('Unexpected database pool error', err);
21
+ });
22
+
23
+ export const db = drizzle(pool, { schema });
@@ -0,0 +1,42 @@
1
+ import { pgTable, bigserial, text, timestamp, jsonb, uuid, index } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { auditActionTypeEnum } from './enums';
4
+ import { users } from './users';
5
+ import { organizations } from './organizations';
6
+ import { hospitals } from './hospitals';
7
+
8
+ export const auditLogs = pgTable('audit_logs', {
9
+ id: bigserial('id', { mode: 'bigint' }).primaryKey(),
10
+ timestamp: timestamp('timestamp', { withTimezone: true }).defaultNow().notNull(),
11
+ actorUserId: uuid('actor_user_id'),
12
+ organizationId: uuid('organization_id'),
13
+ hospitalId: uuid('hospital_id'),
14
+ entityType: text('entity_type').notNull(),
15
+ entityId: text('entity_id').notNull(),
16
+ actionType: auditActionTypeEnum('action_type').notNull(),
17
+ previousState: jsonb('previous_state'),
18
+ newState: jsonb('new_state'),
19
+ changeReason: text('change_reason'),
20
+ ipAddress: text('ip_address'),
21
+ sessionId: text('session_id'),
22
+ }, (t) => ({
23
+ orgTimeIdx: index('audit_org_time_idx').on(t.organizationId, t.timestamp),
24
+ entityIdx: index('audit_entity_idx').on(t.entityType, t.entityId),
25
+ actorTimeIdx: index('audit_actor_time_idx').on(t.actorUserId, t.timestamp),
26
+ }));
27
+
28
+ export const auditLogsRelations = relations(auditLogs, ({ one }) => ({
29
+ actorUser: one(users, {
30
+ fields: [auditLogs.actorUserId],
31
+ references: [users.id],
32
+ }),
33
+ organization: one(organizations, {
34
+ fields: [auditLogs.organizationId],
35
+ references: [organizations.id],
36
+ }),
37
+ hospital: one(hospitals, {
38
+ fields: [auditLogs.hospitalId],
39
+ references: [hospitals.id],
40
+ }),
41
+ }));
42
+
@@ -0,0 +1,39 @@
1
+ import { pgTable, uuid, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { departmentStatusEnum } from './enums';
4
+ import { organizations } from './organizations';
5
+ import { hospitals } from './hospitals';
6
+ import { users } from './users';
7
+
8
+ export const departments = pgTable('departments', {
9
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
10
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
11
+ hospitalId: uuid('hospital_id').notNull().references(() => hospitals.id),
12
+ name: text('name').notNull(),
13
+ code: text('code').notNull(),
14
+ departmentType: text('department_type'),
15
+ managerUserId: uuid('manager_user_id'), // fk relations handled below
16
+ status: departmentStatusEnum('status').default('active'),
17
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
18
+ updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
19
+ createdByUserId: uuid('created_by_user_id'),
20
+ updatedByUserId: uuid('updated_by_user_id'),
21
+ }, (t) => ({
22
+ hospitalCodeIdx: uniqueIndex('department_hospital_code_idx').on(t.hospitalId, t.code),
23
+ }));
24
+
25
+ export const departmentsRelations = relations(departments, ({ one }) => ({
26
+ organization: one(organizations, {
27
+ fields: [departments.organizationId],
28
+ references: [organizations.id],
29
+ }),
30
+ hospital: one(hospitals, {
31
+ fields: [departments.hospitalId],
32
+ references: [hospitals.id],
33
+ }),
34
+ manager: one(users, {
35
+ fields: [departments.managerUserId],
36
+ references: [users.id],
37
+ }),
38
+ }));
39
+
@@ -0,0 +1,38 @@
1
+ import { pgTable, uuid, text, integer, timestamp, index } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { riskClassificationEnum, criticalityLevelEnum, refDataStatusEnum } from './enums';
4
+ import { organizations } from './organizations';
5
+ import { users } from './users';
6
+
7
+ export const deviceCategories = pgTable('device_categories', {
8
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
9
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
10
+ name: text('name').notNull(),
11
+ code: text('code').notNull(),
12
+ description: text('description'),
13
+ riskClassification: riskClassificationEnum('risk_classification'),
14
+ criticalityLevel: criticalityLevelEnum('criticality_level'),
15
+ defaultPmIntervalDays: integer('default_pm_interval_days'),
16
+ status: refDataStatusEnum('status').default('active'),
17
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
18
+ createdByUserId: uuid('created_by_user_id').references(() => users.id),
19
+ updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
20
+ updatedByUserId: uuid('updated_by_user_id').references(() => users.id),
21
+ archivedAt: timestamp('archived_at', { withTimezone: true }),
22
+ archivedByUserId: uuid('archived_by_user_id').references(() => users.id),
23
+ }, (t) => ({
24
+ orgCodeIdx: index('device_cat_org_code_idx').on(t.organizationId, t.code),
25
+ }));
26
+
27
+ export const deviceCategoriesRelations = relations(deviceCategories, ({ one }) => ({
28
+ organization: one(organizations, {
29
+ fields: [deviceCategories.organizationId],
30
+ references: [organizations.id],
31
+ }),
32
+ createdByUser: one(users, {
33
+ fields: [deviceCategories.createdByUserId],
34
+ references: [users.id],
35
+ relationName: 'categoriesCreatedByUser',
36
+ }),
37
+ }));
38
+
@@ -0,0 +1,195 @@
1
+ import { pgTable, uuid, text, timestamp, date, numeric, integer, jsonb, index } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import {
4
+ deviceStatusCodeEnum, deviceLifecycleStatusEnum,
5
+ criticalityLevelEnum, riskClassificationEnum,
6
+ qrLabelStatusEnum, deviceDocumentCategoryEnum,
7
+ documentVisibilityEnum, transferReasonEnum,
8
+ } from './enums';
9
+ import { organizations } from './organizations';
10
+ import { hospitals } from './hospitals';
11
+ import { departments } from './departments';
12
+ import { locations } from './locations';
13
+ import { users } from './users';
14
+ import { deviceCategories } from './device-categories';
15
+ import { manufacturers, deviceModels } from './manufacturers';
16
+
17
+ // ── Core Devices Table ──────────────────────────────────────────────────────────
18
+
19
+ export const devices = pgTable('devices', {
20
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
21
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
22
+ hospitalId: uuid('hospital_id').notNull().references(() => hospitals.id),
23
+ departmentId: uuid('department_id').notNull().references(() => departments.id),
24
+ locationId: uuid('location_id').references(() => locations.id),
25
+ exactLocationDescription: text('exact_location_description'),
26
+
27
+ internalCode: text('internal_code').notNull(),
28
+ assetNumber: text('asset_number').notNull(),
29
+ serialNumber: text('serial_number'),
30
+ name: text('name').notNull(),
31
+
32
+ deviceCategoryId: uuid('device_category_id').notNull().references(() => deviceCategories.id),
33
+ manufacturerId: uuid('manufacturer_id').references(() => manufacturers.id),
34
+ deviceModelId: uuid('device_model_id').references(() => deviceModels.id),
35
+ modelNameFree: text('model_name_free'),
36
+
37
+ criticalityLevel: criticalityLevelEnum('criticality_level').default('medium'),
38
+ riskClassification: riskClassificationEnum('risk_classification'),
39
+
40
+ currentStatusCode: deviceStatusCodeEnum('current_status_code').default('operational').notNull(),
41
+ statusChangedAt: timestamp('status_changed_at', { withTimezone: true }),
42
+ statusChangedByUserId: uuid('status_changed_by_user_id').references(() => users.id),
43
+ statusLimitationsNote: text('status_limitations_note'),
44
+
45
+ purchaseDate: date('purchase_date'),
46
+ purchaseCost: numeric('purchase_cost', { precision: 12, scale: 2 }),
47
+ currency: text('currency').default('USD'),
48
+ installationDate: date('installation_date'),
49
+ commissioningDate: date('commissioning_date'),
50
+ warrantyStartDate: date('warranty_start_date'),
51
+ warrantyEndDate: date('warranty_end_date'),
52
+
53
+ technicalSpecifications: jsonb('technical_specifications'),
54
+
55
+ assignedEngineerUserId: uuid('assigned_engineer_user_id').references(() => users.id),
56
+
57
+ nextPmDueDate: date('next_pm_due_date'),
58
+ lastMaintenanceCompletedAt: timestamp('last_maintenance_completed_at', { withTimezone: true }),
59
+ calibrationExpiresOn: date('calibration_expires_on'),
60
+
61
+ lifecycleStatus: deviceLifecycleStatusEnum('lifecycle_status').default('active').notNull(),
62
+ decommissionedAt: timestamp('decommissioned_at', { withTimezone: true }),
63
+ decommissionedByUserId: uuid('decommissioned_by_user_id').references(() => users.id),
64
+ decommissionReason: text('decommission_reason'),
65
+
66
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
67
+ createdByUserId: uuid('created_by_user_id').references(() => users.id),
68
+ updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
69
+ updatedByUserId: uuid('updated_by_user_id').references(() => users.id),
70
+ archivedAt: timestamp('archived_at', { withTimezone: true }),
71
+ archivedByUserId: uuid('archived_by_user_id').references(() => users.id),
72
+ archiveReason: text('archive_reason'),
73
+ }, (t) => ({
74
+ lookupIdx: index('idx_devices_lookup').on(t.organizationId, t.hospitalId, t.departmentId, t.currentStatusCode),
75
+ pmDueIdx: index('idx_devices_pm_due').on(t.organizationId, t.nextPmDueDate),
76
+ internalCodeIdx: index('idx_devices_internal_code').on(t.organizationId, t.internalCode),
77
+ assetNumberIdx: index('idx_devices_asset_number').on(t.organizationId, t.assetNumber),
78
+ }));
79
+
80
+ export const devicesRelations = relations(devices, ({ one }) => ({
81
+ organization: one(organizations, { fields: [devices.organizationId], references: [organizations.id] }),
82
+ hospital: one(hospitals, { fields: [devices.hospitalId], references: [hospitals.id] }),
83
+ department: one(departments, { fields: [devices.departmentId], references: [departments.id] }),
84
+ location: one(locations, { fields: [devices.locationId], references: [locations.id] }),
85
+ deviceCategory: one(deviceCategories, { fields: [devices.deviceCategoryId], references: [deviceCategories.id] }),
86
+ manufacturer: one(manufacturers, { fields: [devices.manufacturerId], references: [manufacturers.id] }),
87
+ deviceModel: one(deviceModels, { fields: [devices.deviceModelId], references: [deviceModels.id] }),
88
+ assignedEngineer: one(users, { fields: [devices.assignedEngineerUserId], references: [users.id], relationName: 'devicesAssignedToEngineer' }),
89
+ createdByUser: one(users, { fields: [devices.createdByUserId], references: [users.id], relationName: 'devicesCreatedByUser' }),
90
+ }));
91
+
92
+ // ── QR Labels ───────────────────────────────────────────────────────────────────
93
+
94
+ export const deviceQrLabels = pgTable('device_qr_labels', {
95
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
96
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
97
+ deviceId: uuid('device_id').notNull().references(() => devices.id, { onDelete: 'cascade' }),
98
+ opaqueReference: text('opaque_reference').notNull().unique(),
99
+ labelStatus: qrLabelStatusEnum('label_status').default('active').notNull(),
100
+ printedAt: timestamp('printed_at', { withTimezone: true }),
101
+ printedByUserId: uuid('printed_by_user_id').references(() => users.id),
102
+ printCount: integer('print_count').default(0),
103
+ revokedAt: timestamp('revoked_at', { withTimezone: true }),
104
+ revokedByUserId: uuid('revoked_by_user_id').references(() => users.id),
105
+ revocationReason: text('revocation_reason'),
106
+ replacedByQrId: uuid('replaced_by_qr_id'),
107
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
108
+ createdByUserId: uuid('created_by_user_id').references(() => users.id),
109
+ }, (t) => ({
110
+ deviceActiveIdx: index('idx_device_qr_active').on(t.deviceId, t.labelStatus),
111
+ }));
112
+
113
+ export const deviceQrLabelsRelations = relations(deviceQrLabels, ({ one }) => ({
114
+ device: one(devices, { fields: [deviceQrLabels.deviceId], references: [devices.id] }),
115
+ organization: one(organizations, { fields: [deviceQrLabels.organizationId], references: [organizations.id] }),
116
+ printedByUser: one(users, { fields: [deviceQrLabels.printedByUserId], references: [users.id], relationName: 'qrPrintedByUser' }),
117
+ }));
118
+
119
+ // ── Status History (append-only) ────────────────────────────────────────────────
120
+
121
+ export const deviceStatusHistory = pgTable('device_status_history', {
122
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
123
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
124
+ deviceId: uuid('device_id').notNull().references(() => devices.id, { onDelete: 'cascade' }),
125
+ previousStatusCode: text('previous_status_code'),
126
+ newStatusCode: text('new_status_code').notNull(),
127
+ reason: text('reason'),
128
+ notes: text('notes'),
129
+ effectiveAt: timestamp('effective_at', { withTimezone: true }).defaultNow().notNull(),
130
+ changedByUserId: uuid('changed_by_user_id').notNull().references(() => users.id),
131
+ relatedTicketId: uuid('related_ticket_id'),
132
+ relatedMaintenanceRecordId: uuid('related_maintenance_record_id'),
133
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
134
+ }, (t) => ({
135
+ deviceTimeIdx: index('idx_device_status_history_device').on(t.deviceId, t.effectiveAt),
136
+ }));
137
+
138
+ export const deviceStatusHistoryRelations = relations(deviceStatusHistory, ({ one }) => ({
139
+ device: one(devices, { fields: [deviceStatusHistory.deviceId], references: [devices.id] }),
140
+ changedByUser: one(users, { fields: [deviceStatusHistory.changedByUserId], references: [users.id], relationName: 'statusChangedByUser' }),
141
+ }));
142
+
143
+ // ── Location History (append-only) ──────────────────────────────────────────────
144
+
145
+ export const deviceLocationHistory = pgTable('device_location_history', {
146
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
147
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
148
+ deviceId: uuid('device_id').notNull().references(() => devices.id, { onDelete: 'cascade' }),
149
+ previousHospitalId: uuid('previous_hospital_id'),
150
+ previousDepartmentId: uuid('previous_department_id'),
151
+ previousLocationId: uuid('previous_location_id'),
152
+ newHospitalId: uuid('new_hospital_id').notNull(),
153
+ newDepartmentId: uuid('new_department_id').notNull(),
154
+ newLocationId: uuid('new_location_id'),
155
+ transferReason: transferReasonEnum('transfer_reason').notNull(),
156
+ notes: text('notes'),
157
+ effectiveAt: timestamp('effective_at', { withTimezone: true }).defaultNow().notNull(),
158
+ changedByUserId: uuid('changed_by_user_id').notNull().references(() => users.id),
159
+ relatedTicketId: uuid('related_ticket_id'),
160
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
161
+ }, (t) => ({
162
+ deviceTimeIdx: index('idx_device_location_history_device').on(t.deviceId, t.effectiveAt),
163
+ }));
164
+
165
+ export const deviceLocationHistoryRelations = relations(deviceLocationHistory, ({ one }) => ({
166
+ device: one(devices, { fields: [deviceLocationHistory.deviceId], references: [devices.id] }),
167
+ changedByUser: one(users, { fields: [deviceLocationHistory.changedByUserId], references: [users.id], relationName: 'locationChangedByUser' }),
168
+ newHospital: one(hospitals, { fields: [deviceLocationHistory.newHospitalId], references: [hospitals.id] }),
169
+ newDepartment: one(departments, { fields: [deviceLocationHistory.newDepartmentId], references: [departments.id] }),
170
+ }));
171
+
172
+ // ── Device Attachments ──────────────────────────────────────────────────────────
173
+
174
+ export const deviceAttachments = pgTable('device_attachments', {
175
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
176
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
177
+ deviceId: uuid('device_id').notNull().references(() => devices.id, { onDelete: 'cascade' }),
178
+ documentCategory: deviceDocumentCategoryEnum('document_category').notNull(),
179
+ fileName: text('file_name').notNull(),
180
+ fileSize: integer('file_size'),
181
+ mimeType: text('mime_type'),
182
+ storageKey: text('storage_key').notNull(),
183
+ visibility: documentVisibilityEnum('visibility').default('biomedical_only'),
184
+ uploadedByUserId: uuid('uploaded_by_user_id').references(() => users.id),
185
+ uploadedAt: timestamp('uploaded_at', { withTimezone: true }).defaultNow().notNull(),
186
+ archivedAt: timestamp('archived_at', { withTimezone: true }),
187
+ }, (t) => ({
188
+ deviceIdx: index('idx_device_attachments_device').on(t.deviceId),
189
+ }));
190
+
191
+ export const deviceAttachmentsRelations = relations(deviceAttachments, ({ one }) => ({
192
+ device: one(devices, { fields: [deviceAttachments.deviceId], references: [devices.id] }),
193
+ uploadedByUser: one(users, { fields: [deviceAttachments.uploadedByUserId], references: [users.id], relationName: 'attachmentsUploadedByUser' }),
194
+ }));
195
+
@@ -0,0 +1,63 @@
1
+ import { pgTable, uuid, text, timestamp, jsonb } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { users } from './users';
4
+ import { organizations } from './organizations';
5
+ import { hospitals } from './hospitals';
6
+
7
+ export const engineerDutyStatusValues = ['on_duty', 'on_call', 'in_maintenance', 'off_duty'] as const;
8
+ export type EngineerDutyStatus = (typeof engineerDutyStatusValues)[number];
9
+
10
+ export const engineerProfiles = pgTable('engineer_profiles', {
11
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
12
+ userId: uuid('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }).unique(),
13
+ organizationId: uuid('organization_id').references(() => organizations.id),
14
+ hospitalId: uuid('hospital_id').references(() => hospitals.id),
15
+ jobTitle: text('job_title').notNull().default('Biomedical Engineer'),
16
+ specialization: text('specialization').default('General Biomedical Engineering'),
17
+ extension: text('extension'),
18
+ mobileNumber: text('mobile_number'),
19
+ dutyStatus: text('duty_status').$type<EngineerDutyStatus>().default('on_duty').notNull(),
20
+ shiftHours: text('shift_hours').default('08:00 AM - 04:00 PM'),
21
+ workingDays: jsonb('working_days').$type<string[]>().default(['Sun', 'Mon', 'Tue', 'Wed', 'Thu']),
22
+ onCallDays: jsonb('on_call_days').$type<string[]>().default([]),
23
+ coveredDepartmentIds: jsonb('covered_department_ids').$type<string[]>().default([]),
24
+ emergencyPriority: text('emergency_priority').default('first_responder'),
25
+ notes: text('notes'),
26
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
27
+ updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
28
+ });
29
+
30
+ export const engineerDutyShifts = pgTable('engineer_duty_shifts', {
31
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
32
+ engineerProfileId: uuid('engineer_profile_id').notNull().references(() => engineerProfiles.id, { onDelete: 'cascade' }),
33
+ shiftDate: text('shift_date').notNull(), // 'YYYY-MM-DD'
34
+ shiftType: text('shift_type').notNull().default('morning'), // 'morning', 'evening', 'night', 'on_call', 'off'
35
+ startTime: text('start_time'),
36
+ endTime: text('end_time'),
37
+ notes: text('notes'),
38
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
39
+ });
40
+
41
+ export const engineerProfilesRelations = relations(engineerProfiles, ({ one, many }) => ({
42
+ user: one(users, {
43
+ fields: [engineerProfiles.userId],
44
+ references: [users.id],
45
+ }),
46
+ organization: one(organizations, {
47
+ fields: [engineerProfiles.organizationId],
48
+ references: [organizations.id],
49
+ }),
50
+ hospital: one(hospitals, {
51
+ fields: [engineerProfiles.hospitalId],
52
+ references: [hospitals.id],
53
+ }),
54
+ dutyShifts: many(engineerDutyShifts),
55
+ }));
56
+
57
+ export const engineerDutyShiftsRelations = relations(engineerDutyShifts, ({ one }) => ({
58
+ engineerProfile: one(engineerProfiles, {
59
+ fields: [engineerDutyShifts.engineerProfileId],
60
+ references: [engineerProfiles.id],
61
+ }),
62
+ }));
63
+
@@ -0,0 +1,115 @@
1
+ import { pgTable, uuid, text, timestamp, integer, jsonb, index, date } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { roundStatusEnum, roundVisitStatusEnum } from './enums';
4
+ import { organizations } from './organizations';
5
+ import { hospitals } from './hospitals';
6
+ import { departments } from './departments';
7
+ import { users } from './users';
8
+ import { electronicSignatures } from './signatures';
9
+
10
+ // ── Engineer Rounds ─────────────────────────────────────────────────────────────
11
+
12
+ export const engineerRounds = pgTable('engineer_rounds', {
13
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
14
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
15
+ hospitalId: uuid('hospital_id').notNull().references(() => hospitals.id),
16
+ engineerId: uuid('engineer_id').notNull().references(() => users.id),
17
+ roundDate: date('round_date').notNull(),
18
+ shiftType: text('shift_type').notNull().default('morning'), // 'morning', 'evening', 'night'
19
+ status: roundStatusEnum('status').default('scheduled').notNull(),
20
+ startedAt: timestamp('started_at', { withTimezone: true }),
21
+ completedAt: timestamp('completed_at', { withTimezone: true }),
22
+ startSignatureId: uuid('start_signature_id').references(() => electronicSignatures.id),
23
+ totalDepartments: integer('total_departments').default(0).notNull(),
24
+ completedDepartments: integer('completed_departments').default(0).notNull(),
25
+ totalIssuesReported: integer('total_issues_reported').default(0).notNull(),
26
+ totalNotes: integer('total_notes').default(0).notNull(),
27
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
28
+ updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
29
+ }, (t) => ({
30
+ lookupIdx: index('idx_engineer_rounds_lookup').on(t.organizationId, t.hospitalId, t.engineerId, t.roundDate),
31
+ dateIdx: index('idx_engineer_rounds_date').on(t.organizationId, t.roundDate, t.status),
32
+ engineerIdx: index('idx_engineer_rounds_engineer').on(t.engineerId, t.roundDate),
33
+ }));
34
+
35
+ // ── Round Department Visits ─────────────────────────────────────────────────────
36
+
37
+ export const roundDepartmentVisits = pgTable('round_department_visits', {
38
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
39
+ roundId: uuid('round_id').notNull().references(() => engineerRounds.id, { onDelete: 'cascade' }),
40
+ departmentId: uuid('department_id').notNull().references(() => departments.id),
41
+ departmentName: text('department_name').notNull(), // Snapshot for historical reference
42
+ sequence: integer('sequence').notNull().default(0),
43
+ status: roundVisitStatusEnum('status').default('pending').notNull(),
44
+ startedAt: timestamp('started_at', { withTimezone: true }),
45
+ completedAt: timestamp('completed_at', { withTimezone: true }),
46
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
47
+ }, (t) => ({
48
+ roundIdx: index('idx_round_visits_round').on(t.roundId, t.sequence),
49
+ deptIdx: index('idx_round_visits_dept').on(t.departmentId, t.roundId),
50
+ }));
51
+
52
+ // ── Round Visit Notes ───────────────────────────────────────────────────────────
53
+
54
+ export const roundVisitNotes = pgTable('round_visit_notes', {
55
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
56
+ visitId: uuid('visit_id').notNull().references(() => roundDepartmentVisits.id, { onDelete: 'cascade' }),
57
+ authorId: uuid('author_id').notNull().references(() => users.id),
58
+ noteText: text('note_text').notNull(),
59
+ // Stores parsed @device mentions: [{ deviceId, deviceName, internalCode }]
60
+ deviceMentions: jsonb('device_mentions').$type<Array<{
61
+ deviceId: string;
62
+ deviceName: string;
63
+ internalCode: string;
64
+ }>>().default([]),
65
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
66
+ }, (t) => ({
67
+ visitIdx: index('idx_round_notes_visit').on(t.visitId),
68
+ }));
69
+
70
+ // ── Relations ───────────────────────────────────────────────────────────────────
71
+
72
+ export const engineerRoundsRelations = relations(engineerRounds, ({ one, many }) => ({
73
+ organization: one(organizations, {
74
+ fields: [engineerRounds.organizationId],
75
+ references: [organizations.id],
76
+ }),
77
+ hospital: one(hospitals, {
78
+ fields: [engineerRounds.hospitalId],
79
+ references: [hospitals.id],
80
+ }),
81
+ engineer: one(users, {
82
+ fields: [engineerRounds.engineerId],
83
+ references: [users.id],
84
+ relationName: 'roundsPerformedByEngineer',
85
+ }),
86
+ startSignature: one(electronicSignatures, {
87
+ fields: [engineerRounds.startSignatureId],
88
+ references: [electronicSignatures.id],
89
+ }),
90
+ departmentVisits: many(roundDepartmentVisits),
91
+ }));
92
+
93
+ export const roundDepartmentVisitsRelations = relations(roundDepartmentVisits, ({ one, many }) => ({
94
+ round: one(engineerRounds, {
95
+ fields: [roundDepartmentVisits.roundId],
96
+ references: [engineerRounds.id],
97
+ }),
98
+ department: one(departments, {
99
+ fields: [roundDepartmentVisits.departmentId],
100
+ references: [departments.id],
101
+ }),
102
+ notes: many(roundVisitNotes),
103
+ }));
104
+
105
+ export const roundVisitNotesRelations = relations(roundVisitNotes, ({ one }) => ({
106
+ visit: one(roundDepartmentVisits, {
107
+ fields: [roundVisitNotes.visitId],
108
+ references: [roundDepartmentVisits.id],
109
+ }),
110
+ author: one(users, {
111
+ fields: [roundVisitNotes.authorId],
112
+ references: [users.id],
113
+ relationName: 'roundNotesAuthored',
114
+ }),
115
+ }));