Author SHA1 Message Date
Josh-Heaps bb35460097 Prescription ai update 2026-02-17 09:32:43 -07:00
Josh-Heaps d0c8c1249b bugfix 2026-02-17 09:11:49 -07:00
Josh-Heaps e971a5f329 Add custom colors 2026-02-13 14:13:32 -07:00
Josh-Heaps 91ef4f41dd Make an all patients view. 2026-02-13 10:11:44 -07:00
Josh-Heaps cfd6bb530b Fix so people are scoped to users 2026-02-12 15:14:49 -07:00
Josh-Heaps c173677f57 Add password reset functionality 2026-02-12 13:14:01 -07:00
42 changed files with 2259 additions and 405 deletions
+3 -1
View File
@@ -11,7 +11,9 @@
"Bash(tree:*)", "Bash(tree:*)",
"Bash(del Index.cshtml Index.cshtml.cs)", "Bash(del Index.cshtml Index.cshtml.cs)",
"Bash(dotnet build:*)", "Bash(dotnet build:*)",
"Bash(find:*)" "Bash(find:*)",
"Bash(grep:*)",
"Bash(ls:*)"
], ],
"deny": [], "deny": [],
"ask": [] "ask": []
-77
View File
@@ -1,77 +0,0 @@
# .gitea/workflows/deploy.yml
name: Deploy Media Server
on:
push:
branches: [ "master" ]
workflow_dispatch: {}
concurrency:
group: deploy-media-${{ gitea.ref }}
cancel-in-progress: true
jobs:
build-deploy:
runs-on: ubuntu-latest
steps:
- name: Install toolchain
run: |
apt-get update
apt-get install -y --no-install-recommends rsync openssh-client
- name: Checkout
uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.0.x'
- name: Restore
run: dotnet restore
- name: Publish
run: dotnet publish -c Release -o ./publish
- name: Prepare SSH
env:
SSH_KEY: ${{ secrets.MEDIA_SSH_KEY }}
SSH_HOST: ${{ secrets.MEDIA_SSH_HOST }}
SSH_PORT: ${{ secrets.MEDIA_SSH_PORT }}
run: |
set -euo pipefail
PORT="${SSH_PORT:-22}"
install -m 700 -d ~/.ssh
printf '%s\n' "$SSH_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -p "$PORT" "$SSH_HOST" >> ~/.ssh/known_hosts 2>/dev/null
# Staged through /tmp because the deploy user can't write /var/www directly.
# /usr/local/sbin/deploy-media (root-owned, the only command in deploy's
# sudoers) moves it into place with --exclude=App_Data, so the uploaded
# media and its encrypted store are never touched by --delete.
- name: Stage publish output
env:
SSH_HOST: ${{ secrets.MEDIA_SSH_HOST }}
SSH_PORT: ${{ secrets.MEDIA_SSH_PORT }}
SSH_USER: ${{ secrets.MEDIA_SSH_USER }}
run: |
set -euo pipefail
PORT="${SSH_PORT:-22}"
SSH_OPTS="-p $PORT -i $HOME/.ssh/deploy_key -o StrictHostKeyChecking=yes"
ssh $SSH_OPTS "$SSH_USER@$SSH_HOST" \
"rm -rf /tmp/media-app-stage && mkdir -p /tmp/media-app-stage"
rsync -az --delete -e "ssh $SSH_OPTS" \
publish/ "$SSH_USER@$SSH_HOST:/tmp/media-app-stage/"
- name: Install and restart
env:
SSH_HOST: ${{ secrets.MEDIA_SSH_HOST }}
SSH_PORT: ${{ secrets.MEDIA_SSH_PORT }}
SSH_USER: ${{ secrets.MEDIA_SSH_USER }}
run: |
set -euo pipefail
PORT="${SSH_PORT:-22}"
ssh -p "$PORT" -i "$HOME/.ssh/deploy_key" "$SSH_USER@$SSH_HOST" \
"sudo -n /usr/local/sbin/deploy-media && rm -rf /tmp/media-app-stage"
+138 -48
View File
@@ -17,7 +17,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
var people = await medicalDocsService.GetPeopleAsync(); var people = await medicalDocsService.GetPeopleAsync(userId.Value);
return Ok(people); return Ok(people);
} }
@@ -31,13 +31,68 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
if (string.IsNullOrWhiteSpace(request.Name)) if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" }); return BadRequest(new { error = "Name is required" });
var person = await medicalDocsService.CreatePersonAsync(request.Name.Trim(), request.DateOfBirth, request.Notes); var person = await medicalDocsService.CreatePersonAsync(userId.Value, request.Name.Trim(), request.DateOfBirth, request.Notes);
if (person == null) if (person == null)
return StatusCode(500, new { error = "Failed to create person" }); return StatusCode(500, new { error = "Failed to create person" });
return Ok(person); return Ok(person);
} }
// --- People Access ---
[HttpGet("people/{personId}/access")]
public async Task<IActionResult> GetPersonAccess(long personId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasPersonAccess(userId.Value, personId)) return Forbid();
var users = await medicalDocsService.GetPeopleAccessAsync(personId);
return Ok(users);
}
[HttpPost("people/{personId}/access")]
public async Task<IActionResult> GrantPersonAccess(long personId, [FromBody] GrantAccessRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasPersonAccess(userId.Value, personId)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Username))
return BadRequest(new { error = "Username is required" });
var targetUser = await dbExecutor.ExecuteReaderAsync(
"SELECT id FROM app.users WHERE LOWER(username) = LOWER(@username)",
reader => reader.GetInt64(0),
new { username = request.Username.Trim() });
if (targetUser == 0)
return NotFound(new { error = "User not found" });
var success = await medicalDocsService.GrantAccessAsync(personId, targetUser);
if (!success)
return StatusCode(500, new { error = "Failed to grant access" });
return Ok(new { success = true });
}
[HttpDelete("people/{personId}/access/{targetUserId}")]
public async Task<IActionResult> RevokePersonAccess(long personId, long targetUserId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasPersonAccess(userId.Value, personId)) return Forbid();
var success = await medicalDocsService.RevokeAccessAsync(personId, targetUserId);
if (!success)
return BadRequest(new { error = "Cannot revoke access — at least one user must have access" });
return Ok(new { success = true });
}
// --- Documents --- // --- Documents ---
[HttpGet("documents")] [HttpGet("documents")]
@@ -46,6 +101,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId.HasValue && !await HasPersonAccess(userId.Value, personId.Value)) return Forbid();
if (limit < 1 || limit > 100) limit = 50; if (limit < 1 || limit > 100) limit = 50;
if (offset < 0) offset = 0; if (offset < 0) offset = 0;
@@ -56,7 +112,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
[HttpGet("documents/search")] [HttpGet("documents/search")]
public async Task<IActionResult> SearchDocuments( public async Task<IActionResult> SearchDocuments(
[FromQuery] long personId, [FromQuery] long? personId = null,
[FromQuery] string? search = null, [FromQuery] string? search = null,
[FromQuery] string? classification = null, [FromQuery] string? classification = null,
[FromQuery] string? documentType = null, [FromQuery] string? documentType = null,
@@ -72,28 +128,24 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId.HasValue && !await HasPersonAccess(userId.Value, personId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
if (limit < 1 || limit > 100) limit = 50; if (limit < 1 || limit > 100) limit = 50;
if (offset < 0) offset = 0; if (offset < 0) offset = 0;
var documents = await medicalDocsService.SearchDocumentsAsync(personId, search, classification, documentType, doctorId, tagId, conditionId, fromDate, toDate, aiProcessed, offset, limit); var documents = await medicalDocsService.SearchDocumentsAsync(personId, search, classification, documentType, doctorId, tagId, conditionId, fromDate, toDate, aiProcessed, accessUserId: personId.HasValue ? null : userId, offset: offset, limit: limit);
return Ok(documents); return Ok(documents);
} }
[HttpGet("tags")] [HttpGet("tags")]
public async Task<IActionResult> GetPersonTags([FromQuery] long personId) public async Task<IActionResult> GetPersonTags([FromQuery] long? personId = null)
{ {
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId.HasValue && !await HasPersonAccess(userId.Value, personId.Value)) return Forbid();
if (personId <= 0) var tags = await medicalDocsService.GetPersonTagsAsync(personId, accessUserId: personId.HasValue ? null : userId);
return BadRequest(new { error = "personId is required" });
var tags = await medicalDocsService.GetPersonTagsAsync(personId);
return Ok(tags); return Ok(tags);
} }
@@ -104,6 +156,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasPersonAccess(userId.Value, personId)) return Forbid();
if (file == null || file.Length == 0) if (file == null || file.Length == 0)
return BadRequest(new { error = "No file provided" }); return BadRequest(new { error = "No file provided" });
@@ -126,6 +179,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
if (request.PersonId <= 0) if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" }); return BadRequest(new { error = "Person is required" });
if (!await HasPersonAccess(userId.Value, request.PersonId)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Title)) if (string.IsNullOrWhiteSpace(request.Title))
return BadRequest(new { error = "Title is required" }); return BadRequest(new { error = "Title is required" });
@@ -144,6 +198,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "document", id)) return Forbid();
var doc = await medicalDocsService.GetDocumentByIdAsync(id); var doc = await medicalDocsService.GetDocumentByIdAsync(id);
if (doc == null) return NotFound(new { error = "Document not found" }); if (doc == null) return NotFound(new { error = "Document not found" });
@@ -157,6 +212,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "document", id)) return Forbid();
var doc = await medicalDocsService.GetDocumentByIdAsync(id); var doc = await medicalDocsService.GetDocumentByIdAsync(id);
if (doc == null) return NotFound(new { error = "Document not found" }); if (doc == null) return NotFound(new { error = "Document not found" });
@@ -176,6 +232,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "document", id)) return Forbid();
var success = await medicalDocsService.UpdateDocumentAsync(id, request.Title, request.Description, request.DocumentDate, request.Classification, request.DoctorId); var success = await medicalDocsService.UpdateDocumentAsync(id, request.Title, request.Description, request.DocumentDate, request.Classification, request.DoctorId);
if (!success) return NotFound(new { error = "Document not found" }); if (!success) return NotFound(new { error = "Document not found" });
@@ -189,6 +246,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "document", id)) return Forbid();
var success = await medicalDocsService.DeleteDocumentAsync(id); var success = await medicalDocsService.DeleteDocumentAsync(id);
if (!success) return NotFound(new { error = "Document not found" }); if (!success) return NotFound(new { error = "Document not found" });
@@ -204,6 +262,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "document", id)) return Forbid();
var doc = await medicalDocsService.GetDocumentByIdAsync(id); var doc = await medicalDocsService.GetDocumentByIdAsync(id);
if (doc == null) return NotFound(new { error = "Document not found" }); if (doc == null) return NotFound(new { error = "Document not found" });
@@ -260,21 +319,23 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "document", id)) return Forbid();
var tags = await medicalDocsService.GetDocumentTagsAsync(id); var tags = await medicalDocsService.GetDocumentTagsAsync(id);
return Ok(tags); return Ok(tags);
} }
// --- Doctors --- // --- Doctors (shared, no per-person access check) ---
[HttpGet("doctors")] [HttpGet("doctors")]
public async Task<IActionResult> GetDoctors() public async Task<IActionResult> GetDoctors([FromQuery] long? personId = null)
{ {
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId.HasValue && !await HasPersonAccess(userId.Value, personId.Value)) return Forbid();
var doctors = await medicalDocsService.GetDoctorsAsync(); var doctors = await medicalDocsService.GetDoctorsAsync(personId, accessUserId: personId.HasValue ? null : userId);
return Ok(doctors); return Ok(doctors);
} }
@@ -284,11 +345,12 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasPersonAccess(userId.Value, request.PersonId)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name)) if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" }); return BadRequest(new { error = "Name is required" });
var doctor = await medicalDocsService.CreateDoctorAsync(request.Name.Trim(), request.Specialty, request.Phone, request.Address, request.Notes); var doctor = await medicalDocsService.CreateDoctorAsync(request.PersonId, request.Name.Trim(), request.Specialty, request.Phone, request.Address, request.Notes);
if (doctor == null) if (doctor == null)
return StatusCode(500, new { error = "Failed to create doctor" }); return StatusCode(500, new { error = "Failed to create doctor" });
@@ -301,6 +363,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "doctor", id)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name)) if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" }); return BadRequest(new { error = "Name is required" });
@@ -317,6 +380,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "doctor", id)) return Forbid();
var success = await medicalDocsService.DeleteDoctorAsync(id); var success = await medicalDocsService.DeleteDoctorAsync(id);
if (!success) return NotFound(new { error = "Doctor not found" }); if (!success) return NotFound(new { error = "Doctor not found" });
@@ -327,16 +391,14 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
// --- Conditions --- // --- Conditions ---
[HttpGet("conditions")] [HttpGet("conditions")]
public async Task<IActionResult> GetConditions([FromQuery] long personId) public async Task<IActionResult> GetConditions([FromQuery] long? personId = null)
{ {
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId.HasValue && !await HasPersonAccess(userId.Value, personId.Value)) return Forbid();
if (personId <= 0) var conditions = await medicalDocsService.GetConditionsAsync(personId, accessUserId: personId.HasValue ? null : userId);
return BadRequest(new { error = "personId is required" });
var conditions = await medicalDocsService.GetConditionsAsync(personId);
return Ok(conditions); return Ok(conditions);
} }
@@ -349,6 +411,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
if (request.PersonId <= 0) if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" }); return BadRequest(new { error = "Person is required" });
if (!await HasPersonAccess(userId.Value, request.PersonId)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name)) if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" }); return BadRequest(new { error = "Name is required" });
@@ -365,6 +428,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "condition", id)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name)) if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" }); return BadRequest(new { error = "Name is required" });
@@ -381,6 +445,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "condition", id)) return Forbid();
var success = await medicalDocsService.DeleteConditionAsync(id); var success = await medicalDocsService.DeleteConditionAsync(id);
if (!success) return NotFound(new { error = "Condition not found" }); if (!success) return NotFound(new { error = "Condition not found" });
@@ -391,16 +456,14 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
// --- Prescriptions --- // --- Prescriptions ---
[HttpGet("prescriptions")] [HttpGet("prescriptions")]
public async Task<IActionResult> GetPrescriptions([FromQuery] long personId) public async Task<IActionResult> GetPrescriptions([FromQuery] long? personId = null)
{ {
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId.HasValue && !await HasPersonAccess(userId.Value, personId.Value)) return Forbid();
if (personId <= 0) var prescriptions = await medicalDocsService.GetPrescriptionsAsync(personId, accessUserId: personId.HasValue ? null : userId);
return BadRequest(new { error = "personId is required" });
var prescriptions = await medicalDocsService.GetPrescriptionsAsync(personId);
return Ok(prescriptions); return Ok(prescriptions);
} }
@@ -413,6 +476,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
if (request.PersonId <= 0) if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" }); return BadRequest(new { error = "Person is required" });
if (!await HasPersonAccess(userId.Value, request.PersonId)) return Forbid();
if (string.IsNullOrWhiteSpace(request.MedicationName)) if (string.IsNullOrWhiteSpace(request.MedicationName))
return BadRequest(new { error = "Medication name is required" }); return BadRequest(new { error = "Medication name is required" });
@@ -429,6 +493,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "prescription", id)) return Forbid();
if (string.IsNullOrWhiteSpace(request.MedicationName)) if (string.IsNullOrWhiteSpace(request.MedicationName))
return BadRequest(new { error = "Medication name is required" }); return BadRequest(new { error = "Medication name is required" });
@@ -445,6 +510,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "prescription", id)) return Forbid();
var success = await medicalDocsService.DeletePrescriptionAsync(id); var success = await medicalDocsService.DeletePrescriptionAsync(id);
if (!success) return NotFound(new { error = "Prescription not found" }); if (!success) return NotFound(new { error = "Prescription not found" });
@@ -460,6 +526,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "prescription", id)) return Forbid();
var pickups = await medicalDocsService.GetPickupsAsync(id); var pickups = await medicalDocsService.GetPickupsAsync(id);
return Ok(pickups); return Ok(pickups);
@@ -471,6 +538,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "prescription", id)) return Forbid();
var pickup = await medicalDocsService.CreatePickupAsync(id, request.PickupDate, request.Quantity, request.Pharmacy, request.Cost, request.Notes); var pickup = await medicalDocsService.CreatePickupAsync(id, request.PickupDate, request.Quantity, request.Pharmacy, request.Cost, request.Notes);
if (pickup == null) if (pickup == null)
@@ -485,6 +553,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "pickup", id)) return Forbid();
var success = await medicalDocsService.DeletePickupAsync(id); var success = await medicalDocsService.DeletePickupAsync(id);
if (!success) return NotFound(new { error = "Pickup not found" }); if (!success) return NotFound(new { error = "Pickup not found" });
@@ -495,16 +564,14 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
// --- Billing Providers --- // --- Billing Providers ---
[HttpGet("providers")] [HttpGet("providers")]
public async Task<IActionResult> GetProviders([FromQuery] long personId) public async Task<IActionResult> GetProviders([FromQuery] long? personId = null)
{ {
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId.HasValue && !await HasPersonAccess(userId.Value, personId.Value)) return Forbid();
if (personId <= 0) var providers = await medicalDocsService.GetProvidersAsync(personId, accessUserId: personId.HasValue ? null : userId);
return BadRequest(new { error = "personId is required" });
var providers = await medicalDocsService.GetProvidersAsync(personId);
return Ok(providers); return Ok(providers);
} }
@@ -517,6 +584,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
if (request.PersonId <= 0) if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" }); return BadRequest(new { error = "Person is required" });
if (!await HasPersonAccess(userId.Value, request.PersonId)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name)) if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" }); return BadRequest(new { error = "Name is required" });
@@ -533,6 +601,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "provider", id)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name)) if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" }); return BadRequest(new { error = "Name is required" });
@@ -549,6 +618,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "provider", id)) return Forbid();
var success = await medicalDocsService.DeleteProviderAsync(id); var success = await medicalDocsService.DeleteProviderAsync(id);
if (!success) return NotFound(new { error = "Provider not found" }); if (!success) return NotFound(new { error = "Provider not found" });
@@ -564,6 +634,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "provider", id)) return Forbid();
var payments = await medicalDocsService.GetProviderPaymentsAsync(id); var payments = await medicalDocsService.GetProviderPaymentsAsync(id);
return Ok(payments); return Ok(payments);
@@ -575,6 +646,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "provider", id)) return Forbid();
if (request.Amount <= 0) if (request.Amount <= 0)
return BadRequest(new { error = "Amount must be greater than 0" }); return BadRequest(new { error = "Amount must be greater than 0" });
@@ -592,6 +664,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "provider-payment", id)) return Forbid();
var success = await medicalDocsService.DeleteProviderPaymentAsync(id); var success = await medicalDocsService.DeleteProviderPaymentAsync(id);
if (!success) return NotFound(new { error = "Payment not found" }); if (!success) return NotFound(new { error = "Payment not found" });
@@ -602,16 +675,14 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
// --- Bills --- // --- Bills ---
[HttpGet("bills")] [HttpGet("bills")]
public async Task<IActionResult> GetBills([FromQuery] long personId, [FromQuery] long? providerId = null) public async Task<IActionResult> GetBills([FromQuery] long? personId = null, [FromQuery] long? providerId = null)
{ {
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId.HasValue && !await HasPersonAccess(userId.Value, personId.Value)) return Forbid();
if (personId <= 0) var bills = await medicalDocsService.GetBillsAsync(personId, providerId, accessUserId: personId.HasValue ? null : userId);
return BadRequest(new { error = "personId is required" });
var bills = await medicalDocsService.GetBillsAsync(personId, providerId);
return Ok(bills); return Ok(bills);
} }
@@ -624,6 +695,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
if (request.PersonId <= 0) if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" }); return BadRequest(new { error = "Person is required" });
if (!await HasPersonAccess(userId.Value, request.PersonId)) return Forbid();
if (request.TotalAmount <= 0) if (request.TotalAmount <= 0)
return BadRequest(new { error = "Amount must be greater than 0" }); return BadRequest(new { error = "Amount must be greater than 0" });
@@ -640,6 +712,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "bill", id)) return Forbid();
if (request.TotalAmount <= 0) if (request.TotalAmount <= 0)
return BadRequest(new { error = "Amount must be greater than 0" }); return BadRequest(new { error = "Amount must be greater than 0" });
@@ -656,6 +729,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "bill", id)) return Forbid();
var success = await medicalDocsService.DeleteBillAsync(id); var success = await medicalDocsService.DeleteBillAsync(id);
if (!success) return NotFound(new { error = "Bill not found" }); if (!success) return NotFound(new { error = "Bill not found" });
@@ -669,6 +743,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "bill", id)) return Forbid();
if (request.DocumentId <= 0) if (request.DocumentId <= 0)
return BadRequest(new { error = "Document is required" }); return BadRequest(new { error = "Document is required" });
@@ -686,6 +761,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "bill", billId)) return Forbid();
var success = await medicalDocsService.UnlinkDocumentFromBillAsync(billId, docId); var success = await medicalDocsService.UnlinkDocumentFromBillAsync(billId, docId);
if (!success) return NotFound(new { error = "Link not found" }); if (!success) return NotFound(new { error = "Link not found" });
@@ -701,6 +777,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "bill", id)) return Forbid();
var charges = await medicalDocsService.GetChargesAsync(id); var charges = await medicalDocsService.GetChargesAsync(id);
return Ok(charges); return Ok(charges);
@@ -712,6 +789,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "bill", id)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Description)) if (string.IsNullOrWhiteSpace(request.Description))
return BadRequest(new { error = "Description is required" }); return BadRequest(new { error = "Description is required" });
@@ -731,6 +809,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (!await HasResourceAccess(userId.Value, "bill-charge", id)) return Forbid();
var success = await medicalDocsService.DeleteChargeAsync(id); var success = await medicalDocsService.DeleteChargeAsync(id);
if (!success) return NotFound(new { error = "Charge not found" }); if (!success) return NotFound(new { error = "Charge not found" });
@@ -741,19 +820,17 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
// --- Timeline --- // --- Timeline ---
[HttpGet("timeline")] [HttpGet("timeline")]
public async Task<IActionResult> GetTimeline([FromQuery] long personId, [FromQuery] int offset = 0, [FromQuery] int limit = 100) public async Task<IActionResult> GetTimeline([FromQuery] long? personId = null, [FromQuery] int offset = 0, [FromQuery] int limit = 100)
{ {
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId.HasValue && !await HasPersonAccess(userId.Value, personId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
if (limit < 1 || limit > 200) limit = 100; if (limit < 1 || limit > 200) limit = 100;
if (offset < 0) offset = 0; if (offset < 0) offset = 0;
var events = await medicalDocsService.GetTimelineAsync(personId, offset, limit); var events = await medicalDocsService.GetTimelineAsync(personId, accessUserId: personId.HasValue ? null : userId, offset: offset, limit: limit);
return Ok(events); return Ok(events);
} }
@@ -768,6 +845,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
if (personId <= 0 || doctorId <= 0) if (personId <= 0 || doctorId <= 0)
return BadRequest(new { error = "personId and doctorId are required" }); return BadRequest(new { error = "personId and doctorId are required" });
if (!await HasPersonAccess(userId.Value, personId)) return Forbid();
var data = await medicalDocsService.GetVisitPrepAsync(personId, doctorId); var data = await medicalDocsService.GetVisitPrepAsync(personId, doctorId);
return Ok(data); return Ok(data);
@@ -782,6 +860,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
if (request.PersonId <= 0 || request.DoctorId <= 0) if (request.PersonId <= 0 || request.DoctorId <= 0)
return BadRequest(new { error = "personId and doctorId are required" }); return BadRequest(new { error = "personId and doctorId are required" });
if (!await HasPersonAccess(userId.Value, request.PersonId)) return Forbid();
var data = await medicalDocsService.GetVisitPrepAsync(request.PersonId, request.DoctorId); var data = await medicalDocsService.GetVisitPrepAsync(request.PersonId, request.DoctorId);
var doctor = await medicalDocsService.GetDoctorByIdAsync(request.DoctorId); var doctor = await medicalDocsService.GetDoctorByIdAsync(request.DoctorId);
@@ -793,20 +872,18 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
} }
[HttpGet("bills/summary")] [HttpGet("bills/summary")]
public async Task<IActionResult> GetBillSummary([FromQuery] long personId) public async Task<IActionResult> GetBillSummary([FromQuery] long? personId = null)
{ {
var userId = GetUserIdFromAuth(); var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized(); if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid(); if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId.HasValue && !await HasPersonAccess(userId.Value, personId.Value)) return Forbid();
if (personId <= 0) var summary = await medicalDocsService.GetBillSummaryAsync(personId, accessUserId: personId.HasValue ? null : userId);
return BadRequest(new { error = "personId is required" });
var summary = await medicalDocsService.GetBillSummaryAsync(personId);
return Ok(summary); return Ok(summary);
} }
// --- Auth helpers (same pattern as AdminApi) --- // --- Auth helpers ---
private async Task<bool> HasMedicalAccess(long userId) private async Task<bool> HasMedicalAccess(long userId)
{ {
@@ -815,6 +892,18 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
new { UserId = userId }); new { UserId = userId });
} }
private async Task<bool> HasPersonAccess(long userId, long personId)
{
return await medicalDocsService.HasAccessToPersonAsync(userId, personId);
}
private async Task<bool> HasResourceAccess(long userId, string resourceType, long resourceId)
{
var personId = await medicalDocsService.GetPersonIdForResourceAsync(resourceType, resourceId);
if (personId == null) return false;
return await medicalDocsService.HasAccessToPersonAsync(userId, personId.Value);
}
private long? GetUserIdFromAuth() private long? GetUserIdFromAuth()
{ {
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
@@ -836,7 +925,7 @@ public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDoc
public record CreatePersonRequest(string Name, DateTime? DateOfBirth = null, string? Notes = 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 CreateNoteRequest(long PersonId, string Title, string? Description = null, DateTime? DocumentDate = null, string? Classification = null);
public record UpdateDocumentRequest(string? Title = null, string? Description = null, DateTime? DocumentDate = null, string? Classification = null, long? DoctorId = null); public record UpdateDocumentRequest(string? Title = null, string? Description = null, DateTime? DocumentDate = null, string? Classification = null, long? DoctorId = null);
public record CreateDoctorRequest(string Name, string? Specialty = null, string? Phone = null, string? Address = null, string? Notes = null); public record CreateDoctorRequest(long PersonId, 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 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 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, string? RxNumber = null); public record CreatePrescriptionRequest(long PersonId, string MedicationName, string? Dosage = null, string? Frequency = null, long? DoctorId = null, DateTime? StartDate = null, string? Notes = null, string? RxNumber = null);
@@ -851,3 +940,4 @@ public record LinkDocumentRequest(long DocumentId);
public record CreateChargeRequest(string Description, decimal Amount); public record CreateChargeRequest(string Description, decimal Amount);
public record ProcessBatchRequest(List<long> DocumentIds); public record ProcessBatchRequest(List<long> DocumentIds);
public record VisitPrepSummaryRequest(long PersonId, long DoctorId); public record VisitPrepSummaryRequest(long PersonId, long DoctorId);
public record GrantAccessRequest(string Username);
+74
View File
@@ -0,0 +1,74 @@
using System.Text.RegularExpressions;
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace Media.JoshHeaps.Net.Api;
[ApiController]
[Route("api/theme")]
public partial class ThemeApi(ThemeService themeService) : ControllerBase
{
private static readonly HashSet<string> ValidCssVariables =
[
"--bg-primary", "--bg-secondary", "--bg-tertiary", "--bg-hover",
"--text-primary", "--text-secondary",
"--border-primary", "--border-secondary",
"--accent-primary", "--accent-hover",
"--danger", "--danger-hover", "--success"
];
[GeneratedRegex(@"^#[0-9a-fA-F]{6}$")]
private static partial Regex HexColorRegex();
[HttpGet("my")]
public async Task<IActionResult> GetMyTheme()
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
var theme = await themeService.GetUserThemeAsync(userId.Value);
if (theme == null)
{
return Ok(new { baseTheme = "light", colorOverrides = new Dictionary<string, string>() });
}
return Ok(new { baseTheme = theme.BaseTheme, colorOverrides = theme.ColorOverrides });
}
[HttpPut("my")]
public async Task<IActionResult> SaveMyTheme([FromBody] SaveThemeRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (request.BaseTheme != "dark" && request.BaseTheme != "light")
return BadRequest("baseTheme must be 'dark' or 'light'");
foreach (var (key, value) in request.ColorOverrides)
{
if (!ValidCssVariables.Contains(key))
return BadRequest($"Invalid CSS variable: {key}");
if (!HexColorRegex().IsMatch(value))
return BadRequest($"Invalid hex color for {key}: {value}");
}
await themeService.SaveUserThemeAsync(userId.Value, request.BaseTheme, request.ColorOverrides);
return Ok();
}
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 SaveThemeRequest(string BaseTheme, Dictionary<string, string> ColorOverrides);
@@ -0,0 +1,12 @@
CREATE TABLE app.password_reset_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
token_hash VARCHAR(64) NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ NULL,
FOREIGN KEY (user_id) REFERENCES app.users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_prt_token_hash ON app.password_reset_tokens(token_hash);
CREATE INDEX IF NOT EXISTS idx_prt_user_id ON app.password_reset_tokens(user_id);
@@ -0,0 +1,10 @@
CREATE TABLE IF NOT EXISTS app.medical_people_access (
id BIGSERIAL PRIMARY KEY,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
user_id BIGINT NOT NULL REFERENCES app.users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
UNIQUE(person_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_mpa_user_id ON app.medical_people_access(user_id);
CREATE INDEX IF NOT EXISTS idx_mpa_person_id ON app.medical_people_access(person_id);
@@ -0,0 +1,7 @@
-- Add person_id to medical_doctors to scope doctors per person
ALTER TABLE app.medical_doctors ADD COLUMN IF NOT EXISTS person_id BIGINT REFERENCES app.medical_people(id);
CREATE INDEX IF NOT EXISTS idx_medical_doctors_person_id ON app.medical_doctors(person_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_medical_doctors_person_name
ON app.medical_doctors(person_id, LOWER(name)) WHERE person_id IS NOT NULL;
@@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS app.user_theme_overrides (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES app.users(id) ON DELETE CASCADE,
base_theme TEXT NOT NULL DEFAULT 'light',
color_overrides JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id)
);
CREATE INDEX IF NOT EXISTS idx_uto_user_id ON app.user_theme_overrides(user_id);
@@ -3,6 +3,7 @@ namespace Media.JoshHeaps.Net.Models;
public class MedicalDoctor public class MedicalDoctor
{ {
public long Id { get; set; } public long Id { get; set; }
public long PersonId { get; set; }
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public string? Specialty { get; set; } public string? Specialty { get; set; }
public string? Phone { get; set; } public string? Phone { get; set; }
@@ -9,3 +9,9 @@ public class MedicalPerson
public DateTime CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; } public DateTime UpdatedAt { get; set; }
} }
public class PersonAccessUser
{
public long Id { get; set; }
public string Username { get; set; } = string.Empty;
}
@@ -4,6 +4,7 @@ public class TimelineEvent
{ {
public string EventType { get; set; } = ""; public string EventType { get; set; } = "";
public long Id { get; set; } public long Id { get; set; }
public long PersonId { get; set; }
public string? Label { get; set; } public string? Label { get; set; }
public string? Detail { get; set; } public string? Detail { get; set; }
public string? SubType { get; set; } public string? SubType { get; set; }
@@ -0,0 +1,11 @@
namespace Media.JoshHeaps.Net.Models;
public class UserThemeOverrides
{
public long Id { get; set; }
public long UserId { get; set; }
public string BaseTheme { get; set; } = "light";
public Dictionary<string, string> ColorOverrides { get; set; } = new();
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
+1
View File
@@ -21,6 +21,7 @@
</a> </a>
<h1>Welcome back, @Model.Dashboard?.Username!</h1> <h1>Welcome back, @Model.Dashboard?.Username!</h1>
</div> </div>
<div class="quick-actions"> <div class="quick-actions">
@if (Model.Dashboard?.EmailVerified == false) @if (Model.Dashboard?.EmailVerified == false)
{ {
+3
View File
@@ -60,11 +60,14 @@
<div class="invalid-feedback"></div> <div class="invalid-feedback"></div>
</div> </div>
<div class="form-options">
<div class="checkbox-wrapper"> <div class="checkbox-wrapper">
<input type="checkbox" id="rememberMe" name="rememberMe" <input type="checkbox" id="rememberMe" name="rememberMe"
@(Model.RememberMe ? "checked" : "") /> @(Model.RememberMe ? "checked" : "") />
<label for="rememberMe">Remember me</label> <label for="rememberMe">Remember me</label>
</div> </div>
<a href="/LoginHelp" class="forgot-password-link">Forgot password?</a>
</div>
<button type="submit" class="btn-primary">Sign In</button> <button type="submit" class="btn-primary">Sign In</button>
</form> </form>
+7 -1
View File
@@ -20,7 +20,7 @@ public class LoginModel(AuthService authService) : PageModel
public string? SuccessMessage { get; set; } public string? SuccessMessage { get; set; }
public string? WarningMessage { get; set; } public string? WarningMessage { get; set; }
public void OnGet([FromQuery] string? registered, [FromQuery] string? verified) public void OnGet([FromQuery] string? registered, [FromQuery] string? verified, [FromQuery] string? reset)
{ {
// Check if user is already logged in // Check if user is already logged in
var userId = HttpContext.Session.GetString("UserId"); var userId = HttpContext.Session.GetString("UserId");
@@ -41,6 +41,12 @@ public class LoginModel(AuthService authService) : PageModel
{ {
SuccessMessage = "Email verified! You can now sign in."; SuccessMessage = "Email verified! You can now sign in.";
} }
// Show success message if password was just reset
if (reset == "true")
{
SuccessMessage = "Your password has been reset. You can now sign in with your new password.";
}
} }
public async Task<IActionResult> OnPostAsync() public async Task<IActionResult> OnPostAsync()
+102
View File
@@ -0,0 +1,102 @@
@page
@model Media.JoshHeaps.Net.Pages.LoginHelpModel
@{
ViewData["Title"] = "Login Help";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/auth.css" asp-append-version="true" />
}
@section Scripts {
<script src="~/js/auth.js" asp-append-version="true"></script>
}
<div class="auth-container">
<div class="auth-card">
@if (Model.ShowResetForm)
{
<div class="auth-header">
<h1>Reset Password</h1>
<p>Enter your new password below</p>
</div>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<div class="alert alert-danger">
@Model.ErrorMessage
</div>
}
<form id="resetPasswordForm" method="post" asp-page-handler="ResetPassword">
@Html.AntiForgeryToken()
<input type="hidden" name="Token" value="@Model.Token" />
<div class="form-group">
<label for="newPassword" class="form-label">New Password</label>
<div class="password-wrapper">
<input type="password" class="form-control" id="newPassword" name="NewPassword"
autocomplete="new-password" required minlength="8" />
<button type="button" class="password-toggle">Show</button>
</div>
<div class="invalid-feedback"></div>
<div class="password-strength">
<div class="password-strength-bar"></div>
</div>
<div class="password-strength-text"></div>
</div>
<div class="form-group">
<label for="confirmPassword" class="form-label">Confirm Password</label>
<div class="password-wrapper">
<input type="password" class="form-control" id="confirmPassword" name="ConfirmPassword"
autocomplete="new-password" required minlength="8" />
<button type="button" class="password-toggle">Show</button>
</div>
<div class="invalid-feedback"></div>
</div>
<button type="submit" class="btn-primary">Reset Password</button>
</form>
}
else
{
<div class="auth-header">
<h1>Forgot Password</h1>
<p>Enter your email to receive a reset link</p>
</div>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<div class="alert alert-danger">
@Model.ErrorMessage
</div>
}
@if (!string.IsNullOrEmpty(Model.SuccessMessage))
{
<div class="alert alert-success">
@Model.SuccessMessage
</div>
}
<form id="requestResetForm" method="post" asp-page-handler="RequestReset">
@Html.AntiForgeryToken()
<div class="form-group">
<label for="email" class="form-label">Email Address</label>
<input type="email" class="form-control" id="email" name="Email"
value="@Model.Email" autocomplete="email" required />
<div class="invalid-feedback"></div>
</div>
<button type="submit" class="btn-primary">Send Reset Link</button>
</form>
}
<div class="auth-footer">
<p>Remember your password? <a href="/Login">Sign in</a></p>
</div>
</div>
</div>
@@ -0,0 +1,111 @@
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public class LoginHelpModel(AuthService authService, EmailService emailService, ILogger<LoginHelpModel> logger) : PageModel
{
[BindProperty]
public string Email { get; set; } = string.Empty;
[BindProperty]
public string Token { get; set; } = string.Empty;
[BindProperty]
public string NewPassword { get; set; } = string.Empty;
[BindProperty]
public string ConfirmPassword { get; set; } = string.Empty;
public string? ErrorMessage { get; set; }
public string? SuccessMessage { get; set; }
public bool ShowResetForm { get; set; }
public async Task<IActionResult> OnGetAsync([FromQuery] string? token)
{
// Redirect if already logged in
var userId = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userId))
return Redirect("/Landing");
if (!string.IsNullOrEmpty(token))
{
var (valid, error) = await authService.ValidatePasswordResetTokenAsync(token);
if (valid)
{
ShowResetForm = true;
Token = token;
}
else
{
ErrorMessage = error;
}
}
return Page();
}
public async Task<IActionResult> OnPostRequestResetAsync()
{
// Redirect if already logged in
var userId = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userId))
return Redirect("/Landing");
if (string.IsNullOrWhiteSpace(Email))
{
ErrorMessage = "Please enter your email address.";
return Page();
}
var (success, error, token, username) = await authService.RequestPasswordResetAsync(Email.Trim());
if (!success)
{
logger.LogError("Password reset request failed for {Email}: {Error}", Email, error);
}
// Send email if we got a token back (user exists and is eligible)
if (token != null)
{
await emailService.SendPasswordResetEmailAsync(Email.Trim(), username ?? Email.Split('@')[0], token);
}
// Always show the same message regardless of whether the email exists
SuccessMessage = "If an account exists with that email, you will receive a password reset link shortly.";
return Page();
}
public async Task<IActionResult> OnPostResetPasswordAsync()
{
// Redirect if already logged in
var userId = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userId))
return Redirect("/Landing");
if (string.IsNullOrWhiteSpace(NewPassword) || NewPassword.Length < 8)
{
ErrorMessage = "Password must be at least 8 characters.";
ShowResetForm = true;
return Page();
}
if (NewPassword != ConfirmPassword)
{
ErrorMessage = "Passwords do not match.";
ShowResetForm = true;
return Page();
}
var (success, error) = await authService.ResetPasswordAsync(Token, NewPassword);
if (!success)
{
ErrorMessage = error;
return Page();
}
return Redirect("/Login?reset=true");
}
}
@@ -285,6 +285,23 @@
</div> </div>
</div> </div>
<!-- Share Access Modal -->
<div class="doc-viewer-overlay" id="shareAccessOverlay" style="display:none" onclick="medDocsCloseShareModal(event)">
<div class="doc-viewer-modal" style="max-width:420px;max-height:400px;" onclick="event.stopPropagation()">
<div class="doc-viewer-header">
<span class="doc-viewer-title">Share Patient Access</span>
<button class="doc-viewer-close" onclick="medDocsCloseShareModal()" title="Close">&times;</button>
</div>
<div class="doc-viewer-body" style="padding:1rem;overflow-y:auto;">
<div id="shareAccessList" style="margin-bottom:1rem;"></div>
<div style="display:flex;gap:0.5rem;">
<input type="text" id="shareUsername" placeholder="Username..." class="form-input" style="flex:1;" />
<button class="btn btn-primary btn-sm" onclick="medDocsGrantAccess()">Grant</button>
</div>
</div>
</div>
</div>
@section Scripts { @section Scripts {
<script src="~/js/medical-docs/state.js" asp-append-version="true"></script> <script src="~/js/medical-docs/state.js" asp-append-version="true"></script>
<script src="~/js/medical-docs/tabs.js" asp-append-version="true"></script> <script src="~/js/medical-docs/tabs.js" asp-append-version="true"></script>
+11 -127
View File
@@ -7,133 +7,8 @@
@section Styles { @section Styles {
<link rel="stylesheet" href="~/css/Home/page.css" asp-append-version="true" /> <link rel="stylesheet" href="~/css/Home/page.css" asp-append-version="true" />
<style> <link rel="stylesheet" href="~/css/profile.css" asp-append-version="true" />
.profile-container { <link rel="stylesheet" href="~/css/theme-customizer.css" asp-append-version="true" />
max-width: 800px;
margin: 40px auto;
padding: 0 20px;
}
.profile-section {
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
padding: 24px;
margin-bottom: 20px;
}
.profile-section h2 {
margin: 0 0 20px 0;
font-size: 18px;
font-weight: 600;
color: var(--text-primary);
border-bottom: 1px solid var(--border-primary);
padding-bottom: 12px;
}
.profile-field {
margin-bottom: 16px;
}
.profile-field label {
display: block;
font-weight: 500;
color: var(--text-secondary);
margin-bottom: 4px;
font-size: 14px;
}
.profile-field-value {
color: var(--text-primary);
font-size: 15px;
}
.theme-toggle-container {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 0;
}
.theme-toggle-label {
display: flex;
flex-direction: column;
}
.theme-toggle-label strong {
color: var(--text-primary);
font-size: 15px;
margin-bottom: 4px;
}
.theme-toggle-label span {
color: var(--text-secondary);
font-size: 13px;
}
.toggle-switch {
position: relative;
display: inline-block;
width: 50px;
height: 26px;
}
.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--bg-tertiary);
border: 1px solid var(--border-primary);
transition: 0.3s;
border-radius: 34px;
}
.toggle-slider:before {
position: absolute;
content: "";
height: 18px;
width: 18px;
left: 3px;
bottom: 3px;
background-color: var(--text-secondary);
transition: 0.3s;
border-radius: 50%;
}
input:checked + .toggle-slider {
background-color: var(--accent-primary);
border-color: var(--accent-primary);
}
input:checked + .toggle-slider:before {
transform: translateX(24px);
background-color: var(--bg-primary);
}
.back-link {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--accent-primary);
text-decoration: none;
font-size: 14px;
margin-bottom: 20px;
transition: color 0.2s ease;
}
.back-link:hover {
color: var(--accent-hover);
}
</style>
} }
<div class="profile-container"> <div class="profile-container">
@@ -176,5 +51,14 @@
<span class="toggle-slider"></span> <span class="toggle-slider"></span>
</label> </label>
</div> </div>
<div class="theme-toggle-container">
<div class="theme-toggle-label">
<strong>Custom Colors</strong>
<span>Personalize individual theme colors</span>
</div>
<button class="customize-btn" onclick="openThemeCustomizer()">Customize</button>
</div>
</div> </div>
</div> </div>
<script src="~/js/theme-customizer.js" asp-append-version="true"></script>
+1
View File
@@ -19,6 +19,7 @@ builder.Services.AddScoped<FolderService>();
builder.Services.AddScoped<GraphService>(); builder.Services.AddScoped<GraphService>();
builder.Services.AddScoped<MedicalDocsService>(); builder.Services.AddScoped<MedicalDocsService>();
builder.Services.AddSingleton<MedicalAiService>(); builder.Services.AddSingleton<MedicalAiService>();
builder.Services.AddScoped<ThemeService>();
// Add session support // Add session support
builder.Services.AddDistributedMemoryCache(); builder.Services.AddDistributedMemoryCache();
+171
View File
@@ -1,3 +1,5 @@
using System.Security.Cryptography;
using System.Text;
using Media.JoshHeaps.Net; using Media.JoshHeaps.Net;
using Media.JoshHeaps.Net.Models; using Media.JoshHeaps.Net.Models;
@@ -302,4 +304,173 @@ public class AuthService(DbExecutor db)
new { userId, lastLogin = DateTime.UtcNow } new { userId, lastLogin = DateTime.UtcNow }
); );
} }
public static string GenerateSecureToken()
{
var bytes = RandomNumberGenerator.GetBytes(32);
return Convert.ToBase64String(bytes)
.Replace("+", "-")
.Replace("/", "_")
.TrimEnd('=');
}
public static string HashToken(string token)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(token));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
public async Task<(bool Success, string? Error, string? Token, string? Username)> RequestPasswordResetAsync(string email)
{
try
{
var userRow = await db.ExecuteReaderAsync(
"SELECT id, username, is_active, locked_until FROM app.users WHERE email = @email",
reader => new
{
UserId = reader.GetInt64(0),
Username = reader.GetString(1),
IsActive = reader.GetBoolean(2),
LockedUntil = reader.IsDBNull(3) ? (DateTime?)null : reader.GetDateTime(3)
},
new { email }
);
if (userRow == null)
{
// Artificial delay to prevent timing-based email enumeration
await Task.Delay(Random.Shared.Next(100, 300));
return (true, null, null, null);
}
// Silently succeed for inactive/locked accounts (don't reveal state)
if (!userRow.IsActive ||
(userRow.LockedUntil.HasValue && userRow.LockedUntil.Value > DateTime.UtcNow))
{
return (true, null, null, null);
}
// Rate limit: max 3 requests per hour
var recentCount = await db.ExecuteAsync<long>(
@"SELECT COUNT(*) FROM app.password_reset_tokens
WHERE user_id = @userId AND created_at > @cutoff",
new { userId = userRow.UserId, cutoff = DateTimeOffset.UtcNow.AddHours(-1) }
);
if (recentCount >= 3)
{
return (true, null, null, null);
}
// Invalidate all existing unused tokens for this user
await db.ExecuteNonQueryAsync(
@"UPDATE app.password_reset_tokens
SET used_at = @now
WHERE user_id = @userId AND used_at IS NULL",
new { userId = userRow.UserId, now = DateTimeOffset.UtcNow }
);
// Generate and store new token
var token = GenerateSecureToken();
var tokenHash = HashToken(token);
var expiresAt = DateTimeOffset.UtcNow.AddHours(1);
await db.ExecuteNonQueryAsync(
@"INSERT INTO app.password_reset_tokens (user_id, token_hash, expires_at)
VALUES (@userId, @tokenHash, @expiresAt)",
new { userId = userRow.UserId, tokenHash, expiresAt }
);
return (true, null, token, userRow.Username);
}
catch (Exception ex)
{
return (false, $"Password reset request failed: {ex.Message}", null, null);
}
}
public async Task<(bool Valid, string? Error)> ValidatePasswordResetTokenAsync(string token)
{
try
{
var tokenHash = HashToken(token);
var tokenRow = await db.ExecuteReaderAsync(
@"SELECT expires_at, used_at FROM app.password_reset_tokens
WHERE token_hash = @tokenHash",
reader => new
{
ExpiresAt = reader.GetFieldValue<DateTimeOffset>(0),
UsedAt = reader.IsDBNull(1) ? (DateTimeOffset?)null : reader.GetFieldValue<DateTimeOffset>(1)
},
new { tokenHash }
);
if (tokenRow == null)
return (false, "Invalid or expired reset link. Please request a new one.");
if (tokenRow.UsedAt.HasValue)
return (false, "This reset link has already been used. Please request a new one.");
if (tokenRow.ExpiresAt < DateTimeOffset.UtcNow)
return (false, "This reset link has expired. Please request a new one.");
return (true, null);
}
catch (Exception ex)
{
return (false, $"Token validation failed: {ex.Message}");
}
}
public async Task<(bool Success, string? Error)> ResetPasswordAsync(string token, string newPassword)
{
try
{
var tokenHash = HashToken(token);
var tokenRow = await db.ExecuteReaderAsync(
@"SELECT id, user_id, expires_at, used_at FROM app.password_reset_tokens
WHERE token_hash = @tokenHash",
reader => new
{
Id = reader.GetInt64(0),
UserId = reader.GetInt64(1),
ExpiresAt = reader.GetFieldValue<DateTimeOffset>(2),
UsedAt = reader.IsDBNull(3) ? (DateTimeOffset?)null : reader.GetFieldValue<DateTimeOffset>(3)
},
new { tokenHash }
);
if (tokenRow == null)
return (false, "Invalid or expired reset link. Please request a new one.");
if (tokenRow.UsedAt.HasValue)
return (false, "This reset link has already been used. Please request a new one.");
if (tokenRow.ExpiresAt < DateTimeOffset.UtcNow)
return (false, "This reset link has expired. Please request a new one.");
// Hash new password and update user
var passwordHash = HashPassword(newPassword);
await db.ExecuteNonQueryAsync(
@"UPDATE app.users
SET password_hash = @passwordHash, failed_login_attempts = 0, locked_until = NULL
WHERE id = @userId",
new { userId = tokenRow.UserId, passwordHash }
);
// Mark token as used
await db.ExecuteNonQueryAsync(
"UPDATE app.password_reset_tokens SET used_at = @now WHERE id = @tokenId",
new { tokenId = tokenRow.Id, now = DateTimeOffset.UtcNow }
);
return (true, null);
}
catch (Exception ex)
{
return (false, $"Password reset failed: {ex.Message}");
}
}
} }
+1 -1
View File
@@ -107,7 +107,7 @@ If you didn't create an account, you can safely ignore this email.
try try
{ {
var appUrl = config["AppUrl"] ?? "http://localhost:5000"; var appUrl = config["AppUrl"] ?? "http://localhost:5000";
var resetUrl = $"{appUrl}/ResetPassword?token={resetToken}"; var resetUrl = $"{appUrl}/LoginHelp?token={resetToken}";
var message = new MimeMessage(); var message = new MimeMessage();
message.From.Add(new MailboxAddress( message.From.Add(new MailboxAddress(
@@ -123,7 +123,7 @@ public class MedicalAiService
{ {
try try
{ {
var doctor = await medicalDocsService.FindOrCreateDoctorByNameAsync(doctorName.Trim()); var doctor = await medicalDocsService.FindOrCreateDoctorByNameAsync(doc.PersonId, doctorName.Trim(), this);
doctorId = doctor?.Id; doctorId = doctor?.Id;
} }
catch (Exception ex) catch (Exception ex)
@@ -263,7 +263,7 @@ public class MedicalAiService
- ""doctorName"": string or null — the individual doctor/physician name mentioned (e.g. ""Dr. John Smith"" → ""John Smith""). If multiple, pick the primary/treating physician. - ""doctorName"": string or null — the individual doctor/physician name mentioned (e.g. ""Dr. John Smith"" → ""John Smith""). If multiple, pick the primary/treating physician.
- ""conditionNames"": array of medical condition names mentioned or clearly implied (e.g. ""Type 2 Diabetes"", ""Hypertension""). Only include conditions you can confidently identify. Use standard medical terminology. Return empty array if none are obvious. - ""conditionNames"": array of medical condition names mentioned or clearly implied (e.g. ""Type 2 Diabetes"", ""Hypertension""). Only include conditions you can confidently identify. Use standard medical terminology. Return empty array if none are obvious.
Return ONLY the JSON object, no other text."; Return ONLY the JSON object, no other text. If a document is a receipt for an individual prescription, label it as a prescription.";
var userPrompt = $"Analyze this medical document text and classify it.\n\nDocument text:\n{truncatedText}"; var userPrompt = $"Analyze this medical document text and classify it.\n\nDocument text:\n{truncatedText}";
@@ -447,7 +447,7 @@ Only include fields you can confidently extract. Return ONLY the JSON object, no
return null; return null;
} }
_logger.LogError("claude CLI exited with code {ExitCode}: {Stderr}", process.ExitCode, stderr); _logger.LogError("claude CLI exited with code {ExitCode}.\nStderr: {Stderr}\nStdout: {Stdout}", process.ExitCode, stderr, stdout);
return null; return null;
} }
@@ -631,6 +631,42 @@ Consider abbreviations, slight misspellings, and variations (e.g., ""Intermounta
} }
} }
public async Task<string?> FuzzyMatchDoctorAsync(string extractedName, List<string> existingDoctorNames)
{
try
{
var doctorList = string.Join("\n", existingDoctorNames.Select(n => $" - {n}"));
var systemPrompt = @"You are matching a doctor name extracted from a medical document against a list of known doctors for a patient. Return ONLY a JSON object with:
- ""matchedName"": the exact string from the existing list that matches, or null if no match
- ""confidence"": ""high"", ""medium"", or ""low""
Consider abbreviations, titles, and variations (e.g., ""Dr. John Smith"" matches ""John Smith"", ""J. Smith MD"" matches ""John Smith"", ""Smith, John"" matches ""John Smith""). Only return a match with medium or high confidence.";
var userPrompt = $"Extracted doctor name: \"{extractedName}\"\n\nExisting doctors:\n{doctorList}";
var response = await CallClaudeCliAsync(systemPrompt, userPrompt, HaikuModel);
if (response == null) return null;
var json = ExtractJson(response);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var matchedName = root.TryGetProperty("matchedName", out var mn) && mn.ValueKind == JsonValueKind.String ? mn.GetString() : null;
var confidence = root.TryGetProperty("confidence", out var conf) ? conf.GetString() : "low";
if (matchedName != null && confidence != "low")
return matchedName;
return null;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Fuzzy doctor matching failed for \"{ExtractedName}\"", extractedName);
return null;
}
}
public async Task<string?> FuzzyMatchConditionAsync(string extractedName, List<string> existingConditionNames) public async Task<string?> FuzzyMatchConditionAsync(string extractedName, List<string> existingConditionNames)
{ {
try try
@@ -6,12 +6,16 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
{ {
// --- People --- // --- People ---
public async Task<List<MedicalPerson>> GetPeopleAsync() public async Task<List<MedicalPerson>> GetPeopleAsync(long userId)
{ {
try try
{ {
return await db.ExecuteListReaderAsync( return await db.ExecuteListReaderAsync(
"SELECT id, name, date_of_birth, notes, created_at, updated_at FROM app.medical_people ORDER BY name", @"SELECT mp.id, mp.name, mp.date_of_birth, mp.notes, mp.created_at, mp.updated_at
FROM app.medical_people mp
JOIN app.medical_people_access mpa ON mpa.person_id = mp.id
WHERE mpa.user_id = @userId
ORDER BY mp.name",
reader => new MedicalPerson reader => new MedicalPerson
{ {
Id = reader.GetInt64(0), Id = reader.GetInt64(0),
@@ -20,7 +24,8 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
Notes = reader.IsDBNull(3) ? null : reader.GetString(3), Notes = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4), CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5) UpdatedAt = reader.GetDateTime(5)
}); },
new { userId });
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -29,12 +34,12 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
} }
} }
public async Task<MedicalPerson?> CreatePersonAsync(string name, DateTime? dateOfBirth = null, string? notes = null) public async Task<MedicalPerson?> CreatePersonAsync(long userId, string name, DateTime? dateOfBirth = null, string? notes = null)
{ {
try try
{ {
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
return await db.ExecuteReaderAsync( var person = await db.ExecuteReaderAsync(
@"INSERT INTO app.medical_people (name, date_of_birth, notes, created_at, updated_at) @"INSERT INTO app.medical_people (name, date_of_birth, notes, created_at, updated_at)
VALUES (@name, @dateOfBirth, @notes, @createdAt, @updatedAt) VALUES (@name, @dateOfBirth, @notes, @createdAt, @updatedAt)
RETURNING id, name, date_of_birth, notes, created_at, updated_at", RETURNING id, name, date_of_birth, notes, created_at, updated_at",
@@ -48,6 +53,15 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
UpdatedAt = reader.GetDateTime(5) UpdatedAt = reader.GetDateTime(5)
}, },
new { name, dateOfBirth, notes, createdAt = now, updatedAt = now }); new { name, dateOfBirth, notes, createdAt = now, updatedAt = now });
if (person != null)
{
await db.ExecuteNonQueryAsync(
"INSERT INTO app.medical_people_access (person_id, user_id) VALUES (@personId, @userId) ON CONFLICT DO NOTHING",
new { personId = person.Id, userId });
}
return person;
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -56,6 +70,110 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
} }
} }
// --- People Access ---
public async Task<bool> HasAccessToPersonAsync(long userId, long personId)
{
try
{
return await db.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.medical_people_access WHERE user_id = @userId AND person_id = @personId)",
new { userId, personId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to check person access");
return false;
}
}
public async Task<bool> GrantAccessAsync(long personId, long targetUserId)
{
try
{
await db.ExecuteNonQueryAsync(
"INSERT INTO app.medical_people_access (person_id, user_id) VALUES (@personId, @userId) ON CONFLICT DO NOTHING",
new { personId, userId = targetUserId });
return true;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to grant person access");
return false;
}
}
public async Task<bool> RevokeAccessAsync(long personId, long targetUserId)
{
try
{
var count = await db.ExecuteAsync<long>(
"SELECT COUNT(*) FROM app.medical_people_access WHERE person_id = @personId",
new { personId });
if (count <= 1)
return false;
await db.ExecuteNonQueryAsync(
"DELETE FROM app.medical_people_access WHERE person_id = @personId AND user_id = @userId",
new { personId, userId = targetUserId });
return true;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to revoke person access");
return false;
}
}
public async Task<List<PersonAccessUser>> GetPeopleAccessAsync(long personId)
{
try
{
return await db.ExecuteListReaderAsync(
@"SELECT u.id, u.username FROM app.users u
JOIN app.medical_people_access mpa ON mpa.user_id = u.id
WHERE mpa.person_id = @personId
ORDER BY u.username",
reader => new PersonAccessUser
{
Id = reader.GetInt64(0),
Username = reader.GetString(1)
},
new { personId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get person access list");
return [];
}
}
public async Task<long?> GetPersonIdForResourceAsync(string resourceType, long resourceId)
{
try
{
var sql = resourceType switch
{
"document" => "SELECT person_id FROM app.medical_documents WHERE id = @id",
"doctor" => "SELECT person_id FROM app.medical_doctors WHERE id = @id",
"condition" => "SELECT person_id FROM app.medical_conditions WHERE id = @id",
"prescription" => "SELECT person_id FROM app.medical_prescriptions WHERE id = @id",
"pickup" => "SELECT p.person_id FROM app.medical_prescription_pickups pk JOIN app.medical_prescriptions p ON pk.prescription_id = p.id WHERE pk.id = @id",
"provider" => "SELECT person_id FROM app.medical_billing_providers WHERE id = @id",
"provider-payment" => "SELECT bp.person_id FROM app.medical_provider_payments pp JOIN app.medical_billing_providers bp ON pp.provider_id = bp.id WHERE pp.id = @id",
"bill" => "SELECT person_id FROM app.medical_bills WHERE id = @id",
"bill-charge" => "SELECT b.person_id FROM app.medical_bill_charges bc JOIN app.medical_bills b ON bc.bill_id = b.id WHERE bc.id = @id",
_ => throw new ArgumentException($"Unknown resource type: {resourceType}")
};
return await db.ExecuteAsync<long?>(sql, new { id = resourceId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get person ID for {ResourceType} {ResourceId}", resourceType, resourceId);
return null;
}
}
// --- Documents --- // --- Documents ---
public async Task<MedicalDocument?> SaveDocumentAsync(long personId, IFormFile file, string? title = null, string? description = null, DateTime? documentDate = null, string? classification = null) public async Task<MedicalDocument?> SaveDocumentAsync(long personId, IFormFile file, string? title = null, string? description = null, DateTime? documentDate = null, string? classification = null)
@@ -180,11 +298,14 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
} }
} }
public async Task<List<MedicalDocument>> SearchDocumentsAsync(long personId, string? search = null, string? classification = null, string? documentType = null, long? doctorId = null, long? tagId = null, long? conditionId = null, DateTime? fromDate = null, DateTime? toDate = null, bool? aiProcessed = null, int offset = 0, int limit = 50) public async Task<List<MedicalDocument>> SearchDocumentsAsync(long? personId = null, string? search = null, string? classification = null, string? documentType = null, long? doctorId = null, long? tagId = null, long? conditionId = null, DateTime? fromDate = null, DateTime? toDate = null, bool? aiProcessed = null, long? accessUserId = null, int offset = 0, int limit = 50)
{ {
try try
{ {
var conditions = new List<string> { "person_id = @personId" }; var personFilter = personId.HasValue
? "person_id = @personId"
: "person_id IN (SELECT person_id FROM app.medical_people_access WHERE user_id = @accessUserId)";
var conditions = new List<string> { personFilter };
if (!string.IsNullOrWhiteSpace(search)) if (!string.IsNullOrWhiteSpace(search))
conditions.Add("(title ILIKE @search OR description ILIKE @search OR extracted_text ILIKE @search)"); conditions.Add("(title ILIKE @search OR description ILIKE @search OR extracted_text ILIKE @search)");
@@ -222,7 +343,8 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
return await db.ExecuteListReaderAsync(query, MapDocument, new return await db.ExecuteListReaderAsync(query, MapDocument, new
{ {
personId, personId = personId ?? 0L,
accessUserId = accessUserId ?? 0L,
search = !string.IsNullOrWhiteSpace(search) ? $"%{search}%" : (string?)null, search = !string.IsNullOrWhiteSpace(search) ? $"%{search}%" : (string?)null,
classification, classification,
documentType, documentType,
@@ -243,16 +365,20 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
} }
} }
public async Task<List<MedicalTag>> GetPersonTagsAsync(long personId) public async Task<List<MedicalTag>> GetPersonTagsAsync(long? personId = null, long? accessUserId = null)
{ {
try try
{ {
var personFilter = personId.HasValue
? "d.person_id = @personId"
: "d.person_id IN (SELECT person_id FROM app.medical_people_access WHERE user_id = @accessUserId)";
return await db.ExecuteListReaderAsync( return await db.ExecuteListReaderAsync(
@"SELECT DISTINCT t.id, t.name, t.created_at $@"SELECT DISTINCT t.id, t.name, t.created_at
FROM app.medical_tags t FROM app.medical_tags t
JOIN app.medical_document_tags dt ON dt.tag_id = t.id JOIN app.medical_document_tags dt ON dt.tag_id = t.id
JOIN app.medical_documents d ON dt.document_id = d.id JOIN app.medical_documents d ON dt.document_id = d.id
WHERE d.person_id = @personId WHERE {personFilter}
ORDER BY t.name", ORDER BY t.name",
reader => new MedicalTag reader => new MedicalTag
{ {
@@ -260,7 +386,7 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
Name = reader.GetString(1), Name = reader.GetString(1),
CreatedAt = reader.GetDateTime(2) CreatedAt = reader.GetDateTime(2)
}, },
new { personId }); new { personId = personId ?? 0L, accessUserId = accessUserId ?? 0L });
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -380,39 +506,45 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
// --- Doctors --- // --- Doctors ---
public async Task<List<MedicalDoctor>> GetDoctorsAsync() public async Task<List<MedicalDoctor>> GetDoctorsAsync(long? personId = null, long? accessUserId = null)
{ {
try try
{ {
var personFilter = personId.HasValue
? "person_id = @personId"
: "person_id IN (SELECT person_id FROM app.medical_people_access WHERE user_id = @accessUserId)";
return await db.ExecuteListReaderAsync( return await db.ExecuteListReaderAsync(
"SELECT id, name, specialty, phone, address, notes, created_at, updated_at FROM app.medical_doctors ORDER BY name", $"SELECT id, person_id, name, specialty, phone, address, notes, created_at, updated_at FROM app.medical_doctors WHERE {personFilter} ORDER BY name",
reader => new MedicalDoctor reader => new MedicalDoctor
{ {
Id = reader.GetInt64(0), Id = reader.GetInt64(0),
Name = reader.GetString(1), PersonId = reader.GetInt64(1),
Specialty = reader.IsDBNull(2) ? null : reader.GetString(2), Name = reader.GetString(2),
Phone = reader.IsDBNull(3) ? null : reader.GetString(3), Specialty = reader.IsDBNull(3) ? null : reader.GetString(3),
Address = reader.IsDBNull(4) ? null : reader.GetString(4), Phone = reader.IsDBNull(4) ? null : reader.GetString(4),
Notes = reader.IsDBNull(5) ? null : reader.GetString(5), Address = reader.IsDBNull(5) ? null : reader.GetString(5),
CreatedAt = reader.GetDateTime(6), Notes = reader.IsDBNull(6) ? null : reader.GetString(6),
UpdatedAt = reader.GetDateTime(7) CreatedAt = reader.GetDateTime(7),
}); UpdatedAt = reader.GetDateTime(8)
},
new { personId = personId ?? 0L, accessUserId = accessUserId ?? 0L });
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "Failed to get doctors"); logger.LogError(ex, "Failed to get doctors for person {PersonId}", personId);
return []; return [];
} }
} }
public async Task<MedicalDoctor?> CreateDoctorAsync(string name, string? specialty = null, string? phone = null, string? address = null, string? notes = null) public async Task<MedicalDoctor?> CreateDoctorAsync(long personId, string name, string? specialty = null, string? phone = null, string? address = null, string? notes = null)
{ {
try try
{ {
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
return await db.ExecuteReaderAsync( return await db.ExecuteReaderAsync(
@"INSERT INTO app.medical_doctors (name, specialty, phone, address, notes, created_at, updated_at) @"INSERT INTO app.medical_doctors (person_id, name, specialty, phone, address, notes, created_at, updated_at)
VALUES (@name, @specialty, @phone, @address, @notes, @createdAt, @updatedAt) VALUES (@personId, @name, @specialty, @phone, @address, @notes, @createdAt, @updatedAt)
RETURNING id, name, specialty, phone, address, notes, created_at, updated_at", RETURNING id, name, specialty, phone, address, notes, created_at, updated_at",
reader => new MedicalDoctor reader => new MedicalDoctor
{ {
@@ -425,11 +557,11 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
CreatedAt = reader.GetDateTime(6), CreatedAt = reader.GetDateTime(6),
UpdatedAt = reader.GetDateTime(7) UpdatedAt = reader.GetDateTime(7)
}, },
new { name, specialty, phone, address, notes, createdAt = now, updatedAt = now }); new { personId, name, specialty, phone, address, notes, createdAt = now, updatedAt = now });
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "Failed to create doctor"); logger.LogError(ex, "Failed to create doctor for person {PersonId}", personId);
return null; return null;
} }
} }
@@ -493,12 +625,16 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
// --- Conditions --- // --- Conditions ---
public async Task<List<MedicalCondition>> GetConditionsAsync(long personId) public async Task<List<MedicalCondition>> GetConditionsAsync(long? personId = null, long? accessUserId = null)
{ {
try try
{ {
var personFilter = personId.HasValue
? "person_id = @personId"
: "person_id IN (SELECT person_id FROM app.medical_people_access WHERE user_id = @accessUserId)";
return await db.ExecuteListReaderAsync( 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", $"SELECT id, person_id, name, diagnosed_date, notes, is_active, created_at, updated_at FROM app.medical_conditions WHERE {personFilter} ORDER BY name",
reader => new MedicalCondition reader => new MedicalCondition
{ {
Id = reader.GetInt64(0), Id = reader.GetInt64(0),
@@ -510,7 +646,7 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
CreatedAt = reader.GetDateTime(6), CreatedAt = reader.GetDateTime(6),
UpdatedAt = reader.GetDateTime(7) UpdatedAt = reader.GetDateTime(7)
}, },
new { personId }); new { personId = personId ?? 0L, accessUserId = accessUserId ?? 0L });
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -581,17 +717,21 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
// --- Prescriptions --- // --- Prescriptions ---
public async Task<List<MedicalPrescription>> GetPrescriptionsAsync(long personId) public async Task<List<MedicalPrescription>> GetPrescriptionsAsync(long? personId = null, long? accessUserId = null)
{ {
try try
{ {
var personFilter = personId.HasValue
? "p.person_id = @personId"
: "p.person_id IN (SELECT person_id FROM app.medical_people_access WHERE user_id = @accessUserId)";
return await db.ExecuteListReaderAsync( 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, p.rx_number, $@"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, p.rx_number,
d.name AS doctor_name, 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 (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 FROM app.medical_prescriptions p
LEFT JOIN app.medical_doctors d ON p.doctor_id = d.id LEFT JOIN app.medical_doctors d ON p.doctor_id = d.id
WHERE p.person_id = @personId WHERE {personFilter}
ORDER BY p.medication_name", ORDER BY p.medication_name",
reader => new MedicalPrescription reader => new MedicalPrescription
{ {
@@ -611,7 +751,7 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
DoctorName = reader.IsDBNull(13) ? null : reader.GetString(13), DoctorName = reader.IsDBNull(13) ? null : reader.GetString(13),
LastPickupDate = reader.IsDBNull(14) ? null : reader.GetDateTime(14) LastPickupDate = reader.IsDBNull(14) ? null : reader.GetDateTime(14)
}, },
new { personId }); new { personId = personId ?? 0L, accessUserId = accessUserId ?? 0L });
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -873,12 +1013,13 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
} }
} }
public async Task<MedicalDoctor?> FindOrCreateDoctorByNameAsync(string doctorName) public async Task<MedicalDoctor?> FindOrCreateDoctorByNameAsync(long personId, string doctorName, MedicalAiService aiService)
{ {
try try
{ {
// Step 1: Exact match
var existing = await db.ExecuteReaderAsync( var existing = await db.ExecuteReaderAsync(
"SELECT id, name, specialty, phone, address, notes, created_at, updated_at FROM app.medical_doctors WHERE LOWER(name) = LOWER(@name) LIMIT 1", "SELECT id, name, specialty, phone, address, notes, created_at, updated_at FROM app.medical_doctors WHERE person_id = @personId AND LOWER(name) = LOWER(@name) LIMIT 1",
reader => new MedicalDoctor reader => new MedicalDoctor
{ {
Id = reader.GetInt64(0), Id = reader.GetInt64(0),
@@ -890,15 +1031,29 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
CreatedAt = reader.GetDateTime(6), CreatedAt = reader.GetDateTime(6),
UpdatedAt = reader.GetDateTime(7) UpdatedAt = reader.GetDateTime(7)
}, },
new { name = doctorName }); new { personId, name = doctorName });
if (existing != null) return existing; if (existing != null) return existing;
return await CreateDoctorAsync(doctorName); // Step 2: AI fuzzy match
var allDoctors = await GetDoctorsAsync(personId);
if (allDoctors.Count > 0)
{
var existingNames = allDoctors.Select(d => d.Name).ToList();
var matchedName = await aiService.FuzzyMatchDoctorAsync(doctorName, existingNames);
if (matchedName != null)
{
var matched = allDoctors.FirstOrDefault(d => string.Equals(d.Name, matchedName, StringComparison.OrdinalIgnoreCase));
if (matched != null) return matched;
}
}
// Step 3: Create new
return await CreateDoctorAsync(personId, doctorName);
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "Failed to find or create doctor by name \"{DoctorName}\"", doctorName); logger.LogError(ex, "Failed to find or create doctor by name \"{DoctorName}\" for person {PersonId}", doctorName, personId);
return null; return null;
} }
} }
@@ -915,7 +1070,7 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
var docName = rxInfo.DoctorName ?? doctorName; var docName = rxInfo.DoctorName ?? doctorName;
if (!string.IsNullOrWhiteSpace(docName)) if (!string.IsNullOrWhiteSpace(docName))
{ {
var doctor = await FindOrCreateDoctorByNameAsync(docName.Trim()); var doctor = await FindOrCreateDoctorByNameAsync(personId, docName.Trim(), aiService);
doctorId = doctor?.Id; doctorId = doctor?.Id;
} }
@@ -1081,18 +1236,22 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
// --- Billing Providers --- // --- Billing Providers ---
public async Task<List<MedicalBillingProvider>> GetProvidersAsync(long personId) public async Task<List<MedicalBillingProvider>> GetProvidersAsync(long? personId = null, long? accessUserId = null)
{ {
try try
{ {
var personFilter = personId.HasValue
? "p.person_id = @personId"
: "p.person_id IN (SELECT person_id FROM app.medical_people_access WHERE user_id = @accessUserId)";
return await db.ExecuteListReaderAsync( return await db.ExecuteListReaderAsync(
@"SELECT p.id, p.name, p.person_id, p.notes, p.created_at, p.updated_at, $@"SELECT p.id, p.name, p.person_id, p.notes, p.created_at, p.updated_at,
COALESCE(SUM(b.total_amount), 0) AS total_charged, COALESCE(SUM(b.total_amount), 0) AS total_charged,
COALESCE((SELECT SUM(pp.amount) FROM app.medical_provider_payments pp WHERE pp.provider_id = p.id), 0) AS total_paid, COALESCE((SELECT SUM(pp.amount) FROM app.medical_provider_payments pp WHERE pp.provider_id = p.id), 0) AS total_paid,
COUNT(DISTINCT b.id) AS bill_count COUNT(DISTINCT b.id) AS bill_count
FROM app.medical_billing_providers p FROM app.medical_billing_providers p
LEFT JOIN app.medical_bills b ON b.provider_id = p.id LEFT JOIN app.medical_bills b ON b.provider_id = p.id
WHERE p.person_id = @personId WHERE {personFilter}
GROUP BY p.id, p.name, p.person_id, p.notes, p.created_at, p.updated_at GROUP BY p.id, p.name, p.person_id, p.notes, p.created_at, p.updated_at
ORDER BY p.name", ORDER BY p.name",
reader => new MedicalBillingProvider reader => new MedicalBillingProvider
@@ -1107,7 +1266,7 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
TotalPaid = reader.GetDecimal(7), TotalPaid = reader.GetDecimal(7),
BillCount = reader.GetInt32(8) BillCount = reader.GetInt32(8)
}, },
new { personId }); new { personId = personId ?? 0L, accessUserId = accessUserId ?? 0L });
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -1363,10 +1522,13 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
// --- Bills --- // --- Bills ---
public async Task<List<MedicalBill>> GetBillsAsync(long personId, long? providerId = null) public async Task<List<MedicalBill>> GetBillsAsync(long? personId = null, long? providerId = null, long? accessUserId = null)
{ {
try try
{ {
var personFilter = personId.HasValue
? "b.person_id = @personId"
: "b.person_id IN (SELECT person_id FROM app.medical_people_access WHERE user_id = @accessUserId)";
var providerFilter = providerId.HasValue ? "AND b.provider_id = @providerId" : ""; var providerFilter = providerId.HasValue ? "AND b.provider_id = @providerId" : "";
var query = $@"SELECT b.id, b.person_id, b.total_amount, b.summary, b.category, b.bill_date, b.doctor_id, b.provider_id, b.source, b.created_at, b.updated_at, var query = $@"SELECT b.id, b.person_id, b.total_amount, b.summary, b.category, b.bill_date, b.doctor_id, b.provider_id, b.source, b.created_at, b.updated_at,
@@ -1379,10 +1541,10 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
FROM app.medical_bills b FROM app.medical_bills b
LEFT JOIN app.medical_doctors d ON b.doctor_id = d.id LEFT JOIN app.medical_doctors d ON b.doctor_id = d.id
LEFT JOIN app.medical_billing_providers bp ON b.provider_id = bp.id LEFT JOIN app.medical_billing_providers bp ON b.provider_id = bp.id
WHERE b.person_id = @personId {providerFilter} WHERE {personFilter} {providerFilter}
ORDER BY b.bill_date DESC NULLS LAST, b.created_at DESC"; ORDER BY b.bill_date DESC NULLS LAST, b.created_at DESC";
return await db.ExecuteListReaderAsync(query, MapBill, new { personId, providerId }); return await db.ExecuteListReaderAsync(query, MapBill, new { personId = personId ?? 0L, accessUserId = accessUserId ?? 0L, providerId });
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -1502,26 +1664,34 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
// --- Bill Summary --- // --- Bill Summary ---
public async Task<BillSummary> GetBillSummaryAsync(long personId) public async Task<BillSummary> GetBillSummaryAsync(long? personId = null, long? accessUserId = null)
{ {
try try
{ {
var personFilter = personId.HasValue
? "b.person_id = @personId"
: "b.person_id IN (SELECT person_id FROM app.medical_people_access WHERE user_id = @accessUserId)";
var providerPersonFilter = personId.HasValue
? "prov.person_id = @personId"
: "prov.person_id IN (SELECT person_id FROM app.medical_people_access WHERE user_id = @accessUserId)";
var filterParams = new { personId = personId ?? 0L, accessUserId = accessUserId ?? 0L };
var totals = await db.ExecuteReaderAsync( var totals = await db.ExecuteReaderAsync(
@"SELECT COALESCE(SUM(b.total_amount), 0), $@"SELECT COALESCE(SUM(b.total_amount), 0),
COALESCE((SELECT SUM(pp.amount) FROM app.medical_provider_payments pp COALESCE((SELECT SUM(pp.amount) FROM app.medical_provider_payments pp
JOIN app.medical_billing_providers prov ON pp.provider_id = prov.id JOIN app.medical_billing_providers prov ON pp.provider_id = prov.id
WHERE prov.person_id = @personId), 0) WHERE {providerPersonFilter}), 0)
FROM app.medical_bills b FROM app.medical_bills b
WHERE b.person_id = @personId", WHERE {personFilter}",
reader => new { Charged = reader.GetDecimal(0), TotalPaid = reader.GetDecimal(1) }, reader => new { Charged = reader.GetDecimal(0), TotalPaid = reader.GetDecimal(1) },
new { personId }); filterParams);
var byYear = await db.ExecuteListReaderAsync( var byYear = await db.ExecuteListReaderAsync(
@"SELECT EXTRACT(YEAR FROM COALESCE(b.bill_date, b.created_at))::int AS year, $@"SELECT EXTRACT(YEAR FROM COALESCE(b.bill_date, b.created_at))::int AS year,
SUM(b.total_amount), SUM(b.total_amount),
COUNT(b.id) COUNT(b.id)
FROM app.medical_bills b FROM app.medical_bills b
WHERE b.person_id = @personId WHERE {personFilter}
GROUP BY EXTRACT(YEAR FROM COALESCE(b.bill_date, b.created_at))::int GROUP BY EXTRACT(YEAR FROM COALESCE(b.bill_date, b.created_at))::int
ORDER BY year DESC", ORDER BY year DESC",
reader => new YearBreakdown reader => new YearBreakdown
@@ -1530,15 +1700,15 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
Total = reader.GetDecimal(1), Total = reader.GetDecimal(1),
Count = reader.GetInt32(2) Count = reader.GetInt32(2)
}, },
new { personId }); filterParams);
var byProvider = await db.ExecuteListReaderAsync( var byProvider = await db.ExecuteListReaderAsync(
@"SELECT COALESCE(prov.name, 'Unassigned'), $@"SELECT COALESCE(prov.name, 'Unassigned'),
COALESCE(SUM(b.total_amount), 0), COALESCE(SUM(b.total_amount), 0),
COUNT(b.id) COUNT(b.id)
FROM app.medical_bills b FROM app.medical_bills b
LEFT JOIN app.medical_billing_providers prov ON b.provider_id = prov.id LEFT JOIN app.medical_billing_providers prov ON b.provider_id = prov.id
WHERE b.person_id = @personId WHERE {personFilter}
GROUP BY COALESCE(prov.name, 'Unassigned') GROUP BY COALESCE(prov.name, 'Unassigned')
ORDER BY COALESCE(SUM(b.total_amount), 0) DESC", ORDER BY COALESCE(SUM(b.total_amount), 0) DESC",
reader => new ProviderBreakdown reader => new ProviderBreakdown
@@ -1547,7 +1717,7 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
Total = reader.GetDecimal(1), Total = reader.GetDecimal(1),
Count = reader.GetInt32(2) Count = reader.GetInt32(2)
}, },
new { personId }); filterParams);
var charged = totals?.Charged ?? 0; var charged = totals?.Charged ?? 0;
var totalPaid = totals?.TotalPaid ?? 0; var totalPaid = totals?.TotalPaid ?? 0;
@@ -2167,30 +2337,34 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
// --- Timeline --- // --- Timeline ---
public async Task<List<TimelineEvent>> GetTimelineAsync(long personId, int offset = 0, int limit = 100) public async Task<List<TimelineEvent>> GetTimelineAsync(long? personId = null, long? accessUserId = null, int offset = 0, int limit = 100)
{ {
try try
{ {
var personFilter = personId.HasValue
? "= @personId"
: "IN (SELECT person_id FROM app.medical_people_access WHERE user_id = @accessUserId)";
return await db.ExecuteListReaderAsync( return await db.ExecuteListReaderAsync(
@"SELECT event_type, id, label, detail, sub_type, event_date, doctor_id, created_at $@"SELECT event_type, id, person_id, label, detail, sub_type, event_date, doctor_id, created_at
FROM ( FROM (
SELECT 'document' AS event_type, d.id, COALESCE(d.title, d.file_name) AS label, d.description AS detail, SELECT 'document' AS event_type, d.id, d.person_id, COALESCE(d.title, d.file_name) AS label, d.description AS detail,
d.classification AS sub_type, d.document_date AS event_date, d.doctor_id, d.created_at d.classification AS sub_type, d.document_date AS event_date, d.doctor_id, d.created_at
FROM app.medical_documents d WHERE d.person_id = @personId FROM app.medical_documents d WHERE d.person_id {personFilter}
UNION ALL UNION ALL
SELECT 'condition', c.id, c.name, c.notes, SELECT 'condition', c.id, c.person_id, c.name, c.notes,
CASE WHEN c.is_active THEN 'active' ELSE 'resolved' END, c.diagnosed_date, NULL, c.created_at CASE WHEN c.is_active THEN 'active' ELSE 'resolved' END, c.diagnosed_date, NULL, c.created_at
FROM app.medical_conditions c WHERE c.person_id = @personId FROM app.medical_conditions c WHERE c.person_id {personFilter}
UNION ALL UNION ALL
SELECT 'prescription', p.id, p.medication_name, CONCAT_WS(' - ', p.dosage, p.frequency), SELECT 'prescription', p.id, p.person_id, p.medication_name, CONCAT_WS(' - ', p.dosage, p.frequency),
CASE WHEN p.is_active THEN 'active' ELSE 'ended' END, p.start_date, p.doctor_id, p.created_at CASE WHEN p.is_active THEN 'active' ELSE 'ended' END, p.start_date, p.doctor_id, p.created_at
FROM app.medical_prescriptions p WHERE p.person_id = @personId FROM app.medical_prescriptions p WHERE p.person_id {personFilter}
UNION ALL UNION ALL
SELECT 'bill', b.id, b.summary, bp.name, SELECT 'bill', b.id, b.person_id, b.summary, bp.name,
b.category, b.bill_date, b.doctor_id, b.created_at b.category, b.bill_date, b.doctor_id, b.created_at
FROM app.medical_bills b FROM app.medical_bills b
LEFT JOIN app.medical_billing_providers bp ON b.provider_id = bp.id LEFT JOIN app.medical_billing_providers bp ON b.provider_id = bp.id
WHERE b.person_id = @personId WHERE b.person_id {personFilter}
) AS timeline ) AS timeline
ORDER BY COALESCE(event_date, created_at) DESC ORDER BY COALESCE(event_date, created_at) DESC
LIMIT @limit OFFSET @offset", LIMIT @limit OFFSET @offset",
@@ -2198,14 +2372,15 @@ public class MedicalDocsService(DbExecutor db, IWebHostEnvironment environment,
{ {
EventType = reader.GetString(0), EventType = reader.GetString(0),
Id = reader.GetInt64(1), Id = reader.GetInt64(1),
Label = reader.IsDBNull(2) ? null : reader.GetString(2), PersonId = reader.GetInt64(2),
Detail = reader.IsDBNull(3) ? null : reader.GetString(3), Label = reader.IsDBNull(3) ? null : reader.GetString(3),
SubType = reader.IsDBNull(4) ? null : reader.GetString(4), Detail = reader.IsDBNull(4) ? null : reader.GetString(4),
EventDate = reader.IsDBNull(5) ? null : reader.GetDateTime(5), SubType = reader.IsDBNull(5) ? null : reader.GetString(5),
DoctorId = reader.IsDBNull(6) ? null : reader.GetInt64(6), EventDate = reader.IsDBNull(6) ? null : reader.GetDateTime(6),
CreatedAt = reader.GetDateTime(7) DoctorId = reader.IsDBNull(7) ? null : reader.GetInt64(7),
CreatedAt = reader.GetDateTime(8)
}, },
new { personId, limit, offset }); new { personId = personId ?? 0L, accessUserId = accessUserId ?? 0L, limit, offset });
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -0,0 +1,43 @@
using System.Text.Json;
using Media.JoshHeaps.Net.Models;
namespace Media.JoshHeaps.Net.Services;
public class ThemeService(DbExecutor db)
{
public async Task<UserThemeOverrides?> GetUserThemeAsync(long userId)
{
return await db.ExecuteReaderAsync<UserThemeOverrides?>(
@"SELECT id, user_id, base_theme, color_overrides::text, created_at, updated_at
FROM app.user_theme_overrides
WHERE user_id = @userId",
reader =>
{
if (!reader.Read()) return null;
var overridesJson = reader.GetString(3);
return new UserThemeOverrides
{
Id = reader.GetInt64(0),
UserId = reader.GetInt64(1),
BaseTheme = reader.GetString(2),
ColorOverrides = JsonSerializer.Deserialize<Dictionary<string, string>>(overridesJson) ?? new(),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5)
};
},
new { userId });
}
public async Task SaveUserThemeAsync(long userId, string baseTheme, Dictionary<string, string> colorOverrides)
{
var overridesJson = JsonSerializer.Serialize(colorOverrides);
await db.ExecuteNonQueryAsync(
@"INSERT INTO app.user_theme_overrides (user_id, base_theme, color_overrides, created_at, updated_at)
VALUES (@userId, @baseTheme, @overridesJson::jsonb, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON CONFLICT (user_id) DO UPDATE
SET base_theme = @baseTheme,
color_overrides = @overridesJson::jsonb,
updated_at = CURRENT_TIMESTAMP",
new { userId, baseTheme, overridesJson });
}
}
+23
View File
@@ -152,6 +152,29 @@
display: block; display: block;
} }
.form-options {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
}
.form-options .checkbox-wrapper {
margin-bottom: 0;
}
.forgot-password-link {
color: var(--text-secondary);
font-size: 13px;
text-decoration: none;
transition: color 0.2s ease;
}
.forgot-password-link:hover {
color: var(--accent-primary);
text-decoration: underline;
}
.checkbox-wrapper { .checkbox-wrapper {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -323,6 +323,39 @@
color: #fff; color: #fff;
} }
.person-pill-row {
display: flex;
align-items: center;
gap: 4px;
}
.person-pill-row .person-pill {
flex: 1;
min-width: 0;
}
.person-share-btn {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
background: transparent;
border: 1px solid var(--border-primary);
border-radius: 50%;
color: var(--text-muted);
cursor: pointer;
transition: all 0.2s ease;
flex-shrink: 0;
}
.person-share-btn:hover {
border-color: var(--accent-primary);
color: var(--accent-primary);
background: var(--bg-tertiary);
}
/* ======================== */ /* ======================== */
/* Form Inputs */ /* Form Inputs */
/* ======================== */ /* ======================== */
@@ -1494,6 +1527,26 @@
line-height: 1.6; line-height: 1.6;
} }
/* ======================== */
/* All-mode (read-only) */
/* ======================== */
.all-mode .add-form-toggle { display: none; }
.all-mode .add-form-collapsible { display: none; }
.person-badge {
display: inline-block;
padding: 1px 7px;
background: var(--accent-primary);
color: #fff;
border-radius: 10px;
font-size: 10px;
font-weight: 600;
letter-spacing: 0.3px;
vertical-align: middle;
margin-right: 4px;
}
/* ======================== */ /* ======================== */
/* Responsive (<=768px) */ /* Responsive (<=768px) */
/* ======================== */ /* ======================== */
+140
View File
@@ -0,0 +1,140 @@
.profile-container {
max-width: 800px;
margin: 40px auto;
padding: 0 20px;
}
.profile-section {
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
padding: 24px;
margin-bottom: 20px;
}
.profile-section h2 {
margin: 0 0 20px 0;
font-size: 18px;
font-weight: 600;
color: var(--text-primary);
border-bottom: 1px solid var(--border-primary);
padding-bottom: 12px;
}
.profile-field {
margin-bottom: 16px;
}
.profile-field label {
display: block;
font-weight: 500;
color: var(--text-secondary);
margin-bottom: 4px;
font-size: 14px;
}
.profile-field-value {
color: var(--text-primary);
font-size: 15px;
}
.theme-toggle-container {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 0;
}
.theme-toggle-label {
display: flex;
flex-direction: column;
}
.theme-toggle-label strong {
color: var(--text-primary);
font-size: 15px;
margin-bottom: 4px;
}
.theme-toggle-label span {
color: var(--text-secondary);
font-size: 13px;
}
.toggle-switch {
position: relative;
display: inline-block;
width: 50px;
height: 26px;
}
.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--bg-tertiary);
border: 1px solid var(--border-primary);
transition: 0.3s;
border-radius: 34px;
}
.toggle-slider:before {
position: absolute;
content: "";
height: 18px;
width: 18px;
left: 3px;
bottom: 3px;
background-color: var(--text-secondary);
transition: 0.3s;
border-radius: 50%;
}
input:checked + .toggle-slider {
background-color: var(--accent-primary);
border-color: var(--accent-primary);
}
input:checked + .toggle-slider:before {
transform: translateX(24px);
background-color: var(--bg-primary);
}
.back-link {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--accent-primary);
text-decoration: none;
font-size: 14px;
margin-bottom: 20px;
transition: color 0.2s ease;
}
.back-link:hover {
color: var(--accent-hover);
}
.customize-btn {
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 6px;
color: var(--text-primary);
padding: 8px 16px;
font-size: 14px;
cursor: pointer;
transition: background 0.15s;
}
.customize-btn:hover {
background: var(--bg-hover);
}
@@ -0,0 +1,214 @@
#theme-customizer-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
z-index: 10000;
display: flex;
align-items: center;
justify-content: center;
}
#theme-customizer-modal {
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: 8px;
width: 90vw;
max-width: 1200px;
height: 90vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.tc-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 20px;
border-bottom: 1px solid var(--border-primary);
flex-shrink: 0;
}
.tc-header h3 {
margin: 0;
font-size: 18px;
color: var(--text-primary);
}
.tc-close-btn {
background: none;
border: none;
font-size: 24px;
color: var(--text-secondary);
cursor: pointer;
line-height: 1;
}
.tc-close-btn:hover {
color: var(--text-primary);
}
.tc-controls {
padding: 12px 20px;
border-bottom: 1px solid var(--border-primary);
flex-shrink: 0;
}
.tc-row {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 8px;
}
.tc-row:last-child {
margin-bottom: 0;
}
.tc-row label {
min-width: 110px;
font-size: 14px;
color: var(--text-secondary);
font-weight: 500;
}
.tc-row select,
.tc-row input[type="text"] {
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 4px;
color: var(--text-primary);
padding: 6px 10px;
font-size: 14px;
}
.tc-row select {
flex: 1;
max-width: 280px;
}
.tc-picker-row input[type="color"] {
width: 40px;
height: 34px;
border: 1px solid var(--border-primary);
border-radius: 4px;
cursor: pointer;
padding: 2px;
background: var(--bg-secondary);
}
.tc-picker-row input[type="text"] {
width: 90px;
font-family: monospace;
}
.tc-swatches {
display: flex;
gap: 6px;
flex-wrap: wrap;
margin: 8px 0 4px;
}
.tc-swatch {
width: 28px;
height: 28px;
border-radius: 4px;
border: 2px solid var(--border-secondary);
cursor: pointer;
transition: border-color 0.15s;
}
.tc-swatch:hover {
border-color: var(--text-secondary);
}
.tc-swatch-overridden {
border-color: var(--accent-primary);
border-width: 2px;
}
.tc-swatch-selected {
outline: 2px solid var(--accent-primary);
outline-offset: 2px;
}
.tc-btn-row {
display: flex;
gap: 10px;
margin-top: 8px;
}
.tc-btn {
padding: 8px 16px;
border-radius: 6px;
border: 1px solid var(--border-primary);
font-size: 14px;
cursor: pointer;
background: var(--bg-secondary);
color: var(--text-primary);
transition: background 0.15s;
}
.tc-btn:hover {
background: var(--bg-hover);
}
.tc-btn-save {
background: var(--accent-primary);
color: #fff;
border-color: var(--accent-primary);
}
.tc-btn-save:hover {
background: var(--accent-hover);
}
.tc-btn-reset {
margin-left: auto;
color: var(--danger);
border-color: var(--danger);
}
.tc-btn-reset:hover {
background: var(--danger);
color: #fff;
}
.tc-btn-small {
padding: 4px 10px;
font-size: 12px;
}
.tc-preview {
flex: 1;
min-height: 0;
padding: 0 20px 20px;
display: flex;
flex-direction: column;
}
.tc-preview iframe {
width: 100%;
flex: 1;
min-height: 0;
border: 1px solid var(--border-primary);
border-radius: 4px;
}
@media (max-width: 600px) {
#theme-customizer-modal {
width: 98vw;
height: 98vh;
}
.tc-row {
flex-wrap: wrap;
}
.tc-row label {
min-width: auto;
}
}
+136
View File
@@ -336,9 +336,145 @@ function initRegisterForm() {
}); });
} }
// Password reset form validation
function initPasswordResetForm() {
const form = document.getElementById('resetPasswordForm');
if (!form) return;
const passwordInput = document.getElementById('newPassword');
const confirmPasswordInput = document.getElementById('confirmPassword');
if (passwordInput) {
passwordInput.addEventListener('input', function() {
checkPasswordStrength(this.value);
if (this.value && validatePassword(this.value)) {
clearError(this);
}
if (confirmPasswordInput && confirmPasswordInput.value) {
if (confirmPasswordInput.value === this.value) {
clearError(confirmPasswordInput);
} else {
showError(confirmPasswordInput, 'Passwords do not match');
}
}
});
passwordInput.addEventListener('blur', function() {
if (!this.value) {
showError(this, 'Password is required');
} else if (!validatePassword(this.value)) {
showError(this, 'Password must be at least 8 characters');
} else {
clearError(this);
}
});
}
if (confirmPasswordInput) {
confirmPasswordInput.addEventListener('input', function() {
if (passwordInput && this.value === passwordInput.value) {
clearError(this);
}
});
confirmPasswordInput.addEventListener('blur', function() {
if (!this.value) {
showError(this, 'Please confirm your password');
} else if (passwordInput && this.value !== passwordInput.value) {
showError(this, 'Passwords do not match');
} else {
clearError(this);
}
});
}
form.addEventListener('submit', function(e) {
e.preventDefault();
let isValid = true;
if (!passwordInput.value) {
showError(passwordInput, 'Password is required');
isValid = false;
} else if (!validatePassword(passwordInput.value)) {
showError(passwordInput, 'Password must be at least 8 characters');
isValid = false;
} else {
clearError(passwordInput);
}
if (!confirmPasswordInput.value) {
showError(confirmPasswordInput, 'Please confirm your password');
isValid = false;
} else if (confirmPasswordInput.value !== passwordInput.value) {
showError(confirmPasswordInput, 'Passwords do not match');
isValid = false;
} else {
clearError(confirmPasswordInput);
}
if (isValid) {
const submitBtn = form.querySelector('button[type="submit"]');
submitBtn.disabled = true;
submitBtn.innerHTML = '<span class="spinner"></span> Resetting...';
form.submit();
}
});
}
// Request reset form validation
function initRequestResetForm() {
const form = document.getElementById('requestResetForm');
if (!form) return;
const emailInput = document.getElementById('email');
if (emailInput) {
emailInput.addEventListener('blur', function() {
if (!this.value.trim()) {
showError(this, 'Email is required');
} else if (!validateEmail(this.value)) {
showError(this, 'Please enter a valid email address');
} else {
clearError(this);
}
});
emailInput.addEventListener('input', function() {
if (this.value.trim() && validateEmail(this.value)) {
clearError(this);
}
});
}
form.addEventListener('submit', function(e) {
e.preventDefault();
if (!emailInput.value.trim()) {
showError(emailInput, 'Email is required');
return;
}
if (!validateEmail(emailInput.value)) {
showError(emailInput, 'Please enter a valid email address');
return;
}
clearError(emailInput);
const submitBtn = form.querySelector('button[type="submit"]');
submitBtn.disabled = true;
submitBtn.innerHTML = '<span class="spinner"></span> Sending...';
form.submit();
});
}
// Initialize on page load // Initialize on page load
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
initPasswordToggles(); initPasswordToggles();
initLoginForm(); initLoginForm();
initRegisterForm(); initRegisterForm();
initPasswordResetForm();
initRequestResetForm();
}); });
@@ -4,11 +4,10 @@
// --- Providers --- // --- Providers ---
app.loadBills = async function () { app.loadBills = async function () {
if (!state.selectedPersonId) return; const personParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const [providersRes, summaryRes] = await Promise.all([ const [providersRes, summaryRes] = await Promise.all([
fetch(`${app.API}/providers?personId=${state.selectedPersonId}`), fetch(`${app.API}/providers${personParam}`),
fetch(`${app.API}/bills/summary?personId=${state.selectedPersonId}`) fetch(`${app.API}/bills/summary${personParam}`)
]); ]);
if (providersRes.ok) { if (providersRes.ok) {
@@ -78,7 +77,8 @@
if (!container) return; if (!container) return;
// Fetch unassigned bills // Fetch unassigned bills
const unassignedRes = await fetch(`${app.API}/bills?personId=${state.selectedPersonId}`); const unassignedBillParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const unassignedRes = await fetch(`${app.API}/bills${unassignedBillParam}`);
let unassignedBills = []; let unassignedBills = [];
if (unassignedRes.ok) { if (unassignedRes.ok) {
const allBills = await unassignedRes.json(); const allBills = await unassignedRes.json();
@@ -99,7 +99,7 @@
<div class="prescription-info"> <div class="prescription-info">
<div class="prescription-name"> <div class="prescription-name">
<span class="expand-btn" id="provider-expand-${p.id}">&#9654;</span> <span class="expand-btn" id="provider-expand-${p.id}">&#9654;</span>
${app.escapeHtml(p.name)} ${app.personBadge(p.personId)}${app.escapeHtml(p.name)}
<span class="bill-status ${statusClass}">${statusLabel}</span> <span class="bill-status ${statusClass}">${statusLabel}</span>
</div> </div>
<div class="prescription-meta"> <div class="prescription-meta">
@@ -164,8 +164,9 @@
const section = document.getElementById(`provider-details-${providerId}`); const section = document.getElementById(`provider-details-${providerId}`);
if (!section) return; if (!section) return;
const billsParam = state.selectedPersonId ? `personId=${state.selectedPersonId}&` : '';
const [billsRes, paymentsRes] = await Promise.all([ const [billsRes, paymentsRes] = await Promise.all([
fetch(`${app.API}/bills?personId=${state.selectedPersonId}&providerId=${providerId}`), fetch(`${app.API}/bills?${billsParam}providerId=${providerId}`),
fetch(`${app.API}/providers/${providerId}/payments`) fetch(`${app.API}/providers/${providerId}/payments`)
]); ]);
@@ -192,6 +193,8 @@
return `<option value="${d.id}">${app.escapeHtml(label)}</option>`; return `<option value="${d.id}">${app.escapeHtml(label)}</option>`;
}).join(''); }).join('');
const showForms = state.selectedPersonId ? '' : 'style="display:none"';
const billsHtml = bills.map(b => { const billsHtml = bills.map(b => {
const meta = []; const meta = [];
if (b.billDate) meta.push(app.formatDate(b.billDate)); if (b.billDate) meta.push(app.formatDate(b.billDate));
@@ -213,7 +216,7 @@
${docNames ? `<div style="margin-left:18px;">${docNames}</div>` : ''} ${docNames ? `<div style="margin-left:18px;">${docNames}</div>` : ''}
<div id="bill-charges-${b.id}" style="display:none;margin-left:18px;margin-top:4px;"> <div id="bill-charges-${b.id}" style="display:none;margin-left:18px;margin-top:4px;">
<div class="charges-header">Charges</div> <div class="charges-header">Charges</div>
<div class="pickup-form"> <div class="pickup-form" ${showForms}>
<div class="inline-form-row"> <div class="inline-form-row">
<input type="text" id="chargeDesc-${b.id}" placeholder="Description *" class="form-input" /> <input type="text" id="chargeDesc-${b.id}" placeholder="Description *" class="form-input" />
<input type="number" id="chargeAmount-${b.id}" placeholder="Amount *" class="form-input" step="0.01" min="0.01" /> <input type="number" id="chargeAmount-${b.id}" placeholder="Amount *" class="form-input" step="0.01" min="0.01" />
@@ -221,8 +224,8 @@
</div> </div>
</div> </div>
<div class="charge-list" id="chargeList-${b.id}"></div> <div class="charge-list" id="chargeList-${b.id}"></div>
<div class="section-divider"></div> <div class="section-divider" ${showForms}></div>
<div class="pickup-form"> <div class="pickup-form" ${showForms}>
<div class="inline-form-row"> <div class="inline-form-row">
<select id="linkDoc-${b.id}" class="form-input"> <select id="linkDoc-${b.id}" class="form-input">
<option value="">Link document...</option> <option value="">Link document...</option>
@@ -251,7 +254,7 @@
section.innerHTML = ` section.innerHTML = `
<div class="charges-section"> <div class="charges-section">
<div class="charges-header">Bills</div> <div class="charges-header">Bills</div>
<div class="pickup-form"> <div class="pickup-form" ${showForms}>
<div class="inline-form-row"> <div class="inline-form-row">
<input type="number" id="newBillAmount-${providerId}" placeholder="Amount *" class="form-input" step="0.01" min="0.01" /> <input type="number" id="newBillAmount-${providerId}" placeholder="Amount *" class="form-input" step="0.01" min="0.01" />
<input type="text" id="newBillSummary-${providerId}" placeholder="Summary" class="form-input" /> <input type="text" id="newBillSummary-${providerId}" placeholder="Summary" class="form-input" />
@@ -265,7 +268,7 @@
<div class="section-divider"></div> <div class="section-divider"></div>
<div class="payments-section"> <div class="payments-section">
<div class="charges-header">Payments</div> <div class="charges-header">Payments</div>
<div class="pickup-form"> <div class="pickup-form" ${showForms}>
<div class="inline-form-row"> <div class="inline-form-row">
<input type="number" id="provPayAmount-${providerId}" placeholder="Amount *" class="form-input" step="0.01" min="0.01" /> <input type="number" id="provPayAmount-${providerId}" placeholder="Amount *" class="form-input" step="0.01" min="0.01" />
<input type="date" id="provPayDate-${providerId}" class="form-input" title="Payment date" /> <input type="date" id="provPayDate-${providerId}" class="form-input" title="Payment date" />
@@ -281,7 +284,8 @@
const section = document.getElementById('provider-details-unassigned'); const section = document.getElementById('provider-details-unassigned');
if (!section) return; if (!section) return;
const res = await fetch(`${app.API}/bills?personId=${state.selectedPersonId}`); const unassignedParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const res = await fetch(`${app.API}/bills${unassignedParam}`);
if (!res.ok) return; if (!res.ok) return;
const allBills = await res.json(); const allBills = await res.json();
const bills = allBills.filter(b => !b.providerId); const bills = allBills.filter(b => !b.providerId);
@@ -531,7 +535,8 @@
if (!providerId) { alert('Select a provider'); return; } if (!providerId) { alert('Select a provider'); return; }
// Get current bill details first // Get current bill details first
const getRes = await fetch(`${app.API}/bills?personId=${state.selectedPersonId}`); const assignParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const getRes = await fetch(`${app.API}/bills${assignParam}`);
if (!getRes.ok) return; if (!getRes.ok) return;
const allBills = await getRes.json(); const allBills = await getRes.json();
const bill = allBills.find(b => b.id === billId); const bill = allBills.find(b => b.id === billId);
@@ -561,9 +566,10 @@
app.refreshProvider = async function (providerId) { app.refreshProvider = async function (providerId) {
// Refresh the summary and provider header, then reload details // Refresh the summary and provider header, then reload details
const refreshParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const [providersRes, summaryRes] = await Promise.all([ const [providersRes, summaryRes] = await Promise.all([
fetch(`${app.API}/providers?personId=${state.selectedPersonId}`), fetch(`${app.API}/providers${refreshParam}`),
fetch(`${app.API}/bills/summary?personId=${state.selectedPersonId}`) fetch(`${app.API}/bills/summary${refreshParam}`)
]); ]);
if (providersRes.ok) { if (providersRes.ok) {
@@ -2,8 +2,8 @@
const { state } = app; const { state } = app;
app.loadConditions = async function () { app.loadConditions = async function () {
if (!state.selectedPersonId) return; const personParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const res = await fetch(`${app.API}/conditions?personId=${state.selectedPersonId}`); const res = await fetch(`${app.API}/conditions${personParam}`);
if (!res.ok) return; if (!res.ok) return;
const conditions = await res.json(); const conditions = await res.json();
app.renderConditions(conditions); app.renderConditions(conditions);
@@ -24,7 +24,7 @@
: '<span class="badge-inactive">Inactive</span>'; : '<span class="badge-inactive">Inactive</span>';
return `<div class="condition-item" id="condition-${c.id}"> return `<div class="condition-item" id="condition-${c.id}">
<div class="condition-info"> <div class="condition-info">
<div class="condition-name">${app.escapeHtml(c.name)} ${statusBadge}</div> <div class="condition-name">${app.personBadge(c.personId)}${app.escapeHtml(c.name)} ${statusBadge}</div>
${meta.length ? `<div class="condition-meta">${meta.join(' &middot; ')}</div>` : ''} ${meta.length ? `<div class="condition-meta">${meta.join(' &middot; ')}</div>` : ''}
${c.notes ? `<div class="condition-meta">${app.escapeHtml(c.notes)}</div>` : ''} ${c.notes ? `<div class="condition-meta">${app.escapeHtml(c.notes)}</div>` : ''}
</div> </div>
@@ -64,7 +64,8 @@
}; };
app.toggleConditionActive = async function (id, isActive) { app.toggleConditionActive = async function (id, isActive) {
const res = await fetch(`${app.API}/conditions?personId=${state.selectedPersonId}`); const toggleParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const res = await fetch(`${app.API}/conditions${toggleParam}`);
if (!res.ok) return; if (!res.ok) return;
const conditions = await res.json(); const conditions = await res.json();
const condition = conditions.find(c => c.id === id); const condition = conditions.find(c => c.id === id);
@@ -2,7 +2,8 @@
const { state } = app; const { state } = app;
app.loadDoctors = async function () { app.loadDoctors = async function () {
const res = await fetch(`${app.API}/doctors`); const personParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const res = await fetch(`${app.API}/doctors${personParam}`);
if (!res.ok) return; if (!res.ok) return;
state.doctors = await res.json(); state.doctors = await res.json();
app.renderDoctors(); app.renderDoctors();
@@ -26,7 +27,7 @@
return `<div class="doctor-card-wrapper" id="doctor-wrapper-${doc.id}"> return `<div class="doctor-card-wrapper" id="doctor-wrapper-${doc.id}">
<div class="doctor-card" id="doctor-${doc.id}"> <div class="doctor-card" id="doctor-${doc.id}">
<div class="doctor-info"> <div class="doctor-info">
<div class="doctor-name">${app.escapeHtml(doc.name)}</div> <div class="doctor-name">${app.personBadge(doc.personId)}${app.escapeHtml(doc.name)}</div>
<div class="doctor-details">${details.map(d => app.escapeHtml(d)).join(' &middot; ')}</div> <div class="doctor-details">${details.map(d => app.escapeHtml(d)).join(' &middot; ')}</div>
${doc.notes ? `<div class="doctor-notes">${app.escapeHtml(doc.notes)}</div>` : ''} ${doc.notes ? `<div class="doctor-notes">${app.escapeHtml(doc.notes)}</div>` : ''}
</div> </div>
@@ -68,6 +69,7 @@
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
personId: state.selectedPersonId,
name, name,
specialty: document.getElementById('newDoctorSpecialty').value.trim() || null, specialty: document.getElementById('newDoctorSpecialty').value.trim() || null,
phone: document.getElementById('newDoctorPhone').value.trim() || null, phone: document.getElementById('newDoctorPhone').value.trim() || null,
@@ -5,7 +5,7 @@
app.buildFilterQuery = function () { app.buildFilterQuery = function () {
const params = new URLSearchParams(); const params = new URLSearchParams();
params.set('personId', state.selectedPersonId); if (state.selectedPersonId) params.set('personId', state.selectedPersonId);
const search = document.getElementById('filterSearch').value.trim(); const search = document.getElementById('filterSearch').value.trim();
if (search) params.set('search', search); if (search) params.set('search', search);
@@ -47,8 +47,8 @@
}; };
app.loadFilterTags = async function () { app.loadFilterTags = async function () {
if (!state.selectedPersonId) return; const personParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const res = await fetch(`${app.API}/tags?personId=${state.selectedPersonId}`); const res = await fetch(`${app.API}/tags${personParam}`);
if (!res.ok) return; if (!res.ok) return;
const tags = await res.json(); const tags = await res.json();
const select = document.getElementById('filterTag'); const select = document.getElementById('filterTag');
@@ -59,8 +59,8 @@
}; };
app.loadFilterConditions = async function () { app.loadFilterConditions = async function () {
if (!state.selectedPersonId) return; const personParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const res = await fetch(`${app.API}/conditions?personId=${state.selectedPersonId}`); const res = await fetch(`${app.API}/conditions${personParam}`);
if (!res.ok) return; if (!res.ok) return;
const conditions = await res.json(); const conditions = await res.json();
const select = document.getElementById('filterCondition'); const select = document.getElementById('filterCondition');
@@ -93,8 +93,6 @@
// --- Documents --- // --- Documents ---
app.loadDocuments = async function () { app.loadDocuments = async function () {
if (!state.selectedPersonId) return;
const query = app.buildFilterQuery(); const query = app.buildFilterQuery();
const res = await fetch(`${app.API}/documents/search?${query}`); const res = await fetch(`${app.API}/documents/search?${query}`);
if (!res.ok) return; if (!res.ok) return;
@@ -172,7 +170,7 @@
<div class="doc-info"> <div class="doc-info">
<div class="doc-title"> <div class="doc-title">
<span class="expand-btn" id="doc-expand-${doc.id}">&#9654;</span> <span class="expand-btn" id="doc-expand-${doc.id}">&#9654;</span>
${app.escapeHtml(displayTitle)} ${app.personBadge(doc.personId)}${app.escapeHtml(displayTitle)}
</div> </div>
<div class="doc-meta"> <div class="doc-meta">
<span>${meta.join(' &middot; ')}</span> <span>${meta.join(' &middot; ')}</span>
@@ -1,7 +1,6 @@
(function (app) { (function (app) {
document.addEventListener('DOMContentLoaded', async function () { document.addEventListener('DOMContentLoaded', async function () {
await app.loadPeople(); await app.loadPeople();
await app.loadDoctors();
// Add person // Add person
document.getElementById('addPersonBtn').addEventListener('click', () => app.addPerson()); document.getElementById('addPersonBtn').addEventListener('click', () => app.addPerson());
@@ -49,8 +48,7 @@
document.getElementById(id).addEventListener('change', () => app.loadDocuments()); document.getElementById(id).addEventListener('change', () => app.loadDocuments());
}); });
// Default state // Default: load all-persons view
app.switchMainTab('doctors'); app.selectAll();
app.updateTabStates();
}); });
})(MedDocs); })(MedDocs);
@@ -10,8 +10,16 @@
app.renderPeople = function () { app.renderPeople = function () {
const container = document.getElementById('peopleList'); const container = document.getElementById('peopleList');
container.innerHTML = state.people.map(p => const allPill = `<div class="person-pill-row">
`<button class="person-pill ${p.id === state.selectedPersonId ? 'active' : ''}" onclick="medDocsSelectPerson(${p.id})">${app.escapeHtml(p.name)}</button>` <button class="person-pill ${!state.selectedPersonId ? 'active' : ''}" onclick="medDocsSelectAll()">All</button>
</div>`;
container.innerHTML = allPill + state.people.map(p =>
`<div class="person-pill-row">
<button class="person-pill ${p.id === state.selectedPersonId ? 'active' : ''}" onclick="medDocsSelectPerson(${p.id})">${app.escapeHtml(p.name)}</button>
<button class="person-share-btn" onclick="medDocsOpenShareModal(${p.id}, event)" title="Share access">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><line x1="19" y1="8" x2="19" y2="14"></line><line x1="22" y1="11" x2="16" y2="11"></line></svg>
</button>
</div>`
).join(''); ).join('');
}; };
@@ -42,6 +50,7 @@
state.selectedPersonId = personId; state.selectedPersonId = personId;
app.renderPeople(); app.renderPeople();
document.querySelector('.medical-main').classList.remove('all-mode');
document.getElementById('summaryCards').style.display = ''; document.getElementById('summaryCards').style.display = '';
document.getElementById('filterBar').style.display = ''; document.getElementById('filterBar').style.display = '';
app.updateTabStates(); app.updateTabStates();
@@ -53,6 +62,7 @@
app.populateFilterDoctorDropdown(); app.populateFilterDoctorDropdown();
app.loadDocuments(); app.loadDocuments();
app.loadDoctors();
app.loadConditions(); app.loadConditions();
app.loadPrescriptions(); app.loadPrescriptions();
app.loadBills(); app.loadBills();
@@ -61,5 +71,112 @@
app.switchMainTab('documents'); app.switchMainTab('documents');
}; };
app.selectAll = function () {
state.selectedPersonId = null;
app.renderPeople();
document.querySelector('.medical-main').classList.add('all-mode');
document.getElementById('summaryCards').style.display = '';
document.getElementById('filterBar').style.display = '';
app.updateTabStates();
app.clearFilters(false);
app.loadFilterTags();
app.loadFilterConditions();
app.populateFilterDoctorDropdown();
app.loadDocuments();
app.loadDoctors();
app.loadConditions();
app.loadPrescriptions();
app.loadBills();
app.loadTimeline();
app.switchMainTab('documents');
};
// --- Share Access ---
app.openShareModal = async function (personId, event) {
event.stopPropagation();
state.sharePersonId = personId;
document.getElementById('shareAccessOverlay').style.display = '';
document.getElementById('shareUsername').value = '';
await app.loadShareAccess(personId);
};
app.closeShareModal = function (event) {
if (event && event.target !== event.currentTarget) return;
document.getElementById('shareAccessOverlay').style.display = 'none';
state.sharePersonId = null;
};
app.loadShareAccess = async function (personId) {
const container = document.getElementById('shareAccessList');
container.innerHTML = '<div style="color:var(--text-muted);">Loading...</div>';
const res = await fetch(`${app.API}/people/${personId}/access`);
if (!res.ok) {
container.innerHTML = '<div style="color:var(--text-muted);">Failed to load access list</div>';
return;
}
const users = await res.json();
state.shareAccessUsers = users;
if (users.length === 0) {
container.innerHTML = '<div style="color:var(--text-muted);">No users have access</div>';
return;
}
container.innerHTML = users.map(u =>
`<div style="display:flex;align-items:center;justify-content:space-between;padding:0.4rem 0;border-bottom:1px solid var(--border-primary);">
<span>${app.escapeHtml(u.username)}</span>
<button class="btn btn-danger btn-sm" onclick="medDocsRevokeAccess(${personId}, ${u.id})" ${users.length <= 1 ? 'disabled title="Cannot remove the last user"' : ''} style="padding:0.15rem 0.5rem;font-size:0.75rem;">&times;</button>
</div>`
).join('');
};
app.grantAccess = async function () {
const input = document.getElementById('shareUsername');
const username = input.value.trim();
if (!username || !state.sharePersonId) return;
const res = await fetch(`${app.API}/people/${state.sharePersonId}/access`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username })
});
if (!res.ok) {
const err = await res.json();
alert(err.error || 'Failed to grant access');
return;
}
input.value = '';
await app.loadShareAccess(state.sharePersonId);
};
app.revokeAccess = async function (personId, targetUserId) {
const res = await fetch(`${app.API}/people/${personId}/access/${targetUserId}`, {
method: 'DELETE'
});
if (!res.ok) {
const err = await res.json();
alert(err.error || 'Failed to revoke access');
return;
}
await app.loadShareAccess(personId);
};
window.medDocsSelectPerson = (id) => app.selectPerson(id); window.medDocsSelectPerson = (id) => app.selectPerson(id);
window.medDocsSelectAll = () => app.selectAll();
window.medDocsOpenShareModal = (id, event) => app.openShareModal(id, event);
window.medDocsCloseShareModal = (event) => app.closeShareModal(event);
window.medDocsGrantAccess = () => app.grantAccess();
window.medDocsRevokeAccess = (personId, userId) => app.revokeAccess(personId, userId);
})(MedDocs); })(MedDocs);
@@ -2,8 +2,8 @@
const { state } = app; const { state } = app;
app.loadPrescriptions = async function () { app.loadPrescriptions = async function () {
if (!state.selectedPersonId) return; const personParam = state.selectedPersonId ? `?personId=${state.selectedPersonId}` : '';
const res = await fetch(`${app.API}/prescriptions?personId=${state.selectedPersonId}`); const res = await fetch(`${app.API}/prescriptions${personParam}`);
if (!res.ok) return; if (!res.ok) return;
const prescriptions = await res.json(); const prescriptions = await res.json();
state.currentPrescriptions = prescriptions; state.currentPrescriptions = prescriptions;
@@ -33,7 +33,7 @@
<div class="prescription-info"> <div class="prescription-info">
<div class="prescription-name"> <div class="prescription-name">
<span class="expand-btn" id="expand-${rx.id}">&#9654;</span> <span class="expand-btn" id="expand-${rx.id}">&#9654;</span>
${app.escapeHtml(rx.medicationName)} ${statusBadge} ${app.personBadge(rx.personId)}${app.escapeHtml(rx.medicationName)} ${statusBadge}
</div> </div>
<div class="prescription-meta">${meta.map(m => app.escapeHtml(m)).join(' &middot; ')}</div> <div class="prescription-meta">${meta.map(m => app.escapeHtml(m)).join(' &middot; ')}</div>
<div class="prescription-meta">Last pickup: ${app.escapeHtml(lastPickup)}</div> <div class="prescription-meta">Last pickup: ${app.escapeHtml(lastPickup)}</div>
@@ -44,7 +44,7 @@
</div> </div>
</div> </div>
<div class="pickup-section" id="pickups-${rx.id}" style="display: none;"> <div class="pickup-section" id="pickups-${rx.id}" style="display: none;">
<div class="pickup-form"> ${state.selectedPersonId ? `<div class="pickup-form">
<div class="inline-form-row"> <div class="inline-form-row">
<input type="date" id="pickupDate-${rx.id}" class="form-input" title="Pickup date" /> <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="pickupQty-${rx.id}" placeholder="Quantity" class="form-input" />
@@ -52,7 +52,7 @@
<input type="number" id="pickupCost-${rx.id}" placeholder="Cost" class="form-input" step="0.01" /> <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> <button class="btn btn-primary btn-sm" onclick="medDocsAddPickup(${rx.id})">Log Pickup</button>
</div> </div>
</div> </div>` : ''}
<div class="pickup-list" id="pickupList-${rx.id}"></div> <div class="pickup-list" id="pickupList-${rx.id}"></div>
</div> </div>
</div>`; </div>`;
@@ -73,5 +73,11 @@ window.MedDocs = {
updateSummaryCount(id, count) { updateSummaryCount(id, count) {
const el = document.getElementById(id); const el = document.getElementById(id);
if (el) el.textContent = count; if (el) el.textContent = count;
},
personBadge(personId) {
if (this.state.selectedPersonId) return '';
const person = this.state.people.find(p => p.id === personId);
return person ? `<span class="person-badge">${this.escapeHtml(person.name)}</span>` : '';
} }
}; };
@@ -2,8 +2,6 @@
const { state } = app; const { state } = app;
app.switchMainTab = function (tabName) { app.switchMainTab = function (tabName) {
if (!state.selectedPersonId && tabName !== 'doctors') return;
state.activeTab = tabName; state.activeTab = tabName;
document.querySelectorAll('.main-tab').forEach(btn => { document.querySelectorAll('.main-tab').forEach(btn => {
@@ -32,16 +30,8 @@
}; };
app.updateTabStates = function () { app.updateTabStates = function () {
var personTabs = ['documents', 'conditions', 'prescriptions', 'bills', 'timeline']; document.querySelectorAll('.main-tab.disabled').forEach(function (btn) {
personTabs.forEach(function (tab) {
var btn = document.querySelector('.main-tab[data-tab="' + tab + '"]');
if (btn) {
if (state.selectedPersonId) {
btn.classList.remove('disabled'); btn.classList.remove('disabled');
} else {
btn.classList.add('disabled');
}
}
}); });
}; };
@@ -21,12 +21,11 @@
}; };
app.loadTimeline = async function () { app.loadTimeline = async function () {
if (!state.selectedPersonId) return;
state.timelineOffset = 0; state.timelineOffset = 0;
state.timelineEvents = []; state.timelineEvents = [];
var res = await fetch(app.API + '/timeline?personId=' + state.selectedPersonId + '&offset=0&limit=' + TIMELINE_LIMIT); var personParam = state.selectedPersonId ? 'personId=' + state.selectedPersonId + '&' : '';
var res = await fetch(app.API + '/timeline?' + personParam + 'offset=0&limit=' + TIMELINE_LIMIT);
if (!res.ok) return; if (!res.ok) return;
var events = await res.json(); var events = await res.json();
@@ -39,9 +38,8 @@
}; };
app.loadMoreTimeline = async function () { app.loadMoreTimeline = async function () {
if (!state.selectedPersonId) return; var morePersonParam = state.selectedPersonId ? 'personId=' + state.selectedPersonId + '&' : '';
var res = await fetch(app.API + '/timeline?' + morePersonParam + 'offset=' + state.timelineOffset + '&limit=' + TIMELINE_LIMIT);
var res = await fetch(app.API + '/timeline?personId=' + state.selectedPersonId + '&offset=' + state.timelineOffset + '&limit=' + TIMELINE_LIMIT);
if (!res.ok) return; if (!res.ok) return;
var events = await res.json(); var events = await res.json();
@@ -90,7 +88,7 @@
+ '<div class="timeline-icon">' + icon + '</div>' + '<div class="timeline-icon">' + icon + '</div>'
+ '<div class="timeline-content">' + '<div class="timeline-content">'
+ '<div class="timeline-date">' + dateStr + ' ' + typeBadge + ' ' + subBadge + '</div>' + '<div class="timeline-date">' + dateStr + ' ' + typeBadge + ' ' + subBadge + '</div>'
+ '<div class="timeline-label">' + app.escapeHtml(ev.label || 'Untitled') + '</div>' + '<div class="timeline-label">' + app.personBadge(ev.personId) + app.escapeHtml(ev.label || 'Untitled') + '</div>'
+ detail + detail
+ '</div>' + '</div>'
+ '</div>'; + '</div>';
@@ -0,0 +1,431 @@
// Theme Customizer - Color picker modal with live iframe preview
(function() {
var COLOR_VARIABLES = [
{ group: 'Background', vars: [
{ key: '--bg-primary', name: 'Primary Background' },
{ key: '--bg-secondary', name: 'Secondary Background' },
{ key: '--bg-tertiary', name: 'Tertiary Background' },
{ key: '--bg-hover', name: 'Hover Background' }
]},
{ group: 'Text', vars: [
{ key: '--text-primary', name: 'Primary Text' },
{ key: '--text-secondary', name: 'Secondary Text' }
]},
{ group: 'Border', vars: [
{ key: '--border-primary', name: 'Primary Border' },
{ key: '--border-secondary', name: 'Secondary Border' }
]},
{ group: 'Accent', vars: [
{ key: '--accent-primary', name: 'Primary Accent' },
{ key: '--accent-hover', name: 'Accent Hover' }
]},
{ group: 'Status', vars: [
{ key: '--danger', name: 'Danger' },
{ key: '--danger-hover', name: 'Danger Hover' },
{ key: '--success', name: 'Success' }
]}
];
var allVarKeys = [];
COLOR_VARIABLES.forEach(function(g) {
g.vars.forEach(function(v) { allVarKeys.push(v.key); });
});
var pendingOverrides = {};
var savedOverrides = {};
var modal = null;
var iframe = null;
function getBaseTheme() {
return document.documentElement.getAttribute('data-theme') || 'light';
}
function getComputedColor(varName) {
return getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
}
function getCurrentColor(varName) {
if (pendingOverrides[varName]) return pendingOverrides[varName];
// Get the base theme value (not the overridden inline value)
return getResolvedBaseColor(varName);
}
function getResolvedBaseColor(varName) {
// To get the real CSS variable value without inline overrides,
// we temporarily remove the inline style, read computed, then restore
var inline = document.documentElement.style.getPropertyValue(varName);
if (inline) {
document.documentElement.style.removeProperty(varName);
var val = getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
document.documentElement.style.setProperty(varName, inline);
return val;
}
return getComputedColor(varName);
}
function rgbToHex(rgb) {
if (!rgb || rgb.charAt(0) === '#') return rgb;
var match = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (!match) return rgb;
return '#' + [match[1], match[2], match[3]].map(function(x) {
return parseInt(x).toString(16).padStart(2, '0');
}).join('');
}
function buildModal() {
var overlay = document.createElement('div');
overlay.id = 'theme-customizer-overlay';
var container = document.createElement('div');
container.id = 'theme-customizer-modal';
// Header
var header = document.createElement('div');
header.className = 'tc-header';
header.innerHTML = '<h3>Customize Colors</h3>';
var closeBtn = document.createElement('button');
closeBtn.className = 'tc-close-btn';
closeBtn.textContent = '\u00D7';
closeBtn.onclick = cancelCustomizer;
header.appendChild(closeBtn);
container.appendChild(header);
// Controls area
var controls = document.createElement('div');
controls.className = 'tc-controls';
// Base theme selector
var themeRow = document.createElement('div');
themeRow.className = 'tc-row';
themeRow.innerHTML = '<label>Base Theme:</label>';
var themeSelect = document.createElement('select');
themeSelect.id = 'tc-base-theme';
themeSelect.innerHTML = '<option value="light">Light</option><option value="dark">Dark</option>';
themeSelect.value = getBaseTheme();
themeSelect.onchange = function() {
document.documentElement.setAttribute('data-theme', themeSelect.value);
localStorage.setItem(window._themeUtils.THEME_KEY, themeSelect.value);
var toggle = document.getElementById('theme-toggle');
if (toggle) toggle.checked = themeSelect.value === 'dark';
// Re-apply pending overrides to parent
applyPendingToDocument();
updatePickerForSelection();
updateSwatches();
applyToIframe();
};
themeRow.appendChild(themeSelect);
controls.appendChild(themeRow);
// Color variable selector
var varRow = document.createElement('div');
varRow.className = 'tc-row';
varRow.innerHTML = '<label>Color Variable:</label>';
var varSelect = document.createElement('select');
varSelect.id = 'tc-var-select';
COLOR_VARIABLES.forEach(function(group) {
var optgroup = document.createElement('optgroup');
optgroup.label = group.group;
group.vars.forEach(function(v) {
var opt = document.createElement('option');
opt.value = v.key;
opt.textContent = v.name;
optgroup.appendChild(opt);
});
varSelect.appendChild(optgroup);
});
varSelect.onchange = function() { updatePickerForSelection(); };
varRow.appendChild(varSelect);
controls.appendChild(varRow);
// Color picker row
var pickerRow = document.createElement('div');
pickerRow.className = 'tc-row tc-picker-row';
var colorInput = document.createElement('input');
colorInput.type = 'color';
colorInput.id = 'tc-color-picker';
var hexInput = document.createElement('input');
hexInput.type = 'text';
hexInput.id = 'tc-hex-input';
hexInput.placeholder = '#000000';
hexInput.maxLength = 7;
var removeBtn = document.createElement('button');
removeBtn.id = 'tc-remove-override';
removeBtn.className = 'tc-btn tc-btn-small';
removeBtn.textContent = 'Reset';
removeBtn.title = 'Remove override for this variable';
removeBtn.onclick = function() {
var key = varSelect.value;
delete pendingOverrides[key];
applyPendingToDocument();
updatePickerForSelection();
updateSwatches();
applyToIframe();
};
colorInput.addEventListener('input', function() {
var key = varSelect.value;
pendingOverrides[key] = colorInput.value;
hexInput.value = colorInput.value;
applyPendingToDocument();
updateSwatches();
applyToIframe();
});
hexInput.addEventListener('input', function() {
var val = hexInput.value;
if (/^#[0-9a-fA-F]{6}$/.test(val)) {
var key = varSelect.value;
pendingOverrides[key] = val;
colorInput.value = val;
applyPendingToDocument();
updateSwatches();
applyToIframe();
}
});
pickerRow.appendChild(colorInput);
pickerRow.appendChild(hexInput);
pickerRow.appendChild(removeBtn);
controls.appendChild(pickerRow);
// Swatch strip
var swatchContainer = document.createElement('div');
swatchContainer.className = 'tc-swatches';
swatchContainer.id = 'tc-swatches';
controls.appendChild(swatchContainer);
// Buttons
var btnRow = document.createElement('div');
btnRow.className = 'tc-btn-row';
var saveBtn = document.createElement('button');
saveBtn.className = 'tc-btn tc-btn-save';
saveBtn.textContent = 'Save';
saveBtn.onclick = saveCustomizer;
var cancelBtn = document.createElement('button');
cancelBtn.className = 'tc-btn tc-btn-cancel';
cancelBtn.textContent = 'Cancel';
cancelBtn.onclick = cancelCustomizer;
var resetBtn = document.createElement('button');
resetBtn.className = 'tc-btn tc-btn-reset';
resetBtn.textContent = 'Reset to Defaults';
resetBtn.onclick = resetCustomizer;
btnRow.appendChild(saveBtn);
btnRow.appendChild(cancelBtn);
btnRow.appendChild(resetBtn);
controls.appendChild(btnRow);
container.appendChild(controls);
// Iframe preview
var previewContainer = document.createElement('div');
previewContainer.className = 'tc-preview';
iframe = document.createElement('iframe');
iframe.id = 'theme-preview-iframe';
iframe.src = '/';
iframe.addEventListener('load', function() { applyToIframe(); });
previewContainer.appendChild(iframe);
container.appendChild(previewContainer);
overlay.appendChild(container);
return overlay;
}
function updatePickerForSelection() {
var varSelect = document.getElementById('tc-var-select');
var colorInput = document.getElementById('tc-color-picker');
var hexInput = document.getElementById('tc-hex-input');
var removeBtn = document.getElementById('tc-remove-override');
if (!varSelect || !colorInput || !hexInput) return;
var key = varSelect.value;
var color = getCurrentColor(key);
var hex = rgbToHex(color);
if (!hex || hex.charAt(0) !== '#') hex = '#000000';
colorInput.value = hex;
hexInput.value = hex;
removeBtn.style.display = pendingOverrides[key] ? 'inline-block' : 'none';
}
function updateSwatches() {
var container = document.getElementById('tc-swatches');
var varSelect = document.getElementById('tc-var-select');
if (!container) return;
container.innerHTML = '';
allVarKeys.forEach(function(key) {
var swatch = document.createElement('div');
swatch.className = 'tc-swatch';
if (pendingOverrides[key]) swatch.classList.add('tc-swatch-overridden');
if (varSelect && varSelect.value === key) swatch.classList.add('tc-swatch-selected');
var color = pendingOverrides[key] || rgbToHex(getResolvedBaseColor(key));
swatch.style.backgroundColor = color;
swatch.title = key + ': ' + color;
swatch.onclick = function() {
if (varSelect) {
varSelect.value = key;
updatePickerForSelection();
}
};
container.appendChild(swatch);
});
}
function applyPendingToDocument() {
// First clear all overrides
allVarKeys.forEach(function(key) {
document.documentElement.style.removeProperty(key);
});
// Apply pending
for (var key in pendingOverrides) {
if (pendingOverrides.hasOwnProperty(key)) {
document.documentElement.style.setProperty(key, pendingOverrides[key]);
}
}
}
function applyToIframe() {
if (!iframe || !iframe.contentDocument) return;
try {
var iframeRoot = iframe.contentDocument.documentElement;
var themeSelect = document.getElementById('tc-base-theme');
var baseTheme = themeSelect ? themeSelect.value : getBaseTheme();
iframeRoot.setAttribute('data-theme', baseTheme);
// Clear previous overrides
allVarKeys.forEach(function(key) {
iframeRoot.style.removeProperty(key);
});
// Apply pending
for (var key in pendingOverrides) {
if (pendingOverrides.hasOwnProperty(key)) {
iframeRoot.style.setProperty(key, pendingOverrides[key]);
}
}
} catch (e) {
// Cross-origin or not yet loaded
}
}
function saveCustomizer() {
var themeSelect = document.getElementById('tc-base-theme');
var baseTheme = themeSelect ? themeSelect.value : getBaseTheme();
// Save to localStorage
localStorage.setItem(window._themeUtils.OVERRIDES_KEY, JSON.stringify(pendingOverrides));
localStorage.setItem(window._themeUtils.THEME_KEY, baseTheme);
// Sync dark mode toggle
var toggle = document.getElementById('theme-toggle');
if (toggle) toggle.checked = baseTheme === 'dark';
// Apply to document
document.documentElement.setAttribute('data-theme', baseTheme);
applyPendingToDocument();
savedOverrides = JSON.parse(JSON.stringify(pendingOverrides));
// Save to API
fetch('/api/theme/my', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ baseTheme: baseTheme, colorOverrides: pendingOverrides })
});
closeModal();
}
function cancelCustomizer() {
// Restore from saved state
pendingOverrides = JSON.parse(JSON.stringify(savedOverrides));
var savedTheme = localStorage.getItem(window._themeUtils.THEME_KEY) || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
var toggle = document.getElementById('theme-toggle');
if (toggle) toggle.checked = savedTheme === 'dark';
// Clear all inline overrides and re-apply saved
allVarKeys.forEach(function(key) {
document.documentElement.style.removeProperty(key);
});
for (var key in savedOverrides) {
if (savedOverrides.hasOwnProperty(key)) {
document.documentElement.style.setProperty(key, savedOverrides[key]);
}
}
closeModal();
}
function resetCustomizer() {
pendingOverrides = {};
savedOverrides = {};
// Clear localStorage overrides
localStorage.removeItem(window._themeUtils.OVERRIDES_KEY);
// Clear all inline style properties
allVarKeys.forEach(function(key) {
document.documentElement.style.removeProperty(key);
});
// Save to API
var baseTheme = getBaseTheme();
fetch('/api/theme/my', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ baseTheme: baseTheme, colorOverrides: {} })
});
closeModal();
}
function closeModal() {
if (modal) {
modal.remove();
modal = null;
iframe = null;
}
}
window.openThemeCustomizer = function() {
if (modal) return;
// Load saved overrides from localStorage
var raw = localStorage.getItem(window._themeUtils.OVERRIDES_KEY);
try {
savedOverrides = raw ? JSON.parse(raw) : {};
} catch (e) {
savedOverrides = {};
}
pendingOverrides = JSON.parse(JSON.stringify(savedOverrides));
modal = buildModal();
document.body.appendChild(modal);
updatePickerForSelection();
updateSwatches();
// Also fetch from API to sync
fetch('/api/theme/my')
.then(function(r) { return r.json(); })
.then(function(data) {
if (data && data.colorOverrides && Object.keys(data.colorOverrides).length > 0) {
// If API has overrides and localStorage doesn't, sync
if (Object.keys(savedOverrides).length === 0) {
savedOverrides = data.colorOverrides;
pendingOverrides = JSON.parse(JSON.stringify(data.colorOverrides));
localStorage.setItem(window._themeUtils.OVERRIDES_KEY, JSON.stringify(data.colorOverrides));
applyPendingToDocument();
updatePickerForSelection();
updateSwatches();
applyToIframe();
}
}
if (data && data.baseTheme) {
var themeSelect = document.getElementById('tc-base-theme');
if (themeSelect) themeSelect.value = data.baseTheme;
}
})
.catch(function() {});
};
})();
+50 -7
View File
@@ -1,6 +1,7 @@
// Theme Toggle Functionality // Theme Toggle Functionality
(function() { (function() {
const THEME_KEY = 'theme-preference'; const THEME_KEY = 'theme-preference';
const OVERRIDES_KEY = 'theme-overrides';
// Initialize theme on page load // Initialize theme on page load
function initTheme() { function initTheme() {
@@ -8,31 +9,73 @@
const theme = savedTheme || 'light'; // Default to light const theme = savedTheme || 'light'; // Default to light
document.documentElement.setAttribute('data-theme', theme); document.documentElement.setAttribute('data-theme', theme);
}
// Update toggle if it exists // Apply color overrides from localStorage
const toggle = document.getElementById('theme-toggle'); function applyColorOverrides() {
if (toggle) { var raw = localStorage.getItem(OVERRIDES_KEY);
toggle.checked = theme === 'dark'; if (!raw) return;
try {
var overrides = JSON.parse(raw);
for (var key in overrides) {
if (overrides.hasOwnProperty(key)) {
document.documentElement.style.setProperty(key, overrides[key]);
}
}
} catch (e) {
// Ignore malformed JSON
}
}
// Clear all inline color overrides from documentElement
function clearColorOverrides() {
var raw = localStorage.getItem(OVERRIDES_KEY);
if (!raw) return;
try {
var overrides = JSON.parse(raw);
for (var key in overrides) {
if (overrides.hasOwnProperty(key)) {
document.documentElement.style.removeProperty(key);
}
}
} catch (e) {
// Ignore
} }
} }
// Toggle theme // Toggle theme
function toggleTheme() { function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme') || 'light'; var currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
const newTheme = currentTheme === 'dark' ? 'light' : 'dark'; var newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme); document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem(THEME_KEY, newTheme); localStorage.setItem(THEME_KEY, newTheme);
// Re-apply overrides after theme switch (inline styles take precedence)
applyColorOverrides();
} }
// Initialize immediately (before DOMContentLoaded to prevent flash) // Initialize immediately (before DOMContentLoaded to prevent flash)
initTheme(); initTheme();
applyColorOverrides();
// Set up toggle listener when DOM is ready // Set up toggle listener when DOM is ready
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
const toggle = document.getElementById('theme-toggle'); var toggle = document.getElementById('theme-toggle');
if (toggle) { if (toggle) {
// Sync checkbox state to current theme
var currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
toggle.checked = currentTheme === 'dark';
toggle.addEventListener('change', toggleTheme); toggle.addEventListener('change', toggleTheme);
} }
}); });
// Expose for theme customizer
window._themeUtils = {
applyColorOverrides: applyColorOverrides,
clearColorOverrides: clearColorOverrides,
THEME_KEY: THEME_KEY,
OVERRIDES_KEY: OVERRIDES_KEY
};
})(); })();