Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1496 lines (1241 loc) · 60.6 KB
/
Copy pathscript.js
File metadata and controls
1496 lines (1241 loc) · 60.6 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
class InsulinCalculator {
constructor() {
this.initializeElements();
this.bindEvents();
this.bindWeightSliderEvents();
this.setupInputValidation();
}
initializeElements() {
// Modal elements
this.penSelectButton = document.getElementById('penSelectButton');
this.penSelectLabel = document.getElementById('penSelectLabel');
this.penSelectChevron = document.getElementById('penSelectChevron');
this.penSelectorModal = document.getElementById('penSelectorModal');
this.penSelectorContent = document.getElementById('penSelectorContent');
this.closePenModal = document.getElementById('closePenModal');
this.currentPenId = null; // Currently selected pen ID
this.penSelect = null; // Will be set to selected pen value for compatibility
this.daySupplyInput = document.getElementById('daySupply');
this.unitsPerDoseInput = document.getElementById('unitsPerDose');
this.doseFrequencyInput = document.getElementById('doseFrequency');
this.concentrationInput = document.getElementById('concentration');
this.volumePerPenInput = document.getElementById('volumePerPen');
this.copyBtn = document.getElementById('copyBtn');
this.disclaimerBtn = document.getElementById('disclaimerBtn');
this.disclaimerModal = document.getElementById('disclaimerModal');
this.closeDisclaimerModal = document.getElementById('closeModal');
this.closeDisclaimerModalBtn = document.getElementById('closeModalBtn');
this.resultsDiv = document.getElementById('results');
this.errorDiv = document.getElementById('errorMessage');
this.totalUnitsSpan = document.getElementById('totalUnits');
this.totalMLSpan = document.getElementById('totalML');
this.pensToOrderSpan = document.getElementById('pensToOrder');
this.prescriptionTextP = document.getElementById('prescriptionText');
this.patientWeightInput = document.getElementById('patientWeight');
this.weightUnitToggle = document.getElementById('weightUnitToggle');
this.dosingSlider = document.getElementById('dosingSlider');
this.sliderValueSpan = document.getElementById('sliderValue');
this.estimatedDoseSpan = document.getElementById('estimatedDose');
this.weightBasedDosingDiv = document.getElementById('weightBasedDosing');
this.pricingInfoDiv = document.getElementById('pricingInfo');
this.pricingTextSpan = document.getElementById('pricingText');
this.sliderTooltip = document.getElementById('sliderTooltip');
this.wastageToggle = document.getElementById('wastageToggle');
this.expirationWarning = document.getElementById('expirationWarning');
this.sigGeneration = document.getElementById('sigGeneration');
this.maxDoseWarning = document.getElementById('maxDoseWarning');
this.primingHelpBtn = document.getElementById('primingHelpBtn');
this.primingHelpTooltip = document.getElementById('primingHelpTooltip');
// Discount elements
this.inlineDiscountLinks = document.getElementById('inlineDiscountLinks');
this.inlineDiscountContent = document.getElementById('inlineDiscountContent');
// Clinical guidance elements
this.clinicalGuidance = document.getElementById('clinicalGuidance');
this.clinicalGuidanceText = document.getElementById('clinicalGuidanceText');
this.insulinPens = null;
this.selectedPen = null;
this.includeWastage = true;
// Discount links for each pen category
this.penDiscountInfo = {
// Sanofi pens - GoodRx $35/month + Amazon + SingleCare
'lantus-solostar': {
goodrx: { url: 'https://www.goodrx.com/lantus?label_override=lantus&form=carton&dosage=5-solostar-pens-of-3ml&quantity=1&drugId=37030', text: 'GoodRx $35/month' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' },
singlecare: { url: 'https://www.singlecare.com/prescription/lantus-solostar', text: 'SingleCare' }
},
'toujeo-solostar': {
goodrx: { url: 'https://www.goodrx.com/toujeo', text: 'GoodRx $35/month' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' }
},
'admelog-solostar': {
goodrx: { url: 'https://www.goodrx.com/admelog', text: 'GoodRx $35/month' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' },
singlecare: { url: 'https://www.singlecare.com/prescription/admelog-solostar', text: 'SingleCare' }
},
'apidra-solostar': {
goodrx: { url: 'https://www.goodrx.com/apidra', text: 'GoodRx $35/month' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' }
},
// Lilly pens - Lilly Insulin Savings + Amazon
'humalog-kwikpen': {
lilly: { url: 'https://www.insulinaffordability.com/', text: 'Lilly Insulin Savings' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' }
},
'humalog-kwikpen-u200': {
lilly: { url: 'https://www.insulinaffordability.com/', text: 'Lilly Insulin Savings' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' }
},
'basaglar-kwikpen': {
lilly: { url: 'https://www.insulinaffordability.com/', text: 'Lilly Insulin Savings' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' }
},
// Novo Nordisk pens - $35/month program + Amazon
'novolog-flexpen': {
novocare: { url: 'https://www.novocare.com/diabetes/help-with-costs/help-with-insulin-costs.html', text: 'Novo Nordisk $35/month' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' }
},
'fiasp-flextouch': {
novocare: { url: 'https://www.novocare.com/diabetes/help-with-costs/help-with-insulin-costs.html', text: 'Novo Nordisk $35/month' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' }
},
'levemir-flextouch': {
novocare: { url: 'https://www.novocare.com/diabetes/help-with-costs/help-with-insulin-costs.html', text: 'Novo Nordisk $35/month' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' }
},
'tresiba-flextouch': {
novocare: { url: 'https://www.novocare.com/diabetes/help-with-costs/help-with-insulin-costs.html', text: 'Novo Nordisk $35/month' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' }
},
'tresiba-flextouch-u200': {
novocare: { url: 'https://www.novocare.com/diabetes/help-with-costs/help-with-insulin-costs.html', text: 'Novo Nordisk $35/month' },
amazon: { url: 'https://www.aboutamazon.com/news/retail/amazon-pharmacy-insulin-coupons', text: 'Amazon' }
}
};
// Max dose limits per injection for insulin pens (in units)
this.maxDoseLimits = {
'humalog-kwikpen': 60,
'humalog-kwikpen-u200': 160,
'novolog-flexpen': 60,
'fiasp-flextouch': 80,
'lantus-solostar': 80,
'basaglar-kwikpen': 80,
'tresiba-flextouch': 80,
'tresiba-flextouch-u200': 160,
'toujeo-solostar': 80,
'toujeo-max-solostar': 160, // Note: This doesn't exist in current data but included for completeness
'levemir-flextouch': 80,
'admelog-solostar': 60, // Same as Humalog U-100
'apidra-solostar': 60 // Typical for rapid-acting pens
};
this.populateModal();
}
bindEvents() {
this.copyBtn.addEventListener('click', () => this.copyPrescription());
this.disclaimerBtn.addEventListener('click', () => this.showDisclaimer());
this.closeDisclaimerModal.addEventListener('click', () => this.hideDisclaimer());
this.closeDisclaimerModalBtn.addEventListener('click', () => this.hideDisclaimer());
this.disclaimerModal.addEventListener('click', (e) => {
if (e.target === this.disclaimerModal) {
this.hideDisclaimer();
}
});
// Modal events
this.penSelectButton.addEventListener('click', () => {
this.openModal();
});
this.penSelectButton.addEventListener('keydown', (e) => this.handleButtonKeydown(e));
// Close modal events
this.closePenModal.addEventListener('click', () => {
this.closeModal();
});
// Close modal on escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.penSelectorModal &&
!this.penSelectorModal.classList.contains('hidden')) {
this.closeModal();
}
});
// Close modal when clicking outside
this.penSelectorModal.addEventListener('click', (e) => {
if (e.target === this.penSelectorModal) {
this.closeModal();
}
});
// Priming loss toggle event
if (this.wastageToggle) {
this.wastageToggle.addEventListener('change', () => {
this.includeWastage = this.wastageToggle.checked;
this.calculate();
});
}
// Priming help tooltip event
if (this.primingHelpBtn && this.primingHelpTooltip) {
this.primingHelpBtn.addEventListener('click', () => {
this.primingHelpTooltip.classList.toggle('hidden');
});
// Close tooltip when clicking outside
document.addEventListener('click', (e) => {
if (!this.primingHelpBtn.contains(e.target) && !this.primingHelpTooltip.contains(e.target)) {
this.primingHelpTooltip.classList.add('hidden');
}
});
}
// Live calculation on input change
const inputs = [
this.daySupplyInput,
this.unitsPerDoseInput,
this.doseFrequencyInput,
this.concentrationInput,
this.volumePerPenInput
];
inputs.forEach(input => {
input.addEventListener('input', () => {
this.calculate();
// Update expiration warning when day supply changes
if (input === this.daySupplyInput) {
this.checkExpirationWarning(this.penSelect);
}
});
input.addEventListener('change', () => {
this.calculate();
// Update expiration warning when day supply changes
if (input === this.daySupplyInput) {
this.checkExpirationWarning(this.penSelect);
}
});
});
}
getInputValues() {
return {
daySupply: parseFloat(this.daySupplyInput.value) || 30,
unitsPerDose: parseFloat(this.unitsPerDoseInput.value),
doseFrequency: parseFloat(this.doseFrequencyInput.value) || 1,
concentration: parseFloat(this.concentrationInput.value),
volumePerPen: parseFloat(this.volumePerPenInput.value)
};
}
validateInputs(values) {
const errors = [];
if (!values.unitsPerDose || values.unitsPerDose <= 0) {
errors.push('Units per dose is required and must be greater than 0');
}
if (!values.concentration || values.concentration <= 0) {
errors.push('Insulin concentration is required and must be greater than 0');
}
if (!values.volumePerPen || values.volumePerPen <= 0) {
errors.push('Volume per pen is required and must be greater than 0');
}
if (values.daySupply <= 0) {
errors.push('Day supply must be greater than 0');
}
if (values.doseFrequency <= 0) {
errors.push('Dose frequency must be greater than 0');
}
return errors;
}
calculateResults(values) {
// Baseline units needed = units/dose × doses/day × days
const baselineUnits = values.unitsPerDose * values.doseFrequency * values.daySupply;
// Calculate priming loss based on manufacturer specifications
let primingLoss = 0;
let primingUnitsPerDose = 0;
if (this.includeWastage && this.selectedPen && this.selectedPen.priming_units) {
primingUnitsPerDose = this.selectedPen.priming_units;
// priming_loss = priming_units × injections_per_day × days_supply
primingLoss = primingUnitsPerDose * values.doseFrequency * values.daySupply;
}
// Total units needed = baseline + priming loss
const totalUnits = baselineUnits + primingLoss;
// Total mL needed = total units ÷ units/mL
const totalML = totalUnits / values.concentration;
// Pens to order = ceil(total mL ÷ mL per pen)
let pensToOrder = Math.ceil(totalML / values.volumePerPen);
// Check expiration constraints
const expirationCheck = this.checkPenExpiration(values.daySupply, pensToOrder);
if (expirationCheck.needsMorePens) {
pensToOrder = expirationCheck.recommendedPens;
}
return {
baselineUnits: Math.round(baselineUnits * 100) / 100,
primingLoss: Math.round(primingLoss * 100) / 100,
primingUnitsPerDose,
totalUnits: Math.round(totalUnits * 100) / 100,
totalML: Math.round(totalML * 100) / 100,
pensToOrder,
expirationWarning: expirationCheck.warning,
wastageIncluded: this.includeWastage,
dailyDose: values.unitsPerDose * values.doseFrequency // Add daily dose for clinical guidance
};
}
displayClinicalGuidance(values, results) {
// Only show guidance for Lantus or Toujeo
if (!this.selectedPen ||
(this.selectedPen.value !== 'lantus-solostar' && this.selectedPen.value !== 'toujeo-solostar')) {
this.clinicalGuidance.classList.add('hidden');
return;
}
const dailyDose = results.dailyDose;
let guidanceText = '';
// Don't show guidance for patients under 60 units
if (dailyDose < 60) {
this.clinicalGuidance.classList.add('hidden');
return;
}
if (this.selectedPen.value === 'lantus-solostar') {
if (dailyDose >= 60) {
guidanceText = 'For patients requiring 60 units or more per day, consider switching to Toujeo (insulin glargine U-300) for easier injections (lower volume), and potentially smoother, longer-acting insulin coverage.';
}
} else if (this.selectedPen.value === 'toujeo-solostar') {
guidanceText = 'Toujeo (insulin glargine U-300) may be preferred for patients needing higher daily doses (≥60 units), or when smoother, longer-acting basal coverage is desired.';
}
if (guidanceText) {
this.clinicalGuidanceText.textContent = guidanceText;
this.clinicalGuidance.classList.remove('hidden');
} else {
this.clinicalGuidance.classList.add('hidden');
}
}
generatePrescriptionNote(values, results) {
const insulinType = this.selectedPen ? this.selectedPen.generic : 'insulin';
const frequency = values.doseFrequency === 1 ? 'daily' : `${values.doseFrequency} times daily`;
return `Order ${results.pensToOrder} pen${results.pensToOrder > 1 ? 's' : ''} of ${insulinType} ${values.concentration} units/mL, use ${values.unitsPerDose} units ${frequency}, ${values.daySupply} day supply`;
}
generateDischargeText(values, results) {
let breakdown = `Baseline units: ${results.baselineUnits}\n`;
if (this.includeWastage && results.primingLoss > 0) {
breakdown += `Priming loss: ${results.primingLoss} units (based on ${results.primingUnitsPerDose} units × ${values.doseFrequency} × ${values.daySupply})\n`;
breakdown += `Total units required (including priming): ${results.totalUnits} units\n\n`;
} else {
breakdown += `Total units required: ${results.totalUnits} units\n\n`;
}
const pensNeeded = results.pensToOrder;
breakdown += `Pens Needed: ${pensNeeded}\n\n`;
return breakdown;
}
generateRxSig(values, results) {
const insulinType = this.selectedPen ? this.selectedPen.generic : 'insulin';
const brandName = this.selectedPen ? this.selectedPen.brand : 'Insulin Pen';
const frequency = values.doseFrequency === 1 ? 'once daily' : `${values.doseFrequency} times daily`;
// Use 5-pen box NDC for discharge prescriptions
let ndcCode = 'N/A';
console.log('generateRxSig - selectedPen:', this.selectedPen);
if (this.selectedPen && this.selectedPen.ndc_codes) {
console.log('NDC codes available:', this.selectedPen.ndc_codes);
// Look for 5-pen box NDC (ending in -05) or use first available
const boxNDC = this.selectedPen.ndc_codes.find(ndc => ndc.endsWith('-05'));
ndcCode = boxNDC || this.selectedPen.ndc_codes[0];
console.log('Selected NDC:', ndcCode);
} else {
console.log('No selectedPen or no ndc_codes');
}
return {
sig: `Inject ${values.unitsPerDose} units subcutaneously ${frequency}.`,
disp: `Disp: ${results.pensToOrder} pen${results.pensToOrder > 1 ? 's' : ''} (${values.volumePerPen} mL each)`,
ndc: `NDC: ${ndcCode}`,
fullSig: `${insulinType} ${values.concentration} units/mL pen\n\nInject ${values.unitsPerDose} units subcutaneously ${frequency}.\n\nDisp: ${results.pensToOrder} pen${results.pensToOrder > 1 ? 's' : ''} (${values.volumePerPen} mL each)\nNDC: ${ndcCode}`
};
}
displayResults(results, prescriptionNote) {
// Validate calculation results before displaying
const validation = this.validateCalculationResults(results);
if (!validation.isValid) {
this.displayError(validation.errors);
return;
}
// Always use discharge mode display
this.totalUnitsSpan.textContent = `${results.totalUnits} units`;
this.totalMLSpan.textContent = `${results.totalML} mL`;
this.pensToOrderSpan.textContent = results.pensToOrder;
// Custom discharge prescription text
const values = this.getInputValues();
const dischargeText = this.generateDischargeText(values, results);
this.prescriptionTextP.textContent = dischargeText;
// Generate and display Rx Sig
const rxSig = this.generateRxSig(values, results);
if (this.sigGeneration) {
this.sigGeneration.innerHTML = `
<div class="text-sm font-mono bg-gray-50 p-3 sm:p-4 rounded-md border border-gray-200">
<div class="font-bold mb-2 text-gray-900">Prescription Sig:</div>
<div class="text-gray-800">${rxSig.sig}</div>
<div class="mt-2 text-gray-800">${rxSig.disp}</div>
<div class="text-gray-800">${rxSig.ndc}</div>
</div>
`;
}
// Show warnings if any
if (validation.warnings.length > 0) {
this.showCalculationWarnings(validation.warnings);
}
// Show discount links
this.displayDiscountLinks(values, results);
// Show clinical guidance for Lantus/Toujeo
this.displayClinicalGuidance(values, results);
this.resultsDiv.classList.remove('hidden');
this.errorDiv.classList.add('hidden');
}
validateCalculationResults(results) {
const errors = [];
const warnings = [];
// Check for unreasonable total units
if (results.totalUnits > 10000) {
errors.push('Calculated total units is extremely high. Please verify inputs.');
} else if (results.totalUnits > 3000) {
warnings.push('High total units calculated. Please double-check dosing.');
}
// Check for unreasonable pen count
if (results.pensToOrder > 50) {
errors.push('Calculated pen count is unusually high. Please verify inputs.');
} else if (results.pensToOrder > 20) {
warnings.push('High number of pens calculated. Please verify day supply and dosing.');
}
// Check for very small doses that might indicate input errors
if (results.totalUnits < 1) {
warnings.push('Very low total units calculated. Please verify dosing inputs.');
}
return {
isValid: errors.length === 0,
errors,
warnings
};
}
showCalculationWarnings(warnings) {
// Create warning display above results
const existingWarning = this.resultsDiv.querySelector('.calculation-warnings');
if (existingWarning) {
existingWarning.remove();
}
const warningDiv = document.createElement('div');
warningDiv.className = 'calculation-warnings bg-yellow-50 border border-yellow-200 rounded-lg p-3 mb-4';
const title = document.createElement('div');
title.className = 'text-sm font-medium text-yellow-800 mb-2';
title.textContent = '⚠️ Please Review:';
warningDiv.appendChild(title);
warnings.forEach(warning => {
const warningText = document.createElement('div');
warningText.className = 'text-sm text-yellow-700';
warningText.textContent = `• ${warning}`;
warningDiv.appendChild(warningText);
});
this.resultsDiv.insertBefore(warningDiv, this.resultsDiv.firstChild);
}
displayError(errors) {
this.errorDiv.querySelector('p').textContent = errors.join('. ');
this.errorDiv.classList.remove('hidden');
this.resultsDiv.classList.add('hidden');
this.clinicalGuidance.classList.add('hidden');
}
calculate() {
const values = this.getInputValues();
// Don't show validation errors if essential fields are empty (user hasn't started yet)
if (!values.unitsPerDose || !values.concentration || !values.volumePerPen) {
this.resultsDiv.classList.add('hidden');
this.errorDiv.classList.add('hidden');
this.clinicalGuidance.classList.add('hidden');
return;
}
const errors = this.validateInputs(values);
if (errors.length > 0) {
this.displayError(errors);
return;
}
const results = this.calculateResults(values);
const prescriptionNote = this.generatePrescriptionNote(values, results);
this.displayResults(results, prescriptionNote);
}
async copyPrescription() {
try {
const text = this.prescriptionTextP.textContent;
await navigator.clipboard.writeText(text);
// Visual feedback
const originalText = this.copyBtn.textContent;
this.copyBtn.textContent = 'Copied!';
this.copyBtn.classList.add('bg-green-600');
this.copyBtn.classList.remove('bg-blue-600');
setTimeout(() => {
this.copyBtn.textContent = originalText;
this.copyBtn.classList.remove('bg-green-600');
this.copyBtn.classList.add('bg-blue-600');
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
// Fallback: show alert with text to copy manually
alert(`Copy this prescription note:\n\n${this.prescriptionTextP.textContent}`);
}
}
async populateModal() {
try {
const response = await fetch('final_insulin_pens.json');
const data = await response.json();
this.insulinPens = data;
// Populate modal content
this.populateModalContent();
// Set default selection to Lantus SoloStar after DOM is ready
setTimeout(() => {
this.selectPen('lantus-solostar');
}, 0);
} catch (error) {
console.error('Error loading insulin pens:', error);
}
}
populateModalContent() {
if (!this.insulinPens || !this.penSelectorContent) return;
this.penSelectorContent.innerHTML = '';
// Add pen options by category
const categories = ['basal', 'rapid', 'ultra-rapid'];
const categoryLabels = {
'basal': 'Long-Acting (Basal)',
'rapid': 'Rapid-Acting (Mealtime)',
'ultra-rapid': 'Ultra-Rapid-Acting'
};
categories.forEach(category => {
if (this.insulinPens[category] && this.insulinPens[category].length > 0) {
// Add category section
const categorySection = document.createElement('div');
categorySection.className = 'space-y-3';
// Add category header
const categoryHeader = document.createElement('h4');
categoryHeader.className = 'text-sm font-medium text-gray-800 mb-3';
categoryHeader.textContent = categoryLabels[category];
categorySection.appendChild(categoryHeader);
// Add pen grid
const penGrid = document.createElement('div');
penGrid.className = 'grid grid-cols-1 sm:grid-cols-2 gap-3';
// Add pen options
this.insulinPens[category].forEach(pen => {
const has35MonthDiscount = this.penDiscountInfo[pen.value] &&
(this.penDiscountInfo[pen.value].goodrx || this.penDiscountInfo[pen.value].novocare);
const penCard = document.createElement('button');
penCard.type = 'button';
penCard.className = 'pen-card rounded-lg shadow px-4 py-4 sm:py-3 hover:ring hover:ring-blue-300 transition text-left bg-white border border-gray-200 focus:outline-none min-h-[64px] sm:min-h-[auto] active:bg-gray-50';
penCard.setAttribute('data-pen-value', pen.value);
penCard.setAttribute('data-pen-id', pen.value); // Add data-pen-id for consistency
// Selection state will be set by updateModalSelection() when modal opens
penCard.innerHTML = `
<div class="flex items-start space-x-3">
<div class="flex-shrink-0">
<svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"></path></svg>
</div>
<div class="flex-1 min-w-0">
<div class="flex items-center space-x-2">
${has35MonthDiscount ? '<span class="text-xs font-medium text-green-700 bg-green-50 px-1.5 py-0.5 rounded">$35/mo</span>' : ''}
<div class="font-medium text-gray-900 truncate">${pen.brand}</div>
</div>
<div class="text-sm text-gray-600 mt-1">
<div>${pen.generic}</div>
<div class="flex items-center space-x-2 text-xs text-gray-500 mt-1">
<span>${pen.concentration} units/mL</span>
<span>•</span>
<span>${pen.volume} mL</span>
${has35MonthDiscount ? '<span>• $35/month</span>' : ''}
</div>
</div>
</div>
</div>
`;
penCard.addEventListener('click', () => {
this.selectPen(pen.value);
});
penCard.addEventListener('keydown', (e) => this.handleCardKeydown(e, pen.value));
penGrid.appendChild(penCard);
});
categorySection.appendChild(penGrid);
this.penSelectorContent.appendChild(categorySection);
}
});
}
// Modal methods
openModal() {
this.penSelectorModal.classList.remove('hidden');
this.penSelectButton.setAttribute('aria-expanded', 'true');
document.body.style.overflow = 'hidden';
// Update visual selection to match current state
this.updateModalSelection();
// Focus first pen card for accessibility (but not the selected one to avoid focus ring confusion)
const firstPenCard = this.penSelectorContent.querySelector('.pen-card');
if (firstPenCard && !this.isMobile()) {
// Only focus if it's not the selected card to avoid focus ring on selected item
if (firstPenCard.getAttribute('data-pen-id') !== this.currentPenId) {
firstPenCard.focus();
}
}
}
closeModal() {
this.penSelectorModal.classList.add('hidden');
this.penSelectButton.setAttribute('aria-expanded', 'false');
document.body.style.overflow = '';
this.penSelectButton.focus();
}
setPenValues(unitsPerMl, mlPerPen, penType = null) {
this.concentrationInput.value = unitsPerMl;
this.volumePerPenInput.value = mlPerPen;
// Disable concentration and volume fields when pen is selected (fixed values)
this.concentrationInput.disabled = true;
this.volumePerPenInput.disabled = true;
this.concentrationInput.classList.add('bg-gray-100', 'cursor-not-allowed');
this.volumePerPenInput.classList.add('bg-gray-100', 'cursor-not-allowed');
if (penType === 'rapid' || penType === 'ultra-rapid') {
this.doseFrequencyInput.value = 3;
} else if (penType === 'basal') {
this.doseFrequencyInput.value = 1;
}
const selectedValue = this.penSelect;
this.selectedPen = selectedValue ? this.findPenByValue(selectedValue) : null;
this.calculate();
}
findPenByValue(value) {
if (!this.insulinPens) return null;
for (const category of Object.values(this.insulinPens)) {
if (Array.isArray(category)) {
const pen = category.find(p => p.value === value);
if (pen) return pen;
}
}
return null;
}
findPenType(value) {
if (!this.insulinPens) return null;
for (const [type, category] of Object.entries(this.insulinPens)) {
if (Array.isArray(category)) {
const pen = category.find(p => p.value === value);
if (pen) return type;
}
}
return null;
}
updateResultsUI() {
// No additional UI updates needed in discharge mode
}
showDisclaimer() {
this.disclaimerModal.classList.remove('hidden');
document.body.style.overflow = 'hidden';
}
hideDisclaimer() {
this.disclaimerModal.classList.add('hidden');
document.body.style.overflow = 'auto';
}
bindWeightSliderEvents() {
this.dosingSlider.addEventListener('input', () => this.calculateDoseFromSlider());
this.patientWeightInput.addEventListener('input', () => {
this.validateWeightInput();
this.updateSliderState();
this.calculateDoseFromSlider();
});
// Handle iOS keyboard dismissal and auto-scroll
this.patientWeightInput.addEventListener('blur', () => {
// Small delay to ensure keyboard is dismissed
setTimeout(() => {
if (this.patientWeightInput.value && this.patientWeightInput.value.trim() !== '') {
this.scrollToDosingSlider();
}
}, 300);
});
this.weightUnitToggle.addEventListener('click', () => this.toggleWeightUnit());
// Add hover events for tooltip
this.dosingSlider.addEventListener('mouseenter', () => this.showSliderTooltip());
this.dosingSlider.addEventListener('mouseleave', () => this.hideSliderTooltip());
this.updateSliderState();
this.calculateDoseFromSlider();
}
calculateDoseFromSlider() {
const weight = parseFloat(this.patientWeightInput.value);
const sliderValue = parseInt(this.dosingSlider.value);
const weightUnit = this.weightUnitToggle.dataset.unit;
const dosingValues = [0.1, 0.2, 0.3];
const dosingRate = dosingValues[sliderValue] || 0.1;
this.sliderValueSpan.textContent = `${dosingRate} u/kg/day`;
if (weight && weight > 0 && this.isValidWeight(weight)) {
let weightInKg = weight;
if (weightUnit === 'lbs') {
weightInKg = weight * 0.4536;
}
const dailyDose = Math.round(weightInKg * dosingRate);
this.estimatedDoseSpan.textContent = `${dailyDose} units`;
this.setDoseFromWeight(dailyDose);
} else {
this.estimatedDoseSpan.textContent = weight ? 'Invalid weight' : 'Enter weight above';
}
}
setDoseFromWeight(dose) {
if (dose && dose > 0) {
this.unitsPerDoseInput.value = dose;
this.calculate();
}
}
toggleWeightBasedDosing(penType) {
if (penType === 'basal') {
this.weightBasedDosingDiv.classList.remove('hidden');
} else {
this.weightBasedDosingDiv.classList.add('hidden');
}
}
showPricingInfo(penValue, pen) {
// Hide pricing info for all pens
this.pricingInfoDiv.classList.add('hidden');
}
toggleWeightUnit() {
const currentUnit = this.weightUnitToggle.dataset.unit;
const newUnit = currentUnit === 'kg' ? 'lbs' : 'kg';
const currentWeight = parseFloat(this.patientWeightInput.value);
// If there's a weight value, ask for confirmation
if (currentWeight && currentWeight > 0) {
const convertedWeight = currentUnit === 'kg'
? Math.round(currentWeight / 0.4536 * 10) / 10 // kg to lbs
: Math.round(currentWeight * 0.4536 * 10) / 10; // lbs to kg
const message = `Convert ${currentWeight} ${currentUnit} to ${convertedWeight} ${newUnit}?`;
const options = [
{ text: 'Convert Weight', action: 'convert' },
{ text: 'Clear Weight', action: 'clear' },
{ text: 'Cancel', action: 'cancel' }
];
this.showWeightConversionDialog(message, options, (action) => {
if (action === 'convert') {
this.patientWeightInput.value = convertedWeight;
this.updateWeightUnit(newUnit);
} else if (action === 'clear') {
this.patientWeightInput.value = '';
this.updateWeightUnit(newUnit);
}
// For 'cancel', do nothing
});
} else {
// No weight value, just change unit
this.updateWeightUnit(newUnit);
}
}
updateWeightUnit(newUnit) {
this.weightUnitToggle.dataset.unit = newUnit;
this.weightUnitToggle.textContent = newUnit;
this.calculateDoseFromSlider();
}
showWeightConversionDialog(message, options, callback) {
// Create modal overlay
const overlay = document.createElement('div');
overlay.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50';
// Create dialog
const dialog = document.createElement('div');
dialog.className = 'bg-white rounded-lg max-w-sm w-full p-6';
// Add message
const messageEl = document.createElement('p');
messageEl.className = 'text-gray-900 mb-4 text-center';
messageEl.textContent = message;
dialog.appendChild(messageEl);
// Add buttons
const buttonContainer = document.createElement('div');
buttonContainer.className = 'space-y-2';
options.forEach(option => {
const button = document.createElement('button');
button.className = option.action === 'convert'
? 'w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500'
: option.action === 'clear'
? 'w-full bg-yellow-600 text-white py-2 px-4 rounded-md hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-yellow-500'
: 'w-full bg-gray-300 text-gray-700 py-2 px-4 rounded-md hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-500';
button.textContent = option.text;
button.addEventListener('click', () => {
document.body.removeChild(overlay);
callback(option.action);
});
buttonContainer.appendChild(button);
});
dialog.appendChild(buttonContainer);
overlay.appendChild(dialog);
document.body.appendChild(overlay);
// Close on overlay click
overlay.addEventListener('click', (e) => {
if (e.target === overlay) {
document.body.removeChild(overlay);
callback('cancel');
}
});
}
setupInputValidation() {
// Enhanced validation for all numeric inputs
this.unitsPerDoseInput.addEventListener('input', (e) => {
this.validateUnitsPerDose(e.target);
this.checkMaxDoseLimit();
});
this.daySupplyInput.addEventListener('input', (e) => {
this.validateDaySupply(e.target);
});
this.concentrationInput.addEventListener('input', (e) => {
this.validateConcentration(e.target);
});
this.volumePerPenInput.addEventListener('input', (e) => {
this.validateVolumePerPen(e.target);
});
this.doseFrequencyInput.addEventListener('input', (e) => {
this.validateDoseFrequency(e.target);
});
}
validateConcentration(input) {
const value = parseFloat(input.value);
if (!input.value || input.value.trim() === '' || isNaN(value)) {
this.clearInputValidation(input);
return true;
}
if (value <= 0) {
this.showInputError(input, 'Concentration must be greater than 0');
return false;
}
if (value < 50 || value > 500) {
this.showInputError(input, 'Concentration typically 50-500 units/mL');
return false;
}
this.clearInputValidation(input);
return true;
}
validateVolumePerPen(input) {
const value = parseFloat(input.value);
if (!input.value || input.value.trim() === '' || isNaN(value)) {
this.clearInputValidation(input);
return true;
}
if (value <= 0) {
this.showInputError(input, 'Volume must be greater than 0');
return false;
}
if (value < 0.5 || value > 10) {
this.showInputError(input, 'Volume typically 0.5-10 mL per pen');
return false;
}
this.clearInputValidation(input);
return true;
}
validateDoseFrequency(input) {
const value = parseFloat(input.value);
if (!input.value || input.value.trim() === '' || isNaN(value)) {
this.clearInputValidation(input);
return true;
}
if (value <= 0 || value !== Math.floor(value)) {
this.showInputError(input, 'Frequency must be a whole number greater than 0');
return false;
}
if (value > 10) {
this.showInputError(input, 'Frequency typically 1-10 doses per day');
return false;
}
this.clearInputValidation(input);
return true;
}
validateUnitsPerDose(input) {
const value = parseFloat(input.value);
// Don't validate empty fields (user hasn't entered anything yet)
if (!input.value || input.value.trim() === '' || isNaN(value)) {
this.clearInputValidation(input);
return true;
}
if (value <= 0) {
this.showInputError(input, 'Dose must be greater than 0');