@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,748 @@
1
+ 'use server';
2
+
3
+ import { db } from '@/lib/db';
4
+ import {
5
+ devices, deviceQrLabels, deviceStatusHistory,
6
+ deviceLocationHistory, maintenanceTasks, maintenanceRecords,
7
+ electronicSignatures, signatureEvents, deviceAttachments,
8
+ deviceCategories, serviceTickets,
9
+ } from '@/lib/db/schema';
10
+ import { requireAuth, requireRole, requireScope } from '@/lib/auth/rbac';
11
+ import { createAuditLog } from '@/lib/audit';
12
+ import {
13
+ createDeviceSchema, updateDeviceSchema, transferDeviceSchema,
14
+ changeDeviceStatusSchema, decommissionDeviceSchema,
15
+ } from '@/lib/validators/devices';
16
+ import { eq, desc, and, or, ilike, sql, inArray } from 'drizzle-orm';
17
+ import { nanoid } from 'nanoid';
18
+
19
+ function generateOpaqueReference(): string {
20
+ return `dv_${nanoid(10)}`;
21
+ }
22
+
23
+ function generateInternalCode(): string {
24
+ const year = new Date().getFullYear();
25
+ const seq = nanoid(6).toUpperCase();
26
+ return `DEV-${year}-${seq}`;
27
+ }
28
+
29
+ // ── List / Search ───────────────────────────────────────────────────────────────
30
+
31
+ export async function getDevices(filters?: {
32
+ search?: string;
33
+ organizationId?: string;
34
+ hospitalId?: string;
35
+ departmentId?: string;
36
+ categoryId?: string;
37
+ manufacturerId?: string;
38
+ status?: string;
39
+ criticality?: string;
40
+ page?: number;
41
+ pageSize?: number;
42
+ }) {
43
+ await requireAuth();
44
+ try {
45
+ const conditions: any[] = [];
46
+ if (filters?.organizationId) conditions.push(eq(devices.organizationId, filters.organizationId));
47
+ if (filters?.hospitalId) conditions.push(eq(devices.hospitalId, filters.hospitalId));
48
+ if (filters?.departmentId) conditions.push(eq(devices.departmentId, filters.departmentId));
49
+ if (filters?.categoryId) conditions.push(eq(devices.deviceCategoryId, filters.categoryId));
50
+ if (filters?.manufacturerId) conditions.push(eq(devices.manufacturerId, filters.manufacturerId));
51
+ if (filters?.status) conditions.push(eq(devices.currentStatusCode, filters.status as any));
52
+ if (filters?.criticality) conditions.push(eq(devices.criticalityLevel, filters.criticality as any));
53
+ if (filters?.search) {
54
+ conditions.push(
55
+ or(
56
+ ilike(devices.name, `%${filters.search}%`),
57
+ ilike(devices.assetNumber, `%${filters.search}%`),
58
+ ilike(devices.serialNumber, `%${filters.search}%`),
59
+ ilike(devices.internalCode, `%${filters.search}%`),
60
+ )
61
+ );
62
+ }
63
+
64
+ const page = filters?.page || 1;
65
+ const pageSize = filters?.pageSize || 25;
66
+ const whereClause = conditions.length > 0 ? and(...conditions) : undefined;
67
+
68
+ const data = await db.query.devices.findMany({
69
+ where: whereClause,
70
+ with: {
71
+ deviceCategory: true,
72
+ manufacturer: true,
73
+ hospital: true,
74
+ department: true,
75
+ location: true,
76
+ assignedEngineer: true,
77
+ },
78
+ orderBy: [desc(devices.createdAt)],
79
+ limit: pageSize,
80
+ offset: (page - 1) * pageSize,
81
+ });
82
+
83
+ return { success: true, data };
84
+ } catch (error: any) {
85
+ return { success: false, error: error.message };
86
+ }
87
+ }
88
+
89
+ export async function getDeviceById(id: string) {
90
+ await requireAuth();
91
+ try {
92
+ const data = await db.query.devices.findFirst({
93
+ where: eq(devices.id, id),
94
+ with: {
95
+ organization: true,
96
+ hospital: true,
97
+ department: true,
98
+ location: true,
99
+ deviceCategory: true,
100
+ manufacturer: true,
101
+ deviceModel: true,
102
+ assignedEngineer: true,
103
+ },
104
+ });
105
+ return { success: true, data };
106
+ } catch (error: any) {
107
+ return { success: false, error: error.message };
108
+ }
109
+ }
110
+
111
+ // ── Create ──────────────────────────────────────────────────────────────────────
112
+
113
+ export async function createDevice(input: unknown) {
114
+ const session = await requireAuth();
115
+ await requireRole('SYS_ADMIN', 'ORG_ADMIN', 'BIOMED_MGR', 'BIOMED_ENG');
116
+ const validated = createDeviceSchema.safeParse(input);
117
+ if (!validated.success) return { success: false, error: validated.error.message };
118
+
119
+ await requireScope({
120
+ organizationId: validated.data.organizationId,
121
+ hospitalId: validated.data.hospitalId,
122
+ departmentId: validated.data.departmentId,
123
+ });
124
+
125
+ try {
126
+ return await db.transaction(async (tx) => {
127
+ const internalCode = generateInternalCode();
128
+ const opaqueReference = generateOpaqueReference();
129
+
130
+ // Resolve category if not specified or empty
131
+ let categoryId = validated.data.deviceCategoryId || undefined;
132
+ let resolvedCriticality = validated.data.criticalityLevel;
133
+ let resolvedRisk = validated.data.riskClassification;
134
+
135
+ if (!categoryId) {
136
+ const allCats = await tx.query.deviceCategories.findMany({
137
+ where: eq(deviceCategories.organizationId, validated.data.organizationId),
138
+ });
139
+ const lowerName = validated.data.name.toLowerCase();
140
+ const matched = allCats.find((c) =>
141
+ lowerName.includes(c.name.toLowerCase()) ||
142
+ lowerName.includes(c.code.toLowerCase()) ||
143
+ c.name.toLowerCase().includes(lowerName)
144
+ );
145
+ if (matched) {
146
+ categoryId = matched.id;
147
+ resolvedCriticality = resolvedCriticality || matched.criticalityLevel || 'medium';
148
+ resolvedRisk = resolvedRisk || matched.riskClassification || 'class_i';
149
+ } else {
150
+ const generalCat = allCats.find((c) => c.code === 'GENERAL');
151
+ if (generalCat) {
152
+ categoryId = generalCat.id;
153
+ resolvedCriticality = resolvedCriticality || generalCat.criticalityLevel || 'medium';
154
+ resolvedRisk = resolvedRisk || generalCat.riskClassification || 'class_i';
155
+ } else if (allCats.length > 0) {
156
+ categoryId = allCats[0].id;
157
+ resolvedCriticality = resolvedCriticality || allCats[0].criticalityLevel || 'medium';
158
+ resolvedRisk = resolvedRisk || allCats[0].riskClassification || 'class_i';
159
+ } else {
160
+ const [newCat] = await tx.insert(deviceCategories).values({
161
+ organizationId: validated.data.organizationId,
162
+ name: 'General Medical Equipment',
163
+ code: 'GENERAL',
164
+ riskClassification: 'class_i',
165
+ criticalityLevel: 'medium',
166
+ defaultPmIntervalDays: 365,
167
+ createdByUserId: session.id,
168
+ }).returning();
169
+ categoryId = newCat.id;
170
+ resolvedCriticality = resolvedCriticality || 'medium';
171
+ resolvedRisk = resolvedRisk || 'class_i';
172
+ }
173
+ }
174
+ }
175
+
176
+ const [newDevice] = await tx.insert(devices).values({
177
+ ...validated.data,
178
+ deviceCategoryId: categoryId,
179
+ criticalityLevel: resolvedCriticality,
180
+ riskClassification: resolvedRisk,
181
+ internalCode,
182
+ currentStatusCode: 'operational',
183
+ lifecycleStatus: 'active',
184
+ statusChangedAt: new Date(),
185
+ statusChangedByUserId: session.id,
186
+ createdByUserId: session.id,
187
+ updatedByUserId: session.id,
188
+ }).returning();
189
+
190
+ // Create active QR label
191
+ await tx.insert(deviceQrLabels).values({
192
+ organizationId: validated.data.organizationId,
193
+ deviceId: newDevice.id,
194
+ opaqueReference,
195
+ labelStatus: 'active',
196
+ createdByUserId: session.id,
197
+ });
198
+
199
+ // Initial status history
200
+ await tx.insert(deviceStatusHistory).values({
201
+ organizationId: validated.data.organizationId,
202
+ deviceId: newDevice.id,
203
+ previousStatusCode: null,
204
+ newStatusCode: 'operational',
205
+ reason: 'Device registered',
206
+ changedByUserId: session.id,
207
+ });
208
+
209
+ // Initial location history
210
+ await tx.insert(deviceLocationHistory).values({
211
+ organizationId: validated.data.organizationId,
212
+ deviceId: newDevice.id,
213
+ newHospitalId: validated.data.hospitalId,
214
+ newDepartmentId: validated.data.departmentId,
215
+ newLocationId: validated.data.locationId || null,
216
+ transferReason: 'relocation',
217
+ notes: 'Initial device registration',
218
+ changedByUserId: session.id,
219
+ });
220
+
221
+ await createAuditLog(tx, {
222
+ action: 'CREATE', entityType: 'device', entityId: newDevice.id,
223
+ actorId: session.id, details: { ...validated.data, internalCode, opaqueReference },
224
+ });
225
+
226
+ return { success: true, data: newDevice };
227
+ });
228
+ } catch (error: any) {
229
+ return { success: false, error: error.message };
230
+ }
231
+ }
232
+
233
+ // ── Update ──────────────────────────────────────────────────────────────────────
234
+
235
+ export async function updateDevice(id: string, input: unknown) {
236
+ const session = await requireAuth();
237
+ await requireRole('SYS_ADMIN', 'ORG_ADMIN', 'BIOMED_MGR', 'BIOMED_ENG');
238
+ const validated = updateDeviceSchema.safeParse(input);
239
+ if (!validated.success) return { success: false, error: validated.error.message };
240
+
241
+ try {
242
+ const device = await db.query.devices.findFirst({ where: eq(devices.id, id) });
243
+ if (!device) return { success: false, error: 'Device not found' };
244
+
245
+ await requireScope({
246
+ organizationId: device.organizationId,
247
+ hospitalId: device.hospitalId,
248
+ departmentId: device.departmentId,
249
+ });
250
+
251
+ return await db.transaction(async (tx) => {
252
+ const [updated] = await tx.update(devices)
253
+ .set({ ...validated.data, updatedByUserId: session.id, updatedAt: new Date() })
254
+ .where(eq(devices.id, id))
255
+ .returning();
256
+ await createAuditLog(tx, {
257
+ action: 'UPDATE', entityType: 'device', entityId: id,
258
+ actorId: session.id, details: validated.data,
259
+ });
260
+ return { success: true, data: updated };
261
+ });
262
+ } catch (error: any) {
263
+ return { success: false, error: error.message };
264
+ }
265
+ }
266
+
267
+ // ── Transfer Location ───────────────────────────────────────────────────────────
268
+
269
+ export async function transferDeviceLocation(id: string, input: unknown) {
270
+ const session = await requireAuth();
271
+ await requireRole('SYS_ADMIN', 'ORG_ADMIN', 'BIOMED_MGR', 'BIOMED_ENG');
272
+ const validated = transferDeviceSchema.safeParse(input);
273
+ if (!validated.success) return { success: false, error: validated.error.message };
274
+
275
+ try {
276
+ const device = await db.query.devices.findFirst({ where: eq(devices.id, id) });
277
+ if (!device) return { success: false, error: 'Device not found' };
278
+
279
+ return await db.transaction(async (tx) => {
280
+ // Record location history
281
+ await tx.insert(deviceLocationHistory).values({
282
+ organizationId: device.organizationId,
283
+ deviceId: id,
284
+ previousHospitalId: device.hospitalId,
285
+ previousDepartmentId: device.departmentId,
286
+ previousLocationId: device.locationId,
287
+ newHospitalId: validated.data.destinationHospitalId,
288
+ newDepartmentId: validated.data.destinationDepartmentId,
289
+ newLocationId: validated.data.destinationLocationId || null,
290
+ transferReason: validated.data.transferReason,
291
+ notes: validated.data.notes,
292
+ changedByUserId: session.id,
293
+ });
294
+
295
+ // Update device location
296
+ const [updated] = await tx.update(devices).set({
297
+ hospitalId: validated.data.destinationHospitalId,
298
+ departmentId: validated.data.destinationDepartmentId,
299
+ locationId: validated.data.destinationLocationId || null,
300
+ updatedByUserId: session.id,
301
+ updatedAt: new Date(),
302
+ }).where(eq(devices.id, id)).returning();
303
+
304
+ await createAuditLog(tx, {
305
+ action: 'TRANSFER', entityType: 'device', entityId: id,
306
+ actorId: session.id,
307
+ details: {
308
+ from: { hospitalId: device.hospitalId, departmentId: device.departmentId, locationId: device.locationId },
309
+ to: validated.data,
310
+ },
311
+ });
312
+
313
+ return { success: true, data: updated };
314
+ });
315
+ } catch (error: any) {
316
+ return { success: false, error: error.message };
317
+ }
318
+ }
319
+
320
+ // ── Change Status ───────────────────────────────────────────────────────────────
321
+
322
+ export async function changeDeviceStatus(id: string, input: unknown) {
323
+ const session = await requireAuth();
324
+ await requireRole('SYS_ADMIN', 'BIOMED_MGR', 'BIOMED_ENG', 'BIOMED_TECH');
325
+ const validated = changeDeviceStatusSchema.safeParse(input);
326
+ if (!validated.success) return { success: false, error: validated.error.message };
327
+
328
+ try {
329
+ const device = await db.query.devices.findFirst({ where: eq(devices.id, id) });
330
+ if (!device) return { success: false, error: 'Device not found' };
331
+
332
+ return await db.transaction(async (tx) => {
333
+ // Record status history
334
+ await tx.insert(deviceStatusHistory).values({
335
+ organizationId: device.organizationId,
336
+ deviceId: id,
337
+ previousStatusCode: device.currentStatusCode,
338
+ newStatusCode: validated.data.newStatusCode,
339
+ reason: validated.data.reason,
340
+ notes: validated.data.notes,
341
+ changedByUserId: session.id,
342
+ relatedTicketId: validated.data.ticketId,
343
+ relatedMaintenanceRecordId: validated.data.maintenanceRecordId,
344
+ });
345
+
346
+ // Update device
347
+ const statusUpdate: any = {
348
+ currentStatusCode: validated.data.newStatusCode as any,
349
+ statusChangedAt: new Date(),
350
+ statusChangedByUserId: session.id,
351
+ updatedByUserId: session.id,
352
+ updatedAt: new Date(),
353
+ };
354
+ if (validated.data.limitationsNote) {
355
+ statusUpdate.statusLimitationsNote = validated.data.limitationsNote;
356
+ }
357
+ if (validated.data.newStatusCode === 'operational') {
358
+ statusUpdate.statusLimitationsNote = null;
359
+ }
360
+
361
+ const [updated] = await tx.update(devices)
362
+ .set(statusUpdate)
363
+ .where(eq(devices.id, id))
364
+ .returning();
365
+
366
+ await createAuditLog(tx, {
367
+ action: 'UPDATE', entityType: 'device', entityId: id,
368
+ actorId: session.id,
369
+ details: { previousStatus: device.currentStatusCode, ...validated.data },
370
+ });
371
+
372
+ return { success: true, data: updated };
373
+ });
374
+ } catch (error: any) {
375
+ return { success: false, error: error.message };
376
+ }
377
+ }
378
+
379
+ // ── Decommission ────────────────────────────────────────────────────────────────
380
+
381
+ export async function decommissionDevice(id: string, input: unknown) {
382
+ const session = await requireAuth();
383
+ await requireRole('SYS_ADMIN', 'BIOMED_MGR');
384
+ const validated = decommissionDeviceSchema.safeParse(input);
385
+ if (!validated.success) return { success: false, error: validated.error.message };
386
+
387
+ try {
388
+ const device = await db.query.devices.findFirst({ where: eq(devices.id, id) });
389
+ if (!device) return { success: false, error: 'Device not found' };
390
+ if (device.lifecycleStatus === 'decommissioned') {
391
+ return { success: false, error: 'Device is already decommissioned' };
392
+ }
393
+
394
+ return await db.transaction(async (tx) => {
395
+ await tx.insert(deviceStatusHistory).values({
396
+ organizationId: device.organizationId,
397
+ deviceId: id,
398
+ previousStatusCode: device.currentStatusCode,
399
+ newStatusCode: 'decommissioned',
400
+ reason: validated.data.reason,
401
+ changedByUserId: session.id,
402
+ });
403
+
404
+ const [updated] = await tx.update(devices).set({
405
+ currentStatusCode: 'decommissioned',
406
+ lifecycleStatus: 'decommissioned',
407
+ decommissionedAt: new Date(),
408
+ decommissionedByUserId: session.id,
409
+ decommissionReason: validated.data.reason,
410
+ statusChangedAt: new Date(),
411
+ statusChangedByUserId: session.id,
412
+ updatedByUserId: session.id,
413
+ updatedAt: new Date(),
414
+ }).where(eq(devices.id, id)).returning();
415
+
416
+ await createAuditLog(tx, {
417
+ action: 'DEACTIVATE', entityType: 'device', entityId: id,
418
+ actorId: session.id, details: validated.data,
419
+ });
420
+
421
+ return { success: true, data: updated };
422
+ });
423
+ } catch (error: any) {
424
+ return { success: false, error: error.message };
425
+ }
426
+ }
427
+
428
+ // ── Status & Location History ───────────────────────────────────────────────────
429
+
430
+ export async function getDeviceStatusHistory(deviceId: string) {
431
+ await requireAuth();
432
+ try {
433
+ const data = await db.query.deviceStatusHistory.findMany({
434
+ where: eq(deviceStatusHistory.deviceId, deviceId),
435
+ with: { changedByUser: true },
436
+ orderBy: [desc(deviceStatusHistory.effectiveAt)],
437
+ });
438
+ return { success: true, data };
439
+ } catch (error: any) {
440
+ return { success: false, error: error.message };
441
+ }
442
+ }
443
+
444
+ export async function getDeviceLocationHistory(deviceId: string) {
445
+ await requireAuth();
446
+ try {
447
+ const data = await db.query.deviceLocationHistory.findMany({
448
+ where: eq(deviceLocationHistory.deviceId, deviceId),
449
+ with: { changedByUser: true, newHospital: true, newDepartment: true },
450
+ orderBy: [desc(deviceLocationHistory.effectiveAt)],
451
+ });
452
+ return { success: true, data };
453
+ } catch (error: any) {
454
+ return { success: false, error: error.message };
455
+ }
456
+ }
457
+
458
+ // ── Maintenance History ────────────────────────────────────────────────────────
459
+
460
+ export async function getDeviceMaintenanceHistory(deviceId: string) {
461
+ await requireAuth();
462
+ try {
463
+ const tasks = await db.query.maintenanceTasks.findMany({
464
+ where: eq(maintenanceTasks.deviceId, deviceId),
465
+ with: {
466
+ assignedEngineer: true,
467
+ },
468
+ orderBy: [desc(maintenanceTasks.createdAt)],
469
+ });
470
+
471
+ const records = await db.query.maintenanceRecords.findMany({
472
+ where: eq(maintenanceRecords.deviceId, deviceId),
473
+ orderBy: [desc(maintenanceRecords.completedAt)],
474
+ });
475
+
476
+ return { success: true, data: { tasks, records } };
477
+ } catch (error: any) {
478
+ return { success: false, error: error.message };
479
+ }
480
+ }
481
+
482
+ // ── Device Signatures & Audit Events ───────────────────────────────────────────
483
+
484
+ export async function getDeviceSignatures(deviceId: string) {
485
+ await requireAuth();
486
+ try {
487
+ // 1. Find all maintenance records for this device
488
+ const records = await db.query.maintenanceRecords.findMany({
489
+ where: eq(maintenanceRecords.deviceId, deviceId),
490
+ columns: { id: true },
491
+ });
492
+ const recordIds = records.map((r) => r.id);
493
+
494
+ // 2. Find all service tickets for this device (with number + title)
495
+ const ticketRows = await db.query.serviceTickets.findMany({
496
+ where: eq(serviceTickets.deviceId, deviceId),
497
+ columns: { id: true, ticketNumber: true, title: true },
498
+ });
499
+ const ticketIds = ticketRows.map((t) => t.id);
500
+ const ticketMap = new Map(ticketRows.map((t) => [t.id, { ticketNumber: t.ticketNumber, title: t.title }]));
501
+
502
+ // 2b. Find all maintenance tasks for this device (with number + title + maintenanceType)
503
+ const taskRows = await db.query.maintenanceTasks.findMany({
504
+ where: eq(maintenanceTasks.deviceId, deviceId),
505
+ columns: { id: true, taskNumber: true, title: true, maintenanceType: true },
506
+ });
507
+ const taskMap = new Map(taskRows.map((t) => [t.id, { taskNumber: t.taskNumber, title: t.title, maintenanceType: t.maintenanceType }]));
508
+
509
+ // 2c. Build a map from maintenance record ID -> task info (including task ID for href)
510
+ const recordTaskMap = new Map<string, { taskId: string; taskNumber: string; title: string; maintenanceType: string | null }>();
511
+ if (recordIds.length > 0) {
512
+ // Each maintenance record belongs to a task
513
+ const recordsWithTask = await db.query.maintenanceRecords.findMany({
514
+ where: inArray(maintenanceRecords.id, recordIds),
515
+ columns: { id: true, maintenanceTaskId: true },
516
+ });
517
+ for (const rec of recordsWithTask) {
518
+ if (rec.maintenanceTaskId) {
519
+ const taskInfo = taskMap.get(rec.maintenanceTaskId);
520
+ if (taskInfo) {
521
+ recordTaskMap.set(rec.id, { taskId: rec.maintenanceTaskId, ...taskInfo });
522
+ }
523
+ }
524
+ }
525
+ }
526
+
527
+ // 3. Fetch signatures for the device itself, its maintenance records, or its service tickets
528
+ const conditions = [
529
+ and(
530
+ eq(electronicSignatures.entityType, 'device_status_change'),
531
+ eq(electronicSignatures.entityId, deviceId),
532
+ ),
533
+ ];
534
+
535
+ if (recordIds.length > 0) {
536
+ conditions.push(
537
+ and(
538
+ eq(electronicSignatures.entityType, 'maintenance_record'),
539
+ inArray(electronicSignatures.entityId, recordIds),
540
+ ),
541
+ );
542
+ }
543
+
544
+ if (ticketIds.length > 0) {
545
+ conditions.push(
546
+ and(
547
+ eq(electronicSignatures.entityType, 'ticket_resolution'),
548
+ inArray(electronicSignatures.entityId, ticketIds),
549
+ ),
550
+ );
551
+ }
552
+
553
+ const signatures = await db.query.electronicSignatures.findMany({
554
+ where: or(...conditions),
555
+ with: {
556
+ signerUser: true,
557
+ },
558
+ orderBy: [desc(electronicSignatures.signedAt)],
559
+ });
560
+
561
+ // 4. Enrich each signature with source metadata
562
+ const enrichedSignatures = signatures.map((sig) => {
563
+ let sourceLabel = '';
564
+ let sourceNumber = '';
565
+ let sourceHref = '';
566
+ let sourceType: string = sig.entityType || 'unknown';
567
+
568
+ if (sig.entityType === 'ticket_resolution') {
569
+ const ticket = ticketMap.get(sig.entityId);
570
+ if (ticket) {
571
+ sourceLabel = ticket.title || 'Service Ticket';
572
+ sourceNumber = ticket.ticketNumber || '';
573
+ sourceHref = `/tickets/${sig.entityId}`;
574
+ } else {
575
+ sourceLabel = 'Service Ticket';
576
+ sourceHref = `/tickets/${sig.entityId}`;
577
+ }
578
+ } else if (sig.entityType === 'maintenance_record') {
579
+ const task = recordTaskMap.get(sig.entityId);
580
+ if (task) {
581
+ sourceLabel = task.title || 'Maintenance Task';
582
+ sourceNumber = task.taskNumber || '';
583
+ sourceHref = `/maintenance/tasks/${task.taskId}`;
584
+ if (task.maintenanceType === 'preventive_maintenance') {
585
+ sourceType = 'preventive_maintenance';
586
+ } else if (task.maintenanceType === 'calibration') {
587
+ sourceType = 'calibration';
588
+ } else {
589
+ sourceType = 'corrective_maintenance';
590
+ }
591
+ } else {
592
+ sourceLabel = 'Maintenance Record';
593
+ sourceType = 'corrective_maintenance';
594
+ }
595
+ } else if (sig.entityType === 'device_status_change') {
596
+ sourceLabel = 'Device Status Change';
597
+ sourceType = 'device_status_change';
598
+ } else if (sig.entityType === 'engineer_round') {
599
+ sourceLabel = 'Daily Round / Inspection';
600
+ sourceType = 'engineer_round';
601
+ }
602
+
603
+ return {
604
+ ...sig,
605
+ sourceType,
606
+ sourceLabel,
607
+ sourceNumber,
608
+ sourceHref,
609
+ };
610
+ });
611
+
612
+ // 5. Fetch associated signature events (hash chain audit)
613
+ const sigIds = signatures.map((s) => s.id);
614
+ let events: any[] = [];
615
+ if (sigIds.length > 0) {
616
+ events = await db.query.signatureEvents.findMany({
617
+ where: inArray(signatureEvents.signatureId, sigIds),
618
+ orderBy: [desc(signatureEvents.timestamp)],
619
+ });
620
+ }
621
+
622
+ return { success: true, data: { signatures: enrichedSignatures, events } };
623
+ } catch (error: any) {
624
+ return { success: false, error: error.message };
625
+ }
626
+ }
627
+
628
+ // ── Device Documents & Attachments ─────────────────────────────────────────────
629
+
630
+ export async function getDeviceDocuments(deviceId: string) {
631
+ await requireAuth();
632
+ try {
633
+ const documents = await db.query.deviceAttachments.findMany({
634
+ where: eq(deviceAttachments.deviceId, deviceId),
635
+ with: {
636
+ uploadedByUser: true,
637
+ },
638
+ orderBy: [desc(deviceAttachments.uploadedAt)],
639
+ });
640
+ return { success: true, data: documents };
641
+ } catch (error: any) {
642
+ return { success: false, error: error.message };
643
+ }
644
+ }
645
+
646
+ // ── Role-Shaped Device Profile (Spec §5) ───────────────────────────────────────
647
+
648
+ export type DeviceProfileLevel = 'staff' | 'department_manager' | 'technician' | 'biomedical_engineer' | 'admin';
649
+
650
+ export interface RoleShapedDeviceProfile {
651
+ device: any;
652
+ profileLevel: DeviceProfileLevel;
653
+ visibleSections: string[];
654
+ allowedActions: string[];
655
+ }
656
+
657
+ export async function getDeviceProfile(deviceId: string): Promise<{
658
+ success: boolean;
659
+ data?: RoleShapedDeviceProfile;
660
+ error?: string;
661
+ }> {
662
+ const session = await requireAuth();
663
+ try {
664
+ const device = await db.query.devices.findFirst({
665
+ where: eq(devices.id, deviceId),
666
+ with: {
667
+ organization: true,
668
+ hospital: true,
669
+ department: true,
670
+ location: true,
671
+ deviceCategory: true,
672
+ manufacturer: true,
673
+ deviceModel: true,
674
+ assignedEngineer: true,
675
+ },
676
+ });
677
+
678
+ if (!device) return { success: false, error: 'Device not found' };
679
+
680
+ const roles = session.roles || [];
681
+ const isSysAdmin = roles.includes('SYS_ADMIN');
682
+ const isOrgAdmin = roles.includes('ORG_ADMIN');
683
+ const isBiomedMgr = roles.includes('BIOMED_MGR');
684
+ const isBiomedEng = roles.includes('BIOMED_ENG');
685
+ const isBiomedTech = roles.includes('BIOMED_TECH');
686
+ const isDeptMgr = roles.includes('DEPT_MGR') || roles.includes('CLINICAL_HEAD');
687
+
688
+ let profileLevel: DeviceProfileLevel = 'staff';
689
+ let visibleSections = ['overview', 'active-tickets', 'documents'];
690
+ let allowedActions = ['report_problem', 'view_qr'];
691
+
692
+ if (isSysAdmin || isBiomedMgr || isBiomedEng) {
693
+ profileLevel = isSysAdmin && !isBiomedEng && !isBiomedMgr ? 'admin' : 'biomedical_engineer';
694
+ visibleSections = [
695
+ 'overview',
696
+ 'technical',
697
+ 'maintenance',
698
+ 'signatures',
699
+ 'status-history',
700
+ 'location-history',
701
+ 'documents',
702
+ ];
703
+ allowedActions = [
704
+ 'report_problem',
705
+ 'view_qr',
706
+ 'edit',
707
+ 'transfer',
708
+ 'change_status',
709
+ 'decommission',
710
+ 'create_maintenance',
711
+ ];
712
+ } else if (isBiomedTech) {
713
+ profileLevel = 'technician';
714
+ visibleSections = [
715
+ 'overview',
716
+ 'technical',
717
+ 'maintenance',
718
+ 'status-history',
719
+ 'location-history',
720
+ 'documents',
721
+ ];
722
+ allowedActions = ['report_problem', 'view_qr', 'change_status', 'perform_work'];
723
+ } else if (isDeptMgr) {
724
+ profileLevel = 'department_manager';
725
+ visibleSections = ['overview', 'active-tickets', 'maintenance-summary', 'documents'];
726
+ allowedActions = ['report_problem', 'view_qr'];
727
+ } else {
728
+ // Staff / Doctor view: simple operational safety focus
729
+ profileLevel = 'staff';
730
+ visibleSections = ['overview', 'active-tickets', 'documents'];
731
+ allowedActions = ['report_problem', 'view_qr'];
732
+ }
733
+
734
+ return {
735
+ success: true,
736
+ data: {
737
+ device,
738
+ profileLevel,
739
+ visibleSections,
740
+ allowedActions,
741
+ },
742
+ };
743
+ } catch (error: any) {
744
+ return { success: false, error: error.message };
745
+ }
746
+ }
747
+
748
+