- System Overview
- Architecture
- Technology Stack
- Database Schema
- Authentication & Authorization
- Core Modules
- API Endpoints
- Installation Guide
- Configuration
- Security Features
The EMR System is a comprehensive healthcare management application designed to digitize and streamline medical record keeping, patient management, appointment scheduling, medication tracking, laboratory management, and billing operations.
- Patient Management: Complete patient demographics, medical history, and health records
- Appointment Scheduling: Calendar-based appointment booking and management
- Clinical Documentation: Comprehensive medical records, progress notes, and assessments
- Medication Management: Prescription tracking, dosage management, and drug interactions
- Laboratory Integration: Lab orders, results tracking, and diagnostic reports
- Billing & Insurance: Invoice generation, insurance claims, and payment tracking
- Role-Based Access Control: Secure multi-role authentication system
- Audit Trail: Complete logging of all system activities
The EMR System follows a layered architecture with clear separation of concerns:
┌─────────────────────────────────────────┐
│ Presentation Layer │
│ (React Frontend / Swagger UI) │
└─────────────────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ API Layer (Controllers) │
│ (RESTful Web API - .NET 8) │
└─────────────────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ Business Logic Layer │
│ (Services & Domain Logic) │
└─────────────────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ Data Access Layer │
│ (Repositories & Entity Framework) │
└─────────────────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ Database Layer │
│ (SQL Server) │
└─────────────────────────────────────────┘
EMR-System/
├── EMRDataLayer/ # Data Access Layer
│ ├── Model/ # Entity Models
│ │ ├── Patient.cs
│ │ ├── Provider.cs
│ │ ├── Appointment.cs
│ │ ├── MedicalRecord.cs
│ │ ├── Prescription.cs
│ │ ├── Medication.cs
│ │ ├── LabOrder.cs
│ │ ├── LabResult.cs
│ │ ├── Billing.cs
│ │ ├── BillingItem.cs
│ │ ├── Insurance.cs
│ │ ├── Allergy.cs
│ │ ├── Immunization.cs
│ │ ├── VitalSign.cs
│ │ ├── User.cs
│ │ └── Address.cs
│ ├── DataContext/
│ │ └── EMRDbContext.cs # Database Context
│ └── Repository/ # Repository Pattern
│ ├── IRepository/ # Interfaces
│ └── Repository.cs # Implementations
│
├── EMRWebAPI/ # API Layer
│ ├── Controllers/ # API Controllers
│ │ ├── AuthController.cs
│ │ ├── UserController.cs
│ │ └── [Other Controllers]
│ ├── Services/ # Business Logic
│ │ ├── JwtService.cs
│ │ ├── UserService.cs
│ │ └── IServices/
│ ├── Model/ # DTOs
│ │ ├── LoginDTO.cs
│ │ ├── RegisterDto.cs
│ │ ├── RefreshTokenDto.cs
│ │ └── [Other DTOs]
│ ├── AutoMapper/ # Object Mapping
│ ├── Program.cs # Application Entry
│ └── appsettings.json # Configuration
│
└── emrwebfrontend/ # React Frontend
└── [React Components]
- Framework: .NET 8.0
- ORM: Entity Framework Core 8.0
- Database: SQL Server (LocalDB for development)
- Authentication: JWT (JSON Web Tokens)
- API Documentation: Swagger/OpenAPI 3.0
- Logging: NLog
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.0.0" />- Framework: React.js
- UI Library: Bootstrap
- HTTP Client: Axios
Extended with custom User model for authentication.
Patients
├── Id (PK)
├── FirstName
├── LastName
├── MiddleName
├── DateOfBirth
├── Gender
├── SocialSecurityNumber
├── Email
├── PhoneNumber
├── EmergencyContact
├── EmergencyContactName
├── BloodType
├── MaritalStatus
├── Occupation
├── Employer
├── PreferredLanguage
├── Ethnicity
├── Race
├── IsActive
├── CreatedDate
├── ModifiedDate
├── CreatedBy
├── ModifiedBy
└── AddressId (FK)Providers
├── Id (PK)
├── FirstName
├── LastName
├── MiddleName
├── Specialization
├── LicenseNumber
├── NPI (National Provider Identifier)
├── DEA (Drug Enforcement Administration)
├── Email
├── PhoneNumber
├── IsActive
├── CreatedDate
├── ModifiedDate
└── UserId (FK)Appointments
├── Id (PK)
├── PatientId (FK)
├── ProviderId (FK)
├── AppointmentDate
├── StartTime
├── EndTime
├── Status (Scheduled, Confirmed, InProgress, Completed, Cancelled, NoShow)
├── AppointmentType
├── ReasonForVisit
├── Notes
├── RoomNumber
├── CreatedDate
└── ModifiedDateMedicalRecords
├── Id (PK)
├── PatientId (FK)
├── ProviderId (FK)
├── VisitDate
├── ChiefComplaint
├── HistoryOfPresentIllness
├── PhysicalExamination
├── Assessment
├── Diagnosis
├── TreatmentPlan
├── ProgressNotes
├── RecordType
├── IsSigned
├── SignedDate
├── CreatedDate
└── ModifiedDateMedications
├── Id (PK)
├── Name
├── GenericName
├── BrandName
├── Category
├── Form (Tablet, Capsule, Liquid)
├── Strength
├── NDC (National Drug Code)
├── Description
├── SideEffects
├── Contraindications
├── IsControlledSubstance
├── DEASchedule
├── IsActive
├── CreatedDate
└── ModifiedDatePrescriptions
├── Id (PK)
├── PatientId (FK)
├── ProviderId (FK)
├── MedicationId (FK)
├── Dosage
├── Frequency
├── Route (Oral, IV, IM)
├── Quantity
├── Refills
├── StartDate
├── EndDate
├── Instructions
├── Status (Active, Discontinued, Completed, OnHold)
├── IsGenericAllowed
├── CreatedDate
└── ModifiedDateLabOrders
├── Id (PK)
├── PatientId (FK)
├── ProviderId (FK)
├── TestName
├── TestCode
├── Category
├── Priority (Stat, Urgent, Routine)
├── Status (Ordered, InProgress, Completed, Cancelled)
├── OrderedDate
├── CollectedDate
├── CompletedDate
└── ClinicalNotesLabResults
├── Id (PK)
├── LabOrderId (FK)
├── TestComponent
├── Value
├── Unit
├── ReferenceRange
├── Flag (Normal, High, Low, Critical)
├── ResultDate
├── Comments
├── PerformedBy
└── CreatedDateBillings
├── Id (PK)
├── PatientId (FK)
├── InvoiceNumber
├── InvoiceDate
├── DueDate
├── TotalAmount
├── PaidAmount
├── BalanceAmount
├── Status (Unpaid, Partial, Paid, Overdue)
├── PaymentMethod
├── PaymentDate
├── InsuranceId (FK)
├── InsuranceCoverage
├── PatientResponsibility
├── Notes
├── CreatedDate
└── ModifiedDateBillingItems
├── Id (PK)
├── BillingId (FK)
├── Description
├── CPTCode (Current Procedural Terminology)
├── ICDCode (International Classification of Diseases)
├── Quantity
├── UnitPrice
├── TotalPrice
└── CreatedDateInsurances
├── Id (PK)
├── PatientId (FK)
├── InsuranceCompany
├── PolicyNumber
├── GroupNumber
├── PlanType (HMO, PPO, EPO, POS)
├── PolicyHolderName
├── PolicyHolderRelationship
├── PolicyHolderSSN
├── EffectiveDate
├── ExpirationDate
├── InsurancePhone
├── InsuranceAddress
├── IsPrimary
├── IsActive
├── CreatedDate
└── ModifiedDateAllergies
├── Id (PK)
├── PatientId (FK)
├── Allergen
├── AllergyType (Drug, Food, Environmental)
├── Severity (Mild, Moderate, Severe, Life-threatening)
├── Reaction
├── OnsetDate
├── Notes
├── IsActive
├── CreatedDate
└── ModifiedDateImmunizations
├── Id (PK)
├── PatientId (FK)
├── VaccineName
├── CVXCode
├── AdministeredDate
├── AdministeredBy
├── Route
├── Site
├── LotNumber
├── Manufacturer
├── ExpirationDate
├── DoseNumber
├── Notes
├── CreatedDate
└── ModifiedDateVitalSigns
├── Id (PK)
├── PatientId (FK)
├── MeasurementDate
├── Temperature
├── TemperatureUnit
├── SystolicBP
├── DiastolicBP
├── HeartRate
├── RespiratoryRate
├── OxygenSaturation
├── Height
├── HeightUnit
├── Weight
├── WeightUnit
├── BMI
├── MeasuredBy
├── Notes
└── CreatedDatePatient 1──────* Appointment
Patient 1──────* MedicalRecord
Patient 1──────* Prescription
Patient 1──────* LabOrder
Patient 1──────* Billing
Patient 1──────* Insurance
Patient 1──────* Allergy
Patient 1──────* Immunization
Patient 1──────* VitalSign
Provider 1─────* Appointment
Provider 1─────* MedicalRecord
Provider 1─────* Prescription
Provider 1─────* LabOrder
Medication 1───* Prescription
LabOrder 1─────* LabResult
Billing 1──────* BillingItem
Billing *──────1 Insurance
User 1─────────1 Provider
User *─────────1 Address
Patient *──────1 Address
The system uses JSON Web Tokens (JWT) for stateless authentication:
{
"header": {
"alg": "HS256",
"typ": "JWT"
},
"payload": {
"nameid": "user-guid",
"email": "user@example.com",
"FirstName": "John",
"LastName": "Doe",
"role": ["Doctor", "Administrator"],
"exp": 1735689600
}
}- Algorithm: HMAC-SHA256
- Expiration: 24 hours (configurable)
- Refresh Token: Supported for seamless re-authentication
- Claims: User ID, Email, Name, Roles
-
Administrator
- Full system access
- User management
- System configuration
- All module access
-
Doctor
- Patient management
- Medical records (full access)
- Prescriptions
- Lab orders
- Appointments
-
Nurse
- Patient vitals
- Appointments
- Medical records (view/update)
- Medication administration
-
Receptionist
- Patient registration
- Appointment scheduling
- Basic patient information
-
Lab Technician
- Lab orders
- Lab results entry
- Diagnostic reports
-
Billing Staff
- Billing management
- Insurance processing
- Payment tracking
- Invoice generation
services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly",
policy => policy.RequireRole("Administrator"));
options.AddPolicy("DoctorOnly",
policy => policy.RequireRole("Doctor", "Administrator"));
options.AddPolicy("NurseOnly",
policy => policy.RequireRole("Nurse", "Doctor", "Administrator"));
options.AddPolicy("LabTechOnly",
policy => policy.RequireRole("Lab Technician", "Doctor", "Administrator"));
options.AddPolicy("BillingOnly",
policy => policy.RequireRole("Billing Staff", "Administrator"));
});Purpose: Manage complete patient demographics, contacts, and personal information.
Key Features:
- Patient registration and profile management
- Demographics tracking
- Emergency contact information
- Medical history
- Insurance information linking
- Address management
Purpose: Manage patient appointments with healthcare providers.
Key Features:
- Appointment booking
- Calendar view
- Appointment status tracking
- Reminder notifications
- Conflict detection
- Room assignment
Purpose: Comprehensive medical record keeping and clinical notes.
Key Features:
- SOAP notes (Subjective, Objective, Assessment, Plan)
- Chief complaints
- Physical examination records
- Diagnosis tracking
- Treatment plans
- Progress notes
- Electronic signature support
Purpose: Prescription and medication tracking.
Key Features:
- Medication database
- Prescription creation
- Dosage and frequency management
- Refill tracking
- Drug interaction alerts
- Controlled substance tracking (DEA schedule)
Purpose: Lab test ordering and results management.
Key Features:
- Lab order creation
- Test catalog
- Result entry and tracking
- Critical value flagging
- Reference range validation
- Report generation
Purpose: Financial management and insurance processing.
Key Features:
- Invoice generation
- CPT/ICD code support
- Insurance claim processing
- Payment tracking
- Statement generation
- Outstanding balance reports
Purpose: Patient safety through allergy and vaccination records.
Key Features:
- Allergy documentation
- Severity classification
- Reaction tracking
- Immunization records
- Vaccination schedules
- CVX code support
Purpose: Track patient vital signs and measurements.
Key Features:
- Temperature, BP, heart rate
- Height, weight, BMI
- Oxygen saturation
- Respiratory rate
- Historical trending
- Unit conversion
Register a new user (Admin only)
{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@example.com",
"phoneNumber": "+1234567890",
"password": "SecureP@ss123",
"confirmPassword": "SecureP@ss123",
"roles": ["Doctor"]
}User login
{
"email": "john.doe@example.com",
"password": "SecureP@ss123"
}Response:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "base64-encoded-refresh-token",
"user": {
"id": "user-guid",
"email": "john.doe@example.com",
"firstName": "John",
"lastName": "Doe",
"roles": ["Doctor"]
}
}Refresh expired access token
{
"accessToken": "expired-token",
"refreshToken": "valid-refresh-token"
}Get current user profile (Authenticated)
Logout user (Authenticated)
- .NET 8.0 SDK or later
- SQL Server (LocalDB, Express, or Full)
- Visual Studio 2022 or VS Code
- Node.js (for frontend)
- Clone the Repository
git clone https://github.com/JoelHJames1/EMR-System.git
cd EMR-System- Restore NuGet Packages
cd EMRWebAPI
dotnet restore- Update Connection String
Edit
appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Your-SQL-Server-Connection-String"
}
}- Create Database
dotnet ef database update --project ../EMRDataLayerOr create migration if needed:
dotnet ef migrations add InitialCreate --project ../EMRDataLayer
dotnet ef database update --project ../EMRDataLayer- Run the Application
dotnet runThe API will be available at: https://localhost:7099
- Access Swagger UI
Navigate to:
https://localhost:7099/swagger
- Navigate to Frontend Directory
cd emrwebfrontend- Install Dependencies
npm install- Start Development Server
npm startThe frontend will be available at: http://localhost:3000
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=EMRSystemDB;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
},
"Jwt": {
"Key": "Your-Secret-Key-At-Least-32-Characters-Long",
"Issuer": "EMRSystem",
"Audience": "EMRSystemUsers",
"ExpireHours": "24"
}
}{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.AspNetCore": "Information"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=EMRSystemDB_Dev;..."
}
}Use environment variables or Azure Key Vault for sensitive data.
- Minimum 8 characters
- Requires uppercase, lowercase, digit, and special character
- Hashed using ASP.NET Core Identity (PBKDF2)
- No plain text storage
- 5 failed login attempts
- 15-minute lockout period
- Prevents brute force attacks
- HMAC-SHA256 signing
- Short expiration (24 hours)
- Refresh token mechanism
- Secure token validation
- All API calls over HTTPS
- Certificate validation
- TLS 1.2+ required
- Configurable origin whitelist
- Controlled in production
- Development mode: localhost allowed
- Entity Framework parameterized queries
- No raw SQL execution
- Input validation
- Model validation attributes
- Required fields enforcement
- Email and phone format validation
- Custom business rule validation
- NLog logging
- User action tracking
- Created/Modified timestamps
- Created/Modified by user ID
- Granular permission control
- Multi-role support
- Policy-based authorization
- Attribute-based access control
dotnet ef migrations add MigrationName --project EMRDataLayer --startup-project EMRWebAPIdotnet ef database update --project EMRDataLayer --startup-project EMRWebAPIdotnet ef database update PreviousMigrationName --project EMRDataLayer --startup-project EMRWebAPIdotnet ef migrations remove --project EMRDataLayer --startup-project EMRWebAPI- Indexed foreign keys
- Composite indexes on frequently queried columns
- Eager loading for related entities
- Pagination for large datasets
- Response caching for read-heavy endpoints
- Distributed cache for multi-server deployments
- Cache invalidation on updates
- Asynchronous operations (async/await)
- DTOs to reduce payload size
- Compression for API responses
- Rate limiting for API protection
- PHI Protection: Encrypted data at rest and in transit
- Access Controls: Role-based authentication
- Audit Logs: Complete activity tracking
- Data Backup: Regular automated backups
- Ready for HL7 FHIR integration
- Standard medical codes (ICD, CPT, NDC, CVX)
- RESTful API for third-party integration
- Standard JSON data formats
- OpenAPI/Swagger documentation
- Verify SQL Server is running
- Check connection string
- Ensure database exists
- Verify user permissions
- Check JWT key configuration
- Verify token expiration
- Ensure clock synchronization
- Validate issuer/audience
- Delete existing database
- Remove migration files
- Recreate migrations
- Check model configurations
- Verify CORS policy configuration
- Check allowed origins
- Ensure preflight requests handled
- Validate request headers
- Patient Portal: Self-service portal for patients
- Telemedicine: Video consultation integration
- Mobile App: iOS/Android applications
- AI Integration: Diagnostic assistance and predictive analytics
- Electronic Prescribing: E-prescribing integration
- Imaging Integration: DICOM viewer for radiology
- Reporting Module: Advanced analytics and dashboards
- Notifications: SMS/Email alerts and reminders
- Multi-language Support: Internationalization
- Cloud Deployment: Azure/AWS hosting
- Current Version: 1.0.0
- Framework: .NET 8.0
- Database: SQL Server 2019+
- Email: support@emrsystem.com
- GitHub: https://github.com/JoelHJames1/EMR-System
MIT License - See LICENSE.txt for details
- CPT: Current Procedural Terminology
- CVX: Vaccine Administered Code
- DEA: Drug Enforcement Administration
- EMR: Electronic Medical Record
- HL7: Health Level Seven International
- HIPAA: Health Insurance Portability and Accountability Act
- ICD: International Classification of Diseases
- JWT: JSON Web Token
- NDC: National Drug Code
- NPI: National Provider Identifier
- PHI: Protected Health Information
- RBAC: Role-Based Access Control
- SOAP: Subjective, Objective, Assessment, Plan
Document Version: 1.0 Last Updated: 2024 Author: EMR System Development Team