@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.
- package/LICENSE +22 -0
- package/README.md +203 -2
- package/drizzle.config.ts +11 -0
- package/next.config.ts +51 -0
- package/package.json +99 -3
- package/postcss.config.mjs +7 -0
- package/public/hospital_demo_devices.csv +32 -0
- package/public/icons/icon-192.png +0 -0
- package/public/icons/icon-512.png +0 -0
- package/public/icons/icon-maskable-512.png +0 -0
- package/public/manifest.webmanifest +31 -0
- package/public/sw.js +177 -0
- package/src/app/(auth)/layout.tsx +20 -0
- package/src/app/(auth)/login/page.tsx +135 -0
- package/src/app/(dashboard)/admin/audit-logs/page.tsx +178 -0
- package/src/app/(dashboard)/admin/data/page.tsx +37 -0
- package/src/app/(dashboard)/admin/departments/[deptId]/edit/page.tsx +206 -0
- package/src/app/(dashboard)/admin/departments/[deptId]/page.tsx +71 -0
- package/src/app/(dashboard)/admin/departments/new/page.tsx +6 -0
- package/src/app/(dashboard)/admin/departments/page.tsx +6 -0
- package/src/app/(dashboard)/admin/general/page.tsx +374 -0
- package/src/app/(dashboard)/admin/hospitals/[hospitalId]/edit/page.tsx +304 -0
- package/src/app/(dashboard)/admin/hospitals/[hospitalId]/page.tsx +94 -0
- package/src/app/(dashboard)/admin/hospitals/new/page.tsx +302 -0
- package/src/app/(dashboard)/admin/hospitals/page.tsx +6 -0
- package/src/app/(dashboard)/admin/layout.tsx +49 -0
- package/src/app/(dashboard)/admin/organizations/[orgId]/edit/page.tsx +172 -0
- package/src/app/(dashboard)/admin/organizations/[orgId]/page.tsx +82 -0
- package/src/app/(dashboard)/admin/organizations/new/page.tsx +150 -0
- package/src/app/(dashboard)/admin/organizations/page.tsx +6 -0
- package/src/app/(dashboard)/admin/page.tsx +258 -0
- package/src/app/(dashboard)/admin/roles/page.tsx +153 -0
- package/src/app/(dashboard)/admin/settings/page.tsx +69 -0
- package/src/app/(dashboard)/admin/users/[userId]/edit/page.tsx +153 -0
- package/src/app/(dashboard)/admin/users/[userId]/page.tsx +317 -0
- package/src/app/(dashboard)/admin/users/invite/page.tsx +3 -0
- package/src/app/(dashboard)/admin/users/new/page.tsx +5 -0
- package/src/app/(dashboard)/admin/users/page.tsx +23 -0
- package/src/app/(dashboard)/dashboard/page.tsx +462 -0
- package/src/app/(dashboard)/departments/[deptId]/page.tsx +39 -0
- package/src/app/(dashboard)/departments/new/page.tsx +330 -0
- package/src/app/(dashboard)/departments/page.tsx +52 -0
- package/src/app/(dashboard)/devices/[id]/edit/page.tsx +131 -0
- package/src/app/(dashboard)/devices/[id]/page.tsx +408 -0
- package/src/app/(dashboard)/devices/[id]/qr/page.tsx +54 -0
- package/src/app/(dashboard)/devices/new/page.tsx +382 -0
- package/src/app/(dashboard)/devices/page.tsx +80 -0
- package/src/app/(dashboard)/engineering-team/page.tsx +41 -0
- package/src/app/(dashboard)/layout.tsx +43 -0
- package/src/app/(dashboard)/maintenance/checklists/page.tsx +57 -0
- package/src/app/(dashboard)/maintenance/page.tsx +231 -0
- package/src/app/(dashboard)/maintenance/plans/page.tsx +142 -0
- package/src/app/(dashboard)/maintenance/tasks/[id]/page.tsx +997 -0
- package/src/app/(dashboard)/maintenance/tasks/page.tsx +119 -0
- package/src/app/(dashboard)/more/page.tsx +310 -0
- package/src/app/(dashboard)/my-department/page.tsx +151 -0
- package/src/app/(dashboard)/notifications/notification-list.tsx +103 -0
- package/src/app/(dashboard)/notifications/page.tsx +59 -0
- package/src/app/(dashboard)/profile/page.tsx +27 -0
- package/src/app/(dashboard)/reports/costs/page.tsx +127 -0
- package/src/app/(dashboard)/reports/history/page.tsx +105 -0
- package/src/app/(dashboard)/reports/inventory/page.tsx +116 -0
- package/src/app/(dashboard)/reports/maintenance/page.tsx +136 -0
- package/src/app/(dashboard)/reports/page.tsx +120 -0
- package/src/app/(dashboard)/reports/tickets/page.tsx +139 -0
- package/src/app/(dashboard)/reports/workload/page.tsx +135 -0
- package/src/app/(dashboard)/rounds/[id]/page.tsx +197 -0
- package/src/app/(dashboard)/rounds/history/page.tsx +82 -0
- package/src/app/(dashboard)/rounds/page.tsx +107 -0
- package/src/app/(dashboard)/scan/[code]/page.tsx +154 -0
- package/src/app/(dashboard)/scan/page.tsx +73 -0
- package/src/app/(dashboard)/team/page.tsx +42 -0
- package/src/app/(dashboard)/tickets/[id]/page.tsx +465 -0
- package/src/app/(dashboard)/tickets/create/page.tsx +722 -0
- package/src/app/(dashboard)/tickets/page.tsx +55 -0
- package/src/app/(dashboard)/tickets/triage/page.tsx +161 -0
- package/src/app/api/admin/data/export/route.ts +316 -0
- package/src/app/api/auth/[...nextauth]/route.ts +3 -0
- package/src/app/api/health/route.ts +46 -0
- package/src/app/api/notifications/sse/route.ts +91 -0
- package/src/app/api/notifications/subscribe/route.ts +54 -0
- package/src/app/api/notifications/vapid-key/route.ts +7 -0
- package/src/app/api/reports/export/route.ts +102 -0
- package/src/app/api/tickets/[id]/attachments/route.ts +129 -0
- package/src/app/api/tickets/[id]/live-sync/route.ts +52 -0
- package/src/app/error.tsx +54 -0
- package/src/app/globals.css +89 -0
- package/src/app/layout.tsx +59 -0
- package/src/app/not-found.tsx +32 -0
- package/src/app/page.tsx +5 -0
- package/src/components/admin/add-department-user-dialog.tsx +759 -0
- package/src/components/admin/add-engineer-dialog.tsx +773 -0
- package/src/components/admin/add-user-type-dialog.tsx +89 -0
- package/src/components/admin/audit-log-export.tsx +113 -0
- package/src/components/admin/audit-log-filters.tsx +255 -0
- package/src/components/admin/audit-log-table.tsx +383 -0
- package/src/components/admin/data-management/danger-zone.tsx +301 -0
- package/src/components/admin/data-management/data-management-tabs.tsx +61 -0
- package/src/components/admin/data-management/export-center.tsx +301 -0
- package/src/components/admin/data-management/import-wizard.tsx +558 -0
- package/src/components/admin/settings-forms/features-form.tsx +115 -0
- package/src/components/admin/settings-forms/health-panel.tsx +182 -0
- package/src/components/admin/settings-forms/localization-form.tsx +203 -0
- package/src/components/admin/settings-forms/retention-form.tsx +164 -0
- package/src/components/admin/settings-forms/security-form.tsx +186 -0
- package/src/components/admin/system-settings-tabs.tsx +88 -0
- package/src/components/admin/user-role-dialog.tsx +293 -0
- package/src/components/admin/user-status-dialog.tsx +166 -0
- package/src/components/admin/users-page-client.tsx +514 -0
- package/src/components/dashboard/action-buttons.tsx +93 -0
- package/src/components/dashboard/admin-alerts.tsx +86 -0
- package/src/components/dashboard/availability-alerts.tsx +65 -0
- package/src/components/dashboard/maintenance-due-list.tsx +87 -0
- package/src/components/dashboard/round-widget.tsx +110 -0
- package/src/components/dashboard/stat-card.tsx +38 -0
- package/src/components/dashboard/ticket-list-compact.tsx +86 -0
- package/src/components/departments/department-cards-view.tsx +244 -0
- package/src/components/departments/department-detail-view.tsx +467 -0
- package/src/components/departments/department-visuals.tsx +190 -0
- package/src/components/departments/my-department-view.tsx +333 -0
- package/src/components/devices/change-status-dialog.tsx +146 -0
- package/src/components/devices/device-action-buttons.tsx +125 -0
- package/src/components/devices/device-availability-banner.tsx +59 -0
- package/src/components/devices/device-badges.tsx +55 -0
- package/src/components/devices/device-documents-tab.tsx +93 -0
- package/src/components/devices/device-maintenance-tab.tsx +113 -0
- package/src/components/devices/device-mini-qr.tsx +109 -0
- package/src/components/devices/device-qr-card.tsx +187 -0
- package/src/components/devices/device-signatures-tab.tsx +607 -0
- package/src/components/devices/device-tickets-tab.tsx +139 -0
- package/src/components/devices/device-timelines.tsx +124 -0
- package/src/components/devices/qr-camera-scanner.tsx +167 -0
- package/src/components/devices/qr-code-display.tsx +139 -0
- package/src/components/devices/quick-add-category-dialog.tsx +135 -0
- package/src/components/devices/quick-add-manufacturer-dialog.tsx +212 -0
- package/src/components/devices/transfer-device-dialog.tsx +190 -0
- package/src/components/layout/header.tsx +80 -0
- package/src/components/layout/mobile-nav.tsx +91 -0
- package/src/components/layout/more-item-badge.tsx +15 -0
- package/src/components/layout/nav-badge.tsx +72 -0
- package/src/components/layout/sidebar.tsx +297 -0
- package/src/components/maintenance/maintenance-badges.tsx +579 -0
- package/src/components/maintenance/maintenance-nav.tsx +107 -0
- package/src/components/maintenance/parts-costs-manager.tsx +909 -0
- package/src/components/maintenance/signature-card.tsx +413 -0
- package/src/components/maintenance/task-action-bar.tsx +955 -0
- package/src/components/notifications/notification-bell.tsx +367 -0
- package/src/components/notifications/notification-item.tsx +93 -0
- package/src/components/notifications/notification-preferences.tsx +182 -0
- package/src/components/profile/user-profile-view.tsx +626 -0
- package/src/components/providers/nav-counts-provider.tsx +235 -0
- package/src/components/providers/session-provider.tsx +7 -0
- package/src/components/providers/theme-provider.tsx +124 -0
- package/src/components/pwa/install-prompt.tsx +82 -0
- package/src/components/pwa/sw-register.tsx +43 -0
- package/src/components/reports/export-button.tsx +62 -0
- package/src/components/reports/filter-chips.tsx +47 -0
- package/src/components/reports/summary-cards.tsx +40 -0
- package/src/components/reports/transparency-header.tsx +54 -0
- package/src/components/rounds/department-visit-sheet.tsx +199 -0
- package/src/components/rounds/mention-textarea.tsx +187 -0
- package/src/components/rounds/round-calendar.tsx +233 -0
- package/src/components/rounds/round-department-list.tsx +281 -0
- package/src/components/rounds/round-history-client.tsx +218 -0
- package/src/components/rounds/start-round-card.tsx +184 -0
- package/src/components/shared/confirm-dialog.tsx +67 -0
- package/src/components/shared/data-table.tsx +104 -0
- package/src/components/shared/page-header.tsx +20 -0
- package/src/components/shared/sign-out-button.tsx +52 -0
- package/src/components/shared/status-badge.tsx +42 -0
- package/src/components/shared/table-search.tsx +55 -0
- package/src/components/signatures/sign-action-dialog.tsx +253 -0
- package/src/components/signatures/signature-history.tsx +121 -0
- package/src/components/signatures/signature-status-panel.tsx +164 -0
- package/src/components/team/department-coverage.tsx +141 -0
- package/src/components/team/edit-engineer-dialog.tsx +242 -0
- package/src/components/team/engineer-card.tsx +180 -0
- package/src/components/team/engineer-details-dialog.tsx +432 -0
- package/src/components/team/schedule-calendar.tsx +204 -0
- package/src/components/team/staff-engineer-team-view.tsx +368 -0
- package/src/components/team/team-header-stats.tsx +88 -0
- package/src/components/team/team-page-client.tsx +216 -0
- package/src/components/theme/theme-selector-card.tsx +63 -0
- package/src/components/theme/theme-toggle.tsx +65 -0
- package/src/components/tickets/staff-status-label.tsx +58 -0
- package/src/components/tickets/staff-ticket-card.tsx +109 -0
- package/src/components/tickets/staff-ticket-progress-tracker.tsx +405 -0
- package/src/components/tickets/staff-tickets-view.tsx +182 -0
- package/src/components/tickets/ticket-action-buttons.tsx +873 -0
- package/src/components/tickets/ticket-auto-refresh.tsx +197 -0
- package/src/components/tickets/ticket-badges.tsx +43 -0
- package/src/components/tickets/ticket-card.tsx +197 -0
- package/src/components/tickets/ticket-cards-view.tsx +395 -0
- package/src/components/tickets/ticket-comment-section.tsx +684 -0
- package/src/components/tickets/ticket-dispatch-status.tsx +184 -0
- package/src/components/tickets/ticket-list-auto-refresh.tsx +55 -0
- package/src/components/tickets/ticket-reporter-profile.tsx +235 -0
- package/src/components/tickets/ticket-signatures-panel.tsx +32 -0
- package/src/components/tickets/ticket-timeline.tsx +131 -0
- package/src/components/tickets/ticket-triage-panel.tsx +124 -0
- package/src/components/tickets/tickets-nav.tsx +107 -0
- package/src/components/ui/avatar.tsx +43 -0
- package/src/components/ui/badge.tsx +34 -0
- package/src/components/ui/button.tsx +58 -0
- package/src/components/ui/card.tsx +77 -0
- package/src/components/ui/checkbox.tsx +31 -0
- package/src/components/ui/dialog.tsx +123 -0
- package/src/components/ui/dropdown-menu.tsx +126 -0
- package/src/components/ui/form.tsx +179 -0
- package/src/components/ui/input.tsx +24 -0
- package/src/components/ui/label.tsx +27 -0
- package/src/components/ui/popover.tsx +34 -0
- package/src/components/ui/progress.tsx +36 -0
- package/src/components/ui/scroll-area.tsx +47 -0
- package/src/components/ui/select.tsx +160 -0
- package/src/components/ui/separator.tsx +25 -0
- package/src/components/ui/sheet.tsx +131 -0
- package/src/components/ui/switch.tsx +30 -0
- package/src/components/ui/table.tsx +121 -0
- package/src/components/ui/tabs.tsx +62 -0
- package/src/components/ui/textarea.tsx +23 -0
- package/src/components/ui/tooltip.tsx +27 -0
- package/src/lib/actions/__tests__/devices.test.ts +176 -0
- package/src/lib/actions/__tests__/signatures.test.ts +303 -0
- package/src/lib/actions/__tests__/tickets.test.ts +243 -0
- package/src/lib/actions/audit-logs.ts +298 -0
- package/src/lib/actions/checklists.ts +429 -0
- package/src/lib/actions/dashboard.ts +358 -0
- package/src/lib/actions/data-management.ts +723 -0
- package/src/lib/actions/departments.ts +369 -0
- package/src/lib/actions/device-categories.ts +117 -0
- package/src/lib/actions/devices.ts +748 -0
- package/src/lib/actions/engineer-rounds.ts +973 -0
- package/src/lib/actions/engineers.ts +285 -0
- package/src/lib/actions/hospitals.ts +148 -0
- package/src/lib/actions/locations.ts +115 -0
- package/src/lib/actions/maintenance-plans.ts +316 -0
- package/src/lib/actions/maintenance-tasks.ts +415 -0
- package/src/lib/actions/manufacturers.ts +132 -0
- package/src/lib/actions/nav-counts.ts +144 -0
- package/src/lib/actions/notifications.ts +136 -0
- package/src/lib/actions/organizations.ts +99 -0
- package/src/lib/actions/qr.ts +147 -0
- package/src/lib/actions/report-history.ts +77 -0
- package/src/lib/actions/reports.ts +192 -0
- package/src/lib/actions/roles.ts +32 -0
- package/src/lib/actions/signature-auth.ts +377 -0
- package/src/lib/actions/signatures.ts +532 -0
- package/src/lib/actions/system-settings.ts +274 -0
- package/src/lib/actions/tickets.ts +1445 -0
- package/src/lib/actions/users.ts +740 -0
- package/src/lib/audit/index.ts +103 -0
- package/src/lib/auth/__tests__/rbac.test.ts +33 -0
- package/src/lib/auth/index.ts +338 -0
- package/src/lib/auth/password.ts +10 -0
- package/src/lib/auth/rbac.ts +103 -0
- package/src/lib/auth/types.ts +57 -0
- package/src/lib/constants/departments.ts +16 -0
- package/src/lib/constants/manufacturers.ts +32 -0
- package/src/lib/db/index.ts +23 -0
- package/src/lib/db/schema/audit-logs.ts +42 -0
- package/src/lib/db/schema/departments.ts +39 -0
- package/src/lib/db/schema/device-categories.ts +38 -0
- package/src/lib/db/schema/devices.ts +195 -0
- package/src/lib/db/schema/engineer-profiles.ts +63 -0
- package/src/lib/db/schema/engineer-rounds.ts +115 -0
- package/src/lib/db/schema/enums.ts +148 -0
- package/src/lib/db/schema/hospitals.ts +34 -0
- package/src/lib/db/schema/index.ts +24 -0
- package/src/lib/db/schema/locations.ts +46 -0
- package/src/lib/db/schema/maintenance-plans.ts +99 -0
- package/src/lib/db/schema/maintenance-records.ts +161 -0
- package/src/lib/db/schema/maintenance-tasks.ts +196 -0
- package/src/lib/db/schema/manufacturers.ts +60 -0
- package/src/lib/db/schema/notifications.ts +48 -0
- package/src/lib/db/schema/organizations.ts +24 -0
- package/src/lib/db/schema/report-history.ts +28 -0
- package/src/lib/db/schema/roles.ts +59 -0
- package/src/lib/db/schema/sessions.ts +46 -0
- package/src/lib/db/schema/signature-events.ts +48 -0
- package/src/lib/db/schema/signature-policies.ts +60 -0
- package/src/lib/db/schema/signatures.ts +87 -0
- package/src/lib/db/schema/tickets.ts +169 -0
- package/src/lib/db/schema/user-assignments.ts +85 -0
- package/src/lib/db/schema/users.ts +39 -0
- package/src/lib/db/seed.ts +131 -0
- package/src/lib/logger/__tests__/logger.test.ts +154 -0
- package/src/lib/logger/formatters.ts +159 -0
- package/src/lib/logger/index.ts +184 -0
- package/src/lib/logger/types.ts +48 -0
- package/src/lib/notifications/create.ts +71 -0
- package/src/lib/notifications/dispatcher.ts +490 -0
- package/src/lib/notifications/index.ts +7 -0
- package/src/lib/notifications/push-sender.ts +128 -0
- package/src/lib/notifications/push.ts +64 -0
- package/src/lib/notifications/triggers.ts +166 -0
- package/src/lib/utils/__tests__/crypto.test.ts +30 -0
- package/src/lib/utils/__tests__/export.test.ts +55 -0
- package/src/lib/utils/__tests__/nav-badge.test.ts +147 -0
- package/src/lib/utils/__tests__/staff-status.test.ts +50 -0
- package/src/lib/utils/attestations.ts +19 -0
- package/src/lib/utils/crypto.ts +18 -0
- package/src/lib/utils/csv-parser.ts +181 -0
- package/src/lib/utils/export.ts +45 -0
- package/src/lib/utils/nav-badge.ts +225 -0
- package/src/lib/utils/sound.ts +152 -0
- package/src/lib/utils/staff-status.ts +115 -0
- package/src/lib/utils.ts +6 -0
- package/src/lib/validators/__tests__/auth.test.ts +127 -0
- package/src/lib/validators/__tests__/data-management.test.ts +182 -0
- package/src/lib/validators/__tests__/devices-profile.test.ts +129 -0
- package/src/lib/validators/__tests__/devices.test.ts +98 -0
- package/src/lib/validators/__tests__/engineer-rounds.test.ts +170 -0
- package/src/lib/validators/__tests__/maintenance.test.ts +178 -0
- package/src/lib/validators/__tests__/signatures.test.ts +154 -0
- package/src/lib/validators/__tests__/system-settings.test.ts +119 -0
- package/src/lib/validators/__tests__/tickets.test.ts +176 -0
- package/src/lib/validators/__tests__/users.test.ts +92 -0
- package/src/lib/validators/auth.ts +32 -0
- package/src/lib/validators/data-management.ts +67 -0
- package/src/lib/validators/departments.ts +14 -0
- package/src/lib/validators/devices.ts +94 -0
- package/src/lib/validators/engineer-rounds.ts +70 -0
- package/src/lib/validators/hospitals.ts +17 -0
- package/src/lib/validators/locations.ts +15 -0
- package/src/lib/validators/maintenance.ts +211 -0
- package/src/lib/validators/organizations.ts +11 -0
- package/src/lib/validators/reports.ts +31 -0
- package/src/lib/validators/signatures.ts +49 -0
- package/src/lib/validators/system-settings.ts +55 -0
- package/src/lib/validators/tickets.ts +125 -0
- package/src/lib/validators/users.ts +43 -0
- package/src/middleware.ts +45 -0
- package/tailwind.config.ts +76 -0
- package/tsconfig.json +28 -0
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
'use server';
|
|
2
|
+
|
|
3
|
+
import { db } from '@/lib/db';
|
|
4
|
+
import { departments, hospitals, devices, serviceTickets, locations, users } from '@/lib/db/schema';
|
|
5
|
+
import { requireAuth, requireRole, requireScope } from '@/lib/auth/rbac';
|
|
6
|
+
import { createAuditLog } from '@/lib/audit';
|
|
7
|
+
import { createDepartmentSchema, updateDepartmentSchema } from '@/lib/validators/departments';
|
|
8
|
+
import { DEFAULT_HOSPITAL_DEPARTMENTS } from '@/lib/constants/departments';
|
|
9
|
+
import { eq, and, sql, count } from 'drizzle-orm';
|
|
10
|
+
|
|
11
|
+
export async function getDepartments(filters?: { hospitalId?: string; organizationId?: string } | string) {
|
|
12
|
+
await requireAuth();
|
|
13
|
+
try {
|
|
14
|
+
let whereClause = undefined;
|
|
15
|
+
if (typeof filters === 'string') {
|
|
16
|
+
whereClause = eq(departments.hospitalId, filters);
|
|
17
|
+
} else if (filters?.hospitalId) {
|
|
18
|
+
whereClause = eq(departments.hospitalId, filters.hospitalId);
|
|
19
|
+
} else if (filters?.organizationId) {
|
|
20
|
+
whereClause = eq(departments.organizationId, filters.organizationId);
|
|
21
|
+
}
|
|
22
|
+
const data = await db.query.departments.findMany({ where: whereClause });
|
|
23
|
+
return { success: true, data };
|
|
24
|
+
} catch (error: any) {
|
|
25
|
+
return { success: false, error: error.message };
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function getDepartmentById(id: string) {
|
|
30
|
+
await requireAuth();
|
|
31
|
+
try {
|
|
32
|
+
const data = await db.query.departments.findFirst({
|
|
33
|
+
where: eq(departments.id, id),
|
|
34
|
+
});
|
|
35
|
+
return { success: true, data };
|
|
36
|
+
} catch (error: any) {
|
|
37
|
+
return { success: false, error: error.message };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function createDepartment(input: unknown) {
|
|
42
|
+
const session = await requireAuth();
|
|
43
|
+
const validated = createDepartmentSchema.safeParse(input);
|
|
44
|
+
if (!validated.success) return { success: false, error: validated.error.message };
|
|
45
|
+
|
|
46
|
+
await requireRole('SYS_ADMIN', 'ORG_ADMIN');
|
|
47
|
+
await requireScope({ organizationId: validated.data.organizationId, hospitalId: validated.data.hospitalId });
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const dataToInsert = {
|
|
51
|
+
...validated.data,
|
|
52
|
+
managerUserId: validated.data.managerUserId ? validated.data.managerUserId : null,
|
|
53
|
+
};
|
|
54
|
+
return await db.transaction(async (tx) => {
|
|
55
|
+
const [newDept] = await tx.insert(departments).values(dataToInsert).returning();
|
|
56
|
+
await createAuditLog(tx, {
|
|
57
|
+
action: 'CREATE',
|
|
58
|
+
entityType: 'department',
|
|
59
|
+
entityId: newDept.id,
|
|
60
|
+
actorId: session.id,
|
|
61
|
+
details: dataToInsert,
|
|
62
|
+
});
|
|
63
|
+
return { success: true, data: newDept };
|
|
64
|
+
});
|
|
65
|
+
} catch (error: any) {
|
|
66
|
+
return { success: false, error: error.message };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function updateDepartment(id: string, input: unknown) {
|
|
71
|
+
const session = await requireAuth();
|
|
72
|
+
const validated = updateDepartmentSchema.safeParse(input);
|
|
73
|
+
if (!validated.success) return { success: false, error: validated.error.message };
|
|
74
|
+
|
|
75
|
+
await requireRole('SYS_ADMIN', 'ORG_ADMIN');
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
const dept = await db.query.departments.findFirst({ where: eq(departments.id, id) });
|
|
79
|
+
if (!dept) return { success: false, error: 'Department not found' };
|
|
80
|
+
await requireScope({ organizationId: dept.organizationId, hospitalId: dept.hospitalId, departmentId: id });
|
|
81
|
+
|
|
82
|
+
const dataToUpdate = {
|
|
83
|
+
...validated.data,
|
|
84
|
+
...(validated.data.managerUserId !== undefined
|
|
85
|
+
? { managerUserId: validated.data.managerUserId ? validated.data.managerUserId : null }
|
|
86
|
+
: {}),
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
return await db.transaction(async (tx) => {
|
|
90
|
+
const [updated] = await tx.update(departments).set(dataToUpdate).where(eq(departments.id, id)).returning();
|
|
91
|
+
await createAuditLog(tx, {
|
|
92
|
+
action: 'UPDATE',
|
|
93
|
+
entityType: 'department',
|
|
94
|
+
entityId: id,
|
|
95
|
+
actorId: session.id,
|
|
96
|
+
details: dataToUpdate,
|
|
97
|
+
});
|
|
98
|
+
return { success: true, data: updated };
|
|
99
|
+
});
|
|
100
|
+
} catch (error: any) {
|
|
101
|
+
return { success: false, error: error.message };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function archiveDepartment(id: string) {
|
|
106
|
+
const session = await requireAuth();
|
|
107
|
+
await requireRole('SYS_ADMIN', 'ORG_ADMIN');
|
|
108
|
+
|
|
109
|
+
try {
|
|
110
|
+
const dept = await db.query.departments.findFirst({ where: eq(departments.id, id) });
|
|
111
|
+
if (!dept) return { success: false, error: 'Department not found' };
|
|
112
|
+
await requireScope({ organizationId: dept.organizationId, hospitalId: dept.hospitalId, departmentId: id });
|
|
113
|
+
|
|
114
|
+
return await db.transaction(async (tx) => {
|
|
115
|
+
const [archived] = await tx.update(departments).set({ status: 'archived' }).where(eq(departments.id, id)).returning();
|
|
116
|
+
await createAuditLog(tx, {
|
|
117
|
+
action: 'ARCHIVE',
|
|
118
|
+
entityType: 'department',
|
|
119
|
+
entityId: id,
|
|
120
|
+
actorId: session.id,
|
|
121
|
+
details: { status: 'archived' },
|
|
122
|
+
});
|
|
123
|
+
return { success: true, data: archived };
|
|
124
|
+
});
|
|
125
|
+
} catch (error: any) {
|
|
126
|
+
return { success: false, error: error.message };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export async function getDepartmentsOverview(filters?: { hospitalId?: string }) {
|
|
131
|
+
const session = await requireAuth();
|
|
132
|
+
try {
|
|
133
|
+
const orgId = session.organizationId;
|
|
134
|
+
|
|
135
|
+
// Fetch hospitals for organization selector
|
|
136
|
+
const hospitalsList = await db.query.hospitals.findMany({
|
|
137
|
+
where: orgId ? eq(hospitals.organizationId, orgId) : undefined,
|
|
138
|
+
orderBy: (h, { asc }) => [asc(h.name)],
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
// Build conditions for departments
|
|
142
|
+
const conditions = [];
|
|
143
|
+
if (orgId) conditions.push(eq(departments.organizationId, orgId));
|
|
144
|
+
if (filters?.hospitalId && filters.hospitalId !== 'all') {
|
|
145
|
+
conditions.push(eq(departments.hospitalId, filters.hospitalId));
|
|
146
|
+
}
|
|
147
|
+
conditions.push(eq(departments.status, 'active'));
|
|
148
|
+
|
|
149
|
+
const depts = await db.query.departments.findMany({
|
|
150
|
+
where: conditions.length > 0 ? and(...conditions) : undefined,
|
|
151
|
+
with: {
|
|
152
|
+
hospital: true,
|
|
153
|
+
manager: true,
|
|
154
|
+
},
|
|
155
|
+
orderBy: (d, { asc }) => [asc(d.name)],
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
// Fetch device counts per department
|
|
159
|
+
const deviceStats = await db
|
|
160
|
+
.select({
|
|
161
|
+
departmentId: devices.departmentId,
|
|
162
|
+
totalDevices: count(devices.id),
|
|
163
|
+
operationalDevices: count(
|
|
164
|
+
sql`CASE WHEN ${devices.currentStatusCode} = 'operational' THEN 1 END`
|
|
165
|
+
),
|
|
166
|
+
outOfServiceDevices: count(
|
|
167
|
+
sql`CASE WHEN ${devices.currentStatusCode} IN ('out_of_service', 'under_repair', 'under_maintenance') THEN 1 END`
|
|
168
|
+
),
|
|
169
|
+
})
|
|
170
|
+
.from(devices)
|
|
171
|
+
.where(orgId ? eq(devices.organizationId, orgId) : undefined)
|
|
172
|
+
.groupBy(devices.departmentId);
|
|
173
|
+
|
|
174
|
+
// Fetch active ticket counts per department (status not in closed, resolved, cancelled)
|
|
175
|
+
const ticketStats = await db
|
|
176
|
+
.select({
|
|
177
|
+
departmentId: serviceTickets.departmentId,
|
|
178
|
+
activeTickets: count(serviceTickets.id),
|
|
179
|
+
})
|
|
180
|
+
.from(serviceTickets)
|
|
181
|
+
.where(
|
|
182
|
+
and(
|
|
183
|
+
orgId ? eq(serviceTickets.organizationId, orgId) : undefined,
|
|
184
|
+
sql`${serviceTickets.statusCode} NOT IN ('resolved', 'closed', 'cancelled')`
|
|
185
|
+
)
|
|
186
|
+
)
|
|
187
|
+
.groupBy(serviceTickets.departmentId);
|
|
188
|
+
|
|
189
|
+
const deviceStatsMap = new Map(deviceStats.map(s => [s.departmentId, s]));
|
|
190
|
+
const ticketStatsMap = new Map(ticketStats.map(s => [s.departmentId, Number(s.activeTickets) || 0]));
|
|
191
|
+
|
|
192
|
+
const result = depts.map(dept => {
|
|
193
|
+
const dStats = deviceStatsMap.get(dept.id);
|
|
194
|
+
const total = Number(dStats?.totalDevices) || 0;
|
|
195
|
+
const operational = Number(dStats?.operationalDevices) || 0;
|
|
196
|
+
const outOfService = Number(dStats?.outOfServiceDevices) || 0;
|
|
197
|
+
const activeTickets = ticketStatsMap.get(dept.id) || 0;
|
|
198
|
+
|
|
199
|
+
return {
|
|
200
|
+
id: dept.id,
|
|
201
|
+
name: dept.name,
|
|
202
|
+
code: dept.code,
|
|
203
|
+
departmentType: dept.departmentType,
|
|
204
|
+
status: dept.status,
|
|
205
|
+
hospital: dept.hospital,
|
|
206
|
+
manager: dept.manager ? { id: dept.manager.id, fullName: dept.manager.fullName, email: dept.manager.email } : null,
|
|
207
|
+
stats: {
|
|
208
|
+
totalDevices: total,
|
|
209
|
+
operationalDevices: operational,
|
|
210
|
+
outOfServiceDevices: outOfService,
|
|
211
|
+
activeTickets,
|
|
212
|
+
operationalRate: total > 0 ? Math.round((operational / total) * 100) : 100,
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
return {
|
|
218
|
+
success: true,
|
|
219
|
+
data: {
|
|
220
|
+
departments: result,
|
|
221
|
+
hospitals: hospitalsList.map(h => ({ id: h.id, name: h.name, code: h.code })),
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
} catch (error: any) {
|
|
225
|
+
return { success: false, error: error.message };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export async function getDepartmentDetails(departmentId: string) {
|
|
230
|
+
await requireAuth();
|
|
231
|
+
try {
|
|
232
|
+
const dept = await db.query.departments.findFirst({
|
|
233
|
+
where: eq(departments.id, departmentId),
|
|
234
|
+
with: {
|
|
235
|
+
hospital: true,
|
|
236
|
+
manager: true,
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
if (!dept) {
|
|
241
|
+
return { success: false, error: 'Department not found' };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Devices in this department
|
|
245
|
+
const deptDevices = await db.query.devices.findMany({
|
|
246
|
+
where: eq(devices.departmentId, departmentId),
|
|
247
|
+
with: {
|
|
248
|
+
deviceCategory: true,
|
|
249
|
+
manufacturer: true,
|
|
250
|
+
location: true,
|
|
251
|
+
},
|
|
252
|
+
orderBy: (d, { desc }) => [desc(d.createdAt)],
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
// Active tickets in this department
|
|
256
|
+
const deptTickets = await db.query.serviceTickets.findMany({
|
|
257
|
+
where: and(
|
|
258
|
+
eq(serviceTickets.departmentId, departmentId),
|
|
259
|
+
sql`${serviceTickets.statusCode} NOT IN ('resolved', 'closed', 'cancelled')`
|
|
260
|
+
),
|
|
261
|
+
with: {
|
|
262
|
+
device: true,
|
|
263
|
+
reportedByUser: true,
|
|
264
|
+
},
|
|
265
|
+
orderBy: (t, { desc }) => [desc(t.reportedAt)],
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
// Locations / rooms in this department
|
|
269
|
+
const deptLocations = await db.query.locations.findMany({
|
|
270
|
+
where: eq(locations.departmentId, departmentId),
|
|
271
|
+
orderBy: (l, { asc }) => [asc(l.name)],
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
// Summary stats
|
|
275
|
+
const totalDevices = deptDevices.length;
|
|
276
|
+
const operationalDevices = deptDevices.filter(d => d.currentStatusCode === 'operational').length;
|
|
277
|
+
const outOfServiceDevices = deptDevices.filter(d =>
|
|
278
|
+
['out_of_service', 'under_repair', 'under_maintenance'].includes(d.currentStatusCode)
|
|
279
|
+
).length;
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
success: true,
|
|
283
|
+
data: {
|
|
284
|
+
department: {
|
|
285
|
+
...dept,
|
|
286
|
+
hospitalName: dept.hospital?.name,
|
|
287
|
+
managerName: dept.manager?.fullName,
|
|
288
|
+
},
|
|
289
|
+
devices: deptDevices,
|
|
290
|
+
tickets: deptTickets,
|
|
291
|
+
locations: deptLocations,
|
|
292
|
+
stats: {
|
|
293
|
+
totalDevices,
|
|
294
|
+
operationalDevices,
|
|
295
|
+
outOfServiceDevices,
|
|
296
|
+
activeTicketsCount: deptTickets.length,
|
|
297
|
+
operationalRate: totalDevices > 0 ? Math.round((operationalDevices / totalDevices) * 100) : 100,
|
|
298
|
+
},
|
|
299
|
+
},
|
|
300
|
+
};
|
|
301
|
+
} catch (error: any) {
|
|
302
|
+
return { success: false, error: error.message };
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// ── Default Clinical Departments ──────────────────────────────────────────────
|
|
307
|
+
|
|
308
|
+
export async function seedDefaultDepartmentsForHospital(hospitalId: string) {
|
|
309
|
+
const session = await requireAuth();
|
|
310
|
+
await requireRole('SYS_ADMIN', 'ORG_ADMIN', 'HOSP_ADMIN');
|
|
311
|
+
|
|
312
|
+
try {
|
|
313
|
+
const hospital = await db.query.hospitals.findFirst({
|
|
314
|
+
where: eq(hospitals.id, hospitalId),
|
|
315
|
+
});
|
|
316
|
+
if (!hospital) return { success: false, error: 'Hospital not found' };
|
|
317
|
+
|
|
318
|
+
await requireScope({ organizationId: hospital.organizationId, hospitalId });
|
|
319
|
+
|
|
320
|
+
// Fetch existing department codes for this hospital
|
|
321
|
+
const existing = await db.query.departments.findMany({
|
|
322
|
+
where: eq(departments.hospitalId, hospitalId),
|
|
323
|
+
columns: { code: true, name: true },
|
|
324
|
+
});
|
|
325
|
+
const existingCodes = new Set(existing.map((d) => d.code.toUpperCase()));
|
|
326
|
+
const existingNames = new Set(existing.map((d) => d.name.toLowerCase()));
|
|
327
|
+
|
|
328
|
+
const toInsert = DEFAULT_HOSPITAL_DEPARTMENTS.filter((dept) => {
|
|
329
|
+
const nameMatch = existingNames.has(dept.name.toLowerCase());
|
|
330
|
+
const codeMatch = existingCodes.has(dept.code.toUpperCase());
|
|
331
|
+
const partialCodeMatch = Array.from(existingCodes).some(
|
|
332
|
+
(c) => c.startsWith(dept.code) || dept.code.startsWith(c)
|
|
333
|
+
);
|
|
334
|
+
const partialNameMatch = Array.from(existingNames).some(
|
|
335
|
+
(n) => n.includes(dept.departmentType.toLowerCase()) || dept.name.toLowerCase().includes(n)
|
|
336
|
+
);
|
|
337
|
+
return !nameMatch && !codeMatch && !partialCodeMatch && !partialNameMatch;
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
if (toInsert.length === 0) {
|
|
341
|
+
return { success: true, message: 'All default departments already exist', count: 0 };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const inserted = await db.transaction(async (tx) => {
|
|
345
|
+
const records = [];
|
|
346
|
+
for (const d of toInsert) {
|
|
347
|
+
const [newDept] = await tx.insert(departments).values({
|
|
348
|
+
organizationId: hospital.organizationId,
|
|
349
|
+
hospitalId: hospital.id,
|
|
350
|
+
name: d.name,
|
|
351
|
+
code: d.code,
|
|
352
|
+
departmentType: d.departmentType,
|
|
353
|
+
status: 'active',
|
|
354
|
+
managerUserId: session.id,
|
|
355
|
+
createdByUserId: session.id,
|
|
356
|
+
}).onConflictDoNothing().returning();
|
|
357
|
+
if (newDept) records.push(newDept);
|
|
358
|
+
}
|
|
359
|
+
return records;
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
return { success: true, count: inserted.length, data: inserted };
|
|
363
|
+
} catch (error: any) {
|
|
364
|
+
return { success: false, error: error.message };
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
'use server';
|
|
2
|
+
|
|
3
|
+
import { db } from '@/lib/db';
|
|
4
|
+
import { deviceCategories } from '@/lib/db/schema';
|
|
5
|
+
import { requireAuth, requireRole } from '@/lib/auth/rbac';
|
|
6
|
+
import { createAuditLog } from '@/lib/audit';
|
|
7
|
+
import { createDeviceCategorySchema, updateDeviceCategorySchema } from '@/lib/validators/devices';
|
|
8
|
+
import { eq, and, desc } from 'drizzle-orm';
|
|
9
|
+
|
|
10
|
+
export async function getDeviceCategories(organizationId?: string) {
|
|
11
|
+
await requireAuth();
|
|
12
|
+
try {
|
|
13
|
+
if (organizationId) {
|
|
14
|
+
const data = await db.query.deviceCategories.findMany({
|
|
15
|
+
where: eq(deviceCategories.organizationId, organizationId),
|
|
16
|
+
orderBy: [desc(deviceCategories.createdAt)],
|
|
17
|
+
});
|
|
18
|
+
return { success: true, data };
|
|
19
|
+
}
|
|
20
|
+
const data = await db.query.deviceCategories.findMany({
|
|
21
|
+
orderBy: [desc(deviceCategories.createdAt)],
|
|
22
|
+
});
|
|
23
|
+
return { success: true, data };
|
|
24
|
+
} catch (error: any) {
|
|
25
|
+
return { success: false, error: error.message };
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function getDeviceCategoryById(id: string) {
|
|
30
|
+
await requireAuth();
|
|
31
|
+
try {
|
|
32
|
+
const data = await db.query.deviceCategories.findFirst({
|
|
33
|
+
where: eq(deviceCategories.id, id),
|
|
34
|
+
});
|
|
35
|
+
return { success: true, data };
|
|
36
|
+
} catch (error: any) {
|
|
37
|
+
return { success: false, error: error.message };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function createDeviceCategory(input: unknown) {
|
|
42
|
+
const session = await requireAuth();
|
|
43
|
+
await requireRole('SYS_ADMIN', 'ORG_ADMIN', 'BIOMED_MGR', 'BIOMED_ENG');
|
|
44
|
+
|
|
45
|
+
let orgId = (input as any)?.organizationId || session.organizationId;
|
|
46
|
+
if (!orgId) {
|
|
47
|
+
const firstOrg = await db.query.organizations.findFirst();
|
|
48
|
+
orgId = firstOrg?.id;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const payload = typeof input === 'object' && input !== null
|
|
52
|
+
? { organizationId: orgId, ...input }
|
|
53
|
+
: input;
|
|
54
|
+
|
|
55
|
+
const validated = createDeviceCategorySchema.safeParse(payload);
|
|
56
|
+
if (!validated.success) return { success: false, error: validated.error.message };
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
return await db.transaction(async (tx) => {
|
|
60
|
+
const [newCat] = await tx.insert(deviceCategories).values({
|
|
61
|
+
...validated.data,
|
|
62
|
+
createdByUserId: session.id,
|
|
63
|
+
}).returning();
|
|
64
|
+
await createAuditLog(tx, {
|
|
65
|
+
action: 'CREATE', entityType: 'device_category', entityId: newCat.id,
|
|
66
|
+
actorId: session.id, details: validated.data,
|
|
67
|
+
});
|
|
68
|
+
return { success: true, data: newCat };
|
|
69
|
+
});
|
|
70
|
+
} catch (error: any) {
|
|
71
|
+
return { success: false, error: error.message };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function updateDeviceCategory(id: string, input: unknown) {
|
|
76
|
+
const session = await requireAuth();
|
|
77
|
+
await requireRole('SYS_ADMIN', 'ORG_ADMIN', 'BIOMED_MGR');
|
|
78
|
+
const validated = updateDeviceCategorySchema.safeParse(input);
|
|
79
|
+
if (!validated.success) return { success: false, error: validated.error.message };
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
return await db.transaction(async (tx) => {
|
|
83
|
+
const [updated] = await tx.update(deviceCategories)
|
|
84
|
+
.set({ ...validated.data, updatedByUserId: session.id })
|
|
85
|
+
.where(eq(deviceCategories.id, id))
|
|
86
|
+
.returning();
|
|
87
|
+
await createAuditLog(tx, {
|
|
88
|
+
action: 'UPDATE', entityType: 'device_category', entityId: id,
|
|
89
|
+
actorId: session.id, details: validated.data,
|
|
90
|
+
});
|
|
91
|
+
return { success: true, data: updated };
|
|
92
|
+
});
|
|
93
|
+
} catch (error: any) {
|
|
94
|
+
return { success: false, error: error.message };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function archiveDeviceCategory(id: string) {
|
|
99
|
+
const session = await requireAuth();
|
|
100
|
+
await requireRole('SYS_ADMIN', 'ORG_ADMIN', 'BIOMED_MGR');
|
|
101
|
+
try {
|
|
102
|
+
return await db.transaction(async (tx) => {
|
|
103
|
+
const [archived] = await tx.update(deviceCategories)
|
|
104
|
+
.set({ status: 'archived', archivedAt: new Date(), archivedByUserId: session.id })
|
|
105
|
+
.where(eq(deviceCategories.id, id))
|
|
106
|
+
.returning();
|
|
107
|
+
await createAuditLog(tx, {
|
|
108
|
+
action: 'ARCHIVE', entityType: 'device_category', entityId: id,
|
|
109
|
+
actorId: session.id, details: { status: 'archived' },
|
|
110
|
+
});
|
|
111
|
+
return { success: true, data: archived };
|
|
112
|
+
});
|
|
113
|
+
} catch (error: any) {
|
|
114
|
+
return { success: false, error: error.message };
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|