From 0d193c66bc01a9bd00c4247196c874aa53fc8432 Mon Sep 17 00:00:00 2001 From: Otieno Calvine Date: Fri, 3 Sep 2021 10:27:30 +0300 Subject: [PATCH] chore: remove unused apiclient and its dependencies Signed-off-by: Otieno Calvine --- .github/workflows/ci.yml | 1 - .github/workflows/codeql-analysis.yml | 1 - Dockerfile | 9 +- README.md | 15 - go.mod | 7 +- go.sum | 25 - gqlgen.yml | 1 - pkg/onboarding/application/dto/input.go | 16 - .../application/exceptions/custom_errors.go | 8 - .../exceptions/custom_errors_test.go | 2 - .../application/exceptions/error_messages.go | 3 - pkg/onboarding/application/extension/base.go | 43 +- .../extension/mock/extension_mock.go | 60 +- pkg/onboarding/application/utils/helpers.go | 71 --- .../application/utils/helpers_test.go | 234 -------- pkg/onboarding/application/utils/login.go | 54 -- .../application/utils/login_test.go | 169 ------ pkg/onboarding/domain/enum.go | 47 -- pkg/onboarding/domain/enum_test.go | 121 ---- pkg/onboarding/domain/model/models_gen.go | 23 - .../infrastructure/database/fb/firebase.go | 66 +-- .../database/fb/firebase_integration_test.go | 79 --- .../infrastructure/database/service.go | 6 - .../mock/infrastructure_mock.go | 8 - pkg/onboarding/presentation/config.go | 9 +- .../presentation/graph/enums.graphql | 5 - .../presentation/graph/generated/generated.go | 546 ------------------ .../presentation/graph/inputs.graphql | 14 - .../presentation/graph/types.graphql | 13 - pkg/onboarding/presentation/rest/handlers.go | 71 --- .../presentation/rest/handlers_test.go | 182 ------ pkg/onboarding/repository/mock/onboarding.go | 10 - pkg/onboarding/repository/onboarding.go | 1 - pkg/onboarding/usecases/profile.go | 28 - .../usecases/profile_integration_test.go | 88 --- pkg/onboarding/usecases/signup.go | 5 - pkg/onboarding/usecases/signup_unit_test.go | 8 - tests/profile_acceptance_test.go | 175 ------ tests/survey_acceptance_test.go | 50 +- 39 files changed, 65 insertions(+), 2209 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71b90f33..9c222fe3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -69,7 +69,6 @@ jobs: timeout-minutes: 80 steps: - uses: actions/checkout@v2 - - run: git config --global url."https://${user}:${ACCESS_TOKEN}@gitlab.slade360emr.com".insteadOf "https://gitlab.slade360emr.com" - uses: google-github-actions/setup-gcloud@master with: project_id: ${{ secrets.GOOGLE_CLOUD_PROJECT }} diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 1719e52c..0cfd21be 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -25,7 +25,6 @@ jobs: matrix: language: ["go"] steps: - - run: git config --global url."https://${user}:${ACCESS_TOKEN}@gitlab.slade360emr.com".insteadOf "https://gitlab.slade360emr.com" - name: Checkout repository uses: actions/checkout@v2 diff --git a/Dockerfile b/Dockerfile index 49f55d5c..139167d3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,15 +14,8 @@ CMD go mod download # Now copy the rest. COPY . /app/ -# Set up the credentials needed to fetch private code -ARG ACCESS_TOKEN -RUN git config --global url."https://${user}:${ACCESS_TOKEN}@gitlab.slade360emr.com".insteadOf "https://gitlab.slade360emr.com" - -# Retrieve application dependencies. -RUN GOPRIVATE="gitlab.slade360emr.com/go/*" go mod download - # Build the binary. -RUN cd /app/ && CGO_ENABLED=0 GOOS=linux GOPRIVATE="gitlab.slade360emr.com/go/*" go build -v -o server github.com/savannahghi/onboarding +RUN cd /app/ && CGO_ENABLED=0 GOOS=linux go build -v -o server github.com/savannahghi/onboarding # Use the official Alpine image for a lean production container. # https://hub.docker.com/_/alpine diff --git a/README.md b/README.md index c619dc5d..aa9c2f05 100644 --- a/README.md +++ b/README.md @@ -94,21 +94,6 @@ export GOOGLE_APPLICATION_CREDENTIALS="= 1 { - for _, cover := range covers { - if !utils.IfCoverExistsInSlice(profile.Covers, cover) { - if !utils.IfCoverExistsInSlice(newCovers, cover) { - newCovers = append(newCovers, cover) - } - } - } - } else { - newCovers = append(newCovers, covers...) - } - - profile.Covers = append(profile.Covers, newCovers...) - - query := &GetAllQuery{ - CollectionName: fr.GetUserProfileCollectionName(), - FieldName: "id", - Value: profile.ID, - Operator: "==", - } - docs, err := fr.FirestoreClient.GetAll(ctx, query) - if err != nil { - utils.RecordSpanError(span, err) - return exceptions.InternalServerError( - fmt.Errorf("unable to parse user profile as firebase snapshot: %v", err), - ) - } - if len(docs) == 0 { - return exceptions.InternalServerError(fmt.Errorf("user profile not found")) - } - updateCommand := &UpdateCommand{ - CollectionName: fr.GetUserProfileCollectionName(), - ID: docs[0].Ref.ID, - Data: profile, - } - err = fr.FirestoreClient.Update(ctx, updateCommand) - if err != nil { - utils.RecordSpanError(span, err) - return exceptions.InternalServerError( - fmt.Errorf("unable to update user profile covers: %v", err), - ) - } - - return nil -} - // UpdatePushTokens updates the pushTokens attribute of the profile that matches the id. This function does a hard reset instead of prior // matching func (fr *Repository) UpdatePushTokens(ctx context.Context, id string, pushTokens []string) error { diff --git a/pkg/onboarding/infrastructure/database/fb/firebase_integration_test.go b/pkg/onboarding/infrastructure/database/fb/firebase_integration_test.go index 999287a4..aaf75911 100644 --- a/pkg/onboarding/infrastructure/database/fb/firebase_integration_test.go +++ b/pkg/onboarding/infrastructure/database/fb/firebase_integration_test.go @@ -1448,85 +1448,6 @@ func TestRepository_UpdateVerifiedIdentifiers(t *testing.T) { } } -func TestRepository_UpdateCovers(t *testing.T) { - ctx, auth, err := GetTestAuthenticatedContext(t) - if err != nil { - t.Errorf("failed to get test authenticated context: %v", err) - return - } - - fsc, fbc := firestoreClient, firebaseAuth - if fsc == nil { - t.Errorf("failed to initialize test FireStore client") - return - } - if fbc == nil { - t.Errorf("failed to initialize test FireBase client") - return - } - firestoreExtension := fb.NewFirestoreClientExtension(fsc) - fr := fb.NewFirebaseRepository(firestoreExtension, fbc) - - userProfile, err := fr.GetUserProfileByUID(ctx, auth.UID, false) - if err != nil { - t.Errorf("failed to get a user profile") - return - } - - newCover := []profileutils.Cover{ - { - PayerName: "Payer 6", - PayerSladeCode: 27, - MemberName: "Jakom", - MemberNumber: "12345", - }, - } - - type args struct { - ctx context.Context - id string - covers []profileutils.Cover - } - tests := []struct { - name string - args args - wantErr bool - }{ - { - name: "Sad Case - Using an invalid ID", - args: args{ - ctx: ctx, - id: "invalidID", - covers: []profileutils.Cover{ - { - PayerName: "payer1", - PayerSladeCode: 1, - MemberName: "name1", - MemberNumber: "mem1", - }, - }, - }, - wantErr: true, - }, - { - name: "Happy Case - Add a valid new cover", - args: args{ - ctx: ctx, - id: userProfile.ID, - covers: newCover, - }, - wantErr: false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := fr.UpdateCovers(tt.args.ctx, tt.args.id, tt.args.covers); (err != nil) != tt.wantErr { - t.Errorf("Repository.UpdateCovers() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - func TestRepository_UpdateSecondaryEmailAddresses(t *testing.T) { ctx, auth, err := GetTestAuthenticatedContext(t) if err != nil { diff --git a/pkg/onboarding/infrastructure/database/service.go b/pkg/onboarding/infrastructure/database/service.go index 750638f7..74d74d24 100644 --- a/pkg/onboarding/infrastructure/database/service.go +++ b/pkg/onboarding/infrastructure/database/service.go @@ -175,7 +175,6 @@ type UserProfileRepository interface { UpdateVerifiedUIDS(ctx context.Context, id string, uids []string) error UpdateSuspended(ctx context.Context, id string, status bool) error UpdatePhotoUploadID(ctx context.Context, id string, uploadID string) error - UpdateCovers(ctx context.Context, id string, covers []profileutils.Cover) error UpdatePushTokens(ctx context.Context, id string, pushToken []string) error UpdatePermissions(ctx context.Context, id string, perms []profileutils.PermissionType) error UpdateRole(ctx context.Context, id string, role profileutils.RoleType) error @@ -330,11 +329,6 @@ func (d DbService) UpdatePhotoUploadID(ctx context.Context, id string, uploadID return d.firestore.UpdatePhotoUploadID(ctx, id, uploadID) } -// UpdateCovers updates the covers attribute of the profile that matches the id -func (d DbService) UpdateCovers(ctx context.Context, id string, covers []profileutils.Cover) error { - return d.firestore.UpdateCovers(ctx, id, covers) -} - // UpdatePushTokens updates the pushTokens attribute of the profile that matches the id. This function does a hard reset instead of prior // matching func (d DbService) UpdatePushTokens(ctx context.Context, id string, pushToken []string) error { diff --git a/pkg/onboarding/infrastructure/mock/infrastructure_mock.go b/pkg/onboarding/infrastructure/mock/infrastructure_mock.go index c9cfcd4f..e7096cd9 100644 --- a/pkg/onboarding/infrastructure/mock/infrastructure_mock.go +++ b/pkg/onboarding/infrastructure/mock/infrastructure_mock.go @@ -98,9 +98,6 @@ type FakeInfrastructure struct { // UpdatePhotoUploadID updates the photoUploadID attribute of the profile that matches the id UpdatePhotoUploadIDFn func(ctx context.Context, id string, uploadID string) error - // UpdateCovers updates the covers attribute of the profile that matches the id - UpdateCoversFn func(ctx context.Context, id string, covers []profileutils.Cover) error - // UpdatePushTokens updates the pushTokens attribute of the profile that matches the id. This function does a hard reset instead of prior // matching UpdatePushTokensFn func(ctx context.Context, id string, pushToken []string) error @@ -435,11 +432,6 @@ func (f FakeInfrastructure) UpdatePhotoUploadID(ctx context.Context, id string, return f.UpdatePhotoUploadIDFn(ctx, id, uploadID) } -// UpdateCovers updates the covers attribute of the profile that matches the id -func (f FakeInfrastructure) UpdateCovers(ctx context.Context, id string, covers []profileutils.Cover) error { - return f.UpdateCoversFn(ctx, id, covers) -} - // UpdatePushTokens updates the pushTokens attribute of the profile that matches the id. This function does a hard reset instead of prior // matching func (f FakeInfrastructure) UpdatePushTokens(ctx context.Context, id string, pushToken []string) error { diff --git a/pkg/onboarding/presentation/config.go b/pkg/onboarding/presentation/config.go index ba5ad3d3..406829a7 100644 --- a/pkg/onboarding/presentation/config.go +++ b/pkg/onboarding/presentation/config.go @@ -9,7 +9,6 @@ import ( "os" "time" - "gitlab.slade360emr.com/go/apiclient" "go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux" "github.com/savannahghi/firebasetools" @@ -167,7 +166,7 @@ func Router(ctx context.Context) (*mux.Router, error) { // Authenticated routes rs := r.PathPrefix("/roles").Subrouter() - rs.Use(apiclient.AuthenticationMiddleware(firebaseApp)) + rs.Use(firebasetools.AuthenticationMiddleware(firebaseApp)) rs.Path("/create_role").Methods( http.MethodPost, http.MethodOptions). @@ -202,10 +201,6 @@ func Router(ctx context.Context) (*mux.Router, error) { http.MethodPost, http.MethodOptions). HandlerFunc(h.GetUserProfileByPhoneOrEmail()) - isc.Path("/update_covers").Methods( - http.MethodPost, - http.MethodOptions). - HandlerFunc(h.UpdateCovers()) isc.Path("/contactdetails/{attribute}/").Methods( http.MethodPost, http.MethodOptions). @@ -273,7 +268,7 @@ func Router(ctx context.Context) (*mux.Router, error) { // Authenticated routes authR := r.Path("/graphql").Subrouter() - authR.Use(apiclient.AuthenticationMiddleware(firebaseApp)) + authR.Use(firebasetools.AuthenticationMiddleware(firebaseApp)) authR.Methods( http.MethodPost, http.MethodGet, diff --git a/pkg/onboarding/presentation/graph/enums.graphql b/pkg/onboarding/presentation/graph/enums.graphql index f4b22039..94c59c6a 100644 --- a/pkg/onboarding/presentation/graph/enums.graphql +++ b/pkg/onboarding/presentation/graph/enums.graphql @@ -36,11 +36,6 @@ enum PractitionerService { OTHER } -enum BeneficiaryRelationship { - SPOUSE - CHILD -} - enum AccountType { INDIVIDUAL ORGANISATION diff --git a/pkg/onboarding/presentation/graph/generated/generated.go b/pkg/onboarding/presentation/graph/generated/generated.go index 89d8ceab..6e6f12cf 100644 --- a/pkg/onboarding/presentation/graph/generated/generated.go +++ b/pkg/onboarding/presentation/graph/generated/generated.go @@ -64,14 +64,6 @@ type ComplexityRoot struct { PlaceID func(childComplexity int) int } - Beneficiary struct { - DateOfBirth func(childComplexity int) int - Emails func(childComplexity int) int - Msisdns func(childComplexity int) int - Name func(childComplexity int) int - Relationship func(childComplexity int) int - } - BioData struct { DateOfBirth func(childComplexity int) int FirstName func(childComplexity int) int @@ -123,12 +115,6 @@ type ComplexityRoot struct { URL func(childComplexity int) int } - Location struct { - BranchSladeCode func(childComplexity int) int - ID func(childComplexity int) int - Name func(childComplexity int) int - } - Microservice struct { Description func(childComplexity int) int ID func(childComplexity int) int @@ -407,41 +393,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Address.PlaceID(childComplexity), true - case "Beneficiary.dateOfBirth": - if e.complexity.Beneficiary.DateOfBirth == nil { - break - } - - return e.complexity.Beneficiary.DateOfBirth(childComplexity), true - - case "Beneficiary.emails": - if e.complexity.Beneficiary.Emails == nil { - break - } - - return e.complexity.Beneficiary.Emails(childComplexity), true - - case "Beneficiary.msisdns": - if e.complexity.Beneficiary.Msisdns == nil { - break - } - - return e.complexity.Beneficiary.Msisdns(childComplexity), true - - case "Beneficiary.name": - if e.complexity.Beneficiary.Name == nil { - break - } - - return e.complexity.Beneficiary.Name(childComplexity), true - - case "Beneficiary.relationship": - if e.complexity.Beneficiary.Relationship == nil { - break - } - - return e.complexity.Beneficiary.Relationship(childComplexity), true - case "BioData.dateOfBirth": if e.complexity.BioData.DateOfBirth == nil { break @@ -662,27 +613,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Link.URL(childComplexity), true - case "Location.branchSladeCode": - if e.complexity.Location.BranchSladeCode == nil { - break - } - - return e.complexity.Location.BranchSladeCode(childComplexity), true - - case "Location.id": - if e.complexity.Location.ID == nil { - break - } - - return e.complexity.Location.ID(childComplexity), true - - case "Location.name": - if e.complexity.Location.Name == nil { - break - } - - return e.complexity.Location.Name(childComplexity), true - case "Microservice.description": if e.complexity.Microservice.Description == nil { break @@ -1734,11 +1664,6 @@ enum PractitionerService { OTHER } -enum BeneficiaryRelationship { - SPOUSE - CHILD -} - enum AccountType { INDIVIDUAL ORGANISATION @@ -1975,20 +1900,6 @@ input PostVisitSurveyInput { suggestions: String! } -input BeneficiaryInput { - name: String! - msisdns: [String!] - emails: [String!] - relationship: BeneficiaryRelationship! - dateOfBirth: Date! -} - -input LocationInput { - id: ID! - name: String! - branchSladeCode: String -} - input UserAddressInput { latitude: Float! longitude: Float! @@ -2167,19 +2078,6 @@ type UserProfile @key(fields: "id") { roleDetails: [RoleOutput] } -type Beneficiary { - name: String! - msisdns: [String!] - emails: [String!] - relationship: BeneficiaryRelationship! - dateOfBirth: Date! -} - -type Location { - id: ID! - name: String! - branchSladeCode: String -} type Identification { identificationDocType: IdentificationDocType! @@ -3215,175 +3113,6 @@ func (ec *executionContext) _Address_formattedAddress(ctx context.Context, field return ec.marshalOString2ᚖstring(ctx, field.Selections, res) } -func (ec *executionContext) _Beneficiary_name(ctx context.Context, field graphql.CollectedField, obj *model.Beneficiary) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Beneficiary", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Beneficiary_msisdns(ctx context.Context, field graphql.CollectedField, obj *model.Beneficiary) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Beneficiary", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Msisdns, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalOString2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) _Beneficiary_emails(ctx context.Context, field graphql.CollectedField, obj *model.Beneficiary) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Beneficiary", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Emails, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalOString2ᚕstringᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) _Beneficiary_relationship(ctx context.Context, field graphql.CollectedField, obj *model.Beneficiary) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Beneficiary", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Relationship, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(domain.BeneficiaryRelationship) - fc.Result = res - return ec.marshalNBeneficiaryRelationship2githubᚗcomᚋsavannahghiᚋonboardingᚋpkgᚋonboardingᚋdomainᚐBeneficiaryRelationship(ctx, field.Selections, res) -} - -func (ec *executionContext) _Beneficiary_dateOfBirth(ctx context.Context, field graphql.CollectedField, obj *model.Beneficiary) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Beneficiary", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DateOfBirth, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(scalarutils.Date) - fc.Result = res - return ec.marshalNDate2githubᚗcomᚋsavannahghiᚋscalarutilsᚐDate(ctx, field.Selections, res) -} - func (ec *executionContext) _BioData_firstName(ctx context.Context, field graphql.CollectedField, obj *profileutils.BioData) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -4409,108 +4138,6 @@ func (ec *executionContext) _Link_Thumbnail(ctx context.Context, field graphql.C return ec.marshalOString2string(ctx, field.Selections, res) } -func (ec *executionContext) _Location_id(ctx context.Context, field graphql.CollectedField, obj *profileutils.Location) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Location", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Location_name(ctx context.Context, field graphql.CollectedField, obj *profileutils.Location) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Location", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) _Location_branchSladeCode(ctx context.Context, field graphql.CollectedField, obj *profileutils.Location) (ret graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - fc := &graphql.FieldContext{ - Object: "Location", - Field: field, - Args: nil, - IsMethod: false, - IsResolver: false, - } - - ctx = graphql.WithFieldContext(ctx, fc) - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.BranchSladeCode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - func (ec *executionContext) _Microservice_id(ctx context.Context, field graphql.CollectedField, obj *domain.Microservice) (ret graphql.Marshaler) { defer func() { if r := recover(); r != nil { @@ -9706,58 +9333,6 @@ func (ec *executionContext) ___Type_ofType(ctx context.Context, field graphql.Co // region **************************** input.gotpl ***************************** -func (ec *executionContext) unmarshalInputBeneficiaryInput(ctx context.Context, obj interface{}) (model.BeneficiaryInput, error) { - var it model.BeneficiaryInput - var asMap = obj.(map[string]interface{}) - - for k, v := range asMap { - switch k { - case "name": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) - it.Name, err = ec.unmarshalNString2string(ctx, v) - if err != nil { - return it, err - } - case "msisdns": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("msisdns")) - it.Msisdns, err = ec.unmarshalOString2ᚕstringᚄ(ctx, v) - if err != nil { - return it, err - } - case "emails": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("emails")) - it.Emails, err = ec.unmarshalOString2ᚕstringᚄ(ctx, v) - if err != nil { - return it, err - } - case "relationship": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("relationship")) - it.Relationship, err = ec.unmarshalNBeneficiaryRelationship2githubᚗcomᚋsavannahghiᚋonboardingᚋpkgᚋonboardingᚋdomainᚐBeneficiaryRelationship(ctx, v) - if err != nil { - return it, err - } - case "dateOfBirth": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dateOfBirth")) - it.DateOfBirth, err = ec.unmarshalNDate2githubᚗcomᚋsavannahghiᚋscalarutilsᚐDate(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - func (ec *executionContext) unmarshalInputFilterInput(ctx context.Context, obj interface{}) (firebasetools.FilterInput, error) { var it firebasetools.FilterInput var asMap = obj.(map[string]interface{}) @@ -9830,42 +9405,6 @@ func (ec *executionContext) unmarshalInputFilterParam(ctx context.Context, obj i return it, nil } -func (ec *executionContext) unmarshalInputLocationInput(ctx context.Context, obj interface{}) (model.LocationInput, error) { - var it model.LocationInput - var asMap = obj.(map[string]interface{}) - - for k, v := range asMap { - switch k { - case "id": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - it.ID, err = ec.unmarshalNID2string(ctx, v) - if err != nil { - return it, err - } - case "name": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) - it.Name, err = ec.unmarshalNString2string(ctx, v) - if err != nil { - return it, err - } - case "branchSladeCode": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("branchSladeCode")) - it.BranchSladeCode, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - } - } - - return it, nil -} - func (ec *executionContext) unmarshalInputMicroserviceInput(ctx context.Context, obj interface{}) (domain.Microservice, error) { var it domain.Microservice var asMap = obj.(map[string]interface{}) @@ -10313,47 +9852,6 @@ func (ec *executionContext) _Address(ctx context.Context, sel ast.SelectionSet, return out } -var beneficiaryImplementors = []string{"Beneficiary"} - -func (ec *executionContext) _Beneficiary(ctx context.Context, sel ast.SelectionSet, obj *model.Beneficiary) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, beneficiaryImplementors) - - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("Beneficiary") - case "name": - out.Values[i] = ec._Beneficiary_name(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } - case "msisdns": - out.Values[i] = ec._Beneficiary_msisdns(ctx, field, obj) - case "emails": - out.Values[i] = ec._Beneficiary_emails(ctx, field, obj) - case "relationship": - out.Values[i] = ec._Beneficiary_relationship(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } - case "dateOfBirth": - out.Values[i] = ec._Beneficiary_dateOfBirth(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - var bioDataImplementors = []string{"BioData"} func (ec *executionContext) _BioData(ctx context.Context, sel ast.SelectionSet, obj *profileutils.BioData) graphql.Marshaler { @@ -10641,40 +10139,6 @@ func (ec *executionContext) _Link(ctx context.Context, sel ast.SelectionSet, obj return out } -var locationImplementors = []string{"Location"} - -func (ec *executionContext) _Location(ctx context.Context, sel ast.SelectionSet, obj *profileutils.Location) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, locationImplementors) - - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("Location") - case "id": - out.Values[i] = ec._Location_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } - case "name": - out.Values[i] = ec._Location_name(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ - } - case "branchSladeCode": - out.Values[i] = ec._Location_branchSladeCode(ctx, field, obj) - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch() - if invalids > 0 { - return graphql.Null - } - return out -} - var microserviceImplementors = []string{"Microservice"} func (ec *executionContext) _Microservice(ctx context.Context, sel ast.SelectionSet, obj *domain.Microservice) graphql.Marshaler { @@ -11941,16 +11405,6 @@ func (ec *executionContext) marshalNAny2interface(ctx context.Context, sel ast.S return res } -func (ec *executionContext) unmarshalNBeneficiaryRelationship2githubᚗcomᚋsavannahghiᚋonboardingᚋpkgᚋonboardingᚋdomainᚐBeneficiaryRelationship(ctx context.Context, v interface{}) (domain.BeneficiaryRelationship, error) { - var res domain.BeneficiaryRelationship - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNBeneficiaryRelationship2githubᚗcomᚋsavannahghiᚋonboardingᚋpkgᚋonboardingᚋdomainᚐBeneficiaryRelationship(ctx context.Context, sel ast.SelectionSet, v domain.BeneficiaryRelationship) graphql.Marshaler { - return v -} - func (ec *executionContext) unmarshalNBoolean2bool(ctx context.Context, v interface{}) (bool, error) { res, err := graphql.UnmarshalBoolean(v) return res, graphql.ErrorOnPath(ctx, err) diff --git a/pkg/onboarding/presentation/graph/inputs.graphql b/pkg/onboarding/presentation/graph/inputs.graphql index f02b382a..88514cb7 100644 --- a/pkg/onboarding/presentation/graph/inputs.graphql +++ b/pkg/onboarding/presentation/graph/inputs.graphql @@ -14,20 +14,6 @@ input PostVisitSurveyInput { suggestions: String! } -input BeneficiaryInput { - name: String! - msisdns: [String!] - emails: [String!] - relationship: BeneficiaryRelationship! - dateOfBirth: Date! -} - -input LocationInput { - id: ID! - name: String! - branchSladeCode: String -} - input UserAddressInput { latitude: Float! longitude: Float! diff --git a/pkg/onboarding/presentation/graph/types.graphql b/pkg/onboarding/presentation/graph/types.graphql index 13523cb9..1417c8a2 100644 --- a/pkg/onboarding/presentation/graph/types.graphql +++ b/pkg/onboarding/presentation/graph/types.graphql @@ -50,19 +50,6 @@ type UserProfile @key(fields: "id") { roleDetails: [RoleOutput] } -type Beneficiary { - name: String! - msisdns: [String!] - emails: [String!] - relationship: BeneficiaryRelationship! - dateOfBirth: Date! -} - -type Location { - id: ID! - name: String! - branchSladeCode: String -} type Identification { identificationDocType: IdentificationDocType! diff --git a/pkg/onboarding/presentation/rest/handlers.go b/pkg/onboarding/presentation/rest/handlers.go index 5f03a739..ef81ad5e 100644 --- a/pkg/onboarding/presentation/rest/handlers.go +++ b/pkg/onboarding/presentation/rest/handlers.go @@ -16,7 +16,6 @@ import ( "github.com/savannahghi/onboarding/pkg/onboarding/application/dto" "github.com/savannahghi/onboarding/pkg/onboarding/infrastructure" "github.com/savannahghi/onboarding/pkg/onboarding/usecases" - "github.com/savannahghi/profileutils" "github.com/savannahghi/serverutils" "github.com/sirupsen/logrus" ) @@ -37,7 +36,6 @@ type HandlersInterfaces interface { RemoveUserByPhoneNumber() http.HandlerFunc GetUserProfileByUID() http.HandlerFunc GetUserProfileByPhoneOrEmail() http.HandlerFunc - UpdateCovers() http.HandlerFunc ProfileAttributes() http.HandlerFunc RegisterPushToken() http.HandlerFunc AddAdminPermsToUser() http.HandlerFunc @@ -668,75 +666,6 @@ func (h *HandlersInterfacesImpl) RegisterPushToken() http.HandlerFunc { } } -// UpdateCovers is an unauthenticated ISC endpoint that updates the cover of -// a given user given their UID and cover details -func (h *HandlersInterfacesImpl) UpdateCovers() http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - - p := &dto.UpdateCoversPayload{} - serverutils.DecodeJSONToTargetStruct(w, r, p) - if p.UID == nil { - err := fmt.Errorf("expected `UID` to be defined") - errorcodeutil.ReportErr(w, err, http.StatusBadRequest) - return - } - - if p.BeneficiaryID == nil { - err := fmt.Errorf("expected `BeneficiaryID` to be defined") - errorcodeutil.ReportErr(w, err, http.StatusBadRequest) - return - } - - if p.EffectivePolicyNumber == nil { - err := fmt.Errorf("expected `EffectivePolicyNumber` to be defined") - errorcodeutil.ReportErr(w, err, http.StatusBadRequest) - return - } - - if p.ValidFrom == nil { - err := fmt.Errorf("expected `ValidFrom` to be defined") - errorcodeutil.ReportErr(w, err, http.StatusBadRequest) - return - } - - if p.ValidTo == nil { - err := fmt.Errorf("expected `ValidTo` to be defined") - errorcodeutil.ReportErr(w, err, http.StatusBadRequest) - return - } - - auth := &auth.Token{UID: *p.UID} - ctx = context.WithValue(ctx, firebasetools.AuthTokenContextKey, auth) - cover := profileutils.Cover{ - PayerName: *p.PayerName, - MemberNumber: *p.MemberNumber, - MemberName: *p.MemberName, - PayerSladeCode: *p.PayerSladeCode, - BeneficiaryID: *p.BeneficiaryID, - EffectivePolicyNumber: *p.EffectivePolicyNumber, - ValidFrom: *p.ValidFrom, - ValidTo: *p.ValidTo, - } - var covers []profileutils.Cover - covers = append(covers, cover) - - err := h.usecases.UpdateCovers(ctx, covers) - if err != nil { - errorcodeutil.ReportErr(w, err, http.StatusBadRequest) - return - } - - serverutils.WriteJSONResponse( - w, - dto.OKResp{ - Status: "Covers successfully updated", - }, - http.StatusOK, - ) - } -} - // ProfileAttributes retrieves confirmed user profile attributes. // These attributes include a user's verified phone numbers, verified emails // and verified FCM push tokens diff --git a/pkg/onboarding/presentation/rest/handlers_test.go b/pkg/onboarding/presentation/rest/handlers_test.go index 1f5aa403..986274f5 100644 --- a/pkg/onboarding/presentation/rest/handlers_test.go +++ b/pkg/onboarding/presentation/rest/handlers_test.go @@ -10,7 +10,6 @@ import ( "net/http" "net/http/httptest" "testing" - "time" "github.com/google/uuid" "github.com/savannahghi/feedlib" @@ -198,16 +197,6 @@ func composeSendRetryOTPPayload(t *testing.T, phone string, retryStep int) *byte return bytes.NewBuffer(bs) } -func composeCoversUpdatePayload(t *testing.T, payload *dto.UpdateCoversPayload) *bytes.Buffer { - - bs, err := json.Marshal(payload) - if err != nil { - t.Errorf("unable to marshal payload to JSON: %s", err) - return nil - } - return bytes.NewBuffer(bs) -} - func composeSetPrimaryPhoneNumberPayload(t *testing.T, phone, otp string) *bytes.Buffer { payload := dto.SetPrimaryPhoneNumberPayload{ PhoneNumber: &phone, @@ -2041,177 +2030,6 @@ func TestHandlersInterfacesImpl_LoginAnonymous(t *testing.T) { } } -func TestHandlersInterfacesImpl_UpdateCovers(t *testing.T) { - - infra := InitializeFakeInfrastructure() - - usecases := usecases.NewUsecasesInteractor(infra, ext, pinExt) - - h := rest.NewHandlersInterfaces(infra, usecases) - - invalidUID := " " - uid := "5cf354a2-1d3e-400d-8716-7e2aead29f2c" - payerName := "Payer Name" - memberName := "Member Name" - memberNumber := "5678" - payerSladeCode := 1234 - beneficiaryID := 15689 - effectivePolicyNumber := "14582" - - validFromString := "2021-01-01T00:00:00+03:00" - validFrom, err := time.Parse(time.RFC3339, validFromString) - if err != nil { - t.Errorf("failed parse date string: %v", err) - return - } - - validToString := "2022-01-01T00:00:00+03:00" - validTo, err := time.Parse(time.RFC3339, validToString) - if err != nil { - t.Errorf("failed parse date string: %v", err) - return - } - - updateCoversPayloadValid := &dto.UpdateCoversPayload{ - UID: &uid, - PayerName: &payerName, - PayerSladeCode: &payerSladeCode, - MemberName: &memberName, - MemberNumber: &memberNumber, - BeneficiaryID: &beneficiaryID, - EffectivePolicyNumber: &effectivePolicyNumber, - ValidFrom: &validFrom, - ValidTo: &validTo, - } - - updateCoversPayloadInValid := &dto.UpdateCoversPayload{ - UID: &invalidUID, - PayerName: &payerName, - PayerSladeCode: &payerSladeCode, - MemberName: &memberName, - MemberNumber: &memberNumber, - BeneficiaryID: &beneficiaryID, - EffectivePolicyNumber: &effectivePolicyNumber, - ValidFrom: &validFrom, - ValidTo: &validTo, - } - - validPayload := composeCoversUpdatePayload(t, updateCoversPayloadValid) - inValidPayload := composeCoversUpdatePayload(t, updateCoversPayloadInValid) - - type args struct { - url string - httpMethod string - body io.Reader - } - tests := []struct { - name string - args args - want http.HandlerFunc - wantStatus int - wantErr bool - }{ - { - name: "valid:_Successfully_update_covers", - args: args{ - url: fmt.Sprintf("%s/update_covers", serverUrl), - httpMethod: http.MethodPost, - body: validPayload, - }, - wantStatus: http.StatusOK, - wantErr: false, - }, - - { - name: "invalid:_update_covers_fails", - args: args{ - url: fmt.Sprintf("%s/update_covers", serverUrl), - httpMethod: http.MethodPost, - body: validPayload, - }, - wantStatus: http.StatusBadRequest, - wantErr: true, - }, - { - name: "invalid:_get_user_profile_by_UID_fails", - args: args{ - url: fmt.Sprintf("%s/update_covers", serverUrl), - httpMethod: http.MethodPost, - body: inValidPayload, - }, - wantStatus: http.StatusBadRequest, - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - req, err := http.NewRequest(tt.args.httpMethod, tt.args.url, tt.args.body) - if err != nil { - t.Errorf("can't create new request: %v", err) - return - } - - response := httptest.NewRecorder() - - if tt.name == "valid:_Successfully_update_covers" { - fakeBaseExt.GetLoggedInUserUIDFn = func(ctx context.Context) (string, error) { - return "8716-7e2aead29f2c", nil - } - - fakeRepo.GetUserProfileByUIDFn = func(ctx context.Context, uid string, suspended bool) (*profileutils.UserProfile, error) { - return &profileutils.UserProfile{ - ID: "f4f39af7", - }, nil - } - - fakeRepo.UpdateCoversFn = func(ctx context.Context, id string, covers []profileutils.Cover) error { - return nil - } - } - - if tt.name == "invalid:_get_user_profile_by_UID_fails" { - fakeBaseExt.GetLoggedInUserUIDFn = func(ctx context.Context) (string, error) { - return "", fmt.Errorf("failed to get logged in user UID") - } - } - - if tt.name == "invalid:_update_covers_fails" { - fakeBaseExt.GetLoggedInUserUIDFn = func(ctx context.Context) (string, error) { - return "5cf354a2-1d3e-400d-8716-7e2aead29f2c", nil - } - - fakeRepo.GetUserProfileByUIDFn = func(ctx context.Context, uid string, suspended bool) (*profileutils.UserProfile, error) { - return &profileutils.UserProfile{ - ID: "f4f39af7", - }, nil - } - - fakeRepo.UpdateCoversFn = func(ctx context.Context, id string, covers []profileutils.Cover) error { - return fmt.Errorf("unable to update covers") - } - } - - svr := h.UpdateCovers() - svr.ServeHTTP(response, req) - - if tt.wantStatus != response.Code { - t.Errorf("expected status %d, got %d", tt.wantStatus, response.Code) - return - } - - dataResponse, err := ioutil.ReadAll(response.Body) - if err != nil { - t.Errorf("can't read response body: %v", err) - return - } - if dataResponse == nil { - t.Errorf("nil response body data") - return - } - }) - } -} - func TestHandlersInterfacesImpl_RemoveUserByPhoneNumber(t *testing.T) { infra := InitializeFakeInfrastructure() diff --git a/pkg/onboarding/repository/mock/onboarding.go b/pkg/onboarding/repository/mock/onboarding.go index 491ea266..5e709705 100644 --- a/pkg/onboarding/repository/mock/onboarding.go +++ b/pkg/onboarding/repository/mock/onboarding.go @@ -103,7 +103,6 @@ type FakeOnboardingRepository struct { UpdateUserRoleIDsFn func(ctx context.Context, id string, roleIDs []string) error UpdateSuspendedFn func(ctx context.Context, id string, status bool) error UpdatePhotoUploadIDFn func(ctx context.Context, id string, uploadID string) error - UpdateCoversFn func(ctx context.Context, id string, covers []profileutils.Cover) error UpdatePushTokensFn func(ctx context.Context, id string, pushToken []string) error UpdatePermissionsFn func(ctx context.Context, id string, perms []profileutils.PermissionType) error UpdateRoleFn func(ctx context.Context, id string, role profileutils.RoleType) error @@ -354,15 +353,6 @@ func (f *FakeOnboardingRepository) UpdatePhotoUploadID( return f.UpdatePhotoUploadIDFn(ctx, id, uploadID) } -// UpdateCovers ... -func (f *FakeOnboardingRepository) UpdateCovers( - ctx context.Context, - id string, - covers []profileutils.Cover, -) error { - return f.UpdateCoversFn(ctx, id, covers) -} - // UpdatePushTokens ... func (f *FakeOnboardingRepository) UpdatePushTokens( ctx context.Context, diff --git a/pkg/onboarding/repository/onboarding.go b/pkg/onboarding/repository/onboarding.go index 302a476e..05599149 100644 --- a/pkg/onboarding/repository/onboarding.go +++ b/pkg/onboarding/repository/onboarding.go @@ -173,7 +173,6 @@ type UserProfileRepository interface { UpdateVerifiedUIDS(ctx context.Context, id string, uids []string) error UpdateSuspended(ctx context.Context, id string, status bool) error UpdatePhotoUploadID(ctx context.Context, id string, uploadID string) error - UpdateCovers(ctx context.Context, id string, covers []profileutils.Cover) error UpdatePushTokens(ctx context.Context, id string, pushToken []string) error UpdatePermissions(ctx context.Context, id string, perms []profileutils.PermissionType) error UpdateRole(ctx context.Context, id string, role profileutils.RoleType) error diff --git a/pkg/onboarding/usecases/profile.go b/pkg/onboarding/usecases/profile.go index 390057bd..3d320526 100644 --- a/pkg/onboarding/usecases/profile.go +++ b/pkg/onboarding/usecases/profile.go @@ -65,7 +65,6 @@ type ProfileUseCase interface { UpdateVerifiedUIDS(ctx context.Context, uids []string) error UpdateSuspended(ctx context.Context, status bool, phoneNumber string, useContext bool) error UpdatePhotoUploadID(ctx context.Context, uploadID string) error - UpdateCovers(ctx context.Context, covers []profileutils.Cover) error UpdatePushTokens(ctx context.Context, pushToken string, retire bool) error UpdatePermissions(ctx context.Context, perms []profileutils.PermissionType) error AddAdminPermsToUser(ctx context.Context, phone string) error @@ -643,33 +642,6 @@ func (p *ProfileUseCaseImpl) UpdatePhotoUploadID(ctx context.Context, uploadID s } -// UpdateCovers updates primary covers of a specific user profile -func (p *ProfileUseCaseImpl) UpdateCovers(ctx context.Context, covers []profileutils.Cover) error { - ctx, span := tracer.Start(ctx, "UpdateCovers") - defer span.End() - - if len(covers) == 0 { - return fmt.Errorf("no covers to update found") - } - - uid, err := p.baseExt.GetLoggedInUserUID(ctx) - if err != nil { - utils.RecordSpanError(span, err) - return exceptions.UserNotFoundError(err) - } - profile, err := p.infrastructure.GetUserProfileByUID(ctx, uid, false) - if err != nil { - utils.RecordSpanError(span, err) - return err - } - - return p.infrastructure.UpdateCovers( - ctx, - profile.ID, - utils.AddHashToCovers(covers), - ) -} - // UpdatePushTokens updates primary push tokens of a specific user profile. func (p *ProfileUseCaseImpl) UpdatePushTokens( ctx context.Context, diff --git a/pkg/onboarding/usecases/profile_integration_test.go b/pkg/onboarding/usecases/profile_integration_test.go index 05e61516..d2e55ed8 100644 --- a/pkg/onboarding/usecases/profile_integration_test.go +++ b/pkg/onboarding/usecases/profile_integration_test.go @@ -1714,94 +1714,6 @@ func TestIntegrationGetAddresses(t *testing.T) { } } -func TestProfileUseCaseImpl_UpdateCovers(t *testing.T) { - ctx, _, err := GetTestAuthenticatedContext(t) - if err != nil { - t.Errorf("failed to get test authenticated context: %v", err) - return - } - p, err := InitializeTestService(ctx) - if err != nil { - t.Errorf("unable to initialize test service") - return - } - - memberNumber := uuid.New().String() - cover := profileutils.Cover{ - PayerName: *utils.GetRandomName(), - PayerSladeCode: 123, - MemberNumber: memberNumber, - MemberName: *utils.GetRandomName(), - } - - type args struct { - ctx context.Context - covers []profileutils.Cover - } - tests := []struct { - name string - args args - wantErr bool - }{ - { - name: "happy case:) update covers", - args: args{ - ctx: ctx, - covers: []profileutils.Cover{cover}, - }, - wantErr: false, - }, - { - name: "happy case:) update the same covers", - args: args{ - ctx: ctx, - covers: []profileutils.Cover{cover}, - }, - wantErr: false, - }, - { - name: "sad case:( unauthenticated context", - args: args{ - ctx: context.Background(), - covers: []profileutils.Cover{cover}, - }, - wantErr: true, - }, - { - name: "sad case:( update the nil covers", - args: args{ - ctx: ctx, - covers: []profileutils.Cover{}, - }, - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := p.Onboarding.UpdateCovers( - tt.args.ctx, - tt.args.covers, - ); (err != nil) != tt.wantErr { - t.Errorf("ProfileUseCaseImpl.UpdateCovers() error = %v, wantErr %v", - err, - tt.wantErr, - ) - } - profile, err := p.Onboarding.UserProfile(ctx) - if err != nil { - t.Errorf("unable to get user profile") - return - } - - covers := profile.Covers - if len(covers) > 1 { - t.Errorf("expected just one cover") - return - } - }) - } -} - func TestRetireSecondaryPhoneNumbers(t *testing.T) { ctx, _, err := GetTestAuthenticatedContext(t) if err != nil { diff --git a/pkg/onboarding/usecases/signup.go b/pkg/onboarding/usecases/signup.go index 5c8a22b6..b7d7425b 100644 --- a/pkg/onboarding/usecases/signup.go +++ b/pkg/onboarding/usecases/signup.go @@ -14,11 +14,6 @@ import ( "github.com/savannahghi/scalarutils" ) -const ( - // CoverLinkingStatusStarted ... - CoverLinkingStatusStarted = "coverlinking started" -) - // SignUpUseCases represents all the business logic involved in setting up a user type SignUpUseCases interface { // VerifyPhoneNumber checks validity of a phone number by sending an OTP to it diff --git a/pkg/onboarding/usecases/signup_unit_test.go b/pkg/onboarding/usecases/signup_unit_test.go index 7bc63d8f..7fe55419 100644 --- a/pkg/onboarding/usecases/signup_unit_test.go +++ b/pkg/onboarding/usecases/signup_unit_test.go @@ -14,7 +14,6 @@ import ( "github.com/savannahghi/onboarding/pkg/onboarding/domain" "github.com/savannahghi/profileutils" "github.com/savannahghi/scalarutils" - "gitlab.slade360emr.com/go/apiclient" ) func TestSignUpUseCasesImpl_RetirePushToken(t *testing.T) { @@ -1061,13 +1060,6 @@ func TestSignUpUseCasesImpl_CompleteSignup(t *testing.T) { }, nil } - fakeBaseExt.FetchDefaultCurrencyFn = func(c apiclient.Client) (*apiclient.FinancialYearAndCurrency, error) { - id := uuid.New().String() - return &apiclient.FinancialYearAndCurrency{ - ID: &id, - }, nil - } - fakePubSub.TopicIDsFn = func() []string { return []string{uuid.New().String()} } diff --git a/tests/profile_acceptance_test.go b/tests/profile_acceptance_test.go index 8f3ac59f..1cb6a464 100644 --- a/tests/profile_acceptance_test.go +++ b/tests/profile_acceptance_test.go @@ -453,181 +453,6 @@ func TestUserProfile(t *testing.T) { } } -func TestUpdateCovers(t *testing.T) { - client := http.DefaultClient - - phoneNumber := interserviceclient.TestUserPhoneNumber - user, err := CreateTestUserByPhone(t, phoneNumber) - if err != nil { - t.Errorf("failed to create a user by phone %v", err) - return - } - - role, err := CreateTestRole(t, testRoleName) - if err != nil { - t.Errorf("cannot create test role with err: %v", err) - return - } - - _, err = AssignTestRole(t, user.Profile.ID, role.ID) - if err != nil { - t.Errorf("cannot assign test role with err: %v", err) - return - } - - if user == nil { - t.Errorf("nil user found") - return - } - uid := user.Auth.UID - payerName := "Be.Well Payer" - payerSladeCode := 123 - memberName := "Be.Well Member" - memberNumber := "123456" - beneficiaryID := 157858 - effectivePolicyNumber := "14582" - validFromString := "2021-01-01T00:00:00+03:00" - validFrom, err := time.Parse(time.RFC3339, validFromString) - if err != nil { - t.Errorf("failed parse date string: %v", err) - return - } - - validToString := "2022-01-01T00:00:00+03:00" - validTo, err := time.Parse(time.RFC3339, validToString) - if err != nil { - t.Errorf("failed parse date string: %v", err) - return - } - - updateCoversPayload := &dto.UpdateCoversPayload{ - UID: &uid, - PayerName: &payerName, - PayerSladeCode: &payerSladeCode, - MemberName: &memberName, - MemberNumber: &memberNumber, - BeneficiaryID: &beneficiaryID, - EffectivePolicyNumber: &effectivePolicyNumber, - ValidFrom: &validFrom, - ValidTo: &validTo, - } - bs, err := json.Marshal(updateCoversPayload) - if err != nil { - t.Errorf("unable to marshal test item to JSON: %s", err) - } - payload := bytes.NewBuffer(bs) - - emptyData := &dto.UpdateCoversPayload{} - emptyBs, err := json.Marshal(emptyData) - if err != nil { - t.Errorf("unable to marshal test item to JSON: %s", err) - } - emptyPayload := bytes.NewBuffer(emptyBs) - - type args struct { - url string - httpMethod string - body io.Reader - } - tests := []struct { - name string - args args - wantStatus int - wantErr bool - }{ - { - name: "success: update a user's covers", - args: args{ - url: fmt.Sprintf("%s/internal/update_covers", baseURL), - httpMethod: http.MethodPost, - body: payload, - }, - wantStatus: http.StatusOK, - wantErr: false, - }, - { - name: "failure: login user with nil payload supplied", - args: args{ - url: fmt.Sprintf("%s/internal/update_covers", baseURL), - httpMethod: http.MethodPost, - body: emptyPayload, - }, - wantStatus: http.StatusBadRequest, - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r, err := http.NewRequest( - tt.args.httpMethod, - tt.args.url, - tt.args.body, - ) - - if err != nil { - t.Errorf("can't create new request: %v", err) - return - } - - if r == nil { - t.Errorf("nil request") - return - } - - for k, v := range interserviceclient.GetDefaultHeaders(t, baseURL, "onboarding") { - r.Header.Add(k, v) - } - - resp, err := client.Do(r) - if err != nil { - t.Errorf("HTTP error: %v", err) - return - } - if tt.wantStatus != resp.StatusCode { - t.Errorf("expected status %d, got %d", tt.wantStatus, resp.StatusCode) - return - } - dataResponse, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("can't read response body: %v", err) - return - } - if dataResponse == nil { - t.Errorf("nil response body data") - return - } - - data := map[string]interface{}{} - err = json.Unmarshal(dataResponse, &data) - if err != nil { - t.Errorf("bad data returned") - return - } - - if tt.wantErr { - errMsg, ok := data["error"] - if !ok { - t.Errorf("Request error: %s", errMsg) - return - } - } - - if !tt.wantErr { - _, ok := data["error"] - if ok { - t.Errorf("error not expected") - return - } - } - - }) - } - _, err = RemoveTestUserByPhone(t, phoneNumber) - if err != nil { - t.Errorf("unable to remove test user: %s", err) - } -} - func TestEmailsProfileAttributes(t *testing.T) { client := http.DefaultClient phoneNumber := interserviceclient.TestUserPhoneNumber diff --git a/tests/survey_acceptance_test.go b/tests/survey_acceptance_test.go index 7740c545..0467fbfa 100644 --- a/tests/survey_acceptance_test.go +++ b/tests/survey_acceptance_test.go @@ -1,6 +1,7 @@ package tests import ( + "context" "encoding/json" "fmt" "io/ioutil" @@ -8,14 +9,59 @@ import ( "testing" "time" + "github.com/imroc/req" "github.com/savannahghi/firebasetools" - "gitlab.slade360emr.com/go/apiclient" ) +// GetGraphQLHeaders gets relevant GraphQLHeaders +func GetGraphQLHeaders(ctx context.Context) (map[string]string, error) { + authorization, err := GetBearerTokenHeader(ctx) + if err != nil { + return nil, fmt.Errorf("can't Generate Bearer Token: %s", err) + } + return req.Header{ + "Accept": "application/json", + "Content-Type": "application/json", + "Authorization": authorization, + }, nil +} + +// GetBearerTokenHeader gets bearer Token Header +func GetBearerTokenHeader(ctx context.Context) (string, error) { + TestUserEmail := "test@bewell.co.ke" + user, err := firebasetools.GetOrCreateFirebaseUser(ctx, TestUserEmail) + if err != nil { + return "", fmt.Errorf("can't get or create firebase user: %s", err) + } + + if user == nil { + return "", fmt.Errorf("nil firebase user") + } + + customToken, err := firebasetools.CreateFirebaseCustomToken(ctx, user.UID) + if err != nil { + return "", fmt.Errorf("can't create custom token: %s", err) + } + + if customToken == "" { + return "", fmt.Errorf("blank custom token: %s", err) + } + + idTokens, err := firebasetools.AuthenticateCustomFirebaseToken(customToken) + if err != nil { + return "", fmt.Errorf("can't authenticate custom token: %s", err) + } + if idTokens == nil { + return "", fmt.Errorf("nil idTokens") + } + + return fmt.Sprintf("Bearer %s", idTokens.IDToken), nil +} + func TestGraphQLRecordPostVisitSurvey(t *testing.T) { ctx := firebasetools.GetAuthenticatedContext(t) graphQLURL := fmt.Sprintf("%s/%s", baseURL, "graphql") - headers, err := apiclient.GetGraphQLHeaders(ctx) + headers, err := GetGraphQLHeaders(ctx) if err != nil { t.Errorf("error in getting headers: %w", err) return