Skip to main content

UpdateCompaniesHouseSkipStage

public void UpdateCompaniesHouseSkipStage(Entity postImage)
{
// TODO: refactor to remove image and pass in params instead

// Ensure post-image entity is valid
if (postImage == null)
{
throw new ArgumentNullException("postImage cannot be null");
}

tracingService.Trace("Processing post-image for Specific Risk Assessment");

// Retrieve Contact record associated with Specific Risk Assessment
if (!postImage.Contains("tt_contact"))
{
tracingService.Trace("Post-image does not contain 'tt_contact'. Exiting method.");
return;
}

EntityReference contactRef = postImage.GetAttributeValue<EntityReference>("tt_contact");

if (contactRef == null)
{
tracingService.Trace("tt_contact lookup is null. Exiting method.");
return;
}

tracingService.Trace($"Found Contact reference: {contactRef.Id}");

// Retrieve most recently created Companies House Data record associated with Contact
QueryExpression companiesHouseQuery = new QueryExpression("tt_companieshousedata")
{
ColumnSet = new ColumnSet("tt_companieshousedataid", "tt_kycforentitiesskipukbusinesssearchstage"),
Orders = { new OrderExpression("createdon", OrderType.Descending) }
};
companiesHouseQuery.Criteria.AddCondition("tt_contact", ConditionOperator.Equal, contactRef.Id);

EntityCollection companiesHouseRecords = crmService.RetrieveMultiple(companiesHouseQuery);

if (!companiesHouseRecords.Entities.Any())
{
tracingService.Trace("No Companies House Data records found for this Contact.");
return;
}

Entity latestCompaniesHouseRecord = companiesHouseRecords.Entities.First();
tracingService.Trace($"Updating Companies House Data record {latestCompaniesHouseRecord.Id}");

// Retrieve "skip stage" flag from post-image entity
if (!postImage.Contains("tt_kycforentitiesskipukbusinesssearchstage"))
{
tracingService.Trace("Post-image does not contain 'tt_kycforentitiesskipukbusinesssearchstage'. Exiting method.");
return;
}

bool skipStage = postImage.GetAttributeValue<bool>("tt_kycforentitiesskipukbusinesssearchstage");

// Update "tt_kycforentitiesskipukbusinesssearchstage" in Companies House Data record
Entity updateEntity = new Entity("tt_companieshousedata", latestCompaniesHouseRecord.Id)
{
["tt_kycforentitiesskipukbusinesssearchstage"] = skipStage
};

crmService.Update(updateEntity);

tracingService.Trace("Companies House Data record updated successfully.");
}