mirror of
https://github.com/AmanTahiliani/FHIR-Sandbox.git
synced 2026-08-08 04:06:16 -04:00
Patient Match and CGM Demo
This commit is contained in:
125
app/handlers/cgm.go
Normal file
125
app/handlers/cgm.go
Normal file
@@ -0,0 +1,125 @@
|
||||
// Package handlers — cgm.go implements the CGM preview proxy endpoint.
|
||||
//
|
||||
// GET /api/cgm-preview?patient_id=<fhir_id>
|
||||
//
|
||||
// This endpoint proxies requests to the Rimidi Provider CGM API to display
|
||||
// CGM data for a patient that has been matched between HRS and Rimidi.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/AmanTahiliani/FHIR-Sandbox/app/middleware"
|
||||
)
|
||||
|
||||
// proxyTimeout is the HTTP client timeout for the outbound CGM API call.
|
||||
const cgmProxyTimeout = 15 * time.Second
|
||||
|
||||
// HandleCGMPreview handles GET /api/cgm-preview requests.
|
||||
// It requires a valid session and looks up the confirmed match for the patient,
|
||||
// then proxies the request to the Rimidi Provider CGM API.
|
||||
func (h *Handler) HandleCGMPreview(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
sess := middleware.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// ── Resolve patient from query param or session ────────────────
|
||||
patientFHIRID := r.URL.Query().Get("patient_id")
|
||||
if patientFHIRID == "" {
|
||||
patientFHIRID = sess.PatientFHIRID
|
||||
}
|
||||
|
||||
if patientFHIRID == "" {
|
||||
http.Error(w, `{"error":"no patient in context"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// ── Look up confirmed match for this patient ───────────────────
|
||||
match, err := h.store.GetPatientMatchByFHIRID(patientFHIRID, sess.EHRURL)
|
||||
if err != nil {
|
||||
log.Printf("handlers: cgm-preview GetPatientMatchByFHIRID(%s, %s): %v", patientFHIRID, sess.EHRURL, err)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"error": "No confirmed patient match found. Please confirm a match first.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// ── Build Rimidi CGM API URL ───────────────────────────────────
|
||||
rimidiURL := h.cfg.RimidiCGMAPIURL
|
||||
rimidiKey := h.cfg.RimidiInternalAPIKey
|
||||
|
||||
if rimidiURL == "" || rimidiKey == "" {
|
||||
log.Printf("handlers: cgm-preview Rimidi CGM API not configured")
|
||||
http.Error(w, `{"error":"CGM API not configured"}`, http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
// Construct the full URL: {base_url}/{patient_pk}/cgm-preview/
|
||||
cgmURL := rimidiURL + "/" + match.RimidiPatientPK + "/cgm-preview/"
|
||||
|
||||
// ── Call Rimidi CGM API ────────────────────────────────────────
|
||||
client := &http.Client{Timeout: cgmProxyTimeout}
|
||||
req, err := http.NewRequest(http.MethodGet, cgmURL, nil)
|
||||
if err != nil {
|
||||
log.Printf("handlers: cgm-preview new request: %v", err)
|
||||
http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
req.Header.Set("X-Api-Key", rimidiKey)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("handlers: cgm-preview remote call failed: %v", err)
|
||||
http.Error(w, `{"error":"could not reach Rimidi CGM API"}`, http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Printf("handlers: cgm-preview read response: %v", err)
|
||||
http.Error(w, `{"error":"failed to read remote response"}`, http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyLen := len(respBody)
|
||||
if bodyLen > 500 {
|
||||
bodyLen = 500
|
||||
}
|
||||
log.Printf("handlers: cgm-preview remote returned %d: %s", resp.StatusCode, string(respBody[:bodyLen]))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
w.Write(respBody)
|
||||
return
|
||||
}
|
||||
|
||||
// ── Parse and forward the response ──────────────────────────────
|
||||
var cgmData map[string]interface{}
|
||||
if err := json.Unmarshal(respBody, &cgmData); err != nil {
|
||||
log.Printf("handlers: cgm-preview unmarshal response: %v", err)
|
||||
http.Error(w, `{"error":"invalid response from Rimidi CGM API"}`, http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
|
||||
// Reports now come with presigned S3 URLs, no transformation needed
|
||||
|
||||
// Forward the response as-is
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(cgmData)
|
||||
}
|
||||
101
app/handlers/cgm_report_proxy.go
Normal file
101
app/handlers/cgm_report_proxy.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const cgmReportProxyTimeout = 30 * time.Second
|
||||
|
||||
// HandleCGMReportProxy proxies CGM report requests (PDFs and images) from Rimidi Provider.
|
||||
// This allows the browser to access reports without needing to handle API keys directly.
|
||||
func (h *Handler) HandleCGMReportProxy(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// Get the target URL from query parameter
|
||||
targetURL := r.URL.Query().Get("url")
|
||||
if targetURL == "" {
|
||||
http.Error(w, "Missing 'url' query parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate that the URL is from the configured Rimidi CGM API
|
||||
rimidiBaseURL := h.cfg.RimidiCGMAPIURL
|
||||
if rimidiBaseURL == "" {
|
||||
http.Error(w, "CGM API not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
// Extract base URL (remove /{patient_pk}/cgm-preview/)
|
||||
baseURL := rimidiBaseURL
|
||||
if len(baseURL) > 20 {
|
||||
// Remove trailing path components to get base URL
|
||||
lastSlash := -1
|
||||
for i := len(baseURL) - 1; i >= 0; i-- {
|
||||
if baseURL[i] == '/' {
|
||||
lastSlash = i
|
||||
if i > 0 && baseURL[i-1] != '/' {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if lastSlash > 0 {
|
||||
baseURL = baseURL[:lastSlash]
|
||||
}
|
||||
}
|
||||
// Remove /privateadmin/patients if present
|
||||
if len(baseURL) > 20 && baseURL[len(baseURL)-20:] == "/privateadmin/patients" {
|
||||
baseURL = baseURL[:len(baseURL)-20]
|
||||
}
|
||||
// Add /cshub if not present
|
||||
if len(baseURL) < 7 || baseURL[len(baseURL)-7:] != "/cshub" {
|
||||
baseURL = baseURL + "/cshub"
|
||||
}
|
||||
|
||||
// Check if target URL starts with the expected base
|
||||
expectedPrefix := baseURL + "/api/cgm-report-proxy/"
|
||||
if len(targetURL) < len(expectedPrefix) || targetURL[:len(expectedPrefix)] != expectedPrefix {
|
||||
log.Printf("handlers: cgm-report-proxy invalid URL prefix: %s (expected: %s)", targetURL, expectedPrefix)
|
||||
http.Error(w, "Invalid URL", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Call Rimidi Provider API with internal API key
|
||||
client := &http.Client{Timeout: cgmReportProxyTimeout}
|
||||
req, err := http.NewRequest(http.MethodGet, targetURL, nil)
|
||||
if err != nil {
|
||||
log.Printf("handlers: cgm-report-proxy new request: %v", err)
|
||||
http.Error(w, "Internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
req.Header.Set("X-Api-Key", h.cfg.RimidiInternalAPIKey)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("handlers: cgm-report-proxy remote call failed: %v", err)
|
||||
http.Error(w, "Could not fetch report", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Copy response headers
|
||||
for key, values := range resp.Header {
|
||||
for _, value := range values {
|
||||
w.Header().Add(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
// Set status code
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
|
||||
// Copy response body
|
||||
if _, err := io.Copy(w, resp.Body); err != nil {
|
||||
log.Printf("handlers: cgm-report-proxy copy response: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/AmanTahiliani/FHIR-Sandbox/app/fhir"
|
||||
@@ -151,6 +154,16 @@ func (h *Handler) HandleDashboard(w http.ResponseWriter, r *http.Request) {
|
||||
summary := buildClinicalSummary(observations, conditions, medications)
|
||||
synced := r.URL.Query().Get("synced") == "true"
|
||||
|
||||
// ── Check for confirmed Rimidi patient match ────────────────────
|
||||
var rimidiMatch *models.PatientMatch
|
||||
var rimidiPatientKey string
|
||||
match, err := h.store.GetPatientMatchByFHIRID(patientID, ehrURL)
|
||||
if err == nil {
|
||||
rimidiMatch = match
|
||||
// Fetch the signed patient key from Rimidi
|
||||
rimidiPatientKey = h.fetchRimidiPatientKey(match.RimidiPatientPK)
|
||||
}
|
||||
|
||||
h.render(w, "dashboard.html", dashboardData{
|
||||
Patient: patientUser,
|
||||
Practitioner: practitionerUser,
|
||||
@@ -167,6 +180,8 @@ func (h *Handler) HandleDashboard(w http.ResponseWriter, r *http.Request) {
|
||||
LatestSync: latestSync,
|
||||
Session: sess,
|
||||
Synced: synced,
|
||||
RimidiMatch: rimidiMatch,
|
||||
RimidiPatientKey: rimidiPatientKey,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -187,6 +202,75 @@ type dashboardData struct {
|
||||
LatestSync *models.PatientSync
|
||||
Session *models.Session
|
||||
Synced bool
|
||||
RimidiMatch *models.PatientMatch
|
||||
RimidiPatientKey string
|
||||
}
|
||||
|
||||
// fetchRimidiPatientKey fetches the signed patient key from Rimidi Provider API.
|
||||
// Returns empty string if the fetch fails (non-blocking).
|
||||
func (h *Handler) fetchRimidiPatientKey(patientPK string) string {
|
||||
if patientPK == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Build the Rimidi patient key API URL
|
||||
// PatientMatchRemoteURL is like "http://localhost:2222/cshub/api/patient-match/"
|
||||
rimidiBaseURL := h.cfg.PatientMatchRemoteURL
|
||||
if rimidiBaseURL == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Replace "/api/patient-match/" with "/api/patient-key/{pk}/"
|
||||
keyURL := strings.Replace(rimidiBaseURL, "/api/patient-match/", "/api/patient-key/"+patientPK+"/", 1)
|
||||
log.Printf("handlers: fetchRimidiPatientKey constructing URL: %s (from base: %s)", keyURL, rimidiBaseURL)
|
||||
|
||||
// Call Rimidi API to get signed patient key
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
req, err := http.NewRequest(http.MethodGet, keyURL, nil)
|
||||
if err != nil {
|
||||
log.Printf("handlers: fetchRimidiPatientKey new request: %v", err)
|
||||
return ""
|
||||
}
|
||||
// Use internal API key (same as CGM API) for consistency
|
||||
req.Header.Set("X-Api-Key", h.cfg.RimidiInternalAPIKey)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("handlers: fetchRimidiPatientKey remote call failed: %v", err)
|
||||
return ""
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Printf("handlers: fetchRimidiPatientKey read response: %v", err)
|
||||
return ""
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyPreview := ""
|
||||
if len(body) > 0 {
|
||||
if len(body) > 200 {
|
||||
bodyPreview = string(body[:200])
|
||||
} else {
|
||||
bodyPreview = string(body)
|
||||
}
|
||||
}
|
||||
log.Printf("handlers: fetchRimidiPatientKey remote returned %d for URL %s, body: %s", resp.StatusCode, keyURL, bodyPreview)
|
||||
return ""
|
||||
}
|
||||
|
||||
var keyData map[string]interface{}
|
||||
if err := json.Unmarshal(body, &keyData); err != nil {
|
||||
log.Printf("handlers: fetchRimidiPatientKey unmarshal response: %v", err)
|
||||
return ""
|
||||
}
|
||||
|
||||
if patientKey, ok := keyData["patient_key"].(string); ok {
|
||||
return patientKey
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// handleUnauthorized redirects to root for dashboard requests.
|
||||
|
||||
@@ -13,8 +13,11 @@ import (
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/AmanTahiliani/FHIR-Sandbox/app/middleware"
|
||||
"github.com/AmanTahiliani/FHIR-Sandbox/app/models"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// patientMatchRequest is the inbound JSON shape for a match query.
|
||||
@@ -203,3 +206,144 @@ func (h *Handler) HandlePatientMatch(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
// confirmMatchRequest is the inbound JSON shape for a match confirmation.
|
||||
type confirmMatchRequest struct {
|
||||
RimidiPatientRef string `json:"rimidi_patient_ref"`
|
||||
RimidiPatientPK string `json:"rimidi_patient_pk"`
|
||||
}
|
||||
|
||||
// confirmMatchResponse is the response shape for match confirmation.
|
||||
type confirmMatchResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message"`
|
||||
Match *models.PatientMatch `json:"match,omitempty"`
|
||||
}
|
||||
|
||||
// HandleConfirmMatch processes POST /api/patient-match/confirm requests.
|
||||
// It requires a valid session and stores the confirmed match in the database.
|
||||
func (h *Handler) HandleConfirmMatch(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
sess := middleware.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// ── Resolve patient from the session or query param ─────────────
|
||||
patientFHIRID := sess.PatientFHIRID
|
||||
if override := r.URL.Query().Get("patient_id"); override != "" {
|
||||
patientFHIRID = override
|
||||
}
|
||||
|
||||
if patientFHIRID == "" {
|
||||
http.Error(w, `{"error":"no patient in context"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// ── Decode request body ─────────────────────────────────────────
|
||||
var req confirmMatchRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, `{"error":"invalid JSON body"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// ── Validate required fields ────────────────────────────────────
|
||||
if strings.TrimSpace(req.RimidiPatientRef) == "" {
|
||||
http.Error(w, `{"error":"rimidi_patient_ref is required"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.RimidiPatientPK) == "" {
|
||||
http.Error(w, `{"error":"rimidi_patient_pk is required"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// ── Get Rimidi app ID from config ──────────────────────────────
|
||||
rimidiAppID := h.cfg.RimidiAppID
|
||||
if rimidiAppID == "" {
|
||||
rimidiAppID = "demo-app" // Default for demo
|
||||
}
|
||||
|
||||
// ── Create patient match record ─────────────────────────────────
|
||||
match := &models.PatientMatch{
|
||||
ID: uuid.NewString(),
|
||||
HRSPatientFHIRID: patientFHIRID,
|
||||
HRSEHRURL: sess.EHRURL,
|
||||
RimidiAppID: rimidiAppID,
|
||||
RimidiPatientPK: req.RimidiPatientPK,
|
||||
RimidiPatientRef: req.RimidiPatientRef,
|
||||
ConfirmedAt: time.Now().UTC(),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
UpdatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
// ── Store match in database ────────────────────────────────────
|
||||
if err := h.store.UpsertPatientMatch(match); err != nil {
|
||||
log.Printf("handlers: confirm-match UpsertPatientMatch failed: %v", err)
|
||||
http.Error(w, `{"error":"failed to store match"}`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("handlers: confirmed patient match: hrs_patient=%s rimidi_pk=%s", patientFHIRID, req.RimidiPatientPK)
|
||||
|
||||
// ── Write success response ─────────────────────────────────────
|
||||
resp := confirmMatchResponse{
|
||||
Success: true,
|
||||
Message: "Patient match confirmed successfully",
|
||||
Match: match,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
// HandleUnlinkMatch processes DELETE /api/patient-match/unlink requests.
|
||||
// It requires a valid session and removes the confirmed match for the patient.
|
||||
func (h *Handler) HandleUnlinkMatch(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete && r.Method != http.MethodPost {
|
||||
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
sess := middleware.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// ── Resolve patient from query param or session ────────────────
|
||||
patientFHIRID := r.URL.Query().Get("patient_id")
|
||||
if patientFHIRID == "" {
|
||||
patientFHIRID = sess.PatientFHIRID
|
||||
}
|
||||
|
||||
if patientFHIRID == "" {
|
||||
http.Error(w, `{"error":"no patient in context"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// ── Delete the match ──────────────────────────────────────────
|
||||
err := h.store.DeletePatientMatch(patientFHIRID, sess.EHRURL)
|
||||
if err != nil {
|
||||
log.Printf("handlers: unlink-match DeletePatientMatch(%s, %s): %v", patientFHIRID, sess.EHRURL, err)
|
||||
http.Error(w, `{"error":"failed to unlink patient"}`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("handlers: unlinked patient match: hrs_patient=%s", patientFHIRID)
|
||||
|
||||
// ── Write success response ─────────────────────────────────────
|
||||
resp := map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "Patient unlinked successfully",
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user