public void RecalculateAndChangeAgreementPaid(
            RecalculateType type,
            Entities.new_invoice target,
            Entities.new_invoice entityWithData,
            Entities.new_invoice entityWithOldData = null)
        {
            Entities.new_invoice entityToCheckPaid = target.new_fact == null ? entityWithData : target;

            if (IsPaid(entityToCheckPaid))
            {
                RecalculateAgreementAmount(type, entityWithData, entityWithOldData);

                ChangeAgreementPaidState(entityWithData, IsAgreementFullPaid(entityWithData));
            }
        }
        private Money GetRecalculatedMoneyByType(RecalculateType type, Money agreementMoney, Money currentMoney, Money oldMoney)
        {
            Money outMoney = new Money();

            switch (type)
            {
            case RecalculateType.Create:
            {
                decimal diff = currentMoney.Value + agreementMoney.Value;

                outMoney.Value = diff;
                break;
            }

            case RecalculateType.Delete:
            {
                decimal diff = agreementMoney.Value - currentMoney.Value;

                outMoney.Value = diff;
                break;
            }

            case RecalculateType.Update:
            {
                decimal oldDiff = agreementMoney.Value - oldMoney.Value;
                decimal diff    = oldDiff + currentMoney.Value;

                outMoney.Value = diff;
                break;
            }

            default:
            {
                throw new InvalidPluginExecutionException("Not implemented recalculate type");
            }
            }

            return(outMoney);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="entity">Entity with agremeent and amount fields</param>
        private void RecalculateAgreementAmount(RecalculateType type, Entities.new_invoice entity, Entities.new_invoice oldEntity)
        {
            Entities.new_agreement agreement = _OrganizationService.Retrieve(
                entity.new_dogovorid.LogicalName,
                entity.new_dogovorid.Id,
                new ColumnSet(
                    Entities.new_agreement.Fields.new_factsumma)
                ).ToEntity <Entities.new_agreement>();

            Money agreementMoney = agreement.new_factsumma;
            Money currentMoney   = entity.new_amount;
            Money oldMoney       = oldEntity == null ? new Money(0) : oldEntity.new_amount;

            Money recalculatedMoney = GetRecalculatedMoneyByType(type, agreementMoney, currentMoney, oldMoney);

            Entities.new_agreement updatedAgreement = new Entities.new_agreement
            {
                Id            = agreement.Id,
                new_factsumma = recalculatedMoney
            };

            _OrganizationService.Update(updatedAgreement);
        }