-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReceipt_Reader.html
More file actions
656 lines (603 loc) · 27.7 KB
/
Copy pathReceipt_Reader.html
File metadata and controls
656 lines (603 loc) · 27.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PBC Rx Claim Helper</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script>
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
</script>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,500;0,9..40,700;1,9..40,400&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<style>
:root {
--bg: #f0f2f5;
--card: #ffffff;
--border: #e1e5ea;
--accent: #1a73e8;
--accent-light: #e8f0fe;
--text: #1a1d21;
--text-muted: #5f6368;
--success: #0d904f;
--success-bg: #e6f4ea;
--error: #c5221f;
--error-bg: #fce8e6;
--highlight: #174ea6;
--highlight-bg: #d2e3fc;
--mono: 'JetBrains Mono', monospace;
--sans: 'DM Sans', system-ui, sans-serif;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: var(--sans); background: var(--bg); color: var(--text); min-height: 100vh; }
/* Header bar */
.topbar {
background: #1a1d21;
color: #fff;
padding: 16px 24px;
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 12px;
position: sticky;
top: 0;
z-index: 50;
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
.topbar h1 { font-size: 18px; font-weight: 700; letter-spacing: -0.3px; }
.topbar h1 span { color: var(--accent); }
.topbar-controls { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.key-input {
background: rgba(255,255,255,0.08);
border: 1px solid rgba(255,255,255,0.15);
color: #fff;
padding: 7px 12px;
border-radius: 8px;
font-size: 13px;
width: 260px;
font-family: var(--mono);
transition: border-color 0.2s;
}
.key-input:focus { outline: none; border-color: var(--accent); background: rgba(255,255,255,0.12); }
.key-input::placeholder { color: rgba(255,255,255,0.35); }
.key-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-left: -28px; margin-right: 12px; pointer-events: none; }
.key-dot.active { background: #34a853; box-shadow: 0 0 6px rgba(52,168,83,0.5); }
.key-dot.inactive { background: #5f6368; }
/* Drop zone */
.dropzone {
margin: 24px auto;
max-width: 960px;
border: 2px dashed var(--border);
border-radius: 16px;
padding: 40px 24px;
text-align: center;
cursor: pointer;
transition: all 0.25s;
background: var(--card);
}
.dropzone:hover, .dropzone.dragover {
border-color: var(--accent);
background: var(--accent-light);
}
.dropzone-icon {
width: 56px; height: 56px;
margin: 0 auto 12px;
background: var(--accent-light);
border-radius: 50%;
display: flex; align-items: center; justify-content: center;
transition: transform 0.2s;
}
.dropzone:hover .dropzone-icon { transform: scale(1.1); }
.dropzone h3 { font-size: 15px; font-weight: 600; color: var(--text); }
.dropzone p { font-size: 13px; color: var(--text-muted); margin-top: 4px; }
/* Summary bar */
.summary-bar {
max-width: 960px;
margin: 0 auto 20px;
display: flex;
gap: 12px;
flex-wrap: wrap;
align-items: center;
padding: 0 4px;
}
.summary-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
border-radius: 20px;
font-size: 13px;
font-weight: 600;
background: var(--card);
border: 1px solid var(--border);
}
.summary-chip .num { font-family: var(--mono); color: var(--accent); }
/* Results */
.results-grid {
max-width: 960px;
margin: 0 auto;
padding: 0 4px 40px;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(420px, 1fr));
gap: 16px;
}
@media (max-width: 480px) { .results-grid { grid-template-columns: 1fr; } }
/* Card */
.rx-card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
overflow: hidden;
animation: slideUp 0.35s ease-out;
box-shadow: 0 1px 3px rgba(0,0,0,0.04);
}
@keyframes slideUp { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }
.rx-card-header {
padding: 12px 16px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid var(--border);
background: #fafbfc;
}
.rx-card-header .filename { font-size: 12px; font-weight: 600; color: var(--text-muted); max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.badge {
font-size: 11px; font-weight: 700; padding: 3px 10px; border-radius: 6px;
display: inline-flex; align-items: center; gap: 5px; letter-spacing: 0.3px;
}
.badge.loading { background: var(--accent-light); color: var(--accent); }
.badge.done { background: var(--success-bg); color: var(--success); }
.badge.error { background: var(--error-bg); color: var(--error); }
.rx-card-body { padding: 14px 16px 16px; }
/* Data rows */
.rx-section-label {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.8px;
color: var(--text-muted);
padding: 8px 0 4px;
border-bottom: 1px solid #f0f2f5;
margin-bottom: 2px;
}
.rx-row {
display: flex;
align-items: center;
padding: 5px 0;
border-bottom: 1px solid #f7f8f9;
gap: 8px;
}
.rx-row:last-child { border-bottom: none; }
.rx-label {
font-size: 11px;
font-weight: 600;
color: var(--text-muted);
min-width: 90px;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.rx-value {
flex: 1;
font-size: 13px;
font-weight: 500;
color: var(--text);
font-family: var(--mono);
text-align: right;
user-select: all;
cursor: text;
}
.rx-value.highlight {
color: var(--highlight);
font-weight: 700;
background: var(--highlight-bg);
padding: 2px 8px;
border-radius: 4px;
}
.rx-value.drug-name {
font-family: var(--sans);
font-weight: 600;
color: var(--text);
}
.rx-row .copy-btn {
opacity: 0;
transition: opacity 0.15s;
background: none;
border: none;
cursor: pointer;
padding: 2px;
color: var(--text-muted);
flex-shrink: 0;
}
.rx-row:hover .copy-btn { opacity: 1; }
.copy-btn:hover { color: var(--accent); }
.copy-btn.copied { opacity: 1; color: var(--success); }
.rx-grid-2 { display: grid; grid-template-columns: 1fr 1fr; }
/* Copy-all button */
.copy-all-btn {
margin-top: 10px;
width: 100%;
padding: 8px;
border: 1px solid var(--border);
border-radius: 8px;
background: #fafbfc;
color: var(--text-muted);
font-size: 12px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
}
.copy-all-btn:hover { background: var(--accent-light); color: var(--accent); border-color: var(--accent); }
/* Skeleton */
.skeleton { background: linear-gradient(90deg, #f0f2f5 25%, #e8eaed 50%, #f0f2f5 75%); background-size: 200% 100%; animation: shimmer 1.5s infinite; border-radius: 4px; height: 18px; }
@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
/* Spinner */
.spinner { width: 12px; height: 12px; border: 2px solid var(--accent-light); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.7s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
/* Error message */
.error-box { padding: 10px 14px; background: var(--error-bg); border-radius: 8px; font-size: 12px; color: var(--error); line-height: 1.5; }
.clear-btn {
background: none;
border: 1px solid rgba(255,255,255,0.15);
color: rgba(255,255,255,0.6);
padding: 7px 14px;
border-radius: 8px;
font-size: 12px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.clear-btn:hover { background: rgba(255,255,255,0.08); color: #fff; border-color: rgba(255,255,255,0.3); }
</style>
</head>
<body>
<!-- Top Bar -->
<div class="topbar">
<div>
<h1><span>PBC</span> Rx Claim Helper</h1>
<div style="font-size:11px; color:rgba(255,255,255,0.4); margin-top:2px;">Gemini 3.1 Flash Lite · OpenRouter</div>
</div>
<div class="topbar-controls">
<button class="clear-btn" onclick="clearAll()" title="Clear all results">Clear All</button>
<div style="position:relative; display:flex; align-items:center;">
<input type="password" id="apiKey" placeholder="sk-or-... OpenRouter Key" class="key-input" onchange="saveKey()" oninput="saveKey()">
<span id="keyDot" class="key-dot inactive"></span>
</div>
</div>
</div>
<!-- Drop Zone -->
<label class="dropzone" id="dropzone">
<input type="file" id="fileInput" multiple accept=".pdf,image/jpeg,image/png" style="display:none" onchange="handleFiles(this.files)">
<div class="dropzone-icon">
<svg width="26" height="26" fill="none" stroke="#1a73e8" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/></svg>
</div>
<h3>Drop Pharmacy Receipt PDFs Here</h3>
<p>Scans with Gemini 3.1 Flash Lite vision — extracts fields for PBC claims</p>
</label>
<!-- Summary -->
<div class="summary-bar" id="summaryBar" style="display:none;">
<div class="summary-chip">Receipts: <span class="num" id="countTotal">0</span></div>
<div class="summary-chip">Total Patient Paid: <span class="num" id="sumPaid">$0.00</span></div>
</div>
<!-- Results -->
<div class="results-grid" id="results"></div>
<!-- Optional local config (gitignored): pre-fills your OpenRouter key and
model so you don't paste them each time. Copy config.example.js to
config.local.js and fill it in. A fresh clone without this file simply
falls back to the manual key field (a harmless 404 in the console). -->
<script src="config.local.js"></script>
<script>
// ===== CONFIG =====
// MODEL and the API key can be supplied by config.local.js (gitignored)
// via window.RX_CONFIG, keeping them out of this file and out of git.
const RX_CONFIG = window.RX_CONFIG || {};
const MODEL = RX_CONFIG.MODEL || "google/gemini-3.1-flash-lite";
// ===== STATE =====
let API_KEY = "";
let parsedReceipts = [];
// Restore key — prefer config.local.js, then the browser's saved key.
try {
API_KEY = RX_CONFIG.OPENROUTER_KEY || localStorage.getItem("openrouter_key") || "";
if (API_KEY) {
document.getElementById('apiKey').value = API_KEY;
setKeyDot(true);
}
} catch(e) {}
function saveKey() {
API_KEY = document.getElementById('apiKey').value.trim();
try { localStorage.setItem("openrouter_key", API_KEY); } catch(e) {}
setKeyDot(!!API_KEY);
}
function setKeyDot(ok) {
const d = document.getElementById('keyDot');
d.className = ok ? 'key-dot active' : 'key-dot inactive';
}
// ===== DRAG & DROP =====
const dz = document.getElementById('dropzone');
['dragenter','dragover'].forEach(e => dz.addEventListener(e, ev => { ev.preventDefault(); dz.classList.add('dragover'); }));
['dragleave','drop'].forEach(e => dz.addEventListener(e, ev => { ev.preventDefault(); dz.classList.remove('dragover'); }));
dz.addEventListener('drop', ev => { if (ev.dataTransfer.files.length) handleFiles(ev.dataTransfer.files); });
// ===== CLEAR =====
function clearAll() {
document.getElementById('results').innerHTML = '';
parsedReceipts = [];
updateSummary();
}
// ===== FILE HANDLING =====
async function handleFiles(files) {
if (!API_KEY) {
alert("Please enter your OpenRouter API key first.");
return;
}
for (const file of Array.from(files)) {
const id = 'rx_' + Math.random().toString(36).substr(2, 8);
createCard(id, file.name);
try {
setStatus(id, 'loading', 'Reading...');
const base64 = await fileToBase64Image(file);
setStatus(id, 'loading', 'AI Extracting...');
const data = await callGemini(base64);
parsedReceipts.push(data);
renderCard(id, data);
updateSummary();
} catch (err) {
console.error(err);
showError(id, err.message);
}
}
// Reset file input so same files can be re-uploaded
document.getElementById('fileInput').value = '';
}
// ===== PDF / IMAGE → base64 JPEG =====
async function fileToBase64Image(file) {
if (file.type.startsWith('image/')) {
return await new Promise((res, rej) => {
const r = new FileReader();
r.onload = () => res(r.result);
r.onerror = () => rej(new Error('Failed to read image'));
r.readAsDataURL(file);
});
}
// PDF path
const buf = await file.arrayBuffer();
const pdf = await pdfjsLib.getDocument({ data: buf }).promise;
const page = await pdf.getPage(1);
const vp = page.getViewport({ scale: 2.5 });
const canvas = document.createElement('canvas');
canvas.width = vp.width;
canvas.height = vp.height;
const ctx = canvas.getContext('2d');
await page.render({ canvasContext: ctx, viewport: vp }).promise;
return canvas.toDataURL('image/jpeg', 0.85);
}
// ===== GEMINI API VIA OPENROUTER =====
async function callGemini(dataUrl) {
const prompt = `You are a pharmacy receipt data extractor for Canadian prescription receipts (BC Pharmacare / Pacific Blue Cross).
Extract ALL of the following fields from this receipt image. Return ONLY a valid JSON object with these exact keys:
{
"rx_number": "the Rx: NT-XXXXXXX number",
"claimant": "patient full name as shown (Last, First)",
"initials": "the 2-letter code after the name (e.g. SAS, LG, EL, JD)",
"date": "date in DD-MMM-YYYY format",
"drug_name": "full drug name and strength as printed",
"din": "the DIN number (8 digits)",
"quantity": number of tablets/doses/units dispensed,
"days_supply": number of days supply,
"doctor": "prescribing doctor name",
"cost": the ingredient cost as a number,
"fee": the dispensing fee as a number,
"total": cost + fee total as a number,
"pharmacare": the BC Pharmacare amount as a number (0.00 if none),
"pbc": the Pacific Blue Cross amount as a number (0.00 if not listed or Offline),
"patient_paid": the Patient Pays amount as a number,
"sa_code": "the BCSA#### code (4-digit code only, e.g. 0000 or 0001)",
"new_or_refill": "NEW" or "REFILL",
"illness": "brief inferred condition/use for this medication"
}
IMPORTANT RULES:
- The receipt may be rotated. Read carefully.
- "Patient Pays" is always shown in a bold box - extract that exact number.
- If Pacific Blue Cross shows "Offline" or is not listed, set pbc to 0.00.
- sa_code should be JUST the 4 digits from BCSA#### (e.g., "0000" or "0001").
- Return ONLY the JSON object. No markdown, no backticks, no explanation.`;
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${API_KEY}`,
"Content-Type": "application/json",
"HTTP-Referer": window.location.href,
"X-Title": "PBC Rx Claim Helper"
},
body: JSON.stringify({
model: MODEL,
messages: [{
role: "user",
content: [
{ type: "text", text: prompt },
{ type: "image_url", image_url: { url: dataUrl } }
]
}],
temperature: 0.1,
max_tokens: 1024
})
});
if (!res.ok) {
let msg = `API Error ${res.status}`;
try {
const err = await res.json();
msg = err.error?.message || msg;
if (res.status === 404) msg = "Model not found. Check OpenRouter model availability.";
if (res.status === 402) msg = "Insufficient credits on OpenRouter.";
if (res.status === 429) msg = "Rate limited. Wait a moment and try again.";
} catch(e) {}
throw new Error(msg);
}
const json = await res.json();
if (!json.choices?.length) throw new Error("Empty AI response. Please retry.");
let content = json.choices[0].message.content;
// Strip markdown fences if present
content = content.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();
// Find JSON object in response
const jsonMatch = content.match(/\{[\s\S]*\}/);
if (!jsonMatch) {
console.error("Raw response:", content);
throw new Error("AI did not return valid JSON. Retry this receipt.");
}
try {
return JSON.parse(jsonMatch[0]);
} catch (e) {
console.error("Parse error. Raw:", jsonMatch[0]);
throw new Error("Failed to parse AI response as JSON.");
}
}
// ===== UI: CREATE CARD =====
function createCard(id, filename) {
const div = document.createElement('div');
div.id = id;
div.className = 'rx-card';
div.innerHTML = `
<div class="rx-card-header">
<span class="filename" title="${esc(filename)}">${esc(filename)}</span>
<span id="badge-${id}" class="badge loading"><span class="spinner"></span> Processing</span>
</div>
<div class="rx-card-body" id="body-${id}">
<div style="display:flex;flex-direction:column;gap:8px;padding:8px 0;">
<div class="skeleton" style="width:70%"></div>
<div class="skeleton" style="width:100%"></div>
<div class="skeleton" style="width:55%"></div>
<div class="skeleton" style="width:85%"></div>
<div class="skeleton" style="width:60%"></div>
</div>
</div>
`;
document.getElementById('results').prepend(div);
}
function setStatus(id, type, text) {
const b = document.getElementById(`badge-${id}`);
if (!b) return;
if (type === 'loading') b.innerHTML = `<span class="spinner"></span> ${esc(text)}`;
}
function showError(id, msg) {
const b = document.getElementById(`badge-${id}`);
if (b) { b.className = 'badge error'; b.textContent = 'Error'; }
const body = document.getElementById(`body-${id}`);
if (body) body.innerHTML = `<div class="error-box">${esc(msg)}</div>`;
}
// ===== UI: RENDER CARD =====
function renderCard(id, d) {
const b = document.getElementById(`badge-${id}`);
if (b) {
b.className = 'badge done';
b.innerHTML = `<svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/></svg> Done`;
}
const body = document.getElementById(`body-${id}`);
body.innerHTML = `
<div class="rx-section-label">Prescription</div>
${row('Rx #', d.rx_number)}
${row('Drug', d.drug_name, 'drug-name')}
${row('DIN', d.din)}
${row('Type', d.new_or_refill)}
<div class="rx-section-label">Patient & Provider</div>
${row('Claimant', d.claimant)}
${row('SA Code', d.sa_code)}
${row('Date', d.date)}
${row('Doctor', d.doctor)}
<div class="rx-section-label">Dispensing</div>
<div class="rx-grid-2">
${row('Quantity', d.quantity)}
${row('Days Supply', d.days_supply)}
</div>
<div class="rx-section-label">Costs</div>
<div class="rx-grid-2">
${row('Drug Cost', fmt(d.cost))}
${row('Disp. Fee', fmt(d.fee))}
</div>
${row('Total', fmt(d.total))}
<div class="rx-grid-2">
${row('Pharmacare', fmt(d.pharmacare))}
${row('PBC', fmt(d.pbc))}
</div>
${row('Patient Paid', fmt(d.patient_paid), 'highlight')}
<div class="rx-section-label">Classification</div>
${row('Illness', d.illness)}
<button class="copy-all-btn" onclick='copyAllFields(${JSON.stringify(JSON.stringify(d))})'>
<svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
Copy All Fields
</button>
`;
}
function row(label, value, extraClass = '') {
const v = value != null ? String(value) : '—';
const cls = extraClass ? `rx-value ${extraClass}` : 'rx-value';
return `
<div class="rx-row">
<span class="rx-label">${esc(label)}</span>
<span class="${cls}">${esc(v)}</span>
<button class="copy-btn" onclick="copyOne(this, '${esc(v).replace(/'/g, "\\'")}')">
<svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
</button>
</div>`;
}
// ===== SUMMARY =====
function updateSummary() {
const bar = document.getElementById('summaryBar');
if (parsedReceipts.length === 0) { bar.style.display = 'none'; return; }
bar.style.display = 'flex';
document.getElementById('countTotal').textContent = parsedReceipts.length;
const total = parsedReceipts.reduce((s, r) => s + (parseFloat(r.patient_paid) || 0), 0);
document.getElementById('sumPaid').textContent = '$' + total.toFixed(2);
}
// ===== COPY HELPERS =====
function copyOne(btn, text) {
navigator.clipboard.writeText(text).then(() => {
btn.classList.add('copied');
btn.innerHTML = `<svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>`;
setTimeout(() => {
btn.classList.remove('copied');
btn.innerHTML = `<svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>`;
}, 1200);
});
}
function copyAllFields(jsonStr) {
const d = JSON.parse(jsonStr);
const lines = [
`DIN: ${d.din}`,
`Claimant: ${d.claimant}`,
`SA Code: ${d.sa_code}`,
`Date: ${d.date}`,
`Drug: ${d.drug_name}`,
`Quantity: ${d.quantity}`,
`Days Supply: ${d.days_supply}`,
`Drug Cost: ${fmt(d.cost)}`,
`Disp Fee: ${fmt(d.fee)}`,
`Total: ${fmt(d.total)}`,
`Pharmacare: ${fmt(d.pharmacare)}`,
`PBC: ${fmt(d.pbc)}`,
`Patient Paid: ${fmt(d.patient_paid)}`,
`Illness: ${d.illness}`
].join('\n');
navigator.clipboard.writeText(lines).then(() => {
// Brief visual feedback
event.target.closest('.copy-all-btn').textContent = '✓ Copied!';
setTimeout(() => {
event.target.closest('.copy-all-btn').innerHTML = `<svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg> Copy All Fields`;
}, 1500);
});
}
// ===== UTILS =====
function fmt(n) {
const num = parseFloat(n);
return isNaN(num) ? '0.00' : num.toFixed(2);
}
function esc(s) {
const d = document.createElement('div');
d.textContent = String(s ?? '');
return d.innerHTML;
}
</script>
</body>
</html>