Exemple #1
0
        public async Task <TDeal> SaveAsync <TDeal>(TDeal deal)
            where TDeal : Deal, new()
        {
            if (deal == null)
            {
                throw new ArgumentNullException(nameof(deal));
            }

            var customProperties = (from property in _typeManager.GetPropertyData(deal)
                                    select new ValuedPropertyV2(property.PropertyName, property.Value?.ToString()))
                                   .ToArray();

            var hasProperties = !customProperties.All(cp => string.IsNullOrEmpty(cp.Value));

            var modifiedAssociations = _typeManager.GetModifiedAssociations(deal).ToNestedLookup(o => o.type, o => o.operation, o => o.id);

            if (!hasProperties && IsNew() && !modifiedAssociations.Any())
            {
                return(deal);
            }

            if (IsNew())
            {
                var newDeal = await _client.Deals.CreateAsync(deal.AssociatedContactIds, deal.AssociatedCompanyIds, customProperties).ConfigureAwait(false);

                return(_typeManager.ConvertTo <TDeal>(newDeal));
            }

            await _client.Deals.UpdateAsync(deal.Id, customProperties).ConfigureAwait(false);

            await _client.Deals.AssociateContactsAsync(deal.Id, modifiedAssociations.GetValues(AssociationType.Contact, Operation.Added)).ConfigureAwait(false);

            await _client.Deals.AssociateCompaniesAsync(deal.Id, modifiedAssociations.GetValues(AssociationType.Company, Operation.Added)).ConfigureAwait(false);

            await _client.Deals.RemoveAssociationToContactsAsync(deal.Id, modifiedAssociations.GetValues(AssociationType.Contact, Operation.Removed)).ConfigureAwait(false);

            await _client.Deals.RemoveAssociationToCompaniesAsync(deal.Id, modifiedAssociations.GetValues(AssociationType.Company, Operation.Removed)).ConfigureAwait(false);

            var updatedDeal = await GetAsync <TDeal>(SelectDeal.ById(deal.Id)).ConfigureAwait(false);

            return(updatedDeal);

            bool IsNew()
            {
                return(deal.Id == 0 && deal.Created == default);
            }
        }
 public static Task <TDeal> GetByIdAsync <TDeal>(this IHubSpotDealConnector connector, long dealId) where TDeal : Deal, new()
 => connector.GetAsync <TDeal>(SelectDeal.ById(dealId));