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

[BACK-3183] Add ability to send connection invites for multiple providers #73

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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 go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ require (
github.com/oapi-codegen/runtime v1.1.1
github.com/onsi/ginkgo/v2 v2.19.0
github.com/onsi/gomega v1.33.1
github.com/tidepool-org/clinic/client v0.0.0-20241126104542-715a2a8b0a0f
github.com/tidepool-org/clinic/client v0.0.0-20241210102358-8cb663d5f33f
github.com/tidepool-org/clinic/redox_models v0.0.0-20240802193352-3f912afe2109
github.com/tidepool-org/go-common v0.12.2-0.20240612192926-de6d5c5a742c
github.com/tidepool-org/hydrophone/client v0.0.0-20240613035211-756659d74c0d
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tidepool-org/clinic/client v0.0.0-20241126104542-715a2a8b0a0f h1:RUVq1p3w0FUG5Y32frtkzBOQRc23S/WJDf+vn7ZECFA=
github.com/tidepool-org/clinic/client v0.0.0-20241126104542-715a2a8b0a0f/go.mod h1:7BpAdFdGJNB3aw/xvCz5XnWjSWRoUtWIX4xcMc4Bsko=
github.com/tidepool-org/clinic/client v0.0.0-20241210102358-8cb663d5f33f h1:/HFDu4okm9Md8iCNQc4N9l0rXAtvCNRXxyMAf22sXUA=
github.com/tidepool-org/clinic/client v0.0.0-20241210102358-8cb663d5f33f/go.mod h1:7BpAdFdGJNB3aw/xvCz5XnWjSWRoUtWIX4xcMc4Bsko=
github.com/tidepool-org/clinic/redox_models v0.0.0-20240802193352-3f912afe2109 h1:NVsWq93dgv1mQ/ELrJW1lv4pwMQaoSO0BLaK4qHZ8Xc=
github.com/tidepool-org/clinic/redox_models v0.0.0-20240802193352-3f912afe2109/go.mod h1:bQ9DZxk015RhmGG1tR6jRScP9KxyHvS8tzPbVtr82DE=
github.com/tidepool-org/go-common v0.12.2-0.20240612192926-de6d5c5a742c h1:hJZyiHNGeqyLA/5p60/0H9CZtJi4fAuzOuyQF0TpF7E=
Expand Down
62 changes: 38 additions & 24 deletions patients/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,9 @@ func (p *PatientCDCConsumer) handleCDCEvent(event PatientCDCEvent) error {
return err
}

// Only send invite email if patient does not have a pending dexcom connect request, which also
// Only send invite email if patient does not have a pending connection request, which also
// sends an email that provides a pathway towards claiming the account
if !event.PatientHasPendingDexcomConnection() {
if !event.PatientHasPendingConnection() {
if err := p.applyInviteUpdate(event); err != nil {
return err
}
Expand Down Expand Up @@ -177,16 +177,17 @@ func (p *PatientCDCConsumer) handleCDCEvent(event PatientCDCEvent) error {
return p.sendUploadReminder(*event.FullDocument.UserId)
}

if event.IsRequestDexcomConnectEvent() {
p.logger.Infow("processing dexcom connect email", "event", event)
connectionRequests := event.UpdateDescription.UpdatedFields.GetUpdatedConnectionRequests()
if len(connectionRequests) > 0 {
p.logger.Infow("processing connection requests", "event", event)

if event.FullDocument.IsCustodial() {
invite := confirmations.UpsertAccountSignupConfirmationJSONRequestBody{
ClinicId: (*confirmations.ClinicId)(&event.FullDocument.ClinicId.Value),
InvitedBy: (*confirmations.TidepoolUserId)(event.FullDocument.InvitedBy),
ClinicId: &event.FullDocument.ClinicId.Value,
InvitedBy: event.FullDocument.InvitedBy,
}

response, err := p.confirmations.UpsertAccountSignupConfirmationWithResponse(ctx, confirmations.UserId(*event.FullDocument.UserId), invite)
response, err := p.confirmations.UpsertAccountSignupConfirmationWithResponse(ctx, *event.FullDocument.UserId, invite)
if err != nil {
return fmt.Errorf("unable to upsert confirmation: %v", err)
}
Expand All @@ -198,26 +199,38 @@ func (p *PatientCDCConsumer) handleCDCEvent(event PatientCDCEvent) error {
}
}

templateName := "request_dexcom_connect"

if event.FullDocument.IsCustodial() {
templateName = "request_dexcom_connect_custodial"
providers := map[string]struct{}{}
for _, r := range connectionRequests {
providers[r.ProviderName] = struct{}{}
}

if event.FullDocument.DataSources != nil {
for _, source := range *event.FullDocument.DataSources {
if *source.ProviderName == DexcomDataSourceProviderName && *source.State == string(clinics.DataSourceStatePendingReconnect) {
templateName = "request_dexcom_reconnect"
errs := make([]error, 0, len(providers))
for providerName := range providers {
templatePrefix := fmt.Sprintf("request_%s_", providerName)
action := "connect"
if event.FullDocument.IsCustodial() {
action = "connect_custodial"
}
if event.FullDocument.DataSources != nil {
for _, source := range *event.FullDocument.DataSources {
if *source.ProviderName == providerName && *source.State == string(clinics.DataSourceStatePendingReconnect) {
action = "reconnect"
}
}
}
}

return p.sendDexcomConnectEmail(
*event.FullDocument.UserId,
event.FullDocument.ClinicId.Value,
*event.FullDocument.FullName,
templateName,
)
templateName := templatePrefix + action
errs = append(errs, p.sendProviderConnectEmail(
providerName,
*event.FullDocument.UserId,
event.FullDocument.ClinicId.Value,
*event.FullDocument.FullName,
templateName,
))
}
if err := errors.Join(errs...); err != nil {
return err
}
}

return nil
Expand Down Expand Up @@ -292,7 +305,7 @@ func (p *PatientCDCConsumer) sendUploadReminder(userId string) error {
return p.mailer.SendEmailTemplate(ctx, template)
}

func (p *PatientCDCConsumer) sendDexcomConnectEmail(userId, clinicId, patientName, templateName string) error {
func (p *PatientCDCConsumer) sendProviderConnectEmail(providerName, userId, clinicId, patientName, templateName string) error {
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()

Expand All @@ -314,7 +327,7 @@ func (p *PatientCDCConsumer) sendDexcomConnectEmail(userId, clinicId, patientNam
return err
}

restrictedTokenPaths := []string{"/v1/oauth/dexcom"}
restrictedTokenPaths := []string{"/v1/oauth/" + providerName}
restrictedTokenExpirationTime := time.Now().Add(restrictedTokenExpirationDuration)

// Create new or update existing restricted token for this path and user
Expand Down Expand Up @@ -360,6 +373,7 @@ func (p *PatientCDCConsumer) sendDexcomConnectEmail(userId, clinicId, patientNam
"ClinicName": clinicName,
"RestrictedTokenId": restrictedToken.ID,
"PatientName": patientName,
"ProviderName": providerName,
},
}

Expand Down
18 changes: 18 additions & 0 deletions patients/consumer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,22 @@ var _ = Describe("PatientCDCConsumer", func() {
Expect(event.FullDocument.LastRequestedDexcomConnectTime.Value).To(Equal(int64(1725664480753)))
})
})

Describe("", func() {
It("returns only the added provider connection request", func() {
fixture, err := test.LoadFixture("test/fixtures/provider_connection_request.txt")
Expect(err).ToNot(HaveOccurred())

// Some editors add a new line at the end of the file by default, remove it
fixture = []byte(strings.TrimSuffix(string(fixture), "\n"))

event := patients.PatientCDCEvent{}
err = patients.UnmarshalEvent(fixture, &event)
Expect(err).ToNot(HaveOccurred())

requests := event.UpdateDescription.UpdatedFields.GetUpdatedConnectionRequests()
Expect(requests).To(HaveLen(1))
Expect(requests[0].ProviderName).To(Equal("dexcom"))
})
})
})
80 changes: 53 additions & 27 deletions patients/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,6 @@ func (p PatientCDCEvent) IsUploadReminderEvent() bool {
return lastUploadReminderTime != nil && lastUploadReminderTime.Value > 0
}

func (p PatientCDCEvent) IsRequestDexcomConnectEvent() bool {
if p.OperationType != cdc.OperationTypeUpdate && p.OperationType != cdc.OperationTypeReplace {
return false
}
if p.FullDocument.UserId == nil || p.UpdateDescription.UpdatedFields.LastRequestedDexcomConnectTime == nil {
return false
}
return p.UpdateDescription.UpdatedFields.LastRequestedDexcomConnectTime.Value > 0
}

func (p PatientCDCEvent) IsProfileUpdateEvent() bool {
if p.OperationType != cdc.OperationTypeInsert && p.OperationType != cdc.OperationTypeUpdate && p.OperationType != cdc.OperationTypeReplace {
return false
Expand All @@ -55,10 +45,10 @@ func (p PatientCDCEvent) IsPatientCreateFromExistingUserEvent() bool {
return p.OperationType == cdc.OperationTypeInsert && !p.FullDocument.IsCustodial()
}

func (p PatientCDCEvent) PatientHasPendingDexcomConnection() bool {
func (p PatientCDCEvent) PatientHasPendingConnection() bool {
if p.FullDocument.DataSources != nil {
for _, dataSource := range *p.FullDocument.DataSources {
if *dataSource.ProviderName == DexcomDataSourceProviderName && *dataSource.State == string(clinics.DataSourceStatePending) {
if *dataSource.State == string(clinics.DataSourceStatePending) {
return true
}
}
Expand Down Expand Up @@ -110,21 +100,31 @@ type CDCSummary struct {
}

type Patient struct {
Id *cdc.ObjectId `json:"_id" bson:"_id"`
ClinicId *cdc.ObjectId `json:"clinicId" bson:"clinicId"`
UserId *string `json:"userId" bson:"userId"`
BirthDate *string `json:"birthDate" bson:"birthDate"`
Email *string `json:"email" bson:"email"`
FullName *string `json:"fullName" bson:"fullName"`
Mrn *string `json:"mrn" bson:"mrn"`
TargetDevices *[]string `json:"targetDevices" bson:"targetDevices"`
DataSources *[]PatientDataSource `json:"dataSources" bson:"dataSources"`
Permissions *Permissions `json:"permissions" bson:"permissions"`
IsMigrated bool `json:"isMigrated" bson:"isMigrated"`
InvitedBy *string `json:"invitedBy" bson:"invitedBy"`
LastRequestedDexcomConnectTime *cdc.Date `json:"lastRequestedDexcomConnectTime" bson:"lastRequestedDexcomConnectTime"`
LastUploadReminderTime *cdc.Date `json:"lastUploadReminderTime" bson:"lastUploadReminderTime"`
Summary *CDCSummary `json:"summary" bson:"summary"`
Id *cdc.ObjectId `json:"_id" bson:"_id"`
ClinicId *cdc.ObjectId `json:"clinicId" bson:"clinicId"`
UserId *string `json:"userId" bson:"userId"`
BirthDate *string `json:"birthDate" bson:"birthDate"`
Email *string `json:"email" bson:"email"`
FullName *string `json:"fullName" bson:"fullName"`
Mrn *string `json:"mrn" bson:"mrn"`
TargetDevices *[]string `json:"targetDevices" bson:"targetDevices"`
DataSources *[]PatientDataSource `json:"dataSources" bson:"dataSources"`
Permissions *Permissions `json:"permissions" bson:"permissions"`
IsMigrated bool `json:"isMigrated" bson:"isMigrated"`
InvitedBy *string `json:"invitedBy" bson:"invitedBy"`
LastRequestedDexcomConnectTime *cdc.Date `json:"lastRequestedDexcomConnectTime" bson:"lastRequestedDexcomConnectTime"`
LastUploadReminderTime *cdc.Date `json:"lastUploadReminderTime" bson:"lastUploadReminderTime"`
Summary *CDCSummary `json:"summary" bson:"summary"`
ProviderConnectionRequests ProviderConnectionRequests `json:"providerConnectionRequests" bson:"providerConnectionRequests"`
}

type ProviderConnectionRequests map[string]ConnectionRequests

type ConnectionRequests []ConnectionRequest

type ConnectionRequest struct {
ProviderName string `json:"providerName" bson:"providerName"`
CreatedTime cdc.Date `json:"createdTime" bson:"createdTime"`
}

func (p PatientCDCEvent) CreateDataSourceBody(source clients.DataSource) clinics.DataSource {
Expand Down Expand Up @@ -170,4 +170,30 @@ func (u UpdateDescription) applyUpdatesToExistingProfile(profile map[string]inte

type UpdatedFields struct {
Patient

// Partial updates to nested fields are encoded using dot notation in CDC events
ProviderConnectionRequestsDexcom ConnectionRequests `json:"providerConnectionRequests.dexcom"`
ProviderConnectionRequestsTwiist ConnectionRequests `json:"providerConnectionRequests.twiist"`
ProviderConnectionRequestsAbbott ConnectionRequests `json:"providerConnectionRequests.abbott"`
}

func (u UpdatedFields) GetUpdatedConnectionRequests() ConnectionRequests {
var requests ConnectionRequests
for _, r := range u.ProviderConnectionRequests {
requests = AppendMostRecentConnectionRequest(requests, r)
}
requests = AppendMostRecentConnectionRequest(requests, u.ProviderConnectionRequestsDexcom)
requests = AppendMostRecentConnectionRequest(requests, u.ProviderConnectionRequestsTwiist)
requests = AppendMostRecentConnectionRequest(requests, u.ProviderConnectionRequestsAbbott)

return requests
}

func AppendMostRecentConnectionRequest(requests ConnectionRequests, updated ConnectionRequests) ConnectionRequests {
if len(updated) == 0 {
return requests
}

return append(requests, updated[0])
}

1 change: 1 addition & 0 deletions patients/test/fixtures/provider_connection_request.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"{\"_id\": {\"_data\": \"8267630CE9000000022B022C0100296E5A1004CA752E224B144B56984F45CBAC162F2D46645F69640064675C6D28FB758F5D1D7106930004\"}, \"operationType\": \"update\", \"clusterTime\": {\"$timestamp\": {\"t\": 1734544617, \"i\": 2}}, \"wallTime\": {\"$date\": 1734544617208}, \"fullDocument\": {\"_id\": {\"$oid\": \"675c6d28fb758f5d1d710693\"}, \"clinicId\": {\"$oid\": \"65e100a1c7c732ced4f793a6\"}, \"userId\": \"b650bb9b-34ee-4c5d-aff0-bd149084c658\", \"birthDate\": \"1999-11-11\", \"email\": \"[email protected]\", \"fullName\": \"No Emailio\", \"mrn\": null, \"targetDevices\": null, \"tags\": [], \"permissions\": {\"custodian\": {}, \"view\": {}, \"upload\": {}, \"note\": {}}, \"createdTime\": {\"$date\": 1734110504368}, \"updatedTime\": {\"$date\": 1734544617207}, \"invitedBy\": \"65568c91-1348-4810-ad8b-dedfbfa72f57\", \"requireUniqueMrn\": false, \"dataSources\": [{\"expirationTime\": {\"$date\": 1737136617207}, \"providerName\": \"dexcom\", \"state\": \"pending\"}, {\"providerName\": \"libre\", \"state\": \"pending\"}, {\"expirationTime\": {\"$date\": 1737136295511}, \"providerName\": \"abbott\", \"state\": \"pending\"}], \"providerConnectionRequests\": {\"dexcom\": [{\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734544617207}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734544596419}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734538128524}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734538113834}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734537591344}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734537572678}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734537544729}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734537529577}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734536783858}}], \"abbott\": [{\"providerName\": \"abbott\", \"createdTime\": {\"$date\": 1734544295511}}, {\"providerName\": \"abbott\", \"createdTime\": {\"$date\": 1734542848014}}, {\"providerName\": \"abbott\", \"createdTime\": {\"$date\": 1734538133521}}, {\"providerName\": \"abbott\", \"createdTime\": {\"$date\": 1734538120330}}, {\"providerName\": \"abbott\", \"createdTime\": {\"$date\": 1734537752687}}, {\"providerName\": \"abbott\", \"createdTime\": {\"$date\": 1734537602922}}, {\"providerName\": \"abbott\", \"createdTime\": {\"$date\": 1734537601172}}]}}, \"ns\": {\"db\": \"clinic\", \"coll\": \"patients\"}, \"documentKey\": {\"_id\": {\"$oid\": \"675c6d28fb758f5d1d710693\"}}, \"updateDescription\": {\"updatedFields\": {\"updatedTime\": {\"$date\": 1734544617207}, \"dataSources.0.expirationTime\": {\"$date\": 1737136617207}, \"providerConnectionRequests.dexcom\": [{\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734544617207}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734544596419}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734538128524}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734538113834}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734537591344}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734537572678}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734537544729}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734537529577}}, {\"providerName\": \"dexcom\", \"createdTime\": {\"$date\": 1734536783858}}]}, \"removedFields\": [], \"truncatedArrays\": []}}"
Loading