Author SHA1 Message Date
Josh-Heaps b2d0c72541 add cache invalidation 2026-08-26 17:19:17 -06:00
Josh-Heaps 941759f7c3 Add image upload capabilities 2026-08-26 17:19:17 -06:00
Josh-Heaps 2443b92c23 Update blog button 2026-08-26 17:19:16 -06:00
Josh-HeapsandClaude Opus 4.6 d8015f54ef Add blog management: migration, API, service, and admin UI
Blog posts stored in PostgreSQL with markdown rendering via Markdig.
Public API for reads, admin-only writes with dual auth (JWT + session).
Admin page for creating, editing, and deleting posts.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-08-26 17:19:16 -06:00
jheaps d1eb772e89 Merge pull request 'add gitea workflow' (#1) from gitea/workflow into master
Deploy Media Server / build-deploy (push) Successful in 54s
Reviewed-on: #1
2026-08-26 16:04:43 -06:00
Josh-Heaps caad111457 add gitea workflow 2026-08-26 16:04:03 -06:00
Josh Heaps dda6ac68dc Merge pull request #7 from JoshHeaps/mobileUi
Deploy Media Server / build (push) Successful in 39s
Deploy Media Server / deploy (push) Failing after 7s
Add document viewer
2026-02-12 09:55:24 -07:00
Josh-Heaps 8982011155 Add document viewer 2026-02-12 09:53:25 -07:00
Josh Heaps af309ca8d6 Merge pull request #6 from JoshHeaps/mobileUi
mobile ui
2026-02-10 17:31:09 -07:00
Josh-Heaps 811f732495 mobile ui 2026-02-10 17:30:26 -07:00
Josh Heaps 6b83d7df0f Merge pull request #5 from JoshHeaps/feature/AdminPage
Feature/admin page
2026-02-10 16:55:41 -07:00
Josh-Heaps 6814270b7c Fully implement medical documentation 2026-02-10 16:54:51 -07:00
Josh-Heaps 9ede3ae53f Implement first four phases of medical docs roadmap 2026-02-09 16:35:45 -07:00
Josh-Heaps e69e5663ce Add fleshed out admin page 2026-02-09 14:38:58 -07:00
Josh-Heaps 14d748de80 Add user roles and admin page 2026-02-09 13:52:59 -07:00
Josh-Heaps 9bbbe3aaad update claude.md 2026-02-09 13:52:49 -07:00
Josh-Heaps c9aa9886e4 Add claude.md 2026-02-09 13:28:31 -07:00
Josh-Heaps a26ffec104 Fix sql scripts 2026-02-09 13:23:34 -07:00
Josh Heaps c35396f906 Merge pull request #4 from JoshHeaps/feature/NoteGraph
Create node graph page
2026-01-02 17:15:16 -07:00
Josh-Heaps dae8fbfe5e Create node graph page 2026-01-02 17:13:39 -07:00
Josh Heaps 9e9439eec9 Merge pull request #3 from JoshHeaps/feature/Folders
Add folder sharing
2025-10-21 17:47:31 -06:00
Josh Heaps dd6995bfc7 Merge pull request #2 from JoshHeaps/feature/Folders
Add folders
2025-10-21 16:51:28 -06:00
104 changed files with 15288 additions and 269 deletions
+6 -1
View File
@@ -6,7 +6,12 @@
"Bash(powershell:*)",
"Bash(dotnet script:*)",
"Bash(taskkill:*)",
"Bash(dir:*)"
"Bash(dir:*)",
"Bash(cd:*)",
"Bash(tree:*)",
"Bash(del Index.cshtml Index.cshtml.cs)",
"Bash(dotnet build:*)",
"Bash(find:*)"
],
"deny": [],
"ask": []
+77
View File
@@ -0,0 +1,77 @@
# .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"
+56
View File
@@ -0,0 +1,56 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
Full-stack ASP.NET Core 8 media management application (Media.JoshHeaps.Net) with encrypted photo storage, folder organization with sharing, and knowledge graph visualization. PostgreSQL backend, Razor Pages frontend with vanilla JavaScript.
## Build & Run
```bash
# Restore and build
dotnet build Media.JoshHeaps.Net.sln
# Run the app (HTTPS: localhost:7007, HTTP: localhost:5029)
dotnet run --project Media.JoshHeaps.Net
# Run database migrations (requires psql on PATH)
./run-migrations.ps1 -ConnectionString "<connection_string>"
```
Sensitive config (DB connection string, JWT signing key, encryption key, email credentials) is stored in .NET User Secrets (ID: `1ee15d15-1d19-471d-8772-ce72aeaafbd3`). No test project exists.
## Architecture
### Backend Layers
- **Api/** — REST controllers. Routes: `/api/auth/`, `/api/media/`, `/api/folder/`, `/api/folder-share/`, `/api/graph/`
- **Services/** — Business logic (AuthService, MediaService, FolderService, GraphService, EmailService, EncryptionService, UserService). Registered via DI in Program.cs.
- **Models/** — Data models shared between API and Razor Pages
- **Pages/** — Razor Pages for server-rendered UI. Protected pages inherit from `AuthenticatedPageModel` (session-based auth).
### Authentication
Dual auth scheme: **session cookies** for Razor Pages, **JWT Bearer** for API endpoints. Session timeout is 2 hours; JWT expiry is 30 days. Account locks after 5 failed login attempts for 15 minutes.
### Database
PostgreSQL via `DbExecutor` singleton — a custom async query executor using raw Npgsql (no ORM). Parameterized queries use reflection on anonymous objects. Migration scripts in `Database/` are numbered 001011 and must run in order (each script's dependencies come before it). **All database changes must be backwards-compatible with the existing production database — never drop tables, columns, or alter data in ways that could cause data loss. Use additive migrations (ADD COLUMN, CREATE TABLE, etc.) and `IF NOT EXISTS` guards where appropriate.**
### File Storage
Media files are encrypted with AES-256-CBC before storage in `App_Data/media/{userId}/`. Each file gets a random IV. Files are decrypted on-demand when served. Max upload: 10MB, allowed types: JPEG, PNG, GIF, WEBP.
### Frontend
Razor Pages + vanilla JS + Bootstrap 5. Key JS files in `wwwroot/js/`:
- `gallery.js` / `folders.js` / `upload.js` / `drag-drop.js` — gallery and folder UI
- `folder-sharing.js` — sharing modal and permissions
- `network-graph.js` — D3-based graph visualization with community detection
- `context-menu.js` — right-click context menus
- `theme.js` — dark/light theme toggle
### Key Dependencies
Npgsql (PostgreSQL), BCrypt.Net-Next (password hashing), MailKit (email), SixLabors.ImageSharp (image processing), Microsoft.AspNetCore.Authentication.JwtBearer
+45
View File
@@ -0,0 +1,45 @@
# Medical Documentation System — Roadmap
A dedicated admin-only section for organizing medical documents (receipts, doctor notes, recorded conversations, lab results, etc.) for multiple family members. Uses Claude AI to auto-classify, tag, and extract structured data from uploaded documents. Completely separate from the existing media/gallery system.
---
## Phase 1: Database Foundation & Core Document Management ✅
Tables for people, documents, tags, doctors, conditions, prescriptions, costs. Basic CRUD service. Admin-gated Razor Page with file upload and plain-text note entry.
## Phase 2: People & Document Browsing ✅
UI for managing people (family members). Document list with filtering by person, type icons, download/preview.
## Phase 3: Claude AI Integration ✅
`MedicalAiService` using Claude API. On upload: OCR, text extraction, auto-classification, auto-tagging, structured data extraction. Manual transcript field for audio files.
## Phase 4: Doctors, Conditions & Prescription Tracking ✅
Doctor/condition management (global doctors, per-person conditions). Prescription tracking with doctor linkage, expandable pickup history, and "last pickup" display. Inline add/edit/delete for all entities.
## Phase 5: AI CLI Migration ✅
Replaced Claude HTTP API with `claude -p` CLI pipe mode. Sequential `Channel<long>` background queue replaces fire-and-forget `Task.Run`. Rate limit detection parses reset time from CLI output and pauses the queue. Temp file approach for image/PDF OCR via CLI with `--allowedTools Read`.
## Phase 6: Bills & Payments ✅
Replaced the flat `medical_document_costs` model (which double/triple-counted AI-extracted line items) with a proper billing system. Bills represent unique charges; payments track money applied toward them (patient payments, insurance payments, adjustments, write-offs). Summary card shows out-of-pocket vs total charged. Bills support linked documents, expandable payment lists, and filter by paid/unpaid status. Old costs API endpoints preserved for backward compatibility with AI processing.
## Phase 7: AI Bills Integration ✅
Updated AI extraction prompt to create bills + payments instead of flat costs. On re-process: deletes AI-sourced bills/payments for document, re-creates (prevents duplicates). Smart matching: if extracted charge matches existing bill for same person (same amount, category, date within 30 days), links document instead of creating new. Removed `AddCostsAsync`, all costs CRUD methods, costs API endpoints, and `MedicalDocumentCost` model. DB table retained per policy.
## Phase 8: Search & Filtering ⬅️ **Up Next**
Full-text search on extracted text. Filter by person, doctor, condition, tags, document type, date range. Combined filters.
## Phase 9: AI-Enhanced Insights
Medical timeline per person. Visit prep summaries. Batch re-analysis when AI improves.
## Phase 10: Polish & Hardening
Pagination/lazy-loading. Export (PDF summary, CSV costs). Mobile-responsive UI.
---
## Feature requests (I'm writing these down for me. I may ask you to do these in the future, so please design any changes with the fact in mind that they may need to acommodate these)
## Calendar
A calendar that's easy to navigate, and shows what documents are on each day. If I see the month of January, at the very least, I should see something on the calendar indicating which days in January a document is associated with.
## Custom Colors
An easy way to customize colors instead of just having a light mode/dark mode. I still want to have light mode/dark mode as defaults, but custom colors should be an option as well.
+184
View File
@@ -0,0 +1,184 @@
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace Media.JoshHeaps.Net.Api;
[ApiController]
[Route("api/admin")]
public class AdminApi(DbExecutor dbExecutor) : ControllerBase
{
[HttpGet("users")]
public async Task<IActionResult> GetUsers([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
{
var authUserId = GetUserIdFromAuth();
if (authUserId == null) return Unauthorized();
if (!await IsAdmin(authUserId.Value)) return Forbid();
if (page < 1) page = 1;
if (pageSize < 1 || pageSize > 100) pageSize = 20;
var offset = (page - 1) * pageSize;
var totalCount = await dbExecutor.ExecuteAsync<long>(
"SELECT COUNT(*) FROM app.users");
var users = await dbExecutor.ExecuteListReaderAsync(
@"SELECT u.id, u.username, u.email, u.is_active
FROM app.users u
ORDER BY u.id
LIMIT @PageSize OFFSET @Offset",
reader => new
{
Id = reader.GetInt64(0),
Username = reader.GetString(1),
Email = reader.GetString(2),
IsActive = reader.GetBoolean(3)
},
new { PageSize = pageSize, Offset = offset });
// Fetch all roles for these users in one query using a subquery
var userRoles = users.Count > 0
? await dbExecutor.ExecuteListReaderAsync(
@"SELECT ur.user_id, r.id, r.name
FROM app.user_roles ur
JOIN app.roles r ON ur.role_id = r.id
WHERE ur.user_id IN (
SELECT u.id FROM app.users u ORDER BY u.id LIMIT @PageSize OFFSET @Offset
)",
reader => new
{
UserId = reader.GetInt64(0),
RoleId = reader.GetInt64(1),
RoleName = reader.GetString(2)
},
new { PageSize = pageSize, Offset = offset })
: [];
var result = users.Select(u => new
{
u.Id,
u.Username,
u.Email,
u.IsActive,
Roles = userRoles.Where(r => r.UserId == u.Id)
.Select(r => new { Id = r.RoleId, Name = r.RoleName })
.ToList()
});
return Ok(new { users = result, totalCount });
}
[HttpGet("roles")]
public async Task<IActionResult> GetRoles()
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await IsAdmin(userId.Value)) return Forbid();
var roles = await dbExecutor.ExecuteListReaderAsync(
"SELECT id, name FROM app.roles ORDER BY id",
reader => new { Id = reader.GetInt64(0), Name = reader.GetString(1) });
return Ok(roles);
}
[HttpPost("roles")]
public async Task<IActionResult> CreateRole([FromBody] CreateRoleRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await IsAdmin(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Role name is required" });
var name = request.Name.Trim().ToLowerInvariant();
var existing = await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.roles WHERE name = @Name)",
new { Name = name });
if (existing)
return BadRequest(new { error = "Role already exists" });
var role = await dbExecutor.ExecuteReaderAsync(
"INSERT INTO app.roles (name) VALUES (@Name) RETURNING id, name",
reader => new { Id = reader.GetInt64(0), Name = reader.GetString(1) },
new { Name = name });
return Ok(role);
}
[HttpPost("users/{targetUserId}/roles/{roleId}")]
public async Task<IActionResult> AssignRole(long targetUserId, long roleId)
{
var adminId = GetUserIdFromAuth();
if (adminId == null) return Unauthorized();
if (!await IsAdmin(adminId.Value)) return Forbid();
var userExists = await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.users WHERE id = @UserId)",
new { UserId = targetUserId });
if (!userExists) return NotFound(new { error = "User not found" });
var roleExists = await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.roles WHERE id = @RoleId)",
new { RoleId = roleId });
if (!roleExists) return NotFound(new { error = "Role not found" });
var alreadyAssigned = await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.user_roles WHERE user_id = @UserId AND role_id = @RoleId)",
new { UserId = targetUserId, RoleId = roleId });
if (alreadyAssigned) return Ok(new { success = true });
await dbExecutor.ExecuteNonQueryAsync(
"INSERT INTO app.user_roles (user_id, role_id) VALUES (@UserId, @RoleId)",
new { UserId = targetUserId, RoleId = roleId });
return Ok(new { success = true });
}
[HttpDelete("users/{targetUserId}/roles/{roleId}")]
public async Task<IActionResult> RemoveRole(long targetUserId, long roleId)
{
var adminId = GetUserIdFromAuth();
if (adminId == null) return Unauthorized();
if (!await IsAdmin(adminId.Value)) return Forbid();
await dbExecutor.ExecuteNonQueryAsync(
"DELETE FROM app.user_roles WHERE user_id = @UserId AND role_id = @RoleId",
new { UserId = targetUserId, RoleId = roleId });
return Ok(new { success = true });
}
private async Task<bool> IsAdmin(long userId)
{
return await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.user_roles ur JOIN app.roles r ON ur.role_id = r.id WHERE ur.user_id = @UserId AND r.name = 'admin')",
new { UserId = userId });
}
private long? GetUserIdFromAuth()
{
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!string.IsNullOrEmpty(userIdClaim) && long.TryParse(userIdClaim, out var jwtUserId))
{
return jwtUserId;
}
var userIdString = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userIdString) && long.TryParse(userIdString, out var sessionUserId))
{
return sessionUserId;
}
return null;
}
}
public record CreateRoleRequest(string Name);
+6 -15
View File
@@ -11,17 +11,8 @@ namespace Media.JoshHeaps.Net.Api;
[ApiController]
[Route("api/auth")]
public class AuthApi : ControllerBase
public class AuthApi(AuthService authService, IConfiguration configuration) : ControllerBase
{
private readonly AuthService _authService;
private readonly IConfiguration _configuration;
public AuthApi(AuthService authService, IConfiguration configuration)
{
_authService = authService;
_configuration = configuration;
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
@@ -30,7 +21,7 @@ public class AuthApi : ControllerBase
return BadRequest(new { error = "Email/username and password are required" });
}
var (success, error, userInfo) = await _authService.LoginAsync(request.EmailOrUsername, request.Password);
var (success, error, userInfo) = await authService.LoginAsync(request.EmailOrUsername, request.Password);
if (!success || userInfo == null)
{
@@ -77,10 +68,10 @@ public class AuthApi : ControllerBase
private string GenerateJwtToken(UserLoginInfo user)
{
var jwtKey = _configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key not configured");
var jwtIssuer = _configuration["Jwt:Issuer"] ?? throw new InvalidOperationException("JWT Issuer not configured");
var jwtAudience = _configuration["Jwt:Audience"] ?? throw new InvalidOperationException("JWT Audience not configured");
var jwtExpiryDays = int.Parse(_configuration["Jwt:ExpiryInDays"] ?? "30");
var jwtKey = configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key not configured");
var jwtIssuer = configuration["Jwt:Issuer"] ?? throw new InvalidOperationException("JWT Issuer not configured");
var jwtAudience = configuration["Jwt:Audience"] ?? throw new InvalidOperationException("JWT Audience not configured");
var jwtExpiryDays = int.Parse(configuration["Jwt:ExpiryInDays"] ?? "30");
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
+206
View File
@@ -0,0 +1,206 @@
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace Media.JoshHeaps.Net.Api;
[ApiController]
[Route("api/blog")]
public class BlogApi(BlogService blogService, DbExecutor dbExecutor, IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger<BlogApi> logger) : ControllerBase
{
[HttpGet("posts")]
public async Task<IActionResult> GetPosts()
{
var posts = await blogService.GetAllPostsAsync();
return Ok(posts.Select(MapToPublicDto));
}
[HttpGet("posts/{slug}")]
public async Task<IActionResult> GetPostBySlug(string slug)
{
var post = await blogService.GetPostBySlugAsync(slug);
if (post is null) return NotFound();
return Ok(MapToPublicDto(post));
}
[HttpGet("posts/tags/{tag}")]
public async Task<IActionResult> GetPostsByTag(string tag)
{
var posts = await blogService.GetPostsByTagAsync(tag);
return Ok(posts.Select(MapToPublicDto));
}
[HttpGet("posts/admin/{id}")]
public async Task<IActionResult> GetPostForAdmin(long id)
{
var userId = GetUserIdFromAuth();
if (userId is null) return Unauthorized();
if (!await IsAdmin(userId.Value)) return Forbid();
var post = await blogService.GetPostByIdAsync(id);
if (post is null) return NotFound();
return Ok(MapToAdminDto(post));
}
[HttpPost("posts")]
public async Task<IActionResult> CreatePost([FromBody] CreateBlogPostRequest request)
{
var userId = GetUserIdFromAuth();
if (userId is null) return Unauthorized();
if (!await IsAdmin(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Title))
return BadRequest(new { error = "Title is required" });
if (string.IsNullOrWhiteSpace(request.MarkdownContent))
return BadRequest(new { error = "Content is required" });
var post = await blogService.CreatePostAsync(
request.Title.Trim(),
request.Summary?.Trim() ?? "",
request.MarkdownContent,
request.Tags ?? [],
userId.Value,
request.PublishedDate ?? DateTime.UtcNow);
if (post is null)
return StatusCode(500, new { error = "Failed to create post" });
_ = InvalidateFrontendCacheAsync();
return Ok(MapToAdminDto(post));
}
[HttpPut("posts/{id}")]
public async Task<IActionResult> UpdatePost(long id, [FromBody] UpdateBlogPostRequest request)
{
var userId = GetUserIdFromAuth();
if (userId is null) return Unauthorized();
if (!await IsAdmin(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Title))
return BadRequest(new { error = "Title is required" });
if (string.IsNullOrWhiteSpace(request.MarkdownContent))
return BadRequest(new { error = "Content is required" });
var post = await blogService.UpdatePostAsync(
id,
request.Title.Trim(),
request.Summary?.Trim() ?? "",
request.MarkdownContent,
request.Tags ?? [],
request.PublishedDate ?? DateTime.UtcNow);
if (post is null)
return NotFound(new { error = "Post not found" });
_ = InvalidateFrontendCacheAsync();
return Ok(MapToAdminDto(post));
}
[HttpDelete("posts/{id}")]
public async Task<IActionResult> DeletePost(long id)
{
var userId = GetUserIdFromAuth();
if (userId is null) return Unauthorized();
if (!await IsAdmin(userId.Value)) return Forbid();
var deleted = await blogService.DeletePostAsync(id);
if (!deleted) return NotFound(new { error = "Post not found" });
_ = InvalidateFrontendCacheAsync();
return Ok(new { success = true });
}
[HttpPost("images")]
public async Task<IActionResult> UploadImage(IFormFile file)
{
var userId = GetUserIdFromAuth();
if (userId is null) return Unauthorized();
if (!await IsAdmin(userId.Value)) return Forbid();
if (file is null || file.Length == 0)
return BadRequest(new { error = "No file provided" });
var (url, error) = await blogService.SaveImageAsync(file);
if (url is null)
return BadRequest(new { error });
return Ok(new { url });
}
[HttpGet("images/{fileName}")]
public IActionResult GetImage(string fileName)
{
var (filePath, mimeType) = blogService.GetImagePath(fileName);
if (filePath is null)
return NotFound();
return PhysicalFile(filePath, mimeType!);
}
private static object MapToPublicDto(Models.BlogPost post) => new
{
post.Id,
post.Slug,
post.Title,
post.Summary,
post.Tags,
post.PublishedDate,
post.HtmlContent
};
private static object MapToAdminDto(Models.BlogPost post) => new
{
post.Id,
post.Slug,
post.Title,
post.Summary,
post.MarkdownContent,
post.Tags,
post.PublishedDate,
post.CreatedAt,
post.UpdatedAt
};
private async Task InvalidateFrontendCacheAsync()
{
try
{
var url = configuration["BlogCache:InvalidateUrl"];
var key = configuration["BlogCache:InvalidateKey"];
if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(key)) return;
var client = httpClientFactory.CreateClient();
client.Timeout = TimeSpan.FromSeconds(5);
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Add("X-Invalidate-Key", key);
await client.SendAsync(request);
}
catch (Exception ex)
{
logger.LogWarning(ex, "Failed to invalidate frontend blog cache");
}
}
private async Task<bool> IsAdmin(long userId)
{
return await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.user_roles ur JOIN app.roles r ON ur.role_id = r.id WHERE ur.user_id = @UserId AND r.name = 'admin')",
new { UserId = userId });
}
private long? GetUserIdFromAuth()
{
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!string.IsNullOrEmpty(userIdClaim) && long.TryParse(userIdClaim, out var jwtUserId))
return jwtUserId;
var userIdString = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userIdString) && long.TryParse(userIdString, out var sessionUserId))
return sessionUserId;
return null;
}
}
public record CreateBlogPostRequest(string Title, string? Summary, string MarkdownContent, List<string>? Tags, DateTime? PublishedDate);
public record UpdateBlogPostRequest(string Title, string? Summary, string MarkdownContent, List<string>? Tags, DateTime? PublishedDate);
+11 -18
View File
@@ -6,15 +6,8 @@ namespace Media.JoshHeaps.Net.Api;
[ApiController]
[Route("api/folder")]
public class FolderApi : ControllerBase
public class FolderApi(FolderService folderService) : ControllerBase
{
private readonly FolderService _folderService;
public FolderApi(FolderService folderService)
{
_folderService = folderService;
}
[HttpGet("list")]
public async Task<IActionResult> ListFolders([FromQuery] long? folderId = null)
{
@@ -24,7 +17,7 @@ public class FolderApi : ControllerBase
return Unauthorized(new { error = "Not authenticated" });
}
var folders = await _folderService.GetUserFoldersAsync(userId.Value, folderId);
var folders = await folderService.GetUserFoldersAsync(userId.Value, folderId);
return Ok(folders);
}
@@ -37,7 +30,7 @@ public class FolderApi : ControllerBase
return Unauthorized(new { error = "Not authenticated" });
}
var path = await _folderService.GetFolderPathAsync(folderId, userId.Value);
var path = await folderService.GetFolderPathAsync(folderId, userId.Value);
return Ok(path);
}
@@ -58,14 +51,14 @@ public class FolderApi : ControllerBase
// If parent folder specified, check ownership (can't create in shared folders)
if (request.ParentFolderId.HasValue)
{
var parentOwnerId = await _folderService.GetFolderOwnerIdAsync(request.ParentFolderId.Value);
var parentOwnerId = await folderService.GetFolderOwnerIdAsync(request.ParentFolderId.Value);
if (parentOwnerId != userId.Value)
{
return Forbid("Cannot create folders in shared folders");
}
}
var folder = await _folderService.CreateFolderAsync(userId.Value, request.Name, request.ParentFolderId);
var folder = await folderService.CreateFolderAsync(userId.Value, request.Name, request.ParentFolderId);
if (folder == null)
{
return BadRequest(new { error = "Failed to create folder" });
@@ -89,13 +82,13 @@ public class FolderApi : ControllerBase
}
// Check ownership (can't rename shared folders)
var ownerId = await _folderService.GetFolderOwnerIdAsync(request.FolderId);
var ownerId = await folderService.GetFolderOwnerIdAsync(request.FolderId);
if (ownerId != userId.Value)
{
return Forbid("Cannot rename shared folders");
}
var success = await _folderService.RenameFolderAsync(request.FolderId, userId.Value, request.NewName);
var success = await folderService.RenameFolderAsync(request.FolderId, userId.Value, request.NewName);
if (!success)
{
return BadRequest(new { error = "Failed to rename folder" });
@@ -114,13 +107,13 @@ public class FolderApi : ControllerBase
}
// Check ownership (can't delete shared folders)
var ownerId = await _folderService.GetFolderOwnerIdAsync(folderId);
var ownerId = await folderService.GetFolderOwnerIdAsync(folderId);
if (ownerId != userId.Value)
{
return Forbid("Cannot delete shared folders");
}
var success = await _folderService.DeleteFolderAsync(folderId, userId.Value, deleteContents);
var success = await folderService.DeleteFolderAsync(folderId, userId.Value, deleteContents);
if (!success)
{
return BadRequest(new { error = "Failed to delete folder" });
@@ -139,13 +132,13 @@ public class FolderApi : ControllerBase
}
// Check ownership (can't move shared folders)
var ownerId = await _folderService.GetFolderOwnerIdAsync(request.FolderId);
var ownerId = await folderService.GetFolderOwnerIdAsync(request.FolderId);
if (ownerId != userId.Value)
{
return Forbid("Cannot move shared folders");
}
var success = await _folderService.MoveFolderAsync(request.FolderId, userId.Value, request.NewParentFolderId);
var success = await folderService.MoveFolderAsync(request.FolderId, userId.Value, request.NewParentFolderId);
if (!success)
{
return BadRequest(new { error = "Failed to move folder" });
+6 -15
View File
@@ -6,17 +6,8 @@ namespace Media.JoshHeaps.Net.Api;
[ApiController]
[Route("api/folder-share")]
public class FolderShareApi : ControllerBase
public class FolderShareApi(FolderService folderService, UserService userService) : ControllerBase
{
private readonly FolderService _folderService;
private readonly UserService _userService;
public FolderShareApi(FolderService folderService, UserService userService)
{
_folderService = folderService;
_userService = userService;
}
[HttpPost("share")]
public async Task<IActionResult> ShareFolder([FromBody] ShareFolderRequest request)
{
@@ -26,7 +17,7 @@ public class FolderShareApi : ControllerBase
return Unauthorized(new { error = "Not authenticated" });
}
var share = await _folderService.ShareFolderAsync(request.FolderId, userId.Value, request.SharedWithUserId);
var share = await folderService.ShareFolderAsync(request.FolderId, userId.Value, request.SharedWithUserId);
if (share == null)
{
return BadRequest(new { error = "Failed to share folder" });
@@ -44,7 +35,7 @@ public class FolderShareApi : ControllerBase
return Unauthorized(new { error = "Not authenticated" });
}
var success = await _folderService.UnshareFolderAsync(folderId, userId.Value, sharedWithUserId);
var success = await folderService.UnshareFolderAsync(folderId, userId.Value, sharedWithUserId);
if (!success)
{
return BadRequest(new { error = "Failed to unshare folder" });
@@ -62,7 +53,7 @@ public class FolderShareApi : ControllerBase
return Unauthorized(new { error = "Not authenticated" });
}
var shares = await _folderService.GetFolderSharesAsync(folderId, userId.Value);
var shares = await folderService.GetFolderSharesAsync(folderId, userId.Value);
return Ok(shares);
}
@@ -75,7 +66,7 @@ public class FolderShareApi : ControllerBase
return Unauthorized(new { error = "Not authenticated" });
}
var sharedFolders = await _folderService.GetSharedFoldersAsync(userId.Value);
var sharedFolders = await folderService.GetSharedFoldersAsync(userId.Value);
return Ok(sharedFolders);
}
@@ -93,7 +84,7 @@ public class FolderShareApi : ControllerBase
return Ok(new List<object>());
}
var users = await _userService.SearchUsersAsync(query, userId.Value);
var users = await userService.SearchUsersAsync(query, userId.Value);
return Ok(users);
}
+381
View File
@@ -0,0 +1,381 @@
using Media.JoshHeaps.Net.Services;
using Media.JoshHeaps.Net.Models;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace Media.JoshHeaps.Net.Api;
[ApiController]
[Route("api/graph")]
public class GraphApi(GraphService graphService) : ControllerBase
{
#region Graph Endpoints
[HttpGet("list")]
public async Task<IActionResult> ListGraphs()
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var graphs = await graphService.GetUserGraphsAsync(userId.Value);
return Ok(graphs);
}
[HttpGet("{graphId}")]
public async Task<IActionResult> GetGraph(long graphId)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var graph = await graphService.GetGraphByIdAsync(graphId, userId.Value);
if (graph == null)
{
return NotFound(new { error = "Graph not found" });
}
return Ok(graph);
}
[HttpGet("{graphId}/data")]
public async Task<IActionResult> GetGraphData(long graphId)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var graphData = await graphService.GetGraphDataAsync(graphId, userId.Value);
if (graphData.Graph == null || graphData.Graph.Id == 0)
{
return NotFound(new { error = "Graph not found" });
}
return Ok(graphData);
}
[HttpPost("create")]
public async Task<IActionResult> CreateGraph([FromBody] CreateGraphRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
if (string.IsNullOrWhiteSpace(request.Name))
{
return BadRequest(new { error = "Graph name is required" });
}
var graph = await graphService.CreateGraphAsync(userId.Value, request.Name, request.Description);
if (graph == null)
{
return BadRequest(new { error = "Failed to create graph" });
}
return Ok(graph);
}
[HttpPut("{graphId}")]
public async Task<IActionResult> UpdateGraph(long graphId, [FromBody] UpdateGraphRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
if (string.IsNullOrWhiteSpace(request.Name))
{
return BadRequest(new { error = "Graph name is required" });
}
var success = await graphService.UpdateGraphAsync(graphId, userId.Value, request.Name, request.Description);
if (!success)
{
return BadRequest(new { error = "Failed to update graph" });
}
return Ok(new { success = true });
}
[HttpDelete("{graphId}")]
public async Task<IActionResult> DeleteGraph(long graphId)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var success = await graphService.DeleteGraphAsync(graphId, userId.Value);
if (!success)
{
return BadRequest(new { error = "Failed to delete graph" });
}
return Ok(new { success = true });
}
[HttpPost("{graphId}/clone")]
public async Task<IActionResult> CloneGraph(long graphId, [FromBody] CloneGraphRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
if (string.IsNullOrWhiteSpace(request.NewName))
{
return BadRequest(new { error = "New graph name is required" });
}
var newGraph = await graphService.CloneGraphAsync(graphId, userId.Value, request.NewName);
if (newGraph == null)
{
return BadRequest(new { error = "Failed to clone graph" });
}
return Ok(newGraph);
}
#endregion
#region Node Endpoints
[HttpGet("{graphId}/nodes")]
public async Task<IActionResult> GetNodes(long graphId)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var nodes = await graphService.GetGraphNodesAsync(graphId, userId.Value);
return Ok(nodes);
}
[HttpPost("{graphId}/nodes")]
public async Task<IActionResult> CreateNode(long graphId, [FromBody] CreateNodeRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
if (string.IsNullOrWhiteSpace(request.Label))
{
return BadRequest(new { error = "Node label is required" });
}
var node = await graphService.CreateNodeAsync(graphId, userId.Value, request.Label, request.Notes);
if (node == null)
{
return BadRequest(new { error = "Failed to create node" });
}
return Ok(node);
}
[HttpPut("nodes/{nodeId}")]
public async Task<IActionResult> UpdateNode(long nodeId, [FromBody] UpdateNodeRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
if (string.IsNullOrWhiteSpace(request.Label))
{
return BadRequest(new { error = "Node label is required" });
}
var success = await graphService.UpdateNodeAsync(nodeId, userId.Value, request.Label, request.Notes);
if (!success)
{
return BadRequest(new { error = "Failed to update node" });
}
return Ok(new { success = true });
}
[HttpDelete("nodes/{nodeId}")]
public async Task<IActionResult> DeleteNode(long nodeId)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var success = await graphService.DeleteNodeAsync(nodeId, userId.Value);
if (!success)
{
return BadRequest(new { error = "Failed to delete node" });
}
return Ok(new { success = true });
}
[HttpGet("{graphId}/nodes/search")]
public async Task<IActionResult> SearchNodes(long graphId, [FromQuery] string q)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
if (string.IsNullOrWhiteSpace(q))
{
return BadRequest(new { error = "Search term is required" });
}
var nodes = await graphService.SearchNodesAsync(graphId, userId.Value, q);
return Ok(nodes);
}
#endregion
#region Edge Endpoints
[HttpGet("{graphId}/edges")]
public async Task<IActionResult> GetEdges(long graphId)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var edges = await graphService.GetGraphEdgesAsync(graphId, userId.Value);
return Ok(edges);
}
[HttpPost("{graphId}/edges")]
public async Task<IActionResult> CreateEdge(long graphId, [FromBody] CreateEdgeRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var edge = await graphService.CreateEdgeAsync(graphId, userId.Value, request.SourceNodeId, request.TargetNodeId);
if (edge == null)
{
return BadRequest(new { error = "Failed to create edge" });
}
return Ok(edge);
}
[HttpDelete("edges/{edgeId}")]
public async Task<IActionResult> DeleteEdge(long edgeId)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var success = await graphService.DeleteEdgeAsync(edgeId, userId.Value);
if (!success)
{
return BadRequest(new { error = "Failed to delete edge" });
}
return Ok(new { success = true });
}
#endregion
#region Filter Endpoints
[HttpGet("{graphId}/nodes/filter/connects-to/{targetNodeId}")]
public async Task<IActionResult> FilterConnectsTo(long graphId, long targetNodeId)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var nodes = await graphService.FilterConnectsToAsync(graphId, userId.Value, targetNodeId);
return Ok(nodes);
}
[HttpGet("{graphId}/nodes/filter/not-connects-to/{targetNodeId}")]
public async Task<IActionResult> FilterDoesNotConnectTo(long graphId, long targetNodeId)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var nodes = await graphService.FilterDoesNotConnectToAsync(graphId, userId.Value, targetNodeId);
return Ok(nodes);
}
[HttpGet("{graphId}/nodes/filter/two-degrees/{targetNodeId}")]
public async Task<IActionResult> FilterTwoDegrees(long graphId, long targetNodeId)
{
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var nodes = await graphService.FilterConnectsTwoDegreesAsync(graphId, userId.Value, targetNodeId);
return Ok(nodes);
}
#endregion
#region Helper Methods
private long? GetUserIdFromAuth()
{
// First try JWT claims (for mobile/API authentication)
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!string.IsNullOrEmpty(userIdClaim) && long.TryParse(userIdClaim, out var jwtUserId))
{
return jwtUserId;
}
// Fall back to session (for web authentication)
var userIdString = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userIdString) && long.TryParse(userIdString, out var sessionUserId))
{
return sessionUserId;
}
return null;
}
#endregion
}
#region Request Models
public record CreateGraphRequest(string Name, string? Description);
public record UpdateGraphRequest(string Name, string? Description);
public record CloneGraphRequest(string NewName);
public record CreateNodeRequest(string Label, string? Notes);
public record UpdateNodeRequest(string Label, string? Notes);
public record CreateEdgeRequest(long SourceNodeId, long TargetNodeId);
#endregion
+8 -17
View File
@@ -6,17 +6,8 @@ namespace Media.JoshHeaps.Net.Api;
[ApiController]
[Route("api/media")]
public class MediaApi : ControllerBase
public class MediaApi(MediaService mediaService, FolderService folderService) : ControllerBase
{
private readonly MediaService _mediaService;
private readonly FolderService _folderService;
public MediaApi(MediaService mediaService, FolderService folderService)
{
_mediaService = mediaService;
_folderService = folderService;
}
[HttpGet("load")]
public async Task<IActionResult> LoadMedia([FromQuery] int offset = 0, [FromQuery] int limit = 20, [FromQuery] long? folderId = null)
{
@@ -27,7 +18,7 @@ public class MediaApi : ControllerBase
return Unauthorized();
}
var media = await _mediaService.GetUserMediaAsync(userId.Value, offset, limit, folderId, userId.Value);
var media = await mediaService.GetUserMediaAsync(userId.Value, offset, limit, folderId, userId.Value);
return Ok(media);
}
@@ -43,14 +34,14 @@ public class MediaApi : ControllerBase
}
// Get media metadata (includes ownership check)
var media = await _mediaService.GetMediaByIdAsync(mediaId, userId.Value);
var media = await mediaService.GetMediaByIdAsync(mediaId, userId.Value);
if (media == null)
{
return NotFound(new { error = "Image not found or access denied" });
}
// Get decrypted image data
var imageData = await _mediaService.GetDecryptedMediaDataAsync(mediaId, userId.Value);
var imageData = await mediaService.GetDecryptedMediaDataAsync(mediaId, userId.Value);
if (imageData == null)
{
return NotFound(new { error = "Image file not found" });
@@ -73,7 +64,7 @@ public class MediaApi : ControllerBase
// Check folder ownership if uploading to a folder (can't upload to shared folders)
if (folderId.HasValue)
{
var ownerId = await _folderService.GetFolderOwnerIdAsync(folderId.Value);
var ownerId = await folderService.GetFolderOwnerIdAsync(folderId.Value);
if (ownerId != userId.Value)
{
return Forbid("Cannot upload to shared folders");
@@ -99,7 +90,7 @@ public class MediaApi : ControllerBase
}
// Save media using existing service
var media = await _mediaService.SaveMediaAsync(userId.Value, file, description, folderId);
var media = await mediaService.SaveMediaAsync(userId.Value, file, description, folderId);
if (media == null)
{
return StatusCode(500, new { error = "Failed to upload image" });
@@ -118,7 +109,7 @@ public class MediaApi : ControllerBase
return Unauthorized(new { error = "Not authenticated" });
}
var success = await _mediaService.MoveMediaToFolderAsync(request.MediaId, userId.Value, request.FolderId);
var success = await mediaService.MoveMediaToFolderAsync(request.MediaId, userId.Value, request.FolderId);
if (!success)
{
return BadRequest(new { error = "Failed to move media" });
@@ -147,7 +138,7 @@ public class MediaApi : ControllerBase
foreach (var mediaId in request.MediaIds)
{
var success = await _mediaService.MoveMediaToFolderAsync(mediaId, userId.Value, request.FolderId);
var success = await mediaService.MoveMediaToFolderAsync(mediaId, userId.Value, request.FolderId);
if (success)
{
successCount++;
+853
View File
@@ -0,0 +1,853 @@
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace Media.JoshHeaps.Net.Api;
[ApiController]
[Route("api/medical-docs")]
public class MedicalDocsApi(DbExecutor dbExecutor, MedicalDocsService medicalDocsService, MedicalAiService medicalAiService) : ControllerBase
{
// --- People ---
[HttpGet("people")]
public async Task<IActionResult> GetPeople()
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var people = await medicalDocsService.GetPeopleAsync();
return Ok(people);
}
[HttpPost("people")]
public async Task<IActionResult> CreatePerson([FromBody] CreatePersonRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var person = await medicalDocsService.CreatePersonAsync(request.Name.Trim(), request.DateOfBirth, request.Notes);
if (person == null)
return StatusCode(500, new { error = "Failed to create person" });
return Ok(person);
}
// --- Documents ---
[HttpGet("documents")]
public async Task<IActionResult> GetDocuments([FromQuery] long? personId, [FromQuery] int offset = 0, [FromQuery] int limit = 50)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (limit < 1 || limit > 100) limit = 50;
if (offset < 0) offset = 0;
var documents = await medicalDocsService.GetDocumentsAsync(personId, offset, limit);
return Ok(documents);
}
[HttpGet("documents/search")]
public async Task<IActionResult> SearchDocuments(
[FromQuery] long personId,
[FromQuery] string? search = null,
[FromQuery] string? classification = null,
[FromQuery] string? documentType = null,
[FromQuery] long? doctorId = null,
[FromQuery] long? tagId = null,
[FromQuery] long? conditionId = null,
[FromQuery] DateTime? fromDate = null,
[FromQuery] DateTime? toDate = null,
[FromQuery] bool? aiProcessed = null,
[FromQuery] int offset = 0,
[FromQuery] int limit = 50)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
if (limit < 1 || limit > 100) limit = 50;
if (offset < 0) offset = 0;
var documents = await medicalDocsService.SearchDocumentsAsync(personId, search, classification, documentType, doctorId, tagId, conditionId, fromDate, toDate, aiProcessed, offset, limit);
return Ok(documents);
}
[HttpGet("tags")]
public async Task<IActionResult> GetPersonTags([FromQuery] long personId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
var tags = await medicalDocsService.GetPersonTagsAsync(personId);
return Ok(tags);
}
[HttpPost("documents/upload")]
[RequestSizeLimit(52_428_800)] // 50MB
public async Task<IActionResult> UploadDocument([FromForm] long personId, [FromForm] string? title, [FromForm] string? description, [FromForm] DateTime? documentDate, [FromForm] string? classification, IFormFile file)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (file == null || file.Length == 0)
return BadRequest(new { error = "No file provided" });
var doc = await medicalDocsService.SaveDocumentAsync(personId, file, title, description, documentDate, classification);
if (doc == null)
return StatusCode(500, new { error = "Failed to save document" });
medicalAiService.EnqueueProcessing(doc.Id);
return Ok(doc);
}
[HttpPost("documents/note")]
public async Task<IActionResult> CreateNote([FromBody] CreateNoteRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" });
if (string.IsNullOrWhiteSpace(request.Title))
return BadRequest(new { error = "Title is required" });
var doc = await medicalDocsService.SaveNoteAsync(request.PersonId, request.Title.Trim(), request.Description ?? "", request.DocumentDate, request.Classification);
if (doc == null)
return StatusCode(500, new { error = "Failed to create note" });
medicalAiService.EnqueueProcessing(doc.Id);
return Ok(doc);
}
[HttpGet("documents/{id}")]
public async Task<IActionResult> GetDocument(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var doc = await medicalDocsService.GetDocumentByIdAsync(id);
if (doc == null) return NotFound(new { error = "Document not found" });
return Ok(doc);
}
[HttpGet("documents/{id}/download")]
public async Task<IActionResult> DownloadDocument(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var doc = await medicalDocsService.GetDocumentByIdAsync(id);
if (doc == null) return NotFound(new { error = "Document not found" });
if (doc.DocumentType != "file")
return BadRequest(new { error = "Cannot download a note" });
var data = await medicalDocsService.GetDecryptedDocumentDataAsync(id);
if (data == null) return NotFound(new { error = "File not found" });
return File(data, doc.MimeType ?? "application/octet-stream", doc.FileName);
}
[HttpPut("documents/{id}")]
public async Task<IActionResult> UpdateDocument(long id, [FromBody] UpdateDocumentRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
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" });
return Ok(new { success = true });
}
[HttpDelete("documents/{id}")]
public async Task<IActionResult> DeleteDocument(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeleteDocumentAsync(id);
if (!success) return NotFound(new { error = "Document not found" });
return Ok(new { success = true });
}
// --- AI Processing ---
[HttpPost("documents/{id}/process")]
public async Task<IActionResult> ProcessDocument(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var doc = await medicalDocsService.GetDocumentByIdAsync(id);
if (doc == null) return NotFound(new { error = "Document not found" });
medicalAiService.EnqueueProcessing(id);
return Ok(new { success = true, message = "AI processing started" });
}
[HttpPost("documents/process-all")]
public async Task<IActionResult> ProcessAllDocuments()
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var unprocessedIds = await medicalDocsService.GetUnprocessedDocumentIdsAsync();
foreach (var docId in unprocessedIds)
{
medicalAiService.EnqueueProcessing(docId);
}
return Ok(new { success = true, queued = unprocessedIds.Count });
}
[HttpPost("documents/process-batch")]
public async Task<IActionResult> ProcessBatch([FromBody] ProcessBatchRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.DocumentIds == null || request.DocumentIds.Count == 0)
return BadRequest(new { error = "No document IDs provided" });
var queued = 0;
foreach (var docId in request.DocumentIds)
{
var doc = await medicalDocsService.GetDocumentByIdAsync(docId);
if (doc != null)
{
medicalAiService.EnqueueProcessing(docId);
queued++;
}
}
return Ok(new { queued });
}
[HttpGet("documents/{id}/tags")]
public async Task<IActionResult> GetDocumentTags(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var tags = await medicalDocsService.GetDocumentTagsAsync(id);
return Ok(tags);
}
// --- Doctors ---
[HttpGet("doctors")]
public async Task<IActionResult> GetDoctors()
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var doctors = await medicalDocsService.GetDoctorsAsync();
return Ok(doctors);
}
[HttpPost("doctors")]
public async Task<IActionResult> CreateDoctor([FromBody] CreateDoctorRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var doctor = await medicalDocsService.CreateDoctorAsync(request.Name.Trim(), request.Specialty, request.Phone, request.Address, request.Notes);
if (doctor == null)
return StatusCode(500, new { error = "Failed to create doctor" });
return Ok(doctor);
}
[HttpPut("doctors/{id}")]
public async Task<IActionResult> UpdateDoctor(long id, [FromBody] CreateDoctorRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var success = await medicalDocsService.UpdateDoctorAsync(id, request.Name.Trim(), request.Specialty, request.Phone, request.Address, request.Notes);
if (!success) return NotFound(new { error = "Doctor not found" });
return Ok(new { success = true });
}
[HttpDelete("doctors/{id}")]
public async Task<IActionResult> DeleteDoctor(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeleteDoctorAsync(id);
if (!success) return NotFound(new { error = "Doctor not found" });
return Ok(new { success = true });
}
// --- Conditions ---
[HttpGet("conditions")]
public async Task<IActionResult> GetConditions([FromQuery] long personId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
var conditions = await medicalDocsService.GetConditionsAsync(personId);
return Ok(conditions);
}
[HttpPost("conditions")]
public async Task<IActionResult> CreateCondition([FromBody] CreateConditionRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" });
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var condition = await medicalDocsService.CreateConditionAsync(request.PersonId, request.Name.Trim(), request.DiagnosedDate, request.Notes);
if (condition == null)
return StatusCode(500, new { error = "Failed to create condition" });
return Ok(condition);
}
[HttpPut("conditions/{id}")]
public async Task<IActionResult> UpdateCondition(long id, [FromBody] UpdateConditionRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var success = await medicalDocsService.UpdateConditionAsync(id, request.Name.Trim(), request.DiagnosedDate, request.Notes, request.IsActive);
if (!success) return NotFound(new { error = "Condition not found" });
return Ok(new { success = true });
}
[HttpDelete("conditions/{id}")]
public async Task<IActionResult> DeleteCondition(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeleteConditionAsync(id);
if (!success) return NotFound(new { error = "Condition not found" });
return Ok(new { success = true });
}
// --- Prescriptions ---
[HttpGet("prescriptions")]
public async Task<IActionResult> GetPrescriptions([FromQuery] long personId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
var prescriptions = await medicalDocsService.GetPrescriptionsAsync(personId);
return Ok(prescriptions);
}
[HttpPost("prescriptions")]
public async Task<IActionResult> CreatePrescription([FromBody] CreatePrescriptionRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" });
if (string.IsNullOrWhiteSpace(request.MedicationName))
return BadRequest(new { error = "Medication name is required" });
var prescription = await medicalDocsService.CreatePrescriptionAsync(request.PersonId, request.MedicationName.Trim(), request.Dosage, request.Frequency, request.DoctorId, request.StartDate, request.Notes, request.RxNumber?.Trim());
if (prescription == null)
return StatusCode(500, new { error = "Failed to create prescription" });
return Ok(prescription);
}
[HttpPut("prescriptions/{id}")]
public async Task<IActionResult> UpdatePrescription(long id, [FromBody] UpdatePrescriptionRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.MedicationName))
return BadRequest(new { error = "Medication name is required" });
var success = await medicalDocsService.UpdatePrescriptionAsync(id, request.MedicationName.Trim(), request.Dosage, request.Frequency, request.DoctorId, request.StartDate, request.EndDate, request.Notes, request.IsActive, request.RxNumber?.Trim());
if (!success) return NotFound(new { error = "Prescription not found" });
return Ok(new { success = true });
}
[HttpDelete("prescriptions/{id}")]
public async Task<IActionResult> DeletePrescription(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeletePrescriptionAsync(id);
if (!success) return NotFound(new { error = "Prescription not found" });
return Ok(new { success = true });
}
// --- Pickups ---
[HttpGet("prescriptions/{id}/pickups")]
public async Task<IActionResult> GetPickups(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var pickups = await medicalDocsService.GetPickupsAsync(id);
return Ok(pickups);
}
[HttpPost("prescriptions/{id}/pickups")]
public async Task<IActionResult> CreatePickup(long id, [FromBody] CreatePickupRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var pickup = await medicalDocsService.CreatePickupAsync(id, request.PickupDate, request.Quantity, request.Pharmacy, request.Cost, request.Notes);
if (pickup == null)
return StatusCode(500, new { error = "Failed to create pickup" });
return Ok(pickup);
}
[HttpDelete("pickups/{id}")]
public async Task<IActionResult> DeletePickup(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeletePickupAsync(id);
if (!success) return NotFound(new { error = "Pickup not found" });
return Ok(new { success = true });
}
// --- Billing Providers ---
[HttpGet("providers")]
public async Task<IActionResult> GetProviders([FromQuery] long personId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
var providers = await medicalDocsService.GetProvidersAsync(personId);
return Ok(providers);
}
[HttpPost("providers")]
public async Task<IActionResult> CreateProvider([FromBody] CreateProviderRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" });
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var provider = await medicalDocsService.CreateProviderAsync(request.PersonId, request.Name.Trim(), request.Notes);
if (provider == null)
return StatusCode(500, new { error = "Failed to create provider" });
return Ok(provider);
}
[HttpPut("providers/{id}")]
public async Task<IActionResult> UpdateProvider(long id, [FromBody] UpdateProviderRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { error = "Name is required" });
var success = await medicalDocsService.UpdateProviderAsync(id, request.Name.Trim(), request.Notes);
if (!success) return NotFound(new { error = "Provider not found" });
return Ok(new { success = true });
}
[HttpDelete("providers/{id}")]
public async Task<IActionResult> DeleteProvider(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeleteProviderAsync(id);
if (!success) return NotFound(new { error = "Provider not found" });
return Ok(new { success = true });
}
// --- Provider Payments ---
[HttpGet("providers/{id}/payments")]
public async Task<IActionResult> GetProviderPayments(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var payments = await medicalDocsService.GetProviderPaymentsAsync(id);
return Ok(payments);
}
[HttpPost("providers/{id}/payments")]
public async Task<IActionResult> CreateProviderPayment(long id, [FromBody] CreateProviderPaymentRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.Amount <= 0)
return BadRequest(new { error = "Amount must be greater than 0" });
var payment = await medicalDocsService.CreateProviderPaymentAsync(id, request.Amount, request.PaymentDate, request.Description);
if (payment == null)
return StatusCode(500, new { error = "Failed to create payment" });
return Ok(payment);
}
[HttpDelete("provider-payments/{id}")]
public async Task<IActionResult> DeleteProviderPayment(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeleteProviderPaymentAsync(id);
if (!success) return NotFound(new { error = "Payment not found" });
return Ok(new { success = true });
}
// --- Bills ---
[HttpGet("bills")]
public async Task<IActionResult> GetBills([FromQuery] long personId, [FromQuery] long? providerId = null)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
var bills = await medicalDocsService.GetBillsAsync(personId, providerId);
return Ok(bills);
}
[HttpPost("bills")]
public async Task<IActionResult> CreateBill([FromBody] CreateBillRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.PersonId <= 0)
return BadRequest(new { error = "Person is required" });
if (request.TotalAmount <= 0)
return BadRequest(new { error = "Amount must be greater than 0" });
var bill = await medicalDocsService.CreateBillAsync(request.PersonId, request.TotalAmount, request.Summary, request.Category, request.BillDate, request.DoctorId, request.ProviderId);
if (bill == null)
return StatusCode(500, new { error = "Failed to create bill" });
return Ok(bill);
}
[HttpPut("bills/{id}")]
public async Task<IActionResult> UpdateBill(long id, [FromBody] UpdateBillRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.TotalAmount <= 0)
return BadRequest(new { error = "Amount must be greater than 0" });
var success = await medicalDocsService.UpdateBillAsync(id, request.TotalAmount, request.Summary, request.Category, request.BillDate, request.DoctorId, request.ProviderId);
if (!success) return NotFound(new { error = "Bill not found" });
return Ok(new { success = true });
}
[HttpDelete("bills/{id}")]
public async Task<IActionResult> DeleteBill(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeleteBillAsync(id);
if (!success) return NotFound(new { error = "Bill not found" });
return Ok(new { success = true });
}
[HttpPost("bills/{id}/documents")]
public async Task<IActionResult> LinkDocumentToBill(long id, [FromBody] LinkDocumentRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.DocumentId <= 0)
return BadRequest(new { error = "Document is required" });
var success = await medicalDocsService.LinkDocumentToBillAsync(id, request.DocumentId);
if (!success)
return StatusCode(500, new { error = "Failed to link document" });
return Ok(new { success = true });
}
[HttpDelete("bills/{billId}/documents/{docId}")]
public async Task<IActionResult> UnlinkDocumentFromBill(long billId, long docId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.UnlinkDocumentFromBillAsync(billId, docId);
if (!success) return NotFound(new { error = "Link not found" });
return Ok(new { success = true });
}
// --- Bill Charges ---
[HttpGet("bills/{id}/charges")]
public async Task<IActionResult> GetBillCharges(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var charges = await medicalDocsService.GetChargesAsync(id);
return Ok(charges);
}
[HttpPost("bills/{id}/charges")]
public async Task<IActionResult> CreateCharge(long id, [FromBody] CreateChargeRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (string.IsNullOrWhiteSpace(request.Description))
return BadRequest(new { error = "Description is required" });
if (request.Amount <= 0)
return BadRequest(new { error = "Amount must be greater than 0" });
var charge = await medicalDocsService.CreateChargeAsync(id, request.Description.Trim(), request.Amount);
if (charge == null)
return StatusCode(500, new { error = "Failed to create charge" });
return Ok(charge);
}
[HttpDelete("bill-charges/{id}")]
public async Task<IActionResult> DeleteCharge(long id)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
var success = await medicalDocsService.DeleteChargeAsync(id);
if (!success) return NotFound(new { error = "Charge not found" });
return Ok(new { success = true });
}
// --- Timeline ---
[HttpGet("timeline")]
public async Task<IActionResult> GetTimeline([FromQuery] long personId, [FromQuery] int offset = 0, [FromQuery] int limit = 100)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
if (limit < 1 || limit > 200) limit = 100;
if (offset < 0) offset = 0;
var events = await medicalDocsService.GetTimelineAsync(personId, offset, limit);
return Ok(events);
}
// --- Visit Prep ---
[HttpGet("visit-prep")]
public async Task<IActionResult> GetVisitPrep([FromQuery] long personId, [FromQuery] long doctorId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0 || doctorId <= 0)
return BadRequest(new { error = "personId and doctorId are required" });
var data = await medicalDocsService.GetVisitPrepAsync(personId, doctorId);
return Ok(data);
}
[HttpPost("visit-prep/summary")]
public async Task<IActionResult> GenerateVisitPrepSummary([FromBody] VisitPrepSummaryRequest request)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (request.PersonId <= 0 || request.DoctorId <= 0)
return BadRequest(new { error = "personId and doctorId are required" });
var data = await medicalDocsService.GetVisitPrepAsync(request.PersonId, request.DoctorId);
var doctor = await medicalDocsService.GetDoctorByIdAsync(request.DoctorId);
if (doctor == null)
return NotFound(new { error = "Doctor not found" });
var summary = await medicalAiService.GenerateVisitPrepSummaryAsync(doctor.Name, doctor.Specialty, data);
return Ok(new { summary });
}
[HttpGet("bills/summary")]
public async Task<IActionResult> GetBillSummary([FromQuery] long personId)
{
var userId = GetUserIdFromAuth();
if (userId == null) return Unauthorized();
if (!await HasMedicalAccess(userId.Value)) return Forbid();
if (personId <= 0)
return BadRequest(new { error = "personId is required" });
var summary = await medicalDocsService.GetBillSummaryAsync(personId);
return Ok(summary);
}
// --- Auth helpers (same pattern as AdminApi) ---
private async Task<bool> HasMedicalAccess(long userId)
{
return await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.user_roles ur JOIN app.roles r ON ur.role_id = r.id WHERE ur.user_id = @UserId AND r.name = 'medical')",
new { UserId = userId });
}
private long? GetUserIdFromAuth()
{
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!string.IsNullOrEmpty(userIdClaim) && long.TryParse(userIdClaim, out var jwtUserId))
{
return jwtUserId;
}
var userIdString = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userIdString) && long.TryParse(userIdString, out var sessionUserId))
{
return sessionUserId;
}
return null;
}
}
public record CreatePersonRequest(string Name, DateTime? DateOfBirth = null, string? Notes = null);
public record CreateNoteRequest(long PersonId, string Title, string? Description = null, DateTime? DocumentDate = null, string? Classification = null);
public record 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 CreateConditionRequest(long PersonId, string Name, DateTime? DiagnosedDate = null, string? Notes = null);
public record UpdateConditionRequest(string Name, DateTime? DiagnosedDate = null, string? Notes = null, bool IsActive = true);
public record CreatePrescriptionRequest(long PersonId, string MedicationName, string? Dosage = null, string? Frequency = null, long? DoctorId = null, DateTime? StartDate = null, string? Notes = null, string? RxNumber = null);
public record UpdatePrescriptionRequest(string MedicationName, string? Dosage = null, string? Frequency = null, long? DoctorId = null, DateTime? StartDate = null, DateTime? EndDate = null, string? Notes = null, bool IsActive = true, string? RxNumber = null);
public record CreatePickupRequest(DateTime PickupDate, string? Quantity = null, string? Pharmacy = null, decimal? Cost = null, string? Notes = null);
public record CreateProviderRequest(long PersonId, string Name, string? Notes = null);
public record UpdateProviderRequest(string Name, string? Notes = null);
public record CreateProviderPaymentRequest(decimal Amount, DateTime? PaymentDate = null, string? Description = null);
public record CreateBillRequest(long PersonId, decimal TotalAmount, string? Summary = null, string? Category = null, DateTime? BillDate = null, long? DoctorId = null, long? ProviderId = null);
public record UpdateBillRequest(decimal TotalAmount, string? Summary = null, string? Category = null, DateTime? BillDate = null, long? DoctorId = null, long? ProviderId = null);
public record LinkDocumentRequest(long DocumentId);
public record CreateChargeRequest(string Description, decimal Amount);
public record ProcessBatchRequest(List<long> DocumentIds);
public record VisitPrepSummaryRequest(long PersonId, long DoctorId);
@@ -0,0 +1,2 @@
CREATE SCHEMA IF NOT EXISTS app
AUTHORIZATION josh;
@@ -0,0 +1,16 @@
CREATE TABLE IF NOT EXISTS app.users (
id BIGSERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
username VARCHAR(50) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
is_active BOOLEAN DEFAULT TRUE,
email_verified BOOLEAN DEFAULT FALSE,
failed_login_attempts INTEGER DEFAULT 0,
locked_until TIMESTAMP NULL,
last_login TIMESTAMP NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_email ON app.users(email);
CREATE INDEX IF NOT EXISTS idx_username ON app.users(username);
@@ -0,0 +1,16 @@
-- Network Graphs Table
-- Stores user-created network graphs
CREATE TABLE IF NOT EXISTS app.graphs (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
name VARCHAR(255) NOT NULL,
description TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES app.users(id) ON DELETE CASCADE,
-- Ensure graph names are unique per user
UNIQUE (user_id, name)
);
CREATE INDEX IF NOT EXISTS idx_graphs_user_id ON app.graphs(user_id);
CREATE INDEX IF NOT EXISTS idx_graphs_name ON app.graphs(name);
@@ -0,0 +1,15 @@
-- Graph Nodes Table
-- Stores nodes within network graphs
-- Node positions are calculated automatically by the client using community detection
CREATE TABLE IF NOT EXISTS app.graph_nodes (
id BIGSERIAL PRIMARY KEY,
graph_id BIGINT NOT NULL,
label VARCHAR(255) NOT NULL,
notes TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (graph_id) REFERENCES app.graphs(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_graph_nodes_graph_id ON app.graph_nodes(graph_id);
CREATE INDEX IF NOT EXISTS idx_graph_nodes_label ON app.graph_nodes(label);
@@ -0,0 +1,22 @@
-- Graph Edges Table
-- Stores connections/relationships between nodes in a graph
CREATE TABLE IF NOT EXISTS app.graph_edges (
id BIGSERIAL PRIMARY KEY,
graph_id BIGINT NOT NULL,
source_node_id BIGINT NOT NULL,
target_node_id BIGINT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (graph_id) REFERENCES app.graphs(id) ON DELETE CASCADE,
FOREIGN KEY (source_node_id) REFERENCES app.graph_nodes(id) ON DELETE CASCADE,
FOREIGN KEY (target_node_id) REFERENCES app.graph_nodes(id) ON DELETE CASCADE,
-- Prevent duplicate edges between the same nodes
UNIQUE (graph_id, source_node_id, target_node_id),
-- Prevent self-loops (node connecting to itself)
CHECK (source_node_id != target_node_id)
);
CREATE INDEX IF NOT EXISTS idx_graph_edges_graph_id ON app.graph_edges(graph_id);
CREATE INDEX IF NOT EXISTS idx_graph_edges_source_node_id ON app.graph_edges(source_node_id);
CREATE INDEX IF NOT EXISTS idx_graph_edges_target_node_id ON app.graph_edges(target_node_id);
-- Composite index for efficient bidirectional queries
CREATE INDEX IF NOT EXISTS idx_graph_edges_nodes ON app.graph_edges(source_node_id, target_node_id);
@@ -0,0 +1,20 @@
-- Roles table for role-based access control
CREATE TABLE IF NOT EXISTS app.roles (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(50) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Seed the admin role
INSERT INTO app.roles (name) VALUES ('admin') ON CONFLICT (name) DO NOTHING;
-- User roles junction table
CREATE TABLE IF NOT EXISTS app.user_roles (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES app.users(id),
role_id BIGINT NOT NULL REFERENCES app.roles(id),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uq_user_role UNIQUE (user_id, role_id)
);
CREATE INDEX IF NOT EXISTS idx_user_roles_user_id ON app.user_roles(user_id);
@@ -0,0 +1,9 @@
-- Medical people (family members, not tied to app users)
CREATE TABLE IF NOT EXISTS app.medical_people (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
date_of_birth DATE NULL,
notes TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1,11 @@
-- Medical doctors
CREATE TABLE IF NOT EXISTS app.medical_doctors (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
specialty VARCHAR(255) NULL,
phone VARCHAR(50) NULL,
address TEXT NULL,
notes TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1,13 @@
-- Medical conditions linked to people
CREATE TABLE IF NOT EXISTS app.medical_conditions (
id BIGSERIAL PRIMARY KEY,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
diagnosed_date DATE NULL,
notes TEXT NULL,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_medical_conditions_person_id ON app.medical_conditions(person_id);
@@ -0,0 +1,29 @@
-- Core medical documents table
CREATE TABLE IF NOT EXISTS app.medical_documents (
id BIGSERIAL PRIMARY KEY,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
document_type VARCHAR(10) NOT NULL DEFAULT 'file', -- 'file' or 'note'
file_name VARCHAR(255) NULL,
file_path VARCHAR(500) NULL,
file_size BIGINT NULL,
mime_type VARCHAR(100) NULL,
is_encrypted BOOLEAN DEFAULT true,
title VARCHAR(500) NULL,
description TEXT NULL,
document_date DATE NULL, -- the date OF the document
classification VARCHAR(100) NULL, -- receipt, lab_result, prescription, imaging, etc.
extracted_text TEXT NULL,
ai_processed BOOLEAN DEFAULT false,
ai_processed_at TIMESTAMP NULL,
ai_raw_response JSONB NULL,
doctor_id BIGINT NULL REFERENCES app.medical_doctors(id) ON DELETE SET NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_medical_documents_person_id ON app.medical_documents(person_id);
CREATE INDEX IF NOT EXISTS idx_medical_documents_doctor_id ON app.medical_documents(doctor_id);
CREATE INDEX IF NOT EXISTS idx_medical_documents_classification ON app.medical_documents(classification);
CREATE INDEX IF NOT EXISTS idx_medical_documents_document_date ON app.medical_documents(document_date);
CREATE INDEX IF NOT EXISTS idx_medical_documents_created_at ON app.medical_documents(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_medical_documents_ai_processed ON app.medical_documents(ai_processed);
@@ -0,0 +1,16 @@
-- Medical tags and document-tag junction
CREATE TABLE IF NOT EXISTS app.medical_tags (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS app.medical_document_tags (
document_id BIGINT NOT NULL REFERENCES app.medical_documents(id) ON DELETE CASCADE,
tag_id BIGINT NOT NULL REFERENCES app.medical_tags(id) ON DELETE CASCADE,
source VARCHAR(10) NOT NULL DEFAULT 'manual', -- 'ai' or 'manual'
CONSTRAINT uq_medical_document_tag UNIQUE (document_id, tag_id)
);
CREATE INDEX IF NOT EXISTS idx_medical_document_tags_document_id ON app.medical_document_tags(document_id);
CREATE INDEX IF NOT EXISTS idx_medical_document_tags_tag_id ON app.medical_document_tags(tag_id);
@@ -0,0 +1,32 @@
-- Medical prescriptions and pickup tracking
CREATE TABLE IF NOT EXISTS app.medical_prescriptions (
id BIGSERIAL PRIMARY KEY,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
doctor_id BIGINT NULL REFERENCES app.medical_doctors(id) ON DELETE SET NULL,
medication_name VARCHAR(255) NOT NULL,
dosage VARCHAR(100) NULL,
frequency VARCHAR(100) NULL,
is_active BOOLEAN DEFAULT true,
start_date DATE NULL,
end_date DATE NULL,
notes TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_medical_prescriptions_person_id ON app.medical_prescriptions(person_id);
CREATE INDEX IF NOT EXISTS idx_medical_prescriptions_doctor_id ON app.medical_prescriptions(doctor_id);
CREATE TABLE IF NOT EXISTS app.medical_prescription_pickups (
id BIGSERIAL PRIMARY KEY,
prescription_id BIGINT NOT NULL REFERENCES app.medical_prescriptions(id) ON DELETE CASCADE,
document_id BIGINT NULL REFERENCES app.medical_documents(id) ON DELETE SET NULL,
pickup_date DATE NOT NULL,
quantity VARCHAR(100) NULL,
pharmacy VARCHAR(255) NULL,
cost DECIMAL(10,2) NULL,
notes TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_medical_prescription_pickups_prescription_id ON app.medical_prescription_pickups(prescription_id);
@@ -0,0 +1,16 @@
-- Medical document costs
CREATE TABLE IF NOT EXISTS app.medical_document_costs (
id BIGSERIAL PRIMARY KEY,
document_id BIGINT NOT NULL REFERENCES app.medical_documents(id) ON DELETE CASCADE,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
amount DECIMAL(10,2) NOT NULL,
cost_type VARCHAR(50) NULL, -- copay, deductible, out_of_pocket, etc.
category VARCHAR(50) NULL, -- office_visit, lab, pharmacy, etc.
cost_date DATE NULL,
description TEXT NULL,
source VARCHAR(10) NOT NULL DEFAULT 'manual', -- 'ai' or 'manual'
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_medical_document_costs_document_id ON app.medical_document_costs(document_id);
CREATE INDEX IF NOT EXISTS idx_medical_document_costs_person_id ON app.medical_document_costs(person_id);
@@ -0,0 +1,9 @@
-- Junction table linking medical documents to conditions
CREATE TABLE IF NOT EXISTS app.medical_document_conditions (
document_id BIGINT NOT NULL REFERENCES app.medical_documents(id) ON DELETE CASCADE,
condition_id BIGINT NOT NULL REFERENCES app.medical_conditions(id) ON DELETE CASCADE,
CONSTRAINT uq_medical_document_condition UNIQUE (document_id, condition_id)
);
CREATE INDEX IF NOT EXISTS idx_medical_document_conditions_document_id ON app.medical_document_conditions(document_id);
CREATE INDEX IF NOT EXISTS idx_medical_document_conditions_condition_id ON app.medical_document_conditions(condition_id);
@@ -0,0 +1,36 @@
-- Migration 021: Medical Bills & Payments
-- Replaces the flat medical_document_costs model with proper billing:
-- Bills (charges) with Payments (receipts) tracked against them.
CREATE TABLE IF NOT EXISTS app.medical_bills (
id BIGSERIAL PRIMARY KEY,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
total_amount DECIMAL(10,2) NOT NULL,
summary TEXT,
category VARCHAR(50),
bill_date DATE,
doctor_id BIGINT REFERENCES app.medical_doctors(id) ON DELETE SET NULL,
source VARCHAR(10) NOT NULL DEFAULT 'manual',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS app.medical_bill_documents (
id BIGSERIAL PRIMARY KEY,
bill_id BIGINT NOT NULL REFERENCES app.medical_bills(id) ON DELETE CASCADE,
document_id BIGINT NOT NULL REFERENCES app.medical_documents(id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(bill_id, document_id)
);
CREATE TABLE IF NOT EXISTS app.medical_bill_payments (
id BIGSERIAL PRIMARY KEY,
bill_id BIGINT NOT NULL REFERENCES app.medical_bills(id) ON DELETE CASCADE,
document_id BIGINT REFERENCES app.medical_documents(id) ON DELETE SET NULL,
amount DECIMAL(10,2) NOT NULL,
payment_type VARCHAR(30) NOT NULL,
payment_date DATE,
description TEXT,
source VARCHAR(10) NOT NULL DEFAULT 'manual',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1,11 @@
-- Migration 022: Bill Line Items (Charges)
-- Breaks down bill totals into individual named charges.
CREATE TABLE IF NOT EXISTS app.medical_bill_charges (
id BIGSERIAL PRIMARY KEY,
bill_id BIGINT NOT NULL REFERENCES app.medical_bills(id) ON DELETE CASCADE,
description TEXT NOT NULL,
amount DECIMAL(10,2) NOT NULL,
source VARCHAR(10) NOT NULL DEFAULT 'manual',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1,28 @@
-- 023: Medical billing providers
-- Providers are the top-level billing entity. Bills belong to a provider, payments go to a provider.
CREATE TABLE IF NOT EXISTS app.medical_billing_providers (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
person_id BIGINT NOT NULL REFERENCES app.medical_people(id) ON DELETE CASCADE,
notes TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_billing_providers_name_person
ON app.medical_billing_providers (LOWER(name), person_id);
ALTER TABLE app.medical_bills ADD COLUMN IF NOT EXISTS provider_id BIGINT
REFERENCES app.medical_billing_providers(id) ON DELETE SET NULL;
CREATE TABLE IF NOT EXISTS app.medical_provider_payments (
id BIGSERIAL PRIMARY KEY,
provider_id BIGINT NOT NULL REFERENCES app.medical_billing_providers(id) ON DELETE CASCADE,
document_id BIGINT REFERENCES app.medical_documents(id) ON DELETE SET NULL,
amount DECIMAL(10,2) NOT NULL,
payment_date DATE,
description TEXT,
source VARCHAR(10) NOT NULL DEFAULT 'manual',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1 @@
ALTER TABLE app.medical_prescriptions ADD COLUMN IF NOT EXISTS rx_number VARCHAR(50) NULL;
@@ -0,0 +1,30 @@
CREATE TABLE IF NOT EXISTS app.blog_posts (
id BIGSERIAL PRIMARY KEY,
slug VARCHAR(200) UNIQUE NOT NULL,
title VARCHAR(500) NOT NULL,
summary TEXT NOT NULL DEFAULT '',
markdown_content TEXT NOT NULL,
html_content TEXT NOT NULL,
tags TEXT[] NOT NULL DEFAULT '{}',
author_id BIGINT NOT NULL REFERENCES app.users(id),
published_date TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_blog_posts_slug ON app.blog_posts(slug);
CREATE INDEX IF NOT EXISTS idx_blog_posts_published_date ON app.blog_posts(published_date DESC);
-- Seed existing blog post
INSERT INTO app.blog_posts (slug, title, summary, markdown_content, html_content, tags, author_id, published_date)
SELECT
'my-first-post',
'My First Post',
'Welcome to my blog! Here I''ll share thoughts on software development, projects I''m working on, and things I find interesting.',
E'# Welcome to My Blog\n\nI''ve been meaning to start writing about the things I build and learn, and I''m finally getting around to it.\n\n## What to Expect\n\nI plan to write about:\n\n- **Projects** I''m working on, like this website and the other things on my portfolio\n- **Software development** tips and patterns I find useful\n- **Problem solving** approaches that have helped me grow as a developer\n\n## Why a Blog?\n\nBuilding things is great, but explaining *how* and *why* you built them is just as valuable. Writing forces you to organize your thoughts, and hopefully someone else finds it useful along the way.\n\nStay tuned for more posts!',
E'<h1>Welcome to My Blog</h1>\n<p>I''ve been meaning to start writing about the things I build and learn, and I''m finally getting around to it.</p>\n<h2>What to Expect</h2>\n<p>I plan to write about:</p>\n<ul>\n<li><strong>Projects</strong> I''m working on, like this website and the other things on my portfolio</li>\n<li><strong>Software development</strong> tips and patterns I find useful</li>\n<li><strong>Problem solving</strong> approaches that have helped me grow as a developer</li>\n</ul>\n<h2>Why a Blog?</h2>\n<p>Building things is great, but explaining <em>how</em> and <em>why</em> you built them is just as valuable. Writing forces you to organize your thoughts, and hopefully someone else finds it useful along the way.</p>\n<p>Stay tuned for more posts!</p>',
ARRAY['dev', 'personal'],
(SELECT id FROM app.users WHERE id = 1),
'2026-03-06T00:00:00Z'
WHERE EXISTS (SELECT 1 FROM app.users WHERE id = 1)
AND NOT EXISTS (SELECT 1 FROM app.blog_posts WHERE slug = 'my-first-post');
+16
View File
@@ -103,4 +103,20 @@ public class DbExecutor(IConfiguration config)
return results;
}
// Executes a non-query command (INSERT, UPDATE, DELETE) and returns rows affected
public async Task<int> ExecuteNonQueryAsync(string query, object? parameters = null)
{
parameters ??= new();
using var conn = new NpgsqlConnection(ConnectionString);
await conn.OpenAsync();
using var cmd = new NpgsqlCommand(query, conn);
foreach (var prop in parameters.GetType().GetProperties())
{
cmd.Parameters.AddWithValue($"@{prop.Name}", prop.GetValue(parameters) ?? DBNull.Value);
}
return await cmd.ExecuteNonQueryAsync();
}
}
@@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="MailKit" Version="4.8.0" />
<PackageReference Include="Markdig" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.11" />
<PackageReference Include="Npgsql" Version="9.0.4" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
+16
View File
@@ -0,0 +1,16 @@
namespace Media.JoshHeaps.Net.Models;
public class BlogPost
{
public long Id { get; set; }
public string Slug { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string Summary { get; set; } = string.Empty;
public string MarkdownContent { get; set; } = string.Empty;
public string HtmlContent { get; set; } = string.Empty;
public List<string> Tags { get; set; } = [];
public long AuthorId { get; set; }
public DateTime PublishedDate { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
+17
View File
@@ -0,0 +1,17 @@
namespace Media.JoshHeaps.Net.Models;
public class Graph
{
public long Id { get; set; }
public long UserId { get; set; }
public string Name { get; set; } = string.Empty;
public string? Description { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
public class GraphWithCounts : Graph
{
public int NodeCount { get; set; }
public int EdgeCount { get; set; }
}
+17
View File
@@ -0,0 +1,17 @@
namespace Media.JoshHeaps.Net.Models;
public class GraphEdge
{
public long Id { get; set; }
public long GraphId { get; set; }
public long SourceNodeId { get; set; }
public long TargetNodeId { get; set; }
public DateTime CreatedAt { get; set; }
}
public class GraphData
{
public Graph Graph { get; set; } = new();
public List<GraphNodeWithConnections> Nodes { get; set; } = [];
public List<GraphEdge> Edges { get; set; } = [];
}
+16
View File
@@ -0,0 +1,16 @@
namespace Media.JoshHeaps.Net.Models;
public class GraphNode
{
public long Id { get; set; }
public long GraphId { get; set; }
public string Label { get; set; } = string.Empty;
public string? Notes { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
public class GraphNodeWithConnections : GraphNode
{
public int ConnectionCount { get; set; }
}
+21
View File
@@ -0,0 +1,21 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalBill
{
public long Id { get; set; }
public long PersonId { get; set; }
public decimal TotalAmount { get; set; }
public string? Summary { get; set; }
public string? Category { get; set; }
public DateTime? BillDate { get; set; }
public long? DoctorId { get; set; }
public long? ProviderId { get; set; }
public string Source { get; set; } = "manual";
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
// Populated via JOIN, not stored in DB
public string? DoctorName { get; set; }
public string? ProviderName { get; set; }
public string? DocumentNames { get; set; }
}
@@ -0,0 +1,11 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalBillCharge
{
public long Id { get; set; }
public long BillId { get; set; }
public string Description { get; set; } = "";
public decimal Amount { get; set; }
public string Source { get; set; } = "manual";
public DateTime CreatedAt { get; set; }
}
@@ -0,0 +1,17 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalBillPayment
{
public long Id { get; set; }
public long BillId { get; set; }
public long? DocumentId { get; set; }
public decimal Amount { get; set; }
public string PaymentType { get; set; } = string.Empty;
public DateTime? PaymentDate { get; set; }
public string? Description { get; set; }
public string Source { get; set; } = "manual";
public DateTime CreatedAt { get; set; }
// Populated via JOIN, not stored in DB
public string? DocumentName { get; set; }
}
@@ -0,0 +1,18 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalBillingProvider
{
public long Id { get; set; }
public string Name { get; set; } = "";
public long PersonId { get; set; }
public string? Notes { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
// Populated via aggregation, not stored in DB
public decimal TotalCharged { get; set; }
public decimal TotalPaid { get; set; }
public int BillCount { get; set; }
public decimal Balance => TotalCharged - TotalPaid;
}
@@ -0,0 +1,13 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalCondition
{
public long Id { get; set; }
public long PersonId { get; set; }
public string Name { get; set; } = string.Empty;
public DateTime? DiagnosedDate { get; set; }
public string? Notes { get; set; }
public bool IsActive { get; set; } = true;
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,13 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalDoctor
{
public long Id { get; set; }
public string Name { get; set; } = string.Empty;
public string? Specialty { get; set; }
public string? Phone { get; set; }
public string? Address { get; set; }
public string? Notes { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,27 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalDocument
{
public long Id { get; set; }
public long PersonId { get; set; }
public string DocumentType { get; set; } = "file"; // "file" or "note"
public string? FileName { get; set; }
public string? FilePath { get; set; }
public long? FileSize { get; set; }
public string? MimeType { get; set; }
public bool IsEncrypted { get; set; } = true;
public string? Title { get; set; }
public string? Description { get; set; }
public DateTime? DocumentDate { get; set; }
public string? Classification { get; set; }
public string? ExtractedText { get; set; }
public bool AiProcessed { get; set; }
public DateTime? AiProcessedAt { get; set; }
public string? AiRawResponse { get; set; }
public long? DoctorId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
// Convenience properties populated separately
public List<MedicalTag> Tags { get; set; } = [];
}
@@ -0,0 +1,11 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalPerson
{
public long Id { get; set; }
public string Name { get; set; } = string.Empty;
public DateTime? DateOfBirth { get; set; }
public string? Notes { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
@@ -0,0 +1,22 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalPrescription
{
public long Id { get; set; }
public long PersonId { get; set; }
public long? DoctorId { get; set; }
public string MedicationName { get; set; } = string.Empty;
public string? Dosage { get; set; }
public string? Frequency { get; set; }
public string? RxNumber { get; set; }
public bool IsActive { get; set; } = true;
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string? Notes { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
// Populated via JOIN, not stored in DB
public string? DoctorName { get; set; }
public DateTime? LastPickupDate { get; set; }
}
@@ -0,0 +1,14 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalPrescriptionPickup
{
public long Id { get; set; }
public long PrescriptionId { get; set; }
public long? DocumentId { get; set; }
public DateTime PickupDate { get; set; }
public string? Quantity { get; set; }
public string? Pharmacy { get; set; }
public decimal? Cost { get; set; }
public string? Notes { get; set; }
public DateTime CreatedAt { get; set; }
}
@@ -0,0 +1,13 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalProviderPayment
{
public long Id { get; set; }
public long ProviderId { get; set; }
public long? DocumentId { get; set; }
public decimal Amount { get; set; }
public DateTime? PaymentDate { get; set; }
public string? Description { get; set; }
public string Source { get; set; } = "manual";
public DateTime CreatedAt { get; set; }
}
+8
View File
@@ -0,0 +1,8 @@
namespace Media.JoshHeaps.Net.Models;
public class MedicalTag
{
public long Id { get; set; }
public string Name { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
}
@@ -0,0 +1,13 @@
namespace Media.JoshHeaps.Net.Models;
public class TimelineEvent
{
public string EventType { get; set; } = "";
public long Id { get; set; }
public string? Label { get; set; }
public string? Detail { get; set; }
public string? SubType { get; set; }
public DateTime? EventDate { get; set; }
public long? DoctorId { get; set; }
public DateTime CreatedAt { get; set; }
}
@@ -0,0 +1,27 @@
namespace Media.JoshHeaps.Net.Models;
public class VisitPrepData
{
public List<VisitPrepDocument> RecentDocuments { get; set; } = [];
public List<MedicalCondition> ActiveConditions { get; set; } = [];
public List<MedicalPrescription> ActivePrescriptions { get; set; } = [];
public List<VisitPrepBill> RecentBills { get; set; } = [];
}
public class VisitPrepDocument
{
public long Id { get; set; }
public string? Title { get; set; }
public string? FileName { get; set; }
public DateTime? DocumentDate { get; set; }
public string? Classification { get; set; }
}
public class VisitPrepBill
{
public long Id { get; set; }
public decimal TotalAmount { get; set; }
public string? Summary { get; set; }
public string? Category { get; set; }
public DateTime? BillDate { get; set; }
}
+64
View File
@@ -0,0 +1,64 @@
@page
@model Media.JoshHeaps.Net.Pages.AdminModel
@{
ViewData["Title"] = "Admin";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/admin.css" asp-append-version="true" />
}
<div class="dashboard-container">
<div class="welcome-section">
<div class="welcome-left">
<a href="/Landing" class="back-button" title="Back to Home">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="19" y1="12" x2="5" y2="12"></line>
<polyline points="12 19 5 12 12 5"></polyline>
</svg>
</a>
<h1>Admin</h1>
</div>
<div class="quick-actions">
<a href="/Profile" class="btn btn-secondary">Profile</a>
<a href="/Logout" class="btn btn-danger">Logout</a>
</div>
</div>
<div class="admin-section">
<div class="section-header">
<h2>Roles</h2>
</div>
<div class="roles-list" id="rolesList"></div>
<div class="create-role-form">
<input type="text" id="newRoleName" placeholder="New role name" class="form-input" />
<button id="createRoleBtn" class="btn btn-primary">Create Role</button>
</div>
</div>
<div class="admin-section">
<div class="section-header">
<h2>Users</h2>
</div>
<div class="table-container">
<table class="admin-table">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Roles</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="usersTableBody">
</tbody>
</table>
</div>
<div class="pagination" id="pagination"></div>
</div>
</div>
@section Scripts {
<script src="~/js/admin.js" asp-append-version="true"></script>
}
+20
View File
@@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Mvc;
namespace Media.JoshHeaps.Net.Pages
{
public class AdminModel(DbExecutor dbExecutor) : AuthenticatedPageModel
{
private readonly DbExecutor _dbExecutor = dbExecutor;
public async Task<IActionResult> OnGetAsync()
{
RequireAuthentication();
LoadUserSession();
var denied = await RequireRole("admin", _dbExecutor);
if (denied != null) return denied;
return Page();
}
}
}
@@ -5,6 +5,15 @@ namespace Media.JoshHeaps.Net.Pages;
public abstract class AuthenticatedPageModel : PageModel
{
protected async Task<IActionResult?> RequireRole(string role, DbExecutor dbExecutor)
{
var hasRole = await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.user_roles ur JOIN app.roles r ON ur.role_id = r.id WHERE ur.user_id = @UserId AND r.name = @Role)",
new { UserId, Role = role });
return hasRole ? null : NotFound();
}
public long UserId { get; private set; }
protected string Username { get; private set; } = string.Empty;
protected string Email { get; private set; } = string.Empty;
@@ -0,0 +1,87 @@
@page
@model Media.JoshHeaps.Net.Pages.BlogAdminModel
@{
ViewData["Title"] = "Blog Admin";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/blog-admin.css" asp-append-version="true" />
}
<div class="dashboard-container">
<div class="welcome-section">
<div class="welcome-left">
<a href="/Admin" class="back-button" title="Back to Admin">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="19" y1="12" x2="5" y2="12"></line>
<polyline points="12 19 5 12 12 5"></polyline>
</svg>
</a>
<h1>Blog Admin</h1>
</div>
<div class="quick-actions">
<button id="newPostBtn" class="btn btn-primary">New Post</button>
</div>
</div>
<div id="postsList" class="admin-section">
<div class="section-header">
<h2>Posts</h2>
</div>
<div class="table-container">
<table class="admin-table">
<thead>
<tr>
<th>Title</th>
<th>Slug</th>
<th>Tags</th>
<th>Published</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="postsTableBody"></tbody>
</table>
</div>
</div>
<div id="postEditor" class="admin-section" style="display: none;">
<div class="section-header">
<h2 id="editorTitle">New Post</h2>
</div>
<input type="hidden" id="editPostId" />
<div class="form-group">
<label for="postTitle">Title</label>
<input type="text" id="postTitle" class="form-input" placeholder="Post title" />
</div>
<div class="form-group">
<label for="postSummary">Summary</label>
<input type="text" id="postSummary" class="form-input" placeholder="Brief summary" />
</div>
<div class="form-group">
<label for="postTags">Tags (comma-separated)</label>
<input type="text" id="postTags" class="form-input" placeholder="dev, personal" />
</div>
<div class="form-group">
<label for="postDate">Published Date</label>
<input type="date" id="postDate" class="form-input" />
</div>
<div class="form-group">
<label for="postContent">Markdown Content</label>
<div class="content-toolbar">
<button type="button" id="uploadImageBtn" class="btn btn-secondary btn-sm">Upload Image</button>
<input type="file" id="imageFileInput" accept="image/jpeg,image/png,image/gif,image/webp" style="display: none;" />
<span id="uploadStatus" class="upload-status"></span>
</div>
<textarea id="postContent" class="form-input form-textarea" placeholder="Write your post in markdown..."></textarea>
</div>
<div class="editor-actions">
<button id="savePostBtn" class="btn btn-primary">Save</button>
<button id="cancelEditBtn" class="btn btn-secondary">Cancel</button>
</div>
</div>
</div>
@section Scripts {
<script src="~/js/blog-admin.js" asp-append-version="true"></script>
}
@@ -0,0 +1,19 @@
using Microsoft.AspNetCore.Mvc;
namespace Media.JoshHeaps.Net.Pages;
public class BlogAdminModel(DbExecutor dbExecutor) : AuthenticatedPageModel
{
private readonly DbExecutor _dbExecutor = dbExecutor;
public async Task<IActionResult> OnGetAsync()
{
RequireAuthentication();
LoadUserSession();
var denied = await RequireRole("admin", _dbExecutor);
if (denied != null) return denied;
return Page();
}
}
@@ -1,18 +1,26 @@
@page "{handler?}"
@model Media.JoshHeaps.Net.Pages.IndexModel
@model Media.JoshHeaps.Net.Pages.GalleryModel
@{
ViewData["Title"] = "Dashboard";
ViewData["Title"] = "Gallery";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/Home/page.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/Gallery/page.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/gallery.css" asp-append-version="true" />
}
<div class="dashboard-container">
<div class="welcome-section">
<div class="welcome-left">
<a href="/Landing" class="back-button" title="Back to Home">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="19" y1="12" x2="5" y2="12"></line>
<polyline points="12 19 5 12 12 5"></polyline>
</svg>
</a>
<h1>Welcome back, @Model.Dashboard?.Username!</h1>
</div>
<div class="quick-actions">
@if (Model.Dashboard?.EmailVerified == false)
{
@@ -59,11 +67,11 @@
<div class="card">
<div class="gallery-header">
<div class="breadcrumb-nav">
<a href="/[email protected]">Home</a>
<a href="/Gallery[email protected]">Home</a>
@foreach (var folder in Model.FolderPath)
{
<span class="breadcrumb-separator">/</span>
<a href="/[email protected]&[email protected]">@folder.Name</a>
<a href="/Gallery[email protected]&[email protected]">@folder.Name</a>
}
@if (Model.IsSharedFolder && !string.IsNullOrEmpty(Model.SharedByUsername))
{
@@ -72,9 +80,9 @@
</div>
<div class="header-actions">
<div class="view-mode-toggle">
<a href="/?view=own" class="view-mode-btn @(Model.ViewMode == "own" ? "active" : "")">My Folders</a>
<a href="/?view=shared" class="view-mode-btn @(Model.ViewMode == "shared" ? "active" : "")">Shared with Me</a>
<a href="/?view=all" class="view-mode-btn @(Model.ViewMode == "all" ? "active" : "")">All</a>
<a href="/Gallery?view=own" class="view-mode-btn @(Model.ViewMode == "own" ? "active" : "")">My Folders</a>
<a href="/Gallery?view=shared" class="view-mode-btn @(Model.ViewMode == "shared" ? "active" : "")">Shared with Me</a>
<a href="/Gallery?view=all" class="view-mode-btn @(Model.ViewMode == "all" ? "active" : "")">All</a>
</div>
@if (!Model.IsSharedFolder)
{
@@ -97,8 +105,8 @@
@if (Model.CurrentFolderId.HasValue)
{
var backUrl = Model.FolderPath.Count > 1
? $"/?folderId={Model.FolderPath[Model.FolderPath.Count - 2].Id}&view={Model.ViewMode}"
: $"/?view={Model.ViewMode}";
? $"/Gallery?folderId={Model.FolderPath[Model.FolderPath.Count - 2].Id}&view={Model.ViewMode}"
: $"/Gallery?view={Model.ViewMode}";
<div class="gallery-item folder-item" data-folder-id="back" onclick="window.location.href='@backUrl'">
<div class="folder-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
@@ -110,7 +118,7 @@
}
@foreach (var sharedFolder in Model.SharedFolders)
{
<div class="gallery-item folder-item shared-folder-item" data-folder-id="@sharedFolder.FolderId" onclick="window.location.href='/[email protected]&[email protected]'">
<div class="gallery-item folder-item shared-folder-item" data-folder-id="@sharedFolder.FolderId" onclick="window.location.href='/Gallery[email protected]&[email protected]'">
<div class="folder-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
@@ -125,7 +133,7 @@
}
@foreach (var folder in Model.Folders)
{
<div class="gallery-item folder-item @(folder.UserId != Model.UserId ? "shared-folder-item" : "")" data-folder-id="@folder.Id" data-owner-id="@folder.UserId" onclick="window.location.href='/[email protected]&[email protected]'">
<div class="gallery-item folder-item @(folder.UserId != Model.UserId ? "shared-folder-item" : "")" data-folder-id="@folder.Id" data-owner-id="@folder.UserId" onclick="window.location.href='/Gallery[email protected]&[email protected]'">
<div class="folder-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
@@ -4,16 +4,16 @@ using Microsoft.AspNetCore.Mvc;
namespace Media.JoshHeaps.Net.Pages
{
public class IndexModel(UserService userService, MediaService mediaService, FolderService folderService) : AuthenticatedPageModel
public class GalleryModel(UserService userService, MediaService mediaService, FolderService folderService) : AuthenticatedPageModel
{
private readonly MediaService _mediaService = mediaService;
private readonly FolderService _folderService = folderService;
public UserDashboard? Dashboard { get; set; }
public List<UserMedia> MediaItems { get; set; } = new();
public List<Folder> Folders { get; set; } = new();
public List<Folder> FolderPath { get; set; } = new();
public List<SharedFolderInfo> SharedFolders { get; set; } = new();
public List<UserMedia> MediaItems { get; set; } = [];
public List<Folder> Folders { get; set; } = [];
public List<Folder> FolderPath { get; set; } = [];
public List<SharedFolderInfo> SharedFolders { get; set; } = [];
public long? CurrentFolderId { get; set; }
public bool IsSharedFolder { get; set; }
public long? FolderOwnerId { get; set; }
@@ -64,7 +64,7 @@ namespace Media.JoshHeaps.Net.Pages
SharedFolders = await _folderService.GetSharedFoldersAsync(UserId);
if (!CurrentFolderId.HasValue)
{
Folders = new List<Folder>();
Folders = [];
}
else if (IsSharedFolder && FolderOwnerId.HasValue)
{
+190
View File
@@ -0,0 +1,190 @@
@page
@model Media.JoshHeaps.Net.Pages.LandingModel
@{
ViewData["Title"] = "Home";
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Media Manager</title>
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/landing.css" asp-append-version="true" />
<script src="~/js/theme.js" asp-append-version="true"></script>
</head>
<body>
<div class="landing-wrapper">
<div class="landing-container">
<div class="landing-header">
<div class="logo-area">
<div class="logo-circle">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path>
<polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline>
<line x1="12" y1="22.08" x2="12" y2="12"></line>
</svg>
</div>
<h1>Welcome Back</h1>
<p class="subtitle">Choose a workspace to continue</p>
</div>
</div>
<div class="cards-grid">
<a href="/Gallery" class="landing-card">
<div class="card-content">
<div class="card-icon-wrapper">
<div class="card-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
<circle cx="8.5" cy="8.5" r="1.5"></circle>
<polyline points="21 15 16 10 5 21"></polyline>
</svg>
</div>
</div>
<div class="card-text">
<h2>Media Storage</h2>
<p class="card-description">Upload, organize, and manage your images in folders with sharing capabilities</p>
</div>
</div>
<div class="card-footer">
<span class="card-link-text">Open workspace</span>
<div class="card-arrow">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="5" y1="12" x2="19" y2="12"></line>
<polyline points="12 5 19 12 12 19"></polyline>
</svg>
</div>
</div>
</a>
<a href="/NetworkGraph" class="landing-card">
<div class="card-content">
<div class="card-icon-wrapper">
<div class="card-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="3"></circle>
<circle cx="6" cy="18" r="2"></circle>
<circle cx="18" cy="18" r="2"></circle>
<circle cx="18" cy="6" r="2"></circle>
<circle cx="6" cy="6" r="2"></circle>
<line x1="13.5" y1="10.5" x2="16.5" y2="7.5"></line>
<line x1="10.5" y1="10.5" x2="7.5" y2="7.5"></line>
<line x1="10.5" y1="13.5" x2="7.5" y2="16.5"></line>
<line x1="13.5" y1="13.5" x2="16.5" y2="16.5"></line>
</svg>
</div>
</div>
<div class="card-text">
<h2>Network Graphs</h2>
<p class="card-description">Create and visualize network graphs to map relationships and connections</p>
</div>
</div>
<div class="card-footer">
<span class="card-link-text">Open workspace</span>
<div class="card-arrow">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="5" y1="12" x2="19" y2="12"></line>
<polyline points="12 5 19 12 12 19"></polyline>
</svg>
</div>
</div>
</a>
@if (Model.IsAdmin)
{
<a href="/Admin" class="landing-card">
<div class="card-content">
<div class="card-icon-wrapper">
<div class="card-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
</svg>
</div>
</div>
<div class="card-text">
<h2>Admin</h2>
<p class="card-description">Site administration and management tools</p>
</div>
</div>
<div class="card-footer">
<span class="card-link-text">Open workspace</span>
<div class="card-arrow">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="5" y1="12" x2="19" y2="12"></line>
<polyline points="12 5 19 12 12 19"></polyline>
</svg>
</div>
</div>
</a>
<a href="/BlogAdmin" class="landing-card">
<div class="card-content">
<div class="card-icon-wrapper">
<div class="card-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 20h9"></path>
<path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path>
</svg>
</div>
</div>
<div class="card-text">
<h2>Blog</h2>
<p class="card-description">Create and manage blog posts for your website</p>
</div>
</div>
<div class="card-footer">
<span class="card-link-text">Open workspace</span>
<div class="card-arrow">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="5" y1="12" x2="19" y2="12"></line>
<polyline points="12 5 19 12 12 19"></polyline>
</svg>
</div>
</div>
</a>
}
@if (Model.HasMedicalRole)
{
<a href="/MedicalDocs" class="landing-card">
<div class="card-content">
<div class="card-icon-wrapper">
<div class="card-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="12" y1="11" x2="12" y2="17"></line>
<line x1="9" y1="14" x2="15" y2="14"></line>
</svg>
</div>
</div>
<div class="card-text">
<h2>Medical Documents</h2>
<p class="card-description">Organize medical records, receipts, and notes for the family</p>
</div>
</div>
<div class="card-footer">
<span class="card-link-text">Open workspace</span>
<div class="card-arrow">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="5" y1="12" x2="19" y2="12"></line>
<polyline points="12 5 19 12 12 19"></polyline>
</svg>
</div>
</div>
</a>
}
</div>
<div class="landing-footer">
<a href="/Profile" class="footer-link">Profile</a>
<span class="footer-separator">•</span>
<a href="/Logout" class="footer-link">Logout</a>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,26 @@
using Microsoft.AspNetCore.Mvc;
namespace Media.JoshHeaps.Net.Pages
{
public class LandingModel(DbExecutor dbExecutor) : AuthenticatedPageModel
{
public bool IsAdmin { get; set; }
public bool HasMedicalRole { get; set; }
public async Task<IActionResult> OnGetAsync()
{
RequireAuthentication();
LoadUserSession();
IsAdmin = await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.user_roles ur JOIN app.roles r ON ur.role_id = r.id WHERE ur.user_id = @UserId AND r.name = 'admin')",
new { UserId });
HasMedicalRole = await dbExecutor.ExecuteAsync<bool>(
"SELECT EXISTS(SELECT 1 FROM app.user_roles ur JOIN app.roles r ON ur.role_id = r.id WHERE ur.user_id = @UserId AND r.name = 'medical')",
new { UserId });
return Page();
}
}
}
+4 -11
View File
@@ -5,10 +5,8 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public class LoginModel : PageModel
public class LoginModel(AuthService authService) : PageModel
{
private readonly AuthService _authService;
[BindProperty]
public string Email { get; set; } = string.Empty;
@@ -22,18 +20,13 @@ public class LoginModel : PageModel
public string? SuccessMessage { get; set; }
public string? WarningMessage { get; set; }
public LoginModel(AuthService authService)
{
_authService = authService;
}
public void OnGet([FromQuery] string? registered, [FromQuery] string? verified)
{
// Check if user is already logged in
var userId = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userId))
{
Response.Redirect("/");
Response.Redirect("/Landing");
return;
}
@@ -58,7 +51,7 @@ public class LoginModel : PageModel
return Page();
}
var (success, error, userInfo) = await _authService.LoginAsync(Email, Password);
var (success, error, userInfo) = await authService.LoginAsync(Email, Password);
if (!success || userInfo == null)
{
@@ -91,6 +84,6 @@ public class LoginModel : PageModel
Response.Cookies.Append("RememberMe", userInfo.Id.ToString(), cookieOptions);
}
return Redirect("/");
return Redirect("/Landing");
}
}
@@ -0,0 +1,299 @@
@page
@model Media.JoshHeaps.Net.Pages.MedicalDocsModel
@{
ViewData["Title"] = "Medical Documents";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/medical-docs.css" asp-append-version="true" />
}
<div class="dashboard-container">
<div class="welcome-section">
<div class="welcome-left">
<a href="/Landing" class="back-button" title="Back to Home">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="19" y1="12" x2="5" y2="12"></line>
<polyline points="12 19 5 12 12 5"></polyline>
</svg>
</a>
<h1>Medical Documents</h1>
</div>
<div class="quick-actions">
<a href="/Profile" class="btn btn-secondary">Profile</a>
<a href="/Logout" class="btn btn-danger">Logout</a>
</div>
</div>
<div class="medical-layout">
<!-- Sidebar: People -->
<div class="medical-sidebar">
<h3>People</h3>
<div class="sidebar-people-list" id="peopleList"></div>
<div class="sidebar-add-person">
<input type="text" id="newPersonName" placeholder="Add person..." class="form-input" />
<button id="addPersonBtn" class="btn btn-primary btn-sm">Add</button>
</div>
</div>
<!-- Main Content -->
<div class="medical-main">
<!-- Summary Cards -->
<div class="summary-cards" id="summaryCards" style="display: none;">
<div class="summary-card active" data-tab="documents" onclick="medDocsSwitchTab('documents')">
<div class="count" id="summaryDocCount">0</div>
<div class="label">Documents</div>
</div>
<div class="summary-card" data-tab="conditions" onclick="medDocsSwitchTab('conditions')">
<div class="count" id="summaryCondCount">0</div>
<div class="label">Conditions</div>
</div>
<div class="summary-card" data-tab="prescriptions" onclick="medDocsSwitchTab('prescriptions')">
<div class="count" id="summaryRxCount">0</div>
<div class="label">Prescriptions</div>
</div>
<div class="summary-card" data-tab="doctors" onclick="medDocsSwitchTab('doctors')">
<div class="count" id="summaryDrCount">0</div>
<div class="label">Doctors</div>
</div>
<div class="summary-card" data-tab="bills" onclick="medDocsSwitchTab('bills')">
<div class="count" id="summaryBillOop">$0</div>
<div class="label">Total Paid</div>
<div class="sublabel" id="summaryBillCharged">of $0 charged</div>
<div class="sublabel" id="summaryBillDue"></div>
</div>
<div class="summary-card" data-tab="timeline" onclick="medDocsSwitchTab('timeline')">
<div class="count" id="summaryTimelineIcon">&#128197;</div>
<div class="label">Timeline</div>
</div>
</div>
<!-- Main Tabs -->
<div class="main-tabs" id="mainTabs">
<button class="main-tab" data-tab="documents" onclick="medDocsSwitchTab('documents')">Documents</button>
<button class="main-tab" data-tab="conditions" onclick="medDocsSwitchTab('conditions')">Conditions</button>
<button class="main-tab" data-tab="prescriptions" onclick="medDocsSwitchTab('prescriptions')">Prescriptions</button>
<button class="main-tab active" data-tab="doctors" onclick="medDocsSwitchTab('doctors')">Doctors</button>
<button class="main-tab" data-tab="bills" onclick="medDocsSwitchTab('bills')">Bills</button>
<button class="main-tab" data-tab="timeline" onclick="medDocsSwitchTab('timeline')">Timeline</button>
</div>
<!-- Tab Panels -->
<div class="tab-panels">
<!-- Documents Panel -->
<div class="tab-panel" id="panel-documents">
<div class="add-form-toggle">
<button class="btn btn-secondary" onclick="medDocsToggleAddForm('panel-documents')">+ Add Document</button>
<span class="doc-count" id="docCount"></span>
<button class="btn btn-secondary btn-sm" id="processAllBtn" style="display: none;" onclick="medDocsProcessAll()">Process All with AI</button>
<button class="btn btn-secondary btn-sm" id="batchModeBtn" style="display: none;" onclick="medDocsToggleBatchMode()">Select &amp; Reprocess</button>
</div>
<div class="add-form-collapsible">
<div class="upload-sub-tabs">
<button class="tab-btn active" data-tab="file">Upload File</button>
<button class="tab-btn" data-tab="note">Text Note</button>
</div>
<!-- File Upload -->
<div class="tab-content active" id="tab-file">
<div class="upload-area" id="dropZone">
<div class="upload-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="17 8 12 3 7 8"></polyline>
<line x1="12" y1="3" x2="12" y2="15"></line>
</svg>
</div>
<p>Drag & drop files here or <button class="link-btn" id="browseBtn">browse</button></p>
<p class="upload-hint">Any file type, up to 50MB</p>
<input type="file" id="fileInput" multiple style="display: none;" />
</div>
<div class="upload-fields">
<input type="text" id="fileTitle" placeholder="Title (optional)" class="form-input" />
<input type="text" id="fileDescription" placeholder="Description (optional)" class="form-input" />
<input type="date" id="fileDate" class="form-input" />
<select id="fileClassification" class="form-input">
<option value="">Classification (optional)</option>
<option value="receipt">Receipt</option>
<option value="lab_result">Lab Result</option>
<option value="prescription">Prescription</option>
<option value="imaging">Imaging</option>
<option value="dr_note">Doctor Note</option>
<option value="insurance">Insurance</option>
<option value="referral">Referral</option>
<option value="discharge">Discharge Summary</option>
<option value="recording">Recording/Transcript</option>
<option value="other">Other</option>
</select>
</div>
<div class="upload-queue" id="uploadQueue"></div>
</div>
<!-- Text Note -->
<div class="tab-content" id="tab-note">
<div class="note-form">
<input type="text" id="noteTitle" placeholder="Title *" class="form-input" />
<textarea id="noteDescription" placeholder="Note content..." class="form-input note-textarea" rows="6"></textarea>
<div class="note-fields">
<input type="date" id="noteDate" class="form-input" />
<select id="noteClassification" class="form-input">
<option value="">Classification (optional)</option>
<option value="receipt">Receipt</option>
<option value="lab_result">Lab Result</option>
<option value="prescription">Prescription</option>
<option value="dr_note">Doctor Note</option>
<option value="recording">Recording/Transcript</option>
<option value="other">Other</option>
</select>
</div>
<button id="saveNoteBtn" class="btn btn-primary">Save Note</button>
</div>
</div>
</div>
<div class="filter-bar" id="filterBar" style="display: none;">
<input type="text" id="filterSearch" placeholder="Search documents..." class="form-input filter-search" />
<select id="filterClassification" class="form-input">
<option value="">All Classifications</option>
<option value="receipt">Receipt</option>
<option value="lab_result">Lab Result</option>
<option value="prescription">Prescription</option>
<option value="imaging">Imaging</option>
<option value="dr_note">Doctor Note</option>
<option value="insurance">Insurance</option>
<option value="referral">Referral</option>
<option value="discharge">Discharge Summary</option>
<option value="recording">Recording/Transcript</option>
<option value="other">Other</option>
</select>
<select id="filterDocType" class="form-input">
<option value="">All Types</option>
<option value="file">Files</option>
<option value="note">Notes</option>
</select>
<select id="filterDoctor" class="form-input">
<option value="">All Doctors</option>
</select>
<select id="filterTag" class="form-input">
<option value="">All Tags</option>
</select>
<select id="filterCondition" class="form-input">
<option value="">All Conditions</option>
</select>
<input type="date" id="filterFromDate" class="form-input" title="From date" />
<input type="date" id="filterToDate" class="form-input" title="To date" />
<button class="btn btn-secondary btn-sm" onclick="medDocsClearFilters()">Clear</button>
</div>
<div class="batch-toolbar" id="batchToolbar" style="display:none">
<label><input type="checkbox" id="selectAllCheckbox" onchange="medDocsToggleSelectAll(this.checked)"> Select All</label>
<span id="batchCount">0 selected</span>
<button class="btn btn-primary btn-sm" onclick="medDocsProcessBatch()">Reprocess Selected</button>
<button class="btn btn-secondary btn-sm" onclick="medDocsToggleBatchMode()">Cancel</button>
</div>
<div class="documents-list" id="documentsList"></div>
</div>
<!-- Conditions Panel -->
<div class="tab-panel" id="panel-conditions">
<div class="add-form-toggle">
<button class="btn btn-secondary" onclick="medDocsToggleAddForm('panel-conditions')">+ Add Condition</button>
</div>
<div class="add-form-collapsible">
<div class="inline-form-row">
<input type="text" id="newConditionName" placeholder="Condition name *" class="form-input" />
<input type="date" id="newConditionDate" class="form-input" title="Diagnosed date" />
<input type="text" id="newConditionNotes" placeholder="Notes" class="form-input" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddCondition()">Add</button>
</div>
</div>
<div class="conditions-list" id="conditionsList"></div>
</div>
<!-- Prescriptions Panel -->
<div class="tab-panel" id="panel-prescriptions">
<div class="add-form-toggle">
<button class="btn btn-secondary" onclick="medDocsToggleAddForm('panel-prescriptions')">+ Add Prescription</button>
</div>
<div class="add-form-collapsible">
<div class="inline-form-row">
<input type="text" id="newRxMedication" placeholder="Medication name *" class="form-input" />
<input type="text" id="newRxNumber" placeholder="RX#" class="form-input rx-number-input" />
<input type="text" id="newRxDosage" placeholder="Dosage" class="form-input" />
<input type="text" id="newRxFrequency" placeholder="Frequency" class="form-input" />
<select id="newRxDoctor" class="form-input">
<option value="">Doctor (optional)</option>
</select>
<input type="date" id="newRxStartDate" class="form-input" title="Start date" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddPrescription()">Add</button>
</div>
</div>
<div class="prescriptions-list" id="prescriptionsList"></div>
</div>
<!-- Doctors Panel -->
<div class="tab-panel active" id="panel-doctors">
<div class="add-form-toggle">
<button class="btn btn-secondary" onclick="medDocsToggleAddForm('panel-doctors')">+ Add Doctor</button>
</div>
<div class="add-form-collapsible">
<div class="inline-form-row">
<input type="text" id="newDoctorName" placeholder="Name *" class="form-input" />
<input type="text" id="newDoctorSpecialty" placeholder="Specialty" class="form-input" />
<input type="text" id="newDoctorPhone" placeholder="Phone" class="form-input" />
<input type="text" id="newDoctorAddress" placeholder="Address" class="form-input" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddDoctor()">Add</button>
</div>
</div>
<div class="doctors-list" id="doctorsList"></div>
</div>
<!-- Bills Panel -->
<div class="tab-panel" id="panel-bills">
<div class="add-form-toggle">
<button class="btn btn-secondary" onclick="medDocsToggleAddForm('panel-bills')">+ Add Provider</button>
</div>
<div class="add-form-collapsible">
<div class="inline-form-row">
<input type="text" id="newProviderName" placeholder="Provider name *" class="form-input" />
<input type="text" id="newProviderNotes" placeholder="Notes (optional)" class="form-input" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddProvider()">Add</button>
</div>
</div>
<div id="billSummarySection"></div>
<div class="providers-list" id="providersList"></div>
</div>
<!-- Timeline Panel -->
<div class="tab-panel" id="panel-timeline">
<div id="timelineList"></div>
<button class="btn btn-secondary" id="timelineLoadMore" style="display:none" onclick="medDocsLoadMoreTimeline()">Load More</button>
</div>
</div>
</div>
</div>
</div>
<!-- Document Viewer Modal -->
<div class="doc-viewer-overlay" id="docViewerOverlay" style="display:none" onclick="medDocsCloseViewer(event)">
<div class="doc-viewer-modal" onclick="event.stopPropagation()">
<div class="doc-viewer-header">
<span class="doc-viewer-title" id="docViewerTitle"></span>
<button class="doc-viewer-close" onclick="medDocsCloseViewer()" title="Close">&times;</button>
</div>
<div class="doc-viewer-body" id="docViewerBody">
</div>
</div>
</div>
@section Scripts {
<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/people.js" asp-append-version="true"></script>
<script src="~/js/medical-docs/documents.js" asp-append-version="true"></script>
<script src="~/js/medical-docs/doctors.js" asp-append-version="true"></script>
<script src="~/js/medical-docs/conditions.js" asp-append-version="true"></script>
<script src="~/js/medical-docs/prescriptions.js" asp-append-version="true"></script>
<script src="~/js/medical-docs/bills.js" asp-append-version="true"></script>
<script src="~/js/medical-docs/timeline.js" asp-append-version="true"></script>
<script src="~/js/medical-docs/init.js" asp-append-version="true"></script>
}
@@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Mvc;
namespace Media.JoshHeaps.Net.Pages
{
public class MedicalDocsModel(DbExecutor dbExecutor) : AuthenticatedPageModel
{
private readonly DbExecutor _dbExecutor = dbExecutor;
public async Task<IActionResult> OnGetAsync()
{
RequireAuthentication();
LoadUserSession();
var denied = await RequireRole("medical", _dbExecutor);
if (denied != null) return denied;
return Page();
}
}
}
@@ -0,0 +1,275 @@
@page
@model Media.JoshHeaps.Net.Pages.NetworkGraphModel
@{
ViewData["Title"] = "Network Graphs";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/Gallery/page.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/network-graph.css" asp-append-version="true" />
}
<div class="dashboard-container">
<!-- Header Section -->
<div class="welcome-section">
<div class="welcome-left">
<a href="/Landing" class="back-button" title="Back to Home">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="19" y1="12" x2="5" y2="12"></line>
<polyline points="12 19 5 12 12 5"></polyline>
</svg>
</a>
<h1>Network Graphs</h1>
</div>
<div class="quick-actions">
<button type="button" class="btn btn-primary" id="new-graph-btn">New Graph</button>
<a href="/Profile" class="btn btn-secondary">Profile</a>
<a href="/Logout" class="btn btn-danger">Logout</a>
</div>
</div>
<!-- Graph Selection & Management -->
<div class="graph-manager-section">
<div class="graph-selector-card card">
<h2>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 8px;">
<path d="M3 3v18h18"></path>
<path d="M18 17V9"></path>
<path d="M13 17V5"></path>
<path d="M8 17v-3"></path>
</svg>
Your Graphs
</h2>
<div class="graphs-list" id="graphs-list">
@if (Model.Graphs.Count == 0)
{
<div class="empty-state">
<p>No graphs yet. Create your first graph to get started!</p>
</div>
}
else
{
foreach (var graph in Model.Graphs)
{
<div class="graph-item @(graph.Id == Model.SelectedGraphId ? "active" : "")" data-graph-id="@graph.Id">
<div class="graph-info" onclick="selectGraph(@graph.Id)">
<div class="graph-name">@graph.Name</div>
<div class="graph-stats">
<span class="stat">@graph.NodeCount nodes</span>
<span class="stat">@graph.EdgeCount edges</span>
</div>
</div>
<div class="graph-actions">
<button type="button" class="btn-icon" onclick="event.stopPropagation(); editGraph(@graph.Id, '@graph.Name', '@(graph.Description ?? "")')" title="Edit">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
</svg>
</button>
<button type="button" class="btn-icon" onclick="event.stopPropagation(); cloneGraph(@graph.Id, '@graph.Name')" title="Clone">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
</svg>
</button>
<button type="button" class="btn-icon danger" onclick="event.stopPropagation(); deleteGraph(@graph.Id, '@graph.Name')" title="Delete">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
</svg>
</button>
</div>
</div>
}
}
</div>
</div>
</div>
<!-- Graph Visualization & Tools -->
<div class="graph-workspace" id="graph-workspace" style="display: none;">
<!-- Toolbar -->
<div class="graph-toolbar card">
<div class="toolbar-section">
<button type="button" class="btn btn-secondary" id="add-node-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="8" x2="12" y2="16"></line>
<line x1="8" y1="12" x2="16" y2="12"></line>
</svg>
Add Node
</button>
<button type="button" class="btn btn-secondary" id="link-nodes-btn" disabled>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
</svg>
Link Selected
</button>
</div>
<div class="toolbar-section">
<input type="text" id="search-nodes" class="search-input" placeholder="Search nodes..." />
<input type="number" id="degrees-input" class="search-input" placeholder="Degrees" min="1" max="10" value="1" style="width: 100px; display: none;" />
<select id="filter-mode-select" class="filter-select" style="display: none;">
<option value="exact">Exactly</option>
<option value="within">Within</option>
<option value="outside">Outside</option>
</select>
<button type="button" class="btn btn-secondary" id="apply-filter-btn" style="display: none;">Apply Filter</button>
<button type="button" class="btn btn-secondary" id="clear-filter-btn" style="display: none;">Clear</button>
</div>
</div>
<!-- Canvas -->
<div class="graph-canvas-container card">
<canvas id="graph-canvas"></canvas>
<div class="canvas-help-text">
<span>💡 Right-click nodes for options • Ctrl+Click to select multiple • Double-click to edit</span>
</div>
<div class="canvas-controls">
<button type="button" class="canvas-btn" id="zoom-in-btn" title="Zoom In">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
<line x1="11" y1="8" x2="11" y2="14"></line>
<line x1="8" y1="11" x2="14" y2="11"></line>
</svg>
</button>
<button type="button" class="canvas-btn" id="zoom-out-btn" title="Zoom Out">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
<line x1="8" y1="11" x2="14" y2="11"></line>
</svg>
</button>
<button type="button" class="canvas-btn" id="reset-view-btn" title="Reset View">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"></path>
<path d="M21 3v5h-5"></path>
<path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"></path>
<path d="M3 21v-5h5"></path>
</svg>
</button>
</div>
</div>
</div>
</div>
<!-- New Graph Modal -->
<div id="graph-modal" class="modal" style="display: none;">
<div class="modal-backdrop" onclick="closeGraphModal()"></div>
<div class="modal-dialog">
<div class="modal-header">
<h3 id="graph-modal-title">New Graph</h3>
<button type="button" class="modal-close" onclick="closeGraphModal()">&times;</button>
</div>
<div class="modal-body">
<form id="graph-form">
<div class="form-group">
<label for="graph-name">Graph Name *</label>
<input type="text" id="graph-name" class="form-control" required />
</div>
<div class="form-group">
<label for="graph-description">Description</label>
<textarea id="graph-description" class="form-control" rows="3"></textarea>
</div>
<div class="modal-actions">
<button type="button" class="btn btn-secondary" onclick="closeGraphModal()">Cancel</button>
<button type="submit" class="btn btn-primary" id="save-graph-btn">Create Graph</button>
</div>
</form>
</div>
</div>
</div>
<!-- Node Modal -->
<div id="node-modal" class="modal" style="display: none;">
<div class="modal-backdrop" onclick="closeNodeModal()"></div>
<div class="modal-dialog modal-dialog-large">
<div class="modal-header">
<h3 id="node-modal-title">New Node</h3>
<button type="button" class="modal-close" onclick="closeNodeModal()">&times;</button>
</div>
<div class="modal-body">
<form id="node-form">
<div class="form-group">
<label for="node-label">Label *</label>
<input type="text" id="node-label" class="form-control" required />
</div>
<div class="form-group">
<label for="node-notes">Notes</label>
<textarea id="node-notes" class="form-control" rows="5" placeholder="Add detailed notes about this node..."></textarea>
</div>
<!-- Connections Section (only shown when editing) -->
<div id="node-connections-section" style="display: none;">
<div class="form-group">
<label>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align: middle; margin-right: 4px;">
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
</svg>
Connections
</label>
<!-- Add Connection -->
<div class="connection-search-container">
<input type="text" id="connection-search" class="form-control" placeholder="Search nodes to connect..." autocomplete="off" />
<div id="connection-search-results" class="search-results-dropdown" style="display: none;"></div>
</div>
<!-- Current Connections List -->
<div id="node-connections-list" class="connections-list"></div>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn btn-secondary" onclick="closeNodeModal()">Cancel</button>
<button type="submit" class="btn btn-primary" id="save-node-btn">Create Node</button>
</div>
</form>
</div>
</div>
</div>
<!-- Context Menu -->
<div id="node-context-menu" class="context-menu" style="display: none;">
<div class="context-menu-item" data-action="edit">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
</svg>
Edit Node
</div>
<div class="context-menu-item" data-action="link">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
</svg>
Link to Selected
</div>
<div class="context-menu-item" data-action="select">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="9 11 12 14 22 4"></polyline>
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path>
</svg>
Add to Selection
</div>
<div class="context-menu-divider"></div>
<div class="context-menu-item danger" data-action="delete">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
</svg>
Delete Node
</div>
</div>
@section Scripts {
<script>
const selectedGraphId = @(Model.SelectedGraphId?.ToString() ?? "null");
</script>
<script src="~/js/network-graph.js" asp-append-version="true"></script>
}
@@ -0,0 +1,25 @@
using Media.JoshHeaps.Net.Models;
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
namespace Media.JoshHeaps.Net.Pages
{
public class NetworkGraphModel(GraphService graphService) : AuthenticatedPageModel
{
private readonly GraphService _graphService = graphService;
public List<GraphWithCounts> Graphs { get; set; } = [];
public long? SelectedGraphId { get; set; }
public async Task<IActionResult> OnGetAsync([FromQuery] long? graphId = null)
{
RequireAuthentication();
LoadUserSession();
Graphs = await _graphService.GetUserGraphsAsync(UserId);
SelectedGraphId = graphId;
return Page();
}
}
}
+3 -12
View File
@@ -5,11 +5,8 @@ using System.Text.RegularExpressions;
namespace Media.JoshHeaps.Net.Pages;
public class RegisterModel : PageModel
public class RegisterModel(AuthService authService, EmailService emailService) : PageModel
{
private readonly AuthService _authService;
private readonly EmailService _emailService;
[BindProperty]
public string Email { get; set; } = string.Empty;
@@ -24,12 +21,6 @@ public class RegisterModel : PageModel
public string? ErrorMessage { get; set; }
public RegisterModel(AuthService authService, EmailService emailService)
{
_authService = authService;
_emailService = emailService;
}
public void OnGet()
{
// Check if user is already logged in
@@ -79,7 +70,7 @@ public class RegisterModel : PageModel
}
// Register user
var (success, error, verificationToken) = await _authService.RegisterUserAsync(Email, Username, Password);
var (success, error, verificationToken) = await authService.RegisterUserAsync(Email, Username, Password);
if (!success)
{
@@ -90,7 +81,7 @@ public class RegisterModel : PageModel
// Send verification email
if (!string.IsNullOrEmpty(verificationToken))
{
await _emailService.SendVerificationEmailAsync(Email, Username, verificationToken);
await emailService.SendVerificationEmailAsync(Email, Username, verificationToken);
}
// Redirect to verification pending page
@@ -4,23 +4,14 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public class ResendVerificationModel : PageModel
public class ResendVerificationModel(AuthService authService, EmailService emailService) : PageModel
{
private readonly AuthService _authService;
private readonly EmailService _emailService;
[BindProperty]
public string Email { get; set; } = string.Empty;
public string? ErrorMessage { get; set; }
public string? SuccessMessage { get; set; }
public ResendVerificationModel(AuthService authService, EmailService emailService)
{
_authService = authService;
_emailService = emailService;
}
public void OnGet([FromQuery] string? email)
{
if (!string.IsNullOrEmpty(email))
@@ -37,7 +28,7 @@ public class ResendVerificationModel : PageModel
return Page();
}
var (success, error, verificationToken) = await _authService.ResendVerificationTokenAsync(Email);
var (success, error, verificationToken) = await authService.ResendVerificationTokenAsync(Email);
if (!success)
{
@@ -48,7 +39,7 @@ public class ResendVerificationModel : PageModel
// Send verification email
if (!string.IsNullOrEmpty(verificationToken))
{
var emailSent = await _emailService.SendVerificationEmailAsync(Email, Email, verificationToken);
var emailSent = await emailService.SendVerificationEmailAsync(Email, Email, verificationToken);
if (emailSent)
{
@@ -4,19 +4,12 @@ using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public class VerifyEmailModel : PageModel
public class VerifyEmailModel(AuthService authService) : PageModel
{
private readonly AuthService _authService;
public bool Success { get; set; }
public string Message { get; set; } = string.Empty;
public bool ShowResendLink { get; set; }
public VerifyEmailModel(AuthService authService)
{
_authService = authService;
}
public async Task<IActionResult> OnGetAsync([FromQuery] string? token)
{
if (string.IsNullOrEmpty(token))
@@ -27,7 +20,7 @@ public class VerifyEmailModel : PageModel
return Page();
}
var (success, error) = await _authService.VerifyEmailAsync(token);
var (success, error) = await authService.VerifyEmailAsync(token);
Success = success;
+12
View File
@@ -16,6 +16,11 @@ builder.Services.AddScoped<EmailService>();
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<MediaService>();
builder.Services.AddScoped<FolderService>();
builder.Services.AddScoped<GraphService>();
builder.Services.AddScoped<MedicalDocsService>();
builder.Services.AddSingleton<MedicalAiService>();
builder.Services.AddScoped<BlogService>();
builder.Services.AddHttpClient();
// Add session support
builder.Services.AddDistributedMemoryCache();
@@ -71,4 +76,11 @@ app.UseAuthorization();
app.MapRazorPages();
app.MapControllers(); // Map API controllers
// Redirect root to Landing page
app.MapGet("/", context =>
{
context.Response.Redirect("/Landing");
return Task.CompletedTask;
});
app.Run();
+258
View File
@@ -0,0 +1,258 @@
using System.Text.RegularExpressions;
using Markdig;
using Media.JoshHeaps.Net.Models;
namespace Media.JoshHeaps.Net.Services;
public partial class BlogService(DbExecutor db, IWebHostEnvironment environment, ILogger<BlogService> logger)
{
private static readonly HashSet<string> AllowedMimeTypes = ["image/jpeg", "image/png", "image/gif", "image/webp"];
private const long MaxImageSize = 10 * 1024 * 1024;
private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder()
.UseAdvancedExtensions()
.Build();
public async Task<List<BlogPost>> GetAllPostsAsync()
{
try
{
return await db.ExecuteListReaderAsync(
@"SELECT id, slug, title, summary, markdown_content, html_content, tags, author_id, published_date, created_at, updated_at
FROM app.blog_posts
ORDER BY published_date DESC",
MapBlogPost);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get all blog posts");
return [];
}
}
public async Task<BlogPost?> GetPostByIdAsync(long id)
{
try
{
return await db.ExecuteReaderAsync(
@"SELECT id, slug, title, summary, markdown_content, html_content, tags, author_id, published_date, created_at, updated_at
FROM app.blog_posts
WHERE id = @Id",
MapBlogPost,
new { Id = id });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get blog post by id {Id}", id);
return null;
}
}
public async Task<BlogPost?> GetPostBySlugAsync(string slug)
{
try
{
return await db.ExecuteReaderAsync(
@"SELECT id, slug, title, summary, markdown_content, html_content, tags, author_id, published_date, created_at, updated_at
FROM app.blog_posts
WHERE slug = @Slug",
MapBlogPost,
new { Slug = slug });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get blog post by slug {Slug}", slug);
return null;
}
}
public async Task<List<BlogPost>> GetPostsByTagAsync(string tag)
{
try
{
return await db.ExecuteListReaderAsync(
@"SELECT id, slug, title, summary, markdown_content, html_content, tags, author_id, published_date, created_at, updated_at
FROM app.blog_posts
WHERE @Tag = ANY(tags)
ORDER BY published_date DESC",
MapBlogPost,
new { Tag = tag });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get blog posts by tag {Tag}", tag);
return [];
}
}
public async Task<BlogPost?> CreatePostAsync(string title, string summary, string markdownContent, List<string> tags, long authorId, DateTime publishedDate)
{
try
{
var slug = GenerateSlug(title);
var htmlContent = Markdown.ToHtml(markdownContent, Pipeline);
var now = DateTime.UtcNow;
return await db.ExecuteReaderAsync(
@"INSERT INTO app.blog_posts (slug, title, summary, markdown_content, html_content, tags, author_id, published_date, created_at, updated_at)
VALUES (@Slug, @Title, @Summary, @MarkdownContent, @HtmlContent, @Tags, @AuthorId, @PublishedDate, @CreatedAt, @UpdatedAt)
RETURNING id, slug, title, summary, markdown_content, html_content, tags, author_id, published_date, created_at, updated_at",
MapBlogPost,
new
{
Slug = slug,
Title = title,
Summary = summary,
MarkdownContent = markdownContent,
HtmlContent = htmlContent,
Tags = tags.ToArray(),
AuthorId = authorId,
PublishedDate = publishedDate,
CreatedAt = now,
UpdatedAt = now
});
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create blog post '{Title}'", title);
return null;
}
}
public async Task<BlogPost?> UpdatePostAsync(long id, string title, string summary, string markdownContent, List<string> tags, DateTime publishedDate)
{
try
{
var slug = GenerateSlug(title);
var htmlContent = Markdown.ToHtml(markdownContent, Pipeline);
return await db.ExecuteReaderAsync(
@"UPDATE app.blog_posts
SET slug = @Slug, title = @Title, summary = @Summary, markdown_content = @MarkdownContent,
html_content = @HtmlContent, tags = @Tags, published_date = @PublishedDate, updated_at = @UpdatedAt
WHERE id = @Id
RETURNING id, slug, title, summary, markdown_content, html_content, tags, author_id, published_date, created_at, updated_at",
MapBlogPost,
new
{
Id = id,
Slug = slug,
Title = title,
Summary = summary,
MarkdownContent = markdownContent,
HtmlContent = htmlContent,
Tags = tags.ToArray(),
PublishedDate = publishedDate,
UpdatedAt = DateTime.UtcNow
});
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to update blog post {Id}", id);
return null;
}
}
public async Task<bool> DeletePostAsync(long id)
{
try
{
var rows = await db.ExecuteNonQueryAsync(
"DELETE FROM app.blog_posts WHERE id = @Id",
new { Id = id });
return rows > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to delete blog post {Id}", id);
return false;
}
}
public async Task<(string? url, string? error)> SaveImageAsync(IFormFile file)
{
if (!AllowedMimeTypes.Contains(file.ContentType))
return (null, "Only JPEG, PNG, GIF, and WEBP images are allowed");
if (file.Length > MaxImageSize)
return (null, "Image must be under 10MB");
var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
if (string.IsNullOrEmpty(ext)) ext = ".jpg";
var fileName = $"{Guid.NewGuid()}{ext}";
var folder = Path.Combine(environment.ContentRootPath, "App_Data", "blog");
Directory.CreateDirectory(folder);
var filePath = Path.Combine(folder, fileName);
try
{
await using var stream = new FileStream(filePath, FileMode.Create);
await file.CopyToAsync(stream);
return ($"/api/blog/images/{fileName}", null);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to save blog image");
if (File.Exists(filePath)) File.Delete(filePath);
return (null, "Failed to save image");
}
}
public (string? filePath, string? mimeType) GetImagePath(string fileName)
{
if (fileName.Contains("..") || fileName.Contains('/') || fileName.Contains('\\'))
return (null, null);
var filePath = Path.Combine(environment.ContentRootPath, "App_Data", "blog", fileName);
if (!File.Exists(filePath))
return (null, null);
var ext = Path.GetExtension(fileName).ToLowerInvariant();
var mimeType = ext switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
".webp" => "image/webp",
_ => "application/octet-stream"
};
return (filePath, mimeType);
}
private static BlogPost MapBlogPost(Npgsql.NpgsqlDataReader reader)
{
return new BlogPost
{
Id = reader.GetInt64(0),
Slug = reader.GetString(1),
Title = reader.GetString(2),
Summary = reader.GetString(3),
MarkdownContent = reader.GetString(4),
HtmlContent = reader.GetString(5),
Tags = reader.GetFieldValue<string[]>(6).ToList(),
AuthorId = reader.GetInt64(7),
PublishedDate = reader.GetDateTime(8),
CreatedAt = reader.GetDateTime(9),
UpdatedAt = reader.GetDateTime(10)
};
}
private static string GenerateSlug(string title)
{
var slug = title.ToLowerInvariant();
slug = SlugInvalidChars().Replace(slug, "");
slug = SlugWhitespace().Replace(slug, "-");
slug = SlugMultipleDashes().Replace(slug, "-");
return slug.Trim('-');
}
[GeneratedRegex(@"[^a-z0-9\s-]")]
private static partial Regex SlugInvalidChars();
[GeneratedRegex(@"\s+")]
private static partial Regex SlugWhitespace();
[GeneratedRegex(@"-{2,}")]
private static partial Regex SlugMultipleDashes();
}
+21 -30
View File
@@ -4,28 +4,19 @@ using MimeKit;
namespace Media.JoshHeaps.Net.Services;
public class EmailService
public class EmailService(IConfiguration config, ILogger<EmailService> logger)
{
private readonly IConfiguration _config;
private readonly ILogger<EmailService> _logger;
public EmailService(IConfiguration config, ILogger<EmailService> logger)
{
_config = config;
_logger = logger;
}
public async Task<bool> SendVerificationEmailAsync(string toEmail, string username, string verificationToken)
{
try
{
var appUrl = _config["AppUrl"] ?? "https://media.joshheaps.net";
var appUrl = config["AppUrl"] ?? "https://media.joshheaps.net";
var verificationUrl = $"{appUrl}/VerifyEmail?token={verificationToken}";
var message = new MimeMessage();
message.From.Add(new MailboxAddress(
_config["Email:FromName"] ?? "Media App",
_config["Email:FromEmail"] ?? "[email protected]"
config["Email:FromName"] ?? "Media App",
config["Email:FromEmail"] ?? "[email protected]"
));
message.To.Add(new MailboxAddress(username, toEmail));
message.Subject = "Verify Your Email Address";
@@ -85,11 +76,11 @@ If you didn't create an account, you can safely ignore this email.
using var client = new SmtpClient();
var smtpHost = _config["Email:SmtpHost"];
var smtpPort = int.Parse(_config["Email:SmtpPort"] ?? "587");
var smtpUsername = _config["Email:SmtpUsername"];
var smtpPassword = _config["Email:SmtpPassword"];
var enableSsl = bool.Parse(_config["Email:EnableSsl"] ?? "true");
var smtpHost = config["Email:SmtpHost"];
var smtpPort = int.Parse(config["Email:SmtpPort"] ?? "587");
var smtpUsername = config["Email:SmtpUsername"];
var smtpPassword = config["Email:SmtpPassword"];
var enableSsl = bool.Parse(config["Email:EnableSsl"] ?? "true");
await client.ConnectAsync(smtpHost, smtpPort, enableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None);
@@ -101,12 +92,12 @@ If you didn't create an account, you can safely ignore this email.
await client.SendAsync(message);
await client.DisconnectAsync(true);
_logger.LogInformation($"Verification email sent to {toEmail}");
logger.LogInformation($"Verification email sent to {toEmail}");
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Failed to send verification email to {toEmail}");
logger.LogError(ex, $"Failed to send verification email to {toEmail}");
return false;
}
}
@@ -115,13 +106,13 @@ If you didn't create an account, you can safely ignore this email.
{
try
{
var appUrl = _config["AppUrl"] ?? "http://localhost:5000";
var appUrl = config["AppUrl"] ?? "http://localhost:5000";
var resetUrl = $"{appUrl}/ResetPassword?token={resetToken}";
var message = new MimeMessage();
message.From.Add(new MailboxAddress(
_config["Email:FromName"] ?? "Media App",
_config["Email:FromEmail"] ?? "[email protected]"
config["Email:FromName"] ?? "Media App",
config["Email:FromEmail"] ?? "[email protected]"
));
message.To.Add(new MailboxAddress(username, toEmail));
message.Subject = "Password Reset Request";
@@ -184,11 +175,11 @@ If you didn't request a password reset, you can safely ignore this email.
using var client = new SmtpClient();
var smtpHost = _config["Email:SmtpHost"];
var smtpPort = int.Parse(_config["Email:SmtpPort"] ?? "587");
var smtpUsername = _config["Email:SmtpUsername"];
var smtpPassword = _config["Email:SmtpPassword"];
var enableSsl = bool.Parse(_config["Email:EnableSsl"] ?? "true");
var smtpHost = config["Email:SmtpHost"];
var smtpPort = int.Parse(config["Email:SmtpPort"] ?? "587");
var smtpUsername = config["Email:SmtpUsername"];
var smtpPassword = config["Email:SmtpPassword"];
var enableSsl = bool.Parse(config["Email:EnableSsl"] ?? "true");
await client.ConnectAsync(smtpHost, smtpPort, enableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None);
@@ -200,12 +191,12 @@ If you didn't request a password reset, you can safely ignore this email.
await client.SendAsync(message);
await client.DisconnectAsync(true);
_logger.LogInformation($"Password reset email sent to {toEmail}");
logger.LogInformation($"Password reset email sent to {toEmail}");
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Failed to send password reset email to {toEmail}");
logger.LogError(ex, $"Failed to send password reset email to {toEmail}");
return false;
}
}
+45 -54
View File
@@ -2,17 +2,8 @@ using Media.JoshHeaps.Net.Models;
namespace Media.JoshHeaps.Net.Services;
public class FolderService
public class FolderService(DbExecutor db, ILogger<FolderService> logger)
{
private readonly DbExecutor _db;
private readonly ILogger<FolderService> _logger;
public FolderService(DbExecutor db, ILogger<FolderService> logger)
{
_db = db;
_logger = logger;
}
public async Task<Folder?> CreateFolderAsync(long userId, string name, long? parentFolderId = null)
{
try
@@ -20,7 +11,7 @@ public class FolderService
// Validate folder name
if (string.IsNullOrWhiteSpace(name))
{
_logger.LogWarning("Cannot create folder with empty name for user {UserId}", userId);
logger.LogWarning("Cannot create folder with empty name for user {UserId}", userId);
return null;
}
@@ -28,7 +19,7 @@ public class FolderService
var sanitizedName = SanitizeFolderName(name);
if (string.IsNullOrWhiteSpace(sanitizedName))
{
_logger.LogWarning("Folder name became empty after sanitization for user {UserId}", userId);
logger.LogWarning("Folder name became empty after sanitization for user {UserId}", userId);
return null;
}
@@ -38,7 +29,7 @@ public class FolderService
var parentExists = await FolderExistsAsync(parentFolderId.Value, userId);
if (!parentExists)
{
_logger.LogWarning("Parent folder {ParentFolderId} not found for user {UserId}", parentFolderId.Value, userId);
logger.LogWarning("Parent folder {ParentFolderId} not found for user {UserId}", parentFolderId.Value, userId);
return null;
}
}
@@ -48,7 +39,7 @@ public class FolderService
VALUES (@userId, @name, @parentFolderId, @createdAt, @updatedAt)
RETURNING id, user_id, name, parent_folder_id, created_at, updated_at";
var folder = await _db.ExecuteReaderAsync(query, reader =>
var folder = await db.ExecuteReaderAsync(query, reader =>
{
return new Folder
{
@@ -72,7 +63,7 @@ public class FolderService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create folder '{Name}' for user {UserId}", name, userId);
logger.LogError(ex, "Failed to create folder '{Name}' for user {UserId}", name, userId);
return null;
}
}
@@ -99,7 +90,7 @@ public class FolderService
ORDER BY name ASC";
}
var folders = await _db.ExecuteListReaderAsync(query, reader =>
var folders = await db.ExecuteListReaderAsync(query, reader =>
{
return new Folder
{
@@ -116,8 +107,8 @@ public class FolderService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get folders for user {UserId}, parent {ParentFolderId}", userId, parentFolderId);
return new List<Folder>();
logger.LogError(ex, "Failed to get folders for user {UserId}, parent {ParentFolderId}", userId, parentFolderId);
return [];
}
}
@@ -130,7 +121,7 @@ public class FolderService
FROM app.folders
WHERE id = @folderId AND user_id = @userId";
var folder = await _db.ExecuteReaderAsync(query, reader =>
var folder = await db.ExecuteReaderAsync(query, reader =>
{
return new Folder
{
@@ -147,7 +138,7 @@ public class FolderService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get folder {FolderId} for user {UserId}", folderId, userId);
logger.LogError(ex, "Failed to get folder {FolderId} for user {UserId}", folderId, userId);
return null;
}
}
@@ -159,7 +150,7 @@ public class FolderService
var sanitizedName = SanitizeFolderName(newName);
if (string.IsNullOrWhiteSpace(sanitizedName))
{
_logger.LogWarning("Cannot rename folder to empty name");
logger.LogWarning("Cannot rename folder to empty name");
return false;
}
@@ -168,7 +159,7 @@ public class FolderService
SET name = @newName, updated_at = @updatedAt
WHERE id = @folderId AND user_id = @userId";
await _db.ExecuteAsync<object>(query, new
await db.ExecuteAsync<object>(query, new
{
folderId,
userId,
@@ -180,7 +171,7 @@ public class FolderService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to rename folder {FolderId} for user {UserId}", folderId, userId);
logger.LogError(ex, "Failed to rename folder {FolderId} for user {UserId}", folderId, userId);
return false;
}
}
@@ -193,12 +184,12 @@ public class FolderService
var hasSubfoldersQuery = "SELECT COUNT(*) FROM app.folders WHERE parent_folder_id = @folderId";
var hasMediaQuery = "SELECT COUNT(*) FROM app.user_media WHERE folder_id = @folderId";
var subfolderCount = await _db.ExecuteReaderAsync(hasSubfoldersQuery, reader => reader.GetInt64(0), new { folderId });
var mediaCount = await _db.ExecuteReaderAsync(hasMediaQuery, reader => reader.GetInt64(0), new { folderId });
var subfolderCount = await db.ExecuteReaderAsync(hasSubfoldersQuery, reader => reader.GetInt64(0), new { folderId });
var mediaCount = await db.ExecuteReaderAsync(hasMediaQuery, reader => reader.GetInt64(0), new { folderId });
if (!deleteContents && (subfolderCount > 0 || mediaCount > 0))
{
_logger.LogWarning("Cannot delete folder {FolderId} - it contains items", folderId);
logger.LogWarning("Cannot delete folder {FolderId} - it contains items", folderId);
return false;
}
@@ -214,7 +205,7 @@ public class FolderService
SET parent_folder_id = @parentFolderId, updated_at = @updatedAt
WHERE parent_folder_id = @folderId AND user_id = @userId";
await _db.ExecuteAsync<object>(moveSubfoldersQuery, new
await db.ExecuteAsync<object>(moveSubfoldersQuery, new
{
parentFolderId = folder.ParentFolderId,
folderId,
@@ -228,7 +219,7 @@ public class FolderService
SET folder_id = @parentFolderId, updated_at = @updatedAt
WHERE folder_id = @folderId AND user_id = @userId";
await _db.ExecuteAsync<object>(moveMediaQuery, new
await db.ExecuteAsync<object>(moveMediaQuery, new
{
parentFolderId = folder.ParentFolderId,
folderId,
@@ -240,13 +231,13 @@ public class FolderService
// Delete the folder
var deleteQuery = "DELETE FROM app.folders WHERE id = @folderId AND user_id = @userId";
await _db.ExecuteAsync<object>(deleteQuery, new { folderId, userId });
await db.ExecuteAsync<object>(deleteQuery, new { folderId, userId });
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete folder {FolderId} for user {UserId}", folderId, userId);
logger.LogError(ex, "Failed to delete folder {FolderId} for user {UserId}", folderId, userId);
return false;
}
}
@@ -275,7 +266,7 @@ public class FolderService
var isDescendant = await IsFolderDescendantAsync(newParentFolderId.Value, folderId);
if (isDescendant)
{
_logger.LogWarning("Cannot move folder {FolderId} into its descendant {ParentFolderId}", folderId, newParentFolderId.Value);
logger.LogWarning("Cannot move folder {FolderId} into its descendant {ParentFolderId}", folderId, newParentFolderId.Value);
return false;
}
}
@@ -285,7 +276,7 @@ public class FolderService
SET parent_folder_id = @newParentFolderId, updated_at = @updatedAt
WHERE id = @folderId AND user_id = @userId";
await _db.ExecuteAsync<object>(query, new
await db.ExecuteAsync<object>(query, new
{
folderId,
userId,
@@ -297,7 +288,7 @@ public class FolderService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to move folder {FolderId} for user {UserId}", folderId, userId);
logger.LogError(ex, "Failed to move folder {FolderId} for user {UserId}", folderId, userId);
return false;
}
}
@@ -330,8 +321,8 @@ public class FolderService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get folder path for folder {FolderId}", folderId);
return new List<Folder>();
logger.LogError(ex, "Failed to get folder path for folder {FolderId}", folderId);
return [];
}
}
@@ -340,7 +331,7 @@ public class FolderService
try
{
var query = "SELECT COUNT(*) FROM app.folders WHERE id = @folderId AND user_id = @userId";
var count = await _db.ExecuteReaderAsync(query, reader => reader.GetInt64(0), new { folderId, userId });
var count = await db.ExecuteReaderAsync(query, reader => reader.GetInt64(0), new { folderId, userId });
return count > 0;
}
catch
@@ -371,7 +362,7 @@ public class FolderService
visited.Add(currentId);
var query = "SELECT parent_folder_id FROM app.folders WHERE id = @folderId";
var parentId = await _db.ExecuteReaderAsync(query, reader => reader.IsDBNull(0) ? (long?)null : reader.GetInt64(0), new { folderId = currentId });
var parentId = await db.ExecuteReaderAsync(query, reader => reader.IsDBNull(0) ? (long?)null : reader.GetInt64(0), new { folderId = currentId });
if (!parentId.HasValue)
{
@@ -385,7 +376,7 @@ public class FolderService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to check if folder {PotentialDescendantId} is descendant of {AncestorId}", potentialDescendantId, ancestorId);
logger.LogError(ex, "Failed to check if folder {PotentialDescendantId} is descendant of {AncestorId}", potentialDescendantId, ancestorId);
return false;
}
}
@@ -421,7 +412,7 @@ public class FolderService
var folder = await GetFolderByIdAsync(folderId, ownerId);
if (folder == null)
{
_logger.LogWarning("Cannot share folder {FolderId} - not found or not owned by {OwnerId}", folderId, ownerId);
logger.LogWarning("Cannot share folder {FolderId} - not found or not owned by {OwnerId}", folderId, ownerId);
return null;
}
@@ -437,7 +428,7 @@ public class FolderService
VALUES (@folderId, @ownerId, @sharedWithUserId, @permissionLevel, @includeSubfolders, @createdAt, @updatedAt)
RETURNING id, folder_id, owner_user_id, shared_with_user_id, permission_level, include_subfolders, created_at, updated_at";
var share = await _db.ExecuteReaderAsync(query, reader =>
var share = await db.ExecuteReaderAsync(query, reader =>
{
return new FolderShare
{
@@ -465,7 +456,7 @@ public class FolderService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to share folder {FolderId} with user {SharedWithUserId}", folderId, sharedWithUserId);
logger.LogError(ex, "Failed to share folder {FolderId} with user {SharedWithUserId}", folderId, sharedWithUserId);
return null;
}
}
@@ -478,12 +469,12 @@ public class FolderService
DELETE FROM app.folder_shares
WHERE folder_id = @folderId AND owner_user_id = @ownerId AND shared_with_user_id = @sharedWithUserId";
await _db.ExecuteAsync<object>(query, new { folderId, ownerId, sharedWithUserId });
await db.ExecuteAsync<object>(query, new { folderId, ownerId, sharedWithUserId });
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to unshare folder {FolderId} from user {SharedWithUserId}", folderId, sharedWithUserId);
logger.LogError(ex, "Failed to unshare folder {FolderId} from user {SharedWithUserId}", folderId, sharedWithUserId);
return false;
}
}
@@ -500,7 +491,7 @@ public class FolderService
WHERE fs.folder_id = @folderId AND fs.owner_user_id = @ownerId
ORDER BY u.username ASC";
var shares = await _db.ExecuteListReaderAsync(query, reader =>
var shares = await db.ExecuteListReaderAsync(query, reader =>
{
return new FolderShareWithUser
{
@@ -519,8 +510,8 @@ public class FolderService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get shares for folder {FolderId}", folderId);
return new List<FolderShareWithUser>();
logger.LogError(ex, "Failed to get shares for folder {FolderId}", folderId);
return [];
}
}
@@ -536,7 +527,7 @@ public class FolderService
WHERE fs.shared_with_user_id = @userId
ORDER BY f.name ASC";
var sharedFolders = await _db.ExecuteListReaderAsync(query, reader =>
var sharedFolders = await db.ExecuteListReaderAsync(query, reader =>
{
return new SharedFolderInfo
{
@@ -553,8 +544,8 @@ public class FolderService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get shared folders for user {UserId}", userId);
return new List<SharedFolderInfo>();
logger.LogError(ex, "Failed to get shared folders for user {UserId}", userId);
return [];
}
}
@@ -567,7 +558,7 @@ public class FolderService
FROM app.folder_shares
WHERE folder_id = @folderId AND shared_with_user_id = @sharedWithUserId";
var share = await _db.ExecuteReaderAsync(query, reader =>
var share = await db.ExecuteReaderAsync(query, reader =>
{
return new FolderShare
{
@@ -596,7 +587,7 @@ public class FolderService
{
// Check if user is the owner
var query = "SELECT COUNT(*) FROM app.folders WHERE id = @folderId AND user_id = @userId";
var isOwner = await _db.ExecuteReaderAsync(query, reader => reader.GetInt64(0), new { folderId, userId });
var isOwner = await db.ExecuteReaderAsync(query, reader => reader.GetInt64(0), new { folderId, userId });
if (isOwner > 0) return true;
// Check if folder is shared with user (including parent folders due to subfolders)
@@ -619,12 +610,12 @@ public class FolderService
INNER JOIN folder_hierarchy fh ON fs.folder_id = fh.id
WHERE fs.shared_with_user_id = @userId AND fs.include_subfolders = true";
var hasShare = await _db.ExecuteReaderAsync(shareQuery, reader => reader.GetInt64(0), new { folderId, userId });
var hasShare = await db.ExecuteReaderAsync(shareQuery, reader => reader.GetInt64(0), new { folderId, userId });
return hasShare > 0;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to check folder access for folder {FolderId} and user {UserId}", folderId, userId);
logger.LogError(ex, "Failed to check folder access for folder {FolderId} and user {UserId}", folderId, userId);
return false;
}
}
@@ -634,7 +625,7 @@ public class FolderService
try
{
var query = "SELECT user_id FROM app.folders WHERE id = @folderId";
var ownerId = await _db.ExecuteReaderAsync(query, reader => reader.GetInt64(0), new { folderId });
var ownerId = await db.ExecuteReaderAsync(query, reader => reader.GetInt64(0), new { folderId });
return ownerId;
}
catch
@@ -0,0 +1,810 @@
using Media.JoshHeaps.Net.Models;
namespace Media.JoshHeaps.Net.Services;
public class GraphService(DbExecutor db, ILogger<GraphService> logger)
{
#region Graph Operations
public async Task<List<GraphWithCounts>> GetUserGraphsAsync(long userId)
{
try
{
var query = @"
SELECT
g.id, g.user_id, g.name, g.description, g.created_at, g.updated_at,
COUNT(DISTINCT n.id) as node_count,
COUNT(DISTINCT e.id) as edge_count
FROM app.graphs g
LEFT JOIN app.graph_nodes n ON g.id = n.graph_id
LEFT JOIN app.graph_edges e ON g.id = e.graph_id
WHERE g.user_id = @userId
GROUP BY g.id, g.user_id, g.name, g.description, g.created_at, g.updated_at
ORDER BY g.updated_at DESC";
return await db.ExecuteListReaderAsync(query, reader =>
{
return new GraphWithCounts
{
Id = reader.GetInt64(0),
UserId = reader.GetInt64(1),
Name = reader.GetString(2),
Description = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5),
NodeCount = reader.GetInt32(6),
EdgeCount = reader.GetInt32(7)
};
}, new { userId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get graphs for user {UserId}", userId);
return [];
}
}
public async Task<Graph?> GetGraphByIdAsync(long graphId, long userId)
{
try
{
var query = @"
SELECT id, user_id, name, description, created_at, updated_at
FROM app.graphs
WHERE id = @graphId AND user_id = @userId";
return await db.ExecuteReaderAsync(query, reader =>
{
return new Graph
{
Id = reader.GetInt64(0),
UserId = reader.GetInt64(1),
Name = reader.GetString(2),
Description = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5)
};
}, new { graphId, userId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get graph {GraphId} for user {UserId}", graphId, userId);
return null;
}
}
public async Task<Graph?> CreateGraphAsync(long userId, string name, string? description = null)
{
try
{
if (string.IsNullOrWhiteSpace(name))
{
logger.LogWarning("Cannot create graph with empty name for user {UserId}", userId);
return null;
}
var query = @"
INSERT INTO app.graphs (user_id, name, description, created_at, updated_at)
VALUES (@userId, @name, @description, @createdAt, @updatedAt)
RETURNING id, user_id, name, description, created_at, updated_at";
return await db.ExecuteReaderAsync(query, reader =>
{
return new Graph
{
Id = reader.GetInt64(0),
UserId = reader.GetInt64(1),
Name = reader.GetString(2),
Description = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5)
};
}, new
{
userId,
name = name.Trim(),
description,
createdAt = DateTime.UtcNow,
updatedAt = DateTime.UtcNow
});
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create graph '{Name}' for user {UserId}", name, userId);
return null;
}
}
public async Task<bool> UpdateGraphAsync(long graphId, long userId, string name, string? description)
{
try
{
if (string.IsNullOrWhiteSpace(name))
{
logger.LogWarning("Cannot update graph with empty name");
return false;
}
var query = @"
UPDATE app.graphs
SET name = @name, description = @description, updated_at = @updatedAt
WHERE id = @graphId AND user_id = @userId";
var rowsAffected = await db.ExecuteNonQueryAsync(query, new
{
graphId,
userId,
name = name.Trim(),
description,
updatedAt = DateTime.UtcNow
});
return rowsAffected > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to update graph {GraphId}", graphId);
return false;
}
}
public async Task<bool> DeleteGraphAsync(long graphId, long userId)
{
try
{
var query = "DELETE FROM app.graphs WHERE id = @graphId AND user_id = @userId";
var rowsAffected = await db.ExecuteNonQueryAsync(query, new { graphId, userId });
return rowsAffected > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to delete graph {GraphId}", graphId);
return false;
}
}
public async Task<Graph?> CloneGraphAsync(long graphId, long userId, string newName)
{
try
{
// Get original graph
var originalGraph = await GetGraphByIdAsync(graphId, userId);
if (originalGraph == null) return null;
// Create new graph
var newGraph = await CreateGraphAsync(userId, newName, originalGraph.Description);
if (newGraph == null) return null;
// Get all nodes from original graph
var nodes = await GetGraphNodesAsync(graphId, userId);
var nodeMapping = new Dictionary<long, long>(); // old ID -> new ID
// Clone nodes
foreach (var node in nodes)
{
var newNode = await CreateNodeAsync(newGraph.Id, userId, node.Label, node.Notes);
if (newNode != null)
{
nodeMapping[node.Id] = newNode.Id;
}
}
// Get all edges from original graph
var edges = await GetGraphEdgesAsync(graphId, userId);
// Clone edges with new node IDs
foreach (var edge in edges)
{
if (nodeMapping.ContainsKey(edge.SourceNodeId) && nodeMapping.ContainsKey(edge.TargetNodeId))
{
await CreateEdgeAsync(newGraph.Id, userId, nodeMapping[edge.SourceNodeId], nodeMapping[edge.TargetNodeId]);
}
}
return newGraph;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to clone graph {GraphId}", graphId);
return null;
}
}
#endregion
#region Node Operations
public async Task<List<GraphNodeWithConnections>> GetGraphNodesAsync(long graphId, long userId)
{
try
{
// Verify user owns the graph
var graph = await GetGraphByIdAsync(graphId, userId);
if (graph == null) return [];
var query = @"
SELECT
n.id, n.graph_id, n.label, n.notes, n.created_at, n.updated_at,
COUNT(DISTINCT e1.id) + COUNT(DISTINCT e2.id) as connection_count
FROM app.graph_nodes n
LEFT JOIN app.graph_edges e1 ON n.id = e1.source_node_id
LEFT JOIN app.graph_edges e2 ON n.id = e2.target_node_id
WHERE n.graph_id = @graphId
GROUP BY n.id, n.graph_id, n.label, n.notes, n.created_at, n.updated_at
ORDER BY n.label";
return await db.ExecuteListReaderAsync(query, reader =>
{
return new GraphNodeWithConnections
{
Id = reader.GetInt64(0),
GraphId = reader.GetInt64(1),
Label = reader.GetString(2),
Notes = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5),
ConnectionCount = reader.GetInt32(6)
};
}, new { graphId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get nodes for graph {GraphId}", graphId);
return [];
}
}
public async Task<GraphNode?> CreateNodeAsync(long graphId, long userId, string label, string? notes = null)
{
try
{
// Verify user owns the graph
var graph = await GetGraphByIdAsync(graphId, userId);
if (graph == null) return null;
if (string.IsNullOrWhiteSpace(label))
{
logger.LogWarning("Cannot create node with empty label");
return null;
}
var query = @"
INSERT INTO app.graph_nodes (graph_id, label, notes, created_at, updated_at)
VALUES (@graphId, @label, @notes, @createdAt, @updatedAt)
RETURNING id, graph_id, label, notes, created_at, updated_at";
var node = await db.ExecuteReaderAsync(query, reader =>
{
return new GraphNode
{
Id = reader.GetInt64(0),
GraphId = reader.GetInt64(1),
Label = reader.GetString(2),
Notes = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5)
};
}, new
{
graphId,
label = label.Trim(),
notes,
createdAt = DateTime.UtcNow,
updatedAt = DateTime.UtcNow
});
// Update graph's updated_at
await TouchGraphAsync(graphId);
return node;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create node in graph {GraphId}", graphId);
return null;
}
}
public async Task<bool> UpdateNodeAsync(long nodeId, long userId, string label, string? notes)
{
try
{
if (string.IsNullOrWhiteSpace(label))
{
logger.LogWarning("Cannot update node with empty label");
return false;
}
// Get node to verify ownership through graph
var node = await GetNodeByIdAsync(nodeId);
if (node == null) return false;
var graph = await GetGraphByIdAsync(node.GraphId, userId);
if (graph == null) return false;
var query = @"
UPDATE app.graph_nodes
SET label = @label, notes = @notes, updated_at = @updatedAt
WHERE id = @nodeId";
var rowsAffected = await db.ExecuteNonQueryAsync(query, new
{
nodeId,
label = label.Trim(),
notes,
updatedAt = DateTime.UtcNow
});
if (rowsAffected > 0)
{
await TouchGraphAsync(node.GraphId);
}
return rowsAffected > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to update node {NodeId}", nodeId);
return false;
}
}
public async Task<bool> DeleteNodeAsync(long nodeId, long userId)
{
try
{
// Get node to verify ownership and get graph ID
var node = await GetNodeByIdAsync(nodeId);
if (node == null) return false;
var graph = await GetGraphByIdAsync(node.GraphId, userId);
if (graph == null) return false;
var query = "DELETE FROM app.graph_nodes WHERE id = @nodeId";
var rowsAffected = await db.ExecuteNonQueryAsync(query, new { nodeId });
if (rowsAffected > 0)
{
await TouchGraphAsync(node.GraphId);
}
return rowsAffected > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to delete node {NodeId}", nodeId);
return false;
}
}
public async Task<List<GraphNodeWithConnections>> SearchNodesAsync(long graphId, long userId, string searchTerm)
{
try
{
// Verify user owns the graph
var graph = await GetGraphByIdAsync(graphId, userId);
if (graph == null) return [];
var query = @"
SELECT
n.id, n.graph_id, n.label, n.notes, n.created_at, n.updated_at,
COUNT(DISTINCT e1.id) + COUNT(DISTINCT e2.id) as connection_count
FROM app.graph_nodes n
LEFT JOIN app.graph_edges e1 ON n.id = e1.source_node_id
LEFT JOIN app.graph_edges e2 ON n.id = e2.target_node_id
WHERE n.graph_id = @graphId
AND (LOWER(n.label) LIKE @searchPattern OR LOWER(n.notes) LIKE @searchPattern)
GROUP BY n.id, n.graph_id, n.label, n.notes, n.created_at, n.updated_at
ORDER BY n.label";
var searchPattern = $"%{searchTerm.ToLower()}%";
return await db.ExecuteListReaderAsync(query, reader =>
{
return new GraphNodeWithConnections
{
Id = reader.GetInt64(0),
GraphId = reader.GetInt64(1),
Label = reader.GetString(2),
Notes = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5),
ConnectionCount = reader.GetInt32(6)
};
}, new { graphId, searchPattern });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to search nodes in graph {GraphId}", graphId);
return [];
}
}
private async Task<GraphNode?> GetNodeByIdAsync(long nodeId)
{
try
{
var query = @"
SELECT id, graph_id, label, notes, created_at, updated_at
FROM app.graph_nodes
WHERE id = @nodeId";
return await db.ExecuteReaderAsync(query, reader =>
{
return new GraphNode
{
Id = reader.GetInt64(0),
GraphId = reader.GetInt64(1),
Label = reader.GetString(2),
Notes = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5)
};
}, new { nodeId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get node {NodeId}", nodeId);
return null;
}
}
#endregion
#region Edge Operations
public async Task<List<GraphEdge>> GetGraphEdgesAsync(long graphId, long userId)
{
try
{
// Verify user owns the graph
var graph = await GetGraphByIdAsync(graphId, userId);
if (graph == null) return [];
var query = @"
SELECT id, graph_id, source_node_id, target_node_id, created_at
FROM app.graph_edges
WHERE graph_id = @graphId
ORDER BY created_at";
return await db.ExecuteListReaderAsync(query, reader =>
{
return new GraphEdge
{
Id = reader.GetInt64(0),
GraphId = reader.GetInt64(1),
SourceNodeId = reader.GetInt64(2),
TargetNodeId = reader.GetInt64(3),
CreatedAt = reader.GetDateTime(4)
};
}, new { graphId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get edges for graph {GraphId}", graphId);
return [];
}
}
public async Task<GraphEdge?> CreateEdgeAsync(long graphId, long userId, long sourceNodeId, long targetNodeId)
{
try
{
// Verify user owns the graph
var graph = await GetGraphByIdAsync(graphId, userId);
if (graph == null) return null;
// Verify both nodes belong to this graph
var sourceNode = await GetNodeByIdAsync(sourceNodeId);
var targetNode = await GetNodeByIdAsync(targetNodeId);
if (sourceNode == null || targetNode == null ||
sourceNode.GraphId != graphId || targetNode.GraphId != graphId)
{
logger.LogWarning("Invalid nodes for edge creation");
return null;
}
var query = @"
INSERT INTO app.graph_edges (graph_id, source_node_id, target_node_id, created_at)
VALUES (@graphId, @sourceNodeId, @targetNodeId, @createdAt)
RETURNING id, graph_id, source_node_id, target_node_id, created_at";
var edge = await db.ExecuteReaderAsync(query, reader =>
{
return new GraphEdge
{
Id = reader.GetInt64(0),
GraphId = reader.GetInt64(1),
SourceNodeId = reader.GetInt64(2),
TargetNodeId = reader.GetInt64(3),
CreatedAt = reader.GetDateTime(4)
};
}, new
{
graphId,
sourceNodeId,
targetNodeId,
createdAt = DateTime.UtcNow
});
await TouchGraphAsync(graphId);
return edge;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create edge in graph {GraphId}", graphId);
return null;
}
}
public async Task<bool> DeleteEdgeAsync(long edgeId, long userId)
{
try
{
// Get edge to verify ownership through graph
var edge = await GetEdgeByIdAsync(edgeId);
if (edge == null) return false;
var graph = await GetGraphByIdAsync(edge.GraphId, userId);
if (graph == null) return false;
var query = "DELETE FROM app.graph_edges WHERE id = @edgeId";
var rowsAffected = await db.ExecuteNonQueryAsync(query, new { edgeId });
if (rowsAffected > 0)
{
await TouchGraphAsync(edge.GraphId);
}
return rowsAffected > 0;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to delete edge {EdgeId}", edgeId);
return false;
}
}
private async Task<GraphEdge?> GetEdgeByIdAsync(long edgeId)
{
try
{
var query = @"
SELECT id, graph_id, source_node_id, target_node_id, created_at
FROM app.graph_edges
WHERE id = @edgeId";
return await db.ExecuteReaderAsync(query, reader =>
{
return new GraphEdge
{
Id = reader.GetInt64(0),
GraphId = reader.GetInt64(1),
SourceNodeId = reader.GetInt64(2),
TargetNodeId = reader.GetInt64(3),
CreatedAt = reader.GetDateTime(4)
};
}, new { edgeId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get edge {EdgeId}", edgeId);
return null;
}
}
#endregion
#region Filter Operations
public async Task<List<GraphNodeWithConnections>> FilterConnectsToAsync(long graphId, long userId, long targetNodeId)
{
try
{
// Verify user owns the graph
var graph = await GetGraphByIdAsync(graphId, userId);
if (graph == null) return [];
var query = @"
SELECT
n.id, n.graph_id, n.label, n.notes, n.created_at, n.updated_at,
COUNT(DISTINCT e1.id) + COUNT(DISTINCT e2.id) as connection_count
FROM app.graph_nodes n
LEFT JOIN app.graph_edges e1 ON n.id = e1.source_node_id
LEFT JOIN app.graph_edges e2 ON n.id = e2.target_node_id
WHERE n.graph_id = @graphId
AND EXISTS (
SELECT 1 FROM app.graph_edges e
WHERE e.graph_id = @graphId
AND (
(e.source_node_id = n.id AND e.target_node_id = @targetNodeId)
OR (e.target_node_id = n.id AND e.source_node_id = @targetNodeId)
)
)
GROUP BY n.id, n.graph_id, n.label, n.notes, n.created_at, n.updated_at
ORDER BY n.label";
return await db.ExecuteListReaderAsync(query, reader =>
{
return new GraphNodeWithConnections
{
Id = reader.GetInt64(0),
GraphId = reader.GetInt64(1),
Label = reader.GetString(2),
Notes = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5),
ConnectionCount = reader.GetInt32(6)
};
}, new { graphId, targetNodeId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to filter nodes connecting to {NodeId}", targetNodeId);
return [];
}
}
public async Task<List<GraphNodeWithConnections>> FilterDoesNotConnectToAsync(long graphId, long userId, long targetNodeId)
{
try
{
// Verify user owns the graph
var graph = await GetGraphByIdAsync(graphId, userId);
if (graph == null) return [];
var query = @"
SELECT
n.id, n.graph_id, n.label, n.notes, n.created_at, n.updated_at,
COUNT(DISTINCT e1.id) + COUNT(DISTINCT e2.id) as connection_count
FROM app.graph_nodes n
LEFT JOIN app.graph_edges e1 ON n.id = e1.source_node_id
LEFT JOIN app.graph_edges e2 ON n.id = e2.target_node_id
WHERE n.graph_id = @graphId
AND n.id != @targetNodeId
AND NOT EXISTS (
SELECT 1 FROM app.graph_edges e
WHERE e.graph_id = @graphId
AND (
(e.source_node_id = n.id AND e.target_node_id = @targetNodeId)
OR (e.target_node_id = n.id AND e.source_node_id = @targetNodeId)
)
)
GROUP BY n.id, n.graph_id, n.label, n.notes, n.created_at, n.updated_at
ORDER BY n.label";
return await db.ExecuteListReaderAsync(query, reader =>
{
return new GraphNodeWithConnections
{
Id = reader.GetInt64(0),
GraphId = reader.GetInt64(1),
Label = reader.GetString(2),
Notes = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5),
ConnectionCount = reader.GetInt32(6)
};
}, new { graphId, targetNodeId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to filter nodes not connecting to {NodeId}", targetNodeId);
return [];
}
}
public async Task<List<GraphNodeWithConnections>> FilterConnectsTwoDegreesAsync(long graphId, long userId, long targetNodeId)
{
try
{
// Verify user owns the graph
var graph = await GetGraphByIdAsync(graphId, userId);
if (graph == null) return [];
// Find nodes that connect to nodes that connect to the target (bidirectional)
var query = @"
SELECT DISTINCT
n.id, n.graph_id, n.label, n.notes, n.created_at, n.updated_at,
COUNT(DISTINCT e1.id) + COUNT(DISTINCT e2.id) as connection_count
FROM app.graph_nodes n
LEFT JOIN app.graph_edges e1 ON n.id = e1.source_node_id
LEFT JOIN app.graph_edges e2 ON n.id = e2.target_node_id
WHERE n.graph_id = @graphId
AND n.id != @targetNodeId
AND EXISTS (
SELECT 1 FROM app.graph_edges e_first, app.graph_edges e_second
WHERE e_first.graph_id = @graphId
AND e_second.graph_id = @graphId
-- n connects to intermediate node (bidirectional)
AND (
(e_first.source_node_id = n.id AND e_second.source_node_id = e_first.target_node_id)
OR (e_first.source_node_id = n.id AND e_second.target_node_id = e_first.target_node_id)
OR (e_first.target_node_id = n.id AND e_second.source_node_id = e_first.source_node_id)
OR (e_first.target_node_id = n.id AND e_second.target_node_id = e_first.source_node_id)
)
-- intermediate node connects to target (bidirectional)
AND (
e_second.source_node_id = @targetNodeId
OR e_second.target_node_id = @targetNodeId
)
-- Exclude direct connections
AND NOT EXISTS (
SELECT 1 FROM app.graph_edges e_direct
WHERE e_direct.graph_id = @graphId
AND (
(e_direct.source_node_id = n.id AND e_direct.target_node_id = @targetNodeId)
OR (e_direct.target_node_id = n.id AND e_direct.source_node_id = @targetNodeId)
)
)
)
GROUP BY n.id, n.graph_id, n.label, n.notes, n.created_at, n.updated_at
ORDER BY n.label";
return await db.ExecuteListReaderAsync(query, reader =>
{
return new GraphNodeWithConnections
{
Id = reader.GetInt64(0),
GraphId = reader.GetInt64(1),
Label = reader.GetString(2),
Notes = reader.IsDBNull(3) ? null : reader.GetString(3),
CreatedAt = reader.GetDateTime(4),
UpdatedAt = reader.GetDateTime(5),
ConnectionCount = reader.GetInt32(6)
};
}, new { graphId, targetNodeId });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to filter nodes with two-degree connections to {NodeId}", targetNodeId);
return [];
}
}
#endregion
#region Helper Methods
private async Task TouchGraphAsync(long graphId)
{
try
{
var query = "UPDATE app.graphs SET updated_at = @updatedAt WHERE id = @graphId";
await db.ExecuteNonQueryAsync(query, new { graphId, updatedAt = DateTime.UtcNow });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to touch graph {GraphId}", graphId);
}
}
public async Task<GraphData> GetGraphDataAsync(long graphId, long userId)
{
try
{
var graph = await GetGraphByIdAsync(graphId, userId);
if (graph == null) return new GraphData();
var nodes = await GetGraphNodesAsync(graphId, userId);
var edges = await GetGraphEdgesAsync(graphId, userId);
return new GraphData
{
Graph = graph,
Nodes = nodes,
Edges = edges
};
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to get graph data for {GraphId}", graphId);
return new GraphData();
}
}
#endregion
}
+27 -42
View File
@@ -2,23 +2,8 @@ using Media.JoshHeaps.Net.Models;
namespace Media.JoshHeaps.Net.Services;
public class MediaService
public class MediaService(DbExecutor db, IWebHostEnvironment environment, EncryptionService encryption, ILogger<MediaService> logger, FolderService folderService)
{
private readonly DbExecutor _db;
private readonly IWebHostEnvironment _environment;
private readonly EncryptionService _encryption;
private readonly ILogger<MediaService> _logger;
private readonly FolderService _folderService;
public MediaService(DbExecutor db, IWebHostEnvironment environment, EncryptionService encryption, ILogger<MediaService> logger, FolderService folderService)
{
_db = db;
_environment = environment;
_encryption = encryption;
_logger = logger;
_folderService = folderService;
}
public async Task<UserMedia?> SaveMediaAsync(long userId, IFormFile file, string? description = null, long? folderId = null)
{
string? tempFilePath = null;
@@ -31,7 +16,7 @@ public class MediaService
var uniqueFileName = $"{Guid.NewGuid()}{fileExtension}.enc"; // .enc for encrypted
// Store outside wwwroot in App_Data folder
var mediaFolder = Path.Combine(_environment.ContentRootPath, "App_Data", "media", userId.ToString());
var mediaFolder = Path.Combine(environment.ContentRootPath, "App_Data", "media", userId.ToString());
Directory.CreateDirectory(mediaFolder);
tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
@@ -57,12 +42,12 @@ public class MediaService
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to read image dimensions for {FileName}", file.FileName);
logger.LogWarning(ex, "Failed to read image dimensions for {FileName}", file.FileName);
}
}
// Encrypt and save
await _encryption.EncryptFileAsync(tempFilePath, encryptedFilePath);
await encryption.EncryptFileAsync(tempFilePath, encryptedFilePath);
// Delete temp file
File.Delete(tempFilePath);
@@ -77,7 +62,7 @@ public class MediaService
VALUES (@userId, @fileName, @filePath, @fileSize, @mimeType, @width, @height, @description, @isEncrypted, @folderId, @createdAt, @updatedAt)
RETURNING id, user_id, file_name, file_path, file_size, mime_type, width, height, description, is_encrypted, folder_id, created_at, updated_at";
var media = await _db.ExecuteReaderAsync(query, reader =>
var media = await db.ExecuteReaderAsync(query, reader =>
{
return new UserMedia
{
@@ -115,7 +100,7 @@ public class MediaService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to save media for user {UserId}", userId);
logger.LogError(ex, "Failed to save media for user {UserId}", userId);
// Cleanup on error
if (tempFilePath != null && File.Exists(tempFilePath))
@@ -139,14 +124,14 @@ public class MediaService
var effectiveUserId = userId;
if (requestingUserId.HasValue && folderId.HasValue)
{
var hasAccess = await _folderService.HasFolderAccessAsync(folderId.Value, requestingUserId.Value);
var hasAccess = await folderService.HasFolderAccessAsync(folderId.Value, requestingUserId.Value);
if (!hasAccess)
{
_logger.LogWarning("User {RequestingUserId} does not have access to folder {FolderId}", requestingUserId.Value, folderId.Value);
return new List<UserMedia>();
logger.LogWarning("User {RequestingUserId} does not have access to folder {FolderId}", requestingUserId.Value, folderId.Value);
return [];
}
// Get the actual owner of the folder
var ownerId = await _folderService.GetFolderOwnerIdAsync(folderId.Value);
var ownerId = await folderService.GetFolderOwnerIdAsync(folderId.Value);
if (ownerId.HasValue)
{
effectiveUserId = ownerId.Value;
@@ -173,7 +158,7 @@ public class MediaService
OFFSET @offset LIMIT @limit";
}
var mediaList = await _db.ExecuteListReaderAsync(query, reader =>
var mediaList = await db.ExecuteListReaderAsync(query, reader =>
{
return new UserMedia
{
@@ -197,8 +182,8 @@ public class MediaService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get media for user {UserId}", userId);
return new List<UserMedia>();
logger.LogError(ex, "Failed to get media for user {UserId}", userId);
return [];
}
}
@@ -212,7 +197,7 @@ public class MediaService
FROM app.user_media
WHERE id = @mediaId";
var media = await _db.ExecuteReaderAsync(query, reader =>
var media = await db.ExecuteReaderAsync(query, reader =>
{
return new UserMedia
{
@@ -244,7 +229,7 @@ public class MediaService
}
// Check if user has access via shared folder
if (media.FolderId.HasValue && await _folderService.HasFolderAccessAsync(media.FolderId.Value, userId))
if (media.FolderId.HasValue && await folderService.HasFolderAccessAsync(media.FolderId.Value, userId))
{
return media;
}
@@ -254,7 +239,7 @@ public class MediaService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get media {MediaId} for user {UserId}", mediaId, userId);
logger.LogError(ex, "Failed to get media {MediaId} for user {UserId}", mediaId, userId);
return null;
}
}
@@ -266,21 +251,21 @@ public class MediaService
var media = await GetMediaByIdAsync(mediaId, userId);
if (media == null)
{
_logger.LogWarning("Media {MediaId} not found or user {UserId} doesn't have access", mediaId, userId);
logger.LogWarning("Media {MediaId} not found or user {UserId} doesn't have access", mediaId, userId);
return null;
}
var fullPath = Path.Combine(_environment.ContentRootPath, media.FilePath);
var fullPath = Path.Combine(environment.ContentRootPath, media.FilePath);
if (!File.Exists(fullPath))
{
_logger.LogError("Media file not found at {FilePath}", fullPath);
logger.LogError("Media file not found at {FilePath}", fullPath);
return null;
}
if (media.IsEncrypted)
{
return await _encryption.DecryptFileAsync(fullPath);
return await encryption.DecryptFileAsync(fullPath);
}
else
{
@@ -289,7 +274,7 @@ public class MediaService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get decrypted media data for {MediaId}", mediaId);
logger.LogError(ex, "Failed to get decrypted media data for {MediaId}", mediaId);
return null;
}
}
@@ -300,16 +285,16 @@ public class MediaService
{
// Get media info first
var query = "SELECT file_path FROM app.user_media WHERE id = @mediaId AND user_id = @userId";
var filePath = await _db.ExecuteReaderAsync(query, reader => reader.GetString(0), new { mediaId, userId });
var filePath = await db.ExecuteReaderAsync(query, reader => reader.GetString(0), new { mediaId, userId });
if (filePath == null) return false;
// Delete from database
var deleteQuery = "DELETE FROM app.user_media WHERE id = @mediaId AND user_id = @userId";
await _db.ExecuteAsync<object>(deleteQuery, new { mediaId, userId });
await db.ExecuteAsync<object>(deleteQuery, new { mediaId, userId });
// Delete physical file
var physicalPath = Path.Combine(_environment.ContentRootPath, filePath);
var physicalPath = Path.Combine(environment.ContentRootPath, filePath);
if (File.Exists(physicalPath))
{
File.Delete(physicalPath);
@@ -319,7 +304,7 @@ public class MediaService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to delete media {MediaId} for user {UserId}", mediaId, userId);
logger.LogError(ex, "Failed to delete media {MediaId} for user {UserId}", mediaId, userId);
return false;
}
}
@@ -333,7 +318,7 @@ public class MediaService
SET folder_id = @folderId, updated_at = @updatedAt
WHERE id = @mediaId AND user_id = @userId";
await _db.ExecuteAsync<object>(query, new
await db.ExecuteAsync<object>(query, new
{
mediaId,
userId,
@@ -345,7 +330,7 @@ public class MediaService
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to move media {MediaId} to folder {FolderId} for user {UserId}", mediaId, folderId, userId);
logger.LogError(ex, "Failed to move media {MediaId} to folder {FolderId} for user {UserId}", mediaId, folderId, userId);
return false;
}
}
@@ -0,0 +1,779 @@
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Channels;
namespace Media.JoshHeaps.Net.Services;
public class MedicalAiService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<MedicalAiService> _logger;
private readonly Channel<long> _queue = Channel.CreateUnbounded<long>();
private DateTime? _rateLimitResetTime;
private const string HaikuModel = "claude-haiku-4-5-20251001";
private const string SonnetModel = "claude-sonnet-4-5-20250929";
public MedicalAiService(IServiceScopeFactory scopeFactory, ILogger<MedicalAiService> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
_ = Task.Run(ProcessQueueAsync);
}
public void EnqueueProcessing(long documentId)
{
_queue.Writer.TryWrite(documentId);
_logger.LogInformation("Enqueued document {DocumentId} for AI processing", documentId);
}
private async Task ProcessQueueAsync()
{
await foreach (var documentId in _queue.Reader.ReadAllAsync())
{
if (_rateLimitResetTime.HasValue && _rateLimitResetTime.Value > DateTime.UtcNow)
{
var delay = _rateLimitResetTime.Value - DateTime.UtcNow;
_logger.LogInformation("Rate limited, waiting {Delay} until {ResetTime}", delay, _rateLimitResetTime.Value);
await Task.Delay(delay);
_rateLimitResetTime = null;
}
try
{
using var scope = _scopeFactory.CreateScope();
var medicalDocsService = scope.ServiceProvider.GetRequiredService<MedicalDocsService>();
await ProcessDocumentAsync(documentId, medicalDocsService);
}
catch (Exception ex)
{
_logger.LogError(ex, "AI processing failed for document {DocumentId}", documentId);
}
}
}
private async Task ProcessDocumentAsync(long documentId, MedicalDocsService medicalDocsService)
{
_logger.LogInformation("Starting AI processing for document {DocumentId}", documentId);
var doc = await medicalDocsService.GetDocumentByIdAsync(documentId);
if (doc == null)
{
_logger.LogWarning("Document {DocumentId} not found for AI processing", documentId);
return;
}
var aiResponses = new Dictionary<string, object>();
// Step 1: Text extraction (Haiku)
string? extractedText = null;
if (doc.DocumentType == "note")
{
extractedText = doc.Description;
}
else if (doc.DocumentType == "file")
{
var fileData = await medicalDocsService.GetDecryptedDocumentDataAsync(documentId);
if (fileData != null && doc.MimeType != null)
{
extractedText = await ExtractTextAsync(fileData, doc.MimeType, doc.FileName);
if (IsRateLimited) { _queue.Writer.TryWrite(documentId); return; }
if (extractedText != null)
aiResponses["extraction"] = new { model = HaikuModel, text = extractedText };
}
}
if (string.IsNullOrWhiteSpace(extractedText))
{
_logger.LogWarning("No text could be extracted from document {DocumentId}", documentId);
extractedText = doc.Title ?? doc.FileName ?? "";
}
// Step 2: Classification + tagging + doctor name (Haiku)
string? classification = doc.Classification;
List<string> tags = [];
string? doctorName = null;
List<string> conditionNames = [];
try
{
var classResult = await ClassifyAndTagAsync(extractedText);
if (IsRateLimited) { _queue.Writer.TryWrite(documentId); return; }
if (classResult != null)
{
classification = classResult.Classification ?? classification;
tags = classResult.Tags ?? [];
doctorName = classResult.DoctorName;
conditionNames = classResult.ConditionNames ?? [];
aiResponses["classification"] = classResult;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Classification failed for document {DocumentId}", documentId);
}
// Step 3: Associate doctor to document (ALL types)
long? doctorId = null;
if (!string.IsNullOrWhiteSpace(doctorName))
{
try
{
var doctor = await medicalDocsService.FindOrCreateDoctorByNameAsync(doctorName.Trim());
doctorId = doctor?.Id;
}
catch (Exception ex)
{
_logger.LogError(ex, "Doctor association failed for document {DocumentId}", documentId);
}
}
// Step 3b: Associate conditions to document (ALL types)
if (conditionNames.Count > 0)
{
try
{
await medicalDocsService.AssignConditionsFromAiAsync(
documentId, doc.PersonId, conditionNames, this);
}
catch (Exception ex)
{
_logger.LogError(ex, "Condition association failed for document {DocumentId}", documentId);
}
}
// Step 4: Branch on classification for targeted extraction
var effectiveClassification = classification ?? "other";
BillingExtractionResult? billingData = null;
PrescriptionExtractionResult? prescriptionData = null;
if (effectiveClassification is "receipt" or "insurance")
{
try
{
billingData = await ExtractBillingDataAsync(extractedText, effectiveClassification);
if (IsRateLimited) { _queue.Writer.TryWrite(documentId); return; }
if (billingData != null)
aiResponses["billing"] = billingData;
}
catch (Exception ex)
{
_logger.LogError(ex, "Billing extraction failed for document {DocumentId}", documentId);
}
}
else if (effectiveClassification == "prescription")
{
try
{
prescriptionData = await ExtractPrescriptionDataAsync(extractedText);
if (IsRateLimited) { _queue.Writer.TryWrite(documentId); return; }
if (prescriptionData != null)
aiResponses["prescription"] = prescriptionData;
}
catch (Exception ex)
{
_logger.LogError(ex, "Prescription extraction failed for document {DocumentId}", documentId);
}
}
// Step 5: Sanitize billing data
if (billingData != null)
SanitizeExtractedBills(billingData);
// Step 6: Persist results
var rawResponse = JsonSerializer.Serialize(aiResponses, JsonOpts);
await medicalDocsService.UpdateAiResultsAsync(documentId, extractedText, classification, rawResponse, doctorId);
if (tags.Count > 0)
await medicalDocsService.AddTagsAsync(documentId, tags);
// Clean up prior AI bills for this document (handles re-processing)
await medicalDocsService.CleanupAiBillsForDocumentAsync(documentId);
// Handle prescription documents
if (prescriptionData?.PrescriptionInfo is { MedicationName: not null } rxInfo)
{
try
{
await medicalDocsService.AddPrescriptionFromAiAsync(
documentId, doc.PersonId, rxInfo, doctorName, this);
}
catch (Exception ex)
{
_logger.LogError(ex, "AI prescription processing failed for document {DocumentId}", documentId);
}
}
// Bill processing (billing documents only)
if (billingData?.Bills is { Count: > 0 })
await medicalDocsService.AddBillsFromAiAsync(documentId, doc.PersonId, billingData.Bills, billingData.Payments, this);
_logger.LogInformation("AI processing complete for document {DocumentId}: classification={Classification}, tags={TagCount}, bills={BillCount}",
documentId, classification, tags.Count, billingData?.Bills?.Count ?? 0);
}
private bool IsRateLimited => _rateLimitResetTime.HasValue && _rateLimitResetTime.Value > DateTime.UtcNow;
private async Task<string?> ExtractTextAsync(byte[] fileData, string mimeType, string? fileName)
{
_logger.LogInformation("Extracting text via CLI, mimeType={MimeType}, size={Size}KB", mimeType, fileData.Length / 1024);
var isImage = mimeType.StartsWith("image/", StringComparison.OrdinalIgnoreCase);
var isPdf = mimeType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase);
if (!isImage && !isPdf)
{
_logger.LogInformation("Unsupported mime type {MimeType} for text extraction", mimeType);
return null;
}
// Write decrypted file to temp path so the CLI can read it
var ext = isPdf ? ".pdf" : Path.GetExtension(fileName ?? ".png");
var tempPath = Path.Combine(Path.GetTempPath(), $"meddoc_{Guid.NewGuid()}{ext}");
try
{
await File.WriteAllBytesAsync(tempPath, fileData);
var systemPrompt = "Extract all text from this medical document. Include all visible text, numbers, dates, names, and amounts. Preserve the structure and formatting as much as possible. If the document is handwritten, do your best to transcribe it. Return only the extracted text, no commentary.";
var userPrompt = $"Please read and extract all text from the file at: {tempPath}";
return await CallClaudeCliAsync(systemPrompt, userPrompt, HaikuModel, allowReadTool: true);
}
finally
{
try { File.Delete(tempPath); } catch { /* cleanup best-effort */ }
}
}
private async Task<ClassificationResult?> ClassifyAndTagAsync(string text)
{
_logger.LogInformation("Classifying and tagging via Haiku CLI");
var truncatedText = text.Length > 4000 ? text[..4000] : text;
var systemPrompt = @"You are a medical document classifier. Analyze the document text and return a JSON object with:
- ""classification"": one of: receipt, lab_result, prescription, imaging, dr_note, insurance, referral, discharge, recording, other
- ""tags"": array of relevant tag strings (lowercase, e.g. ""blood work"", ""cardiology"", ""annual physical"", ""copay"")
- ""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.
Return ONLY the JSON object, no other text.";
var userPrompt = $"Analyze this medical document text and classify it.\n\nDocument text:\n{truncatedText}";
var response = await CallClaudeCliAsync(systemPrompt, userPrompt, HaikuModel);
if (response == null) return null;
var json = ExtractJson(response);
try
{
return JsonSerializer.Deserialize<ClassificationResult>(json, JsonOpts);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to parse classification response: {Response}", response);
return null;
}
}
private async Task<BillingExtractionResult?> ExtractBillingDataAsync(string text, string classification)
{
_logger.LogInformation("Extracting billing data via Sonnet CLI, classification={Classification}", classification);
var truncatedText = text.Length > 6000 ? text[..6000] : text;
var systemPrompt = @"You are a medical billing data extractor. Extract financial data from this document.
Return a JSON object with:
- ""bills"": array of bill/charge objects, each with: ""totalAmount"" (number, the GROSS total of all positive charges before any payments or credits), ""category"" (string: office_visit, lab, pharmacy, imaging, therapy, hospital, specialist, other), ""billDate"" (string, YYYY-MM-DD or null), ""summary"" (string, brief description of the charge), ""providerName"" (string or null — the billing provider/facility name, e.g. ""Intermountain Healthcare"", ""Walgreens"". This is the entity sending the bill, NOT the individual doctor), ""lineItems"" (array of {""description"": string, ""amount"": number} or null — only POSITIVE charge items)
- ""payments"": array of payment objects, each with: ""amount"" (number, always positive), ""paymentType"" (string: patient_payment, insurance_payment, insurance_adjustment, write_off), ""paymentDate"" (string, YYYY-MM-DD or null), ""description"" (string), ""billIndex"" (number or null, 0-based index into the bills array that this payment applies to)
CRITICAL — line items vs payments:
- Line items are ONLY positive charges that break down what was billed (e.g., ""Vitrectomy: $5,731"", ""Supplies: $7,500"").
- Negative amounts, credits, refunds, or items labeled ""payment"" are PAYMENTS, not line items. Extract them in the ""payments"" array with a positive amount.
Example: a line showing ""Payment: -$25.00"" → extract as a patient_payment of $25 (NOT as a line item of -$25).
- totalAmount should be the sum of POSITIVE charges only (before credits/payments are subtracted). Do not subtract payments from totalAmount.
Guidelines for document types:
- EOBs (Explanation of Benefits): create the bill (total charge) plus insurance_payment and/or insurance_adjustment for what insurance covered, and patient_payment for patient responsibility
- Receipts: create the bill (total charge) plus a patient_payment for the amount paid
- Invoices/statements/estimates: create the bill (total positive charges). If any payment or credit lines appear, extract those as payments.
- Each unique charge should be one bill. Do NOT create separate bills for line items that are part of the same visit/service — sum them into one bill.
- If the document lists individual charges (e.g., line items on a statement like ""exam: $150"", ""blood draw: $30""), include them in the ""lineItems"" array for that bill. The sum of line items should approximate totalAmount.
Only include fields you can confidently extract. If no bills are found, return empty arrays. Return ONLY the JSON object, no other text.";
var userPrompt = $"Classification: {classification}\n\nDocument text:\n{truncatedText}";
var response = await CallClaudeCliAsync(systemPrompt, userPrompt, SonnetModel);
if (response == null) return null;
var json = ExtractJson(response);
try
{
return JsonSerializer.Deserialize<BillingExtractionResult>(json, JsonOpts);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to parse billing extraction response: {Response}", response);
return null;
}
}
private async Task<PrescriptionExtractionResult?> ExtractPrescriptionDataAsync(string text)
{
_logger.LogInformation("Extracting prescription data via Sonnet CLI");
var truncatedText = text.Length > 6000 ? text[..6000] : text;
var systemPrompt = @"You are a medical prescription data extractor. Extract prescription details from this document.
Return a JSON object with:
- ""prescriptionInfo"": object with ""medicationName"" (string), ""dosage"" (string or null), ""frequency"" (string or null), ""rxNumber"" (the Rx/prescription number, string or null), ""pharmacy"" (pharmacy name e.g. ""Walgreens"", string or null), ""copay"" (number or null, amount paid), ""pickupDate"" (YYYY-MM-DD or null), ""personName"" (patient name, string or null), ""doctorName"" (prescribing doctor name, string or null)
Only include fields you can confidently extract. Return ONLY the JSON object, no other text.";
var userPrompt = $"Document text:\n{truncatedText}";
var response = await CallClaudeCliAsync(systemPrompt, userPrompt, SonnetModel);
if (response == null) return null;
var json = ExtractJson(response);
try
{
return JsonSerializer.Deserialize<PrescriptionExtractionResult>(json, JsonOpts);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to parse prescription extraction response: {Response}", response);
return null;
}
}
private async Task<string?> CallClaudeCliAsync(string systemPrompt, string userPrompt, string? model = null, bool allowReadTool = false)
{
var combinedPrompt = $"{systemPrompt}\n\n{userPrompt}";
var args = new StringBuilder("-p --output-format text");
if (!string.IsNullOrEmpty(model))
args.Append($" --model {model}");
if (allowReadTool)
args.Append(" --allowedTools Read");
var psi = new ProcessStartInfo
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
if (OperatingSystem.IsWindows())
{
psi.FileName = "cmd.exe";
psi.Arguments = $"/c claude {args}";
}
else
{
psi.FileName = "claude";
psi.Arguments = args.ToString();
}
using var process = Process.Start(psi);
if (process == null)
{
_logger.LogError("Failed to start claude CLI process");
return null;
}
// Write prompt to stdin, then close to signal EOF
await process.StandardInput.WriteAsync(combinedPrompt);
process.StandardInput.Close();
// Read stdout/stderr concurrently to avoid deadlocks
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(120));
try
{
await process.WaitForExitAsync(cts.Token);
}
catch (OperationCanceledException)
{
process.Kill();
_logger.LogError("claude CLI timed out after 120 seconds");
return null;
}
var stdout = await stdoutTask;
var stderr = await stderrTask;
if (!string.IsNullOrEmpty(stderr))
{
var resetTime = ParseRateLimitReset(stderr);
if (resetTime.HasValue)
{
_rateLimitResetTime = resetTime.Value;
_logger.LogWarning("Rate limit detected, reset at {ResetTime}", resetTime.Value);
return null;
}
// Log non-rate-limit stderr as debug info
_logger.LogDebug("claude CLI stderr: {Stderr}", stderr);
}
if (process.ExitCode != 0)
{
// Check stdout too for rate limit messages (some CLIs write there)
var resetFromStdout = ParseRateLimitReset(stdout);
if (resetFromStdout.HasValue)
{
_rateLimitResetTime = resetFromStdout.Value;
_logger.LogWarning("Rate limit detected in stdout, reset at {ResetTime}", resetFromStdout.Value);
return null;
}
_logger.LogError("claude CLI exited with code {ExitCode}: {Stderr}", process.ExitCode, stderr);
return null;
}
return string.IsNullOrWhiteSpace(stdout) ? null : stdout.Trim();
}
private DateTime? ParseRateLimitReset(string output)
{
if (string.IsNullOrEmpty(output)) return null;
// Try ISO timestamp pattern (e.g., 2026-02-09T14:30:00)
var isoMatch = Regex.Match(output, @"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})");
if (isoMatch.Success && DateTime.TryParse(isoMatch.Groups[1].Value, out var isoTime))
{
return isoTime.ToUniversalTime();
}
// Try time pattern (e.g., "reset at 2:30 PM", "try again at 14:30")
var timeMatch = Regex.Match(output, @"(?:reset|try again|available)(?:\s+at)?\s+(\d{1,2}:\d{2}\s*(?:[APap][Mm])?)", RegexOptions.IgnoreCase);
if (timeMatch.Success && DateTime.TryParse(timeMatch.Groups[1].Value, out var parsedTime))
{
// Assume today; if the time has passed, assume tomorrow
var today = DateTime.Today.Add(parsedTime.TimeOfDay);
if (today < DateTime.Now)
today = today.AddDays(1);
return today.ToUniversalTime();
}
// Try "in X minutes" pattern
var minutesMatch = Regex.Match(output, @"(?:in|after)\s+(\d+)\s+minute", RegexOptions.IgnoreCase);
if (minutesMatch.Success && int.TryParse(minutesMatch.Groups[1].Value, out var minutes))
{
return DateTime.UtcNow.AddMinutes(minutes);
}
// Fallback: detect rate limit keywords without a parseable time → wait 15 minutes
if (Regex.IsMatch(output, @"rate.?limit|session.?limit|too many requests|usage limit", RegexOptions.IgnoreCase))
{
return DateTime.UtcNow.AddMinutes(15);
}
return null;
}
private static string ExtractJson(string response)
{
var trimmed = response.Trim();
if (trimmed.StartsWith("```"))
{
var firstNewline = trimmed.IndexOf('\n');
if (firstNewline >= 0)
{
trimmed = trimmed[(firstNewline + 1)..];
var lastFence = trimmed.LastIndexOf("```");
if (lastFence >= 0)
trimmed = trimmed[..lastFence];
}
}
return trimmed.Trim();
}
private static readonly JsonSerializerOptions JsonOpts = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
internal static void SanitizeExtractedBills(BillingExtractionResult result)
{
if (result.Bills == null) return;
result.Payments ??= [];
var paymentKeywords = new[] { "payment", "credit", "refund", "adjustment", "write-off", "write off", "discount", "applied" };
var insuranceKeywords = new[] { "insurance", "ins ", "ins.", "aetna", "cigna", "united", "blue cross", "bcbs", "humana", "anthem", "medicare", "medicaid" };
foreach (var bill in result.Bills)
{
if (bill.LineItems == null) continue;
var toRemove = new List<LineItemExtraction>();
foreach (var item in bill.LineItems)
{
var desc = item.Description?.ToLowerInvariant() ?? "";
var isNegative = item.Amount < 0;
var hasPaymentKeyword = paymentKeywords.Any(k => desc.Contains(k));
if (!isNegative && !hasPaymentKeyword) continue;
var isInsurance = insuranceKeywords.Any(k => desc.Contains(k));
var paymentType = isInsurance ? "insurance_payment" : "patient_payment";
if (desc.Contains("adjustment") || desc.Contains("write-off") || desc.Contains("write off"))
paymentType = isInsurance ? "insurance_adjustment" : "write_off";
var billIndex = result.Bills.IndexOf(bill);
result.Payments.Add(new PaymentExtraction
{
Amount = Math.Abs(item.Amount),
PaymentType = paymentType,
Description = item.Description,
BillIndex = billIndex >= 0 ? billIndex : null
});
toRemove.Add(item);
}
foreach (var item in toRemove)
bill.LineItems.Remove(item);
}
}
public async Task<bool> DisambiguateBillMatchAsync(List<Models.MedicalBillCharge> existingCharges, List<LineItemExtraction> newItems, string? newSummary)
{
try
{
var existingLines = string.Join("\n", existingCharges.Select(c => $" - {c.Description}: ${c.Amount:F2}"));
var newLines = string.Join("\n", newItems.Select(i => $" - {i.Description}: ${i.Amount:F2}"));
var systemPrompt = @"You are comparing two sets of medical bill charges to determine if they represent the same bill. Return ONLY a JSON object with:
- ""sameBill"": true or false
- ""confidence"": ""high"", ""medium"", or ""low""
Consider: charges from the same bill may have slightly different descriptions or amounts across statements. Monthly statements of the same recurring service are the same bill.";
var userPrompt = $"Existing bill charges:\n{existingLines}\n\nNew document charges:\n{newLines}";
if (!string.IsNullOrEmpty(newSummary))
userPrompt += $"\n\nNew document summary: {newSummary}";
var response = await CallClaudeCliAsync(systemPrompt, userPrompt, HaikuModel);
if (response == null) return false;
var json = ExtractJson(response);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var sameBill = root.TryGetProperty("sameBill", out var sb) && sb.GetBoolean();
var confidence = root.TryGetProperty("confidence", out var conf) ? conf.GetString() : "low";
return sameBill && confidence != "low";
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Bill disambiguation failed, defaulting to no match");
return false;
}
}
public async Task<string?> FuzzyMatchProviderAsync(string extractedName, List<string> existingProviderNames)
{
try
{
var providerList = string.Join("\n", existingProviderNames.Select(n => $" - {n}"));
var systemPrompt = @"You are matching a billing provider name extracted from a medical document against a list of known providers. 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, slight misspellings, and variations (e.g., ""Intermountain Health"" matches ""Intermountain Healthcare""). Only return a match with medium or high confidence.";
var userPrompt = $"Extracted provider name: \"{extractedName}\"\n\nExisting providers:\n{providerList}";
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 provider matching failed for \"{ExtractedName}\"", extractedName);
return null;
}
}
public async Task<string?> FuzzyMatchConditionAsync(string extractedName, List<string> existingConditionNames)
{
try
{
var conditionList = string.Join("\n", existingConditionNames.Select(n => $" - {n}"));
var systemPrompt = @"You are matching a medical condition name extracted from a document against a list of known conditions 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, slight variations, and synonyms (e.g., ""Type 2 Diabetes"" matches ""Diabetes Mellitus Type 2"", ""HTN"" matches ""Hypertension""). Only return a match with medium or high confidence.";
var userPrompt = $"Extracted condition name: \"{extractedName}\"\n\nExisting conditions:\n{conditionList}";
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 condition matching failed for \"{ExtractedName}\"", extractedName);
return null;
}
}
public async Task<string?> GenerateVisitPrepSummaryAsync(string doctorName, string? specialty, Models.VisitPrepData data)
{
var sb = new StringBuilder();
sb.AppendLine($"Doctor: {doctorName}");
if (!string.IsNullOrEmpty(specialty))
sb.AppendLine($"Specialty: {specialty}");
sb.AppendLine();
if (data.ActiveConditions.Count > 0)
{
sb.AppendLine("Active Conditions:");
foreach (var c in data.ActiveConditions)
sb.AppendLine($" - {c.Name}{(c.DiagnosedDate.HasValue ? $" (diagnosed {c.DiagnosedDate:yyyy-MM-dd})" : "")}");
sb.AppendLine();
}
if (data.ActivePrescriptions.Count > 0)
{
sb.AppendLine("Current Medications:");
foreach (var rx in data.ActivePrescriptions)
{
var details = new List<string>();
if (!string.IsNullOrEmpty(rx.Dosage)) details.Add(rx.Dosage);
if (!string.IsNullOrEmpty(rx.Frequency)) details.Add(rx.Frequency);
sb.AppendLine($" - {rx.MedicationName}{(details.Count > 0 ? $" ({string.Join(", ", details)})" : "")}");
}
sb.AppendLine();
}
if (data.RecentDocuments.Count > 0)
{
sb.AppendLine("Recent Documents with this Doctor:");
foreach (var doc in data.RecentDocuments)
sb.AppendLine($" - {doc.Title ?? doc.FileName ?? "Untitled"}{(doc.DocumentDate.HasValue ? $" ({doc.DocumentDate:yyyy-MM-dd})" : "")}{(!string.IsNullOrEmpty(doc.Classification) ? $" [{doc.Classification}]" : "")}");
sb.AppendLine();
}
if (data.RecentBills.Count > 0)
{
sb.AppendLine("Recent Bills with this Doctor (last 6 months):");
foreach (var bill in data.RecentBills)
sb.AppendLine($" - ${bill.TotalAmount:F2}{(!string.IsNullOrEmpty(bill.Summary) ? $" - {bill.Summary}" : "")}{(bill.BillDate.HasValue ? $" ({bill.BillDate:yyyy-MM-dd})" : "")}");
sb.AppendLine();
}
var systemPrompt = "You are a medical visit preparation assistant. Produce a concise narrative summary for a patient preparing to visit their doctor. Include: key conditions to discuss, current medications to review, recent visits, and any billing notes. Keep under 500 words.";
var userPrompt = sb.ToString();
return await CallClaudeCliAsync(systemPrompt, userPrompt, SonnetModel);
}
// --- Response DTOs ---
public class ClassificationResult
{
public string? Classification { get; set; }
public List<string>? Tags { get; set; }
public string? DoctorName { get; set; }
public List<string>? ConditionNames { get; set; }
}
public class BillingExtractionResult
{
public List<BillExtraction>? Bills { get; set; }
public List<PaymentExtraction>? Payments { get; set; }
}
public class PrescriptionExtractionResult
{
public PrescriptionInfo? PrescriptionInfo { get; set; }
}
public class BillExtraction
{
public decimal TotalAmount { get; set; }
public string? Category { get; set; }
public string? BillDate { get; set; }
public string? Summary { get; set; }
public string? ProviderName { get; set; }
public List<LineItemExtraction>? LineItems { get; set; }
}
public class LineItemExtraction
{
public string? Description { get; set; }
public decimal Amount { get; set; }
}
public class PaymentExtraction
{
public decimal Amount { get; set; }
public string? PaymentType { get; set; }
public string? PaymentDate { get; set; }
public string? Description { get; set; }
public int? BillIndex { get; set; }
}
public class PrescriptionInfo
{
public string? MedicationName { get; set; }
public string? Dosage { get; set; }
public string? Frequency { get; set; }
public string? RxNumber { get; set; }
public string? Pharmacy { get; set; }
public decimal? Copay { get; set; }
public string? PickupDate { get; set; }
public string? PersonName { get; set; }
public string? DoctorName { get; set; }
}
}
File diff suppressed because it is too large Load Diff
+6 -13
View File
@@ -2,15 +2,8 @@ using Media.JoshHeaps.Net.Models;
namespace Media.JoshHeaps.Net.Services;
public class UserService
public class UserService(DbExecutor db)
{
private readonly DbExecutor _db;
public UserService(DbExecutor db)
{
_db = db;
}
public async Task<UserDashboard?> GetUserDashboardAsync(long userId)
{
try
@@ -23,7 +16,7 @@ public class UserService
LEFT JOIN app.user_profiles p ON u.id = p.user_id
WHERE u.id = @userId";
var dashboard = await _db.ExecuteReaderAsync(query, reader =>
var dashboard = await db.ExecuteReaderAsync(query, reader =>
{
return new UserDashboard
{
@@ -62,7 +55,7 @@ public class UserService
FROM app.user_profiles
WHERE user_id = @userId";
var profile = await _db.ExecuteReaderAsync(query, reader =>
var profile = await db.ExecuteReaderAsync(query, reader =>
{
return new UserProfile
{
@@ -87,7 +80,7 @@ public class UserService
{
try
{
await _db.ExecuteAsync<object>(
await db.ExecuteAsync<object>(
@"UPDATE app.user_profiles
SET bio = @bio, avatar_url = @avatarUrl, location = @location,
website = @website, updated_at = @updatedAt
@@ -116,7 +109,7 @@ public class UserService
ORDER BY username ASC
LIMIT 10";
var users = await _db.ExecuteListReaderAsync(searchQuery, reader =>
var users = await db.ExecuteListReaderAsync(searchQuery, reader =>
{
return new UserSearchResult
{
@@ -130,7 +123,7 @@ public class UserService
}
catch (Exception)
{
return new List<UserSearchResult>();
return [];
}
}
}
+4
View File
@@ -20,6 +20,10 @@
"FromName": "Media App",
"EnableSsl": "true"
},
"BlogCache": {
"InvalidateUrl": "https://joshheaps.net/api/blog/invalidate",
"InvalidateKey": "CHANGE_ME"
},
"FileUpload": {
"MaxFileSizeMB": 10,
"AllowedImageTypes": ["image/jpeg", "image/png", "image/gif", "image/webp"],
@@ -0,0 +1,188 @@
.dashboard-container {
max-width: 1200px;
margin: 0 auto;
padding: 40px 20px;
}
.welcome-section {
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
color: var(--text-primary);
padding: 32px 40px;
border-radius: 8px;
margin-bottom: 32px;
display: flex;
justify-content: space-between;
align-items: center;
}
.welcome-left {
display: flex;
align-items: center;
gap: 16px;
}
.back-button {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
color: var(--text-secondary);
text-decoration: none;
transition: all 0.2s ease;
flex-shrink: 0;
}
.back-button:hover {
background: var(--bg-hover);
border-color: var(--accent-primary);
color: var(--accent-primary);
transform: translateX(-2px);
}
.back-button svg {
width: 20px;
height: 20px;
}
.welcome-section h1 {
margin: 0;
font-size: 28px;
font-weight: 600;
letter-spacing: -0.5px;
}
.welcome-section p {
margin: 0;
opacity: 0.8;
font-size: 16px;
}
.dashboard-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.card {
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
padding: 24px;
transition: border-color 0.2s ease;
}
.card:hover {
border-color: var(--border-secondary);
}
.card 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;
}
.info-row {
display: flex;
justify-content: space-between;
padding: 12px 0;
border-bottom: 1px solid var(--border-secondary);
}
.info-row:last-child {
border-bottom: none;
}
.info-label {
font-weight: 500;
color: var(--text-secondary);
}
.info-value {
color: var(--text-primary);
font-weight: 500;
}
.status-badge {
display: inline-block;
padding: 4px 12px;
border-radius: 6px;
font-size: 12px;
font-weight: 600;
}
.status-verified {
background: rgba(63, 185, 80, 0.15);
color: var(--success);
}
.status-unverified {
background: rgba(187, 128, 9, 0.15);
color: #d29922;
}
.quick-actions {
display: flex;
gap: 10px;
flex-wrap: wrap;
align-content: space-evenly;
}
.btn {
padding: 8px 16px;
border-radius: 6px;
text-decoration: none;
font-weight: 500;
font-size: 14px;
display: inline-block;
transition: all 0.2s ease;
border: 1px solid transparent;
}
.btn-primary {
background: var(--accent-primary);
color: var(--bg-primary);
border-color: var(--accent-primary);
}
.btn-primary:hover {
background: var(--accent-hover);
border-color: var(--accent-hover);
}
.btn-secondary {
background: var(--bg-tertiary);
color: var(--text-primary);
border-color: var(--border-primary);
}
.btn-secondary:hover {
background: var(--bg-hover);
border-color: var(--border-secondary);
}
.btn-danger {
background: transparent;
color: var(--danger);
border-color: var(--danger);
}
.btn-danger:hover {
background: var(--danger);
color: var(--text-primary);
}
.empty-state {
text-align: center;
color: var(--text-secondary);
padding: 20px;
font-style: italic;
}
+355
View File
@@ -0,0 +1,355 @@
.dashboard-container {
max-width: 1200px;
margin: 0 auto;
padding: 40px 20px;
}
.welcome-section {
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
color: var(--text-primary);
padding: 32px 40px;
border-radius: 8px;
margin-bottom: 32px;
display: flex;
justify-content: space-between;
align-items: center;
}
.welcome-left {
display: flex;
align-items: center;
gap: 16px;
}
.back-button {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
color: var(--text-secondary);
text-decoration: none;
transition: all 0.2s ease;
flex-shrink: 0;
}
.back-button:hover {
background: var(--bg-hover);
border-color: var(--accent-primary);
color: var(--accent-primary);
transform: translateX(-2px);
}
.back-button svg {
width: 20px;
height: 20px;
}
.welcome-section h1 {
margin: 0;
font-size: 28px;
font-weight: 600;
letter-spacing: -0.5px;
}
.quick-actions {
display: flex;
gap: 12px;
}
.btn {
padding: 10px 20px;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
text-decoration: none;
cursor: pointer;
border: 1px solid transparent;
transition: all 0.2s ease;
}
.btn-primary {
background: var(--accent-primary);
color: #fff;
border-color: var(--accent-primary);
}
.btn-primary:hover {
background: var(--accent-hover);
border-color: var(--accent-hover);
}
.btn-secondary {
background: var(--bg-secondary);
color: var(--text-primary);
border-color: var(--border-primary);
}
.btn-secondary:hover {
background: var(--bg-hover);
border-color: var(--accent-primary);
}
.btn-danger {
background: var(--danger);
color: #fff;
border-color: var(--danger);
}
.btn-danger:hover {
background: var(--danger-hover);
border-color: var(--danger-hover);
}
/* Admin sections */
.admin-section {
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
padding: 24px;
margin-bottom: 24px;
}
.section-header {
margin-bottom: 16px;
}
.section-header h2 {
margin: 0;
font-size: 20px;
font-weight: 600;
color: var(--text-primary);
}
/* Roles list */
.roles-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 16px;
}
.role-pill {
display: inline-flex;
align-items: center;
padding: 6px 12px;
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 20px;
font-size: 13px;
color: var(--text-primary);
}
/* Create role form */
.create-role-form {
display: flex;
gap: 8px;
align-items: center;
}
.form-input {
padding: 8px 12px;
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: 6px;
color: var(--text-primary);
font-size: 14px;
outline: none;
transition: border-color 0.2s ease;
}
.form-input:focus {
border-color: var(--accent-primary);
}
/* Users table */
.table-container {
overflow-x: auto;
}
.admin-table {
width: 100%;
border-collapse: collapse;
}
.admin-table th,
.admin-table td {
padding: 12px 16px;
text-align: left;
border-bottom: 1px solid var(--border-secondary);
}
.admin-table th {
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-secondary);
background: var(--bg-tertiary);
}
.admin-table td {
font-size: 14px;
color: var(--text-primary);
}
.admin-table tbody tr:hover {
background: var(--bg-hover);
}
/* Role badges in table */
.role-badges {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.role-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 10px;
background: var(--accent-primary);
color: #fff;
border-radius: 12px;
font-size: 12px;
font-weight: 500;
}
.role-badge .remove-role {
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
border: none;
background: rgba(255, 255, 255, 0.2);
color: #fff;
border-radius: 50%;
font-size: 11px;
cursor: pointer;
line-height: 1;
padding: 0;
transition: background 0.2s ease;
}
.role-badge .remove-role:hover {
background: rgba(255, 255, 255, 0.4);
}
/* Add role dropdown */
.add-role-wrapper {
position: relative;
display: inline-block;
}
.add-role-btn {
padding: 4px 10px;
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 6px;
color: var(--text-secondary);
font-size: 12px;
cursor: pointer;
transition: all 0.2s ease;
}
.add-role-btn:hover {
border-color: var(--accent-primary);
color: var(--accent-primary);
}
.add-role-dropdown {
position: absolute;
top: 100%;
left: 0;
margin-top: 4px;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 6px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
z-index: 10;
min-width: 140px;
display: none;
}
.add-role-dropdown.open {
display: block;
}
.add-role-dropdown button {
display: block;
width: 100%;
padding: 8px 12px;
background: none;
border: none;
color: var(--text-primary);
font-size: 13px;
text-align: left;
cursor: pointer;
transition: background 0.15s ease;
}
.add-role-dropdown button:hover {
background: var(--bg-hover);
}
/* Pagination */
.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 12px;
margin-top: 20px;
padding-top: 16px;
}
.pagination button {
padding: 8px 16px;
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 6px;
color: var(--text-primary);
font-size: 13px;
cursor: pointer;
transition: all 0.2s ease;
}
.pagination button:hover:not(:disabled) {
border-color: var(--accent-primary);
color: var(--accent-primary);
}
.pagination button:disabled {
opacity: 0.4;
cursor: default;
}
.pagination .page-info {
font-size: 13px;
color: var(--text-secondary);
}
/* Responsive */
@media (max-width: 768px) {
.welcome-section {
flex-direction: column;
gap: 16px;
padding: 20px;
align-items: flex-start;
}
.admin-table th,
.admin-table td {
padding: 8px 10px;
}
.create-role-form {
flex-direction: column;
align-items: stretch;
}
}
@@ -0,0 +1,281 @@
.dashboard-container {
max-width: 1200px;
margin: 0 auto;
padding: 40px 20px;
}
.welcome-section {
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
color: var(--text-primary);
padding: 32px 40px;
border-radius: 8px;
margin-bottom: 32px;
display: flex;
justify-content: space-between;
align-items: center;
}
.welcome-left {
display: flex;
align-items: center;
gap: 16px;
}
.back-button {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
color: var(--text-secondary);
text-decoration: none;
transition: all 0.2s ease;
flex-shrink: 0;
}
.back-button:hover {
background: var(--bg-hover);
border-color: var(--accent-primary);
color: var(--accent-primary);
transform: translateX(-2px);
}
.back-button svg {
width: 20px;
height: 20px;
}
.welcome-section h1 {
margin: 0;
font-size: 28px;
font-weight: 600;
letter-spacing: -0.5px;
}
.quick-actions {
display: flex;
gap: 12px;
}
.btn {
padding: 10px 20px;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
text-decoration: none;
cursor: pointer;
border: 1px solid transparent;
transition: all 0.2s ease;
}
.btn-sm {
padding: 6px 12px;
font-size: 13px;
}
.btn-primary {
background: var(--accent-primary);
color: #fff;
border-color: var(--accent-primary);
}
.btn-primary:hover {
background: var(--accent-hover);
border-color: var(--accent-hover);
}
.btn-secondary {
background: var(--bg-secondary);
color: var(--text-primary);
border-color: var(--border-primary);
}
.btn-secondary:hover {
background: var(--bg-hover);
border-color: var(--accent-primary);
}
.btn-danger {
background: var(--danger);
color: #fff;
border-color: var(--danger);
}
.btn-danger:hover {
background: var(--danger-hover);
border-color: var(--danger-hover);
}
.admin-section {
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
padding: 24px;
margin-bottom: 24px;
}
.section-header {
margin-bottom: 16px;
}
.section-header h2 {
margin: 0;
font-size: 20px;
font-weight: 600;
color: var(--text-primary);
}
.table-container {
overflow-x: auto;
}
.admin-table {
width: 100%;
border-collapse: collapse;
}
.admin-table th,
.admin-table td {
padding: 12px 16px;
text-align: left;
border-bottom: 1px solid var(--border-secondary);
}
.admin-table th {
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-secondary);
background: var(--bg-tertiary);
}
.admin-table td {
font-size: 14px;
color: var(--text-primary);
}
.admin-table tbody tr:hover {
background: var(--bg-hover);
}
.admin-table code {
font-size: 12px;
padding: 2px 6px;
background: var(--bg-tertiary);
border-radius: 4px;
color: var(--text-secondary);
}
.empty-message {
text-align: center;
color: var(--text-secondary);
font-style: italic;
}
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.tag-pill {
display: inline-flex;
align-items: center;
padding: 2px 8px;
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 12px;
font-size: 12px;
color: var(--text-secondary);
}
.action-cell {
display: flex;
gap: 6px;
}
/* Editor form */
.form-group {
margin-bottom: 16px;
}
.form-group label {
display: block;
margin-bottom: 6px;
font-size: 13px;
font-weight: 500;
color: var(--text-secondary);
}
.form-input {
width: 100%;
padding: 10px 12px;
background: var(--bg-primary);
border: 1px solid var(--border-primary);
border-radius: 6px;
color: var(--text-primary);
font-size: 14px;
outline: none;
transition: border-color 0.2s ease;
box-sizing: border-box;
}
.form-input:focus {
border-color: var(--accent-primary);
}
.content-toolbar {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
}
.upload-status {
font-size: 13px;
color: var(--text-secondary);
}
.upload-error {
color: var(--danger);
}
.upload-success {
color: var(--success, #22c55e);
}
.form-textarea {
min-height: 400px;
resize: vertical;
font-family: monospace;
line-height: 1.5;
}
.editor-actions {
display: flex;
gap: 8px;
margin-top: 20px;
}
@media (max-width: 768px) {
.welcome-section {
flex-direction: column;
gap: 16px;
padding: 20px;
align-items: flex-start;
}
.admin-table th,
.admin-table td {
padding: 8px 10px;
}
.action-cell {
flex-direction: column;
}
}
+344
View File
@@ -0,0 +1,344 @@
/* Landing Page Styles */
.landing-wrapper {
min-height: 100vh;
background: var(--bg-primary);
display: flex;
align-items: center;
justify-content: center;
padding: 2rem;
}
.landing-container {
width: 100%;
max-width: 1000px;
margin: 0 auto;
}
/* Header Section */
.landing-header {
text-align: center;
margin-bottom: 4rem;
}
.logo-area {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
}
.logo-circle {
width: 72px;
height: 72px;
background: linear-gradient(135deg, var(--accent-primary), #3d8bdb);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 0.5rem;
box-shadow: 0 4px 12px rgba(88, 166, 255, 0.3);
}
.logo-circle svg {
width: 36px;
height: 36px;
color: white;
}
.landing-header h1 {
font-size: 2.75rem;
font-weight: 700;
color: var(--text-primary);
margin: 0;
letter-spacing: -0.02em;
}
.landing-header .subtitle {
font-size: 1.125rem;
color: var(--text-secondary);
margin: 0;
font-weight: 400;
}
/* Cards Grid */
.cards-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
margin-bottom: 3rem;
}
/* Card Styles */
.landing-card {
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 16px;
padding: 0;
text-decoration: none;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
display: flex;
flex-direction: column;
position: relative;
overflow: hidden;
min-height: 280px;
}
.landing-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(135deg,
rgba(88, 166, 255, 0.05) 0%,
rgba(88, 166, 255, 0) 50%);
opacity: 0;
transition: opacity 0.3s ease;
pointer-events: none;
}
.landing-card:hover {
transform: translateY(-4px);
border-color: var(--accent-primary);
box-shadow:
0 12px 24px -10px rgba(88, 166, 255, 0.2),
0 0 0 1px var(--accent-primary);
}
.landing-card:hover::before {
opacity: 1;
}
.landing-card:active {
transform: translateY(-2px);
}
/* Card Content */
.card-content {
padding: 2rem;
flex: 1;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.card-icon-wrapper {
display: flex;
align-items: center;
justify-content: flex-start;
}
.card-icon {
width: 56px;
height: 56px;
background: linear-gradient(135deg,
rgba(88, 166, 255, 0.15),
rgba(88, 166, 255, 0.05));
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
color: var(--accent-primary);
transition: all 0.3s ease;
}
.landing-card:hover .card-icon {
transform: scale(1.05);
background: linear-gradient(135deg,
rgba(88, 166, 255, 0.2),
rgba(88, 166, 255, 0.1));
}
.card-icon svg {
width: 28px;
height: 28px;
}
.card-text {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.landing-card h2 {
font-size: 1.5rem;
font-weight: 600;
color: var(--text-primary);
margin: 0;
letter-spacing: -0.01em;
}
.card-description {
font-size: 0.9375rem;
color: var(--text-secondary);
line-height: 1.6;
margin: 0;
}
/* Card Footer */
.card-footer {
padding: 1.25rem 2rem;
border-top: 1px solid var(--border-primary);
display: flex;
align-items: center;
justify-content: space-between;
background: rgba(88, 166, 255, 0.02);
transition: background 0.3s ease;
}
.landing-card:hover .card-footer {
background: rgba(88, 166, 255, 0.05);
}
.card-link-text {
font-size: 0.875rem;
font-weight: 500;
color: var(--accent-primary);
transition: color 0.2s ease;
}
.landing-card:hover .card-link-text {
color: var(--accent-hover);
}
.card-arrow {
width: 20px;
height: 20px;
color: var(--accent-primary);
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: center;
}
.landing-card:hover .card-arrow {
transform: translateX(4px);
color: var(--accent-hover);
}
.card-arrow svg {
width: 100%;
height: 100%;
}
/* Footer */
.landing-footer {
text-align: center;
padding-top: 2rem;
border-top: 1px solid var(--border-primary);
display: flex;
align-items: center;
justify-content: center;
gap: 1rem;
}
.footer-link {
color: var(--text-secondary);
text-decoration: none;
font-size: 0.875rem;
transition: color 0.2s ease;
}
.footer-link:hover {
color: var(--accent-primary);
}
.footer-separator {
color: var(--border-primary);
font-size: 0.875rem;
}
/* Responsive Design */
@media (max-width: 768px) {
.landing-wrapper {
padding: 1.5rem;
}
.landing-header {
margin-bottom: 3rem;
}
.logo-circle {
width: 64px;
height: 64px;
}
.logo-circle svg {
width: 32px;
height: 32px;
}
.landing-header h1 {
font-size: 2.25rem;
}
.landing-header .subtitle {
font-size: 1rem;
}
.cards-grid {
grid-template-columns: 1fr;
gap: 1.25rem;
margin-bottom: 2.5rem;
}
.landing-card {
min-height: 260px;
}
.card-content {
padding: 1.75rem;
}
.card-icon {
width: 48px;
height: 48px;
}
.card-icon svg {
width: 24px;
height: 24px;
}
.landing-card h2 {
font-size: 1.375rem;
}
.card-footer {
padding: 1rem 1.75rem;
}
}
@media (max-width: 480px) {
.landing-wrapper {
padding: 1rem;
}
.landing-header {
margin-bottom: 2.5rem;
}
.logo-circle {
width: 56px;
height: 56px;
}
.logo-circle svg {
width: 28px;
height: 28px;
}
.landing-header h1 {
font-size: 1.875rem;
}
.card-content {
padding: 1.5rem;
}
.card-footer {
padding: 1rem 1.5rem;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,528 @@
/* Network Graph Page Styles */
/* Graph Manager Section */
.graph-manager-section {
margin-bottom: 32px;
}
.graph-selector-card {
max-width: 100%;
}
.graphs-list {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 20px;
}
.graph-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px;
background: var(--bg-tertiary);
border: 2px solid var(--border-primary);
border-radius: 8px;
transition: all 0.2s ease;
cursor: pointer;
}
.graph-item:hover {
border-color: var(--border-secondary);
background: var(--bg-hover);
}
.graph-item.active {
border-color: var(--accent-primary);
background: rgba(88, 166, 255, 0.05);
}
.graph-info {
flex: 1;
}
.graph-name {
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
margin-bottom: 4px;
}
.graph-stats {
display: flex;
gap: 16px;
font-size: 13px;
color: var(--text-secondary);
}
.graph-stats .stat {
display: flex;
align-items: center;
gap: 4px;
}
.graph-actions {
display: flex;
gap: 8px;
opacity: 0;
transition: opacity 0.2s ease;
}
.graph-item:hover .graph-actions {
opacity: 1;
}
.btn-icon {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 6px;
color: var(--text-secondary);
cursor: pointer;
transition: all 0.2s ease;
}
.btn-icon:hover {
background: var(--bg-hover);
border-color: var(--accent-primary);
color: var(--accent-primary);
}
.btn-icon.danger:hover {
border-color: var(--danger);
color: var(--danger);
}
/* Graph Workspace */
.graph-workspace {
display: flex;
flex-direction: column;
gap: 16px;
}
.graph-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px;
flex-wrap: wrap;
gap: 16px;
}
.toolbar-section {
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
}
.search-input {
padding: 8px 12px;
border: 1px solid var(--border-primary);
border-radius: 6px;
background: var(--bg-tertiary);
color: var(--text-primary);
font-size: 14px;
min-width: 200px;
}
.search-input:focus {
outline: none;
border-color: var(--accent-primary);
}
.filter-select {
padding: 8px 12px;
border: 1px solid var(--border-primary);
border-radius: 6px;
background: var(--bg-tertiary);
color: var(--text-primary);
font-size: 14px;
cursor: pointer;
}
.filter-select:focus {
outline: none;
border-color: var(--accent-primary);
}
/* Canvas */
.graph-canvas-container {
position: relative;
height: 600px;
padding: 0;
overflow: hidden;
}
#graph-canvas {
width: 100%;
height: 100%;
cursor: grab;
}
#graph-canvas:active {
cursor: grabbing;
}
.canvas-controls {
position: absolute;
bottom: 16px;
right: 16px;
display: flex;
flex-direction: column;
gap: 8px;
}
.canvas-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
color: var(--text-secondary);
cursor: pointer;
transition: all 0.2s ease;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.canvas-btn:hover {
background: var(--bg-hover);
border-color: var(--accent-primary);
color: var(--accent-primary);
}
.canvas-help-text {
position: absolute;
top: 16px;
left: 50%;
transform: translateX(-50%);
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
padding: 8px 16px;
font-size: 13px;
color: var(--text-secondary);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
pointer-events: none;
user-select: none;
z-index: 10;
}
/* Context Menu */
.context-menu {
position: fixed;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
z-index: 2000;
min-width: 180px;
overflow: hidden;
}
.context-menu-item {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 16px;
cursor: pointer;
color: var(--text-primary);
font-size: 14px;
transition: background 0.2s ease;
}
.context-menu-item:hover {
background: var(--bg-hover);
}
.context-menu-item svg {
flex-shrink: 0;
}
.context-menu-item.danger {
color: var(--danger);
}
.context-menu-item.danger:hover {
background: rgba(239, 68, 68, 0.1);
}
.context-menu-divider {
height: 1px;
background: var(--border-primary);
margin: 4px 0;
}
/* Modal Styles */
.modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
}
.modal-backdrop {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(4px);
}
.modal-dialog {
position: relative;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: 12px;
width: 90%;
max-width: 500px;
max-height: 90vh;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
z-index: 1001;
}
.modal-dialog-large {
max-width: 650px;
}
.modal-header {
padding: 20px 24px;
border-bottom: 1px solid var(--border-primary);
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-header h3 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: var(--text-primary);
}
.modal-close {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
background: transparent;
border: none;
color: var(--text-secondary);
font-size: 24px;
cursor: pointer;
border-radius: 6px;
transition: all 0.2s ease;
}
.modal-close:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.modal-body {
padding: 24px;
overflow-y: auto;
max-height: calc(90vh - 120px);
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
font-weight: 500;
color: var(--text-primary);
font-size: 14px;
}
.form-control {
width: 100%;
padding: 10px 12px;
border: 1px solid var(--border-primary);
border-radius: 6px;
background: var(--bg-tertiary);
color: var(--text-primary);
font-size: 14px;
font-family: inherit;
transition: border-color 0.2s ease;
}
.form-control:focus {
outline: none;
border-color: var(--accent-primary);
}
textarea.form-control {
resize: vertical;
min-height: 80px;
}
.modal-actions {
display: flex;
justify-content: flex-end;
gap: 12px;
margin-top: 24px;
}
/* Connection Management in Modal */
.connection-search-container {
position: relative;
margin-bottom: 16px;
}
.search-results-dropdown {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 6px;
margin-top: 4px;
max-height: 200px;
overflow-y: auto;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
z-index: 10;
}
.search-result-item {
padding: 10px 12px;
cursor: pointer;
transition: background 0.2s ease;
border-bottom: 1px solid var(--border-primary);
}
.search-result-item:last-child {
border-bottom: none;
}
.search-result-item:hover {
background: var(--bg-hover);
}
.search-result-label {
font-weight: 500;
color: var(--text-primary);
font-size: 14px;
}
.search-result-notes {
font-size: 12px;
color: var(--text-secondary);
margin-top: 2px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.connections-list {
margin-top: 12px;
border: 1px solid var(--border-primary);
border-radius: 6px;
overflow: hidden;
}
.connection-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 12px;
background: var(--bg-tertiary);
border-bottom: 1px solid var(--border-primary);
}
.connection-item:last-child {
border-bottom: none;
}
.connection-info {
flex: 1;
min-width: 0;
}
.connection-label {
font-weight: 500;
color: var(--text-primary);
font-size: 14px;
}
.connection-type {
font-size: 12px;
color: var(--text-secondary);
margin-top: 2px;
}
.connection-remove {
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
background: transparent;
border: 1px solid var(--border-primary);
border-radius: 4px;
color: var(--text-secondary);
cursor: pointer;
transition: all 0.2s ease;
flex-shrink: 0;
margin-left: 8px;
}
.connection-remove:hover {
background: var(--danger);
border-color: var(--danger);
color: white;
}
.connections-empty {
padding: 20px;
text-align: center;
color: var(--text-secondary);
font-size: 14px;
background: var(--bg-tertiary);
}
/* Responsive */
@media (max-width: 768px) {
.graph-toolbar {
flex-direction: column;
align-items: stretch;
}
.toolbar-section {
width: 100%;
justify-content: space-between;
}
.search-input {
flex: 1;
min-width: 0;
}
.graph-canvas-container {
height: 400px;
}
.modal-dialog {
width: 95%;
}
}
+155
View File
@@ -0,0 +1,155 @@
(function () {
let allRoles = [];
let currentPage = 1;
const pageSize = 20;
document.addEventListener('DOMContentLoaded', init);
async function init() {
await loadRoles();
await loadUsers(1);
document.getElementById('createRoleBtn').addEventListener('click', createRole);
document.getElementById('newRoleName').addEventListener('keydown', (e) => {
if (e.key === 'Enter') createRole();
});
document.addEventListener('click', (e) => {
if (!e.target.closest('.add-role-wrapper')) {
document.querySelectorAll('.add-role-dropdown.open').forEach(d => d.classList.remove('open'));
}
});
}
async function loadRoles() {
const res = await fetch('/api/admin/roles');
if (!res.ok) return;
allRoles = await res.json();
renderRolesList();
}
function renderRolesList() {
const container = document.getElementById('rolesList');
container.innerHTML = allRoles.map(r =>
`<span class="role-pill">${escapeHtml(r.name)}</span>`
).join('');
}
async function createRole() {
const input = document.getElementById('newRoleName');
const name = input.value.trim();
if (!name) return;
const res = await fetch('/api/admin/roles', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name })
});
if (!res.ok) {
const err = await res.json();
alert(err.error || 'Failed to create role');
return;
}
input.value = '';
await loadRoles();
await loadUsers(currentPage);
}
async function loadUsers(page) {
currentPage = page;
const res = await fetch(`/api/admin/users?page=${page}&pageSize=${pageSize}`);
if (!res.ok) return;
const data = await res.json();
renderUsersTable(data.users);
renderPagination(data.totalCount);
}
function renderUsersTable(users) {
const tbody = document.getElementById('usersTableBody');
tbody.innerHTML = users.map(user => {
const roleBadges = user.roles.map(r =>
`<span class="role-badge">
${escapeHtml(r.name)}
<button class="remove-role" onclick="adminRemoveRole(${user.id}, ${r.id})" title="Remove role">&times;</button>
</span>`
).join('');
const availableRoles = allRoles.filter(r => !user.roles.some(ur => ur.id === r.id));
const addDropdown = availableRoles.length > 0
? `<div class="add-role-wrapper">
<button class="add-role-btn" onclick="toggleRoleDropdown(this)">+ Add Role</button>
<div class="add-role-dropdown">
${availableRoles.map(r =>
`<button onclick="adminAddRole(${user.id}, ${r.id})">${escapeHtml(r.name)}</button>`
).join('')}
</div>
</div>`
: '';
return `<tr>
<td>${user.id}</td>
<td>${escapeHtml(user.username)}</td>
<td><div class="role-badges">${roleBadges}</div></td>
<td>${addDropdown}</td>
</tr>`;
}).join('');
}
function renderPagination(totalCount) {
const totalPages = Math.ceil(totalCount / pageSize);
const container = document.getElementById('pagination');
if (totalPages <= 1) {
container.innerHTML = '';
return;
}
container.innerHTML = `
<button onclick="adminGoToPage(${currentPage - 1})" ${currentPage <= 1 ? 'disabled' : ''}>Previous</button>
<span class="page-info">Page ${currentPage} of ${totalPages}</span>
<button onclick="adminGoToPage(${currentPage + 1})" ${currentPage >= totalPages ? 'disabled' : ''}>Next</button>
`;
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
// Global functions for inline event handlers
window.adminAddRole = async function (userId, roleId) {
const res = await fetch(`/api/admin/users/${userId}/roles/${roleId}`, { method: 'POST' });
if (!res.ok) {
const err = await res.json();
alert(err.error || 'Failed to add role');
return;
}
await loadUsers(currentPage);
};
window.adminRemoveRole = async function (userId, roleId) {
const res = await fetch(`/api/admin/users/${userId}/roles/${roleId}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json();
alert(err.error || 'Failed to remove role');
return;
}
await loadUsers(currentPage);
};
window.toggleRoleDropdown = function (btn) {
const dropdown = btn.nextElementSibling;
document.querySelectorAll('.add-role-dropdown.open').forEach(d => {
if (d !== dropdown) d.classList.remove('open');
});
dropdown.classList.toggle('open');
};
window.adminGoToPage = function (page) {
loadUsers(page);
};
})();
@@ -0,0 +1,195 @@
(function () {
let posts = [];
document.addEventListener('DOMContentLoaded', init);
async function init() {
await loadPosts();
document.getElementById('newPostBtn').addEventListener('click', showNewPostEditor);
document.getElementById('savePostBtn').addEventListener('click', savePost);
document.getElementById('cancelEditBtn').addEventListener('click', hideEditor);
const imageInput = document.getElementById('imageFileInput');
document.getElementById('uploadImageBtn').addEventListener('click', () => imageInput.click());
imageInput.addEventListener('change', uploadImage);
}
async function uploadImage() {
const input = document.getElementById('imageFileInput');
const status = document.getElementById('uploadStatus');
if (!input.files.length) return;
const file = input.files[0];
const formData = new FormData();
formData.append('file', file);
status.textContent = 'Uploading...';
status.className = 'upload-status';
try {
const res = await fetch('/api/blog/images', { method: 'POST', body: formData });
if (!res.ok) {
const err = await res.json();
status.textContent = err.error || 'Upload failed';
status.className = 'upload-status upload-error';
return;
}
const { url } = await res.json();
const textarea = document.getElementById('postContent');
const markdown = `![${file.name}](${url})`;
const pos = textarea.selectionStart;
const before = textarea.value.substring(0, pos);
const after = textarea.value.substring(pos);
const needsNewline = before.length > 0 && !before.endsWith('\n') ? '\n' : '';
textarea.value = before + needsNewline + markdown + '\n' + after;
textarea.focus();
textarea.selectionStart = textarea.selectionEnd = pos + needsNewline.length + markdown.length + 1;
status.textContent = 'Uploaded!';
status.className = 'upload-status upload-success';
setTimeout(() => { status.textContent = ''; }, 2000);
} catch {
status.textContent = 'Upload failed';
status.className = 'upload-status upload-error';
} finally {
input.value = '';
}
}
async function loadPosts() {
const res = await fetch('/api/blog/posts');
if (!res.ok) return;
posts = await res.json();
renderPostsTable();
}
function renderPostsTable() {
const tbody = document.getElementById('postsTableBody');
if (posts.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="empty-message">No posts yet. Create your first post!</td></tr>';
return;
}
tbody.innerHTML = posts.map(post => {
const tags = post.tags.map(t => `<span class="tag-pill">${escapeHtml(t)}</span>`).join('');
const date = new Date(post.publishedDate).toLocaleDateString();
return `<tr>
<td>${escapeHtml(post.title)}</td>
<td><code>${escapeHtml(post.slug)}</code></td>
<td><div class="tag-list">${tags}</div></td>
<td>${date}</td>
<td class="action-cell">
<button class="btn btn-secondary btn-sm" onclick="blogEditPost(${post.id})">Edit</button>
<button class="btn btn-danger btn-sm" onclick="blogDeletePost(${post.id})">Delete</button>
</td>
</tr>`;
}).join('');
}
function showNewPostEditor() {
document.getElementById('editorTitle').textContent = 'New Post';
document.getElementById('editPostId').value = '';
document.getElementById('postTitle').value = '';
document.getElementById('postSummary').value = '';
document.getElementById('postTags').value = '';
document.getElementById('postContent').value = '';
document.getElementById('postDate').value = new Date().toISOString().split('T')[0];
document.getElementById('postsList').style.display = 'none';
document.getElementById('postEditor').style.display = '';
}
function hideEditor() {
document.getElementById('postEditor').style.display = 'none';
document.getElementById('postsList').style.display = '';
}
async function savePost() {
const id = document.getElementById('editPostId').value;
const title = document.getElementById('postTitle').value.trim();
const summary = document.getElementById('postSummary').value.trim();
const tagsStr = document.getElementById('postTags').value.trim();
const markdownContent = document.getElementById('postContent').value;
const dateStr = document.getElementById('postDate').value;
if (!title) { alert('Title is required'); return; }
if (!markdownContent) { alert('Content is required'); return; }
const tags = tagsStr ? tagsStr.split(',').map(t => t.trim()).filter(t => t) : [];
const publishedDate = dateStr ? new Date(dateStr + 'T00:00:00Z').toISOString() : null;
const body = { title, summary, markdownContent, tags, publishedDate };
const url = id ? `/api/blog/posts/${id}` : '/api/blog/posts';
const method = id ? 'PUT' : 'POST';
const res = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!res.ok) {
const err = await res.json();
alert(err.error || 'Failed to save post');
return;
}
hideEditor();
await loadPosts();
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
window.blogEditPost = async function (id) {
const res = await fetch(`/api/blog/posts`);
if (!res.ok) return;
const allPosts = await res.json();
// Need markdown content, so fetch the admin-specific data
// The public API doesn't return markdownContent, so we fetch all and find by id
// Actually, we need to get it from the create/update response pattern
// For editing, we'll fetch via a dedicated admin endpoint or use stored data
// Since the public GET returns htmlContent but not markdownContent,
// let's make a specific request. But our API only has public routes returning htmlContent.
// We need the admin to get markdownContent too.
// Workaround: find in local posts array (which has htmlContent), but we need markdown.
// The cleanest fix is to have the GET endpoints also return markdownContent for admins,
// but for now let's add an admin-specific detail endpoint.
// Actually, looking at the API, the GET /posts/{slug} returns the public DTO.
// Let me use a different approach: store markdownContent in memory from the list.
// For now, we need to get the post with markdownContent.
// Let's fetch by id from the admin-aware endpoint.
const detailRes = await fetch(`/api/blog/posts/admin/${id}`);
if (!detailRes.ok) {
alert('Failed to load post for editing');
return;
}
const post = await detailRes.json();
document.getElementById('editorTitle').textContent = 'Edit Post';
document.getElementById('editPostId').value = post.id;
document.getElementById('postTitle').value = post.title;
document.getElementById('postSummary').value = post.summary || '';
document.getElementById('postTags').value = (post.tags || []).join(', ');
document.getElementById('postContent').value = post.markdownContent || '';
document.getElementById('postDate').value = new Date(post.publishedDate).toISOString().split('T')[0];
document.getElementById('postsList').style.display = 'none';
document.getElementById('postEditor').style.display = '';
};
window.blogDeletePost = async function (id) {
if (!confirm('Are you sure you want to delete this post?')) return;
const res = await fetch(`/api/blog/posts/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json();
alert(err.error || 'Failed to delete post');
return;
}
await loadPosts();
};
})();
@@ -0,0 +1,617 @@
(function (app) {
const { state } = app;
// --- Providers ---
app.loadBills = async function () {
if (!state.selectedPersonId) return;
const [providersRes, summaryRes] = await Promise.all([
fetch(`${app.API}/providers?personId=${state.selectedPersonId}`),
fetch(`${app.API}/bills/summary?personId=${state.selectedPersonId}`)
]);
if (providersRes.ok) {
state.currentProviders = await providersRes.json();
}
if (summaryRes.ok) {
const summary = await summaryRes.json();
app.loadBillSummary(summary);
}
await app.renderProviders();
};
app.loadBillSummary = function (summary) {
const oopEl = document.getElementById('summaryBillOop');
const chargedEl = document.getElementById('summaryBillCharged');
const dueEl = document.getElementById('summaryBillDue');
if (oopEl) oopEl.textContent = app.formatCurrency(summary.totalPaid);
if (chargedEl) chargedEl.textContent = 'of ' + app.formatCurrency(summary.totalCharged) + ' charged';
if (dueEl) {
if (summary.totalDue > 0) {
dueEl.textContent = app.formatCurrency(summary.totalDue) + ' due';
dueEl.style.display = '';
} else {
dueEl.textContent = '';
dueEl.style.display = 'none';
}
}
const container = document.getElementById('billSummarySection');
if (!container) return;
if (summary.totalCharged === 0) {
container.innerHTML = '';
return;
}
const yearRows = summary.byYear.map(y =>
`<div class="cost-agg-row">
<span>${y.year}</span>
<span>${app.formatCurrency(y.total)} <span class="cost-agg-count">(${y.count} bill${y.count !== 1 ? 's' : ''})</span></span>
</div>`
).join('');
const providerRows = summary.byProvider.map(p =>
`<div class="cost-agg-row">
<span>${app.escapeHtml(p.providerName)}</span>
<span>${app.formatCurrency(p.total)} <span class="cost-agg-count">(${p.count})</span></span>
</div>`
).join('');
container.innerHTML = `<div class="cost-aggregation" style="grid-template-columns: repeat(2, 1fr);">
<div class="cost-agg-card">
<div class="cost-agg-title">Charged by Year</div>
${yearRows || '<div class="empty-state" style="padding:8px">No data</div>'}
</div>
<div class="cost-agg-card">
<div class="cost-agg-title">Charged by Provider</div>
${providerRows || '<div class="empty-state" style="padding:8px">No data</div>'}
</div>
</div>`;
};
app.renderProviders = async function () {
const container = document.getElementById('providersList');
if (!container) return;
// Fetch unassigned bills
const unassignedRes = await fetch(`${app.API}/bills?personId=${state.selectedPersonId}`);
let unassignedBills = [];
if (unassignedRes.ok) {
const allBills = await unassignedRes.json();
unassignedBills = allBills.filter(b => !b.providerId);
}
if (state.currentProviders.length === 0 && unassignedBills.length === 0) {
container.innerHTML = '<div class="empty-state">No billing providers yet. Add a provider to start tracking bills and payments.</div>';
return;
}
let html = state.currentProviders.map(p => {
const statusClass = p.balance <= 0 ? 'paid' : p.totalPaid > 0 ? 'partial' : 'unpaid';
const statusLabel = p.balance <= 0 ? 'Paid' : p.totalPaid > 0 ? 'Partial' : 'Unpaid';
return `<div class="prescription-item provider-item" id="provider-${p.id}">
<div class="prescription-header" onclick="medDocsToggleProvider(${p.id})">
<div class="prescription-info">
<div class="prescription-name">
<span class="expand-btn" id="provider-expand-${p.id}">&#9654;</span>
${app.escapeHtml(p.name)}
<span class="bill-status ${statusClass}">${statusLabel}</span>
</div>
<div class="prescription-meta">
${app.formatCurrency(p.totalCharged)} charged &middot; ${app.formatCurrency(p.totalPaid)} paid &middot; ${app.formatCurrency(p.balance)} balance
&middot; ${p.billCount} bill${p.billCount !== 1 ? 's' : ''}
</div>
${p.notes ? `<div class="prescription-meta">${app.escapeHtml(p.notes)}</div>` : ''}
</div>
<div class="doc-actions" onclick="event.stopPropagation()">
<button class="delete-btn" onclick="medDocsDeleteProvider(${p.id})">Delete</button>
</div>
</div>
<div class="pickup-section" id="provider-details-${p.id}" style="display: none;"></div>
</div>`;
}).join('');
if (unassignedBills.length > 0) {
html += `<div class="prescription-item provider-item" id="provider-unassigned">
<div class="prescription-header" onclick="medDocsToggleUnassigned()">
<div class="prescription-info">
<div class="prescription-name">
<span class="expand-btn" id="provider-expand-unassigned">&#9654;</span>
Bills without a provider
</div>
<div class="prescription-meta">${unassignedBills.length} bill${unassignedBills.length !== 1 ? 's' : ''}</div>
</div>
</div>
<div class="pickup-section" id="provider-details-unassigned" style="display: none;"></div>
</div>`;
}
container.innerHTML = html;
};
app.toggleProvider = async function (providerId) {
const section = document.getElementById(`provider-details-${providerId}`);
const expandBtn = document.getElementById(`provider-expand-${providerId}`);
if (section.style.display === 'none') {
section.style.display = '';
expandBtn.innerHTML = '&#9660;';
await app.loadProviderDetails(providerId);
} else {
section.style.display = 'none';
expandBtn.innerHTML = '&#9654;';
}
};
app.toggleUnassigned = async function () {
const section = document.getElementById('provider-details-unassigned');
const expandBtn = document.getElementById('provider-expand-unassigned');
if (section.style.display === 'none') {
section.style.display = '';
expandBtn.innerHTML = '&#9660;';
await app.loadUnassignedBills();
} else {
section.style.display = 'none';
expandBtn.innerHTML = '&#9654;';
}
};
app.loadProviderDetails = async function (providerId) {
const section = document.getElementById(`provider-details-${providerId}`);
if (!section) return;
const [billsRes, paymentsRes] = await Promise.all([
fetch(`${app.API}/bills?personId=${state.selectedPersonId}&providerId=${providerId}`),
fetch(`${app.API}/providers/${providerId}/payments`)
]);
let bills = [];
let payments = [];
if (billsRes.ok) bills = await billsRes.json();
if (paymentsRes.ok) payments = await paymentsRes.json();
const categoryOptions = `
<option value="">Category</option>
<option value="office_visit">Office Visit</option>
<option value="lab">Lab</option>
<option value="pharmacy">Pharmacy</option>
<option value="imaging">Imaging</option>
<option value="surgery">Surgery</option>
<option value="therapy">Therapy</option>
<option value="emergency">Emergency</option>
<option value="dental">Dental</option>
<option value="vision">Vision</option>
<option value="other">Other</option>`;
const docOptions = state.currentDocuments.map(d => {
const label = d.title || d.fileName || `Document #${d.id}`;
return `<option value="${d.id}">${app.escapeHtml(label)}</option>`;
}).join('');
const billsHtml = bills.map(b => {
const meta = [];
if (b.billDate) meta.push(app.formatDate(b.billDate));
if (b.category) meta.push(app.formatLabel(b.category));
if (b.doctorName) meta.push('Dr. ' + b.doctorName);
const docNames = b.documentNames ? `<div class="bill-meta">Docs: ${app.escapeHtml(b.documentNames)}</div>` : '';
return `<div class="charge-item" style="flex-direction:column;align-items:stretch;gap:4px;" id="bill-${b.id}">
<div style="display:flex;align-items:center;justify-content:space-between;">
<div style="display:flex;align-items:center;gap:8px;flex:1;min-width:0;cursor:pointer;" onclick="medDocsToggleBillCharges(${b.id})">
<span class="expand-btn" id="bill-expand-${b.id}" style="font-size:10px;">&#9654;</span>
<span class="charge-desc">${app.escapeHtml(b.summary || 'Bill')}</span>
<span class="charge-amount">${app.formatCurrency(b.totalAmount)}</span>
</div>
<button class="delete-btn btn-sm" onclick="medDocsDeleteBill(${b.id}, ${providerId})">Delete</button>
</div>
<div class="prescription-meta" style="margin-left:18px;">${meta.map(m => app.escapeHtml(m)).join(' &middot; ')}</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 class="charges-header">Charges</div>
<div class="pickup-form">
<div class="inline-form-row">
<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" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddCharge(${b.id}, ${providerId})">Add</button>
</div>
</div>
<div class="charge-list" id="chargeList-${b.id}"></div>
<div class="section-divider"></div>
<div class="pickup-form">
<div class="inline-form-row">
<select id="linkDoc-${b.id}" class="form-input">
<option value="">Link document...</option>
${docOptions}
</select>
<button class="btn btn-secondary btn-sm" onclick="medDocsLinkDocument(${b.id}, ${providerId})">Link Doc</button>
</div>
</div>
</div>
</div>`;
}).join('');
const paymentsHtml = payments.map(p => {
const meta = [];
if (p.paymentDate) meta.push(app.formatDate(p.paymentDate));
if (p.description) meta.push(p.description);
return `<div class="pickup-item">
<div class="pickup-info">
<span class="pickup-date">${app.formatCurrency(p.amount)}</span>
${meta.length ? `<span class="pickup-meta">${meta.map(m => app.escapeHtml(m)).join(' &middot; ')}</span>` : ''}
</div>
<button class="delete-btn btn-sm" onclick="medDocsDeleteProviderPayment(${p.id}, ${providerId})">Delete</button>
</div>`;
}).join('');
section.innerHTML = `
<div class="charges-section">
<div class="charges-header">Bills</div>
<div class="pickup-form">
<div class="inline-form-row">
<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" />
<select id="newBillCategory-${providerId}" class="form-input">${categoryOptions}</select>
<input type="date" id="newBillDate-${providerId}" class="form-input" title="Bill date" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddBill(${providerId})">Add Bill</button>
</div>
</div>
<div class="bills-in-provider">${billsHtml || '<div class="empty-state" style="padding:8px;font-size:12px">No bills.</div>'}</div>
</div>
<div class="section-divider"></div>
<div class="payments-section">
<div class="charges-header">Payments</div>
<div class="pickup-form">
<div class="inline-form-row">
<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="text" id="provPayDesc-${providerId}" placeholder="Description" class="form-input" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddProviderPayment(${providerId})">Add Payment</button>
</div>
</div>
<div class="payment-list">${paymentsHtml || '<div class="empty-state" style="padding:8px;font-size:12px">No payments recorded.</div>'}</div>
</div>`;
};
app.loadUnassignedBills = async function () {
const section = document.getElementById('provider-details-unassigned');
if (!section) return;
const res = await fetch(`${app.API}/bills?personId=${state.selectedPersonId}`);
if (!res.ok) return;
const allBills = await res.json();
const bills = allBills.filter(b => !b.providerId);
const providerOptions = state.currentProviders.map(p =>
`<option value="${p.id}">${app.escapeHtml(p.name)}</option>`
).join('');
const billsHtml = bills.map(b => {
const meta = [];
if (b.billDate) meta.push(app.formatDate(b.billDate));
if (b.category) meta.push(app.formatLabel(b.category));
return `<div class="charge-item" style="flex-direction:column;align-items:stretch;gap:4px;">
<div style="display:flex;align-items:center;justify-content:space-between;">
<div>
<span class="charge-desc">${app.escapeHtml(b.summary || 'Bill')}</span>
<span class="charge-amount">${app.formatCurrency(b.totalAmount)}</span>
</div>
<div style="display:flex;gap:4px;align-items:center;">
<select id="assignProvider-${b.id}" class="form-input" style="min-width:120px;">
<option value="">Assign to provider...</option>
${providerOptions}
</select>
<button class="btn btn-secondary btn-sm" onclick="medDocsAssignBillToProvider(${b.id})">Assign</button>
<button class="delete-btn btn-sm" onclick="medDocsDeleteBill(${b.id}, 0)">Delete</button>
</div>
</div>
<div class="prescription-meta">${meta.map(m => app.escapeHtml(m)).join(' &middot; ')}</div>
</div>`;
}).join('');
section.innerHTML = `<div class="bills-in-provider">${billsHtml}</div>`;
};
// --- Actions ---
app.addProvider = async function () {
const name = document.getElementById('newProviderName').value.trim();
if (!name) { alert('Provider name is required'); return; }
const res = await fetch(`${app.API}/providers`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
personId: state.selectedPersonId,
name,
notes: document.getElementById('newProviderNotes').value.trim() || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to add provider');
return;
}
document.getElementById('newProviderName').value = '';
document.getElementById('newProviderNotes').value = '';
await app.loadBills();
};
app.deleteProvider = async function (id) {
if (!confirm('Delete this provider and unlink all its bills?')) return;
const res = await fetch(`${app.API}/providers/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await app.loadBills();
};
app.addBill = async function (providerId) {
const amountStr = document.getElementById(`newBillAmount-${providerId}`).value;
if (!amountStr || parseFloat(amountStr) <= 0) { alert('Amount must be greater than 0'); return; }
const res = await fetch(`${app.API}/bills`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
personId: state.selectedPersonId,
totalAmount: parseFloat(amountStr),
summary: document.getElementById(`newBillSummary-${providerId}`).value.trim() || null,
category: document.getElementById(`newBillCategory-${providerId}`).value || null,
billDate: document.getElementById(`newBillDate-${providerId}`).value || null,
providerId
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to add bill');
return;
}
document.getElementById(`newBillAmount-${providerId}`).value = '';
document.getElementById(`newBillSummary-${providerId}`).value = '';
document.getElementById(`newBillCategory-${providerId}`).value = '';
document.getElementById(`newBillDate-${providerId}`).value = '';
await app.refreshProvider(providerId);
};
app.deleteBill = async function (id, providerId) {
if (!confirm('Delete this bill and all its charges?')) return;
const res = await fetch(`${app.API}/bills/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
if (providerId) {
await app.refreshProvider(providerId);
} else {
await app.loadBills();
}
};
app.addProviderPayment = async function (providerId) {
const amountStr = document.getElementById(`provPayAmount-${providerId}`).value;
if (!amountStr || parseFloat(amountStr) <= 0) { alert('Amount must be greater than 0'); return; }
const res = await fetch(`${app.API}/providers/${providerId}/payments`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
amount: parseFloat(amountStr),
paymentDate: document.getElementById(`provPayDate-${providerId}`).value || null,
description: document.getElementById(`provPayDesc-${providerId}`).value.trim() || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to add payment');
return;
}
document.getElementById(`provPayAmount-${providerId}`).value = '';
document.getElementById(`provPayDate-${providerId}`).value = '';
document.getElementById(`provPayDesc-${providerId}`).value = '';
await app.refreshProvider(providerId);
};
app.deleteProviderPayment = async function (id, providerId) {
if (!confirm('Delete this payment?')) return;
const res = await fetch(`${app.API}/provider-payments/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await app.refreshProvider(providerId);
};
app.toggleBillCharges = async function (billId) {
const section = document.getElementById(`bill-charges-${billId}`);
const expandBtn = document.getElementById(`bill-expand-${billId}`);
if (section.style.display === 'none') {
section.style.display = '';
expandBtn.innerHTML = '&#9660;';
await app.loadCharges(billId);
} else {
section.style.display = 'none';
expandBtn.innerHTML = '&#9654;';
}
};
app.loadCharges = async function (billId) {
const res = await fetch(`${app.API}/bills/${billId}/charges`);
if (!res.ok) return;
const charges = await res.json();
const container = document.getElementById(`chargeList-${billId}`);
if (charges.length === 0) {
container.innerHTML = '<div class="empty-state" style="padding:8px;font-size:12px">No line items.</div>';
return;
}
container.innerHTML = charges.map(c =>
`<div class="charge-item">
<div class="charge-info">
<span class="charge-desc">${app.escapeHtml(c.description)}</span>
<span class="charge-amount">${app.formatCurrency(c.amount)}</span>
</div>
<button class="delete-btn btn-sm" onclick="medDocsDeleteCharge(${c.id}, ${billId})">Delete</button>
</div>`
).join('');
};
app.addCharge = async function (billId, providerId) {
const desc = document.getElementById(`chargeDesc-${billId}`).value.trim();
const amountStr = document.getElementById(`chargeAmount-${billId}`).value;
if (!desc) { alert('Description is required'); return; }
if (!amountStr || parseFloat(amountStr) <= 0) { alert('Amount must be greater than 0'); return; }
const res = await fetch(`${app.API}/bills/${billId}/charges`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description: desc, amount: parseFloat(amountStr) })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to add charge');
return;
}
document.getElementById(`chargeDesc-${billId}`).value = '';
document.getElementById(`chargeAmount-${billId}`).value = '';
await app.loadCharges(billId);
};
app.deleteCharge = async function (id, billId) {
if (!confirm('Delete this charge?')) return;
const res = await fetch(`${app.API}/bill-charges/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await app.loadCharges(billId);
};
app.linkDocumentToBill = async function (billId, providerId) {
const select = document.getElementById(`linkDoc-${billId}`);
const docId = select.value;
if (!docId) { alert('Select a document to link'); return; }
const res = await fetch(`${app.API}/bills/${billId}/documents`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ documentId: parseInt(docId) })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to link document');
return;
}
select.value = '';
await app.refreshProvider(providerId);
};
app.assignBillToProvider = async function (billId) {
const select = document.getElementById(`assignProvider-${billId}`);
const providerId = select.value;
if (!providerId) { alert('Select a provider'); return; }
// Get current bill details first
const getRes = await fetch(`${app.API}/bills?personId=${state.selectedPersonId}`);
if (!getRes.ok) return;
const allBills = await getRes.json();
const bill = allBills.find(b => b.id === billId);
if (!bill) return;
const res = await fetch(`${app.API}/bills/${billId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
totalAmount: bill.totalAmount,
summary: bill.summary,
category: bill.category,
billDate: bill.billDate,
doctorId: bill.doctorId,
providerId: parseInt(providerId)
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to assign bill');
return;
}
await app.loadBills();
};
app.refreshProvider = async function (providerId) {
// Refresh the summary and provider header, then reload details
const [providersRes, summaryRes] = await Promise.all([
fetch(`${app.API}/providers?personId=${state.selectedPersonId}`),
fetch(`${app.API}/bills/summary?personId=${state.selectedPersonId}`)
]);
if (providersRes.ok) {
state.currentProviders = await providersRes.json();
}
if (summaryRes.ok) {
const summary = await summaryRes.json();
app.loadBillSummary(summary);
}
// Update the provider header info
const provider = state.currentProviders.find(p => p.id === providerId);
if (provider) {
const headerInfo = document.querySelector(`#provider-${providerId} .prescription-meta`);
if (headerInfo) {
headerInfo.textContent = '';
headerInfo.innerHTML = `${app.formatCurrency(provider.totalCharged)} charged &middot; ${app.formatCurrency(provider.totalPaid)} paid &middot; ${app.formatCurrency(provider.balance)} balance &middot; ${provider.billCount} bill${provider.billCount !== 1 ? 's' : ''}`;
}
const statusBadge = document.querySelector(`#provider-${providerId} .bill-status`);
if (statusBadge) {
const statusClass = provider.balance <= 0 ? 'paid' : provider.totalPaid > 0 ? 'partial' : 'unpaid';
const statusLabel = provider.balance <= 0 ? 'Paid' : provider.totalPaid > 0 ? 'Partial' : 'Unpaid';
statusBadge.className = `bill-status ${statusClass}`;
statusBadge.textContent = statusLabel;
}
}
// Reload provider details if expanded
const section = document.getElementById(`provider-details-${providerId}`);
if (section && section.style.display !== 'none') {
await app.loadProviderDetails(providerId);
}
};
// --- Window bindings ---
window.medDocsAddProvider = () => app.addProvider();
window.medDocsDeleteProvider = (id) => app.deleteProvider(id);
window.medDocsToggleProvider = (id) => app.toggleProvider(id);
window.medDocsToggleUnassigned = () => app.toggleUnassigned();
window.medDocsAddBill = (providerId) => app.addBill(providerId);
window.medDocsDeleteBill = (id, providerId) => app.deleteBill(id, providerId);
window.medDocsToggleBillCharges = (billId) => app.toggleBillCharges(billId);
window.medDocsAddCharge = (billId, providerId) => app.addCharge(billId, providerId);
window.medDocsDeleteCharge = (id, billId) => app.deleteCharge(id, billId);
window.medDocsAddProviderPayment = (providerId) => app.addProviderPayment(providerId);
window.medDocsDeleteProviderPayment = (id, providerId) => app.deleteProviderPayment(id, providerId);
window.medDocsLinkDocument = (billId, providerId) => app.linkDocumentToBill(billId, providerId);
window.medDocsAssignBillToProvider = (billId) => app.assignBillToProvider(billId);
})(MedDocs);
@@ -0,0 +1,107 @@
(function (app) {
const { state } = app;
app.loadConditions = async function () {
if (!state.selectedPersonId) return;
const res = await fetch(`${app.API}/conditions?personId=${state.selectedPersonId}`);
if (!res.ok) return;
const conditions = await res.json();
app.renderConditions(conditions);
app.updateSummaryCount('summaryCondCount', conditions.length);
};
app.renderConditions = function (conditions) {
const container = document.getElementById('conditionsList');
if (conditions.length === 0) {
container.innerHTML = '<div class="empty-state">No conditions tracked yet.</div>';
return;
}
container.innerHTML = conditions.map(c => {
const meta = [];
if (c.diagnosedDate) meta.push('Diagnosed: ' + app.formatDate(c.diagnosedDate));
const statusBadge = c.isActive
? '<span class="badge-active">Active</span>'
: '<span class="badge-inactive">Inactive</span>';
return `<div class="condition-item" id="condition-${c.id}">
<div class="condition-info">
<div class="condition-name">${app.escapeHtml(c.name)} ${statusBadge}</div>
${meta.length ? `<div class="condition-meta">${meta.join(' &middot; ')}</div>` : ''}
${c.notes ? `<div class="condition-meta">${app.escapeHtml(c.notes)}</div>` : ''}
</div>
<div class="doc-actions">
<button onclick="medDocsToggleCondition(${c.id}, ${!c.isActive})">${c.isActive ? 'Deactivate' : 'Activate'}</button>
<button class="delete-btn" onclick="medDocsDeleteCondition(${c.id})">Delete</button>
</div>
</div>`;
}).join('');
};
app.addCondition = async function () {
const name = document.getElementById('newConditionName').value.trim();
if (!name) return;
const res = await fetch(`${app.API}/conditions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
personId: state.selectedPersonId,
name,
diagnosedDate: document.getElementById('newConditionDate').value || null,
notes: document.getElementById('newConditionNotes').value.trim() || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to add condition');
return;
}
document.getElementById('newConditionName').value = '';
document.getElementById('newConditionDate').value = '';
document.getElementById('newConditionNotes').value = '';
await app.loadConditions();
};
app.toggleConditionActive = async function (id, isActive) {
const res = await fetch(`${app.API}/conditions?personId=${state.selectedPersonId}`);
if (!res.ok) return;
const conditions = await res.json();
const condition = conditions.find(c => c.id === id);
if (!condition) return;
const updateRes = await fetch(`${app.API}/conditions/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: condition.name,
diagnosedDate: condition.diagnosedDate,
notes: condition.notes,
isActive
})
});
if (!updateRes.ok) {
const err = await updateRes.json().catch(() => ({}));
alert(err.error || 'Failed to update condition');
return;
}
await app.loadConditions();
};
app.deleteCondition = async function (id) {
if (!confirm('Delete this condition?')) return;
const res = await fetch(`${app.API}/conditions/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await app.loadConditions();
};
window.medDocsAddCondition = () => app.addCondition();
window.medDocsDeleteCondition = (id) => app.deleteCondition(id);
window.medDocsToggleCondition = (id, isActive) => app.toggleConditionActive(id, isActive);
})(MedDocs);
@@ -0,0 +1,295 @@
(function (app) {
const { state } = app;
app.loadDoctors = async function () {
const res = await fetch(`${app.API}/doctors`);
if (!res.ok) return;
state.doctors = await res.json();
app.renderDoctors();
app.populateDoctorDropdowns();
app.updateSummaryCount('summaryDrCount', state.doctors.length);
};
state.expandedVisitPrepId = null;
app.renderDoctors = function () {
const container = document.getElementById('doctorsList');
if (state.doctors.length === 0) {
container.innerHTML = '<div class="empty-state">No doctors added yet.</div>';
return;
}
container.innerHTML = state.doctors.map(doc => {
const details = [doc.specialty, doc.phone, doc.address].filter(Boolean);
const visitPrepBtn = state.selectedPersonId
? `<button onclick="medDocsToggleVisitPrep(${doc.id})">Visit Prep</button>`
: '';
return `<div class="doctor-card-wrapper" id="doctor-wrapper-${doc.id}">
<div class="doctor-card" id="doctor-${doc.id}">
<div class="doctor-info">
<div class="doctor-name">${app.escapeHtml(doc.name)}</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>` : ''}
</div>
<div class="doc-actions">
${visitPrepBtn}
<button onclick="medDocsEditDoctor(${doc.id})">Edit</button>
<button class="delete-btn" onclick="medDocsDeleteDoctor(${doc.id})">Delete</button>
</div>
</div>
<div class="visit-prep-panel" id="visit-prep-${doc.id}" style="display:none"></div>
</div>`;
}).join('');
};
app.populateDoctorDropdowns = function () {
const opts = '<option value="">Doctor (optional)</option>' +
state.doctors.map(d => `<option value="${d.id}">${app.escapeHtml(d.name)}</option>`).join('');
const rxSelect = document.getElementById('newRxDoctor');
if (rxSelect) {
const rxVal = rxSelect.value;
rxSelect.innerHTML = opts;
rxSelect.value = rxVal;
}
const billSelect = document.getElementById('newBillDoctor');
if (billSelect) {
const billVal = billSelect.value;
billSelect.innerHTML = opts;
billSelect.value = billVal;
}
};
app.addDoctor = async function () {
const name = document.getElementById('newDoctorName').value.trim();
if (!name) return;
const res = await fetch(`${app.API}/doctors`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
specialty: document.getElementById('newDoctorSpecialty').value.trim() || null,
phone: document.getElementById('newDoctorPhone').value.trim() || null,
address: document.getElementById('newDoctorAddress').value.trim() || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to add doctor');
return;
}
document.getElementById('newDoctorName').value = '';
document.getElementById('newDoctorSpecialty').value = '';
document.getElementById('newDoctorPhone').value = '';
document.getElementById('newDoctorAddress').value = '';
await app.loadDoctors();
};
app.deleteDoctor = async function (id) {
if (!confirm('Delete this doctor?')) return;
const res = await fetch(`${app.API}/doctors/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await app.loadDoctors();
};
app.editDoctor = function (id) {
const doc = state.doctors.find(d => d.id === id);
if (!doc) return;
const card = document.getElementById(`doctor-${id}`);
if (!card) return;
card.innerHTML = `<div class="inline-edit-form">
<div class="inline-form-row">
<input type="text" id="editDoctorName-${id}" value="${app.escapeAttr(doc.name)}" class="form-input" placeholder="Name *" />
<input type="text" id="editDoctorSpecialty-${id}" value="${app.escapeAttr(doc.specialty || '')}" class="form-input" placeholder="Specialty" />
<input type="text" id="editDoctorPhone-${id}" value="${app.escapeAttr(doc.phone || '')}" class="form-input" placeholder="Phone" />
<input type="text" id="editDoctorAddress-${id}" value="${app.escapeAttr(doc.address || '')}" class="form-input" placeholder="Address" />
<button class="btn btn-primary btn-sm" onclick="medDocsSaveDoctor(${id})">Save</button>
<button class="btn btn-secondary btn-sm" onclick="medDocsCancelEditDoctor()">Cancel</button>
</div>
</div>`;
};
app.saveDoctor = async function (id) {
const name = document.getElementById(`editDoctorName-${id}`).value.trim();
if (!name) return;
const res = await fetch(`${app.API}/doctors/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
specialty: document.getElementById(`editDoctorSpecialty-${id}`).value.trim() || null,
phone: document.getElementById(`editDoctorPhone-${id}`).value.trim() || null,
address: document.getElementById(`editDoctorAddress-${id}`).value.trim() || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to update doctor');
return;
}
await app.loadDoctors();
};
// --- Visit Prep ---
app.toggleVisitPrep = function (doctorId) {
const panel = document.getElementById(`visit-prep-${doctorId}`);
if (!panel) return;
if (state.expandedVisitPrepId === doctorId) {
panel.style.display = 'none';
state.expandedVisitPrepId = null;
return;
}
// Collapse previously expanded
if (state.expandedVisitPrepId !== null) {
const prev = document.getElementById(`visit-prep-${state.expandedVisitPrepId}`);
if (prev) prev.style.display = 'none';
}
state.expandedVisitPrepId = doctorId;
panel.style.display = '';
panel.innerHTML = '<div style="padding:16px;color:var(--text-secondary)">Loading visit prep data...</div>';
app.loadVisitPrep(doctorId);
};
app.loadVisitPrep = async function (doctorId) {
const panel = document.getElementById(`visit-prep-${doctorId}`);
if (!panel) return;
try {
const res = await fetch(`${app.API}/visit-prep?personId=${state.selectedPersonId}&doctorId=${doctorId}`);
if (!res.ok) {
panel.innerHTML = '<div style="padding:16px;color:var(--danger)">Failed to load visit prep data.</div>';
return;
}
const data = await res.json();
app.renderVisitPrep(doctorId, data);
} catch {
panel.innerHTML = '<div style="padding:16px;color:var(--danger)">Error loading visit prep.</div>';
}
};
app.renderVisitPrep = function (doctorId, data) {
const panel = document.getElementById(`visit-prep-${doctorId}`);
if (!panel) return;
let html = '<div class="visit-prep-content">';
// Recent Documents
html += '<div class="visit-prep-section"><div class="visit-prep-section-title">Recent Documents</div>';
if (data.recentDocuments.length > 0) {
html += data.recentDocuments.map(d => {
const label = d.title || d.fileName || 'Untitled';
const date = d.documentDate ? app.formatDate(d.documentDate) : '';
const cls = d.classification ? ` <span class="doc-classification">${app.escapeHtml(app.formatClassification(d.classification))}</span>` : '';
return `<div class="visit-prep-item">${app.escapeHtml(label)}${cls}${date ? ' <span class="visit-prep-date">' + date + '</span>' : ''}</div>`;
}).join('');
} else {
html += '<div class="visit-prep-item" style="color:var(--text-secondary)">No documents for this doctor</div>';
}
html += '</div>';
// Active Conditions
html += '<div class="visit-prep-section"><div class="visit-prep-section-title">Active Conditions</div>';
if (data.activeConditions.length > 0) {
html += '<div class="visit-prep-badges">' + data.activeConditions.map(c =>
`<span class="badge-active">${app.escapeHtml(c.name)}</span>`
).join(' ') + '</div>';
} else {
html += '<div class="visit-prep-item" style="color:var(--text-secondary)">No active conditions</div>';
}
html += '</div>';
// Current Medications
html += '<div class="visit-prep-section"><div class="visit-prep-section-title">Current Medications</div>';
if (data.activePrescriptions.length > 0) {
html += data.activePrescriptions.map(rx => {
const details = [rx.dosage, rx.frequency].filter(Boolean).join(', ');
return `<div class="visit-prep-item">${app.escapeHtml(rx.medicationName)}${details ? ' <span class="visit-prep-date">' + app.escapeHtml(details) + '</span>' : ''}</div>`;
}).join('');
} else {
html += '<div class="visit-prep-item" style="color:var(--text-secondary)">No active prescriptions</div>';
}
html += '</div>';
// Recent Bills
html += '<div class="visit-prep-section"><div class="visit-prep-section-title">Recent Bills (6 months)</div>';
if (data.recentBills.length > 0) {
html += data.recentBills.map(b => {
const date = b.billDate ? app.formatDate(b.billDate) : '';
return `<div class="visit-prep-item">${app.formatCurrency(b.totalAmount)}${b.summary ? ' - ' + app.escapeHtml(b.summary) : ''}${date ? ' <span class="visit-prep-date">' + date + '</span>' : ''}</div>`;
}).join('');
} else {
html += '<div class="visit-prep-item" style="color:var(--text-secondary)">No recent bills</div>';
}
html += '</div>';
// AI Summary
html += '<div class="visit-prep-section">';
html += `<button class="btn btn-primary btn-sm" id="aiSummaryBtn-${doctorId}" onclick="medDocsGenerateVisitSummary(${doctorId})">Generate AI Summary</button>`;
html += `<div class="ai-summary-card" id="aiSummary-${doctorId}" style="display:none"></div>`;
html += '</div>';
html += '</div>';
panel.innerHTML = html;
};
app.generateVisitSummary = async function (doctorId) {
const btn = document.getElementById(`aiSummaryBtn-${doctorId}`);
const card = document.getElementById(`aiSummary-${doctorId}`);
if (!btn || !card) return;
btn.disabled = true;
btn.textContent = 'Generating...';
card.style.display = '';
card.innerHTML = '<div class="ai-summary-loading">Generating AI summary...</div>';
try {
const res = await fetch(`${app.API}/visit-prep/summary`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ personId: state.selectedPersonId, doctorId })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
card.innerHTML = '<div style="color:var(--danger)">' + app.escapeHtml(err.error || 'Failed to generate summary') + '</div>';
btn.disabled = false;
btn.textContent = 'Generate AI Summary';
return;
}
const data = await res.json();
card.innerHTML = '<div class="ai-summary-text">' + app.escapeHtml(data.summary || 'No summary generated.').replace(/\n/g, '<br>') + '</div>';
btn.textContent = 'Regenerate Summary';
btn.disabled = false;
} catch {
card.innerHTML = '<div style="color:var(--danger)">Error generating summary.</div>';
btn.disabled = false;
btn.textContent = 'Generate AI Summary';
}
};
window.medDocsAddDoctor = () => app.addDoctor();
window.medDocsDeleteDoctor = (id) => app.deleteDoctor(id);
window.medDocsEditDoctor = (id) => app.editDoctor(id);
window.medDocsSaveDoctor = (id) => app.saveDoctor(id);
window.medDocsCancelEditDoctor = () => app.renderDoctors();
window.medDocsToggleVisitPrep = (id) => app.toggleVisitPrep(id);
window.medDocsGenerateVisitSummary = (id) => app.generateVisitSummary(id);
})(MedDocs);
@@ -0,0 +1,682 @@
(function (app) {
const { state } = app;
// --- Filters ---
app.buildFilterQuery = function () {
const params = new URLSearchParams();
params.set('personId', state.selectedPersonId);
const search = document.getElementById('filterSearch').value.trim();
if (search) params.set('search', search);
const classification = document.getElementById('filterClassification').value;
if (classification) params.set('classification', classification);
const docType = document.getElementById('filterDocType').value;
if (docType) params.set('documentType', docType);
const doctor = document.getElementById('filterDoctor').value;
if (doctor) params.set('doctorId', doctor);
const tag = document.getElementById('filterTag').value;
if (tag) params.set('tagId', tag);
const condition = document.getElementById('filterCondition').value;
if (condition) params.set('conditionId', condition);
const fromDate = document.getElementById('filterFromDate').value;
if (fromDate) params.set('fromDate', fromDate);
const toDate = document.getElementById('filterToDate').value;
if (toDate) params.set('toDate', toDate);
return params.toString();
};
app.clearFilters = function (reload = true) {
document.getElementById('filterSearch').value = '';
document.getElementById('filterClassification').value = '';
document.getElementById('filterDocType').value = '';
document.getElementById('filterDoctor').value = '';
document.getElementById('filterTag').value = '';
document.getElementById('filterCondition').value = '';
document.getElementById('filterFromDate').value = '';
document.getElementById('filterToDate').value = '';
if (reload) app.loadDocuments();
};
app.loadFilterTags = async function () {
if (!state.selectedPersonId) return;
const res = await fetch(`${app.API}/tags?personId=${state.selectedPersonId}`);
if (!res.ok) return;
const tags = await res.json();
const select = document.getElementById('filterTag');
const currentVal = select.value;
select.innerHTML = '<option value="">All Tags</option>' +
tags.map(t => `<option value="${t.id}">${app.escapeHtml(t.name)}</option>`).join('');
select.value = currentVal;
};
app.loadFilterConditions = async function () {
if (!state.selectedPersonId) return;
const res = await fetch(`${app.API}/conditions?personId=${state.selectedPersonId}`);
if (!res.ok) return;
const conditions = await res.json();
const select = document.getElementById('filterCondition');
const currentVal = select.value;
select.innerHTML = '<option value="">All Conditions</option>' +
conditions.map(c => `<option value="${c.id}">${app.escapeHtml(c.name)}</option>`).join('');
select.value = currentVal;
};
app.populateFilterDoctorDropdown = function () {
const select = document.getElementById('filterDoctor');
const currentVal = select.value;
select.innerHTML = '<option value="">All Doctors</option>' +
state.doctors.map(d => `<option value="${d.id}">${app.escapeHtml(d.name)}</option>`).join('');
select.value = currentVal;
};
// --- Viewer ---
app.getViewerType = function (doc) {
if (doc.documentType === 'note') return 'text';
const mime = (doc.mimeType || '').toLowerCase();
if (mime.startsWith('image/')) return 'image';
if (mime.startsWith('audio/')) return 'audio';
if (mime.startsWith('text/')) return 'text';
if (mime === 'application/pdf') return 'pdf';
return null;
};
// --- Documents ---
app.loadDocuments = async function () {
if (!state.selectedPersonId) return;
const query = app.buildFilterQuery();
const res = await fetch(`${app.API}/documents/search?${query}`);
if (!res.ok) return;
const docs = await res.json();
state.currentDocuments = docs;
app.renderDocuments(docs);
app.updateSummaryCount('summaryDocCount', docs.length);
};
app.renderDocuments = function (docs) {
const container = document.getElementById('documentsList');
const countEl = document.getElementById('docCount');
countEl.textContent = `${docs.length} document${docs.length !== 1 ? 's' : ''}`;
const unprocessedCount = docs.filter(d => !d.aiProcessed).length;
const processAllBtn = document.getElementById('processAllBtn');
if (processAllBtn) {
processAllBtn.style.display = unprocessedCount > 0 ? '' : 'none';
processAllBtn.textContent = `Process All with AI (${unprocessedCount})`;
}
const batchModeBtn = document.getElementById('batchModeBtn');
if (batchModeBtn) {
batchModeBtn.style.display = docs.length > 0 ? '' : 'none';
}
if (docs.length === 0) {
container.innerHTML = '<div class="empty-state">No documents yet. Upload a file or create a note above.</div>';
return;
}
container.innerHTML = docs.map(doc => {
const icon = app.getDocIcon(doc);
const displayTitle = doc.title || doc.fileName || 'Untitled';
const meta = [];
if (doc.documentDate) {
meta.push(app.formatDate(doc.documentDate));
}
if (doc.documentType === 'file' && doc.fileSize) {
meta.push(app.formatSize(doc.fileSize));
}
if (doc.documentType === 'note') {
meta.push('Note');
}
const classificationBadge = doc.classification
? `<span class="doc-classification">${app.escapeHtml(app.formatClassification(doc.classification))}</span>`
: '';
const aiStatusBadge = app.getAiStatusBadge(doc);
const viewerType = app.getViewerType(doc);
const viewBtn = viewerType
? `<button onclick="event.stopPropagation(); medDocsView(${doc.id})">View</button>`
: '';
const downloadBtn = doc.documentType === 'file'
? `<button onclick="event.stopPropagation(); medDocsDownload(${doc.id}, '${app.escapeAttr(doc.fileName || 'download')}')">Download</button>`
: '';
const processBtn = !doc.aiProcessed
? `<button class="ai-process-btn" onclick="event.stopPropagation(); medDocsProcess(${doc.id}, this)">Process AI</button>`
: '';
const batchCheckbox = state.batchSelectMode
? `<input type="checkbox" class="batch-checkbox" id="batch-cb-${doc.id}" ${state.selectedDocIds.has(doc.id) ? 'checked' : ''} onclick="event.stopPropagation(); medDocsToggleDetail(${doc.id})">`
: '';
const batchClass = state.batchSelectMode && state.selectedDocIds.has(doc.id) ? ' batch-selected' : '';
return `<div class="doc-item-wrapper" id="doc-wrapper-${doc.id}">
<div class="doc-item${batchClass}" onclick="medDocsToggleDetail(${doc.id})" style="cursor:pointer">
${batchCheckbox}
<div class="doc-type-icon">${icon}</div>
<div class="doc-info">
<div class="doc-title">
<span class="expand-btn" id="doc-expand-${doc.id}">&#9654;</span>
${app.escapeHtml(displayTitle)}
</div>
<div class="doc-meta">
<span>${meta.join(' &middot; ')}</span>
${classificationBadge}
${aiStatusBadge}
</div>
${doc.description && doc.documentType === 'note' ? `<div class="doc-meta" style="margin-top:4px">${app.escapeHtml(app.truncate(doc.description, 150))}</div>` : ''}
</div>
<div class="doc-actions" onclick="event.stopPropagation()">
${processBtn}
${viewBtn}
${downloadBtn}
<button class="delete-btn" onclick="medDocsDelete(${doc.id})">Delete</button>
</div>
</div>
<div class="doc-detail-panel" id="doc-detail-${doc.id}" style="display:none"></div>
</div>`;
}).join('');
};
// --- File Upload ---
app.handleFileSelect = function (e) {
if (e.target.files.length > 0) {
app.uploadFiles(e.target.files);
}
};
app.uploadFiles = async function (files) {
const queue = document.getElementById('uploadQueue');
for (const file of files) {
const item = document.createElement('div');
item.className = 'upload-item';
item.innerHTML = `
<div class="file-info">
<span class="file-name">${app.escapeHtml(file.name)}</span>
<span class="file-size">${app.formatSize(file.size)}</span>
</div>
<span class="upload-status uploading">Uploading...</span>
`;
queue.appendChild(item);
const statusEl = item.querySelector('.upload-status');
try {
const formData = new FormData();
formData.append('file', file);
formData.append('personId', state.selectedPersonId);
const title = document.getElementById('fileTitle').value.trim();
const description = document.getElementById('fileDescription').value.trim();
const date = document.getElementById('fileDate').value;
const classification = document.getElementById('fileClassification').value;
if (title) formData.append('title', title);
if (description) formData.append('description', description);
if (date) formData.append('documentDate', date);
if (classification) formData.append('classification', classification);
const res = await fetch(`${app.API}/documents/upload`, {
method: 'POST',
body: formData
});
if (res.ok) {
statusEl.textContent = 'Done';
statusEl.className = 'upload-status done';
} else {
const err = await res.json().catch(() => ({}));
statusEl.textContent = err.error || 'Failed';
statusEl.className = 'upload-status error';
}
} catch {
statusEl.textContent = 'Error';
statusEl.className = 'upload-status error';
}
}
document.getElementById('fileTitle').value = '';
document.getElementById('fileDescription').value = '';
document.getElementById('fileDate').value = '';
document.getElementById('fileClassification').value = '';
document.getElementById('fileInput').value = '';
await app.loadDocuments();
};
// --- Notes ---
app.saveNote = async function () {
const title = document.getElementById('noteTitle').value.trim();
const description = document.getElementById('noteDescription').value.trim();
const date = document.getElementById('noteDate').value || null;
const classification = document.getElementById('noteClassification').value || null;
if (!title) {
alert('Title is required');
return;
}
const res = await fetch(`${app.API}/documents/note`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
personId: state.selectedPersonId,
title,
description,
documentDate: date,
classification
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to save note');
return;
}
document.getElementById('noteTitle').value = '';
document.getElementById('noteDescription').value = '';
document.getElementById('noteDate').value = '';
document.getElementById('noteClassification').value = '';
await app.loadDocuments();
};
// --- Globals ---
window.medDocsDownload = function (id, fileName) {
const a = document.createElement('a');
a.href = `${app.API}/documents/${id}/download`;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
// --- Document Viewer ---
let currentBlobUrl = null;
window.medDocsView = async function (id) {
const doc = state.currentDocuments.find(d => d.id === id);
if (!doc) return;
const viewerType = app.getViewerType(doc);
if (!viewerType) return;
const overlay = document.getElementById('docViewerOverlay');
const title = document.getElementById('docViewerTitle');
const body = document.getElementById('docViewerBody');
title.textContent = doc.title || doc.fileName || 'Untitled';
body.innerHTML = '<div class="doc-viewer-loading">Loading...</div>';
overlay.style.display = '';
document.body.style.overflow = 'hidden';
if (doc.documentType === 'note') {
body.innerHTML = `<pre class="doc-viewer-text">${app.escapeHtml(doc.description || '')}</pre>`;
return;
}
try {
const res = await fetch(`${app.API}/documents/${id}/download`);
if (!res.ok) {
body.innerHTML = '<div class="doc-viewer-error">Failed to load document.</div>';
return;
}
const blob = await res.blob();
currentBlobUrl = URL.createObjectURL(blob);
if (viewerType === 'image') {
body.innerHTML = `<img class="doc-viewer-image" src="${currentBlobUrl}" alt="${app.escapeAttr(doc.title || doc.fileName || '')}" />`;
} else if (viewerType === 'audio') {
body.innerHTML = `<audio class="doc-viewer-audio" controls src="${currentBlobUrl}"></audio>`;
} else if (viewerType === 'pdf') {
body.innerHTML = `<iframe class="doc-viewer-pdf" src="${currentBlobUrl}"></iframe>`;
} else if (viewerType === 'text') {
const text = await blob.text();
body.innerHTML = `<pre class="doc-viewer-text">${app.escapeHtml(text)}</pre>`;
URL.revokeObjectURL(currentBlobUrl);
currentBlobUrl = null;
}
} catch {
body.innerHTML = '<div class="doc-viewer-error">Error loading document.</div>';
}
};
window.medDocsCloseViewer = function (event) {
if (event && event.target !== event.currentTarget) return;
const overlay = document.getElementById('docViewerOverlay');
overlay.style.display = 'none';
document.getElementById('docViewerBody').innerHTML = '';
document.body.style.overflow = '';
if (currentBlobUrl) {
URL.revokeObjectURL(currentBlobUrl);
currentBlobUrl = null;
}
};
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {
const overlay = document.getElementById('docViewerOverlay');
if (overlay && overlay.style.display !== 'none') {
window.medDocsCloseViewer();
}
}
});
window.medDocsDelete = async function (id) {
if (!confirm('Delete this document? This cannot be undone.')) return;
const res = await fetch(`${app.API}/documents/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await app.loadDocuments();
};
window.medDocsProcess = async function (id, btn) {
if (btn) {
btn.disabled = true;
btn.textContent = 'Processing...';
btn.classList.add('processing');
}
try {
const res = await fetch(`${app.API}/documents/${id}/process`, { method: 'POST' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to start processing');
if (btn) {
btn.disabled = false;
btn.textContent = 'Process AI';
btn.classList.remove('processing');
}
return;
}
if (btn) {
btn.textContent = 'Queued';
}
setTimeout(() => app.loadDocuments(), 5000);
} catch {
if (btn) {
btn.disabled = false;
btn.textContent = 'Process AI';
btn.classList.remove('processing');
}
}
};
window.medDocsProcessAll = async function () {
const btn = document.getElementById('processAllBtn');
if (btn) {
btn.disabled = true;
btn.textContent = 'Processing...';
}
try {
const res = await fetch(`${app.API}/documents/process-all`, { method: 'POST' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to start processing');
if (btn) {
btn.disabled = false;
}
await app.loadDocuments();
return;
}
const data = await res.json();
if (btn) {
btn.textContent = `Queued ${data.queued} docs`;
}
setTimeout(() => app.loadDocuments(), 8000);
} catch {
if (btn) {
btn.disabled = false;
}
await app.loadDocuments();
}
};
// --- Document Detail Panel ---
app.toggleDetail = function (docId) {
const panel = document.getElementById(`doc-detail-${docId}`);
const arrow = document.getElementById(`doc-expand-${docId}`);
const wrapper = document.getElementById(`doc-wrapper-${docId}`);
if (!panel) return;
if (panel.style.display === 'none') {
panel.style.display = '';
if (arrow) arrow.innerHTML = '&#9660;';
if (wrapper) wrapper.classList.add('expanded');
app.loadDocumentDetail(docId);
} else {
panel.style.display = 'none';
if (arrow) arrow.innerHTML = '&#9654;';
if (wrapper) wrapper.classList.remove('expanded');
}
};
app.loadDocumentDetail = async function (docId) {
const panel = document.getElementById(`doc-detail-${docId}`);
if (!panel) return;
panel.innerHTML = '<div style="padding:16px;color:var(--text-secondary)">Loading...</div>';
try {
const [docRes, tagsRes] = await Promise.all([
fetch(`${app.API}/documents/${docId}`),
fetch(`${app.API}/documents/${docId}/tags`)
]);
if (!docRes.ok) {
panel.innerHTML = '<div style="padding:16px;color:var(--danger)">Failed to load document details.</div>';
return;
}
const doc = await docRes.json();
const tags = tagsRes.ok ? await tagsRes.json() : [];
const classOptions = ['', 'receipt', 'lab_result', 'prescription', 'imaging', 'dr_note', 'insurance', 'referral', 'discharge', 'recording', 'other']
.map(c => `<option value="${c}" ${doc.classification === c ? 'selected' : ''}>${c ? app.formatClassification(c) : 'None'}</option>`).join('');
const doctorOpts = '<option value="">None</option>' +
state.doctors.map(d => `<option value="${d.id}" ${d.id === doc.doctorId ? 'selected' : ''}>${app.escapeHtml(d.name)}</option>`).join('');
const docDate = doc.documentDate ? doc.documentDate.split('T')[0] : '';
const tagBadges = tags.length > 0
? tags.map(t => `<span class="doc-classification" style="background:var(--bg-secondary);color:var(--text-primary);border:1px solid var(--border-primary)">${app.escapeHtml(t.name)}</span>`).join(' ')
: '<span style="color:var(--text-secondary)">No tags</span>';
const readonlyInfo = [];
if (doc.fileName) readonlyInfo.push(`<span>File: ${app.escapeHtml(doc.fileName)}</span>`);
if (doc.fileSize) readonlyInfo.push(`<span>Size: ${app.formatSize(doc.fileSize)}</span>`);
if (doc.createdAt) readonlyInfo.push(`<span>Created: ${app.formatDate(doc.createdAt)}</span>`);
if (doc.aiProcessedAt) readonlyInfo.push(`<span>AI Processed: ${app.formatDate(doc.aiProcessedAt)}</span>`);
panel.innerHTML = `<div class="doc-detail-content">
<div class="doc-detail-row-inline">
<div>
<div class="doc-detail-label">Title</div>
<input type="text" id="detailTitle-${docId}" value="${app.escapeAttr(doc.title || '')}" class="form-input" style="width:100%" placeholder="Title" />
</div>
<div>
<div class="doc-detail-label">Date</div>
<input type="date" id="detailDate-${docId}" value="${docDate}" class="form-input" style="width:100%" />
</div>
<div>
<div class="doc-detail-label">Classification</div>
<select id="detailClass-${docId}" class="form-input" style="width:100%">${classOptions}</select>
</div>
</div>
<div class="doc-detail-row-inline">
<div>
<div class="doc-detail-label">Doctor</div>
<select id="detailDoctor-${docId}" class="form-input" style="width:100%">${doctorOpts}</select>
</div>
<div style="grid-column: span 2">
<div class="doc-detail-label">Description</div>
<textarea id="detailDesc-${docId}" class="form-input" style="width:100%;min-height:40px" placeholder="Description">${app.escapeHtml(doc.description || '')}</textarea>
</div>
</div>
<div style="margin-top:8px">
<button class="btn btn-primary btn-sm" onclick="medDocsSaveDocument(${docId})">Save Changes</button>
</div>
<div class="doc-detail-readonly">
<div class="doc-detail-label">Tags</div>
<div style="margin-bottom:8px">${tagBadges}</div>
<div class="doc-meta">${readonlyInfo.join(' &middot; ')}</div>
</div>
${doc.extractedText ? `<details class="doc-extracted-text-wrapper">
<summary style="cursor:pointer;font-size:12px;color:var(--text-secondary);margin-top:8px">Extracted Text</summary>
<pre class="doc-extracted-text">${app.escapeHtml(doc.extractedText)}</pre>
</details>` : ''}
</div>`;
} catch {
panel.innerHTML = '<div style="padding:16px;color:var(--danger)">Error loading details.</div>';
}
};
app.saveDocument = async function (docId) {
const title = document.getElementById(`detailTitle-${docId}`).value.trim() || null;
const description = document.getElementById(`detailDesc-${docId}`).value.trim() || null;
const documentDate = document.getElementById(`detailDate-${docId}`).value || null;
const classification = document.getElementById(`detailClass-${docId}`).value || null;
const doctorVal = document.getElementById(`detailDoctor-${docId}`).value;
const doctorId = doctorVal ? parseInt(doctorVal) : null;
const res = await fetch(`${app.API}/documents/${docId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, description, documentDate, classification, doctorId })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to update document');
return;
}
await app.loadDocuments();
// Re-expand the detail panel
setTimeout(() => {
const panel = document.getElementById(`doc-detail-${docId}`);
if (panel) {
panel.style.display = '';
const arrow = document.getElementById(`doc-expand-${docId}`);
if (arrow) arrow.innerHTML = '&#9660;';
const wrapper = document.getElementById(`doc-wrapper-${docId}`);
if (wrapper) wrapper.classList.add('expanded');
app.loadDocumentDetail(docId);
}
}, 50);
};
// --- Batch Select Mode ---
state.batchSelectMode = false;
state.selectedDocIds = new Set();
app.toggleBatchMode = function () {
state.batchSelectMode = !state.batchSelectMode;
state.selectedDocIds.clear();
document.getElementById('batchToolbar').style.display = state.batchSelectMode ? '' : 'none';
document.getElementById('selectAllCheckbox').checked = false;
app.updateBatchCount();
app.renderDocuments(state.currentDocuments);
};
app.toggleBatchSelect = function (docId) {
if (state.selectedDocIds.has(docId)) {
state.selectedDocIds.delete(docId);
} else {
state.selectedDocIds.add(docId);
}
app.updateBatchCount();
const wrapper = document.getElementById(`doc-wrapper-${docId}`);
if (wrapper) {
const item = wrapper.querySelector('.doc-item');
if (item) item.classList.toggle('batch-selected', state.selectedDocIds.has(docId));
}
const cb = document.getElementById(`batch-cb-${docId}`);
if (cb) cb.checked = state.selectedDocIds.has(docId);
};
app.toggleSelectAll = function (checked) {
state.selectedDocIds.clear();
if (checked) {
state.currentDocuments.forEach(d => state.selectedDocIds.add(d.id));
}
app.updateBatchCount();
app.renderDocuments(state.currentDocuments);
};
app.updateBatchCount = function () {
const el = document.getElementById('batchCount');
if (el) el.textContent = state.selectedDocIds.size + ' selected';
};
app.processBatch = async function () {
if (state.selectedDocIds.size === 0) {
alert('No documents selected');
return;
}
const res = await fetch(`${app.API}/documents/process-batch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ documentIds: [...state.selectedDocIds] })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to start batch processing');
return;
}
const data = await res.json();
alert(`Queued ${data.queued} document(s) for reprocessing`);
app.toggleBatchMode();
setTimeout(() => app.loadDocuments(), 5000);
};
window.medDocsToggleDetail = (id) => {
if (state.batchSelectMode) {
app.toggleBatchSelect(id);
return;
}
app.toggleDetail(id);
};
window.medDocsSaveDocument = (id) => app.saveDocument(id);
window.medDocsClearFilters = () => app.clearFilters();
window.medDocsToggleBatchMode = () => app.toggleBatchMode();
window.medDocsToggleSelectAll = (checked) => app.toggleSelectAll(checked);
window.medDocsProcessBatch = () => app.processBatch();
})(MedDocs);
@@ -0,0 +1,56 @@
(function (app) {
document.addEventListener('DOMContentLoaded', async function () {
await app.loadPeople();
await app.loadDoctors();
// Add person
document.getElementById('addPersonBtn').addEventListener('click', () => app.addPerson());
document.getElementById('newPersonName').addEventListener('keydown', (e) => {
if (e.key === 'Enter') app.addPerson();
});
// Upload sub-tabs (file vs note)
document.querySelectorAll('.upload-sub-tabs .tab-btn').forEach(btn => {
btn.addEventListener('click', () => app.switchUploadTab(btn.dataset.tab));
});
// File upload
document.getElementById('browseBtn').addEventListener('click', () => {
document.getElementById('fileInput').click();
});
document.getElementById('fileInput').addEventListener('change', app.handleFileSelect);
// Drag and drop
const dropZone = document.getElementById('dropZone');
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('drag-over');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('drag-over');
if (e.dataTransfer.files.length > 0) {
app.uploadFiles(e.dataTransfer.files);
}
});
// Save note
document.getElementById('saveNoteBtn').addEventListener('click', () => app.saveNote());
// Filter bar event listeners
document.getElementById('filterSearch').addEventListener('input', () => {
clearTimeout(app.state.searchDebounceTimer);
app.state.searchDebounceTimer = setTimeout(() => app.loadDocuments(), 300);
});
['filterClassification', 'filterDocType', 'filterDoctor', 'filterTag', 'filterCondition', 'filterFromDate', 'filterToDate'].forEach(id => {
document.getElementById(id).addEventListener('change', () => app.loadDocuments());
});
// Default state
app.switchMainTab('doctors');
app.updateTabStates();
});
})(MedDocs);
@@ -0,0 +1,65 @@
(function (app) {
const { state } = app;
app.loadPeople = async function () {
const res = await fetch(`${app.API}/people`);
if (!res.ok) return;
state.people = await res.json();
app.renderPeople();
};
app.renderPeople = function () {
const container = document.getElementById('peopleList');
container.innerHTML = state.people.map(p =>
`<button class="person-pill ${p.id === state.selectedPersonId ? 'active' : ''}" onclick="medDocsSelectPerson(${p.id})">${app.escapeHtml(p.name)}</button>`
).join('');
};
app.addPerson = async function () {
const input = document.getElementById('newPersonName');
const name = input.value.trim();
if (!name) return;
const res = await fetch(`${app.API}/people`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name })
});
if (!res.ok) {
const err = await res.json();
alert(err.error || 'Failed to add person');
return;
}
input.value = '';
const person = await res.json();
await app.loadPeople();
app.selectPerson(person.id);
};
app.selectPerson = function (personId) {
state.selectedPersonId = personId;
app.renderPeople();
document.getElementById('summaryCards').style.display = '';
document.getElementById('filterBar').style.display = '';
app.updateTabStates();
app.clearFilters(false);
app.loadFilterTags();
app.loadFilterConditions();
app.populateFilterDoctorDropdown();
app.loadDocuments();
app.loadConditions();
app.loadPrescriptions();
app.loadBills();
app.loadTimeline();
app.switchMainTab('documents');
};
window.medDocsSelectPerson = (id) => app.selectPerson(id);
})(MedDocs);
@@ -0,0 +1,265 @@
(function (app) {
const { state } = app;
app.loadPrescriptions = async function () {
if (!state.selectedPersonId) return;
const res = await fetch(`${app.API}/prescriptions?personId=${state.selectedPersonId}`);
if (!res.ok) return;
const prescriptions = await res.json();
state.currentPrescriptions = prescriptions;
app.renderPrescriptions(prescriptions);
app.updateSummaryCount('summaryRxCount', prescriptions.length);
};
app.renderPrescriptions = function (prescriptions) {
const container = document.getElementById('prescriptionsList');
if (prescriptions.length === 0) {
container.innerHTML = '<div class="empty-state">No prescriptions tracked yet.</div>';
return;
}
container.innerHTML = prescriptions.map(rx => {
const meta = [];
if (rx.rxNumber) meta.push('RX# ' + rx.rxNumber);
if (rx.dosage) meta.push(rx.dosage);
if (rx.frequency) meta.push(rx.frequency);
if (rx.doctorName) meta.push('Dr. ' + rx.doctorName);
if (rx.startDate) meta.push('Started: ' + app.formatDate(rx.startDate));
const lastPickup = rx.lastPickupDate ? app.formatDate(rx.lastPickupDate) : 'None';
const statusBadge = rx.isActive
? '<span class="badge-active">Active</span>'
: '<span class="badge-inactive">Inactive</span>';
return `<div class="prescription-item" id="rx-${rx.id}">
<div class="prescription-header" onclick="medDocsTogglePickups(${rx.id})">
<div class="prescription-info">
<div class="prescription-name">
<span class="expand-btn" id="expand-${rx.id}">&#9654;</span>
${app.escapeHtml(rx.medicationName)} ${statusBadge}
</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>
<div class="doc-actions" onclick="event.stopPropagation()">
<button onclick="medDocsEditPrescription(${rx.id})">Edit</button>
<button class="delete-btn" onclick="medDocsDeletePrescription(${rx.id})">Delete</button>
</div>
</div>
<div class="pickup-section" id="pickups-${rx.id}" style="display: none;">
<div class="pickup-form">
<div class="inline-form-row">
<input type="date" id="pickupDate-${rx.id}" class="form-input" title="Pickup date" />
<input type="text" id="pickupQty-${rx.id}" placeholder="Quantity" class="form-input" />
<input type="text" id="pickupPharmacy-${rx.id}" placeholder="Pharmacy" class="form-input" />
<input type="number" id="pickupCost-${rx.id}" placeholder="Cost" class="form-input" step="0.01" />
<button class="btn btn-primary btn-sm" onclick="medDocsAddPickup(${rx.id})">Log Pickup</button>
</div>
</div>
<div class="pickup-list" id="pickupList-${rx.id}"></div>
</div>
</div>`;
}).join('');
};
app.addPrescription = async function () {
const medication = document.getElementById('newRxMedication').value.trim();
if (!medication) return;
const doctorId = document.getElementById('newRxDoctor').value;
const res = await fetch(`${app.API}/prescriptions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
personId: state.selectedPersonId,
medicationName: medication,
dosage: document.getElementById('newRxDosage').value.trim() || null,
frequency: document.getElementById('newRxFrequency').value.trim() || null,
doctorId: doctorId ? parseInt(doctorId) : null,
startDate: document.getElementById('newRxStartDate').value || null,
rxNumber: document.getElementById('newRxNumber').value.trim() || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to add prescription');
return;
}
document.getElementById('newRxMedication').value = '';
document.getElementById('newRxNumber').value = '';
document.getElementById('newRxDosage').value = '';
document.getElementById('newRxFrequency').value = '';
document.getElementById('newRxDoctor').value = '';
document.getElementById('newRxStartDate').value = '';
await app.loadPrescriptions();
};
app.deletePrescription = async function (id) {
if (!confirm('Delete this prescription and all its pickup history?')) return;
const res = await fetch(`${app.API}/prescriptions/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await app.loadPrescriptions();
};
app.togglePickups = async function (rxId) {
const section = document.getElementById(`pickups-${rxId}`);
const expandBtn = document.getElementById(`expand-${rxId}`);
if (section.style.display === 'none') {
section.style.display = '';
expandBtn.innerHTML = '&#9660;';
await app.loadPickups(rxId);
} else {
section.style.display = 'none';
expandBtn.innerHTML = '&#9654;';
}
};
app.loadPickups = async function (rxId) {
const res = await fetch(`${app.API}/prescriptions/${rxId}/pickups`);
if (!res.ok) return;
const pickups = await res.json();
const container = document.getElementById(`pickupList-${rxId}`);
if (pickups.length === 0) {
container.innerHTML = '<div class="empty-state" style="padding:12px">No pickups logged.</div>';
return;
}
container.innerHTML = pickups.map(p => {
const meta = [];
if (p.quantity) meta.push(p.quantity);
if (p.pharmacy) meta.push(p.pharmacy);
if (p.cost != null) meta.push('$' + parseFloat(p.cost).toFixed(2));
return `<div class="pickup-item">
<div class="pickup-info">
<span class="pickup-date">${app.formatDate(p.pickupDate)}</span>
${meta.length ? `<span class="pickup-meta">${meta.map(m => app.escapeHtml(m)).join(' &middot; ')}</span>` : ''}
${p.notes ? `<span class="pickup-meta">${app.escapeHtml(p.notes)}</span>` : ''}
</div>
<button class="delete-btn btn-sm" onclick="medDocsDeletePickup(${p.id}, ${rxId})">Delete</button>
</div>`;
}).join('');
};
app.addPickup = async function (rxId) {
const date = document.getElementById(`pickupDate-${rxId}`).value;
if (!date) {
alert('Pickup date is required');
return;
}
const costStr = document.getElementById(`pickupCost-${rxId}`).value;
const res = await fetch(`${app.API}/prescriptions/${rxId}/pickups`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pickupDate: date,
quantity: document.getElementById(`pickupQty-${rxId}`).value.trim() || null,
pharmacy: document.getElementById(`pickupPharmacy-${rxId}`).value.trim() || null,
cost: costStr ? parseFloat(costStr) : null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to log pickup');
return;
}
document.getElementById(`pickupDate-${rxId}`).value = '';
document.getElementById(`pickupQty-${rxId}`).value = '';
document.getElementById(`pickupPharmacy-${rxId}`).value = '';
document.getElementById(`pickupCost-${rxId}`).value = '';
await app.loadPickups(rxId);
await app.loadPrescriptions();
};
app.deletePickup = async function (id, rxId) {
if (!confirm('Delete this pickup record?')) return;
const res = await fetch(`${app.API}/pickups/${id}`, { method: 'DELETE' });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to delete');
return;
}
await app.loadPickups(rxId);
await app.loadPrescriptions();
};
app.editPrescription = function (id) {
const rx = state.currentPrescriptions.find(r => r.id === id);
if (!rx) return;
const el = document.getElementById(`rx-${id}`);
if (!el) return;
const doctorOpts = '<option value="">Doctor (optional)</option>' +
state.doctors.map(d => `<option value="${d.id}" ${d.id === rx.doctorId ? 'selected' : ''}>${app.escapeHtml(d.name)}</option>`).join('');
const startDate = rx.startDate ? rx.startDate.split('T')[0] : '';
const endDate = rx.endDate ? rx.endDate.split('T')[0] : '';
el.innerHTML = `<div class="inline-edit-form" style="padding: 14px 18px;">
<div class="inline-form-row">
<input type="text" id="editRxMed-${id}" value="${app.escapeAttr(rx.medicationName)}" class="form-input" placeholder="Medication *" />
<input type="text" id="editRxNumber-${id}" value="${app.escapeAttr(rx.rxNumber || '')}" class="form-input" placeholder="RX#" />
<input type="text" id="editRxDosage-${id}" value="${app.escapeAttr(rx.dosage || '')}" class="form-input" placeholder="Dosage" />
<input type="text" id="editRxFrequency-${id}" value="${app.escapeAttr(rx.frequency || '')}" class="form-input" placeholder="Frequency" />
<select id="editRxDoctor-${id}" class="form-input">${doctorOpts}</select>
</div>
<div class="inline-form-row" style="margin-top: 8px;">
<input type="date" id="editRxStart-${id}" value="${startDate}" class="form-input" title="Start date" />
<input type="date" id="editRxEnd-${id}" value="${endDate}" class="form-input" title="End date" />
<input type="text" id="editRxNotes-${id}" value="${app.escapeAttr(rx.notes || '')}" class="form-input" placeholder="Notes" />
<label style="display:flex;align-items:center;gap:4px;font-size:13px;color:var(--text-secondary);">
<input type="checkbox" id="editRxActive-${id}" ${rx.isActive ? 'checked' : ''} /> Active
</label>
<button class="btn btn-primary btn-sm" onclick="medDocsSavePrescription(${id})">Save</button>
<button class="btn btn-secondary btn-sm" onclick="medDocsCancelEditPrescription()">Cancel</button>
</div>
</div>`;
};
app.savePrescription = async function (id) {
const medication = document.getElementById(`editRxMed-${id}`).value.trim();
if (!medication) return;
const doctorVal = document.getElementById(`editRxDoctor-${id}`).value;
const res = await fetch(`${app.API}/prescriptions/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
medicationName: medication,
dosage: document.getElementById(`editRxDosage-${id}`).value.trim() || null,
frequency: document.getElementById(`editRxFrequency-${id}`).value.trim() || null,
doctorId: doctorVal ? parseInt(doctorVal) : null,
startDate: document.getElementById(`editRxStart-${id}`).value || null,
endDate: document.getElementById(`editRxEnd-${id}`).value || null,
notes: document.getElementById(`editRxNotes-${id}`).value.trim() || null,
isActive: document.getElementById(`editRxActive-${id}`).checked,
rxNumber: document.getElementById(`editRxNumber-${id}`).value.trim() || null
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Failed to update prescription');
return;
}
await app.loadPrescriptions();
};
window.medDocsAddPrescription = () => app.addPrescription();
window.medDocsDeletePrescription = (id) => app.deletePrescription(id);
window.medDocsTogglePickups = (rxId) => app.togglePickups(rxId);
window.medDocsAddPickup = (rxId) => app.addPickup(rxId);
window.medDocsDeletePickup = (id, rxId) => app.deletePickup(id, rxId);
window.medDocsEditPrescription = (id) => app.editPrescription(id);
window.medDocsSavePrescription = (id) => app.savePrescription(id);
window.medDocsCancelEditPrescription = () => app.loadPrescriptions();
})(MedDocs);
@@ -0,0 +1,77 @@
window.MedDocs = {
API: '/api/medical-docs',
state: {
people: [],
doctors: [],
currentDocuments: [],
currentPrescriptions: [],
selectedPersonId: null,
activeTab: 'doctors',
searchDebounceTimer: null,
currentProviders: []
},
escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
},
escapeAttr(str) {
return str.replace(/'/g, "\\'").replace(/"/g, '\\"');
},
formatDate(dateStr) {
const d = new Date(dateStr);
return d.toLocaleDateString();
},
formatSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
},
formatCurrency(amount) {
return '$' + parseFloat(amount).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
},
formatLabel(str) {
return str.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
},
formatClassification(c) {
return c.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
},
truncate(str, max) {
return str.length > max ? str.substring(0, max) + '...' : str;
},
getDocIcon(doc) {
if (doc.documentType === 'note') {
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line></svg>';
}
const mime = (doc.mimeType || '').toLowerCase();
if (mime.startsWith('image/')) {
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>';
}
if (mime === 'application/pdf') {
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>';
}
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polyline points="13 2 13 9 20 9"></polyline></svg>';
},
getAiStatusBadge(doc) {
if (doc.aiProcessed) {
return '<span class="ai-badge ai-done" title="AI processed">AI</span>';
}
return '<span class="ai-badge ai-pending" title="Not yet processed">No AI</span>';
},
updateSummaryCount(id, count) {
const el = document.getElementById(id);
if (el) el.textContent = count;
}
};

Some files were not shown because too many files have changed in this diff Show More