# CLQMS Frontend Implementation Plan
## Project Overview
**CLQMS** (Clinical Laboratory Quality Management System) frontend built with SvelteKit using the KISS (Keep It Simple) principle.
## Architecture Decisions (KISS Principles)
- **No TypeScript** - Plain JavaScript to keep it simple
- **Tailwind CSS & DaisyUI** - Utility classes, minimal custom CSS
- **Simple Fetch API** - Manual wrapper functions, no codegen
- **SvelteKit File-based Routing** - Standard patterns
- **Server-side auth checking** - SvelteKit hooks for session validation
## Project Structure\n\n```\nsrc/\n├── lib/\n│ ├── api/ # API service functions\n│ │ ├── client.js # Base fetch wrapper with auth\n│ │ ├── auth.js # Auth endpoints\n│ │ ├── valuesets.js # ValueSet endpoints\n│ │ ├── locations.js # Location endpoints\n│ │ ├── contacts.js # Contact endpoints\n│ │ ├── specialties.js # Specialty endpoints\n│ │ └── ... # Other endpoint modules\n│ ├── components/ # Reusable Svelte components\n│ │ ├── DataTable.svelte\n│ │ ├── Modal.svelte\n│ │ ├── SelectDropdown.svelte\n│ │ ├── Sidebar.svelte\n│ │ └── ToastContainer.svelte\n│ ├── stores/ # Svelte stores\n│ │ ├── auth.js # Auth state\n│ │ └── valuesets.js # Cached lookup values\n│ └── utils/ # Utility functions\n│ └── toast.js # Toast notifications\n├── routes/\n│ ├── +layout.svelte # Root layout with nav\n│ ├── +page.svelte # Redirect to login\n│ ├── login/\n│ │ └── +page.svelte\n│ └── (app)/ # Group: protected routes\n│ ├── +layout.svelte # Auth check with sidebar\n│ ├── dashboard/\n│ │ └── +page.svelte\n│ └── master-data/\n│ ├── +page.svelte\n│ ├── locations/\n│ ├── contacts/\n│ ├── specialties/\n│ └── valuesets/\n├── app.css # Global styles with Tailwind\n└── app.html # HTML template\n```
## Implementation Phases
### Phase 0: Foundation ✅ COMPLETED
**Priority:** High | **Time Estimate:** 1-2 hours | **Status:** Done
- [x] Initialize SvelteKit project with Tailwind CSS
- [x] Configure API base URL and environment variables
- [x] Create base API client with JWT token handling
- [x] Implement login/logout flow
- [x] Create root layout with navigation
- [x] Set up protected route group with auth checks
- [x] Create dashboard homepage
**Key Files:**
- `src/lib/api/client.js` - Base fetch wrapper
- `src/lib/api/auth.js` - Auth endpoints
- `src/lib/stores/auth.js` - Auth state management
- `src/routes/+layout.svelte` - Root layout
- `src/routes/(app)/+layout.svelte` - Protected layout
- `src/routes/login/+page.svelte` - Login page
---
### Phase 1: Foundation Data ✅ COMPLETED
**Priority:** High | **Time Estimate:** 4-6 hours | **Status:** Done
**Why First:** These are prerequisites for all other modules. ValueSets provide dropdown options; Master Data provides reference entities.
#### 1a. System ValueSets Module (Library) ✅ COMPLETED
System ValueSets are pre-defined lookup values used throughout the application (gender, marital status, specimen types, etc.). These are read-only libraries fetched from JSON files and cached.
- [x] ValueSet browser page (view system value sets by key)
- [x] ValueSet items viewer (read-only)
- [x] Cache frequently used value sets in stores
- [x] SelectDropdown component using cached value sets
- [x] Refresh ValueSet cache
**API Endpoints (Library/System ValueSets):**
- `GET /api/valueset` - List all library value sets with item counts
- `GET /api/valueset/{key}` - Get library value set by key (e.g., 'marital_status', 'sex')
- `POST /api/valueset/refresh` - Refresh library ValueSet cache from JSON files
#### 1b. Master Data - Locations & Contacts ✅ COMPLETED
- [x] Locations list page with search (supports LocCode, LocName filters)
- [x] Locations create/edit form
- [x] Contacts (Physicians) list page
- [x] Contacts create/edit form
**API Endpoints:**
**Locations:**
- `GET /api/location` - List locations (query: LocCode, LocName)
- `POST /api/location` - Create location (required: LocCode, LocFull)
- `PATCH /api/location` - Update location (required: LocCode, LocFull)
- `DELETE /api/location` - Delete location (body: { LocationID })
- `GET /api/location/{id}` - Get location details
**Location Schema:**
- `LocationID` - Primary key (auto-generated)
- `SiteID` - Reference to site
- `LocCode` - Location code, max 6 chars (required)
- `Parent` - Parent location ID (for hierarchical locations)
- `LocFull` - Full location name, max 255 chars (required)
- `Description` - Description, max 255 chars
- `LocType` - Location type (e.g., ROOM, WARD, BUILDING)
- `CreateDate`, `EndDate` - Timestamps
**Contacts:**
- `GET /api/contact` - List contacts
- `POST /api/contact` - Create contact (required: NameFirst)
- `PATCH /api/contact` - Update contact
- `DELETE /api/contact` - Delete contact
- `GET /api/contact/{id}` - Get contact details
**Contact Schema:**
- `ContactID` - Primary key (auto-generated)
- `NameFirst` - First name (required)
- `NameLast` - Last name
- `Title` - Title (e.g., Dr, Mr, Mrs)
- `Initial` - Middle initial
- `Birthdate` - Date of birth (ISO 8601)
- `EmailAddress1`, `EmailAddress2` - Email addresses
- `Phone` - Primary phone
- `MobilePhone1`, `MobilePhone2` - Mobile numbers
- `Specialty` - Medical specialty code
- `SubSpecialty` - Sub-specialty code
- `CreateDate`, `EndDate` - Timestamps
#### 1d. Master Data - Supporting Entities ✅ COMPLETED
- [x] Occupations management
- [x] Medical Specialties management
- [x] Counters management (for ID generation)
**API Endpoints:**
**Occupations:**
- `GET /api/occupation` - List occupations
- `POST /api/occupation` - Create occupation (required: OccCode, OccText)
- `PATCH /api/occupation` - Update occupation (required: OccCode, OccText)
- `GET /api/occupation/{id}` - Get occupation details
**Occupation Schema:**
- `OccupationID` - Primary key (auto-generated)
- `OccCode` - Occupation code (required)
- `OccText` - Occupation name/text (required)
- `Description` - Additional description
- `CreateDate` - Creation timestamp
**Medical Specialties:**
- `GET /api/medicalspecialty` - List specialties
- `POST /api/medicalspecialty` - Create specialty (required: SpecialtyText)
- `PATCH /api/medicalspecialty` - Update specialty (required: SpecialtyText)
- `GET /api/medicalspecialty/{id}` - Get specialty details
**Medical Specialty Schema:**
- `SpecialtyID` - Primary key (auto-generated)
- `SpecialtyText` - Specialty name/text (required)
- `Parent` - Parent specialty ID (for hierarchical structure)
- `Title` - Title/abbreviation
- `CreateDate`, `EndDate` - Timestamps
**Counters:**
- `GET /api/counter` - List counters
- `POST /api/counter` - Create counter
- `PATCH /api/counter` - Update counter
- `DELETE /api/counter` - Delete counter (body: { CounterID })
- `GET /api/counter/{id}` - Get counter details
**Counter Schema:**
- `CounterID` - Primary key (auto-generated)
- `CounterDesc` - Counter description/name
- `CounterValue` - Current counter value
- `CounterStart` - Starting value
- `CounterEnd` - Ending value (for auto-reset)
- `CounterReset` - Reset pattern (D=Daily, M=Monthly, Y=Yearly)
#### 1e. Master Data - Geography ✅ COMPLETED
- [x] Geographical areas list
- [x] Provinces list (read-only dropdown)
- [x] Cities list with province filter
**API Endpoints:**
- `GET /api/areageo` - List all geographical areas
- `GET /api/areageo/provinces` - List provinces
- `GET /api/areageo/cities?province_id={id}` - List cities (with province filter)
**Notes:**
- Geography endpoints are read-only (no POST/PATCH/DELETE)
- Used for patient address province/city selection
- Returns hierarchical location data
---
### Phase 2: Patient Management\n**Priority:** High | **Time Estimate:** 3-4 hours\n\n**Dependencies:** Master Data (locations, contacts, occupations, provinces/cities)\n\n#### 2a. Patient CRUD\n- [ ] Patients list page with pagination and search\n- [ ] Patient create form with validation\n- [ ] Patient edit form\n- [ ] Patient detail view\n- [ ] Patient delete with confirmation\n\n**API Endpoints:**\n- `GET /api/patient` - List patients (query: page, perPage, InternalPID, PatientID, Name, Birthdate)\n- `POST /api/patient` - Create patient\n- `PATCH /api/patient` - Update patient\n- `DELETE /api/patient` - Delete patient (soft delete, body: { InternalPID })\n- `GET /api/patient/{id}` - Get patient by ID\n- `GET /api/patient/check` - Check if patient exists (query: PatientID, EmailAddress1)
#### 2b. Advanced Patient Features
- [ ] Patient identifier management (KTP, PASS, SSN, etc.)
- [ ] Patient linking (family relationships)
- [ ] Custodian/guardian assignment
- [ ] Patient address management
**Fields to Implement:**
- PatientID, AlternatePID
- Prefix, NameFirst, NameMiddle, NameLast, NameMaiden, Suffix
- Sex, Birthdate, PlaceOfBirth, Citizenship
- Address fields (Street_1/2/3, ZIP, Province, City, Country)
- Contact (Phone, MobilePhone, EmailAddress1/2)
- Identifiers (PatIdt - type and number)
- Demographics (Race, MaritalStatus, Religion, Ethnic)
- Linked patients (LinkTo)
- Custodian
- DeathIndicator, TimeOfDeath
- Comments (PatCom)
---
### Phase 3: Patient Visits
**Priority:** High | **Time Estimate:** 2-3 hours
**Dependencies:** Patients, Master Data (locations, contacts)
- [ ] Visits list page with filters
- [ ] Create visit form
- [ ] Edit visit form
- [ ] View visits by patient
- [ ] ADT workflow (Admit/Discharge/Transfer)
**API Endpoints:**
- `GET /api/patvisit` - List visits
- `POST /api/patvisit` - Create visit
- `PATCH /api/patvisit` - Update visit
- `DELETE /api/patvisit` - Delete visit
- `GET /api/patvisit/{id}` - Get visit by ID
- `GET /api/patvisit/patient/{patientId}` - Get visits by patient
- `POST /api/patvisitadt` - Create ADT visit
- `PATCH /api/patvisitadt` - Update ADT visit
**Fields:**
- VisitID, PatientID, VisitDate, VisitType
- SiteID, LocationID, DepartmentID
- AttendingPhysician, ReferringPhysician
---
### Phase 4: Specimen Management
**Priority:** Medium | **Time Estimate:** 2-3 hours
**Dependencies:** ValueSets (specimen types, collection methods, statuses)
- [ ] Specimens list page
- [ ] Specimen create/edit forms
- [ ] Container definitions management
- [ ] Specimen preparation methods
- [ ] Specimen statuses
- [ ] Collection methods
- [ ] Samples list with status filtering
**API Endpoints:**
- `GET /api/specimen` - List specimens
- `POST /api/specimen` - Create specimen
- `PATCH /api/specimen` - Update specimen
- `GET /api/specimen/{id}` - Get specimen details
- `GET /api/specimen/container` - List containers
- `POST /api/specimen/container` - Create container
- `PATCH /api/specimen/container` - Update container
- `GET /api/specimen/container/{id}` - Get container details
- `GET /api/specimen/prep` - List preparations
- `POST /api/specimen/prep` - Create preparation
- `PATCH /api/specimen/prep` - Update preparation
- `GET /api/specimen/prep/{id}` - Get preparation details
- `GET /api/specimen/status` - List statuses
- `POST /api/specimen/status` - Create status
- `PATCH /api/specimen/status` - Update status
- `GET /api/specimen/status/{id}` - Get status details
- `GET /api/specimen/collection` - List collection methods
- `POST /api/specimen/collection` - Create collection method
- `PATCH /api/specimen/collection` - Update collection method
- `GET /api/specimen/collection/{id}` - Get collection method details
- `GET /api/sample` - Get samples (with status filter)
---
### Phase 5: Test Catalog\n**Priority:** Medium | **Time Estimate:** 2-3 hours\n\n**Dependencies:** Organization (disciplines, departments), ValueSets\n\n- [ ] Test definitions list with filtering\n- [ ] Create/edit test definitions\n- [ ] Test mapping management (host/client codes)\n\n**API Endpoints:**\n- `GET /api/tests` - List tests\n- `POST /api/tests` - Create test\n- `PATCH /api/tests` - Update test\n- `GET /api/tests/{id}` - Get test details\n\n**Query Parameters:**\n- `page`, `perPage` - Pagination\n- `SiteID` - Filter by site\n- `TestType` - Filter by type (TEST, PARAM, CALC, GROUP, TITLE)\n- `VisibleScr` - Filter by screen visibility (0=hidden, 1=visible)\n- `VisibleRpt` - Filter by report visibility (0=hidden, 1=visible)\n- `TestSiteName` - Search by test name or code\n\n**Test Types:**\n- `TEST` - Technical test\n- `PARAM` - Parameter\n- `CALC` - Calculated\n- `GROUP` - Panel/Profile\n- `TITLE` - Section header\n\n**Test Definition Schema:**\n- `id` - Primary key\n- `TestCode` - Test code\n- `TestName` - Test name\n- `TestType` - Type (TEST, PARAM, CALC, GROUP, TITLE)\n- `DisciplineID` - Reference to discipline\n- `DepartmentID` - Reference to department\n- `SpecimenType` - Specimen type code\n- `Unit` - Measurement unit\n- `Formula` - Calculation formula
---
### Phase 6: Orders\n**Priority:** High | **Time Estimate:** 3-4 hours\n\n**Dependencies:** Patients, Visits, Tests, Specimen, ValueSets (priorities, statuses)\n\n- [ ] Orders list with status filtering\n- [ ] Create order with test selection\n- [ ] Order detail view\n- [ ] Update order status\n- [ ] Order items management\n\n**API Endpoints:**\n- `GET /api/ordertest` - List orders (filters: OrderStatus, InternalPID, page, perPage)\n- `POST /api/ordertest` - Create order (requires: PatientID, Tests array)\n- `PATCH /api/ordertest` - Update order\n- `DELETE /api/ordertest` - Delete order\n- `GET /api/ordertest/{id}` - Get order details\n- `POST /api/ordertest/status` - Update order status (body: { OrderID, OrderStatus })\n\n**Order Status Values:**\n- `ORD` - Ordered\n- `SCH` - Scheduled\n- `ANA` - Analysis\n- `VER` - Verified\n- `REV` - Reviewed\n- `REP` - Reported\n\n**Priority Values:**\n- `R` - Routine\n- `S` - Stat\n- `U` - Urgent\n\n**OrderTest Schema:**\n- `OrderID` - Order identifier\n- `PatientID` - Reference to patient\n- `VisitID` - Reference to visit\n- `OrderDate` - Order timestamp (ISO 8601)\n- `OrderStatus` - Status code (ORD, SCH, ANA, VER, REV, REP)\n- `Priority` - Priority code (R, S, U)\n- `SiteID` - Reference to site\n- `RequestingPhysician` - Requesting physician identifier\n\n**Create Order Request:**\n```json\n{\n \"PatientID\": \"string\",\n \"VisitID\": \"string\" (optional),\n \"Priority\": \"R|S|U\",\n \"SiteID\": integer (optional),\n \"RequestingPhysician\": \"string\" (optional),\n \"Tests\": [\n {\n \"TestID\": integer,\n \"SpecimenType\": \"string\" (optional)\n }\n ]\n}\n```
---
### Phase 7: Results & Dashboard
**Priority:** High | **Time Estimate:** 2-3 hours
**Dependencies:** Orders
- [ ] Dashboard with summary cards
- [ ] Results list with patient filtering
- [ ] Sample tracking view
**API Endpoints:**
- `GET /api/dashboard` - Get dashboard summary
- Returns: pendingOrders, todayResults, criticalResults, activePatients
- `GET /api/result` - Get patient results (filter by PatientID, pagination with page)
**Dashboard Metrics:**
- pendingOrders - Number of pending orders
- todayResults - Results processed today
- criticalResults - Critical/panic results
- activePatients - Currently active patients
---
### Phase 8: User-defined ValueSets
**Priority:** Medium | **Time Estimate:** 3-4 hours
**Dependencies:** Test Catalog (Phase 5)
User-defined ValueSets are created and managed by lab administrators in the database (not from JSON files). These require full CRUD operations and are used for test result interpretation (reference ranges, flags, interpretations).
- [ ] User ValueSet definitions list page
- [ ] User ValueSet definition create/edit form
- [ ] User ValueSet items management (CRUD)
**API Endpoints:**
**User ValueSet Definitions:**
- `GET /api/valueset/user/def` - List user value set definitions
- `POST /api/valueset/user/def` - Create user value set definition
- `GET /api/valueset/user/def/{id}` - Get user value set definition by ID
- `PUT /api/valueset/user/def/{id}` - Update user value set definition
- `DELETE /api/valueset/user/def/{id}` - Delete user value set definition
**User ValueSet Items:**
- `GET /api/valueset/user/items` - List user value set items (filter by VSetID)
- `POST /api/valueset/user/items` - Create user value set item
- `GET /api/valueset/user/items/{id}` - Get user value set item by ID
- `PUT /api/valueset/user/items/{id}` - Update user value set item
- `DELETE /api/valueset/user/items/{id}` - Delete user value set item
**ValueSetDef Schema:**
- `id` - Primary key
- `VSetCode` - Value set code
- `VSetName` - Value set name
- `Description` - Description
- `Category` - Category
**ValueSetItem Schema:**
- `id` - Primary key
- `VSetID` - Reference to ValueSet definition
- `VValue` - Value code
- `VLabel` - Display label
- `VSeq` - Sequence order
- `IsActive` - Active flag (boolean)
---
### Phase 9: Organization Structure\n**Priority:** Medium | **Time Estimate:** 2-3 hours\n\n- [ ] Accounts management\n- [ ] Sites management\n- [ ] Disciplines management\n- [ ] Departments management\n- [ ] Workstations management\n\n**API Endpoints:**\n\n**Accounts:**\n- `GET /api/organization/account` - List accounts\n- `POST /api/organization/account` - Create account\n- `PATCH /api/organization/account` - Update account (body: { id, AccountName, AccountCode, AccountType })\n- `DELETE /api/organization/account` - Delete account (body: { id })\n- `GET /api/organization/account/{id}` - Get account details\n\n**Account Schema:**\n- `id` - Primary key\n- `AccountName` - Account name\n- `AccountCode` - Account code\n- `AccountType` - Account type\n\n**Sites:**\n- `GET /api/organization/site` - List sites\n- `POST /api/organization/site` - Create site\n- `PATCH /api/organization/site` - Update site (body: { id, SiteName, SiteCode, AccountID })\n- `DELETE /api/organization/site` - Delete site (body: { id })\n- `GET /api/organization/site/{id}` - Get site details\n\n**Site Schema:**\n- `id` - Primary key\n- `SiteName` - Site name\n- `SiteCode` - Site code\n- `AccountID` - Reference to account\n\n**Disciplines:**\n- `GET /api/organization/discipline` - List disciplines\n- `POST /api/organization/discipline` - Create discipline\n- `PATCH /api/organization/discipline` - Update discipline (body: { id, DisciplineName, DisciplineCode })\n- `DELETE /api/organization/discipline` - Delete discipline (body: { id })\n- `GET /api/organization/discipline/{id}` - Get discipline details\n\n**Discipline Schema:**\n- `id` - Primary key\n- `DisciplineName` - Discipline name\n- `DisciplineCode` - Discipline code\n\n**Departments:**\n- `GET /api/organization/department` - List departments\n- `POST /api/organization/department` - Create department\n- `PATCH /api/organization/department` - Update department (body: { id, DeptName, DeptCode, SiteID })\n- `DELETE /api/organization/department` - Delete department (body: { id })\n- `GET /api/organization/department/{id}` - Get department details\n\n**Department Schema:**\n- `id` - Primary key\n- `DeptName` - Department name\n- `DeptCode` - Department code\n- `SiteID` - Reference to site\n\n**Workstations:**\n- `GET /api/organization/workstation` - List workstations\n- `POST /api/organization/workstation` - Create workstation\n- `PATCH /api/organization/workstation` - Update workstation (body: { id, WorkstationName, WorkstationCode, SiteID, DepartmentID })\n- `DELETE /api/organization/workstation` - Delete workstation (body: { id })\n- `GET /api/organization/workstation/{id}` - Get workstation details\n\n**Workstation Schema:**\n- `id` - Primary key\n- `WorkstationName` - Workstation name\n- `WorkstationCode` - Workstation code\n- `SiteID` - Reference to site\n- `DepartmentID` - Reference to department
---
### Phase 10: Edge API (Instrument Integration)
**Priority:** Low | **Time Estimate:** 2-3 hours
- [ ] Edge results viewer
- [ ] Pending orders for instruments
- [ ] Instrument status monitoring
**API Endpoints:**
- `GET /api/edge/orders` - Fetch pending orders (filter by instrument_id, status)
- `POST /api/edge/orders/{orderId}/ack` - Acknowledge order delivery
- `POST /api/edge/results` - Receive results from instrument (tiny-edge)
- `POST /api/edge/status` - Log instrument status (status: online, offline, error, maintenance)
---
### Phase 11: Authentication
**Priority:** High | **Time Estimate:** 1-2 hours | **Status:** ✅ COMPLETED
Foundation authentication system for user login/logout and session management.
- [x] Login page with form validation
- [x] JWT token handling (HTTP-only cookie)
- [x] Logout functionality
- [x] Auth state management
- [x] Protected route guards
- [x] Auth status checking
**API Endpoints:**
**V1 Authentication:**
- `POST /api/auth/login` - User login (returns JWT in cookie)
- `POST /api/auth/logout` - User logout
- `GET /api/auth/check` - Check authentication status
- `POST /api/auth/register` - Register new user
- `POST /api/auth/change_pass` - Change password (authenticated)
**V2 Authentication:**
- `POST /v2/auth/login` - V2 User login
- `POST /v2/auth/logout` - V2 User logout
- `GET /v2/auth/check` - V2 Check authentication
- `POST /v2/auth/register` - V2 Register new user
**Security:**
- JWT tokens stored in HTTP-only cookies
- Bearer token support for API requests
- Automatic redirect to login on 401 responses
---
## Reusable Components to Build
### 1. FormInput.svelte
Text input with label, validation, and error display.
**Status:** Not yet implemented - using native inputs with DaisyUI styling
```svelte