public async Task UpdateAsync(CampaignDetails campaign) { var oldCampaign = await _campaignRepository.GetCampaignAsync(campaign.Id.ToGuid()); if (oldCampaign == null) { throw new EntityNotFoundException($"Campaign with id {campaign.Id} does not exist."); } var response = _campaignValidationService.ValidateUpdate(campaign, oldCampaign); if (!response.IsValid) { throw new EntityNotValidException(string.Join(Environment.NewLine, response.ValidationMessages)); } // copy old values to preserve them after update campaign.CreatedBy = oldCampaign.CreatedBy; campaign.CreationDate = oldCampaign.CreationDate; if (campaign.UsePartnerCurrencyRate) { campaign.AmountInTokens = null; campaign.AmountInCurrency = null; } var conditionsToRemove = oldCampaign.Conditions.Where(c1 => campaign.Conditions.All(c2 => c1.Id != c2.Id)); await _conditionService.DeleteAsync(conditionsToRemove); var conditionsToBeChanged = oldCampaign.Conditions.Where(c1 => campaign.Conditions.Any(c2 => c1.Id == c2.Id)).ToList(); foreach (var condition in conditionsToBeChanged) { if (condition.UsePartnerCurrencyRate) { condition.AmountInTokens = null; condition.AmountInCurrency = null; } } await _conditionService.DeleteConditionPartnersAsync(conditionsToBeChanged.Select(c => Guid.Parse(c.Id))); await _conditionService.DeleteConditionAttributesAsync(conditionsToBeChanged.Select(c => Guid.Parse(c.Id))); var contentsToRemove = oldCampaign.Contents.Where(c1 => campaign.Contents.All(c2 => c1.Id != c2.Id)).ToList(); await _earnRuleContentRepository.DeleteAsync(contentsToRemove); foreach (var content in contentsToRemove) { if (content.RuleContentType == RuleContentType.UrlForPicture) { await _fileService.DeleteAsync(content.Id); } } foreach (var condition in campaign.Conditions) { if (condition.RewardRatio != null) { SetRewardThreshold(condition.RewardRatio); } } await _campaignRepository.UpdateAsync(campaign); await PublishCampaignChangeEvent(campaign.Id.ToGuid(), _mapper.Map <CampaignStatus, EventCampaignStatus>(campaign.CampaignStatus), ActionType.Edited); _log.Info($"Campaign was updated: {campaign.ToJson()}", process: nameof(UpdateAsync), context: campaign.Id); }