Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate referral report pdf #396

Merged
merged 1 commit into from
Mar 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ jobs:
- name: Run tests
run: |
go-acc -o coverage.txt --ignore generated,cmd,graph ./... -- -timeout 60m
grep -v "generated.go" coverage.txt | grep -v "_gen.go" | grep -v "_mock.go" | grep -v "*mock.go" | grep -v "mocks.go" | grep -v "*resolver*go" | grep -v "server.go" > coverage.out
grep -v "generated.go" coverage.txt | grep -v "_gen.go" | grep -v "_mock.go" | grep -v "*mock.go" | grep -v "mocks.go" | grep -v "*resolver*go" | grep -v "server.go" | grep -v "*.html" > coverage.out
go tool cover -html=coverage.out -o coverage.html
gocov convert coverage.out > coverage.json
gocov report coverage.json > coverage_report.txt
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
cloud.google.com/go/pubsub v1.33.0
cloud.google.com/go/storage v1.32.0
github.com/99designs/gqlgen v0.17.36
github.com/SebastiaanKlippert/go-wkhtmltopdf v1.9.2
github.com/ahmetb/go-linq/v3 v3.2.0
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2
github.com/brianvoe/gofakeit v3.18.0+incompatible
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym
github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno=
github.com/CloudyKit/jet/v3 v3.0.0/go.mod h1:HKQPgSJmdK8hdoAbKUUWajkHyHo4RaU5rMdUywE7VMo=
github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY=
github.com/SebastiaanKlippert/go-wkhtmltopdf v1.9.2 h1:enQwehstpeaAnsyse1Aqb6r0sU5UJbiNvIqVmPo+KWI=
github.com/SebastiaanKlippert/go-wkhtmltopdf v1.9.2/go.mod h1:SQq4xfIdvf6WYKSDxAJc+xOJdolt+/bc1jnQKMtPMvQ=
github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0=
github.com/agnivade/levenshtein v1.1.1 h1:QY8M92nrzkmr798gCo3kmMyqXFzdQVpxLlGPRBij0P8=
github.com/agnivade/levenshtein v1.1.1/go.mod h1:veldBMzWxcCG2ZvUTKD2kJNRdCk5hVbJomOvKkmgYbo=
Expand Down
16 changes: 16 additions & 0 deletions pkg/clinical/infrastructure/datastore/cloudhealthcare/fhir.go
Original file line number Diff line number Diff line change
Expand Up @@ -2034,3 +2034,19 @@ func (fh StoreImpl) GetFHIRPatientEverything(ctx context.Context, id string, par

return &response, nil
}

// GetFHIRServiceRequest retrieves a FHIR service request using its primary ID
func (fh StoreImpl) GetFHIRServiceRequest(_ context.Context, id string) (*domain.FHIRServiceRequestRelayPayload, error) {
resource := &domain.FHIRServiceRequest{}

err := fh.Dataset.GetFHIRResource(serviceRequestResourceType, id, resource)
if err != nil {
return nil, fmt.Errorf("unable to get %s with ID %s, err: %w", serviceRequestResourceType, id, err)
}

payload := &domain.FHIRServiceRequestRelayPayload{
Resource: resource,
}

return payload, nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ type FHIRMock struct {
MockCreateFHIRDiagnosticReportFn func(_ context.Context, input *domain.FHIRDiagnosticReportInput) (*domain.FHIRDiagnosticReport, error)
MockSearchFHIREncounterAllDataFn func(_ context.Context, params map[string]interface{}, tenant dto.TenantIdentifiers, pagination dto.Pagination) (*domain.PagedFHIRResource, error)
MockGetFHIRPatientEverythingFn func(ctx context.Context, id string, params map[string]interface{}) (*domain.PagedFHIRResource, error)
MockGetFHIRServiceRequestFn func(_ context.Context, id string) (*domain.FHIRServiceRequestRelayPayload, error)
}

// NewFHIRMock initializes a new instance of FHIR mock
Expand Down Expand Up @@ -1537,6 +1538,7 @@ func NewFHIRMock() *FHIRMock {
patientID := uuid.New().String()
patientName := gofakeit.Name()
gender := domain.PatientGenderEnumFemale
phoneNumber := gofakeit.Phone()
return &domain.FHIRPatientRelayPayload{
Resource: &domain.FHIRPatient{
ID: &patientID,
Expand All @@ -1551,6 +1553,11 @@ func NewFHIRMock() *FHIRMock {
Month: 12,
Day: 12,
},
Telecom: []*domain.FHIRContactPoint{
{
Value: &phoneNumber,
},
},
},
}, nil
},
Expand Down Expand Up @@ -2154,6 +2161,42 @@ func NewFHIRMock() *FHIRMock {
TotalCount: 0,
}, nil
},
MockGetFHIRServiceRequestFn: func(_ context.Context, id string) (*domain.FHIRServiceRequestRelayPayload, error) {
resourceID := uuid.New().String()
return &domain.FHIRServiceRequestRelayPayload{
Resource: &domain.FHIRServiceRequest{
ID: &resourceID,
Text: &domain.FHIRNarrative{},
Identifier: []*domain.FHIRIdentifier{},
Subject: &domain.FHIRReference{
ID: &resourceID,
},
Encounter: &domain.FHIRReference{
ID: &resourceID,
},
Extension: []*domain.FHIRExtension{
{
URL: "http://savannahghi.org/fhir/StructureDefinition/referred-facility",
Extension: []domain.Extension{
{
URL: "facilityName",
ValueString: "Nairobi Hospital",
},
},
},
{
URL: "http://savannahghi.org/fhir/StructureDefinition/referred-specialist",
Extension: []domain.Extension{
{
URL: "specialistName",
ValueString: gofakeit.Name(),
},
},
},
},
},
}, nil
},
}
}

