Implement first four phases of medical docs roadmap

This commit is contained in:
Josh-Heaps
2026-02-09 16:35:45 -07:00
parent e69e5663ce
commit 9ede3ae53f
27 changed files with 4095 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
# Medical Documentation System — Roadmap
A dedicated admin-only section for organizing medical documents (receipts, doctor notes, recorded conversations, lab results, etc.) for multiple family members. Uses Claude AI to auto-classify, tag, and extract structured data from uploaded documents. Completely separate from the existing media/gallery system.
---
## Phase 1: Database Foundation & Core Document Management ✅
Tables for people, documents, tags, doctors, conditions, prescriptions, costs. Basic CRUD service. Admin-gated Razor Page with file upload and plain-text note entry.
## Phase 2: People & Document Browsing ✅
UI for managing people (family members). Document list with filtering by person, type icons, download/preview.
## Phase 3: Claude AI Integration ✅
`MedicalAiService` using Claude API. On upload: OCR, text extraction, auto-classification, auto-tagging, structured data extraction. Manual transcript field for audio files.
## Phase 4: Doctors, Conditions & Prescription Tracking ✅
Doctor/condition management (global doctors, per-person conditions). Prescription tracking with doctor linkage, expandable pickup history, and "last pickup" display. Inline add/edit/delete for all entities.
## Phase 5: Financial Tracking ⬅️ **Up Next**
Receipt cost extraction and storage. Aggregation views by year, person, and category.
## Phase 6: Search & Filtering
Full-text search on extracted text. Filter by person, doctor, condition, tags, document type, date range. Combined filters.
## Phase 7: AI-Enhanced Insights
Medical timeline per person. Visit prep summaries. Batch re-analysis when AI improves.
## Phase 8: Polish & Hardening
Background AI processing queue. Pagination/lazy-loading. Export (PDF summary, CSV costs). Mobile-responsive UI.
+449
View File
@@ -0,0 +1,449 @@
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace Media.JoshHeaps.Net.Api;
[ApiController]
[Route("api/medical-docs")]
public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDocsService, MedicalAiService medicalAiService) : ControllerBase
{
// --- People ---
[HttpGet("people")]
public async Task<IActionResult> GetPeople()
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var people = await medicalDocsService.GetPeopleAsync();
return Ok(people);
}
[HttpPost("people")]
public async Task<IActionResult> CreatePerson([FromBody] CreatePersonRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var person = await medicalDocsService.CreatePersonAsync(request.Name.Trim(), request.DateOfBirth, request.Notes);
if (person == null)
return StatusCode(500, new { error = "Failed to create person" });
return Ok(person);
}
// --- Documents ---
[HttpGet("documents")]
public async Task<IActionResult> GetDocuments([FromQuery] long? personId, [FromQuery] int offset = 0, [FromQuery] int limit = 50)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (limit < 1 || limit > 100) limit = 50;
if (offset < 0) offset = 0;
var documents = await medicalDocsService.GetDocumentsAsync(personId, offset, limit);
return Ok(documents);
}
[HttpPost("documents/upload")]
[RequestSizeLimit(52_428_800)] // 50MB
public async Task<IActionResult> UploadDocument([FromForm] long personId, [FromForm] string? title, [FromForm] string? description, [FromForm] DateTime? documentDate, [FromForm] string? classification, IFormFile file)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (file == null || file.Length == 0)
return BadRequest(new { error = "No file provided" });
var doc = await medicalDocsService.SaveDocumentAsync(personId, file, title, description, documentDate, classification);
if (doc == null)
return StatusCode(500, new { error = "Failed to save document" });
medicalAiService.EnqueueProcessing(doc.Id);
return Ok(doc);
}
[HttpPost("documents/note")]
public async Task<IActionResult> CreateNote([FromBody] CreateNoteRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" });
if (string.IsNullOrWhiteSpace(request.Title))
return BadRequest(new { error = "Title is required" });
var doc = await medicalDocsService.SaveNoteAsync(request.PersonId, request.Title.Trim(), request.Description ?? "", request.DocumentDate, request.Classification);
if (doc == null)
return StatusCode(500, new { error = "Failed to create note" });
medicalAiService.EnqueueProcessing(doc.Id);
return Ok(doc);
}
[HttpGet("documents/{id}")]
public async Task<IActionResult> GetDocument(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var doc = await medicalDocsService.GetDocumentByIdAsync(id);
if (doc == null) return NotFound(new { error = "Document not found" });
return Ok(doc);
}
[HttpGet("documents/{id}/download")]
public async Task<IActionResult> DownloadDocument(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var doc = await medicalDocsService.GetDocumentByIdAsync(id);
if (doc == null) return NotFound(new { error = "Document not found" });
if (doc.DocumentType != "file")
return BadRequest(new { error = "Cannot download a note" });
var data = await medicalDocsService.GetDecryptedDocumentDataAsync(id);
if (data == null) return NotFound(new { error = "File not found" });
return File(data, doc.MimeType ?? "application/octet-stream", doc.FileName);
}
[HttpDelete("documents/{id}")]
public async Task<IActionResult> DeleteDocument(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeleteDocumentAsync(id);
if (!success) return NotFound(new { error = "Document not found" });
return Ok(new { success = true });
}
// --- AI Processing ---
[HttpPost("documents/{id}/process")]
public async Task<IActionResult> ProcessDocument(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var doc = await medicalDocsService.GetDocumentByIdAsync(id);
if (doc == null) return NotFound(new { error = "Document not found" });
medicalAiService.EnqueueProcessing(id);
return Ok(new { success = true, message = "AI processing started" });
}
[HttpPost("documents/process-all")]
public async Task<IActionResult> ProcessAllDocuments()
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var unprocessedIds = await medicalDocsService.GetUnprocessedDocumentIdsAsync();
foreach (var docId in unprocessedIds)
{
medicalAiService.EnqueueProcessing(docId);
}
return Ok(new { success = true, queued = unprocessedIds.Count });
}
[HttpGet("documents/{id}/tags")]
public async Task<IActionResult> GetDocumentTags(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var tags = await medicalDocsService.GetDocumentTagsAsync(id);
return Ok(tags);
}
// --- Doctors ---
[HttpGet("doctors")]
public async Task<IActionResult> GetDoctors()
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var doctors = await medicalDocsService.GetDoctorsAsync();
return Ok(doctors);
}
[HttpPost("doctors")]
public async Task<IActionResult> CreateDoctor([FromBody] CreateDoctorRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var doctor = await medicalDocsService.CreateDoctorAsync(request.Name.Trim(), request.Specialty, request.Phone, request.Address, request.Notes);
if (doctor == null)
return StatusCode(500, new { error = "Failed to create doctor" });
return Ok(doctor);
}
[HttpPut("doctors/{id}")]
public async Task<IActionResult> UpdateDoctor(long id, [FromBody] CreateDoctorRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var success = await medicalDocsService.UpdateDoctorAsync(id, request.Name.Trim(), request.Specialty, request.Phone, request.Address, request.Notes);
if (!success) return NotFound(new { error = "Doctor not found" });
return Ok(new { success = true });
}
[HttpDelete("doctors/{id}")]
public async Task<IActionResult> DeleteDoctor(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeleteDoctorAsync(id);
if (!success) return NotFound(new { error = "Doctor not found" });
return Ok(new { success = true });
}
// --- Conditions ---
[HttpGet("conditions")]
public async Task<IActionResult> GetConditions([FromQuery] long personId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
var conditions = await medicalDocsService.GetConditionsAsync(personId);
return Ok(conditions);
}
[HttpPost("conditions")]
public async Task<IActionResult> CreateCondition([FromBody] CreateConditionRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" });
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var condition = await medicalDocsService.CreateConditionAsync(request.PersonId, request.Name.Trim(), request.DiagnosedDate, request.Notes);
if (condition == null)
return StatusCode(500, new { error = "Failed to create condition" });
return Ok(condition);
}
[HttpPut("conditions/{id}")]
public async Task<IActionResult> UpdateCondition(long id, [FromBody] UpdateConditionRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var success = await medicalDocsService.UpdateConditionAsync(id, request.Name.Trim(), request.DiagnosedDate, request.Notes, request.IsActive);
if (!success) return NotFound(new { error = "Condition not found" });
return Ok(new { success = true });
}
[HttpDelete("conditions/{id}")]
public async Task<IActionResult> DeleteCondition(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeleteConditionAsync(id);
if (!success) return NotFound(new { error = "Condition not found" });
return Ok(new { success = true });
}
// --- Prescriptions ---
[HttpGet("prescriptions")]
public async Task<IActionResult> GetPrescriptions([FromQuery] long personId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
var prescriptions = await medicalDocsService.GetPrescriptionsAsync(personId);
return Ok(prescriptions);
}
[HttpPost("prescriptions")]
public async Task<IActionResult> CreatePrescription([FromBody] CreatePrescriptionRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" });
if (string.IsNullOrWhiteSpace(request.MedicationName))
return BadRequest(new { error = "Medication name is required" });
var prescription = await medicalDocsService.CreatePrescriptionAsync(request.PersonId, request.MedicationName.Trim(), request.Dosage, request.Frequency, request.DoctorId, request.StartDate, request.Notes);
if (prescription == null)
return StatusCode(500, new { error = "Failed to create prescription" });
return Ok(prescription);
}
[HttpPut("prescriptions/{id}")]
public async Task<IActionResult> UpdatePrescription(long id, [FromBody] UpdatePrescriptionRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.MedicationName))
return BadRequest(new { error = "Medication name is required" });
var success = await medicalDocsService.UpdatePrescriptionAsync(id, request.MedicationName.Trim(), request.Dosage, request.Frequency, request.DoctorId, request.StartDate, request.EndDate, request.Notes, request.IsActive);
if (!success) return NotFound(new { error = "Prescription not found" });
return Ok(new { success = true });
}
[HttpDelete("prescriptions/{id}")]
public async Task<IActionResult> DeletePrescription(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeletePrescriptionAsync(id);
if (!success) return NotFound(new { error = "Prescription not found" });
return Ok(new { success = true });
}
// --- Pickups ---
[HttpGet("prescriptions/{id}/pickups")]
public async Task<IActionResult> GetPickups(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var pickups = await medicalDocsService.GetPickupsAsync(id);
return Ok(pickups);
}
[HttpPost("prescriptions/{id}/pickups")]
public async Task<IActionResult> CreatePickup(long id, [FromBody] CreatePickupRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var pickup = await medicalDocsService.CreatePickupAsync(id, request.PickupDate, request.Quantity, request.Pharmacy, request.Cost, request.Notes);
if (pickup == null)
return StatusCode(500, new { error = "Failed to create pickup" });
return Ok(pickup);
}
[HttpDelete("pickups/{id}")]
public async Task<IActionResult> DeletePickup(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeletePickupAsync(id);
if (!success) return NotFound(new { error = "Pickup not found" });
return Ok(new { success = true });
}
// --- Auth helpers (same pattern as AdminApi) ---
private async Task<bool> HasMedicalAccess(long userId)
{
return await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.user_roles ur JOIN app.roles r ON ur.role_id = r.id WHERE ur.user_id = @UserId AND r.name = 'medical')",
new { UserId = userId });
}
private long? GetUserIdFromAuth()
{
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!string.IsNullOrEmpty(userIdClaim) && long.TryParse(userIdClaim, out var jwtUserId))
{
return jwtUserId;
}
var userIdString = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userIdString) && long.TryParse(userIdString, out var sessionUserId))
{
return sessionUserId;
}
return null;
}
}
public record CreatePersonRequest(string Name, DateTime? DateOfBirth = null, string? Notes = null);
public record CreateNoteRequest(long PersonId, string Title, string? Description = null, DateTime? DocumentDate = null, string? Classification = null);
public record CreateDoctorRequest(string Name, string? Specialty = null, string? Phone = null, string? Address = null, string? Notes = null);
public record CreateConditionRequest(long PersonId, string Name, DateTime? DiagnosedDate = null, string? Notes = null);
public record UpdateConditionRequest(string Name, DateTime? DiagnosedDate = null, string? Notes = null, bool IsActive = true);
public record CreatePrescriptionRequest(long PersonId, string MedicationName, string? Dosage = null, string? Frequency = null, long? DoctorId = null, DateTime? StartDate = null, string? Notes = null);
public record UpdatePrescriptionRequest(string MedicationName, string? Dosage = null, string? Frequency = null, long? DoctorId = null, DateTime? StartDate = null, DateTime? EndDate = null, string? Notes = null, bool IsActive = true);
public record CreatePickupRequest(DateTime PickupDate, string? Quantity = null, string? Pharmacy = null, decimal? Cost = null, string? Notes = null);
@@ -0,0 +1,9 @@
-- Medical people (family members, not tied to app users)
CREATE TABLE IF NOT EXISTS app.medical_people (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
date_of_birth DATE NULL,
notes TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1,11 @@
-- Medical doctors
CREATE TABLE IF NOT EXISTS app.medical_doctors (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
specialty VARCHAR(255) NULL,
phone VARCHAR(50) NULL,
address TEXT NULL,
notes TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1,13 @@
-- Medical conditions linked to people
CREATE TABLE IF NOT EXISTS app.medical_conditions (
id BIGSERIAL PRIMARY KEY,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
diagnosed_date DATE NULL,
notes TEXT NULL,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_medical_conditions_person_id ON app.medical_conditions(person_id);
@@ -0,0 +1,29 @@
-- Core medical documents table
CREATE TABLE IF NOT EXISTS app.medical_documents (
id BIGSERIAL PRIMARY KEY,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
document_type VARCHAR(10) NOT NULL DEFAULT 'file', -- 'file' or 'note'
file_name VARCHAR(255) NULL,
file_path VARCHAR(500) NULL,
file_size BIGINT NULL,
mime_type VARCHAR(100) NULL,
is_encrypted BOOLEAN DEFAULT true,
title VARCHAR(500) NULL,
description TEXT NULL,
document_date DATE NULL, -- the date OF the document
classification VARCHAR(100) NULL, -- receipt, lab_result, prescription, imaging, etc.
extracted_text TEXT NULL,
ai_processed BOOLEAN DEFAULT false,
ai_processed_at TIMESTAMP NULL,
ai_raw_response JSONB NULL,
doctor_id BIGINT NULL REFERENCES app.medical_doctors(id) ON DELETE SET NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_medical_documents_person_id ON app.medical_documents(person_id);
CREATE INDEX IF NOT EXISTS idx_medical_documents_doctor_id ON app.medical_documents(doctor_id);
CREATE INDEX IF NOT EXISTS idx_medical_documents_classification ON app.medical_documents(classification);
CREATE INDEX IF NOT EXISTS idx_medical_documents_document_date ON app.medical_documents(document_date);
CREATE INDEX IF NOT EXISTS idx_medical_documents_created_at ON app.medical_documents(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_medical_documents_ai_processed ON app.medical_documents(ai_processed);
@@ -0,0 +1,16 @@
-- Medical tags and document-tag junction
CREATE TABLE IF NOT EXISTS app.medical_tags (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS app.medical_document_tags (
document_id BIGINT NOT NULL REFERENCES app.medical_documents(id) ON DELETE CASCADE,
tag_id BIGINT NOT NULL REFERENCES app.medical_tags(id) ON DELETE CASCADE,
source VARCHAR(10) NOT NULL DEFAULT 'manual', -- 'ai' or 'manual'
CONSTRAINT uq_medical_document_tag UNIQUE (document_id, tag_id)
);
CREATE INDEX IF NOT EXISTS idx_medical_document_tags_document_id ON app.medical_document_tags(document_id);
CREATE INDEX IF NOT EXISTS idx_medical_document_tags_tag_id ON app.medical_document_tags(tag_id);
@@ -0,0 +1,32 @@
-- Medical prescriptions and pickup tracking
CREATE TABLE IF NOT EXISTS app.medical_prescriptions (
id BIGSERIAL PRIMARY KEY,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
doctor_id BIGINT NULL REFERENCES app.medical_doctors(id) ON DELETE SET NULL,
medication_name VARCHAR(255) NOT NULL,
dosage VARCHAR(100) NULL,
frequency VARCHAR(100) NULL,
is_active BOOLEAN DEFAULT true,
start_date DATE NULL,
end_date DATE NULL,
notes TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_medical_prescriptions_person_id ON app.medical_prescriptions(person_id);
CREATE INDEX IF NOT EXISTS idx_medical_prescriptions_doctor_id ON app.medical_prescriptions(doctor_id);
CREATE TABLE IF NOT EXISTS app.medical_prescription_pickups (
id BIGSERIAL PRIMARY KEY,
prescription_id BIGINT NOT NULL REFERENCES app.medical_prescriptions(id) ON DELETE CASCADE,
document_id BIGINT NULL REFERENCES app.medical_documents(id) ON DELETE SET NULL,
pickup_date DATE NOT NULL,
quantity VARCHAR(100) NULL,
pharmacy VARCHAR(255) NULL,
cost DECIMAL(10,2) NULL,
notes TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_medical_prescription_pickups_prescription_id ON app.medical_prescription_pickups(prescription_id);
@@ -0,0 +1,16 @@
-- Medical document costs
CREATE TABLE IF NOT EXISTS app.medical_document_costs (
id BIGSERIAL PRIMARY KEY,
document_id BIGINT NOT NULL REFERENCES app.medical_documents(id) ON DELETE CASCADE,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
amount DECIMAL(10,2) NOT NULL,
cost_type VARCHAR(50) NULL, -- copay, deductible, out_of_pocket, etc.
category VARCHAR(50) NULL, -- office_visit, lab, pharmacy, etc.
cost_date DATE NULL,
description TEXT NULL,
source VARCHAR(10) NOT NULL DEFAULT 'manual', -- 'ai' or 'manual'
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_medical_document_costs_document_id ON app.medical_document_costs(document_id);
CREATE INDEX IF NOT EXISTS idx_medical_document_costs_person_id ON app.medical_document_costs(person_id);
@@ -0,0 +1,9 @@
-- Junction table linking medical documents to conditions
CREATE TABLE IF NOT EXISTS app.medical_document_conditions (
document_id BIGINT NOT NULL REFERENCES app.medical_documents(id) ON DELETE CASCADE,
condition_id BIGINT NOT NULL REFERENCES app.medical_conditions(id) ON DELETE CASCADE,
CONSTRAINT uq_medical_document_condition UNIQUE (document_id, condition_id)
);
CREATE INDEX IF NOT EXISTS idx_medical_document_conditions_document_id ON app.medical_document_conditions(document_id);
CREATE INDEX IF NOT EXISTS idx_medical_document_conditions_condition_id ON app.medical_document_conditions(condition_id);
@@ -0,0 +1,13 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalCondition
{
public long Id { get; set; }
public long PersonId { get; set; }
public string Name { get; set; } = string.Empty;
public DateTime? DiagnosedDate { get; set; }
public string? Notes { get; set; }
public bool IsActive { get; set; } = true;
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,13 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalDoctor
{
public long Id { get; set; }
public string Name { get; set; } = string.Empty;
public string? Specialty { get; set; }
public string? Phone { get; set; }
public string? Address { get; set; }
public string? Notes { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,27 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalDocument
{
public long Id { get; set; }
public long PersonId { get; set; }
public string DocumentType { get; set; } = "file"; // "file" or "note"
public string? FileName { get; set; }
public string? FilePath { get; set; }
public long? FileSize { get; set; }
public string? MimeType { get; set; }
public bool IsEncrypted { get; set; } = true;
public string? Title { get; set; }
public string? Description { get; set; }
public DateTime? DocumentDate { get; set; }
public string? Classification { get; set; }
public string? ExtractedText { get; set; }
public bool AiProcessed { get; set; }
public DateTime? AiProcessedAt { get; set; }
public string? AiRawResponse { get; set; }
public long? DoctorId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
// Convenience properties populated separately
public List<MedicalTag> Tags { get; set; } = [];
}
@@ -0,0 +1,15 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalDocumentCost
{
public long Id { get; set; }
public long DocumentId { get; set; }
public long PersonId { get; set; }
public decimal Amount { get; set; }
public string? CostType { get; set; }
public string? Category { get; set; }
public DateTime? CostDate { get; set; }
public string? Description { get; set; }
public string Source { get; set; } = "manual";
public DateTime CreatedAt { get; set; }
}
@@ -0,0 +1,11 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalPerson
{
public long Id { get; set; }
public string Name { get; set; } = string.Empty;
public DateTime? DateOfBirth { get; set; }
public string? Notes { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,21 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalPrescription
{
public long Id { get; set; }
public long PersonId { get; set; }
public long? DoctorId { get; set; }
public string MedicationName { get; set; } = string.Empty;
public string? Dosage { get; set; }
public string? Frequency { get; set; }
public bool IsActive { get; set; } = true;
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string? Notes { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
// Populated via JOIN, not stored in DB
public string? DoctorName { get; set; }
public DateTime? LastPickupDate { get; set; }
}
@@ -0,0 +1,14 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalPrescriptionPickup
{
public long Id { get; set; }
public long PrescriptionId { get; set; }
public long? DocumentId { get; set; }
public DateTime PickupDate { get; set; }
public string? Quantity { get; set; }
public string? Pharmacy { get; set; }
public decimal? Cost { get; set; }
public string? Notes { get; set; }
public DateTime CreatedAt { get; set; }
}
+8
View File
@@ -0,0 +1,8 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalTag
{
public long Id { get; set; }
public string Name { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
}
+32
View File
@@ -119,6 +119,38 @@
</div> </div>
</div> </div>
</a> </a>
}
@if (Model.HasMedicalRole)
{
<a href="/MedicalDocs" class="landing-card">
<div class="card-content">
<div class="card-icon-wrapper">
<div class="card-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="12" y1="11" x2="12" y2="17"></line>
<line x1="9" y1="14" x2="15" y2="14"></line>
</svg>
</div>
</div>
<div class="card-text">
<h2>Medical Documents</h2>
<p class="card-description">Organize medical records, receipts, and notes for the family</p>
</div>
</div>
<div class="card-footer">
<span class="card-link-text">Open workspace</span>
<div class="card-arrow">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="5" y1="12" x2="19" y2="12"></line>
<polyline points="12 5 19 12 12 19"></polyline>
</svg>
</div>
</div>
</a>
} }
</div> </div>
@@ -5,6 +5,7 @@ namespace Media.JoshHeaps.Net.Pages
public class LandingModel(DbExecutor dbExecutor) : AuthenticatedPageModel public class LandingModel(DbExecutor dbExecutor) : AuthenticatedPageModel
{ {
public bool IsAdmin { get; set; } public bool IsAdmin { get; set; }
public bool HasMedicalRole { get; set; }
public async Task<IActionResult> OnGetAsync() public async Task<IActionResult> OnGetAsync()
{ {
@@ -15,6 +16,10 @@ namespace Media.JoshHeaps.Net.Pages
"SELECT EXISTS(SELECT 1 FROM app.user_roles ur JOIN app.roles r ON ur.role_id = r.id WHERE ur.user_id = @UserId AND r.name = 'admin')", "SELECT EXISTS(SELECT 1 FROM app.user_roles ur JOIN app.roles r ON ur.role_id = r.id WHERE ur.user_id = @UserId AND r.name = 'admin')",
new { UserId }); new { UserId });
HasMedicalRole = await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.user_roles ur JOIN app.roles r ON ur.role_id = r.id WHERE ur.user_id = @UserId AND r.name = 'medical')",
new { UserId });
return Page(); return Page();
} }
} }
@@ -0,0 +1,203 @@
@page
@model Media.JoshHeaps.Net.Pages.MedicalDocsModel
@{
ViewData["Title"] = "Medical Documents";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/medical-docs.css" asp-append-version="true" />
}
<div class="dashboard-container">
<div class="welcome-section">
<div class="welcome-left">
<a href="/Landing" class="back-button" title="Back to Home">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="19" y1="12" x2="5" y2="12"></line>
<polyline points="12 19 5 12 12 5"></polyline>
</svg>
</a>
<h1>Medical Documents</h1>
</div>
<div class="quick-actions">
<a href="/Profile" class="btn btn-secondary">Profile</a>
<a href="/Logout" class="btn btn-danger">Logout</a>
</div>
</div>
<div class="medical-layout">
<!-- Sidebar: People -->
<div class="medical-sidebar">
<h3>People</h3>
<div class="sidebar-people-list" id="peopleList"></div>
<div class="sidebar-add-person">
<input type="text" id="newPersonName" placeholder="Add person..." class="form-input" />
<button id="addPersonBtn" class="btn btn-primary btn-sm">Add</button>
</div>
</div>
<!-- Main Content -->
<div class="medical-main">
<!-- Summary Cards -->
<div class="summary-cards" id="summaryCards" style="display: none;">
<div class="summary-card active" data-tab="documents" onclick="medDocsSwitchTab('documents')">
<div class="count" id="summaryDocCount">0</div>
<div class="label">Documents</div>
</div>
<div class="summary-card" data-tab="conditions" onclick="medDocsSwitchTab('conditions')">
<div class="count" id="summaryCondCount">0</div>
<div class="label">Conditions</div>
</div>
<div class="summary-card" data-tab="prescriptions" onclick="medDocsSwitchTab('prescriptions')">
<div class="count" id="summaryRxCount">0</div>
<div class="label">Prescriptions</div>
</div>
<div class="summary-card" data-tab="doctors" onclick="medDocsSwitchTab('doctors')">
<div class="count" id="summaryDrCount">0</div>
<div class="label">Doctors</div>
</div>
</div>
<!-- Main Tabs -->
<div class="main-tabs" id="mainTabs">
<button class="main-tab" data-tab="documents" onclick="medDocsSwitchTab('documents')">Documents</button>
<button class="main-tab" data-tab="conditions" onclick="medDocsSwitchTab('conditions')">Conditions</button>
<button class="main-tab" data-tab="prescriptions" onclick="medDocsSwitchTab('prescriptions')">Prescriptions</button>
<button class="main-tab active" data-tab="doctors" onclick="medDocsSwitchTab('doctors')">Doctors</button>
</div>
<!-- Tab Panels -->
<div class="tab-panels">
<!-- Documents Panel -->
<div class="tab-panel" id="panel-documents">
<div class="add-form-toggle">
<button class="btn btn-secondary" onclick="medDocsToggleAddForm('panel-documents')">+ Add Document</button>
<span class="doc-count" id="docCount"></span>
<button class="btn btn-secondary btn-sm" id="processAllBtn" style="display: none;" onclick="medDocsProcessAll()">Process All with AI</button>
</div>
<div class="add-form-collapsible">
<div class="upload-sub-tabs">
<button class="tab-btn active" data-tab="file">Upload File</button>
<button class="tab-btn" data-tab="note">Text Note</button>
</div>
<!-- File Upload -->
<div class="tab-content active" id="tab-file">
<div class="upload-area" id="dropZone">
<div class="upload-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="17 8 12 3 7 8"></polyline>
<line x1="12" y1="3" x2="12" y2="15"></line>
</svg>
</div>
<p>Drag & drop files here or <button class="link-btn" id="browseBtn">browse</button></p>
<p class="upload-hint">Any file type, up to 50MB</p>
<input type="file" id="fileInput" multiple style="display: none;" />
</div>
<div class="upload-fields">
<input type="text" id="fileTitle" placeholder="Title (optional)" class="form-input" />
<input type="text" id="fileDescription" placeholder="Description (optional)" class="form-input" />
<input type="date" id="fileDate" class="form-input" />
<select id="fileClassification" class="form-input">
<option value="">Classification (optional)</option>
<option value="receipt">Receipt</option>
<option value="lab_result">Lab Result</option>
<option value="prescription">Prescription</option>
<option value="imaging">Imaging</option>
<option value="dr_note">Doctor Note</option>
<option value="insurance">Insurance</option>
<option value="referral">Referral</option>
<option value="discharge">Discharge Summary</option>
<option value="recording">Recording/Transcript</option>
<option value="other">Other</option>
</select>
</div>
<div class="upload-queue" id="uploadQueue"></div>
</div>
<!-- Text Note -->
<div class="tab-content" id="tab-note">
<div class="note-form">
<input type="text" id="noteTitle" placeholder="Title *" class="form-input" />
<textarea id="noteDescription" placeholder="Note content..." class="form-input note-textarea" rows="6"></textarea>
<div class="note-fields">
<input type="date" id="noteDate" class="form-input" />
<select id="noteClassification" class="form-input">
<option value="">Classification (optional)</option>
<option value="receipt">Receipt</option>
<option value="lab_result">Lab Result</option>
<option value="prescription">Prescription</option>
<option value="dr_note">Doctor Note</option>
<option value="recording">Recording/Transcript</option>
<option value="other">Other</option>
</select>
</div>
<button id="saveNoteBtn" class="btn btn-primary">Save Note</button>
</div>
</div>
</div>
<div class="documents-list" id="documentsList"></div>
</div>
<!-- Conditions Panel -->
<div class="tab-panel" id="panel-conditions">
<div class="add-form-toggle">
<button class="btn btn-secondary" onclick="medDocsToggleAddForm('panel-conditions')">+ Add Condition</button>
</div>
<div class="add-form-collapsible">
<div class="inline-form-row">
<input type="text" id="newConditionName" placeholder="Condition name *" class="form-input" />
<input type="date" id="newConditionDate" class="form-input" title="Diagnosed date" />
<input type="text" id="newConditionNotes" placeholder="Notes" class="form-input" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddCondition()">Add</button>
</div>
</div>
<div class="conditions-list" id="conditionsList"></div>
</div>
<!-- Prescriptions Panel -->
<div class="tab-panel" id="panel-prescriptions">
<div class="add-form-toggle">
<button class="btn btn-secondary" onclick="medDocsToggleAddForm('panel-prescriptions')">+ Add Prescription</button>
</div>
<div class="add-form-collapsible">
<div class="inline-form-row">
<input type="text" id="newRxMedication" placeholder="Medication name *" class="form-input" />
<input type="text" id="newRxDosage" placeholder="Dosage" class="form-input" />
<input type="text" id="newRxFrequency" placeholder="Frequency" class="form-input" />
<select id="newRxDoctor" class="form-input">
<option value="">Doctor (optional)</option>
</select>
<input type="date" id="newRxStartDate" class="form-input" title="Start date" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddPrescription()">Add</button>
</div>
</div>
<div class="prescriptions-list" id="prescriptionsList"></div>
</div>
<!-- Doctors Panel -->
<div class="tab-panel active" id="panel-doctors">
<div class="add-form-toggle">
<button class="btn btn-secondary" onclick="medDocsToggleAddForm('panel-doctors')">+ Add Doctor</button>
</div>
<div class="add-form-collapsible">
<div class="inline-form-row">
<input type="text" id="newDoctorName" placeholder="Name *" class="form-input" />
<input type="text" id="newDoctorSpecialty" placeholder="Specialty" class="form-input" />
<input type="text" id="newDoctorPhone" placeholder="Phone" class="form-input" />
<input type="text" id="newDoctorAddress" placeholder="Address" class="form-input" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddDoctor()">Add</button>
</div>
</div>
<div class="doctors-list" id="doctorsList"></div>
</div>
</div>
</div>
</div>
</div>
@section Scripts {
<script src="~/js/medical-docs.js" asp-append-version="true"></script>
}
@@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Mvc;
namespace Media.JoshHeaps.Net.Pages
{
public class MedicalDocsModel(DbExecutor dbExecutor) : AuthenticatedPageModel
{
private readonly DbExecutor _dbExecutor = dbExecutor;
public async Task<IActionResult> OnGetAsync()
{
RequireAuthentication();
LoadUserSession();
var denied = await RequireRole("medical", _dbExecutor);
if (denied != null) return denied;
return Page();
}
}
}
+2
View File
@@ -17,6 +17,8 @@ builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<MediaService>(); builder.Services.AddScoped<MediaService>();
builder.Services.AddScoped<FolderService>(); builder.Services.AddScoped<FolderService>();
builder.Services.AddScoped<GraphService>(); builder.Services.AddScoped<GraphService>();
builder.Services.AddScoped<MedicalDocsService>();
builder.Services.AddSingleton<MedicalAiService>();
// Add session support // Add session support
builder.Services.AddDistributedMemoryCache(); builder.Services.AddDistributedMemoryCache();
@@ -0,0 +1,363 @@
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Media.JoshHeaps.Net.Services;
public class MedicalAiService
{
private readonly HttpClient _httpClient;
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<MedicalAiService> _logger;
private readonly string? _apiKey;
private const string HaikuModel = "claude-haiku-4-5-20251001";
private const string SonnetModel = "claude-sonnet-4-5-20250929";
public MedicalAiService(IConfiguration configuration, IServiceScopeFactory scopeFactory, ILogger<MedicalAiService> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
_apiKey = configuration["Anthropic:ApiKey"];
_httpClient = new HttpClient
{
BaseAddress = new Uri("https://api.anthropic.com")
};
_httpClient.DefaultRequestHeaders.Add("x-api-key", _apiKey ?? "");
_httpClient.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01");
}
public void EnqueueProcessing(long documentId)
{
if (string.IsNullOrEmpty(_apiKey))
{
_logger.LogWarning("Anthropic API key not configured, skipping AI processing for document {DocumentId}", documentId);
return;
}
_ = Task.Run(async () =>
{
try
{
using var scope = _scopeFactory.CreateScope();
var medicalDocsService = scope.ServiceProvider.GetRequiredService<MedicalDocsService>();
await ProcessDocumentAsync(documentId, medicalDocsService);
}
catch (Exception ex)
{
_logger.LogError(ex, "Background AI processing failed for document {DocumentId}", documentId);
}
});
}
private async Task ProcessDocumentAsync(long documentId, MedicalDocsService medicalDocsService)
{
_logger.LogInformation("Starting AI processing for document {DocumentId}", documentId);
var doc = await medicalDocsService.GetDocumentByIdAsync(documentId);
if (doc == null)
{
_logger.LogWarning("Document {DocumentId} not found for AI processing", documentId);
return;
}
var aiResponses = new Dictionary<string, object>();
// Step 1: Text extraction
string? extractedText = null;
if (doc.DocumentType == "note")
{
extractedText = doc.Description;
}
else if (doc.DocumentType == "file")
{
var fileData = await medicalDocsService.GetDecryptedDocumentDataAsync(documentId);
if (fileData != null && doc.MimeType != null)
{
extractedText = await ExtractTextAsync(fileData, doc.MimeType);
if (extractedText != null)
aiResponses["extraction"] = new { model = HaikuModel, text = extractedText };
}
}
if (string.IsNullOrWhiteSpace(extractedText))
{
_logger.LogWarning("No text could be extracted from document {DocumentId}", documentId);
extractedText = doc.Title ?? doc.FileName ?? "";
}
// Step 2: Classification + tagging (Haiku)
string? classification = doc.Classification;
List<string> tags = [];
try
{
var classResult = await ClassifyAndTagAsync(extractedText);
if (classResult != null)
{
classification = classResult.Classification ?? classification;
tags = classResult.Tags ?? [];
aiResponses["classification"] = classResult;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Classification failed for document {DocumentId}", documentId);
}
// Step 3: Structured data extraction (Sonnet)
StructuredExtractionResult? structuredData = null;
try
{
structuredData = await ExtractStructuredDataAsync(extractedText, classification ?? "other");
if (structuredData != null)
aiResponses["structured"] = structuredData;
}
catch (Exception ex)
{
_logger.LogError(ex, "Structured extraction failed for document {DocumentId}", documentId);
}
// Step 4: Persist results
var rawResponse = JsonSerializer.Serialize(aiResponses, JsonOpts);
await medicalDocsService.UpdateAiResultsAsync(documentId, extractedText, classification, rawResponse);
if (tags.Count > 0)
await medicalDocsService.AddTagsAsync(documentId, tags);
if (structuredData?.Costs is { Count: > 0 })
await medicalDocsService.AddCostsAsync(documentId, doc.PersonId, structuredData.Costs);
_logger.LogInformation("AI processing complete for document {DocumentId}: classification={Classification}, tags={TagCount}, costs={CostCount}",
documentId, classification, tags.Count, structuredData?.Costs?.Count ?? 0);
}
private async Task<string?> ExtractTextAsync(byte[] fileData, string mimeType)
{
_logger.LogInformation("Extracting text via Haiku vision, mimeType={MimeType}, size={Size}KB", mimeType, fileData.Length / 1024);
var isImage = mimeType.StartsWith("image/", StringComparison.OrdinalIgnoreCase);
var isPdf = mimeType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase);
if (!isImage && !isPdf)
{
_logger.LogInformation("Unsupported mime type {MimeType} for vision extraction", mimeType);
return null;
}
var base64Data = Convert.ToBase64String(fileData);
var mediaType = isPdf ? "application/pdf" : mimeType;
var sourceType = isPdf ? "base64" : "base64";
var content = new List<object>
{
new
{
type = "image",
source = new
{
type = sourceType,
media_type = mediaType,
data = base64Data
}
},
new
{
type = "text",
text = "Extract all text from this medical document. Include all visible text, numbers, dates, names, and amounts. Preserve the structure and formatting as much as possible. If the document is handwritten, do your best to transcribe it. Return only the extracted text, no commentary."
}
};
var response = await CallClaudeAsync(HaikuModel, content, "You are an OCR assistant. Extract text from medical documents accurately and completely.");
return response;
}
private async Task<ClassificationResult?> ClassifyAndTagAsync(string text)
{
_logger.LogInformation("Classifying and tagging via Haiku");
var truncatedText = text.Length > 4000 ? text[..4000] : text;
var content = new List<object>
{
new
{
type = "text",
text = $"Analyze this medical document text and classify it.\n\nDocument text:\n{truncatedText}"
}
};
var systemPrompt = @"You are a medical document classifier. Analyze the document text and return a JSON object with:
- ""classification"": one of: receipt, lab_result, prescription, imaging, dr_note, insurance, referral, discharge, recording, other
- ""tags"": array of relevant tag strings (lowercase, e.g. ""blood work"", ""cardiology"", ""annual physical"", ""copay"")
Return ONLY the JSON object, no other text.";
var response = await CallClaudeAsync(HaikuModel, content, systemPrompt);
if (response == null) return null;
// Parse JSON from response - handle potential markdown wrapping
var json = ExtractJson(response);
try
{
return JsonSerializer.Deserialize<ClassificationResult>(json, JsonOpts);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to parse classification response: {Response}", response);
return null;
}
}
private async Task<StructuredExtractionResult?> ExtractStructuredDataAsync(string text, string classification)
{
_logger.LogInformation("Extracting structured data via Sonnet, classification={Classification}", classification);
var truncatedText = text.Length > 6000 ? text[..6000] : text;
var content = new List<object>
{
new
{
type = "text",
text = $"Classification: {classification}\n\nDocument text:\n{truncatedText}"
}
};
var systemPrompt = @"You are a medical document data extractor. Extract financial and medical data from the document.
Return a JSON object with:
- ""costs"": array of cost objects, each with: ""amount"" (number), ""costType"" (string: copay, deductible, out_of_pocket, coinsurance, premium, total_charge, other), ""category"" (string: office_visit, lab, pharmacy, imaging, therapy, hospital, specialist, other), ""date"" (string, YYYY-MM-DD or null), ""description"" (string)
- ""doctorName"": string or null - the name of the doctor/provider mentioned
- ""prescriptionInfo"": object or null with ""medicationName"", ""dosage"", ""frequency"" fields
Only include fields you can confidently extract from the text. If no costs are found, return an empty costs array. Return ONLY the JSON object, no other text.";
var response = await CallClaudeAsync(SonnetModel, content, systemPrompt);
if (response == null) return null;
var json = ExtractJson(response);
try
{
return JsonSerializer.Deserialize<StructuredExtractionResult>(json, JsonOpts);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to parse structured extraction response: {Response}", response);
return null;
}
}
private async Task<string?> CallClaudeAsync(string model, List<object> content, string systemPrompt)
{
var requestBody = new
{
model,
max_tokens = 4096,
system = systemPrompt,
messages = new[]
{
new
{
role = "user",
content
}
}
};
var json = JsonSerializer.Serialize(requestBody, JsonOpts);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("/v1/messages", httpContent);
if (!response.IsSuccessStatusCode)
{
var errorBody = await response.Content.ReadAsStringAsync();
_logger.LogError("Claude API error {StatusCode}: {Error}", response.StatusCode, errorBody);
return null;
}
var responseJson = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<ClaudeResponse>(responseJson, JsonOpts);
var textBlock = result?.Content?.FirstOrDefault(c => c.Type == "text");
return textBlock?.Text;
}
private static string ExtractJson(string response)
{
// Handle markdown code blocks
var trimmed = response.Trim();
if (trimmed.StartsWith("```"))
{
var firstNewline = trimmed.IndexOf('\n');
if (firstNewline >= 0)
{
trimmed = trimmed[(firstNewline + 1)..];
var lastFence = trimmed.LastIndexOf("```");
if (lastFence >= 0)
trimmed = trimmed[..lastFence];
}
}
return trimmed.Trim();
}
private static readonly JsonSerializerOptions JsonOpts = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
// --- Response DTOs ---
private class ClaudeResponse
{
public List<ContentBlock>? Content { get; set; }
}
private class ContentBlock
{
public string Type { get; set; } = "";
public string? Text { get; set; }
}
public class ClassificationResult
{
public string? Classification { get; set; }
public List<string>? Tags { get; set; }
}
public class StructuredExtractionResult
{
public List<CostExtraction>? Costs { get; set; }
public string? DoctorName { get; set; }
public PrescriptionInfo? PrescriptionInfo { get; set; }
}
public class CostExtraction
{
public decimal Amount { get; set; }
public string? CostType { get; set; }
public string? Category { get; set; }
public string? Date { get; set; }
public string? Description { get; set; }
}
public class PrescriptionInfo
{
public string? MedicationName { get; set; }
public string? Dosage { get; set; }
public string? Frequency { get; set; }
}
}
@@ -0,0 +1,769 @@
using Media.JoshHeaps.Net.Models;
namespace Media.JoshHeaps.Net.Services;
public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment, EncryptionService encryption, ILogger<MedicalDocsService> logger)
{
// --- People ---
public async Task<List<MedicalPerson>> GetPeopleAsync()
{
try
{
return await db.ExecuteListReaderAsync(
"SELECT id, name, date_of_birth, notes, created_at, updated_at FROM app.medical_people ORDER BY name",
reader => new MedicalPerson
{
Id = reader.GetInt64(0),
Name = reader.GetString(1),
DateOfBirth = reader.IsDBNull(2) ? null : reader.GetDateTime(2),
Notes = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5)
});
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get medical people");
return [];
}
}
public async Task<MedicalPerson?> CreatePersonAsync(string name, DateTime? dateOfBirth = null, string? notes = null)
{
try
{
var now = DateTime.UtcNow;
return await db.ExecuteReaderAsync(
@"INSERT INTO app.medical_people (name, date_of_birth, notes, created_at, updated_at)
VALUES (@name, @dateOfBirth, @notes, @createdAt, @updatedAt)
RETURNING id, name, date_of_birth, notes, created_at, updated_at",
reader => new MedicalPerson
{
Id = reader.GetInt64(0),
Name = reader.GetString(1),
DateOfBirth = reader.IsDBNull(2) ? null : reader.GetDateTime(2),
Notes = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5)
},
new { name, dateOfBirth, notes, createdAt = now, updatedAt = now });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create medical person");
return null;
}
}
// --- Documents ---
public async Task<MedicalDocument?> SaveDocumentAsync(long personId, IFormFile file, string? title = null, string? description = null, DateTime? documentDate = null, string? classification = null)
{
string? tempFilePath = null;
string? encryptedFilePath = null;
try
{
var fileExtension = Path.GetExtension(file.FileName);
var uniqueFileName = $"{Guid.NewGuid()}{fileExtension}.enc";
var mediaFolder = Path.Combine(environment.ContentRootPath, "App_Data", "medical", personId.ToString());
Directory.CreateDirectory(mediaFolder);
tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
encryptedFilePath = Path.Combine(mediaFolder, uniqueFileName);
using (var fileStream = new FileStream(tempFilePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
await encryption.EncryptFileAsync(tempFilePath, encryptedFilePath);
File.Delete(tempFilePath);
tempFilePath = null;
var relativeFilePath = Path.Combine("App_Data", "medical", personId.ToString(), uniqueFileName);
var now = DateTime.UtcNow;
var doc = await db.ExecuteReaderAsync(
@"INSERT INTO app.medical_documents (person_id, document_type, file_name, file_path, file_size, mime_type, is_encrypted, title, description, document_date, classification, created_at, updated_at)
VALUES (@personId, 'file', @fileName, @filePath, @fileSize, @mimeType, true, @title, @description, @documentDate, @classification, @createdAt, @updatedAt)
RETURNING id, person_id, document_type, file_name, file_path, file_size, mime_type, is_encrypted, title, description, document_date, classification, extracted_text, ai_processed, ai_processed_at, doctor_id, created_at, updated_at",
MapDocument,
new
{
personId,
fileName = file.FileName,
filePath = relativeFilePath,
fileSize = file.Length,
mimeType = file.ContentType,
title,
description,
documentDate,
classification,
createdAt = now,
updatedAt = now
});
return doc;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to save medical document for person {PersonId}", personId);
if (tempFilePath != null && File.Exists(tempFilePath))
{
try { File.Delete(tempFilePath); } catch { }
}
if (encryptedFilePath != null && File.Exists(encryptedFilePath))
{
try { File.Delete(encryptedFilePath); } catch { }
}
return null;
}
}
public async Task<MedicalDocument?> SaveNoteAsync(long personId, string title, string description, DateTime? documentDate = null, string? classification = null)
{
try
{
var now = DateTime.UtcNow;
return await db.ExecuteReaderAsync(
@"INSERT INTO app.medical_documents (person_id, document_type, title, description, document_date, classification, is_encrypted, created_at, updated_at)
VALUES (@personId, 'note', @title, @description, @documentDate, @classification, false, @createdAt, @updatedAt)
RETURNING id, person_id, document_type, file_name, file_path, file_size, mime_type, is_encrypted, title, description, document_date, classification, extracted_text, ai_processed, ai_processed_at, doctor_id, created_at, updated_at",
MapDocument,
new { personId, title, description, documentDate, classification, createdAt = now, updatedAt = now });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to save medical note for person {PersonId}", personId);
return null;
}
}
public async Task<List<MedicalDocument>> GetDocumentsAsync(long? personId = null, int offset = 0, int limit = 50)
{
try
{
string query;
object parameters;
if (personId.HasValue)
{
query = @"SELECT id, person_id, document_type, file_name, file_path, file_size, mime_type, is_encrypted, title, description, document_date, classification, extracted_text, ai_processed, ai_processed_at, doctor_id, created_at, updated_at
FROM app.medical_documents
WHERE person_id = @personId
ORDER BY created_at DESC
OFFSET @offset LIMIT @limit";
parameters = new { personId = personId.Value, offset, limit };
}
else
{
query = @"SELECT id, person_id, document_type, file_name, file_path, file_size, mime_type, is_encrypted, title, description, document_date, classification, extracted_text, ai_processed, ai_processed_at, doctor_id, created_at, updated_at
FROM app.medical_documents
ORDER BY created_at DESC
OFFSET @offset LIMIT @limit";
parameters = new { offset, limit };
}
return await db.ExecuteListReaderAsync(query, MapDocument, parameters);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get medical documents");
return [];
}
}
public async Task<MedicalDocument?> GetDocumentByIdAsync(long documentId)
{
try
{
return await db.ExecuteReaderAsync(
@"SELECT id, person_id, document_type, file_name, file_path, file_size, mime_type, is_encrypted, title, description, document_date, classification, extracted_text, ai_processed, ai_processed_at, doctor_id, created_at, updated_at
FROM app.medical_documents
WHERE id = @documentId",
MapDocument,
new { documentId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get medical document {DocumentId}", documentId);
return null;
}
}
public async Task<byte[]?> GetDecryptedDocumentDataAsync(long documentId)
{
try
{
var doc = await GetDocumentByIdAsync(documentId);
if (doc == null || doc.DocumentType != "file" || doc.FilePath == null)
return null;
var fullPath = Path.Combine(environment.ContentRootPath, doc.FilePath);
if (!File.Exists(fullPath))
{
logger.LogError("Medical document file not found at {FilePath}", fullPath);
return null;
}
if (doc.IsEncrypted)
{
return await encryption.DecryptFileAsync(fullPath);
}
else
{
return await File.ReadAllBytesAsync(fullPath);
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get decrypted medical document data for {DocumentId}", documentId);
return null;
}
}
public async Task<bool> DeleteDocumentAsync(long documentId)
{
try
{
var doc = await GetDocumentByIdAsync(documentId);
if (doc == null) return false;
await db.ExecuteNonQueryAsync("DELETE FROM app.medical_documents WHERE id = @documentId", new { documentId });
if (doc.DocumentType == "file" && doc.FilePath != null)
{
var physicalPath = Path.Combine(environment.ContentRootPath, doc.FilePath);
if (File.Exists(physicalPath))
{
File.Delete(physicalPath);
}
}
return true;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to delete medical document {DocumentId}", documentId);
return false;
}
}
// --- Doctors ---
public async Task<List<MedicalDoctor>> GetDoctorsAsync()
{
try
{
return await db.ExecuteListReaderAsync(
"SELECT id, name, specialty, phone, address, notes, created_at, updated_at FROM app.medical_doctors ORDER BY name",
reader => new MedicalDoctor
{
Id = reader.GetInt64(0),
Name = reader.GetString(1),
Specialty = reader.IsDBNull(2) ? null : reader.GetString(2),
Phone = reader.IsDBNull(3) ? null : reader.GetString(3),
Address = reader.IsDBNull(4) ? null : reader.GetString(4),
Notes = reader.IsDBNull(5) ? null : reader.GetString(5),
CreatedAt = reader.GetDateTime(6),
UpdatedAt = reader.GetDateTime(7)
});
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get doctors");
return [];
}
}
public async Task<MedicalDoctor?> CreateDoctorAsync(string name, string? specialty = null, string? phone = null, string? address = null, string? notes = null)
{
try
{
var now = DateTime.UtcNow;
return await db.ExecuteReaderAsync(
@"INSERT INTO app.medical_doctors (name, specialty, phone, address, notes, created_at, updated_at)
VALUES (@name, @specialty, @phone, @address, @notes, @createdAt, @updatedAt)
RETURNING id, name, specialty, phone, address, notes, created_at, updated_at",
reader => new MedicalDoctor
{
Id = reader.GetInt64(0),
Name = reader.GetString(1),
Specialty = reader.IsDBNull(2) ? null : reader.GetString(2),
Phone = reader.IsDBNull(3) ? null : reader.GetString(3),
Address = reader.IsDBNull(4) ? null : reader.GetString(4),
Notes = reader.IsDBNull(5) ? null : reader.GetString(5),
CreatedAt = reader.GetDateTime(6),
UpdatedAt = reader.GetDateTime(7)
},
new { name, specialty, phone, address, notes, createdAt = now, updatedAt = now });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create doctor");
return null;
}
}
public async Task<bool> UpdateDoctorAsync(long id, string name, string? specialty = null, string? phone = null, string? address = null, string? notes = null)
{
try
{
var rows = await db.ExecuteNonQueryAsync(
@"UPDATE app.medical_doctors SET name = @name, specialty = @specialty, phone = @phone, address = @address, notes = @notes, updated_at = @updatedAt
WHERE id = @id",
new { id, name, specialty, phone, address, notes, updatedAt = DateTime.UtcNow });
return rows > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to update doctor {DoctorId}", id);
return false;
}
}
public async Task<bool> DeleteDoctorAsync(long id)
{
try
{
var rows = await db.ExecuteNonQueryAsync("DELETE FROM app.medical_doctors WHERE id = @id", new { id });
return rows > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to delete doctor {DoctorId}", id);
return false;
}
}
// --- Conditions ---
public async Task<List<MedicalCondition>> GetConditionsAsync(long personId)
{
try
{
return await db.ExecuteListReaderAsync(
"SELECT id, person_id, name, diagnosed_date, notes, is_active, created_at, updated_at FROM app.medical_conditions WHERE person_id = @personId ORDER BY name",
reader => new MedicalCondition
{
Id = reader.GetInt64(0),
PersonId = reader.GetInt64(1),
Name = reader.GetString(2),
DiagnosedDate = reader.IsDBNull(3) ? null : reader.GetDateTime(3),
Notes = reader.IsDBNull(4) ? null : reader.GetString(4),
IsActive = reader.GetBoolean(5),
CreatedAt = reader.GetDateTime(6),
UpdatedAt = reader.GetDateTime(7)
},
new { personId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get conditions for person {PersonId}", personId);
return [];
}
}
public async Task<MedicalCondition?> CreateConditionAsync(long personId, string name, DateTime? diagnosedDate = null, string? notes = null)
{
try
{
var now = DateTime.UtcNow;
return await db.ExecuteReaderAsync(
@"INSERT INTO app.medical_conditions (person_id, name, diagnosed_date, notes, created_at, updated_at)
VALUES (@personId, @name, @diagnosedDate, @notes, @createdAt, @updatedAt)
RETURNING id, person_id, name, diagnosed_date, notes, is_active, created_at, updated_at",
reader => new MedicalCondition
{
Id = reader.GetInt64(0),
PersonId = reader.GetInt64(1),
Name = reader.GetString(2),
DiagnosedDate = reader.IsDBNull(3) ? null : reader.GetDateTime(3),
Notes = reader.IsDBNull(4) ? null : reader.GetString(4),
IsActive = reader.GetBoolean(5),
CreatedAt = reader.GetDateTime(6),
UpdatedAt = reader.GetDateTime(7)
},
new { personId, name, diagnosedDate, notes, createdAt = now, updatedAt = now });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create condition for person {PersonId}", personId);
return null;
}
}
public async Task<bool> UpdateConditionAsync(long id, string name, DateTime? diagnosedDate = null, string? notes = null, bool isActive = true)
{
try
{
var rows = await db.ExecuteNonQueryAsync(
@"UPDATE app.medical_conditions SET name = @name, diagnosed_date = @diagnosedDate, notes = @notes, is_active = @isActive, updated_at = @updatedAt
WHERE id = @id",
new { id, name, diagnosedDate, notes, isActive, updatedAt = DateTime.UtcNow });
return rows > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to update condition {ConditionId}", id);
return false;
}
}
public async Task<bool> DeleteConditionAsync(long id)
{
try
{
var rows = await db.ExecuteNonQueryAsync("DELETE FROM app.medical_conditions WHERE id = @id", new { id });
return rows > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to delete condition {ConditionId}", id);
return false;
}
}
// --- Prescriptions ---
public async Task<List<MedicalPrescription>> GetPrescriptionsAsync(long personId)
{
try
{
return await db.ExecuteListReaderAsync(
@"SELECT p.id, p.person_id, p.doctor_id, p.medication_name, p.dosage, p.frequency, p.is_active, p.start_date, p.end_date, p.notes, p.created_at, p.updated_at,
d.name AS doctor_name,
(SELECT MAX(pk.pickup_date) FROM app.medical_prescription_pickups pk WHERE pk.prescription_id = p.id) AS last_pickup
FROM app.medical_prescriptions p
LEFT JOIN app.medical_doctors d ON p.doctor_id = d.id
WHERE p.person_id = @personId
ORDER BY p.medication_name",
reader => new MedicalPrescription
{
Id = reader.GetInt64(0),
PersonId = reader.GetInt64(1),
DoctorId = reader.IsDBNull(2) ? null : reader.GetInt64(2),
MedicationName = reader.GetString(3),
Dosage = reader.IsDBNull(4) ? null : reader.GetString(4),
Frequency = reader.IsDBNull(5) ? null : reader.GetString(5),
IsActive = reader.GetBoolean(6),
StartDate = reader.IsDBNull(7) ? null : reader.GetDateTime(7),
EndDate = reader.IsDBNull(8) ? null : reader.GetDateTime(8),
Notes = reader.IsDBNull(9) ? null : reader.GetString(9),
CreatedAt = reader.GetDateTime(10),
UpdatedAt = reader.GetDateTime(11),
DoctorName = reader.IsDBNull(12) ? null : reader.GetString(12),
LastPickupDate = reader.IsDBNull(13) ? null : reader.GetDateTime(13)
},
new { personId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get prescriptions for person {PersonId}", personId);
return [];
}
}
public async Task<MedicalPrescription?> CreatePrescriptionAsync(long personId, string medicationName, string? dosage = null, string? frequency = null, long? doctorId = null, DateTime? startDate = null, string? notes = null)
{
try
{
var now = DateTime.UtcNow;
return await db.ExecuteReaderAsync(
@"INSERT INTO app.medical_prescriptions (person_id, doctor_id, medication_name, dosage, frequency, start_date, notes, created_at, updated_at)
VALUES (@personId, @doctorId, @medicationName, @dosage, @frequency, @startDate, @notes, @createdAt, @updatedAt)
RETURNING id, person_id, doctor_id, medication_name, dosage, frequency, is_active, start_date, end_date, notes, created_at, updated_at",
reader => new MedicalPrescription
{
Id = reader.GetInt64(0),
PersonId = reader.GetInt64(1),
DoctorId = reader.IsDBNull(2) ? null : reader.GetInt64(2),
MedicationName = reader.GetString(3),
Dosage = reader.IsDBNull(4) ? null : reader.GetString(4),
Frequency = reader.IsDBNull(5) ? null : reader.GetString(5),
IsActive = reader.GetBoolean(6),
StartDate = reader.IsDBNull(7) ? null : reader.GetDateTime(7),
EndDate = reader.IsDBNull(8) ? null : reader.GetDateTime(8),
Notes = reader.IsDBNull(9) ? null : reader.GetString(9),
CreatedAt = reader.GetDateTime(10),
UpdatedAt = reader.GetDateTime(11)
},
new { personId, doctorId, medicationName, dosage, frequency, startDate, notes, createdAt = now, updatedAt = now });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create prescription for person {PersonId}", personId);
return null;
}
}
public async Task<bool> UpdatePrescriptionAsync(long id, string medicationName, string? dosage = null, string? frequency = null, long? doctorId = null, DateTime? startDate = null, DateTime? endDate = null, string? notes = null, bool isActive = true)
{
try
{
var rows = await db.ExecuteNonQueryAsync(
@"UPDATE app.medical_prescriptions SET medication_name = @medicationName, dosage = @dosage, frequency = @frequency, doctor_id = @doctorId, start_date = @startDate, end_date = @endDate, notes = @notes, is_active = @isActive, updated_at = @updatedAt
WHERE id = @id",
new { id, medicationName, dosage, frequency, doctorId, startDate, endDate, notes, isActive, updatedAt = DateTime.UtcNow });
return rows > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to update prescription {PrescriptionId}", id);
return false;
}
}
public async Task<bool> DeletePrescriptionAsync(long id)
{
try
{
var rows = await db.ExecuteNonQueryAsync("DELETE FROM app.medical_prescriptions WHERE id = @id", new { id });
return rows > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to delete prescription {PrescriptionId}", id);
return false;
}
}
// --- Prescription Pickups ---
public async Task<List<MedicalPrescriptionPickup>> GetPickupsAsync(long prescriptionId)
{
try
{
return await db.ExecuteListReaderAsync(
"SELECT id, prescription_id, document_id, pickup_date, quantity, pharmacy, cost, notes, created_at FROM app.medical_prescription_pickups WHERE prescription_id = @prescriptionId ORDER BY pickup_date DESC",
reader => new MedicalPrescriptionPickup
{
Id = reader.GetInt64(0),
PrescriptionId = reader.GetInt64(1),
DocumentId = reader.IsDBNull(2) ? null : reader.GetInt64(2),
PickupDate = reader.GetDateTime(3),
Quantity = reader.IsDBNull(4) ? null : reader.GetString(4),
Pharmacy = reader.IsDBNull(5) ? null : reader.GetString(5),
Cost = reader.IsDBNull(6) ? null : reader.GetDecimal(6),
Notes = reader.IsDBNull(7) ? null : reader.GetString(7),
CreatedAt = reader.GetDateTime(8)
},
new { prescriptionId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get pickups for prescription {PrescriptionId}", prescriptionId);
return [];
}
}
public async Task<MedicalPrescriptionPickup?> CreatePickupAsync(long prescriptionId, DateTime pickupDate, string? quantity = null, string? pharmacy = null, decimal? cost = null, string? notes = null)
{
try
{
return await db.ExecuteReaderAsync(
@"INSERT INTO app.medical_prescription_pickups (prescription_id, pickup_date, quantity, pharmacy, cost, notes, created_at)
VALUES (@prescriptionId, @pickupDate, @quantity, @pharmacy, @cost, @notes, @createdAt)
RETURNING id, prescription_id, document_id, pickup_date, quantity, pharmacy, cost, notes, created_at",
reader => new MedicalPrescriptionPickup
{
Id = reader.GetInt64(0),
PrescriptionId = reader.GetInt64(1),
DocumentId = reader.IsDBNull(2) ? null : reader.GetInt64(2),
PickupDate = reader.GetDateTime(3),
Quantity = reader.IsDBNull(4) ? null : reader.GetString(4),
Pharmacy = reader.IsDBNull(5) ? null : reader.GetString(5),
Cost = reader.IsDBNull(6) ? null : reader.GetDecimal(6),
Notes = reader.IsDBNull(7) ? null : reader.GetString(7),
CreatedAt = reader.GetDateTime(8)
},
new { prescriptionId, pickupDate, quantity, pharmacy, cost, notes, createdAt = DateTime.UtcNow });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create pickup for prescription {PrescriptionId}", prescriptionId);
return null;
}
}
public async Task<bool> DeletePickupAsync(long id)
{
try
{
var rows = await db.ExecuteNonQueryAsync("DELETE FROM app.medical_prescription_pickups WHERE id = @id", new { id });
return rows > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to delete pickup {PickupId}", id);
return false;
}
}
// --- AI Processing Helpers ---
public async Task UpdateAiResultsAsync(long docId, string? extractedText, string? classification, string aiRawResponse)
{
try
{
await db.ExecuteNonQueryAsync(
@"UPDATE app.medical_documents
SET extracted_text = @extractedText,
classification = @classification,
ai_processed = true,
ai_processed_at = @processedAt,
ai_raw_response = @aiRawResponse::jsonb,
updated_at = @updatedAt
WHERE id = @docId",
new
{
docId,
extractedText,
classification,
aiRawResponse,
processedAt = DateTime.UtcNow,
updatedAt = DateTime.UtcNow
});
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to update AI results for document {DocumentId}", docId);
}
}
public async Task AddTagsAsync(long docId, List<string> tagNames, string source = "ai")
{
try
{
foreach (var tagName in tagNames)
{
var normalizedName = tagName.Trim().ToLowerInvariant();
if (string.IsNullOrEmpty(normalizedName)) continue;
// Upsert tag
var tagId = await db.ExecuteAsync<long>(
@"INSERT INTO app.medical_tags (name) VALUES (@name)
ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name
RETURNING id",
new { name = normalizedName });
// Link tag to document
await db.ExecuteNonQueryAsync(
@"INSERT INTO app.medical_document_tags (document_id, tag_id, source)
VALUES (@documentId, @tagId, @source)
ON CONFLICT (document_id, tag_id) DO NOTHING",
new { documentId = docId, tagId, source });
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to add tags for document {DocumentId}", docId);
}
}
public async Task AddCostsAsync(long docId, long personId, List<MedicalAiService.CostExtraction> costs)
{
try
{
foreach (var cost in costs)
{
if (cost.Amount <= 0) continue;
DateTime? costDate = null;
if (!string.IsNullOrEmpty(cost.Date) && DateTime.TryParse(cost.Date, out var parsed))
costDate = parsed;
await db.ExecuteNonQueryAsync(
@"INSERT INTO app.medical_document_costs (document_id, person_id, amount, cost_type, category, cost_date, description, source)
VALUES (@documentId, @personId, @amount, @costType, @category, @costDate, @description, 'ai')",
new
{
documentId = docId,
personId,
amount = cost.Amount,
costType = cost.CostType,
category = cost.Category,
costDate,
description = cost.Description
});
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to add costs for document {DocumentId}", docId);
}
}
public async Task<List<long>> GetUnprocessedDocumentIdsAsync()
{
try
{
return await db.ExecuteListReaderAsync(
"SELECT id FROM app.medical_documents WHERE ai_processed = false ORDER BY created_at",
reader => reader.GetInt64(0));
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get unprocessed document IDs");
return [];
}
}
public async Task<List<MedicalTag>> GetDocumentTagsAsync(long documentId)
{
try
{
return await db.ExecuteListReaderAsync(
@"SELECT t.id, t.name, t.created_at
FROM app.medical_tags t
JOIN app.medical_document_tags dt ON dt.tag_id = t.id
WHERE dt.document_id = @documentId
ORDER BY t.name",
reader => new MedicalTag
{
Id = reader.GetInt64(0),
Name = reader.GetString(1),
CreatedAt = reader.GetDateTime(2)
},
new { documentId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get tags for document {DocumentId}", documentId);
return [];
}
}
private static MedicalDocument MapDocument(Npgsql.NpgsqlDataReader reader)
{
return new MedicalDocument
{
Id = reader.GetInt64(0),
PersonId = reader.GetInt64(1),
DocumentType = reader.GetString(2),
FileName = reader.IsDBNull(3) ? null : reader.GetString(3),
FilePath = reader.IsDBNull(4) ? null : reader.GetString(4),
FileSize = reader.IsDBNull(5) ? null : reader.GetInt64(5),
MimeType = reader.IsDBNull(6) ? null : reader.GetString(6),
IsEncrypted = reader.GetBoolean(7),
Title = reader.IsDBNull(8) ? null : reader.GetString(8),
Description = reader.IsDBNull(9) ? null : reader.GetString(9),
DocumentDate = reader.IsDBNull(10) ? null : reader.GetDateTime(10),
Classification = reader.IsDBNull(11) ? null : reader.GetString(11),
ExtractedText = reader.IsDBNull(12) ? null : reader.GetString(12),
AiProcessed = reader.GetBoolean(13),
AiProcessedAt = reader.IsDBNull(14) ? null : reader.GetDateTime(14),
DoctorId = reader.IsDBNull(15) ? null : reader.GetInt64(15),
CreatedAt = reader.GetDateTime(16),
UpdatedAt = reader.GetDateTime(17)
};
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,966 @@
(function () {
const API = '/api/medical-docs';
let people = [];
let doctors = [];
let selectedPersonId = null;
let activeTab = 'doctors';
document.addEventListener('DOMContentLoaded', init);
async function init() {
await loadPeople();
await loadDoctors();
// Add person
document.getElementById('addPersonBtn').addEventListener('click', addPerson);
document.getElementById('newPersonName').addEventListener('keydown', (e) => {
if (e.key === 'Enter') addPerson();
});
// Upload sub-tabs (file vs note)
document.querySelectorAll('.upload-sub-tabs .tab-btn').forEach(btn => {
btn.addEventListener('click', () => switchUploadTab(btn.dataset.tab));
});
// File upload
document.getElementById('browseBtn').addEventListener('click', () => {
document.getElementById('fileInput').click();
});
document.getElementById('fileInput').addEventListener('change', handleFileSelect);
// Drag and drop
const dropZone = document.getElementById('dropZone');
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('drag-over');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('drag-over');
if (e.dataTransfer.files.length > 0) {
uploadFiles(e.dataTransfer.files);
}
});
// Save note
document.getElementById('saveNoteBtn').addEventListener('click', saveNote);
// Default state: only Doctors tab visible, no summary cards
switchMainTab('doctors');
updateTabStates();
}
// --- Main Tab Switching ---
function switchMainTab(tabName) {
// Person-scoped tabs require a person selection
if (!selectedPersonId && tabName !== 'doctors') return;
activeTab = tabName;
// Update tab buttons
document.querySelectorAll('.main-tab').forEach(btn => {
if (btn.dataset.tab === tabName) {
btn.classList.add('active');
} else {
btn.classList.remove('active');
}
});
// Update tab panels
document.querySelectorAll('.tab-panel').forEach(panel => {
if (panel.id === 'panel-' + tabName) {
panel.classList.add('active');
} else {
panel.classList.remove('active');
}
});
// Update summary card highlights
document.querySelectorAll('.summary-card').forEach(card => {
if (card.dataset.tab === tabName) {
card.classList.add('active');
} else {
card.classList.remove('active');
}
});
}
function updateTabStates() {
var personTabs = ['documents', 'conditions', 'prescriptions'];
personTabs.forEach(function (tab) {
var btn = document.querySelector('.main-tab[data-tab="' + tab + '"]');
if (btn) {
if (selectedPersonId) {
btn.classList.remove('disabled');
} else {
btn.classList.add('disabled');
}
}
});
}
// --- Upload Sub-Tab Switching (file vs note) ---
function switchUploadTab(tab) {
document.querySelectorAll('.upload-sub-tabs .tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.add-form-collapsible .tab-content').forEach(c => c.classList.remove('active'));
document.querySelector(`.upload-sub-tabs .tab-btn[data-tab="${tab}"]`).classList.add('active');
document.getElementById(`tab-${tab}`).classList.add('active');
}
// --- Summary Cards ---
function updateSummaryCount(id, count) {
const el = document.getElementById(id);
if (el) el.textContent = count;
}
// --- Collapsible Add Forms ---
function toggleAddForm(panelId) {
const panel = document.getElementById(panelId);
if (!panel) return;
const collapsible = panel.querySelector('.add-form-collapsible');
if (collapsible) {
collapsible.classList.toggle('open');
}
}
// --- People ---
async function loadPeople() {
const res = await fetch(`${API}/people`);
if (!res.ok) return;
people = await res.json();
renderPeople();
}
function renderPeople() {
const container = document.getElementById('peopleList');
container.innerHTML = people.map(p =>
`<button class="person-pill ${p.id === selectedPersonId ? 'active' : ''}" onclick="medDocsSelectPerson(${p.id})">${escapeHtml(p.name)}</button>`
).join('');
}
async function addPerson() {
const input = document.getElementById('newPersonName');
const name = input.value.trim();
if (!name) return;
const res = await fetch(`${API}/people`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name })
});
if (!res.ok) {
const err = await res.json();
alert(err.error || 'Failed to add person');
return;
}
input.value = '';
const person = await res.json();
await loadPeople();
selectPerson(person.id);
}
function selectPerson(personId) {
selectedPersonId = personId;
renderPeople();
// Show summary cards and enable person-scoped tabs
document.getElementById('summaryCards').style.display = '';
updateTabStates();
// Load data for this person
loadDocuments();
loadConditions();
loadPrescriptions();
// Switch to Documents tab by default
switchMainTab('documents');
}
// --- File Upload ---
function handleFileSelect(e) {
if (e.target.files.length > 0) {
uploadFiles(e.target.files);
}
}
async function uploadFiles(files) {
const queue = document.getElementById('uploadQueue');
for (const file of files) {
const item = document.createElement('div');
item.className = 'upload-item';
item.innerHTML = `
<div class="file-info">
<span class="file-name">${escapeHtml(file.name)}</span>
<span class="file-size">${formatSize(file.size)}</span>
</div>
<span class="upload-status uploading">Uploading...</span>
`;
queue.appendChild(item);
const statusEl = item.querySelector('.upload-status');
try {
const formData = new FormData();
formData.append('file', file);
formData.append('personId', selectedPersonId);
const title = document.getElementById('fileTitle').value.trim();
const description = document.getElementById('fileDescription').value.trim();
const date = document.getElementById('fileDate').value;
const classification = document.getElementById('fileClassification').value;
if (title) formData.append('title', title);
if (description) formData.append('description', description);
if (date) formData.append('documentDate', date);
if (classification) formData.append('classification', classification);
const res = await fetch(`${API}/documents/upload`, {
method: 'POST',
body: formData
});
if (res.ok) {
statusEl.textContent = 'Done';
statusEl.className = 'upload-status done';
} else {
const err = await res.json().catch(() => ({}));
statusEl.textContent = err.error || 'Failed';
statusEl.className = 'upload-status error';
}
} catch {
statusEl.textContent = 'Error';
statusEl.className = 'upload-status error';
}
}
// Clear fields after upload batch
document.getElementById('fileTitle').value = '';
document.getElementById('fileDescription').value = '';
document.getElementById('fileDate').value = '';
document.getElementById('fileClassification').value = '';
document.getElementById('fileInput').value = '';
await loadDocuments();
}
// --- Notes ---
async function saveNote() {
const title = document.getElementById('noteTitle').value.trim();
const description = document.getElementById('noteDescription').value.trim();
const date = document.getElementById('noteDate').value || null;
const classification = document.getElementById('noteClassification').value || null;
if (!title) {
alert('Title is required');
return;
}
const res = await fetch(`${API}/documents/note`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
personId: selectedPersonId,
title,
description,
documentDate: date,
classification
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to save note');
return;
}
document.getElementById('noteTitle').value = '';
document.getElementById('noteDescription').value = '';
document.getElementById('noteDate').value = '';
document.getElementById('noteClassification').value = '';
await loadDocuments();
}
// --- Documents ---
async function loadDocuments() {
if (!selectedPersonId) return;
const res = await fetch(`${API}/documents?personId=${selectedPersonId}`);
if (!res.ok) return;
const docs = await res.json();
renderDocuments(docs);
updateSummaryCount('summaryDocCount', docs.length);
}
function renderDocuments(docs) {
const container = document.getElementById('documentsList');
const countEl = document.getElementById('docCount');
countEl.textContent = `${docs.length} document${docs.length !== 1 ? 's' : ''}`;
// Show/hide Process All button based on unprocessed docs
const unprocessedCount = docs.filter(d => !d.aiProcessed).length;
const processAllBtn = document.getElementById('processAllBtn');
if (processAllBtn) {
processAllBtn.style.display = unprocessedCount > 0 ? '' : 'none';
processAllBtn.textContent = `Process All with AI (${unprocessedCount})`;
}
if (docs.length === 0) {
container.innerHTML = '<div class="empty-state">No documents yet. Upload a file or create a note above.</div>';
return;
}
container.innerHTML = docs.map(doc => {
const icon = getDocIcon(doc);
const displayTitle = doc.title || doc.fileName || 'Untitled';
const meta = [];
if (doc.documentDate) {
meta.push(formatDate(doc.documentDate));
}
if (doc.documentType === 'file' && doc.fileSize) {
meta.push(formatSize(doc.fileSize));
}
if (doc.documentType === 'note') {
meta.push('Note');
}
const classificationBadge = doc.classification
? `<span class="doc-classification">${escapeHtml(formatClassification(doc.classification))}</span>`
: '';
const aiStatusBadge = getAiStatusBadge(doc);
const downloadBtn = doc.documentType === 'file'
? `<button onclick="medDocsDownload(${doc.id}, '${escapeAttr(doc.fileName || 'download')}')">Download</button>`
: '';
const processBtn = !doc.aiProcessed
? `<button class="ai-process-btn" onclick="medDocsProcess(${doc.id}, this)">Process AI</button>`
: '';
return `<div class="doc-item">
<div class="doc-type-icon">${icon}</div>
<div class="doc-info">
<div class="doc-title">${escapeHtml(displayTitle)}</div>
<div class="doc-meta">
<span>${meta.join(' &middot; ')}</span>
${classificationBadge}
${aiStatusBadge}
</div>
${doc.description && doc.documentType === 'note' ? `<div class="doc-meta" style="margin-top:4px">${escapeHtml(truncate(doc.description, 150))}</div>` : ''}
</div>
<div class="doc-actions">
${processBtn}
${downloadBtn}
<button class="delete-btn" onclick="medDocsDelete(${doc.id})">Delete</button>
</div>
</div>`;
}).join('');
}
function getAiStatusBadge(doc) {
if (doc.aiProcessed) {
return '<span class="ai-badge ai-done" title="AI processed">AI</span>';
}
return '<span class="ai-badge ai-pending" title="Not yet processed">No AI</span>';
}
// --- Doctors ---
async function loadDoctors() {
const res = await fetch(`${API}/doctors`);
if (!res.ok) return;
doctors = await res.json();
renderDoctors();
populateDoctorDropdown();
updateSummaryCount('summaryDrCount', doctors.length);
}
function renderDoctors() {
const container = document.getElementById('doctorsList');
if (doctors.length === 0) {
container.innerHTML = '<div class="empty-state">No doctors added yet.</div>';
return;
}
container.innerHTML = doctors.map(doc => {
const details = [doc.specialty, doc.phone, doc.address].filter(Boolean);
return `<div class="doctor-card" id="doctor-${doc.id}">
<div class="doctor-info">
<div class="doctor-name">${escapeHtml(doc.name)}</div>
<div class="doctor-details">${details.map(d => escapeHtml(d)).join(' &middot; ')}</div>
${doc.notes ? `<div class="doctor-notes">${escapeHtml(doc.notes)}</div>` : ''}
</div>
<div class="doc-actions">
<button onclick="medDocsEditDoctor(${doc.id})">Edit</button>
<button class="delete-btn" onclick="medDocsDeleteDoctor(${doc.id})">Delete</button>
</div>
</div>`;
}).join('');
}
function populateDoctorDropdown() {
const select = document.getElementById('newRxDoctor');
if (!select) return;
const currentVal = select.value;
select.innerHTML = '<option value="">Doctor (optional)</option>' +
doctors.map(d => `<option value="${d.id}">${escapeHtml(d.name)}</option>`).join('');
select.value = currentVal;
}
async function addDoctor() {
const name = document.getElementById('newDoctorName').value.trim();
if (!name) return;
const res = await fetch(`${API}/doctors`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
specialty: document.getElementById('newDoctorSpecialty').value.trim() || null,
phone: document.getElementById('newDoctorPhone').value.trim() || null,
address: document.getElementById('newDoctorAddress').value.trim() || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to add doctor');
return;
}
document.getElementById('newDoctorName').value = '';
document.getElementById('newDoctorSpecialty').value = '';
document.getElementById('newDoctorPhone').value = '';
document.getElementById('newDoctorAddress').value = '';
await loadDoctors();
}
async function deleteDoctor(id) {
if (!confirm('Delete this doctor?')) return;
const res = await fetch(`${API}/doctors/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await loadDoctors();
}
async function editDoctor(id) {
const doc = doctors.find(d => d.id === id);
if (!doc) return;
const card = document.getElementById(`doctor-${id}`);
if (!card) return;
card.innerHTML = `<div class="inline-edit-form">
<div class="inline-form-row">
<input type="text" id="editDoctorName-${id}" value="${escapeAttr(doc.name)}" class="form-input" placeholder="Name *" />
<input type="text" id="editDoctorSpecialty-${id}" value="${escapeAttr(doc.specialty || '')}" class="form-input" placeholder="Specialty" />
<input type="text" id="editDoctorPhone-${id}" value="${escapeAttr(doc.phone || '')}" class="form-input" placeholder="Phone" />
<input type="text" id="editDoctorAddress-${id}" value="${escapeAttr(doc.address || '')}" class="form-input" placeholder="Address" />
<button class="btn btn-primary btn-sm" onclick="medDocsSaveDoctor(${id})">Save</button>
<button class="btn btn-secondary btn-sm" onclick="medDocsCancelEditDoctor()">Cancel</button>
</div>
</div>`;
}
async function saveDoctor(id) {
const name = document.getElementById(`editDoctorName-${id}`).value.trim();
if (!name) return;
const res = await fetch(`${API}/doctors/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
specialty: document.getElementById(`editDoctorSpecialty-${id}`).value.trim() || null,
phone: document.getElementById(`editDoctorPhone-${id}`).value.trim() || null,
address: document.getElementById(`editDoctorAddress-${id}`).value.trim() || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to update doctor');
return;
}
await loadDoctors();
}
// --- Conditions ---
async function loadConditions() {
if (!selectedPersonId) return;
const res = await fetch(`${API}/conditions?personId=${selectedPersonId}`);
if (!res.ok) return;
const conditions = await res.json();
renderConditions(conditions);
updateSummaryCount('summaryCondCount', conditions.length);
}
function renderConditions(conditions) {
const container = document.getElementById('conditionsList');
if (conditions.length === 0) {
container.innerHTML = '<div class="empty-state">No conditions tracked yet.</div>';
return;
}
container.innerHTML = conditions.map(c => {
const meta = [];
if (c.diagnosedDate) meta.push('Diagnosed: ' + formatDate(c.diagnosedDate));
const statusBadge = c.isActive
? '<span class="badge-active">Active</span>'
: '<span class="badge-inactive">Inactive</span>';
return `<div class="condition-item" id="condition-${c.id}">
<div class="condition-info">
<div class="condition-name">${escapeHtml(c.name)} ${statusBadge}</div>
${meta.length ? `<div class="condition-meta">${meta.join(' &middot; ')}</div>` : ''}
${c.notes ? `<div class="condition-meta">${escapeHtml(c.notes)}</div>` : ''}
</div>
<div class="doc-actions">
<button onclick="medDocsToggleCondition(${c.id}, ${!c.isActive})">${c.isActive ? 'Deactivate' : 'Activate'}</button>
<button class="delete-btn" onclick="medDocsDeleteCondition(${c.id})">Delete</button>
</div>
</div>`;
}).join('');
}
async function addCondition() {
const name = document.getElementById('newConditionName').value.trim();
if (!name) return;
const res = await fetch(`${API}/conditions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
personId: selectedPersonId,
name,
diagnosedDate: document.getElementById('newConditionDate').value || null,
notes: document.getElementById('newConditionNotes').value.trim() || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to add condition');
return;
}
document.getElementById('newConditionName').value = '';
document.getElementById('newConditionDate').value = '';
document.getElementById('newConditionNotes').value = '';
await loadConditions();
}
async function toggleConditionActive(id, isActive) {
const res = await fetch(`${API}/conditions?personId=${selectedPersonId}`);
if (!res.ok) return;
const conditions = await res.json();
const condition = conditions.find(c => c.id === id);
if (!condition) return;
const updateRes = await fetch(`${API}/conditions/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: condition.name,
diagnosedDate: condition.diagnosedDate,
notes: condition.notes,
isActive
})
});
if (!updateRes.ok) {
const err = await updateRes.json().catch(() => ({}));
alert(err.error || 'Failed to update condition');
return;
}
await loadConditions();
}
async function deleteCondition(id) {
if (!confirm('Delete this condition?')) return;
const res = await fetch(`${API}/conditions/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await loadConditions();
}
// --- Prescriptions ---
async function loadPrescriptions() {
if (!selectedPersonId) return;
const res = await fetch(`${API}/prescriptions?personId=${selectedPersonId}`);
if (!res.ok) return;
const prescriptions = await res.json();
renderPrescriptions(prescriptions);
updateSummaryCount('summaryRxCount', prescriptions.length);
}
function renderPrescriptions(prescriptions) {
const container = document.getElementById('prescriptionsList');
if (prescriptions.length === 0) {
container.innerHTML = '<div class="empty-state">No prescriptions tracked yet.</div>';
return;
}
container.innerHTML = prescriptions.map(rx => {
const meta = [];
if (rx.dosage) meta.push(rx.dosage);
if (rx.frequency) meta.push(rx.frequency);
if (rx.doctorName) meta.push('Dr. ' + rx.doctorName);
if (rx.startDate) meta.push('Started: ' + formatDate(rx.startDate));
const lastPickup = rx.lastPickupDate ? formatDate(rx.lastPickupDate) : 'None';
const statusBadge = rx.isActive
? '<span class="badge-active">Active</span>'
: '<span class="badge-inactive">Inactive</span>';
return `<div class="prescription-item" id="rx-${rx.id}">
<div class="prescription-header" onclick="medDocsTogglePickups(${rx.id})">
<div class="prescription-info">
<div class="prescription-name">
<span class="expand-btn" id="expand-${rx.id}">&#9654;</span>
${escapeHtml(rx.medicationName)} ${statusBadge}
</div>
<div class="prescription-meta">${meta.map(m => escapeHtml(m)).join(' &middot; ')}</div>
<div class="prescription-meta">Last pickup: ${escapeHtml(lastPickup)}</div>
</div>
<div class="doc-actions" onclick="event.stopPropagation()">
<button class="delete-btn" onclick="medDocsDeletePrescription(${rx.id})">Delete</button>
</div>
</div>
<div class="pickup-section" id="pickups-${rx.id}" style="display: none;">
<div class="pickup-form">
<div class="inline-form-row">
<input type="date" id="pickupDate-${rx.id}" class="form-input" title="Pickup date" />
<input type="text" id="pickupQty-${rx.id}" placeholder="Quantity" class="form-input" />
<input type="text" id="pickupPharmacy-${rx.id}" placeholder="Pharmacy" class="form-input" />
<input type="number" id="pickupCost-${rx.id}" placeholder="Cost" class="form-input" step="0.01" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddPickup(${rx.id})">Log Pickup</button>
</div>
</div>
<div class="pickup-list" id="pickupList-${rx.id}"></div>
</div>
</div>`;
}).join('');
}
async function addPrescription() {
const medication = document.getElementById('newRxMedication').value.trim();
if (!medication) return;
const doctorId = document.getElementById('newRxDoctor').value;
const res = await fetch(`${API}/prescriptions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
personId: selectedPersonId,
medicationName: medication,
dosage: document.getElementById('newRxDosage').value.trim() || null,
frequency: document.getElementById('newRxFrequency').value.trim() || null,
doctorId: doctorId ? parseInt(doctorId) : null,
startDate: document.getElementById('newRxStartDate').value || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to add prescription');
return;
}
document.getElementById('newRxMedication').value = '';
document.getElementById('newRxDosage').value = '';
document.getElementById('newRxFrequency').value = '';
document.getElementById('newRxDoctor').value = '';
document.getElementById('newRxStartDate').value = '';
await loadPrescriptions();
}
async function deletePrescription(id) {
if (!confirm('Delete this prescription and all its pickup history?')) return;
const res = await fetch(`${API}/prescriptions/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await loadPrescriptions();
}
async function togglePickups(rxId) {
const section = document.getElementById(`pickups-${rxId}`);
const expandBtn = document.getElementById(`expand-${rxId}`);
if (section.style.display === 'none') {
section.style.display = '';
expandBtn.innerHTML = '&#9660;';
await loadPickups(rxId);
} else {
section.style.display = 'none';
expandBtn.innerHTML = '&#9654;';
}
}
async function loadPickups(rxId) {
const res = await fetch(`${API}/prescriptions/${rxId}/pickups`);
if (!res.ok) return;
const pickups = await res.json();
const container = document.getElementById(`pickupList-${rxId}`);
if (pickups.length === 0) {
container.innerHTML = '<div class="empty-state" style="padding:12px">No pickups logged.</div>';
return;
}
container.innerHTML = pickups.map(p => {
const meta = [];
if (p.quantity) meta.push(p.quantity);
if (p.pharmacy) meta.push(p.pharmacy);
if (p.cost != null) meta.push('$' + parseFloat(p.cost).toFixed(2));
return `<div class="pickup-item">
<div class="pickup-info">
<span class="pickup-date">${formatDate(p.pickupDate)}</span>
${meta.length ? `<span class="pickup-meta">${meta.map(m => escapeHtml(m)).join(' &middot; ')}</span>` : ''}
${p.notes ? `<span class="pickup-meta">${escapeHtml(p.notes)}</span>` : ''}
</div>
<button class="delete-btn btn-sm" onclick="medDocsDeletePickup(${p.id}, ${rxId})">Delete</button>
</div>`;
}).join('');
}
async function addPickup(rxId) {
const date = document.getElementById(`pickupDate-${rxId}`).value;
if (!date) {
alert('Pickup date is required');
return;
}
const costStr = document.getElementById(`pickupCost-${rxId}`).value;
const res = await fetch(`${API}/prescriptions/${rxId}/pickups`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pickupDate: date,
quantity: document.getElementById(`pickupQty-${rxId}`).value.trim() || null,
pharmacy: document.getElementById(`pickupPharmacy-${rxId}`).value.trim() || null,
cost: costStr ? parseFloat(costStr) : null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to log pickup');
return;
}
document.getElementById(`pickupDate-${rxId}`).value = '';
document.getElementById(`pickupQty-${rxId}`).value = '';
document.getElementById(`pickupPharmacy-${rxId}`).value = '';
document.getElementById(`pickupCost-${rxId}`).value = '';
await loadPickups(rxId);
await loadPrescriptions();
}
async function deletePickup(id, rxId) {
if (!confirm('Delete this pickup record?')) return;
const res = await fetch(`${API}/pickups/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await loadPickups(rxId);
await loadPrescriptions();
}
// --- Helpers ---
function getDocIcon(doc) {
if (doc.documentType === 'note') {
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line></svg>';
}
const mime = (doc.mimeType || '').toLowerCase();
if (mime.startsWith('image/')) {
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>';
}
if (mime === 'application/pdf') {
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>';
}
// Default file icon
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polyline points="13 2 13 9 20 9"></polyline></svg>';
}
function formatClassification(c) {
return c.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
}
function formatSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
function formatDate(dateStr) {
const d = new Date(dateStr);
return d.toLocaleDateString();
}
function truncate(str, max) {
return str.length > max ? str.substring(0, max) + '...' : str;
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
function escapeAttr(str) {
return str.replace(/'/g, "\\'").replace(/"/g, '\\"');
}
// --- Global functions for inline handlers ---
window.medDocsSelectPerson = function (id) {
selectPerson(id);
};
window.medDocsSwitchTab = function (tabName) {
switchMainTab(tabName);
};
window.medDocsToggleAddForm = function (panelId) {
toggleAddForm(panelId);
};
window.medDocsDownload = function (id, fileName) {
const a = document.createElement('a');
a.href = `${API}/documents/${id}/download`;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
window.medDocsDelete = async function (id) {
if (!confirm('Delete this document? This cannot be undone.')) return;
const res = await fetch(`${API}/documents/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await loadDocuments();
};
window.medDocsProcess = async function (id, btn) {
if (btn) {
btn.disabled = true;
btn.textContent = 'Processing...';
btn.classList.add('processing');
}
try {
const res = await fetch(`${API}/documents/${id}/process`, { method: 'POST' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to start processing');
if (btn) {
btn.disabled = false;
btn.textContent = 'Process AI';
btn.classList.remove('processing');
}
return;
}
if (btn) {
btn.textContent = 'Queued';
}
// Reload after a delay to pick up results
setTimeout(() => loadDocuments(), 5000);
} catch {
if (btn) {
btn.disabled = false;
btn.textContent = 'Process AI';
btn.classList.remove('processing');
}
}
};
// --- Doctor globals ---
window.medDocsAddDoctor = function () { addDoctor(); };
window.medDocsDeleteDoctor = function (id) { deleteDoctor(id); };
window.medDocsEditDoctor = function (id) { editDoctor(id); };
window.medDocsSaveDoctor = function (id) { saveDoctor(id); };
window.medDocsCancelEditDoctor = function () { renderDoctors(); };
// --- Condition globals ---
window.medDocsAddCondition = function () { addCondition(); };
window.medDocsDeleteCondition = function (id) { deleteCondition(id); };
window.medDocsToggleCondition = function (id, isActive) { toggleConditionActive(id, isActive); };
// --- Prescription globals ---
window.medDocsAddPrescription = function () { addPrescription(); };
window.medDocsDeletePrescription = function (id) { deletePrescription(id); };
window.medDocsTogglePickups = function (rxId) { togglePickups(rxId); };
window.medDocsAddPickup = function (rxId) { addPickup(rxId); };
window.medDocsDeletePickup = function (id, rxId) { deletePickup(id, rxId); };
window.medDocsProcessAll = async function () {
const btn = document.getElementById('processAllBtn');
if (btn) {
btn.disabled = true;
btn.textContent = 'Processing...';
}
try {
const res = await fetch(`${API}/documents/process-all`, { method: 'POST' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to start processing');
if (btn) {
btn.disabled = false;
}
await loadDocuments();
return;
}
const data = await res.json();
if (btn) {
btn.textContent = `Queued ${data.queued} docs`;
}
// Reload after a delay to pick up results
setTimeout(() => loadDocuments(), 8000);
} catch {
if (btn) {
btn.disabled = false;
}
await loadDocuments();
}
};
})();