@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,169 @@
|
|
|
1
|
+
import { pgTable, uuid, text, timestamp, integer, jsonb, index } from 'drizzle-orm/pg-core';
|
|
2
|
+
import { relations } from 'drizzle-orm';
|
|
3
|
+
import {
|
|
4
|
+
ticketStatusCodeEnum, ticketPriorityCodeEnum, ticketTypeCodeEnum,
|
|
5
|
+
ticketSourceEnum, reportedImpactCodeEnum, reporterProblemCategoryCodeEnum,
|
|
6
|
+
maintenanceTypeCodeEnum, technicalProblemCategoryCodeEnum,
|
|
7
|
+
ticketCommentVisibilityEnum, ticketEventTypeEnum, deviceStatusCodeEnum,
|
|
8
|
+
} from './enums';
|
|
9
|
+
import { organizations } from './organizations';
|
|
10
|
+
import { hospitals } from './hospitals';
|
|
11
|
+
import { departments } from './departments';
|
|
12
|
+
import { locations } from './locations';
|
|
13
|
+
import { users } from './users';
|
|
14
|
+
import { devices } from './devices';
|
|
15
|
+
import { roundDepartmentVisits } from './engineer-rounds';
|
|
16
|
+
|
|
17
|
+
// ── Service Tickets ─────────────────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
export const serviceTickets = pgTable('service_tickets', {
|
|
20
|
+
id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
|
|
21
|
+
ticketNumber: text('ticket_number').notNull().unique(),
|
|
22
|
+
organizationId: uuid('organization_id').notNull().references(() => organizations.id),
|
|
23
|
+
|
|
24
|
+
// Device & Location Context
|
|
25
|
+
deviceId: uuid('device_id').references(() => devices.id),
|
|
26
|
+
hospitalId: uuid('hospital_id').notNull().references(() => hospitals.id),
|
|
27
|
+
departmentId: uuid('department_id').notNull().references(() => departments.id),
|
|
28
|
+
locationId: uuid('location_id').references(() => locations.id),
|
|
29
|
+
exactLocationDescription: text('exact_location_description'),
|
|
30
|
+
deviceSnapshot: jsonb('device_snapshot'),
|
|
31
|
+
locationSnapshot: jsonb('location_snapshot'),
|
|
32
|
+
|
|
33
|
+
// Source & Original Report
|
|
34
|
+
source: ticketSourceEnum('source').notNull(),
|
|
35
|
+
ticketType: ticketTypeCodeEnum('ticket_type').default('device_problem').notNull(),
|
|
36
|
+
title: text('title').notNull(),
|
|
37
|
+
description: text('description').notNull(),
|
|
38
|
+
reportedProblemCategory: reporterProblemCategoryCodeEnum('reported_problem_category'),
|
|
39
|
+
reportedImpact: reportedImpactCodeEnum('reported_impact').notNull(),
|
|
40
|
+
reportedLocationCorrection: text('reported_location_correction'),
|
|
41
|
+
requesterContactName: text('requester_contact_name'),
|
|
42
|
+
requesterContactPhone: text('requester_contact_phone'),
|
|
43
|
+
reportedByUserId: uuid('reported_by_user_id').notNull().references(() => users.id),
|
|
44
|
+
reportedAt: timestamp('reported_at', { withTimezone: true }).defaultNow().notNull(),
|
|
45
|
+
|
|
46
|
+
// Triage & Engineering Classification
|
|
47
|
+
statusCode: ticketStatusCodeEnum('status_code').default('new').notNull(),
|
|
48
|
+
priorityCode: ticketPriorityCodeEnum('priority_code').default('p3_normal').notNull(),
|
|
49
|
+
priorityReason: text('priority_reason'),
|
|
50
|
+
triagedByUserId: uuid('triaged_by_user_id').references(() => users.id),
|
|
51
|
+
triagedAt: timestamp('triaged_at', { withTimezone: true }),
|
|
52
|
+
selectedMaintenanceType: maintenanceTypeCodeEnum('selected_maintenance_type'),
|
|
53
|
+
selectedTechnicalCategory: technicalProblemCategoryCodeEnum('selected_technical_category'),
|
|
54
|
+
internalTriageNote: text('internal_triage_note'),
|
|
55
|
+
|
|
56
|
+
// Assignment & SLA
|
|
57
|
+
assignedEngineerUserId: uuid('assigned_engineer_user_id').references(() => users.id),
|
|
58
|
+
assignedTeamId: uuid('assigned_team_id'),
|
|
59
|
+
assignedAt: timestamp('assigned_at', { withTimezone: true }),
|
|
60
|
+
acceptedAt: timestamp('accepted_at', { withTimezone: true }),
|
|
61
|
+
responseTargetAt: timestamp('response_target_at', { withTimezone: true }),
|
|
62
|
+
resolutionTargetAt: timestamp('resolution_target_at', { withTimezone: true }),
|
|
63
|
+
|
|
64
|
+
// Work & Resolution
|
|
65
|
+
waitingReason: text('waiting_reason'),
|
|
66
|
+
waitingDependencyType: text('waiting_dependency_type'),
|
|
67
|
+
resolutionSummary: text('resolution_summary'),
|
|
68
|
+
finalDeviceStatusCode: deviceStatusCodeEnum('final_device_status_code'),
|
|
69
|
+
resolvedAt: timestamp('resolved_at', { withTimezone: true }),
|
|
70
|
+
resolvedByUserId: uuid('resolved_by_user_id').references(() => users.id),
|
|
71
|
+
closedAt: timestamp('closed_at', { withTimezone: true }),
|
|
72
|
+
closedByUserId: uuid('closed_by_user_id').references(() => users.id),
|
|
73
|
+
closureReason: text('closure_reason'),
|
|
74
|
+
cancelledAt: timestamp('cancelled_at', { withTimezone: true }),
|
|
75
|
+
cancelledByUserId: uuid('cancelled_by_user_id').references(() => users.id),
|
|
76
|
+
cancellationReason: text('cancellation_reason'),
|
|
77
|
+
reopenedAt: timestamp('reopened_at', { withTimezone: true }),
|
|
78
|
+
reopenedByUserId: uuid('reopened_by_user_id').references(() => users.id),
|
|
79
|
+
reopenReason: text('reopen_reason'),
|
|
80
|
+
|
|
81
|
+
// Engineer's Round link (nullable — only set for tickets created during a round)
|
|
82
|
+
roundVisitId: uuid('round_visit_id').references(() => roundDepartmentVisits.id),
|
|
83
|
+
|
|
84
|
+
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
|
85
|
+
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
|
86
|
+
}, (t) => ({
|
|
87
|
+
lookupIdx: index('idx_tickets_lookup').on(t.organizationId, t.hospitalId, t.departmentId, t.statusCode),
|
|
88
|
+
ticketNumIdx: index('idx_tickets_number').on(t.organizationId, t.ticketNumber),
|
|
89
|
+
deviceIdx: index('idx_tickets_device').on(t.deviceId, t.statusCode),
|
|
90
|
+
assigneeIdx: index('idx_tickets_assignee').on(t.assignedEngineerUserId, t.statusCode),
|
|
91
|
+
reporterIdx: index('idx_tickets_reporter').on(t.reportedByUserId),
|
|
92
|
+
}));
|
|
93
|
+
|
|
94
|
+
export const serviceTicketsRelations = relations(serviceTickets, ({ one }) => ({
|
|
95
|
+
organization: one(organizations, { fields: [serviceTickets.organizationId], references: [organizations.id] }),
|
|
96
|
+
device: one(devices, { fields: [serviceTickets.deviceId], references: [devices.id] }),
|
|
97
|
+
hospital: one(hospitals, { fields: [serviceTickets.hospitalId], references: [hospitals.id] }),
|
|
98
|
+
department: one(departments, { fields: [serviceTickets.departmentId], references: [departments.id] }),
|
|
99
|
+
location: one(locations, { fields: [serviceTickets.locationId], references: [locations.id] }),
|
|
100
|
+
reportedByUser: one(users, { fields: [serviceTickets.reportedByUserId], references: [users.id], relationName: 'ticketsReportedByUser' }),
|
|
101
|
+
triagedByUser: one(users, { fields: [serviceTickets.triagedByUserId], references: [users.id], relationName: 'ticketsTriagedByUser' }),
|
|
102
|
+
assignedEngineer: one(users, { fields: [serviceTickets.assignedEngineerUserId], references: [users.id], relationName: 'ticketsAssignedToEngineer' }),
|
|
103
|
+
resolvedByUser: one(users, { fields: [serviceTickets.resolvedByUserId], references: [users.id], relationName: 'ticketsResolvedByUser' }),
|
|
104
|
+
closedByUser: one(users, { fields: [serviceTickets.closedByUserId], references: [users.id], relationName: 'ticketsClosedByUser' }),
|
|
105
|
+
}));
|
|
106
|
+
|
|
107
|
+
// ── Ticket Comments ─────────────────────────────────────────────────────────────
|
|
108
|
+
|
|
109
|
+
export const serviceTicketComments = pgTable('service_ticket_comments', {
|
|
110
|
+
id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
|
|
111
|
+
serviceTicketId: uuid('service_ticket_id').notNull().references(() => serviceTickets.id, { onDelete: 'cascade' }),
|
|
112
|
+
authorUserId: uuid('author_user_id').notNull().references(() => users.id),
|
|
113
|
+
visibility: ticketCommentVisibilityEnum('visibility').default('public').notNull(),
|
|
114
|
+
body: text('body').notNull(),
|
|
115
|
+
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
|
116
|
+
editedAt: timestamp('edited_at', { withTimezone: true }),
|
|
117
|
+
editedByUserId: uuid('edited_by_user_id').references(() => users.id),
|
|
118
|
+
}, (t) => ({
|
|
119
|
+
ticketTimeIdx: index('idx_ticket_comments_ticket').on(t.serviceTicketId, t.createdAt),
|
|
120
|
+
}));
|
|
121
|
+
|
|
122
|
+
export const serviceTicketCommentsRelations = relations(serviceTicketComments, ({ one }) => ({
|
|
123
|
+
serviceTicket: one(serviceTickets, { fields: [serviceTicketComments.serviceTicketId], references: [serviceTickets.id] }),
|
|
124
|
+
author: one(users, { fields: [serviceTicketComments.authorUserId], references: [users.id], relationName: 'ticketCommentsAuthor' }),
|
|
125
|
+
}));
|
|
126
|
+
|
|
127
|
+
// ── Ticket Events (append-only timeline) ────────────────────────────────────────
|
|
128
|
+
|
|
129
|
+
export const serviceTicketEvents = pgTable('service_ticket_events', {
|
|
130
|
+
id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
|
|
131
|
+
serviceTicketId: uuid('service_ticket_id').notNull().references(() => serviceTickets.id, { onDelete: 'cascade' }),
|
|
132
|
+
eventType: ticketEventTypeEnum('event_type').notNull(),
|
|
133
|
+
previousValueJsonb: jsonb('previous_value_jsonb'),
|
|
134
|
+
newValueJsonb: jsonb('new_value_jsonb'),
|
|
135
|
+
visibility: ticketCommentVisibilityEnum('visibility').default('public').notNull(),
|
|
136
|
+
reason: text('reason'),
|
|
137
|
+
actorUserId: uuid('actor_user_id').notNull().references(() => users.id),
|
|
138
|
+
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
|
139
|
+
relatedMaintenanceTaskId: uuid('related_maintenance_task_id'),
|
|
140
|
+
}, (t) => ({
|
|
141
|
+
ticketTimeIdx: index('idx_ticket_events_ticket').on(t.serviceTicketId, t.createdAt),
|
|
142
|
+
}));
|
|
143
|
+
|
|
144
|
+
export const serviceTicketEventsRelations = relations(serviceTicketEvents, ({ one }) => ({
|
|
145
|
+
serviceTicket: one(serviceTickets, { fields: [serviceTicketEvents.serviceTicketId], references: [serviceTickets.id] }),
|
|
146
|
+
actor: one(users, { fields: [serviceTicketEvents.actorUserId], references: [users.id], relationName: 'ticketEventsActor' }),
|
|
147
|
+
}));
|
|
148
|
+
|
|
149
|
+
// ── Ticket Attachments ──────────────────────────────────────────────────────────
|
|
150
|
+
|
|
151
|
+
export const serviceTicketAttachments = pgTable('service_ticket_attachments', {
|
|
152
|
+
id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
|
|
153
|
+
serviceTicketId: uuid('service_ticket_id').notNull().references(() => serviceTickets.id, { onDelete: 'cascade' }),
|
|
154
|
+
fileName: text('file_name').notNull(),
|
|
155
|
+
fileSize: integer('file_size'),
|
|
156
|
+
mimeType: text('mime_type'),
|
|
157
|
+
storageKey: text('storage_key').notNull(),
|
|
158
|
+
visibility: ticketCommentVisibilityEnum('visibility').default('public').notNull(),
|
|
159
|
+
uploadedByUserId: uuid('uploaded_by_user_id').notNull().references(() => users.id),
|
|
160
|
+
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
|
161
|
+
}, (t) => ({
|
|
162
|
+
ticketIdx: index('idx_ticket_attachments_ticket').on(t.serviceTicketId),
|
|
163
|
+
}));
|
|
164
|
+
|
|
165
|
+
export const serviceTicketAttachmentsRelations = relations(serviceTicketAttachments, ({ one }) => ({
|
|
166
|
+
serviceTicket: one(serviceTickets, { fields: [serviceTicketAttachments.serviceTicketId], references: [serviceTickets.id] }),
|
|
167
|
+
uploadedByUser: one(users, { fields: [serviceTicketAttachments.uploadedByUserId], references: [users.id], relationName: 'ticketAttachmentsUploader' }),
|
|
168
|
+
}));
|
|
169
|
+
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { pgTable, uuid, timestamp } from 'drizzle-orm/pg-core';
|
|
2
|
+
import { relations } from 'drizzle-orm';
|
|
3
|
+
import { assignmentStatusEnum, scopeTypeEnum } from './enums';
|
|
4
|
+
import { users } from './users';
|
|
5
|
+
import { roles } from './roles';
|
|
6
|
+
import { organizations } from './organizations';
|
|
7
|
+
import { hospitals } from './hospitals';
|
|
8
|
+
import { departments } from './departments';
|
|
9
|
+
import { locations } from './locations';
|
|
10
|
+
|
|
11
|
+
export const userRoleAssignments = pgTable('user_role_assignments', {
|
|
12
|
+
id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
|
|
13
|
+
userId: uuid('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
|
14
|
+
roleId: uuid('role_id').notNull().references(() => roles.id, { onDelete: 'cascade' }),
|
|
15
|
+
organizationId: uuid('organization_id').references(() => organizations.id),
|
|
16
|
+
effectiveFrom: timestamp('effective_from', { withTimezone: true }).defaultNow(),
|
|
17
|
+
effectiveTo: timestamp('effective_to', { withTimezone: true }),
|
|
18
|
+
assignedByUserId: uuid('assigned_by_user_id').references(() => users.id),
|
|
19
|
+
status: assignmentStatusEnum('status').default('active'),
|
|
20
|
+
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
export const userAccessScopes = pgTable('user_access_scopes', {
|
|
24
|
+
id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
|
|
25
|
+
userId: uuid('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
|
26
|
+
organizationId: uuid('organization_id').notNull().references(() => organizations.id),
|
|
27
|
+
hospitalId: uuid('hospital_id').references(() => hospitals.id),
|
|
28
|
+
departmentId: uuid('department_id').references(() => departments.id),
|
|
29
|
+
locationId: uuid('location_id').references(() => locations.id),
|
|
30
|
+
scopeType: scopeTypeEnum('scope_type').notNull(),
|
|
31
|
+
status: assignmentStatusEnum('status').default('active'),
|
|
32
|
+
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
|
33
|
+
createdByUserId: uuid('created_by_user_id').references(() => users.id),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
export const userRoleAssignmentsRelations = relations(userRoleAssignments, ({ one }) => ({
|
|
37
|
+
user: one(users, {
|
|
38
|
+
fields: [userRoleAssignments.userId],
|
|
39
|
+
references: [users.id],
|
|
40
|
+
relationName: 'roleAssignmentsForUser',
|
|
41
|
+
}),
|
|
42
|
+
role: one(roles, {
|
|
43
|
+
fields: [userRoleAssignments.roleId],
|
|
44
|
+
references: [roles.id],
|
|
45
|
+
}),
|
|
46
|
+
organization: one(organizations, {
|
|
47
|
+
fields: [userRoleAssignments.organizationId],
|
|
48
|
+
references: [organizations.id],
|
|
49
|
+
}),
|
|
50
|
+
assignedByUser: one(users, {
|
|
51
|
+
fields: [userRoleAssignments.assignedByUserId],
|
|
52
|
+
references: [users.id],
|
|
53
|
+
relationName: 'rolesAssignedByUser',
|
|
54
|
+
}),
|
|
55
|
+
}));
|
|
56
|
+
|
|
57
|
+
export const userAccessScopesRelations = relations(userAccessScopes, ({ one }) => ({
|
|
58
|
+
user: one(users, {
|
|
59
|
+
fields: [userAccessScopes.userId],
|
|
60
|
+
references: [users.id],
|
|
61
|
+
relationName: 'accessScopesForUser',
|
|
62
|
+
}),
|
|
63
|
+
organization: one(organizations, {
|
|
64
|
+
fields: [userAccessScopes.organizationId],
|
|
65
|
+
references: [organizations.id],
|
|
66
|
+
}),
|
|
67
|
+
hospital: one(hospitals, {
|
|
68
|
+
fields: [userAccessScopes.hospitalId],
|
|
69
|
+
references: [hospitals.id],
|
|
70
|
+
}),
|
|
71
|
+
department: one(departments, {
|
|
72
|
+
fields: [userAccessScopes.departmentId],
|
|
73
|
+
references: [departments.id],
|
|
74
|
+
}),
|
|
75
|
+
location: one(locations, {
|
|
76
|
+
fields: [userAccessScopes.locationId],
|
|
77
|
+
references: [locations.id],
|
|
78
|
+
}),
|
|
79
|
+
createdByUser: one(users, {
|
|
80
|
+
fields: [userAccessScopes.createdByUserId],
|
|
81
|
+
references: [users.id],
|
|
82
|
+
relationName: 'scopesCreatedByUser',
|
|
83
|
+
}),
|
|
84
|
+
}));
|
|
85
|
+
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { pgTable, uuid, text, timestamp, jsonb } from 'drizzle-orm/pg-core';
|
|
2
|
+
import { relations } from 'drizzle-orm';
|
|
3
|
+
import { userAccountStatusEnum } from './enums';
|
|
4
|
+
import { organizations } from './organizations';
|
|
5
|
+
|
|
6
|
+
export const users = pgTable('users', {
|
|
7
|
+
id: uuid('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
|
|
8
|
+
email: text('email').notNull().unique(),
|
|
9
|
+
passwordHash: text('password_hash'),
|
|
10
|
+
fullName: text('full_name').notNull(),
|
|
11
|
+
phone: text('phone'),
|
|
12
|
+
jobTitle: text('job_title'),
|
|
13
|
+
employeeIdentifier: text('employee_identifier'),
|
|
14
|
+
organizationId: uuid('organization_id').references(() => organizations.id),
|
|
15
|
+
accountStatus: userAccountStatusEnum('account_status').default('invited'),
|
|
16
|
+
avatarUrl: text('avatar_url'),
|
|
17
|
+
notificationPreferences: jsonb('notification_preferences').$type<{
|
|
18
|
+
pushEnabled: boolean;
|
|
19
|
+
categories: {
|
|
20
|
+
tickets: boolean;
|
|
21
|
+
maintenance: boolean;
|
|
22
|
+
devices: boolean;
|
|
23
|
+
system: boolean;
|
|
24
|
+
};
|
|
25
|
+
}>(),
|
|
26
|
+
lastLoginAt: timestamp('last_login_at', { withTimezone: true }),
|
|
27
|
+
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
|
28
|
+
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
|
29
|
+
createdByUserId: uuid('created_by_user_id'),
|
|
30
|
+
updatedByUserId: uuid('updated_by_user_id'),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
export const usersRelations = relations(users, ({ one }) => ({
|
|
34
|
+
organization: one(organizations, {
|
|
35
|
+
fields: [users.organizationId],
|
|
36
|
+
references: [organizations.id],
|
|
37
|
+
}),
|
|
38
|
+
}));
|
|
39
|
+
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { Pool } from 'pg';
|
|
2
|
+
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
3
|
+
import * as schema from './schema';
|
|
4
|
+
import { hashPassword } from '@/lib/auth/password';
|
|
5
|
+
import { eq } from 'drizzle-orm';
|
|
6
|
+
|
|
7
|
+
const pool = new Pool({
|
|
8
|
+
connectionString: process.env.DATABASE_URL,
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
const db = drizzle(pool, { schema });
|
|
12
|
+
|
|
13
|
+
async function seed() {
|
|
14
|
+
console.log('Starting seed...');
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
// 1. Create Default Organization
|
|
18
|
+
const [org] = await db.insert(schema.organizations).values({
|
|
19
|
+
name: 'Default Organization',
|
|
20
|
+
code: 'DEFAULT',
|
|
21
|
+
defaultTimezone: 'UTC',
|
|
22
|
+
}).onConflictDoNothing().returning();
|
|
23
|
+
|
|
24
|
+
let orgId = org?.id;
|
|
25
|
+
if (!orgId) {
|
|
26
|
+
const existingOrg = await db.query.organizations.findFirst({
|
|
27
|
+
where: (organizations, { eq }) => eq(organizations.code, 'DEFAULT'),
|
|
28
|
+
});
|
|
29
|
+
orgId = existingOrg!.id;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// 2. Create System Roles
|
|
33
|
+
const systemRoles = [
|
|
34
|
+
{ code: 'SYS_ADMIN', name: 'System Administrator', isSystemRole: true },
|
|
35
|
+
{ code: 'ORG_ADMIN', name: 'Organization Administrator', isSystemRole: true },
|
|
36
|
+
{ code: 'HOSP_ADMIN', name: 'Hospital Administrator', isSystemRole: true },
|
|
37
|
+
{ code: 'BIOMED_MGR', name: 'Biomedical Manager', isSystemRole: true },
|
|
38
|
+
{ code: 'BIOMED_ENG', name: 'Biomedical Engineer', isSystemRole: true },
|
|
39
|
+
{ code: 'BIOMED_TECH', name: 'Biomedical Technician', isSystemRole: true },
|
|
40
|
+
{ code: 'DEPT_MGR', name: 'Department Manager', isSystemRole: true },
|
|
41
|
+
{ code: 'STAFF', name: 'Staff', isSystemRole: true },
|
|
42
|
+
{ code: 'AUDITOR', name: 'Auditor', isSystemRole: true },
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
for (const role of systemRoles) {
|
|
46
|
+
await db.insert(schema.roles).values({
|
|
47
|
+
organizationId: orgId,
|
|
48
|
+
...role,
|
|
49
|
+
}).onConflictDoNothing();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const sysAdminRole = await db.query.roles.findFirst({
|
|
53
|
+
where: (roles, { eq }) => eq(roles.code, 'SYS_ADMIN'),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
if (!sysAdminRole) {
|
|
57
|
+
throw new Error('SYS_ADMIN role not found after insert');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 3. Create all permissions
|
|
61
|
+
const modules = ['DEVICES', 'TICKETS', 'MAINTENANCE', 'PM_CALIBRATION', 'SIGNATURES', 'REPORTS', 'ADMIN', 'AUDIT'];
|
|
62
|
+
const actions = ['VIEW', 'CREATE', 'EDIT', 'ASSIGN', 'APPROVE', 'SIGN', 'RELEASE', 'ARCHIVE', 'EXPORT', 'MANAGE_POLICY'];
|
|
63
|
+
|
|
64
|
+
for (const mod of modules) {
|
|
65
|
+
for (const act of actions) {
|
|
66
|
+
await db.insert(schema.permissions).values({
|
|
67
|
+
module: mod as any,
|
|
68
|
+
action: act as any,
|
|
69
|
+
}).onConflictDoNothing();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// 4. Assign all permissions to SYS_ADMIN
|
|
74
|
+
const allPermissions = await db.query.permissions.findMany();
|
|
75
|
+
for (const permission of allPermissions) {
|
|
76
|
+
await db.insert(schema.rolePermissions).values({
|
|
77
|
+
roleId: sysAdminRole.id,
|
|
78
|
+
permissionId: permission.id,
|
|
79
|
+
}).onConflictDoNothing();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// 5. Create Admin User (only set password on first creation, never overwrite)
|
|
83
|
+
const adminEmail = process.env.ADMIN_EMAIL || 'admin@bemms.local';
|
|
84
|
+
const adminPassword = process.env.ADMIN_PASSWORD || 'admin123';
|
|
85
|
+
const passwordHash = await hashPassword(adminPassword);
|
|
86
|
+
|
|
87
|
+
const [adminUser] = await db.insert(schema.users).values({
|
|
88
|
+
email: adminEmail,
|
|
89
|
+
passwordHash,
|
|
90
|
+
fullName: process.env.ADMIN_FULL_NAME || 'System Administrator',
|
|
91
|
+
employeeIdentifier: 'admin',
|
|
92
|
+
organizationId: orgId,
|
|
93
|
+
accountStatus: 'active',
|
|
94
|
+
}).onConflictDoNothing().returning();
|
|
95
|
+
|
|
96
|
+
let adminId = adminUser?.id;
|
|
97
|
+
if (!adminId) {
|
|
98
|
+
// User already exists — do NOT overwrite password (may have been changed)
|
|
99
|
+
const existingUser = await db.query.users.findFirst({
|
|
100
|
+
where: (users, { eq }) => eq(users.email, adminEmail),
|
|
101
|
+
});
|
|
102
|
+
adminId = existingUser!.id;
|
|
103
|
+
console.log('Admin user already exists — skipping password update to preserve production credentials.');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// 6. Assign SYS_ADMIN role to admin user
|
|
107
|
+
await db.insert(schema.userRoleAssignments).values({
|
|
108
|
+
userId: adminId,
|
|
109
|
+
roleId: sysAdminRole.id,
|
|
110
|
+
organizationId: orgId,
|
|
111
|
+
}).onConflictDoNothing();
|
|
112
|
+
|
|
113
|
+
// 7. Create User Access Scope for Admin User
|
|
114
|
+
await db.insert(schema.userAccessScopes).values({
|
|
115
|
+
userId: adminId,
|
|
116
|
+
organizationId: orgId,
|
|
117
|
+
scopeType: 'organization',
|
|
118
|
+
}).onConflictDoNothing();
|
|
119
|
+
|
|
120
|
+
console.log('Seed completed successfully!');
|
|
121
|
+
} catch (error) {
|
|
122
|
+
console.error('Seed failed:', error);
|
|
123
|
+
await pool.end();
|
|
124
|
+
process.exit(1);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
await pool.end();
|
|
128
|
+
process.exit(0);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
seed();
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
2
|
+
import { createLogger, getLogger, jsonFormatter, prettyFormatter, LogEntry } from '../index';
|
|
3
|
+
|
|
4
|
+
describe('Logger Module', () => {
|
|
5
|
+
let consoleLogSpy: any;
|
|
6
|
+
let consoleWarnSpy: any;
|
|
7
|
+
let consoleErrorSpy: any;
|
|
8
|
+
|
|
9
|
+
beforeEach(() => {
|
|
10
|
+
consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
|
11
|
+
consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
12
|
+
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
vi.restoreAllMocks();
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
describe('createLogger and log levels', () => {
|
|
20
|
+
it('should log messages according to minLevel', () => {
|
|
21
|
+
const logger = createLogger({ minLevel: 'warn' });
|
|
22
|
+
|
|
23
|
+
logger.debug('debug message');
|
|
24
|
+
logger.info('info message');
|
|
25
|
+
logger.warn('warn message');
|
|
26
|
+
logger.error('error message');
|
|
27
|
+
|
|
28
|
+
expect(consoleLogSpy).not.toHaveBeenCalled();
|
|
29
|
+
expect(consoleWarnSpy).toHaveBeenCalledTimes(1);
|
|
30
|
+
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('should emit debug and info to console.log', () => {
|
|
34
|
+
const logger = createLogger({ minLevel: 'debug' });
|
|
35
|
+
|
|
36
|
+
logger.debug('debug test');
|
|
37
|
+
expect(consoleLogSpy).toHaveBeenCalledTimes(1);
|
|
38
|
+
|
|
39
|
+
logger.info('info test');
|
|
40
|
+
expect(consoleLogSpy).toHaveBeenCalledTimes(2);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('should emit warn to console.warn and fatal to console.error', () => {
|
|
44
|
+
const logger = createLogger({ minLevel: 'debug' });
|
|
45
|
+
|
|
46
|
+
logger.warn('warning test');
|
|
47
|
+
expect(consoleWarnSpy).toHaveBeenCalledTimes(1);
|
|
48
|
+
|
|
49
|
+
logger.fatal('fatal error');
|
|
50
|
+
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('should properly serialize errors', () => {
|
|
54
|
+
const logger = createLogger({ minLevel: 'error' });
|
|
55
|
+
const testError = new Error('Database connection failed');
|
|
56
|
+
|
|
57
|
+
logger.error('Query failed', testError, { query: 'SELECT 1' });
|
|
58
|
+
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('should support passing data object as error parameter', () => {
|
|
62
|
+
const logger = createLogger({ minLevel: 'error' });
|
|
63
|
+
logger.error('Something failed', { code: 500, detail: 'timeout' });
|
|
64
|
+
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe('child logger', () => {
|
|
69
|
+
it('should inherit and merge module path and context', () => {
|
|
70
|
+
const parent = createLogger({
|
|
71
|
+
module: 'parent',
|
|
72
|
+
context: { env: 'test', requestId: '123' },
|
|
73
|
+
minLevel: 'info',
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
const child = parent.child({
|
|
77
|
+
module: 'child',
|
|
78
|
+
context: { operation: 'read' },
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
child.info('Child operation');
|
|
82
|
+
expect(consoleLogSpy).toHaveBeenCalledTimes(1);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe('getLogger helper', () => {
|
|
87
|
+
it('should instantiate logger with module identifier and context', () => {
|
|
88
|
+
const log = getLogger('audit', { tenant: 'org-1' });
|
|
89
|
+
expect(log).toBeDefined();
|
|
90
|
+
expect(typeof log.info).toBe('function');
|
|
91
|
+
expect(typeof log.error).toBe('function');
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe('formatters', () => {
|
|
96
|
+
it('jsonFormatter should produce valid JSON', () => {
|
|
97
|
+
const entry: LogEntry = {
|
|
98
|
+
level: 'info',
|
|
99
|
+
message: 'Test JSON message',
|
|
100
|
+
timestamp: new Date().toISOString(),
|
|
101
|
+
module: 'test-mod',
|
|
102
|
+
context: { count: 42, active: true },
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const result = jsonFormatter(entry);
|
|
106
|
+
const parsed = JSON.parse(result);
|
|
107
|
+
|
|
108
|
+
expect(parsed.level).toBe('info');
|
|
109
|
+
expect(parsed.message).toBe('Test JSON message');
|
|
110
|
+
expect(parsed.module).toBe('test-mod');
|
|
111
|
+
expect(parsed.context.count).toBe(42);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('jsonFormatter should handle circular references safely', () => {
|
|
115
|
+
const circularObj: any = { name: 'cyclic' };
|
|
116
|
+
circularObj.self = circularObj;
|
|
117
|
+
|
|
118
|
+
const entry: LogEntry = {
|
|
119
|
+
level: 'warn',
|
|
120
|
+
message: 'Circular test',
|
|
121
|
+
timestamp: new Date().toISOString(),
|
|
122
|
+
context: circularObj,
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const result = jsonFormatter(entry);
|
|
126
|
+
expect(() => JSON.parse(result)).not.toThrow();
|
|
127
|
+
const parsed = JSON.parse(result);
|
|
128
|
+
expect(parsed.context.self).toBe('[Circular]');
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('prettyFormatter should format human-readable output with ANSI colors', () => {
|
|
132
|
+
const entry: LogEntry = {
|
|
133
|
+
level: 'error',
|
|
134
|
+
message: 'Something broke',
|
|
135
|
+
timestamp: '2026-10-11T14:00:00.000Z',
|
|
136
|
+
module: 'system',
|
|
137
|
+
context: { service: 'api' },
|
|
138
|
+
error: {
|
|
139
|
+
name: 'Error',
|
|
140
|
+
message: 'Broken connection',
|
|
141
|
+
stack: 'Error: Broken connection\n at index.ts:1',
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const result = prettyFormatter(entry);
|
|
146
|
+
expect(result).toContain('ERROR');
|
|
147
|
+
expect(result).toContain('system');
|
|
148
|
+
expect(result).toContain('Something broke');
|
|
149
|
+
expect(result).toContain('service=');
|
|
150
|
+
expect(result).toContain('api');
|
|
151
|
+
expect(result).toContain('Broken connection');
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
});
|