Expand Down Expand Up @@ -2511,3 +2554,8 @@ func (fh *FHIRMock) SearchFHIREncounterAllData(ctx context.Context, params map[s
func (fh *FHIRMock) GetFHIRPatientEverything(ctx context.Context, id string, params map[string]interface{}) (*domain.PagedFHIRResource, error) {
return fh.MockGetFHIRPatientEverythingFn(ctx, id, params)
}

// GetFHIRServiceRequest mocks the implementation of getting a service request by ID
func (fh *FHIRMock) GetFHIRServiceRequest(ctx context.Context, id string) (*domain.FHIRServiceRequestRelayPayload, error) {
return fh.MockGetFHIRServiceRequestFn(ctx, id)
}
5 changes: 5 additions & 0 deletions pkg/clinical/presentation/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,11 @@ func SetupRoutes(r *gin.Engine, cacheStore persist.CacheStore, authclient *authu
questionnaireList.Use(rest.AuthenticationGinMiddleware(cacheStore, *authclient))
questionnaireList.Use(rest.TenantIdentifierExtractionMiddleware(infra.FHIR))
questionnaireList.GET("", handlers.ListQuestionnaire)

referralReport := v1.Group("/referral-report")
referralReport.Use(rest.AuthenticationGinMiddleware(cacheStore, *authclient))
referralReport.Use(rest.TenantIdentifierExtractionMiddleware(infra.FHIR))
referralReport.GET("", handlers.GenerateReferralReport)
}

// GQLHandler sets up a GraphQL resolver
Expand Down
16 changes: 16 additions & 0 deletions pkg/clinical/presentation/rest/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,3 +376,19 @@ func (p PresentationHandlersImpl) ListQuestionnaire(c *gin.Context) {

c.JSON(http.StatusOK, questionnaire)
}

func (p PresentationHandlersImpl) GenerateReferralReport(c *gin.Context) {
queryParams := c.Request.URL.Query()
serviceRequestID := queryParams.Get("servicerequest")

c.Header("Content-Type", "application/pdf")
// c.Header("Content-Disposition", "attachment; filename=referral_report.pdf")

err := p.usecases.GenerateReferralReportPDF(c.Request.Context(), serviceRequestID)
if err != nil {
jsonErrorResponse(c, http.StatusBadRequest, err)
return
}

c.JSON(http.StatusOK, gin.H{"Status": "Ok"})
}
1 change: 1 addition & 0 deletions pkg/clinical/repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ type FHIRServiceRequest interface {
SearchFHIRServiceRequest(ctx context.Context, params map[string]interface{}, tenant dto.TenantIdentifiers, pagination dto.Pagination) (*domain.FHIRServiceRequestRelayConnection, error)
CreateFHIRServiceRequest(ctx context.Context, input domain.FHIRServiceRequestInput) (*domain.FHIRServiceRequestRelayPayload, error)
DeleteFHIRServiceRequest(ctx context.Context, id string) (bool, error)
GetFHIRServiceRequest(ctx context.Context, id string) (*domain.FHIRServiceRequestRelayPayload, error)
}
type FHIRMedicationRequest interface {
SearchFHIRMedicationRequest(ctx context.Context, params map[string]interface{}, tenant dto.TenantIdentifiers, pagination dto.Pagination) (*domain.FHIRMedicationRequestRelayConnection, error)
Expand Down
198 changes: 198 additions & 0 deletions pkg/clinical/usecases/clinical/referral_report.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
package clinical

import (
"bytes"
"context"
"fmt"
"html/template"
"log"
"strings"
"time"

"github.com/SebastiaanKlippert/go-wkhtmltopdf"
)

type Patient struct {
Name string
EmpowerID string
NationalID string
PhoneNumber string
DateOfBirth string
Age int
Sex string
}

type NextOfKin struct {
Name string
Relationship string
PhoneNumber string
}

type Facility struct {
Name string
Location string
Contact string
}

type Referral struct {
Reason string
}

type Test struct {
Name string
Results string
Date string
}

type MedicalHistory struct {
Procedure string
Medication string
ReferralNotes string
Tests []Test
}

type ReferredBy struct {
Name string
Designation string
Phone string
Signature string
}

type Footer struct {
Phone string
Email string
Address string
}

type TemplateData struct {
Date string
Time string
Reason string
Patient Patient
NextOfKin NextOfKin
Facility Facility
Referral Referral
MedicalHistory MedicalHistory
ReferredBy ReferredBy
Footer Footer
}

// GenerateReferralReportPDF generates a PDF report for a given referral.
//
// The serviceRequestID is unique to each ServiceRequest resource, which,
// according to FHIR standards, is how referrals are represented. In FHIR, a referral
// is a specific type of ServiceRequest, which typically contains details such
// as the requester, the patient, the requested service, and other clinical information.
//
// By leveraging the serviceRequestID, this function retrieves the associated ServiceRequest
// from the FHIR server. It then extracts relevant data, including patient and encounter
// information, to construct a comprehensive referral report. The report is formatted
// as a PDF, making it suitable for clinical review, record-keeping, or sharing with
// other healthcare professionals.
func (c *UseCasesClinicalImpl) GenerateReferralReportPDF(ctx context.Context, serviceRequestID string) error {
if serviceRequestID == "" {
return fmt.Errorf("service request ID cannot be empty")
}

serviceRequest, err := c.infrastructure.FHIR.GetFHIRServiceRequest(ctx, serviceRequestID)
if err != nil {
return err
}

patient, err := c.infrastructure.FHIR.GetFHIRPatient(ctx, *serviceRequest.Resource.Subject.ID)
if err != nil {
return err
}

age := time.Since(patient.Resource.BirthDate.AsTime()).Hours() / 24 / 365
patientData := Patient{
Name: patient.Resource.Name[0].Text,
EmpowerID: "",
NationalID: "",
PhoneNumber: *patient.Resource.Telecom[0].Value,
DateOfBirth: patient.Resource.BirthDate.String(),
Age: int(age),
Sex: patient.Resource.Gender.String(),
}

var referredFacilityName, referredSpecialistName string

for _, extension := range serviceRequest.Resource.Extension {
switch extension.URL {
case "http://savannahghi.org/fhir/StructureDefinition/referred-facility":
for _, ext := range extension.Extension {
if ext.URL == "facilityName" {
referredFacilityName = ext.ValueString
}
}

case "http://savannahghi.org/fhir/StructureDefinition/referred-specialist":
for _, ext := range extension.Extension {
if ext.URL == "specialistName" {
referredSpecialistName = ext.ValueString
}
}
}
}

data := TemplateData{
Date: time.Now().Format("Monday Jan 2"),
Time: time.Now().Format("15:04"),
Patient: patientData,
NextOfKin: NextOfKin{},
Facility: Facility{
Name: referredFacilityName,
},
Referral: Referral{
// TODO: Get the reason from the API
Reason: "Further Testing",
},
MedicalHistory: MedicalHistory{Procedure: "Screening", Medication: "None", ReferralNotes: "Patient complains of severe abdominal pain and intermittent bleeding.", Tests: []Test{{Name: "VIA", Results: "Positive", Date: "13th May 2024"}}},
ReferredBy: ReferredBy{
Name: referredSpecialistName,
Designation: "Doctor",
Phone: "+254711990990",
Signature: "",
},
Footer: Footer{},
}

tmpl, err := template.ParseFiles("templates/referral_report_template.html")
if err != nil {
log.Print(err)
return err
}

// Fill the template with data
var htmlBuffer bytes.Buffer

err = tmpl.Execute(&htmlBuffer, data)
if err != nil {
log.Fatalf("Error executing template: %v", err)
}

// Convert template output to string
htmlContent := htmlBuffer.String()

// Create a new PDF generator
pdfg, err := wkhtmltopdf.NewPDFGenerator()
if err != nil {
return err
}

// Add one page from an URL, a file, or HTML content
pdfg.AddPage(wkhtmltopdf.NewPageReader(strings.NewReader(htmlContent)))

// Create PDF document in internal buffer
err = pdfg.Create()
if err != nil {
return err
}

err = pdfg.WriteFile("referral_report.pdf")
if err != nil {
return err
}

return nil
}
Loading
Loading