-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedication-tracker.js
More file actions
1906 lines (1597 loc) · 69.9 KB
/
Copy pathmedication-tracker.js
File metadata and controls
1906 lines (1597 loc) · 69.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require('fs');
const path = require('path');
const ChartUtils = require('./chart-utils');
const PDFDocument = require('pdfkit');
const ReminderService = require('./reminder-service');
const ValidationUtils = require('./validation-utils');
const EnhancedMedicationManager = require('./enhanced-medication-manager');
const MedicationValidator = require('./medication-validator');
// Pregnancy Safety Integration - Import as modules, not classes
// These modules are optional dependencies
let PregnancySafetyEngine = null;
let PregnancyInteractionChecker = null;
let PregnancyRiskCalculator = null;
let PregnancyAuditLogger = null;
try {
PregnancySafetyEngine = require('bumpie-meds/src/services/pregnancy-safety-engine');
PregnancyInteractionChecker = require('bumpie-meds/src/services/pregnancy-interaction-checker');
PregnancyRiskCalculator = require('bumpie-meds/src/services/pregnancy-risk-calculator');
PregnancyAuditLogger = require('bumpie-meds/src/services/pregnancy-audit-logger');
} catch (error) {
// Only suppress MODULE_NOT_FOUND errors; re-throw other errors like syntax errors
if (error.code === 'MODULE_NOT_FOUND') {
console.warn('⚠️ Warning: bumpie-meds pregnancy safety modules not available.');
console.warn(' Pregnancy safety features will be disabled.');
console.warn(' To enable these features, install the bumpie-meds package.');
} else {
// Re-throw non-module-not-found errors (e.g., syntax errors in the module)
throw error;
}
}
class MedicationTracker {
constructor(dataFile = 'medications.json') {
this.dataFile = dataFile;
this.data = this.loadData();
this.reminderService = new ReminderService();
this.interactions = this.loadInteractions();
this.idCounter = Date.now();
// Initialize enhanced medication manager and validator
this.medicationManager = new EnhancedMedicationManager();
this.medicationValidator = new MedicationValidator();
// Pregnancy safety modules are functional, not class-based
this.pregnancySafety = PregnancySafetyEngine;
this.pregnancyInteractions = PregnancyInteractionChecker;
this.pregnancyRisk = PregnancyRiskCalculator;
this.pregnancyAudit = PregnancyAuditLogger;
}
generateId() {
return ++this.idCounter;
}
loadInteractions() {
try {
const interactionsFile = path.join(__dirname, 'medication-interactions.json');
if (fs.existsSync(interactionsFile)) {
const rawData = fs.readFileSync(interactionsFile, 'utf8');
return JSON.parse(rawData).interactions;
}
} catch (error) {
console.error('Warning: Could not load medication interactions database:', error.message);
}
return [];
}
normalizeDrugName(name) {
// Normalize drug name for matching (remove common form suffixes, convert to lowercase)
return name.toLowerCase()
.replace(/\s*\d+\s*(mg|mcg|g|ml|iu|units?)\s*/gi, ' ') // Remove dosages
.replace(/\s+(tablet|capsule|pill|cream|ointment|syrup|solution)s?$/i, '') // Remove forms
.replace(/\s+/g, ' ') // Normalize spaces
.trim();
}
loadData() {
try {
if (fs.existsSync(this.dataFile)) {
const rawData = fs.readFileSync(this.dataFile, 'utf8');
return JSON.parse(rawData);
}
} catch (error) {
console.error('Error loading data:', error.message);
}
return {
medications: [],
history: []
};
}
saveData() {
try {
fs.writeFileSync(this.dataFile, JSON.stringify(this.data, null, 2));
return true;
} catch (error) {
console.error('Error saving data:', error.message);
return false;
}
}
// Statistics Summary
showStats() {
const totalMeds = this.data.medications.length;
const activeMeds = this.data.medications.filter(m => m.active).length;
const inactiveMeds = totalMeds - activeMeds;
const totalHistory = this.data.history.length;
// Calculate overall adherence
let adherenceRate = 0;
let currentStreak = 0;
if (totalHistory > 0) {
const takenDoses = this.data.history.filter(h => !h.missed).length;
adherenceRate = ((takenDoses / totalHistory) * 100).toFixed(1);
currentStreak = this.calculateAdherenceStreak();
}
// Calculate days tracking
let daysTracking = 0;
if (totalHistory > 0) {
const firstEntry = new Date(this.data.history[0].timestamp);
daysTracking = Math.ceil((new Date() - firstEntry) / (1000 * 60 * 60 * 24));
}
console.log('\n📊 Medication Tracker - Statistics Summary');
console.log('═'.repeat(60));
console.log(`\n📅 Tracking Duration: ${daysTracking} days`);
console.log('\n💊 Medications:');
console.log(` Active: ${activeMeds}`);
console.log(` Inactive: ${inactiveMeds}`);
console.log(` Total: ${totalMeds}`);
console.log('\n📈 Adherence:');
console.log(` Total doses logged: ${totalHistory}`);
if (totalHistory > 0) {
console.log(` Overall adherence rate: ${adherenceRate}%`);
console.log(` Current streak: ${currentStreak} days`);
}
if (activeMeds > 0) {
console.log('\n🕐 Today\'s Schedule:');
const today = new Date().toDateString();
const activeMedsList = this.data.medications.filter(m => m.active);
activeMedsList.forEach(med => {
const takenToday = this.data.history.some(h =>
h.medicationId === med.id &&
new Date(h.timestamp).toDateString() === today
);
const status = takenToday ? '✓' : '○';
console.log(` ${status} ${med.name} - ${med.dosage} at ${med.scheduledTime}`);
});
}
console.log('\n═'.repeat(60));
}
// Medication Interaction Checking
checkInteractions(newMedName = null, displayWarnings = true) {
const activeMeds = this.data.medications.filter(m => m.active);
const foundInteractions = [];
// If checking for a new medication, include it in the check
const medsToCheck = newMedName
? [...activeMeds.map(m => m.name), newMedName]
: activeMeds.map(m => m.name);
// PERFORMANCE: Build interaction lookup Map for O(1) access instead of O(n) find()
// This reduces overall complexity from O(n³) to O(n²)
const interactionMap = new Map();
this.interactions.forEach(inter => {
const drug1 = this.normalizeDrugName(inter.drug1);
const drug2 = this.normalizeDrugName(inter.drug2);
// Store both directions for bidirectional lookup
const key1 = `${drug1}::${drug2}`;
const key2 = `${drug2}::${drug1}`;
interactionMap.set(key1, inter);
interactionMap.set(key2, inter);
});
// Check all pairs of medications
for (let i = 0; i < medsToCheck.length; i++) {
for (let j = i + 1; j < medsToCheck.length; j++) {
const med1 = this.normalizeDrugName(medsToCheck[i]);
const med2 = this.normalizeDrugName(medsToCheck[j]);
// PERFORMANCE: O(1) Map lookup instead of O(n) find()
const lookupKey = `${med1}::${med2}`;
const interaction = interactionMap.get(lookupKey);
if (interaction) {
foundInteractions.push({
med1: medsToCheck[i],
med2: medsToCheck[j],
interaction: interaction
});
}
}
}
if (displayWarnings && foundInteractions.length > 0) {
console.log('\n⚠️ MEDICATION INTERACTION WARNINGS');
console.log('═'.repeat(70));
foundInteractions.forEach((found, index) => {
const { med1, med2, interaction } = found;
const severityIcon = {
'SEVERE': '🔴',
'MODERATE': '🟡',
'MINOR': '🟢'
};
console.log(`\n${index + 1}. ${severityIcon[interaction.severity]} ${interaction.severity} - ${med1} + ${med2}`);
console.log(` ${interaction.description}`);
console.log(` 💡 ${interaction.recommendation}`);
});
console.log('\n' + '═'.repeat(70));
console.log('⚕️ Always consult your doctor or pharmacist about drug interactions.');
console.log('═'.repeat(70));
}
return foundInteractions;
}
// Backup and Restore
createBackup(backupDir = './backups') {
try {
if (!fs.existsSync(backupDir)) {
fs.mkdirSync(backupDir, { recursive: true });
}
if (!fs.existsSync(this.dataFile)) {
console.log('\n⚠️ No data file found to backup.');
return false;
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
const backupFilename = `medication-backup-${timestamp}.json`;
const backupPath = path.join(backupDir, backupFilename);
const data = fs.readFileSync(this.dataFile);
fs.writeFileSync(backupPath, data);
console.log('\n✓ Backup created successfully!');
console.log(` Location: ${backupPath}`);
console.log(` Time: ${new Date().toLocaleString()}`);
return true;
} catch (error) {
console.error('Error creating backup:', error.message);
return false;
}
}
listBackups(backupDir = './backups') {
try {
if (!fs.existsSync(backupDir)) {
console.log('\n📁 No backups directory found.');
return;
}
const files = fs.readdirSync(backupDir)
.filter(f => f.startsWith('medication-backup-') && f.endsWith('.json'))
.sort()
.reverse();
if (files.length === 0) {
console.log('\n📁 No backups found.');
return;
}
console.log('\n📁 Available Backups:');
console.log('═'.repeat(60));
files.forEach((file, index) => {
const filePath = path.join(backupDir, file);
const stats = fs.statSync(filePath);
const size = (stats.size / 1024).toFixed(2);
const date = stats.mtime.toLocaleString();
console.log(`${index + 1}. ${file}`);
console.log(` Created: ${date}`);
console.log(` Size: ${size} KB`);
});
} catch (error) {
console.error('Error listing backups:', error.message);
}
}
restoreFromBackup(backupFile, backupDir = './backups') {
try {
const backupPath = path.join(backupDir, backupFile);
if (!fs.existsSync(backupPath)) {
console.log('\n❌ Backup file not found.');
return false;
}
if (fs.existsSync(this.dataFile)) {
const preRestoreBackup = `medication-pre-restore-${Date.now()}.json`;
fs.copyFileSync(this.dataFile, path.join(backupDir, preRestoreBackup));
console.log(`\n💾 Current data backed up to: ${preRestoreBackup}`);
}
const backupData = fs.readFileSync(backupPath);
fs.writeFileSync(this.dataFile, backupData);
this.data = this.loadData();
console.log('\n✓ Data restored successfully from backup!');
console.log(` Source: ${backupFile}`);
console.log(` Time: ${new Date().toLocaleString()}`);
return true;
} catch (error) {
console.error('Error restoring backup:', error.message);
return false;
}
}
// Data Export
exportToCSV(outputDir = './exports') {
try {
// Create exports directory if it doesn't exist
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
const baseFilename = `medication-export-${timestamp}`;
// Export medications list
if (this.data.medications.length > 0) {
const medsCSV = this.generateMedicationsCSV();
fs.writeFileSync(path.join(outputDir, `${baseFilename}-medications.csv`), medsCSV);
}
// Export history
if (this.data.history.length > 0) {
const historyCSV = this.generateHistoryCSV();
fs.writeFileSync(path.join(outputDir, `${baseFilename}-history.csv`), historyCSV);
}
console.log(`\n✓ Data exported successfully to ${outputDir}/`);
console.log(` Base filename: ${baseFilename}`);
return true;
} catch (error) {
console.error('Error exporting data:', error.message);
return false;
}
}
generateMedicationsCSV() {
const headers = 'ID,Name,Dosage,Frequency,Scheduled Time,Created,Status\n';
const rows = this.data.medications.map(med => {
const name = (med.name || '').replace(/"/g, '""');
const dosage = (med.dosage || '').replace(/"/g, '""');
const created = new Date(med.createdAt).toLocaleDateString();
const status = med.active ? 'Active' : 'Inactive';
return `${med.id},"${name}","${dosage}","${med.frequency}","${med.scheduledTime}","${created}","${status}"`;
}).join('\n');
return headers + rows;
}
generateHistoryCSV() {
const headers = 'Date,Time,Medication ID,Medication Name,Dosage,Notes,Missed\n';
const rows = this.data.history.map(entry => {
const date = new Date(entry.timestamp);
const dateStr = date.toLocaleDateString();
const timeStr = date.toLocaleTimeString();
const name = (entry.medicationName || '').replace(/"/g, '""');
const dosage = (entry.dosage || '').replace(/"/g, '""');
const notes = (entry.notes || '').replace(/"/g, '""');
const missed = entry.missed ? 'Yes' : 'No';
return `"${dateStr}","${timeStr}",${entry.medicationId},"${name}","${dosage}","${notes}","${missed}"`;
}).join('\n');
return headers + rows;
}
// PDF Export with Charts
exportToPDF(outputDir = './exports') {
return new Promise((resolve, reject) => {
try {
// Create exports directory if it doesn't exist
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
const filename = `medication-report-${timestamp}.pdf`;
const filepath = path.join(outputDir, filename);
// Create PDF document
const doc = new PDFDocument({ margin: 50 });
const stream = fs.createWriteStream(filepath);
doc.pipe(stream);
// Header
doc.fontSize(24).fillColor('#2c3e50').text('Medication Tracker Report', { align: 'center' });
doc.moveDown(0.5);
doc.fontSize(12).fillColor('#7f8c8d').text(new Date().toLocaleDateString('en-US', {
weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'
}), { align: 'center' });
doc.moveDown(2);
// Summary Statistics
this.addMedicationSummary(doc);
doc.moveDown(1.5);
// Active Medications
if (this.data.medications.filter(m => m.active).length > 0) {
this.addActiveMedicationsSection(doc);
doc.moveDown(1.5);
}
// Adherence Chart
if (this.data.history.length > 0) {
this.addAdherenceChart(doc);
doc.moveDown(1.5);
}
// Today's Schedule
this.addTodaySchedule(doc);
doc.moveDown(1.5);
// Recent History
if (this.data.history.length > 0) {
this.addRecentHistory(doc);
}
// Footer
doc.fontSize(8).fillColor('#95a5a6').text(
'Generated by StepSync Medication Tracker',
50,
doc.page.height - 50,
{ align: 'center' }
);
doc.end();
stream.on('finish', () => {
console.log('\n✓ PDF report generated successfully!');
console.log(` Location: ${filepath}`);
resolve(filepath);
});
stream.on('error', (error) => {
console.error('Error writing PDF:', error.message);
reject(error);
});
} catch (error) {
console.error('Error generating PDF:', error.message);
reject(error);
}
});
}
addMedicationSummary(doc) {
doc.fontSize(16).fillColor('#34495e').text('📊 Summary');
doc.moveDown(0.5);
const totalMeds = this.data.medications.length;
const activeMeds = this.data.medications.filter(m => m.active).length;
const totalHistory = this.data.history.length;
let adherenceRate = 0;
let currentStreak = 0;
if (totalHistory > 0) {
const takenDoses = this.data.history.filter(h => !h.missed).length;
adherenceRate = ((takenDoses / totalHistory) * 100).toFixed(1);
currentStreak = this.calculateAdherenceStreak();
}
doc.fontSize(11).fillColor('#2c3e50');
doc.text(`Total Medications: ${totalMeds}`, { indent: 20 });
doc.text(`Active Medications: ${activeMeds}`, { indent: 20 });
doc.text(`Total Doses Tracked: ${totalHistory}`, { indent: 20 });
doc.text(`Adherence Rate: ${adherenceRate}%`, { indent: 20 });
doc.text(`Current Streak: ${currentStreak} days`, { indent: 20 });
}
addActiveMedicationsSection(doc) {
doc.fontSize(16).fillColor('#34495e').text('💊 Active Medications');
doc.moveDown(0.5);
const activeMeds = this.data.medications.filter(m => m.active);
activeMeds.forEach((med, index) => {
doc.fontSize(11).fillColor('#2c3e50').text(`${index + 1}. ${med.name}`, { indent: 20 });
doc.fontSize(10).fillColor('#7f8c8d').text(` Dosage: ${med.dosage}`, { indent: 40 });
doc.text(` Frequency: ${med.frequency}`, { indent: 40 });
doc.text(` Scheduled Time: ${med.scheduledTime}`, { indent: 40 });
if (index < activeMeds.length - 1) doc.moveDown(0.5);
});
}
addAdherenceChart(doc) {
doc.fontSize(16).fillColor('#34495e').text('📈 Adherence Overview (Last 30 Days)');
doc.moveDown(0.5);
// Get last 30 days of history
const now = new Date();
const thirtyDaysAgo = new Date(now.getTime() - (30 * 24 * 60 * 60 * 1000));
const recentHistory = this.data.history
.filter(h => new Date(h.timestamp) >= thirtyDaysAgo)
.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
if (recentHistory.length === 0) {
doc.fontSize(11).fillColor('#7f8c8d').text('No data in the last 30 days', { indent: 20 });
return;
}
// Calculate daily adherence
const dailyAdherence = {};
recentHistory.forEach(entry => {
const date = new Date(entry.timestamp).toLocaleDateString();
if (!dailyAdherence[date]) {
dailyAdherence[date] = { taken: 0, missed: 0 };
}
if (entry.missed) {
dailyAdherence[date].missed++;
} else {
dailyAdherence[date].taken++;
}
});
// Draw pie chart
const centerX = 300;
const centerY = doc.y + 80;
const radius = 60;
const totalTaken = recentHistory.filter(h => !h.missed).length;
const totalMissed = recentHistory.filter(h => h.missed).length;
const total = totalTaken + totalMissed;
// Taken slice (green)
if (totalTaken > 0) {
const takenAngle = (totalTaken / total) * 360;
doc.fillColor('#27ae60').moveTo(centerX, centerY)
.arc(centerX, centerY, radius, 0, takenAngle, false)
.fill();
}
// Missed slice (red)
if (totalMissed > 0) {
const takenAngle = (totalTaken / total) * 360;
const missedAngle = (totalMissed / total) * 360;
doc.fillColor('#e74c3c').moveTo(centerX, centerY)
.arc(centerX, centerY, radius, takenAngle, takenAngle + missedAngle, false)
.fill();
}
// Legend
doc.fontSize(10).fillColor('#27ae60');
doc.text(`✓ Taken: ${totalTaken} (${((totalTaken/total)*100).toFixed(1)}%)`, centerX - radius - 100, centerY + radius + 20);
doc.fillColor('#e74c3c');
doc.text(`✗ Missed: ${totalMissed} (${((totalMissed/total)*100).toFixed(1)}%)`, centerX + 50, centerY + radius + 20);
doc.y = centerY + radius + 50;
}
addTodaySchedule(doc) {
doc.fontSize(16).fillColor('#34495e').text('📅 Today\'s Schedule');
doc.moveDown(0.5);
const activeMeds = this.data.medications.filter(m => m.active);
if (activeMeds.length === 0) {
doc.fontSize(11).fillColor('#7f8c8d').text('No active medications', { indent: 20 });
return;
}
// Sort by scheduled time
const sorted = activeMeds.sort((a, b) => a.scheduledTime.localeCompare(b.scheduledTime));
sorted.forEach((med, index) => {
doc.fontSize(11).fillColor('#2c3e50').text(
`${med.scheduledTime} - ${med.name} (${med.dosage})`,
{ indent: 20 }
);
if (index < sorted.length - 1) doc.moveDown(0.3);
});
}
addRecentHistory(doc) {
doc.fontSize(16).fillColor('#34495e').text('📝 Recent History (Last 10 Entries)');
doc.moveDown(0.5);
const recent = this.data.history
.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
.slice(0, 10);
recent.forEach((entry, index) => {
const date = new Date(entry.timestamp).toLocaleString();
const status = entry.missed ? '✗ Missed' : '✓ Taken';
const statusColor = entry.missed ? '#e74c3c' : '#27ae60';
doc.fontSize(10).fillColor('#2c3e50').text(
`${date} - ${entry.medicationName}`,
{ indent: 20 }
);
doc.fillColor(statusColor).text(status, { indent: 40 });
if (entry.notes) {
doc.fontSize(9).fillColor('#7f8c8d').text(` Note: ${entry.notes}`, { indent: 40 });
}
if (index < recent.length - 1) doc.moveDown(0.3);
});
}
addMedication(name, dosage, frequency, time) {
// Validate required fields
if (!name || typeof name !== 'string' || name.trim() === '') {
console.error('❌ Error: Medication name is required');
return false;
}
if (!dosage || typeof dosage !== 'string' || dosage.trim() === '') {
console.error('❌ Error: Dosage is required');
return false;
}
if (!frequency || typeof frequency !== 'string' || frequency.trim() === '') {
console.error('❌ Error: Frequency is required');
return false;
}
// Validate frequency value (only for English frequencies, allow i18n)
const validFrequencies = ['daily', 'twice-daily', 'three-times-daily', 'four-times-daily', 'weekly', 'as-needed', 'every-other-day'];
const isEnglishFrequency = /^[a-zA-Z-]+$/.test(frequency);
if (isEnglishFrequency && !validFrequencies.includes(frequency.toLowerCase())) {
console.error(`❌ Error: Invalid frequency. Must be one of: ${validFrequencies.join(', ')}`);
return false;
}
// Enhanced validation using medication database (only if database is loaded)
let validationResult = null;
if (this.medicationValidator && this.medicationValidator.medicationManager &&
this.medicationValidator.medicationManager.medications.length > 0) {
validationResult = this.medicationValidator.validate(name, dosage, { checkPregnancy: true });
if (!validationResult.valid) {
console.error('❌ Validation Error:');
validationResult.errors.forEach(err => console.error(` ${err}`));
// Show suggestions if available
if (validationResult.info && validationResult.info.suggestions) {
console.log('\n💡 Did you mean:');
validationResult.info.suggestions.forEach(s => console.log(` - ${s}`));
}
// Show valid dosages if medication found but dosage invalid
if (validationResult.info && validationResult.info.validDosages) {
console.log(`\n💡 Valid dosages for ${name}:`);
console.log(` ${validationResult.info.validDosages.join(', ')}`);
}
return false;
}
// Show validation warnings
if (validationResult.warnings && validationResult.warnings.length > 0) {
console.log('\n⚠️ Warnings:');
validationResult.warnings.forEach(w => {
console.log(` ${w.message}`);
});
}
}
// Check for interactions with current medications BEFORE adding
const interactions = this.checkInteractions(name, false); // Don't display yet
// Check for duplicate medications (only if validator is available and has database)
if (this.medicationValidator && this.medicationValidator.medicationManager &&
this.medicationValidator.medicationManager.medications.length > 0) {
const existingMeds = this.data.medications
.filter(m => m.active)
.map(m => ({ name: m.name, dosage: m.dosage }));
const duplicateCheck = this.medicationValidator.validateMultiple([
...existingMeds,
{ name: name, dosage: dosage }
]);
if (!duplicateCheck.valid) {
console.error('❌ Duplicate medication detected:');
duplicateCheck.errors.forEach(err => console.error(` ${err}`));
return false;
}
}
const medication = {
id: this.generateId(),
name: name,
dosage: dosage,
frequency: frequency, // e.g., 'daily', 'twice-daily', 'weekly'
scheduledTime: time, // e.g., '08:00', '20:00'
createdAt: new Date().toISOString(),
active: true
};
// Add enhanced medication info if available
if (validationResult && validationResult.medication) {
medication.category = validationResult.medication.category;
medication.genericName = validationResult.medication.genericName;
medication.manufacturer = validationResult.medication.manufacturer;
}
this.data.medications.push(medication);
if (this.saveData()) {
console.log('✓ Medication added successfully!');
console.log(` Name: ${name}`);
console.log(` Dosage: ${dosage}`);
console.log(` Frequency: ${frequency}`);
console.log(` Time: ${time}`);
// Show medication details
if (validationResult && validationResult.medication) {
console.log(` Category: ${validationResult.medication.category}`);
console.log(` Generic: ${validationResult.medication.genericName}`);
}
// Now display interaction warnings if any were found
if (interactions.length > 0) {
console.log('');
interactions.forEach((found, index) => {
const { med1, med2, interaction } = found;
const severityIcon = {
'SEVERE': '🔴',
'MODERATE': '🟡',
'MINOR': '🟢'
};
console.log(`${severityIcon[interaction.severity]} ${interaction.severity} INTERACTION WARNING:`);
console.log(` ${med1} + ${med2}`);
console.log(` ${interaction.description}`);
console.log(` 💡 ${interaction.recommendation}`);
if (index < interactions.length - 1) console.log('');
});
console.log('\n⚕️ Please consult your doctor or pharmacist about these interactions.');
}
return medication;
}
return null;
}
/**
* Check pregnancy medication safety
* @param {string} medicationName - Medication name
* @param {number} weekOfPregnancy - Week of pregnancy (1-42)
* @param {Object} options - Additional options
* @returns {Promise<Object>} Safety assessment
*/
async checkPregnancySafety(medicationName, weekOfPregnancy, options = {}) {
try {
// Check if pregnancy safety modules are available
if (!this.pregnancySafety) {
console.warn('⚠️ Pregnancy safety check unavailable - modules not loaded');
return {
safe: false,
error: 'Pregnancy safety modules not available',
recommendation: 'Unable to assess safety - consult healthcare provider immediately',
warning: 'The bumpie-meds package is required for pregnancy safety checks'
};
}
const safetyResult = await this.pregnancySafety.checkMedicationSafety(
medicationName,
weekOfPregnancy
);
// Check for pregnancy-specific interactions if taking other medications
if (this.pregnancyInteractions && this.data.medications && this.data.medications.length > 0) {
const currentMeds = this.data.medications
.filter(m => m.active)
.map(m => m.name);
if (currentMeds.length > 0) {
const interactions = await this.pregnancyInteractions.checkPregnancyInteractions(
[...currentMeds, medicationName],
weekOfPregnancy
);
if (interactions.hasInteractions) {
safetyResult.pregnancyInteractions = interactions;
}
}
}
// Log to audit trail
if (this.pregnancyAudit && options.patientId) {
await this.pregnancyAudit.logSafetyCheck({
patientId: options.patientId,
medicationName,
weekOfPregnancy,
trimester: safetyResult.trimester,
riskScore: safetyResult.riskScore,
riskLevel: safetyResult.riskLevel,
fdaCategory: safetyResult.fdaCategory,
safe: safetyResult.safe,
warnings: safetyResult.warnings || [],
recommendation: safetyResult.recommendation,
sessionId: options.sessionId || null
});
}
return safetyResult;
} catch (error) {
console.error('❌ Pregnancy safety check error:', error.message);
return {
safe: false,
error: error.message,
recommendation: 'Unable to assess safety - consult healthcare provider'
};
}
}
/**
* Search medications in database
* @param {string} query - Search query
* @param {number} limit - Maximum results
* @returns {Array} Search results
*/
searchMedicationDatabase(query, limit = 10) {
return this.medicationManager.searchMedications(query, limit);
}
/**
* Get valid dosages for a medication
* @param {string} medicationName - Medication name
* @returns {Array} Valid dosages
*/
getValidDosages(medicationName) {
return this.medicationManager.getValidDosages(medicationName);
}
/**
* Get medication details from database
* @param {string} medicationName - Medication name
* @returns {Object|null} Medication details
*/
getMedicationDetails(medicationName) {
return this.medicationManager.getMedicationDetails(medicationName);
}
/**
* List all available medications from database
* @param {string} category - Optional category filter
* @returns {Array} List of medications
*/
listAvailableMedications(category = null) {
if (category) {
const meds = this.medicationManager.getMedicationsByCategory(category);
console.log(`\n💊 Available ${category} Medications:`);
console.log('═'.repeat(60));
meds.forEach(med => {
console.log(`\n${med.name} (${med.genericName})`);
console.log(` Dosages: ${med.dosages.join(', ')}`);
console.log(` Brand Names: ${med.brandNames.join(', ')}`);
});
} else {
const names = this.medicationManager.getAllMedicationNames();
console.log(`\n💊 Available Medications (${names.length} total):`);
console.log('═'.repeat(60));
// Group by category
const byCategory = {};
names.forEach(med => {
if (!byCategory[med.category]) {
byCategory[med.category] = [];
}
byCategory[med.category].push(med.name);
});
Object.keys(byCategory).sort().forEach(cat => {
console.log(`\n${cat}:`);
byCategory[cat].forEach(name => {
console.log(` • ${name}`);
});
});
}
console.log('═'.repeat(60));
}
/**
* Show database statistics
*/
showDatabaseStats() {
const stats = this.medicationManager.getStatistics();
console.log('\n📊 Medication Database Statistics:');
console.log('═'.repeat(60));
console.log(`Total Medications: ${stats.totalMedications}`);
console.log(`Categories: ${stats.totalCategories}`);
console.log('\nMedications by Category:');
Object.entries(stats.categories).forEach(([cat, count]) => {
console.log(` ${cat}: ${count}`);
});
console.log('═'.repeat(60));
}
listMedications(activeOnly = true) {
const meds = activeOnly
? this.data.medications.filter(m => m.active)
: this.data.medications;
if (meds.length === 0) {
console.log('No medications found.');
return;
}
console.log('\n📋 Your Medications:');
console.log('─'.repeat(60));
meds.forEach(med => {
console.log(`ID: ${med.id}`);
console.log(` Name: ${med.name}`);
console.log(` Dosage: ${med.dosage}`);
console.log(` Frequency: ${med.frequency}`);
console.log(` Time: ${med.scheduledTime}`);
console.log(` Status: ${med.active ? 'Active' : 'Inactive'}`);
console.log('─'.repeat(60));
});
}
markAsTaken(medicationId, notes = '') {
const medication = this.data.medications.find(m => m.id === parseInt(medicationId));
if (!medication) {
console.log('❌ Medication not found!');
return false;
}
const record = {
medicationId: medication.id,
medicationName: medication.name,
dosage: medication.dosage,
takenAt: new Date().toISOString(),
notes: notes
};
this.data.history.push(record);
// Auto-update pill count if refill tracking is enabled
if (medication.pillCount !== undefined && medication.pillsPerDose) {
this.updatePillCount(medication.id, -medication.pillsPerDose);
}
if (this.saveData()) {
console.log(`✓ Marked "${medication.name}" as taken!`);
console.log(` Time: ${new Date().toLocaleString()}`);
if (notes) console.log(` Notes: ${notes}`);
// Show refill alert if needed
if (medication.pillCount !== undefined) {
const updated = this.data.medications.find(m => m.id === medication.id);
this.checkRefillAlert(updated);
}
return true;
}
return false;
}
// ==================== REFILL TRACKING SYSTEM ====================
setRefillInfo(medicationId, pillCount, pillsPerDose = 1, refillThreshold = 7) {
// Validate medication ID
const medId = ValidationUtils.parseInteger(medicationId, {
min: 1,
fieldName: 'medication ID'
});
if (medId === null) {
return false;
}
const medication = this.data.medications.find(m => m.id === medId);
if (!medication) {
console.log('❌ Medication not found!');
return false;
}
// Validate pill count
const validatedPillCount = ValidationUtils.parseInteger(pillCount, {
min: 0,
max: 10000,
fieldName: 'pill count'
});
// Validate pills per dose
const validatedPillsPerDose = ValidationUtils.parseInteger(pillsPerDose, {
min: 1,
max: 100,
default: 1,
fieldName: 'pills per dose'
});
// Validate refill threshold
const validatedRefillThreshold = ValidationUtils.parseInteger(refillThreshold, {
min: 1,
max: 365,
default: 7,
fieldName: 'refill threshold'