Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, Index, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { Patient } from './patient.entity';

@Entity('appointments')
@Index(['appointmentDate', 'status']) // Optimize appointment scheduling
@Index(['doctorId', 'appointmentDate'])
export class Appointment {
@PrimaryGeneratedColumn()
id: number;

@Column()
patientId: number;

@Column()
doctorId: number;

@Column()
appointmentDate: Date;

@Column()
duration: number; // in minutes

@Column()
type: string; // 'consultation', 'follow_up', 'surgery', 'test'

@Column({ default: 'scheduled' })
status: string; // 'scheduled', 'in_progress', 'completed', 'cancelled'

@Column('text', { nullable: true })
notes: string;

@Column('json', { nullable: true })
vitals: object;

@ManyToOne(() => Patient, patient => patient.appointments)
patient: Patient;

@CreateDateColumn()
createdAt: Date;

@UpdateDateColumn()
updatedAt: Date;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, Index, CreateDateColumn } from 'typeorm';
import { Patient } from './patient.entity';

@Entity('medical_records')
@Index(['patientId', 'recordDate']) // Optimize medical record queries
@Index(['recordType'])
export class MedicalRecord {
@PrimaryGeneratedColumn()
id: number;

@Column()
patientId: number;

@Column()
recordType: string; // 'diagnosis', 'treatment', 'lab_result', 'vital_signs'

@Column('json')
data: object;

@Column()
recordDate: Date;

@Column({ nullable: true })
doctorId: number;

@Column('text', { nullable: true })
notes: string;

@Column({ default: 'active' })
status: string;

@ManyToOne(() => Patient, patient => patient.medicalRecords)
patient: Patient;

@CreateDateColumn()
createdAt: Date;
}
53 changes: 53 additions & 0 deletions src/Hospital-Performance-Optimization/entities/patient.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Entity, PrimaryGeneratedColumn, Column, OneToMany, Index, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { MedicalRecord } from './medical-record.entity';
import { Appointment } from './appointment.entity';

@Entity('patients')
@Index(['medicalRecordNumber'], { unique: true })
@Index(['lastName', 'firstName']) // Optimize patient searches
export class Patient {
@PrimaryGeneratedColumn()
id: number;

@Column({ unique: true })
medicalRecordNumber: string;

@Column()
firstName: string;

@Column()
lastName: string;

@Column()
dateOfBirth: Date;

@Column()
phoneNumber: string;

@Column()
email: string;

@Column('text', { nullable: true })
address: string;

@Column({ default: 'active' })
status: string;

@Column('json', { nullable: true })
emergencyContact: object;

@Column('json', { nullable: true })
insuranceInfo: object;

@OneToMany(() => MedicalRecord, record => record.patient, { lazy: true })
medicalRecords: MedicalRecord[];

@OneToMany(() => Appointment, appointment => appointment.patient, { lazy: true })
appointments: Appointment[];

@CreateDateColumn()
createdAt: Date;

@UpdateDateColumn()
updatedAt: Date;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cache } from 'cache-manager';
import { Cron, CronExpression } from '@nestjs/schedule';
import { Patient } from '../../entities/patient.entity';
import { Appointment } from '../../entities/appointment.entity';
import { MedicalRecord } from '../../entities/medical-record.entity';

