working on Hub for retreiving data from Health Providers.

This commit is contained in:
Jason Kulatunga 2022-08-28 10:51:58 -07:00
parent 93f04802fe
commit 7a9fdfd1b9
12 changed files with 296 additions and 16 deletions

View File

@ -79,19 +79,19 @@ func (sr *sqliteRepository) Close() error {
}
func (sr *sqliteRepository) GetCurrentUser() models.User {
return models.User{Model: &gorm.Model{ID: 1}}
return models.User{Model: gorm.Model{ID: 1}}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DeviceSummary
// ProviderCredentials
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (sr *sqliteRepository) CreateProviderCredentials(ctx context.Context, providerCreds *models.ProviderCredential) error {
providerCreds.UserId = sr.GetCurrentUser().ID
providerCreds.UserID = sr.GetCurrentUser().ID
if sr.gormClient.WithContext(ctx).Model(&providerCreds).
Where(models.ProviderCredential{
UserId: providerCreds.UserId,
UserID: providerCreds.UserID,
ProviderId: providerCreds.ProviderId,
PatientId: providerCreds.PatientId}).Updates(&providerCreds).RowsAffected == 0 {
return sr.gormClient.WithContext(ctx).Create(&providerCreds).Error
@ -103,7 +103,7 @@ func (sr *sqliteRepository) GetProviderCredentials(ctx context.Context) ([]model
var providerCredentials []models.ProviderCredential
results := sr.gormClient.WithContext(ctx).
Where(models.ProviderCredential{UserId: sr.GetCurrentUser().ID}).
Where(models.ProviderCredential{UserID: sr.GetCurrentUser().ID}).
Find(&providerCredentials)
return providerCredentials, results.Error

12
backend/pkg/hub/README.md Normal file
View File

@ -0,0 +1,12 @@
# Hub
The Fasten Hub is a semi stand-alone application that can retrieve data from various Medical Providers, transform it, and
store it in the database. This code will eventually be moved into its own repository.
# Types
There are multiple protocols used by the Medical Provider industry to transfer patient data, the following mechanisms are the
ones that Fasten supports
### FHIR

View File

@ -0,0 +1,28 @@
package hub
import (
"errors"
"fmt"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/cigna"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
"github.com/sirupsen/logrus"
"net/http"
)
func NewClient(providerId string, appConfig config.Interface, globalLogger logrus.FieldLogger, credentials models.ProviderCredential, testHttpClient ...*http.Client) (base.Client, error) {
var providerClient base.Client
var err error
switch providerId {
case "anthem":
providerClient, err = cigna.NewClient(appConfig, globalLogger, credentials, testHttpClient...)
case "cigna":
providerClient, err = cigna.NewClient(appConfig, globalLogger, credentials, testHttpClient...)
default:
return nil, errors.New(fmt.Sprintf("Unknown Provider Type: %s", providerId))
}
return providerClient, err
}

View File

@ -0,0 +1,102 @@
package base
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
gofhir "github.com/fastenhealth/gofhir-client/models"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"net/http"
"strings"
"time"
)
type FhirBaseClient struct {
AppConfig config.Interface
Logger logrus.FieldLogger
OauthClient *http.Client
Credential models.ProviderCredential
}
func NewBaseClient(appConfig config.Interface, globalLogger logrus.FieldLogger, credentials models.ProviderCredential, testHttpClient ...*http.Client) (FhirBaseClient, error) {
var httpClient *http.Client
if len(testHttpClient) == 0 {
httpClient = oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(
&oauth2.Token{
TokenType: "Bearer",
RefreshToken: credentials.RefreshToken,
AccessToken: credentials.AccessToken,
}))
} else {
//Testing mode.
httpClient = testHttpClient[0]
}
httpClient.Timeout = 10 * time.Second
return FhirBaseClient{
AppConfig: appConfig,
Logger: globalLogger,
OauthClient: httpClient,
Credential: credentials,
}, nil
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FHIR
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c *FhirBaseClient) GetPatientEverything(patientId string) (*gofhir.Bundle, error) {
// https://www.hl7.org/fhir/patient-operation-everything.html
data, err := c.GetRequest(fmt.Sprintf("Patient/%s/$everything", patientId))
if err != nil {
return nil, err
}
if bundle, isOk := data.(*gofhir.Bundle); isOk {
return bundle, nil
} else {
return nil, errors.New("could not cast Patient")
}
}
func (c *FhirBaseClient) GetPatient(patientId string) (*gofhir.Patient, error) {
data, err := c.GetRequest(fmt.Sprintf("Patient/%s", patientId))
if err != nil {
return nil, err
}
if patient, isOk := data.(*gofhir.Patient); isOk {
return patient, nil
} else {
return nil, errors.New("could not cast Patient")
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HttpClient
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (c *FhirBaseClient) GetRequest(resourceSubpath string) (interface{}, error) {
url := fmt.Sprintf("%s/%s", strings.TrimRight(c.Credential.ApiEndpointBaseUrl, "/"), strings.TrimLeft(resourceSubpath, "/"))
resp, err := c.OauthClient.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
//log.Printf("%v resp code", resp.StatusCode)
//body, err := ioutil.ReadAll(resp.Body)
//log.Fatalf("JSON BODY: %v", string(body))
var jsonResp map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&jsonResp)
if err != nil {
return nil, err
}
return gofhir.MapToResource(jsonResp, true)
}

View File

@ -0,0 +1,22 @@
package base
type Client interface {
SyncAll() error
//PatientProfile() (models.PatientProfile, error)
//Allergies()
//Encounters()
//Immunizations()
//Instructions()
//Medications()
//Narratives()
//Organizations()
//PlansOfCare()
//Problems()
//Procedures()
//TestResults()
//Vitals()
//CCD()
//Demographics()
//SocialHistory()
}

View File

@ -0,0 +1,44 @@
package cigna
import (
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/hub/internal/fhir/base"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/models"
"github.com/sirupsen/logrus"
"net/http"
)
type CignaClient struct {
base.FhirBaseClient
}
func NewClient(appConfig config.Interface, globalLogger logrus.FieldLogger, credentials models.ProviderCredential, testHttpClient ...*http.Client) (base.Client, error) {
baseClient, err := base.NewBaseClient(appConfig, globalLogger, credentials, testHttpClient...)
return CignaClient{
baseClient,
}, err
}
func (c CignaClient) SyncAll() error {
patient, err := c.GetPatient(c.Credential.PatientId)
if err != nil {
return err
}
c.Logger.Infof("patient: %v", patient)
//bundle, err := c.GetPatientEverything(c.Credential.PatientId)
//if err != nil {
// return err
//}
//c.Logger.Infof("bundle lenght: ", bundle.Total)
return nil
}
//func (c CignaClient) PatientProfile() (models.PatientProfile, error) {
// patient, err := c.GetPatientEverything(fmt.Sprintf("Patient/%s/", c.Credential.PatientId))
//
//
//
// return nil
//}

View File

@ -0,0 +1,46 @@
package models
import "gorm.io/gorm"
//demographics Object (optional) (See demographics)
//alcohol Object (optional) The users alcohol usage. See alcohol object.
//smoking Object (optional) The users smoking habits. See smoking object.
type PatientProfile struct {
gorm.Model
User User `json:"user,omitempty"`
UserID uint `json:"user_id" gorm:"uniqueIndex:idx_user_provider_patient"`
ProviderId string `json:"provider_id" gorm:"uniqueIndex:idx_user_provider_patient"`
PatientId string `json:"patient_id" gorm:"uniqueIndex:idx_user_provider_patient"`
//embedded structs
Demographics `json:"demographics,omitempty"`
}
type Demographics struct {
Address Address `json:"address"` // Object (See address object)
Dob string `json:"dob"` //String (optional) The users date of birth e.g. "04/21/1965"
Ethnicity string `json:"ethnicity"` // String (optional) The ethnicity of the user e.g. "Not Hispanic of Latino"
Gender string `json:"gender"` // String (optional) The users gender e.g. "male"
Language string `json:"language"` //String (optional) The users primary language e.g. "eng"
MaritalStatus string `json:"maritalStatus"` // String (optional) The users marital status (eg: “married”, “single”)
Name Name `json:"name"` // Object (optional) (See name object)
Race string `json:"race"` // String (optional) The users race e.g. "White"
EthnicityCodes string `json:"ethnicityCodes"` // ethnicityCodes Array[Object] (optional) CDC Race & Ethnicity and SNOMED CT Ethnicity codes: See codes
MaritalStatusCodes string `json:"maritalStatusCodes"` // String (optional) SNOMED CT Marital status codes: see codes object
GenderCodes string `json:"genderCodes"` //String (optional) SNOMED CT Gender codes: See codes
}
type Address struct {
City string `json:"city"` // (optional) City of address e.g. "SAN FRANCISCO"
Country string `json:"country"` // (optional) Country of address e.g. "US"
State string `json:"state"` // (optional) State of address e.g. "CA"
Street []string `json:"street"` // Array[String] (optional) Street of address e.g. ["156 22ND AVE NW"]
Zip string `json:"zip"` // (optional) Zip of address e.g. "94123"
}
type Name struct {
Prefix string `json:"prefix"` // String (optional) The title of the provider e.g. "MD"
Given []string `json:"given"` // Array[String] Name values associated with the provider e.g. ["Travis", "R"]
Family string `json:"family"` // String (optional) Family name of the provider e.g. "Liddell"
}

View File

@ -1,13 +1,13 @@
package models
import "gorm.io/gorm"
type ProviderCredential struct {
//TODO: PRIMARY KEY should be UserId + ProviderId + PatientId
User User `json:"user,omitempty" gorm:"foreignKey:ID;references:UserId"`
UserId uint `json:"user_id"`
ProviderId string `json:"provider_id" gorm:"primaryKey"`
PatientId string `json:"patient_id" gorm:"primaryKey"`
gorm.Model
User User `json:"user,omitempty"`
UserID uint `json:"user_id" gorm:"uniqueIndex:idx_user_provider_patient"`
ProviderId string `json:"provider_id" gorm:"uniqueIndex:idx_user_provider_patient"`
PatientId string `json:"patient_id" gorm:"uniqueIndex:idx_user_provider_patient"`
OauthEndpointBaseUrl string `json:"oauth_endpoint_base_url"`
ApiEndpointBaseUrl string `json:"api_endpoint_base_url"`

View File

@ -3,6 +3,6 @@ package models
import "gorm.io/gorm"
type User struct {
*gorm.Model
gorm.Model
Username string `json:"username" gorm:"unique"`
}

View File

@ -0,0 +1,22 @@
package fhir
import (
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/database"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"net/http"
)
func Request(c *gin.Context) {
logger := c.MustGet("LOGGER").(*logrus.Entry)
_ = c.MustGet("REPOSITORY").(database.DatabaseRepository)
//err := databaseRepo.FHIRRequest(c)
var err error
if err != nil {
logger.Errorln("An error occurred while storing provider credential", err)
c.JSON(http.StatusInternalServerError, gin.H{"success": false})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": nil})
}

View File

@ -4,6 +4,7 @@ import (
"fmt"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/config"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/web/handler"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/web/handler/fhir"
"github.com/fastenhealth/fastenhealth-onprem/backend/pkg/web/middleware"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
@ -41,6 +42,8 @@ func (ae *AppEngine) Setup(logger *logrus.Entry) *gin.Engine {
})
api.POST("/provider_credential", handler.CreateProviderCredentials)
api.GET("/provider_credential", handler.ListProviderCredentials)
api.GET("/request", fhir.Request)
}
}

7
go.mod
View File

@ -4,7 +4,7 @@ go 1.18
require (
github.com/analogj/go-util v0.0.0-20210417161720-39b497cca03b
github.com/fastenhealth/gofhir v0.0.0
github.com/fastenhealth/gofhir-client v0.0.0
github.com/gin-gonic/gin v1.8.1
github.com/glebarez/sqlite v1.4.6
github.com/sirupsen/logrus v1.9.0
@ -41,6 +41,7 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/spf13/afero v1.8.2 // indirect
@ -48,7 +49,6 @@ require (
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.3.0 // indirect
github.com/tidwall/pretty v1.0.0 // indirect
github.com/ugorji/go/codec v1.2.7 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect
@ -59,6 +59,7 @@ require (
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/ini.v1 v1.66.4 // indirect
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.16.8 // indirect
@ -67,4 +68,4 @@ require (
modernc.org/sqlite v1.17.3 // indirect
)
replace github.com/fastenhealth/gofhir v0.0.0 => /Users/jason/repos/gopath/src/github.com/fastenhealth/gofhir
replace github.com/fastenhealth/gofhir-client v0.0.0 => /Users/jason/repos/gopath/src/github.com/fastenhealth/gofhir-client