public async Task verify_contract_status_update_handles_invalid_email_addr()
        {
            var contact = await _contactCreationFixture.CreateTestContact();

            var adapter  = new HubspotAdapter();
            var response = await adapter.UpdateContractStatusAsync("*****@*****.**", "Sent", _logger, isTest : true);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
        public async Task verify_invalid_contract_status_handling()
        {
            var contact = await _contactCreationFixture.CreateTestContact();

            var adapter = new HubspotAdapter();

            Exception ex = await Assert.ThrowsAsync <CrmUpdateHandlerException>(() => adapter.UpdateContractStatusAsync(_contactCreationFixture.TestContactEmail, "Bogus", _logger, isTest: true));

            Assert.Equal("Unrecognised contract status: 'Bogus'", ex.Message);
        }
        public async Task verify_happy_case_contract_rejected_update()
        {
            var contact = await _contactCreationFixture.CreateTestContact();

            var adapter  = new HubspotAdapter();
            var response = await adapter.UpdateContractStatusAsync(_contactCreationFixture.TestContactEmail, "Rejected", _logger, isTest : true);

            Assert.True(string.IsNullOrEmpty(response.ErrorMessage));
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
        /// <summary>
        /// Creates the test contact in the HubSpot sandbox if necessary
        /// </summary>
        /// <returns></returns>
        public async Task <CanonicalContact> CreateTestContact()
        {
            var logger = new Mock <ILogger>();
            var log    = logger.Object;

            // Ensure only one thread can enter this code at a time.
            await semaphoreSlim.WaitAsync();

            try
            {
                if (this.contact == null)
                {
                    const bool installationRecordexists = true;
                    var        adapter = new HubspotAdapter();

                    var contactResult = await adapter.CreateHubspotContactAsync(
                        this.TestContactEmailAddress,
                        "Autocreated",
                        "TestUser",
                        "Auto",
                        "08 123456789",
                        "Unit Test 1",
                        "CrmUpdateHandler St",
                        "Test City",
                        "WA",
                        "6000",
                        "Ready To Engage",
                        installationRecordexists,
                        log,
                        true);

                    if (contactResult.StatusCode == System.Net.HttpStatusCode.Conflict)
                    {
                        // Contact already exists - so just use that one
                        contactResult = await adapter.RetrieveHubspotContactByEmailAddr(this.TestContactEmailAddress, false, log, isTest : true);
                    }

                    if (contactResult.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        log.LogError($"Error {contactResult.StatusCode} creating HubSpot contact: {contactResult.ErrorMessage}");
                        throw new Exception(contactResult.ErrorMessage);
                    }

                    this.contact = contactResult.Payload;
                }

                return(this.contact);
            }
            finally
            {
                //When the task is ready, release the semaphore. It is vital to ALWAYS release the semaphore when we are ready, or else we will end up with a Semaphore that is forever locked.
                //This is why it is important to do the Release within a try...finally clause; program execution may crash or take a different path, this way you are guaranteed execution
                semaphoreSlim.Release();
            }
        }
Exemplo n.º 5
0
        public async Task verify_the_test_contact_is_retrieved_from_hubspot_by_email_addr()
        {
            var logger  = new Mock <ILogger>();
            var contact = await contactCreationFixture.CreateTestContact();

            var adapter = new HubspotAdapter();

            var contactRetrievalResult = await adapter.RetrieveHubspotContactByEmailAddr(
                this.contactCreationFixture.TestContactEmailAddress,
                fetchPreviousValues : true,
                log : logger.Object,
                isTest : true);

            Assert.True(string.IsNullOrEmpty(contactRetrievalResult.ErrorMessage), contactRetrievalResult.ErrorMessage);
            Assert.Equal(200, (int)contactRetrievalResult.StatusCode);
            //Assert.Equal("001551", contactRetrievalResult.Payload.contactId);
        }
        public async Task verify_we_can_update_a_regular_property()
        {
            var contact = await _contactCreationFixture.CreateTestContact();

            var adapter = new HubspotAdapter();
            var props   = new HubSpotContactProperties();

            props.Add("mobilephone", "0499888777");
            props.Add("city", "Update City");
            var response = await adapter.UpdateContactDetailsAsync(_contactCreationFixture.TestContactId, props, _logger, isTest : true);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            response = await adapter.RetrieveHubspotContactById(_contactCreationFixture.TestContactId, false, _logger, isTest : true);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            contact = response.Payload;
            Assert.Equal("Update City", contact.city);
        }
Exemplo n.º 7
0
        public void newContact_Tester()
        {
            var newContactProperties = HubspotAdapter.AssembleContactProperties(
                "*****@*****.**",
                "firstname",
                "lastname",
                "preferredName",
                "08 97561234",
                "123 example St",
                "Apt 5",
                "Bedrock",
                "WA",
                "9943",
                "Unsure",
                true);

            var json = JsonConvert.SerializeObject(newContactProperties);

            Assert.NotNull(json);
        }
Exemplo n.º 8
0
        public async Task Verify_Deal_Creation_Happy_Path()
        {
            var contact = await contactCreationFixture.CreateTestContact();

            var logger = new Mock <ILogger>();

            var adapter = new HubspotAdapter();

            // TODO: Update CreateHubSpotDealAsync so it discovers the pipeline ID and the stageID dynamically
            var dealResponse = await adapter.CreateHubSpotDealAsync(
                Convert.ToInt32(contact.contactId),
                "Automated Integration Test - Delete Me",
                "706439",   // Sales Pipeline 1 - you can see the ID in the URL
                "706470",   // Submitted Contract Information, 706470
                logger.Object,
                isTest : true);

            Assert.NotNull(dealResponse);
            Assert.True(string.IsNullOrEmpty(dealResponse.ErrorMessage), dealResponse.ErrorMessage);
            Assert.Equal(HttpStatusCode.OK, dealResponse.StatusCode);
        }
Exemplo n.º 9
0
        public async Task verify_the_test_contact_is_retrieved_from_hubspot_by_id()
        {
            var logger  = new Mock <ILogger>();
            var contact = await contactCreationFixture.CreateTestContact();

            var adapter = new HubspotAdapter();

            var contactRetrievalResult = await adapter.RetrieveHubspotContactById(
                contact.contactId,
                fetchPreviousValues : true,
                log : logger.Object,
                isTest : true
                );

            Assert.True(string.IsNullOrEmpty(contactRetrievalResult.ErrorMessage), contactRetrievalResult.ErrorMessage);
            Assert.Equal(200, (int)contactRetrievalResult.StatusCode);
            Assert.Equal(this.contactCreationFixture.TestContactEmailAddress, contactRetrievalResult.Payload.email);
            Assert.Equal("Autocreated TestUser", contactRetrievalResult.Payload.fullName);
            Assert.Equal("Autocreated.TestUser", contactRetrievalResult.Payload.fullNamePeriodSeparated);
            Assert.Equal("Unit Test 1, CrmUpdateHandler St\nTest City\nWA 6000", contactRetrievalResult.Payload.customerAddress);
        }
Exemplo n.º 10
0
        public async Task <IActionResult> CreateNewContact(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            [Queue("error-notification")] IAsyncCollector <string> errors,
            [Queue("existing-contact-update-review")] IAsyncCollector <string> updateReviewQueue,
            [Queue("installations-to-be-created")] IAsyncCollector <string> installationsAwaitingCreationQueue,
            ILogger log)
        {
            log.LogInformation("CreateNewCrmContact triggered");

            // Test mode can be turned on by passing ?test, or by running from localhost
            // It will use the Hubspot sandbox via a hapikey override, and return a Contact with a hard-coded crmid=2001
            var test   = req.Query["test"];
            var isTest = test.Count > 0;

            if (req.Host.Host == "localhost")
            {
                isTest = true;
            }

            // Instantiate our convenient wrapper for the error-log queue
            var errQ = new ErrorQueueLogger(errors, "CrmUpdateHandler", nameof(CrmContactCreator));

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            if (string.IsNullOrEmpty(requestBody))
            {
                errQ.LogError("Request body is not empty");
                return(new BadRequestObjectResult("Empty Request Body"));
            }

            // For a while, it will be handy to keep a record of the original JSON in the log files, in
            // case we need to track and fix systemic failures that lay undetected for a while.
            log.LogInformation(requestBody);


            dynamic userdata = JsonConvert.DeserializeObject(requestBody);

            // Test
            //userdata.contact.crmid = 99;
            //var dbg = new StringContent(userdata.ToString());


            // If body is empty or not JSON, just return
            if (userdata == null)
            {
                log.LogWarning("Contact information was empty or not JSON");
                errQ.LogError("Contact information was empty or not JSON");
                return(new OkResult());
            }

            string leadStatus = userdata?.leadStatus;

            string firstname     = userdata?.contact?.firstname;
            string lastname      = userdata?.contact?.lastname;
            string preferredName = userdata?.contact?.firstname;   // initialise the preferred name as the first name
            string email         = userdata?.contact?.email;
            string phone         = userdata?.contact?.phone;

            if (string.IsNullOrEmpty(phone))
            {
                phone = userdata?.contact?.mobilephone;
            }

            string installStreetAddress1 = userdata?.installAddress?.street;
            string installStreetAddress2 = userdata?.installAddress?.unit;
            string installCity           = userdata?.installAddress?.suburb;
            string installState          = userdata?.installAddress?.state;
            string installPostcode       = userdata?.installAddress?.postcode;

            string propertyOwnership = userdata?.property?.propertyOwnership; // "owner" or
            string propertyType      = userdata?.property?.propertyType;      // "business" or
            string abn = userdata?.property?.abn;

            string customerStreetAddress1 = userdata?.signatories?.signer1?.address?.street;
            string customerStreetAddress2 = userdata?.signatories?.signer1?.address?.unit;
            string customerCity           = userdata?.signatories?.signer1?.address?.suburb;
            string customerState          = userdata?.signatories?.signer1?.address?.state;
            string customerPostcode       = userdata?.signatories?.signer1?.address?.postcode;


            string mortgageStatus = userdata?.mortgage?.mortgageStatus; // "yes" / "no"
            string bankName       = userdata?.mortgage?.bankName;       // user-selected bank from the dropdown. Drawn from a Blob which in turns is generated by the Flow called "When BankContactDetails change => update bank-dropdown JSON"
            string bankOther      = userdata?.mortgage?.bankOther;      // if user selected "Other" from the dropdown, this is what they entered
            //string bankBranch = userdata?.mortgage?.bankBranch;   // we don't collect bank branch. That comes from BankContactDetails

            const bool installationRecordExists = true; // inhibit the creation of an Installation record.

            log.LogInformation($"Creating {firstname} {lastname} as {email} {(isTest ? "in test database" : string.Empty)}");

            var crmAccessResult = await this._hubSpotAdapter.CreateHubspotContactAsync(
                email,
                firstname,
                lastname,
                preferredName,
                phone,
                customerStreetAddress1,
                customerStreetAddress2,
                customerCity,
                customerState,
                customerPostcode,
                leadStatus,
                installationRecordExists,
                log,
                isTest);

            // Some failures aren't really failures
            if (crmAccessResult.StatusCode == System.Net.HttpStatusCode.Conflict)
            {
                // A Conflict is not unexpected. However, we can't blindly overwrite existing contact details when we don't know anything
                // about the intentions of the caller. The changes must be Approved by a human.
                // To facilitate the Approval process, we take the original data packet (which has enough information for both a HubSpot
                // contact and an Installation record) and supplement it with a list of changes, which the Approval flow can use to present
                // a nice(ish) UI to the approver. After approval, the packet can then continue to flow (via queues) to process that create
                // installations and effect changes to hubspot contacts

                var orig = crmAccessResult.Payload;
                //var changeList = new List<UpdateReviewChange>();

                // The changelist must serialise to 'nice' JSON. No nulls, else Flow can't parse it.
                var updateReview = new UpdateReview();
                updateReview.AddChange("First", orig.firstName ?? "", firstname ?? "");
                updateReview.AddChange("Last", orig.lastName ?? "", lastname ?? "");
                updateReview.AddChange("Phone", orig.phone ?? "", phone ?? "");
                updateReview.AddChange("Street Address", orig.streetAddress ?? "", (customerStreetAddress1 + " " + customerStreetAddress2).Trim());
                updateReview.AddChange("City", orig.city ?? "", customerCity ?? "");
                updateReview.AddChange("State", orig.state ?? "", customerState ?? "");
                updateReview.AddChange("Postcode", orig.postcode ?? "", customerPostcode ?? "");

                var newLeadStatus = HubspotAdapter.ResolveLeadStatus(leadStatus);
                updateReview.AddChange("Lead status", orig.leadStatus ?? "", newLeadStatus ?? "");

                // Mimic the installation-inhib logic in the original contact-creation code.
                if (newLeadStatus == "READY_TO_ENGAGE")
                {
                    if (orig.leadStatus == "INTERESTED")
                    {
                        // We need to inhibit the creation of an Installation record if this approval goes ahead, to prevent a race condition
                        updateReview.AddChange("installationrecordexists", "", "true");
                    }
                }

                // TODO: Call an installation-details web-service to get these details

                var installAddress = HubspotAdapter.AssembleCustomerAddress(
                    (installStreetAddress1 + " " + installStreetAddress2).Trim(),
                    installCity,
                    installState,
                    installPostcode);

                // TODO: more...including Installation fields...
                updateReview.AddChange("Install Address", "", installAddress ?? "");      // TODO
                updateReview.AddChange("propertyOwnership", "", propertyOwnership ?? ""); // TODO
                updateReview.AddChange("propertyType", "", propertyType ?? "");           // TODO
                updateReview.AddChange("ABN", "", abn ?? "");                             // TODO

                updateReview.AddChange("mortgageStatus", "", mortgageStatus ?? "");       // TODO

                var newBankName = (bankName == "Other") ? bankOther : bankName;
                updateReview.AddChange("bankName", "", newBankName ?? "");  // TODO

                userdata.changes = Newtonsoft.Json.Linq.JToken.FromObject(updateReview.Changes);

                // Prepare the original 'Join' data packet for re-use as an Installation if a
                // human approves the changes. And set an 'updatePermitted' flag that signals
                // to the receiving process that the data has been through a human review, and
                // it's OK to update the Installation if it exists already.
                userdata.contact.crmid   = crmAccessResult.Payload.contactId;
                userdata.sendContract    = true;
                userdata.updatePermitted = true;    // if it passes human approval, then it's OK to update the Installation

                string updateReviewPackage = JsonConvert.SerializeObject(userdata);
                log.LogInformation("For the 'existing-contact-update-review' queue:\n" + updateReviewPackage);

                // Queue the submission for human approval
                await updateReviewQueue.AddAsync(updateReviewPackage);

                // Control now passes to the Flow called on contact-update-review message, where the changes are approved or rejected
                return((ActionResult) new OkResult());
            }
            else if (crmAccessResult.StatusCode != System.Net.HttpStatusCode.OK)
            {
                // This is a real failure. We cannot continue.
                log.LogError($"Error {crmAccessResult.StatusCode} creating HubSpot contact: {crmAccessResult.ErrorMessage}");
                errQ.LogError("Error " + crmAccessResult.StatusCode + " creating HubSpot contact: " + crmAccessResult.ErrorMessage);
                return(new BadRequestObjectResult(crmAccessResult.ErrorMessage));
            }

            log.LogInformation($"{firstname} {lastname} ({email}) created as {crmAccessResult.Payload.contactId}");


            // Now we must create an Installations record by placing a job on the 'installations-to-be-created' queue
            // The structure we place on this queue is the same structure as we receive in this method, with the addition of
            //      (1) the contract.crmid property
            //      (2) a 'sendContract' flag that tells the Installation-creator to send a contract when the Installation record is created
            // NB: 'updatePermitted' is NOT set, because it would be a big surprise worthy of a big error to find an existing
            // Installation in the absence of a HubSpot contact record
            userdata.contact.crmid = crmAccessResult.Payload.contactId;
            userdata.sendContract  = true;

            // Place the augmented join-up data-packet on the queue. It will be picked up by the 'DequeueInstallationsForCreation' function in the
            // PlicoInstallationsHandler solution.
            var msg = JsonConvert.SerializeObject(userdata);
            await installationsAwaitingCreationQueue.AddAsync(msg);

            return((ActionResult) new OkObjectResult(crmAccessResult.Payload));
        }