@Injectable()
export class AnalyticsService {
constructor(
@InjectRepository(Patient)
private patientRepository: Repository<Patient>,
@InjectRepository(Appointment)
private appointmentRepository: Repository<Appointment>,
@InjectRepository(MedicalRecord)
private medicalRecordRepository: Repository<MedicalRecord>,
@Inject(CACHE_MANAGER)
private cacheManager: Cache,
) {}

async getDashboardMetrics(): Promise<any> {
const cacheKey = 'dashboard_metrics';
let metrics = await this.cacheManager.get(cacheKey);

if (!metrics) {
const [
totalPatients,
todayAppointments,
pendingAppointments,
recentMedicalRecords,
] = await Promise.all([
this.patientRepository.count(),
this.getTodayAppointmentsCount(),
this.getPendingAppointmentsCount(),
this.getRecentMedicalRecordsCount(),
]);

metrics = {
totalPatients,
todayAppointments,
pendingAppointments,
recentMedicalRecords,
lastUpdated: new Date(),
};

await this.cacheManager.set(cacheKey, metrics, 300); // Cache for 5 minutes
}

return metrics;
}

async getPatientFlowAnalytics(): Promise<any> {
const cacheKey = 'patient_flow_analytics';
let analytics = await this.cacheManager.get(cacheKey);

if (!analytics) {
const query = `
SELECT
DATE(appointment_date) as date,
COUNT(*) as appointment_count,
AVG(duration) as avg_duration,
COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_count,
COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_count
FROM appointments
WHERE appointment_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)
GROUP BY DATE(appointment_date)
ORDER BY date DESC
`;

analytics = await this.appointmentRepository.query(query);
await this.cacheManager.set(cacheKey, analytics, 900); // Cache for 15 minutes
}

return analytics;
}

async getResourceUtilization(): Promise<any> {
const cacheKey = 'resource_utilization';
let utilization = await this.cacheManager.get(cacheKey);

if (!utilization) {
// Calculate room/doctor utilization
const query = `
SELECT
doctor_id,
COUNT(*) as total_appointments,
SUM(duration) as total_minutes,
AVG(duration) as avg_appointment_duration
FROM appointments
WHERE appointment_date >= DATE_SUB(NOW(), INTERVAL 1 WEEK)
GROUP BY doctor_id
ORDER BY total_appointments DESC
`;

utilization = await this.appointmentRepository.query(query);
await this.cacheManager.set(cacheKey, utilization, 600); // Cache for 10 minutes
}

return utilization;
}

// Scheduled task to pre-compute analytics
@Cron(CronExpression.EVERY_5_MINUTES)
async preComputeAnalytics(): Promise<void> {
console.log('Pre-computing analytics...');

// Pre-compute and cache frequently accessed analytics
await Promise.all([
this.getDashboardMetrics(),
this.getPatientFlowAnalytics(),
this.getResourceUtilization(),
]);

console.log('Analytics pre-computation completed');
}

private async getTodayAppointmentsCount(): Promise<number> {
return this.appointmentRepository
.createQueryBuilder('appointment')
.where('DATE(appointment.appointmentDate) = CURDATE()')
.getCount();
}

private async getPendingAppointmentsCount(): Promise<number> {
return this.appointmentRepository
.createQueryBuilder('appointment')
.where('appointment.status = :status', { status: 'scheduled' })
.andWhere('appointment.appointmentDate > NOW()')
.getCount();
}

private async getRecentMedicalRecordsCount(): Promise<number> {
return this.medicalRecordRepository
.createQueryBuilder('record')
.where('DATE(record.createdAt) = CURDATE()')
.getCount();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { RealTimeGateway } from '../real-time/real-time.gateway';

@Injectable()
export class DeviceIntegrationService {
constructor(
private eventEmitter: EventEmitter2,
private realTimeGateway: RealTimeGateway,
) {}

async processDeviceData(deviceId: string, data: any): Promise<void> {
try {
// Validate and process device data
const processedData = await this.validateDeviceData(data);

// Determine data type and route accordingly
switch (processedData.type) {
case 'vital_signs':
await this.processVitalSigns(processedData);
break;
case 'lab_result':
await this.processLabResult(processedData);
break;
case 'imaging':
await this.processImagingData(processedData);
break;
default:
console.warn(`Unknown device data type: ${processedData.type}`);
}

} catch (error) {
console.error(`Error processing device data from ${deviceId}:`, error);
this.eventEmitter.emit('device.error', { deviceId, error: error.message });
}
}

private async validateDeviceData(data: any): Promise<any> {
// Implement data validation logic
if (!data.patientId || !data.type || !data.values) {
throw new Error('Invalid device data format');
}

return {
...data,
timestamp: data.timestamp || new Date(),
validated: true,
};
}

private async processVitalSigns(data: any): Promise<void> {
// Check for critical values
const criticalValues = this.checkCriticalValues(data.values);

if (criticalValues.length > 0) {
this.realTimeGateway.broadcastEmergencyAlert({
type: 'critical_vitals',
patientId: data.patientId,
criticalValues,
severity: 'high',
});
}

// Broadcast real-time vital signs
this.realTimeGateway.broadcastVitalSigns(data.patientId, data.values);

// Emit event for storage
this.eventEmitter.emit('vitals.recorded', data);
}

private async processLabResult(data: any): Promise<void> {
// Process lab results
this.eventEmitter.emit('lab.result', data);
}

private async processImagingData(data: any): Promise<void> {
// Process imaging data
this.eventEmitter.emit('imaging.received', data);
}

private checkCriticalValues(vitals: any): string[] {
const critical = [];

// Example critical value checks
if (vitals.heartRate && (vitals.heartRate < 60 || vitals.heartRate > 100)) {
critical.push(`Heart rate: ${vitals.heartRate} BPM`);
}

if (vitals.bloodPressure) {
const [systolic, diastolic] = vitals.bloodPressure.split('/').map(Number);
if (systolic > 180 || diastolic > 110) {
critical.push(`Blood pressure: ${vitals.bloodPressure}`);
}
}

if (vitals.temperature && (vitals.temperature < 95 || vitals.temperature > 102)) {
critical.push(`Temperature: ${vitals.temperature}°F`);
}

return critical;
}
}
Loading