@omersx/bemms 0.0.0-stage → 1.0.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,196 @@
1
+ import { pgTable, uuid, text, timestamp, integer, boolean, jsonb, index } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import {
4
+ maintenanceTypeCodeEnum,
5
+ technicalProblemCategoryCodeEnum,
6
+ ticketPriorityCodeEnum,
7
+ maintenanceTaskStatusCodeEnum,
8
+ checklistResultCodeEnum,
9
+ } from './enums';
10
+ import { organizations } from './organizations';
11
+ import { hospitals } from './hospitals';
12
+ import { departments } from './departments';
13
+ import { locations } from './locations';
14
+ import { deviceCategories } from './device-categories';
15
+ import { devices } from './devices';
16
+ import { serviceTickets } from './tickets';
17
+ import { users } from './users';
18
+
19
+ // ── Checklist Templates ────────────────────────────────────────────────────────
20
+
21
+ export const checklistTemplates = pgTable('checklist_templates', {
22
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
23
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
24
+ deviceCategoryId: uuid('device_category_id').references(() => deviceCategories.id),
25
+ name: text('name').notNull(),
26
+ code: text('code').unique(),
27
+ maintenanceType: maintenanceTypeCodeEnum('maintenance_type'),
28
+ isActive: boolean('is_active').default(true).notNull(),
29
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
30
+ updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
31
+ }, (t) => ({
32
+ orgIdx: index('idx_checklist_templates_org').on(t.organizationId),
33
+ deviceCatIdx: index('idx_checklist_templates_category').on(t.deviceCategoryId),
34
+ }));
35
+
36
+ export const checklistTemplatesRelations = relations(checklistTemplates, ({ one, many }) => ({
37
+ organization: one(organizations, {
38
+ fields: [checklistTemplates.organizationId],
39
+ references: [organizations.id],
40
+ }),
41
+ deviceCategory: one(deviceCategories, {
42
+ fields: [checklistTemplates.deviceCategoryId],
43
+ references: [deviceCategories.id],
44
+ }),
45
+ versions: many(checklistTemplateVersions),
46
+ }));
47
+
48
+ // ── Checklist Template Versions ────────────────────────────────────────────────
49
+
50
+ export const checklistTemplateVersions = pgTable('checklist_template_versions', {
51
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
52
+ checklistTemplateId: uuid('checklist_template_id').notNull().references(() => checklistTemplates.id, { onDelete: 'cascade' }),
53
+ versionNumber: integer('version_number').notNull(),
54
+ itemsJsonb: jsonb('items_jsonb').notNull(),
55
+ isActive: boolean('is_active').default(true).notNull(),
56
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
57
+ createdByUserId: uuid('created_by_user_id').references(() => users.id),
58
+ }, (t) => ({
59
+ templateVersionIdx: index('idx_checklist_template_versions_template').on(t.checklistTemplateId, t.versionNumber),
60
+ }));
61
+
62
+ export const checklistTemplateVersionsRelations = relations(checklistTemplateVersions, ({ one, many }) => ({
63
+ checklistTemplate: one(checklistTemplates, {
64
+ fields: [checklistTemplateVersions.checklistTemplateId],
65
+ references: [checklistTemplates.id],
66
+ }),
67
+ createdByUser: one(users, {
68
+ fields: [checklistTemplateVersions.createdByUserId],
69
+ references: [users.id],
70
+ relationName: 'checklistVersionsCreatedByUser',
71
+ }),
72
+ tasks: many(maintenanceTasks),
73
+ }));
74
+
75
+ // ── Maintenance Tasks ──────────────────────────────────────────────────────────
76
+
77
+ export const maintenanceTasks = pgTable('maintenance_tasks', {
78
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
79
+ taskNumber: text('task_number').notNull().unique(),
80
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
81
+ hospitalId: uuid('hospital_id').notNull().references(() => hospitals.id),
82
+ departmentId: uuid('department_id').references(() => departments.id),
83
+ locationId: uuid('location_id').references(() => locations.id),
84
+ deviceId: uuid('device_id').notNull().references(() => devices.id),
85
+ serviceTicketId: uuid('service_ticket_id').references(() => serviceTickets.id),
86
+ maintenanceScheduleOccurrenceId: uuid('maintenance_schedule_occurrence_id'),
87
+ maintenanceType: maintenanceTypeCodeEnum('maintenance_type').notNull(),
88
+ technicalProblemCategory: technicalProblemCategoryCodeEnum('technical_problem_category'),
89
+ statusCode: maintenanceTaskStatusCodeEnum('status_code').default('assigned').notNull(),
90
+ title: text('title').notNull(),
91
+ description: text('description'),
92
+ assignedEngineerUserId: uuid('assigned_engineer_user_id').references(() => users.id),
93
+ assignedTeamId: uuid('assigned_team_id'),
94
+ priorityCode: ticketPriorityCodeEnum('priority_code').default('p3_normal'),
95
+ dueDate: timestamp('due_date', { withTimezone: true }),
96
+ acceptedAt: timestamp('accepted_at', { withTimezone: true }),
97
+ startedAt: timestamp('started_at', { withTimezone: true }),
98
+ completedAt: timestamp('completed_at', { withTimezone: true }),
99
+ waitingReason: text('waiting_reason'),
100
+ waitingDependencyType: text('waiting_dependency_type'),
101
+ checklistTemplateVersionId: uuid('checklist_template_version_id').references(() => checklistTemplateVersions.id),
102
+ deviceSnapshot: jsonb('device_snapshot'),
103
+ locationSnapshot: jsonb('location_snapshot'),
104
+ resultRecordId: uuid('result_record_id'),
105
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
106
+ createdByUserId: uuid('created_by_user_id').references(() => users.id),
107
+ updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
108
+ updatedByUserId: uuid('updated_by_user_id').references(() => users.id),
109
+ }, (t) => ({
110
+ lookupIdx: index('idx_maintenance_tasks_lookup').on(t.organizationId, t.hospitalId, t.departmentId, t.statusCode),
111
+ taskNumIdx: index('idx_maintenance_tasks_number').on(t.organizationId, t.taskNumber),
112
+ deviceIdx: index('idx_maintenance_tasks_device').on(t.deviceId, t.statusCode),
113
+ assigneeIdx: index('idx_maintenance_tasks_assignee').on(t.assignedEngineerUserId, t.statusCode),
114
+ ticketIdx: index('idx_maintenance_tasks_ticket').on(t.serviceTicketId),
115
+ dueIdx: index('idx_maintenance_tasks_due').on(t.organizationId, t.dueDate),
116
+ }));
117
+
118
+ export const maintenanceTasksRelations = relations(maintenanceTasks, ({ one, many }) => ({
119
+ organization: one(organizations, {
120
+ fields: [maintenanceTasks.organizationId],
121
+ references: [organizations.id],
122
+ }),
123
+ hospital: one(hospitals, {
124
+ fields: [maintenanceTasks.hospitalId],
125
+ references: [hospitals.id],
126
+ }),
127
+ department: one(departments, {
128
+ fields: [maintenanceTasks.departmentId],
129
+ references: [departments.id],
130
+ }),
131
+ location: one(locations, {
132
+ fields: [maintenanceTasks.locationId],
133
+ references: [locations.id],
134
+ }),
135
+ device: one(devices, {
136
+ fields: [maintenanceTasks.deviceId],
137
+ references: [devices.id],
138
+ }),
139
+ serviceTicket: one(serviceTickets, {
140
+ fields: [maintenanceTasks.serviceTicketId],
141
+ references: [serviceTickets.id],
142
+ }),
143
+ checklistTemplateVersion: one(checklistTemplateVersions, {
144
+ fields: [maintenanceTasks.checklistTemplateVersionId],
145
+ references: [checklistTemplateVersions.id],
146
+ }),
147
+ assignedEngineer: one(users, {
148
+ fields: [maintenanceTasks.assignedEngineerUserId],
149
+ references: [users.id],
150
+ relationName: 'tasksAssignedToEngineer',
151
+ }),
152
+ createdByUser: one(users, {
153
+ fields: [maintenanceTasks.createdByUserId],
154
+ references: [users.id],
155
+ relationName: 'tasksCreatedByUser',
156
+ }),
157
+ updatedByUser: one(users, {
158
+ fields: [maintenanceTasks.updatedByUserId],
159
+ references: [users.id],
160
+ relationName: 'tasksUpdatedByUser',
161
+ }),
162
+ checklistResults: many(maintenanceChecklistResults),
163
+ }));
164
+
165
+ // ── Maintenance Checklist Results ─────────────────────────────────────────────
166
+
167
+ export const maintenanceChecklistResults = pgTable('maintenance_checklist_results', {
168
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
169
+ maintenanceTaskId: uuid('maintenance_task_id').notNull().references(() => maintenanceTasks.id, { onDelete: 'cascade' }),
170
+ maintenanceRecordId: uuid('maintenance_record_id'),
171
+ templateItemId: text('template_item_id').notNull(),
172
+ itemLabelSnapshot: text('item_label_snapshot').notNull(),
173
+ itemOrder: integer('item_order').notNull(),
174
+ resultCode: checklistResultCodeEnum('result_code'),
175
+ measuredValue: text('measured_value'),
176
+ unit: text('unit'),
177
+ notes: text('notes'),
178
+ performedByUserId: uuid('performed_by_user_id').references(() => users.id),
179
+ completedAt: timestamp('completed_at', { withTimezone: true }),
180
+ }, (t) => ({
181
+ taskItemIdx: index('idx_checklist_results_task').on(t.maintenanceTaskId, t.itemOrder),
182
+ recordIdx: index('idx_checklist_results_record').on(t.maintenanceRecordId),
183
+ }));
184
+
185
+ export const maintenanceChecklistResultsRelations = relations(maintenanceChecklistResults, ({ one }) => ({
186
+ maintenanceTask: one(maintenanceTasks, {
187
+ fields: [maintenanceChecklistResults.maintenanceTaskId],
188
+ references: [maintenanceTasks.id],
189
+ }),
190
+ performedByUser: one(users, {
191
+ fields: [maintenanceChecklistResults.performedByUserId],
192
+ references: [users.id],
193
+ relationName: 'checklistResultsPerformedByUser',
194
+ }),
195
+ }));
196
+
@@ -0,0 +1,60 @@
1
+ import { pgTable, uuid, text, timestamp, index } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { refDataStatusEnum } from './enums';
4
+ import { organizations } from './organizations';
5
+ import { users } from './users';
6
+
7
+ export const manufacturers = pgTable('manufacturers', {
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'),
12
+ country: text('country'),
13
+ supportEmail: text('support_email'),
14
+ supportPhone: text('support_phone'),
15
+ website: text('website'),
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
+ archivedAt: timestamp('archived_at', { withTimezone: true }),
21
+ }, (t) => ({
22
+ orgNameIdx: index('mfr_org_name_idx').on(t.organizationId, t.name),
23
+ }));
24
+
25
+ export const manufacturersRelations = relations(manufacturers, ({ one }) => ({
26
+ organization: one(organizations, {
27
+ fields: [manufacturers.organizationId],
28
+ references: [organizations.id],
29
+ }),
30
+ createdByUser: one(users, {
31
+ fields: [manufacturers.createdByUserId],
32
+ references: [users.id],
33
+ relationName: 'manufacturersCreatedByUser',
34
+ }),
35
+ }));
36
+
37
+ export const deviceModels = pgTable('device_models', {
38
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
39
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
40
+ manufacturerId: uuid('manufacturer_id').notNull().references(() => manufacturers.id),
41
+ modelName: text('model_name').notNull(),
42
+ modelNumber: text('model_number'),
43
+ specifications: text('specifications'),
44
+ status: refDataStatusEnum('status').default('active'),
45
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
46
+ }, (t) => ({
47
+ mfrModelIdx: index('model_mfr_idx').on(t.manufacturerId, t.modelName),
48
+ }));
49
+
50
+ export const deviceModelsRelations = relations(deviceModels, ({ one }) => ({
51
+ organization: one(organizations, {
52
+ fields: [deviceModels.organizationId],
53
+ references: [organizations.id],
54
+ }),
55
+ manufacturer: one(manufacturers, {
56
+ fields: [deviceModels.manufacturerId],
57
+ references: [manufacturers.id],
58
+ }),
59
+ }));
60
+
@@ -0,0 +1,48 @@
1
+ import { pgTable, uuid, text, timestamp } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { notificationTypeEnum } from './enums';
4
+ import { organizations } from './organizations';
5
+ import { users } from './users';
6
+
7
+ export const notifications = pgTable('notifications', {
8
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
9
+ organizationId: uuid('organization_id').references(() => organizations.id).notNull(),
10
+ recipientUserId: uuid('recipient_user_id').references(() => users.id).notNull(),
11
+ notificationType: notificationTypeEnum('notification_type').notNull(),
12
+ title: text('title').notNull(),
13
+ body: text('body').notNull(),
14
+ relatedEntityType: text('related_entity_type'),
15
+ relatedEntityId: uuid('related_entity_id'),
16
+ actionUrl: text('action_url'),
17
+ readAt: timestamp('read_at', { withTimezone: true }),
18
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
19
+ });
20
+
21
+ export const notificationsRelations = relations(notifications, ({ one }) => ({
22
+ organization: one(organizations, {
23
+ fields: [notifications.organizationId],
24
+ references: [organizations.id],
25
+ }),
26
+ recipient: one(users, {
27
+ fields: [notifications.recipientUserId],
28
+ references: [users.id],
29
+ }),
30
+ }));
31
+
32
+ export const pushSubscriptions = pgTable('push_subscriptions', {
33
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
34
+ userId: uuid('user_id').references(() => users.id).notNull(),
35
+ endpoint: text('endpoint').notNull(),
36
+ p256dh: text('p256dh').notNull(),
37
+ auth: text('auth').notNull(),
38
+ userAgent: text('user_agent'),
39
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
40
+ });
41
+
42
+ export const pushSubscriptionsRelations = relations(pushSubscriptions, ({ one }) => ({
43
+ user: one(users, {
44
+ fields: [pushSubscriptions.userId],
45
+ references: [users.id],
46
+ }),
47
+ }));
48
+
@@ -0,0 +1,24 @@
1
+ import { pgTable, uuid, text, timestamp, jsonb } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { organizationStatusEnum } from './enums';
4
+ import { users } from './users';
5
+ import { hospitals } from './hospitals';
6
+
7
+ export const organizations = pgTable('organizations', {
8
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
9
+ name: text('name').notNull(),
10
+ code: text('code').notNull().unique(),
11
+ defaultTimezone: text('default_timezone').default('UTC'),
12
+ status: organizationStatusEnum('status').default('active'),
13
+ settings: jsonb('settings'),
14
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
15
+ updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
16
+ createdByUserId: uuid('created_by_user_id'),
17
+ updatedByUserId: uuid('updated_by_user_id'),
18
+ });
19
+
20
+ export const organizationsRelations = relations(organizations, ({ many }) => ({
21
+ hospitals: many(hospitals),
22
+ users: many(users),
23
+ }));
24
+
@@ -0,0 +1,28 @@
1
+ import { pgTable, uuid, text, timestamp, integer, jsonb, index } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { organizations } from './organizations';
4
+ import { users } from './users';
5
+
6
+ export const generatedReports = pgTable('generated_reports', {
7
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
8
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
9
+ reportType: text('report_type').notNull(), // 'inventory', 'tickets', 'maintenance', 'costs', 'workload'
10
+ title: text('title').notNull(),
11
+ filtersJsonb: jsonb('filters_jsonb'),
12
+ dateRangeStart: timestamp('date_range_start', { withTimezone: true }),
13
+ dateRangeEnd: timestamp('date_range_end', { withTimezone: true }),
14
+ timezone: text('timezone').default('UTC'),
15
+ rowCount: integer('row_count'),
16
+ fileFormat: text('file_format').default('csv'), // 'csv', 'xlsx', 'pdf'
17
+ fileName: text('file_name').notNull(),
18
+ generatedByUserId: uuid('generated_by_user_id').notNull().references(() => users.id),
19
+ generatedAt: timestamp('generated_at', { withTimezone: true }).defaultNow().notNull(),
20
+ }, (t) => ({
21
+ orgIdx: index('idx_generated_reports_org').on(t.organizationId, t.generatedAt),
22
+ }));
23
+
24
+ export const generatedReportsRelations = relations(generatedReports, ({ one }) => ({
25
+ organization: one(organizations, { fields: [generatedReports.organizationId], references: [organizations.id] }),
26
+ generatedByUser: one(users, { fields: [generatedReports.generatedByUserId], references: [users.id] }),
27
+ }));
28
+
@@ -0,0 +1,59 @@
1
+ import { pgTable, uuid, text, timestamp, boolean, uniqueIndex } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { roleStatusEnum, permissionModuleEnum, permissionActionEnum } from './enums';
4
+ import { organizations } from './organizations';
5
+
6
+ export const roles = pgTable('roles', {
7
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
8
+ organizationId: uuid('organization_id').references(() => organizations.id),
9
+ code: text('code').notNull().unique(),
10
+ name: text('name').notNull(),
11
+ description: text('description'),
12
+ isSystemRole: boolean('is_system_role').default(false),
13
+ status: roleStatusEnum('status').default('active'),
14
+ createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
15
+ updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
16
+ createdByUserId: uuid('created_by_user_id'),
17
+ updatedByUserId: uuid('updated_by_user_id'),
18
+ });
19
+
20
+ export const permissions = pgTable('permissions', {
21
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
22
+ module: permissionModuleEnum('module').notNull(),
23
+ action: permissionActionEnum('action').notNull(),
24
+ description: text('description'),
25
+ }, (t) => ({
26
+ moduleActionIdx: uniqueIndex('permission_module_action_idx').on(t.module, t.action),
27
+ }));
28
+
29
+ export const rolePermissions = pgTable('role_permissions', {
30
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
31
+ roleId: uuid('role_id').notNull().references(() => roles.id, { onDelete: 'cascade' }),
32
+ permissionId: uuid('permission_id').notNull().references(() => permissions.id, { onDelete: 'cascade' }),
33
+ }, (t) => ({
34
+ rolePermissionIdx: uniqueIndex('role_permission_idx').on(t.roleId, t.permissionId),
35
+ }));
36
+
37
+ export const rolesRelations = relations(roles, ({ one, many }) => ({
38
+ organization: one(organizations, {
39
+ fields: [roles.organizationId],
40
+ references: [organizations.id],
41
+ }),
42
+ rolePermissions: many(rolePermissions),
43
+ }));
44
+
45
+ export const permissionsRelations = relations(permissions, ({ many }) => ({
46
+ rolePermissions: many(rolePermissions),
47
+ }));
48
+
49
+ export const rolePermissionsRelations = relations(rolePermissions, ({ one }) => ({
50
+ role: one(roles, {
51
+ fields: [rolePermissions.roleId],
52
+ references: [roles.id],
53
+ }),
54
+ permission: one(permissions, {
55
+ fields: [rolePermissions.permissionId],
56
+ references: [permissions.id],
57
+ }),
58
+ }));
59
+
@@ -0,0 +1,46 @@
1
+ import { pgTable, uuid, text, timestamp, integer, primaryKey } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import { users } from './users';
4
+
5
+ export const sessions = pgTable('sessions', {
6
+ sessionToken: text('sessionToken').primaryKey(),
7
+ userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
8
+ expires: timestamp('expires', { mode: 'date' }).notNull(),
9
+ });
10
+
11
+ export const accounts = pgTable('accounts', {
12
+ id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
13
+ userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
14
+ type: text('type').notNull(),
15
+ provider: text('provider').notNull(),
16
+ providerAccountId: text('providerAccountId').notNull(),
17
+ refresh_token: text('refresh_token'),
18
+ access_token: text('access_token'),
19
+ expires_at: integer('expires_at'),
20
+ token_type: text('token_type'),
21
+ scope: text('scope'),
22
+ id_token: text('id_token'),
23
+ });
24
+
25
+ export const verificationTokens = pgTable('verification_tokens', {
26
+ identifier: text('identifier').notNull(),
27
+ token: text('token').notNull(),
28
+ expires: timestamp('expires', { mode: 'date' }).notNull(),
29
+ }, (vt) => ({
30
+ compoundKey: primaryKey({ columns: [vt.identifier, vt.token] }),
31
+ }));
32
+
33
+ export const sessionsRelations = relations(sessions, ({ one }) => ({
34
+ user: one(users, {
35
+ fields: [sessions.userId],
36
+ references: [users.id],
37
+ }),
38
+ }));
39
+
40
+ export const accountsRelations = relations(accounts, ({ one }) => ({
41
+ user: one(users, {
42
+ fields: [accounts.userId],
43
+ references: [users.id],
44
+ }),
45
+ }));
46
+
@@ -0,0 +1,48 @@
1
+ import { pgTable, uuid, text, timestamp, index } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import {
4
+ signatureEventTypeEnum,
5
+ signatureStatusEnum,
6
+ } from './enums';
7
+ import { organizations } from './organizations';
8
+ import { electronicSignatures } from './signatures';
9
+ import { users } from './users';
10
+
11
+ // ── Signature Events (append-only hash chain) ─────────────────────────────────
12
+ // Per spec §10.4: Append-only trace events for signature creation, review,
13
+ // rejection, amendment, supersession, and voiding.
14
+
15
+ export const signatureEvents = pgTable('signature_events', {
16
+ id: uuid('id').defaultRandom().primaryKey().$defaultFn(() => crypto.randomUUID()),
17
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
18
+ signatureId: uuid('signature_id').notNull().references(() => electronicSignatures.id),
19
+ eventType: signatureEventTypeEnum('event_type').notNull(),
20
+ actorUserId: uuid('actor_user_id').notNull().references(() => users.id),
21
+ timestamp: timestamp('timestamp', { withTimezone: true, mode: 'date' }).defaultNow().notNull(),
22
+ previousStatus: signatureStatusEnum('previous_status'),
23
+ newStatus: signatureStatusEnum('new_status'),
24
+ reason: text('reason'),
25
+ previousEventHash: text('previous_event_hash'),
26
+ currentEventHash: text('current_event_hash').notNull(),
27
+ }, (t) => ({
28
+ signatureIdx: index('idx_sig_events_signature').on(t.signatureId),
29
+ orgTimeIdx: index('idx_sig_events_org_time').on(t.organizationId, t.timestamp),
30
+ actorIdx: index('idx_sig_events_actor').on(t.actorUserId, t.timestamp),
31
+ }));
32
+
33
+ export const signatureEventsRelations = relations(signatureEvents, ({ one }) => ({
34
+ organization: one(organizations, {
35
+ fields: [signatureEvents.organizationId],
36
+ references: [organizations.id],
37
+ }),
38
+ signature: one(electronicSignatures, {
39
+ fields: [signatureEvents.signatureId],
40
+ references: [electronicSignatures.id],
41
+ }),
42
+ actor: one(users, {
43
+ fields: [signatureEvents.actorUserId],
44
+ references: [users.id],
45
+ relationName: 'signatureEventsActor',
46
+ }),
47
+ }));
48
+
@@ -0,0 +1,60 @@
1
+ import { pgTable, uuid, text, timestamp, boolean, jsonb, index, uniqueIndex } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import {
4
+ signaturePolicyActionEnum,
5
+ criticalityLevelEnum,
6
+ } from './enums';
7
+ import { organizations } from './organizations';
8
+ import { hospitals } from './hospitals';
9
+ import { deviceCategories } from './device-categories';
10
+
11
+ // ── Signature Policies ────────────────────────────────────────────────────────
12
+ // Per spec §10.3 & §6: Configurable rules defining which roles and signatures
13
+ // are required for a particular action, scoped by organization, criticality,
14
+ // and device category.
15
+
16
+ export interface SignaturePolicyRequirement {
17
+ purpose: 'accept' | 'perform' | 'review' | 'approve' | 'release' | 'resolve' | 'close';
18
+ allowedRoles: string[];
19
+ required: boolean;
20
+ }
21
+
22
+ export const signaturePolicies = pgTable('signature_policies', {
23
+ id: uuid('id').defaultRandom().primaryKey().$defaultFn(() => crypto.randomUUID()),
24
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
25
+ hospitalId: uuid('hospital_id').references(() => hospitals.id),
26
+ actionType: signaturePolicyActionEnum('action_type').notNull(),
27
+ criticalityLevel: criticalityLevelEnum('criticality_level'),
28
+ deviceCategoryId: uuid('device_category_id').references(() => deviceCategories.id),
29
+ requiredSignatures: jsonb('required_signatures').$type<SignaturePolicyRequirement[]>().notNull(),
30
+ requireIndependentReview: boolean('require_independent_review').default(false).notNull(),
31
+ performerCanRelease: boolean('performer_can_release').default(true).notNull(),
32
+ requireReauth: boolean('require_reauth').default(true).notNull(),
33
+ effectiveDate: timestamp('effective_date', { withTimezone: true, mode: 'date' }).defaultNow().notNull(),
34
+ isActive: boolean('is_active').default(true).notNull(),
35
+ policyVersion: text('policy_version').default('1.0').notNull(),
36
+ createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' }).defaultNow().notNull(),
37
+ updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'date' }).defaultNow().notNull(),
38
+ createdByUserId: uuid('created_by_user_id'),
39
+ }, (t) => ({
40
+ orgActionIdx: uniqueIndex('idx_sig_policies_org_action').on(
41
+ t.organizationId, t.actionType, t.criticalityLevel, t.deviceCategoryId
42
+ ),
43
+ activeIdx: index('idx_sig_policies_active').on(t.organizationId, t.isActive),
44
+ }));
45
+
46
+ export const signaturePoliciesRelations = relations(signaturePolicies, ({ one }) => ({
47
+ organization: one(organizations, {
48
+ fields: [signaturePolicies.organizationId],
49
+ references: [organizations.id],
50
+ }),
51
+ hospital: one(hospitals, {
52
+ fields: [signaturePolicies.hospitalId],
53
+ references: [hospitals.id],
54
+ }),
55
+ deviceCategory: one(deviceCategories, {
56
+ fields: [signaturePolicies.deviceCategoryId],
57
+ references: [deviceCategories.id],
58
+ }),
59
+ }));
60
+
@@ -0,0 +1,87 @@
1
+ import { pgTable, uuid, text, timestamp, integer, jsonb, index, uniqueIndex, type AnyPgColumn } from 'drizzle-orm/pg-core';
2
+ import { relations } from 'drizzle-orm';
3
+ import {
4
+ recordVersionEntityTypeEnum,
5
+ signaturePurposeEnum,
6
+ signatureAuthMethodEnum,
7
+ signatureStatusEnum,
8
+ } from './enums';
9
+ import { organizations } from './organizations';
10
+ import { users } from './users';
11
+
12
+ export const recordVersions = pgTable('record_versions', {
13
+ id: uuid('id').defaultRandom().primaryKey().$defaultFn(() => crypto.randomUUID()),
14
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
15
+ entityType: recordVersionEntityTypeEnum('entity_type').notNull(),
16
+ entityId: uuid('entity_id').notNull(),
17
+ versionNumber: integer('version_number').notNull(),
18
+ canonicalSnapshotJsonb: jsonb('canonical_snapshot_jsonb').notNull(),
19
+ contentHashSha256: text('content_hash_sha256').notNull(),
20
+ amendmentReason: text('amendment_reason'),
21
+ supersedesVersionId: uuid('supersedes_version_id').references((): AnyPgColumn => recordVersions.id),
22
+ createdByUserId: uuid('created_by_user_id').notNull().references(() => users.id),
23
+ createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' }).defaultNow().notNull(),
24
+ }, (t) => ({
25
+ entityVersionIdx: uniqueIndex('idx_record_versions_entity_version').on(t.entityType, t.entityId, t.versionNumber),
26
+ orgEntityIdx: index('idx_record_versions_org_entity').on(t.organizationId, t.entityType, t.entityId),
27
+ }));
28
+
29
+ export const electronicSignatures = pgTable('electronic_signatures', {
30
+ id: uuid('id').defaultRandom().primaryKey().$defaultFn(() => crypto.randomUUID()),
31
+ organizationId: uuid('organization_id').notNull().references(() => organizations.id),
32
+ recordVersionId: uuid('record_version_id').notNull().references(() => recordVersions.id),
33
+ entityType: recordVersionEntityTypeEnum('entity_type').notNull(),
34
+ entityId: uuid('entity_id').notNull(),
35
+ signaturePurpose: signaturePurposeEnum('signature_purpose').notNull(),
36
+ signerUserId: uuid('signer_user_id').notNull().references(() => users.id),
37
+ signerNameSnapshot: text('signer_name_snapshot').notNull(),
38
+ signerRoleSnapshot: text('signer_role_snapshot').notNull(),
39
+ signerScopeSnapshot: text('signer_scope_snapshot'),
40
+ attestationTextVersion: text('attestation_text_version').notNull(),
41
+ authMethod: signatureAuthMethodEnum('auth_method').notNull(),
42
+ signedAt: timestamp('signed_at', { withTimezone: true, mode: 'date' }).notNull(),
43
+ displayTimezone: text('display_timezone').default('UTC'),
44
+ signedContentHashSha256: text('signed_content_hash_sha256').notNull(),
45
+ signatureStatus: signatureStatusEnum('signature_status').default('active').notNull(),
46
+ comments: text('comments'),
47
+ }, (t) => ({
48
+ entityIdx: index('idx_signatures_entity').on(t.entityType, t.entityId),
49
+ recordVersionIdx: index('idx_signatures_record_version').on(t.recordVersionId),
50
+ signerIdx: index('idx_signatures_signer').on(t.signerUserId, t.signedAt),
51
+ orgTimeIdx: index('idx_signatures_org_time').on(t.organizationId, t.signedAt),
52
+ }));
53
+
54
+ export const recordVersionsRelations = relations(recordVersions, ({ one, many }) => ({
55
+ organization: one(organizations, {
56
+ fields: [recordVersions.organizationId],
57
+ references: [organizations.id],
58
+ }),
59
+ createdByUser: one(users, {
60
+ fields: [recordVersions.createdByUserId],
61
+ references: [users.id],
62
+ relationName: 'recordVersionsCreatedByUser',
63
+ }),
64
+ supersedesVersion: one(recordVersions, {
65
+ fields: [recordVersions.supersedesVersionId],
66
+ references: [recordVersions.id],
67
+ relationName: 'supersededVersions',
68
+ }),
69
+ signatures: many(electronicSignatures),
70
+ }));
71
+
72
+ export const electronicSignaturesRelations = relations(electronicSignatures, ({ one }) => ({
73
+ organization: one(organizations, {
74
+ fields: [electronicSignatures.organizationId],
75
+ references: [organizations.id],
76
+ }),
77
+ recordVersion: one(recordVersions, {
78
+ fields: [electronicSignatures.recordVersionId],
79
+ references: [recordVersions.id],
80
+ }),
81
+ signerUser: one(users, {
82
+ fields: [electronicSignatures.signerUserId],
83
+ references: [users.id],
84
+ relationName: 'signaturesBySigner',
85
+ }),
86
+ }));
87
+