Ejemplo n.º 1
0
        /// <summary>
        /// Prototype method.  This will eventually take list of guids to update
        /// </summary>
        /// <param name="consumerTrustId"></param>
        private void GetSavingsBalance(Guid consumerTrustId)
        {
            string gcsAccountNumber = String.Empty;

            using (TransactionScope transactionScope = new TransactionScope())
            {
                // This provides a context for any transactions.
                DataModelTransaction dataModelTransaction = DataModelTransaction.Current;
                ConsumerTrustRow     consumerTrustRow     = DataModel.ConsumerTrust.ConsumerTrustKey.Find(consumerTrustId);
                consumerTrustRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                try
                {
                    if (consumerTrustRow.IsSavingsAccountNull() == false)
                    {
                        gcsAccountNumber = consumerTrustRow.SavingsAccount;
                    }
                }
                finally
                {
                    consumerTrustRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
            }

            //If there is no GCS account number then we have no need to continue processing.
            //HACK  add logging for empty account numbers
            if (String.IsNullOrEmpty(gcsAccountNumber) == false)
            {
                Decimal savingsBalance = GetSavingsBalance(gcsAccountNumber);
                if (savingsBalance != -1.0M)
                {
                    UpdateSavingsBalance(consumerTrustId, savingsBalance);
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Update the SavingsBalance
        /// </summary>
        /// <param name="consumerTrustId"></param>
        /// <param name="savingsBalance"></param>
        private void UpdateSavingsBalance(Guid consumerTrustId, decimal savingsBalance)
        {
            // An instance of the data model is required for CRUD operations.
            DataModel dataModel = new DataModel();

            using (TransactionScope transactionScope = new TransactionScope())
            {
                Int64 consumerTrustRowVersion;
                // This provides a context for any transactions.
                DataModelTransaction dataModelTransaction = DataModelTransaction.Current;
                ConsumerTrustRow     consumerTrustRow     = DataModel.ConsumerTrust.ConsumerTrustKey.Find(consumerTrustId);
                consumerTrustRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                try
                {
                    consumerTrustRowVersion = consumerTrustRow.RowVersion;
                }
                finally
                {
                    consumerTrustRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }

                dataModel.UpdateConsumerTrust(
                    null,
                    null,
                    new Object[] { consumerTrustId },
                    null,
                    null,
                    consumerTrustRowVersion,
                    null,
                    savingsBalance,
                    null,
                    null,
                    null);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="consumerTrustRowChangeEventArgs"></param>
        void OnConsumerTrustRowChanged(object sender, ConsumerTrustRowChangeEventArgs consumerTrustRowChangeEventArgs)
        {
            if (consumerTrustRowChangeEventArgs.Action != DataRowAction.Add)
            {
                return;
            }

            // Extract the unique working order identifier from the generic event arguments.  The identifier is needed for the handler that creates crosses
            // when the right conditions occur.
            ConsumerTrustRow consumerTrustRow = consumerTrustRowChangeEventArgs.Row;

            //get the consumerId before the row has a chance to go away
            this.actionQueue.Enqueue(consumerTrustRow.ConsumerTrustId);
        }
Ejemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="consumerTrust"></param>
        /// <returns></returns>
        public static MethodResponseErrorCode UpdateConsumerTrust(ConsumerTrust consumerTrust)
        {
            if (consumerTrust.RowId == Guid.Empty)
            {
                throw new MissingFieldException("RowId is not set");
            }

            lock (DataModel.SyncRoot)
            {
                ConsumerTrustRow row = DataModel.ConsumerTrust.ConsumerTrustKey.Find(consumerTrust.RowId);

                if (TradingSupportWebService.ColumnChanged(row, consumerTrust))
                {
                    return(UpdateConsumerTrust(new ConsumerTrust[] { consumerTrust }));
                }
                else
                {
                    return(null);
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a settlement for a Consumer Trust representative.
        /// </summary>
        /// <param name="consumerTrustNegotiationId">The identifier of the negotiation that has been agreed to by both parties.</param>
        public static void CreateConsumerTrustSettlement(Guid consumerTrustNegotiationId)
        {
            // A reference to the data model is required to query the database within the scope of a transaction.
            DataModel dataModel = new DataModel();

            // The locking model does not provide for recursive reader locks or promoting reader locks to writer locks.  So the data is collected
            // during a phase then the table can be locked determinstically to prevent deadlocks, then the calls to update the data model are made
            // once all the reader locks have been released.  This structure holds the information required for the creation of a settlement record.
            TrustSettlementInfo trustSettlementInfo = new TrustSettlementInfo();

            // Extract the ambient transaction.
            DataModelTransaction dataModelTransaction = DataModelTransaction.Current;

            // These rows will be locked momentarily while the data is collected and released before the actual transaction.
            ConsumerTrustNegotiationRow consumerTrustNegotiationRow = null;
            MatchRow     matchRow         = null;
            MatchRow     contraMatchRow   = null;
            BlotterRow   blotterRow       = null;
            BlotterRow   contraBlotterRow = null;
            DebtClassRow debtClassRow     = null;
            ConsumerDebtNegotiationRow consumerDebtNegotiationRow = null;
            WorkingOrderRow            workingOrderRow            = null;
            SecurityRow      securityRow           = null;
            ConsumerTrustRow consumerTrustRow      = null;
            WorkingOrderRow  contraWorkingOrderRow = null;
            SecurityRow      contraSecurityRow     = null;
            ConsumerDebtRow  consumerDebtRow       = null;
            ConsumerRow      consumerRow           = null;
            CreditCardRow    creditCardRow         = null;

            try
            {
                // The starting point for creating a settlement record is to find the negotiation record that has been agreed to by both parties.
                consumerTrustNegotiationRow = DataModel.ConsumerTrustNegotiation.ConsumerTrustNegotiationKey.Find(consumerTrustNegotiationId);
                consumerTrustNegotiationRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // This is the record used to match this asset against another.
                matchRow = consumerTrustNegotiationRow.MatchRow;
                matchRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // The next step is to find the counter parties matching information which will lead us to the counter parties asset which, in turn, contains
                // more information for the settlement.
                contraMatchRow = DataModel.Match.MatchKey.Find(matchRow.ContraMatchId);
                contraMatchRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // The blotter contains a link to the Debt Class which is where the Payee information is found.
                blotterRow = matchRow.BlotterRow;
                blotterRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // The blotter contains a link to the Debt Class which is where the Payee information is found.
                contraBlotterRow = contraMatchRow.BlotterRow;
                contraBlotterRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // The debt class of the debt holder provides information about the Payee.
                debtClassRow = contraBlotterRow.GetDebtClassRows()[0];
                debtClassRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // The negotiation table has a historical component. Ever time a change is made to the negotiation on either side a completely new record
                // is created to record the change.  While the earlier versions are useful for a historical context and for reports, this console is only
                // interested in the current version of the negotiations.
                Int64 maxVersion = Int64.MinValue;
                foreach (ConsumerDebtNegotiationRow versionRow in contraMatchRow.GetConsumerDebtNegotiationRows())
                {
                    try
                    {
                        versionRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        if (versionRow.Version > maxVersion)
                        {
                            maxVersion = versionRow.Version;
                            consumerDebtNegotiationRow = versionRow;
                        }
                    }
                    finally
                    {
                        versionRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }
                }
                consumerDebtNegotiationRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // The working order record is part of the object oriented path that will lead to the the asset information.  This info is also needed for the
                // settlement record.
                workingOrderRow = matchRow.WorkingOrderRow;
                workingOrderRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // The Security record will lead us to the asset.
                securityRow = workingOrderRow.SecurityRowByFK_Security_WorkingOrder_SecurityId;
                securityRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // This row contains the actual asset that is to be matched.
                consumerTrustRow = securityRow.GetConsumerTrustRows()[0];
                consumerTrustRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // The counter party's asset information is also required.
                contraWorkingOrderRow = contraMatchRow.WorkingOrderRow;
                contraWorkingOrderRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // This will lead to the counter party's asset.
                contraSecurityRow = contraWorkingOrderRow.SecurityRowByFK_Security_WorkingOrder_SecurityId;
                contraSecurityRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // This is the asset belonging to the counter party that has just agreed to a settlement.
                consumerDebtRow = contraSecurityRow.GetConsumerDebtRows()[0];
                consumerDebtRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // This is the Debt Negotiator's version of the Consumer will be used to settle the account.
                consumerRow = consumerTrustRow.ConsumerRow;
                consumerRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // We also need to know which credit card was settled.
                creditCardRow = consumerDebtRow.CreditCardRow;
                creditCardRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                // These values are extracted from the data model while reader locks are in place on the related records.  Since the locks aren't recursive
                // and reader locks can't be promoted, any locks held for this collection process must be released before the middle tier methods are
                // called to create the record.
                trustSettlementInfo.AccountBalance              = consumerDebtNegotiationRow.AccountBalance;
                trustSettlementInfo.BlotterId                   = contraWorkingOrderRow.BlotterId;
                trustSettlementInfo.ConsumerTrustNegotiationId  = consumerDebtNegotiationRow.ConsumerDebtNegotiationId;
                trustSettlementInfo.ConsumerTrustSettlementId   = Guid.NewGuid();
                trustSettlementInfo.ContraMatchId               = contraMatchRow.MatchId;
                trustSettlementInfo.ContraMatchRowVersion       = contraMatchRow.RowVersion;
                trustSettlementInfo.CreatedTime                 = DateTime.UtcNow;
                trustSettlementInfo.CreatedUserId               = TradingSupport.DaemonUserId;
                trustSettlementInfo.DebtorAccountNumber         = creditCardRow.AccountNumber;
                trustSettlementInfo.DebtorAddress1              = consumerRow.IsAddress1Null() ? null : consumerRow.Address1;
                trustSettlementInfo.DebtorAddress2              = consumerRow.IsAddress2Null() ? null : consumerRow.Address2;
                trustSettlementInfo.DebtorBankAccountNumber     = consumerRow.IsBankAccountNumberNull() ? null : consumerRow.BankAccountNumber;
                trustSettlementInfo.DebtorBankRoutingNumber     = consumerRow.IsBankRoutingNumberNull() ? null : consumerRow.BankRoutingNumber;
                trustSettlementInfo.DebtorFirstName             = consumerRow.IsFirstNameNull() ? null : consumerRow.FirstName;
                trustSettlementInfo.DebtorLastName              = consumerRow.IsLastNameNull() ? null : consumerRow.LastName;
                trustSettlementInfo.DebtorMiddleName            = consumerRow.IsMiddleNameNull() ? null : consumerRow.MiddleName;
                trustSettlementInfo.DebtorOriginalAccountNumber = creditCardRow.OriginalAccountNumber;
                trustSettlementInfo.DebtorSalutation            = consumerRow.IsSalutationNull() ? null : consumerRow.Salutation;
                trustSettlementInfo.DebtorSuffix                = consumerRow.IsSuffixNull() ? null : consumerRow.Suffix;
                trustSettlementInfo.DebtorCity                  = consumerRow.IsCityNull() ? null : consumerRow.City;
                trustSettlementInfo.DebtorProvinceId            = consumerRow.IsProvinceIdNull() ? null : (Object)consumerRow.ProvinceId;
                trustSettlementInfo.DebtorPostalCode            = consumerRow.IsPostalCodeNull() ? null : consumerRow.PostalCode;
                trustSettlementInfo.DebtStatusId                = contraMatchRow.StatusId;
                trustSettlementInfo.MatchId                = matchRow.MatchId;
                trustSettlementInfo.MatchRowVersion        = matchRow.RowVersion;
                trustSettlementInfo.ModifiedTime           = trustSettlementInfo.CreatedTime;
                trustSettlementInfo.ModifiedUserId         = trustSettlementInfo.CreatedUserId;
                trustSettlementInfo.PayeeAddress1          = debtClassRow.IsAddress1Null() ? null : debtClassRow.Address1;
                trustSettlementInfo.PayeeAddress2          = debtClassRow.IsAddress2Null() ? null : debtClassRow.Address2;
                trustSettlementInfo.PayeeBankAccountNumber = debtClassRow.IsBankAccountNumberNull() ? null : debtClassRow.BankAccountNumber;
                trustSettlementInfo.PayeeBankRoutingNumber = debtClassRow.IsBankRoutingNumberNull() ? null : debtClassRow.BankRoutingNumber;
                trustSettlementInfo.PayeeCity              = debtClassRow.IsCityNull() ? null : debtClassRow.City;
                trustSettlementInfo.PayeeCompanyName       = debtClassRow.IsCompanyNameNull() ? null : debtClassRow.CompanyName;
                trustSettlementInfo.PayeeContactName       = debtClassRow.IsContactNameNull() ? null : debtClassRow.ContactName;
                trustSettlementInfo.PayeeDepartment        = debtClassRow.IsDepartmentNull() ? null : debtClassRow.Department;
                trustSettlementInfo.PayeeEmail             = debtClassRow.IsEmailNull() ? null : debtClassRow.Email;
                trustSettlementInfo.PayeeFax               = debtClassRow.IsFaxNull() ? null : debtClassRow.Fax;
                trustSettlementInfo.PayeeForBenefitOf      = debtClassRow.IsForBenefitOfNull() ? null : debtClassRow.ForBenefitOf;
                trustSettlementInfo.PayeePhone             = debtClassRow.IsPhoneNull() ? null : debtClassRow.Phone;
                trustSettlementInfo.PayeeProvinceId        = debtClassRow.IsProvinceIdNull() ? null : (Object)debtClassRow.ProvinceId;
                trustSettlementInfo.PayeePostalCode        = debtClassRow.IsPostalCodeNull() ? null : debtClassRow.PostalCode;
                trustSettlementInfo.PaymentLength          = consumerDebtNegotiationRow.OfferPaymentLength;
                trustSettlementInfo.TrustStatusId          = matchRow.StatusId;

                // The payment methods acceptable for this settlement is the union of the payment methods acceptable to both sides.
                foreach (ConsumerDebtNegotiationOfferPaymentMethodRow consumerDebtNegotiationOfferPaymentMethodRow
                         in consumerDebtNegotiationRow.GetConsumerDebtNegotiationOfferPaymentMethodRows())
                {
                    try
                    {
                        // The payment method needs to be locked while we check the counter party to see what types of payment methods are used there.
                        consumerDebtNegotiationOfferPaymentMethodRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                        // This loop will compare all of the counter party's acceptable payment methods against the current one offered by the
                        // Debt Holder.  If there are any that are compatible, they are moved to a list that is used to generate the settlement.
                        foreach (ConsumerTrustNegotiationOfferPaymentMethodRow consumerTrustNegotiationOfferPaymentMethodRow
                                 in consumerTrustNegotiationRow.GetConsumerTrustNegotiationOfferPaymentMethodRows())
                        {
                            try
                            {
                                // Lock each of the counter party payment methods while a compatible one is found.
                                consumerTrustNegotiationOfferPaymentMethodRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                                // All compatible payment methods between the parties become part of the settlement information.
                                if (consumerDebtNegotiationOfferPaymentMethodRow.PaymentMethodTypeId ==
                                    consumerTrustNegotiationOfferPaymentMethodRow.PaymentMethodTypeId)
                                {
                                    trustSettlementInfo.PaymentMethods.Add(
                                        new PaymentMethodInfo(Guid.NewGuid(), consumerTrustNegotiationOfferPaymentMethodRow.PaymentMethodTypeId));
                                }
                            }
                            finally
                            {
                                // The counter party payment method is no longer needed.
                                consumerTrustNegotiationOfferPaymentMethodRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                            }
                        }
                    }
                    finally
                    {
                        // This payment method is no longer needed.
                        consumerDebtNegotiationOfferPaymentMethodRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }
                }

                // This will calculate the amount of time until the first payment based on the amount of time in the negotiation and the time units.
                TimeUnitRow timeUnitRow = DataModel.TimeUnit.TimeUnitKey.Find(consumerDebtNegotiationRow.OfferPaymentStartDateUnitId);
                try
                {
                    timeUnitRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                    trustSettlementInfo.PaymentStartDate = CommonConversion.ToDateTime(
                        consumerDebtNegotiationRow.OfferPaymentStartDateLength,
                        timeUnitRow.TimeUnitCode);
                }
                finally
                {
                    timeUnitRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }

                // This will calculate the real value of the settlement from the negotiated parameters.  All settlements are in terms of market value while
                // the negotiations may take place in terms of percentages, market value or basis points.
                SettlementUnitRow settlementUnitRow = consumerDebtNegotiationRow.SettlementUnitRowByFK_SettlementUnit_ConsumerDebtNegotiation_OfferSettlementUnitId;
                try
                {
                    // Lock the SettlementUnit row down while the actual settlement value is calculated.
                    settlementUnitRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                    // This will calclate the actual settlement value from the negotiated value and the units used to negotiate.
                    switch (settlementUnitRow.SettlementUnitCode)
                    {
                    case SettlementUnit.BasisPoint:

                        trustSettlementInfo.SettlementAmount = Math.Round(
                            consumerDebtNegotiationRow.AccountBalance * consumerDebtNegotiationRow.OfferSettlementValue, 2);
                        break;

                    case SettlementUnit.MarketValue:

                        trustSettlementInfo.SettlementAmount = consumerDebtNegotiationRow.OfferSettlementValue;
                        break;

                    case SettlementUnit.Percent:

                        trustSettlementInfo.SettlementAmount = Math.Round(
                            consumerDebtNegotiationRow.AccountBalance * consumerDebtNegotiationRow.OfferSettlementValue, 2);
                        break;
                    }
                }
                finally
                {
                    // The SettlementUnit row is no longer needed.
                    settlementUnitRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }

                // The 'Accepted' status indicates that one side of the negotiation has accepted the offer.
                StatusRow acceptedStatusRow = DataModel.Status.StatusKeyStatusCode.Find(Status.Accepted);
                try
                {
                    acceptedStatusRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                    trustSettlementInfo.AcceptedStatusId = acceptedStatusRow.StatusId;
                }
                finally
                {
                    acceptedStatusRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }

                // The 'New' status is use for all freshly crated settlements.  This state is used to tell the settlement engine that a settlement document
                // should be created from the parameters.
                StatusRow newStatusRow = DataModel.Status.StatusKeyStatusCode.Find(Status.New);
                try
                {
                    newStatusRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                    trustSettlementInfo.NewStatusId = newStatusRow.StatusId;
                }
                finally
                {
                    newStatusRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }

                // The 'Locked' status indicates that one side of the negotiation has accepted the offer.
                StatusRow offerAcceptedStatusRow = DataModel.Status.StatusKeyStatusCode.Find(Status.OfferAccepted);
                try
                {
                    offerAcceptedStatusRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                    trustSettlementInfo.OfferAcceptedStatusId = offerAcceptedStatusRow.StatusId;
                }
                finally
                {
                    offerAcceptedStatusRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }

                // The 'Pending' status indicates that one side of the negotiation has accepted the offer.
                StatusRow pendingStatusRow = DataModel.Status.StatusKeyStatusCode.Find(Status.Pending);
                try
                {
                    pendingStatusRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                    trustSettlementInfo.PendingStatusId = pendingStatusRow.StatusId;
                }
                finally
                {
                    pendingStatusRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
            }
            finally
            {
                // Release the record locks.
                if (consumerTrustNegotiationRow != null)
                {
                    consumerTrustNegotiationRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (matchRow != null)
                {
                    matchRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (contraMatchRow != null)
                {
                    contraMatchRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (blotterRow != null)
                {
                    blotterRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (contraBlotterRow != null)
                {
                    contraBlotterRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (debtClassRow != null)
                {
                    debtClassRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (consumerDebtNegotiationRow != null)
                {
                    consumerDebtNegotiationRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (workingOrderRow != null)
                {
                    workingOrderRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (securityRow != null)
                {
                    securityRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (consumerTrustRow != null)
                {
                    consumerTrustRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (contraWorkingOrderRow != null)
                {
                    contraWorkingOrderRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (contraSecurityRow != null)
                {
                    contraSecurityRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (consumerDebtRow != null)
                {
                    consumerDebtRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (consumerRow != null)
                {
                    consumerRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
                if (creditCardRow != null)
                {
                    creditCardRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
            }

            // Nothing is done if this order has already been settled.
            if (trustSettlementInfo.TrustStatusId == trustSettlementInfo.AcceptedStatusId)
            {
                return;
            }

            // Nothing is done if this side has already accepted the negotiation and is waiting for the other side to respond.
            if (trustSettlementInfo.TrustStatusId == trustSettlementInfo.PendingStatusId)
            {
                return;
            }

            // Busines Rule #1: Don't allow a settlement if the payment methods are not compatible.
            if (trustSettlementInfo.PaymentMethods.Count == 0)
            {
                throw new FaultException <PaymentMethodFault>(new PaymentMethodFault("The negotiation doesn't contain compatible payment methods."));
            }

            // Busines Rule #2: Insure there is a Payee Address
            if (trustSettlementInfo.PayeeAddress1 == null)
            {
                throw new FaultException <ArgumentFault>(new ArgumentFault("The Payee Address was not provided."));
            }
            // Busines Rule #2: Insure there is a Payee City
            if (trustSettlementInfo.PayeeCity == null)
            {
                throw new FaultException <ArgumentFault>(new ArgumentFault("The Payee City was not provided."));
            }

            // Busines Rule #3: Insure there is a Payee Province
            if (trustSettlementInfo.PayeeProvinceId == null)
            {
                throw new FaultException <ArgumentFault>(new ArgumentFault("The Payee Province was not provided."));
            }

            // Busines Rule #4: Insure there is a Payee Company Name
            if (String.IsNullOrEmpty((String)trustSettlementInfo.PayeeCompanyName))
            {
                throw new FaultException <ArgumentFault>(new ArgumentFault("The Payee Company Name was not provided."));
            }

            // Busines Rule #5: Insure there is a Debtor City
            if (String.IsNullOrEmpty((String)trustSettlementInfo.DebtorAddress1))
            {
                throw new FaultException <ArgumentFault>(new ArgumentFault("The Debtor Address was not provided."));
            }

            // Busines Rule #5: Insure there is a Debtor City
            if (String.IsNullOrEmpty((String)trustSettlementInfo.DebtorCity))
            {
                throw new FaultException <ArgumentFault>(new ArgumentFault("The Debtor City was not provided."));
            }

            // Busines Rule #6: Insure there is a Debtor Province
            if (trustSettlementInfo.DebtorProvinceId == null)
            {
                throw new FaultException <ArgumentFault>(new ArgumentFault("The Debtor State was not provided."));
            }

            // Busines Rule #7: Insure there is a first or last name.
            if (String.IsNullOrEmpty((String)trustSettlementInfo.DebtorFirstName) && String.IsNullOrEmpty((String)trustSettlementInfo.DebtorLastName))
            {
                throw new FaultException <ArgumentFault>(new ArgumentFault("The Debtor Name was not provided."));
            }

            // Only when the Consumer Debt side is awaiting a settlement is the settlement generated.
            if (trustSettlementInfo.DebtStatusId == trustSettlementInfo.PendingStatusId)
            {
                // The state of the Match must be updated to reflect that this record is no longer available for negotiation.
                dataModel.UpdateMatch(
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    new Object[] { trustSettlementInfo.MatchId },
                    trustSettlementInfo.MatchRowVersion,
                    trustSettlementInfo.AcceptedStatusId,
                    null);

                // The contra is also updated to reflect the settled state of this negotiation.
                dataModel.UpdateMatch(
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    new Object[] { trustSettlementInfo.ContraMatchId },
                    trustSettlementInfo.ContraMatchRowVersion,
                    trustSettlementInfo.AcceptedStatusId,
                    null);

                // This records the terms of the settlement between the Consumer Trust account and the Consumer Debt account.
                dataModel.CreateConsumerDebtSettlement(
                    trustSettlementInfo.AccountBalance,
                    trustSettlementInfo.BlotterId,
                    trustSettlementInfo.ConsumerTrustNegotiationId,
                    trustSettlementInfo.ConsumerTrustSettlementId,
                    trustSettlementInfo.CreatedTime,
                    trustSettlementInfo.CreatedUserId,
                    trustSettlementInfo.DebtorAccountNumber,
                    trustSettlementInfo.DebtorAddress1,
                    trustSettlementInfo.DebtorAddress2,
                    trustSettlementInfo.DebtorBankAccountNumber,
                    trustSettlementInfo.DebtorBankRoutingNumber,
                    trustSettlementInfo.DebtorCity,
                    trustSettlementInfo.DebtorFirstName,
                    trustSettlementInfo.DebtorLastName,
                    trustSettlementInfo.DebtorMiddleName,
                    trustSettlementInfo.DebtorOriginalAccountNumber,
                    trustSettlementInfo.DebtorPostalCode,
                    trustSettlementInfo.DebtorProvinceId,
                    trustSettlementInfo.DebtorSalutation,
                    trustSettlementInfo.DebtorSuffix,
                    null,
                    trustSettlementInfo.ModifiedTime,
                    trustSettlementInfo.ModifiedUserId,
                    trustSettlementInfo.PayeeAddress1,
                    trustSettlementInfo.PayeeAddress2,
                    trustSettlementInfo.PayeeBankAccountNumber,
                    trustSettlementInfo.PayeeBankRoutingNumber,
                    trustSettlementInfo.PayeeCity,
                    trustSettlementInfo.PayeeCompanyName,
                    trustSettlementInfo.PayeeContactName,
                    trustSettlementInfo.PayeeDepartment,
                    trustSettlementInfo.PayeeEmail,
                    trustSettlementInfo.PayeeFax,
                    trustSettlementInfo.PayeeForBenefitOf,
                    trustSettlementInfo.PayeePhone,
                    trustSettlementInfo.PayeePostalCode,
                    trustSettlementInfo.PayeeProvinceId,
                    trustSettlementInfo.PaymentLength,
                    trustSettlementInfo.PaymentStartDate,
                    trustSettlementInfo.SettlementAmount,
                    null,
                    trustSettlementInfo.NewStatusId);

                // Each of the acceptable payment methods is also written as part of this transaction.
                foreach (PaymentMethodInfo paymentMethodInfo in trustSettlementInfo.PaymentMethods)
                {
                    dataModel.CreateConsumerDebtSettlementPaymentMethod(
                        trustSettlementInfo.BlotterId,
                        trustSettlementInfo.ConsumerTrustSettlementId,
                        paymentMethodInfo.ConsumerTrustSettlementPaymentMethodId,
                        paymentMethodInfo.PaymentMethodId);
                }
            }
            else
            {
                // At this point, the other party has not yet accepted the offer so we set the status of the Match and wait.
                dataModel.UpdateMatch(
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    new Object[] { trustSettlementInfo.MatchId },
                    trustSettlementInfo.MatchRowVersion,
                    trustSettlementInfo.PendingStatusId,
                    null);

                // The counter party must be advised that they can not alter the state of the settlement once it has been accepted.
                dataModel.UpdateMatch(
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    new Object[] { trustSettlementInfo.ContraMatchId },
                    trustSettlementInfo.ContraMatchRowVersion,
                    trustSettlementInfo.OfferAcceptedStatusId,
                    null);
            }
        }
        /// <summary>
        /// Delete a debt holder
        /// </summary>
        /// <returns>True for sucess</returns>
        public override ErrorCode Delete(ConsumerTrust record)
        {
            DataModel            dataModel   = new DataModel();
            DataModelTransaction transaction = DataModelTransaction.Current;

            if (record.RowId == null || DataModel.ConsumerTrust.ConsumerTrustKey.Find(record.RowId) == null)
            {
                return(ErrorCode.RecordNotFound);
            }

            ConsumerTrustRow consumerTrust = DataModel.ConsumerTrust.ConsumerTrustKey.Find(record.RowId);

            consumerTrust.AcquireReaderLock(transaction);
            Guid        debtId   = consumerTrust.ConsumerTrustId;
            ConsumerRow consumer = consumerTrust.ConsumerRow;
            DebtRuleRow debtRule = consumerTrust.DebtRuleRow;

            consumerTrust.ReleaseReaderLock(transaction.TransactionId);

#if false   // If we switch from explicitly deleting the working order to explicitly deleting the security, then we need this.
            if (!TradingSupport.HasAccess(transaction, debtId, AccessRight.Write))
            {
                return(ErrorCode.AccessDenied);
            }
#endif

            consumerTrust.AcquireWriterLock(transaction);
            if (consumerTrust.RowState != DataRowState.Deleted && consumerTrust.RowState != DataRowState.Detached)
            {
                dataModel.DestroyConsumerTrust(new object[] { consumerTrust.ConsumerTrustId }, record.RowVersion);
            }
            consumerTrust.ReleaseWriterLock(transaction.TransactionId);

            consumer.AcquireWriterLock(transaction);
            if (consumer.RowState != DataRowState.Deleted && consumer.RowState != DataRowState.Detached)
            {
                dataModel.DestroyConsumer(new object[] { consumer.ConsumerId }, consumer.RowVersion);
            }
            consumer.ReleaseWriterLock(transaction.TransactionId);

            if (debtRule != null)
            {
                debtRule.AcquireReaderLock(transaction);
                if (debtRule.RowState != DataRowState.Deleted && debtRule.RowState != DataRowState.Detached && debtRule.GetDebtRuleMapRows().Length == 0)
                {
                    DebtRulePersistence debtRulePersistence = new DebtRulePersistence();
                    Guid debtRuleId = debtRule.DebtRuleId;
                    long rowVersion = debtRule.RowVersion;
                    debtRule.ReleaseReaderLock(transaction.TransactionId);
                    debtRulePersistence.Delete(new Records.DebtRule {
                        RowId = debtRuleId, RowVersion = rowVersion
                    });
                }
                else
                {
                    debtRule.ReleaseReaderLock(transaction.TransactionId);
                }
            }

            return(ErrorCode.Success);
        }
Ejemplo n.º 7
0
        public ConsumerTrustMatchInfo(DataModelTransaction dataModelTransaction, WorkingOrderRow workingOrderRow)
        {
            // Initialize the object
            this.PaymentMethodTypes = new List <Guid>();

            // These rows are required for navigating through the asset.  Locks are acquired temporarily for them and released as soon as the Consumer Debt
            // information is collected.
            BlotterRow       blotterRow       = null;
            SecurityRow      securityRow      = null;
            ConsumerTrustRow consumerTrustRow = null;

            // The working order row is where everything starts. This is the asset that is to be matched against another.
            workingOrderRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

            try
            {
                // The working order identifier is used when creating matches.
                this.WorkingOrderId = workingOrderRow.WorkingOrderId;
                // The underlying security is a Consumer Debt record.
                securityRow = workingOrderRow.SecurityRowByFK_Security_WorkingOrder_SecurityId;

                // The blotter row needs to be examined for this cross.
                blotterRow = workingOrderRow.BlotterRow;
            }
            finally
            {
                workingOrderRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
            }


            securityRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
            try
            {
                consumerTrustRow = securityRow.GetConsumerTrustRows()[0];
            }
            finally
            {
                securityRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
            }


            DebtRuleRow debtRuleRow = null;

            // This row contains the actual asset that is to be matched.
            consumerTrustRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
            try
            {
                // The savings balance is used when calculating the status of the match (whether there is enough funds in the account).
                this.SavingsBalance = consumerTrustRow.SavingsBalance;

                if (consumerTrustRow.IsDebtRuleIdNull() == false)
                {
                    // At this point a rule override was found on an asset and there's no need to search the Entity hierarchy.
                    debtRuleRow = consumerTrustRow.DebtRuleRow;
                }
            }
            finally
            {
                consumerTrustRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
            }

            // This will attempt to find the debt rule associated with this credit card.  If there is no rule explicitly associated with the asset,
            // then the entity hierarchy is searched until a debt class is found that contains a rule.  When the rule is found, the values in that rule
            // will become the opening bid.
            DebtClassRow[] blotterRowDebtClassRows = null;
            blotterRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
            try
            {
                // The blotter is required for adding matches to the data model once they are found.
                this.BlotterId = blotterRow.BlotterId;

                if (debtRuleRow == null)
                {
                    blotterRowDebtClassRows = blotterRow.GetDebtClassRows();
                }
            }
            finally
            {
                blotterRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
            }

            if (debtRuleRow == null)
            {
                // At this point, the asset hasn't got an explicit rule, so the hierarchy will need to be searched.  There is only going to be one Debt
                // Class element associated with this blotter, but the iteration is an easier construct to work with than the equivalent array logic
                // for a single element.
                foreach (DebtClassRow debtClassRow in blotterRowDebtClassRows)
                {
                    // This variable will keep track of our current location as we crawl up the hierarchy.
                    DebtClassRow currentDebtClassRow = debtClassRow;
                    DebtClassRow nextDebtClassRow    = null;

                    // This will crawl up the hierarchy until a Debt Class is found with a rule.  This rule will provide the opening values for the
                    // bid on this negotiation.
                    do
                    {
                        // This will lock the current item in the hierarchy so it can be examined for a rule or, failing that, a parent element.
                        currentDebtClassRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        Guid currentDebtClassRowDebtClassId;
                        try
                        {
                            currentDebtClassRowDebtClassId = currentDebtClassRow.DebtClassId;
                            if (currentDebtClassRow.IsDebtRuleIdNull() == false)
                            {
                                // At this point we have finally found a debt rule that can be used to start the negotiations.
                                debtRuleRow = currentDebtClassRow.DebtRuleRow;
                            }
                        }
                        finally
                        {
                            // The current Debt Class can be released.  At this point, every record that was locked to read the hiearchy has been
                            // released and the loop can either exit (when a rule is found) or move on to the parent Debt Class.
                            currentDebtClassRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                        // If the current Debt Class has no rule then the Entity Hierarchy is used to find the parent element.
                        if (debtRuleRow == null)
                        {
                            EntityTreeRow[] entityTreeRows;
                            // The entity is the root of all objects in the hierarchy.  From this object the path to the parent Debt Class can be
                            // navigated.
                            EntityRow entityRow = DataModel.Entity.EntityKey.Find(currentDebtClassRowDebtClassId);

                            // Each entity needs to be locked before the relation can be used.
                            entityRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                            try
                            {
                                entityTreeRows = entityRow.GetEntityTreeRowsByFK_Entity_EntityTree_ChildId();
                            }
                            finally
                            {
                                // Finaly, the current entity is released.  This allows us to finally move on to the next level of the hierarchy
                                // without having to hold the locks for the entire transaction.
                                entityRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                            }

                            // This will find each relation in the hierarchy which uses the current node as a child.
                            foreach (EntityTreeRow entityTreeRow in entityTreeRows)
                            {
                                EntityRow parentEntityRow;
                                // Lock the relation down before navigating to the parent.
                                entityTreeRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                                try
                                {
                                    // This is the parent entity of the current entity in the crawl up the hierarchy.
                                    parentEntityRow = entityTreeRow.EntityRowByFK_Entity_EntityTree_ParentId;
                                }
                                finally
                                {
                                    // The relationship record is released after each level of the hierarchy is examined for a parent.
                                    entityTreeRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                                }

                                BlotterRow[] blotterRows;
                                // The parent entity must be locked befor it can be checked for blotters and then, in turn, debt
                                // classes.
                                parentEntityRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                                try
                                {
                                    blotterRows = parentEntityRow.GetBlotterRows();
                                }
                                finally
                                {
                                    // The parent Entity record is released after each level of the hiearchy is examined for a parent.
                                    parentEntityRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                                }


                                // In practice, there will be zero or one blotter rows.  The iteration makes it easier to check both
                                // conditions.
                                foreach (BlotterRow parentBlotterRow in blotterRows)
                                {
                                    DebtClassRow[] parentBlotterRowDebtClassRows;
                                    // The blotter must be locked before iterating through the Debt Classes that may be associated
                                    // with the blotter.
                                    parentBlotterRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                                    try
                                    {
                                        parentBlotterRowDebtClassRows = parentBlotterRow.GetDebtClassRows();
                                    }
                                    finally
                                    {
                                        // The locks are released after the each level of the hierarchy is checked.
                                        parentBlotterRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                                    }

                                    // Each blotter can have zero or one Debt Classes associated with it.  This is a long an
                                    // tortuous way to finally get to the parent Debt Class.
                                    foreach (DebtClassRow parentDebtClassRow in parentBlotterRowDebtClassRows)
                                    {
                                        // Now that we've finally found the parent Debt Class, it will become the parent on
                                        // the next pass through the hierarchy.  Note that the locks are released each time we
                                        // pass through a level of the hierarchy.
                                        nextDebtClassRow = parentDebtClassRow;
                                    }
                                }
                            }
                        }

                        // Now that all the locks are released, the parent Debt Class becomes the current one for the next level up in the hierarchy.
                        // This algorithm will keep on climbing through the levels until a rule is found or the hierarchy is exhausted.
                        currentDebtClassRow = nextDebtClassRow;
                    } while(debtRuleRow == null && currentDebtClassRow != null);
                }
            }

            // The data is copied out of the Debt Rule when one is found in the Entity hierarchy.
            if (debtRuleRow != null)
            {
                DebtRulePaymentMethodRow[] debtRuleRowDebtRulePaymentMethodRows;
                // At this point we found a rule that can be used for the opening bid of a settlement.
                debtRuleRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                try
                {
                    // These values are used in the opening bid of a negotiated settlement.
                    this.PaymentLength          = debtRuleRow.PaymentLength;
                    this.PaymentStartDateLength = debtRuleRow.PaymentStartDateLength;
                    this.PaymentStartDateUnitId = debtRuleRow.PaymentStartDateUnitId;
                    this.SettlementValue        = debtRuleRow.SettlementValue;
                    this.SettlementUnitId       = debtRuleRow.SettlementUnitId;

                    debtRuleRowDebtRulePaymentMethodRows = debtRuleRow.GetDebtRulePaymentMethodRows();
                }
                finally
                {
                    // A lock on the Debt Rule is no longer required.
                    debtRuleRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }


                // This will copy each of the payment methods that are available for this settlement.  Note that the table rows are locked only long
                // enough to acquire the item, then released.
                foreach (DebtRulePaymentMethodRow debtRulePaymentMethodRow in debtRuleRowDebtRulePaymentMethodRows)
                {
                    debtRulePaymentMethodRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                    try
                    {
                        this.PaymentMethodTypes.Add(debtRulePaymentMethodRow.PaymentMethodTypeId);
                    }
                    finally
                    {
                        debtRulePaymentMethodRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }
                }
            }
        }
        /// <summary>
        /// Update a consumer.
        /// </summary>
        /// <param name="entity">The ConsumerTrust's Entity row.</param>
        /// <returns>The ConsumerId of the Consumer row.</returns>
        private Guid UpdateConsumer(EntityRow entity)
        {
            DataModel            dataModel            = new DataModel();
            DataModelTransaction dataModelTransaction = DataModelTransaction.Current;
            DateTime             modified             = DateTime.UtcNow;
            CountryRow           country;
            Guid             countryId;
            Guid?            provinceId = null;
            EntityRow        dollars;
            Guid             dollarsId;
            ConsumerRow      consumer      = null;
            ConsumerTrustRow consumerTrust = null;
            SecurityRow      security      = null;
            WorkingOrderRow  workingOrder  = null;

            MatchRow[] matches;
            Guid       consumerId;
            Guid       consumerTrustId;
            Guid       entityId;
            Guid       securityId;
            Guid       workingOrderId;
            Int64      consumerVersion;
            Int64      consumerTrustVersion;
            Int64      entityVersion;
            Int64      securityVersion;
            Int64      workingOrderVersion;
            Boolean    updateConsumer      = false;
            Boolean    updateConsumerTrust = false;
            Boolean    updateEntity        = false;
            Boolean    updateSecurity      = false;

            country = TradingSupport.FindCountryByKey(
                this.Record.ConfigurationId,
                "FK_Country_Security",
                new object[] { this.Record.CountryCode });
            countryId = country.CountryId;
            country.ReleaseReaderLock(dataModelTransaction.TransactionId);

            if (this.Record.ProvinceCode != null)
            {
                ProvinceRow province = TradingSupport.FindProvinceByKey(
                    this.Record.ConfigurationId,
                    "FK_Province_Consumer",
                    new object[] { this.Record.ProvinceCode });
                provinceId = province.ProvinceId;
                province.ReleaseReaderLock(dataModelTransaction.TransactionId);
            }

            dollars = TradingSupport.FindEntityByKey(
                this.Record.ConfigurationId,
                "FK_Security_WorkingOrder_SettlementId",
                new object[] { this.Record.Currency });
            dollarsId = dollars.EntityId;
            dollars.ReleaseReaderLock(dataModelTransaction.TransactionId);

            try
            {
                entity.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                entityId      = entity.EntityId;
                entityVersion = entity.RowVersion;
                if (TradingSupport.IsColumnOld(entity, "Name", this.Record.OriginalAccountNumber))
                {
                    updateEntity = true;
                }
            }
            finally
            {
                entity.ReleaseLock(dataModelTransaction.TransactionId);
            }

            try
            {
                security = DataModel.Security.SecurityKey.Find(entityId);
                security.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                securityId      = entityId;
                securityVersion = security.RowVersion;
                workingOrder    = security.GetWorkingOrderRowsByFK_Security_WorkingOrder_SecurityId()[0];
                if (TradingSupport.IsColumnOld(security, "CountryId", countryId))
                {
                    updateSecurity = true;
                }
            }
            finally
            {
                security.ReleaseLock(dataModelTransaction.TransactionId);
            }


            // Control the working order:
            workingOrder.AcquireWriterLock(dataModelTransaction);

            try
            {
                consumerTrust = DataModel.ConsumerTrust.ConsumerTrustKey.Find(entityId);
                consumerTrust.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                consumerTrustId      = consumerTrust.ConsumerTrustId;
                consumerTrustVersion = consumerTrust.RowVersion;
                consumer             = DataModel.Consumer.ConsumerKey.Find(consumerTrust.ConsumerId);
                if (TradingSupport.IsColumnOld(consumerTrust, "SavingsAccount", this.Record.SavingsAccount) ||
                    TradingSupport.IsColumnOld(consumerTrust, "SavingsBalance", this.Record.SavingsBalance) ||
                    TradingSupport.IsColumnOld(consumerTrust, "Tag", this.Record.Tag))
                {
                    updateConsumerTrust = true;
                }
            }
            finally
            {
                consumerTrust.ReleaseLock(dataModelTransaction.TransactionId);
            }

            try
            {
                consumer.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                consumerId      = consumer.ConsumerId;
                consumerVersion = consumer.RowVersion;
                if (TradingSupport.IsColumnOld(consumer, "Address1", this.Record.Address1) ||
                    TradingSupport.IsColumnOld(consumer, "Address2", this.Record.Address2) ||
                    TradingSupport.IsColumnOld(consumer, "BankAccountNumber", this.Record.BankAccountNumber) ||
                    TradingSupport.IsColumnOld(consumer, "BankRoutingNumber", this.Record.BankRoutingNumber) ||
                    TradingSupport.IsColumnOld(consumer, "City", this.Record.City) ||
                    TradingSupport.IsColumnOld(consumer, "DateOfBirth", this.Record.DateOfBirth) ||
                    TradingSupport.IsColumnOld(consumer, "FirstName", this.Record.FirstName) ||
                    TradingSupport.IsColumnOld(consumer, "IsEmployed", this.Record.IsEmployed) ||
                    TradingSupport.IsColumnOld(consumer, "LastName", this.Record.LastName) ||
                    TradingSupport.IsColumnOld(consumer, "PostalCode", this.Record.PostalCode) ||
                    TradingSupport.IsColumnOld(consumer, "MiddleName", this.Record.MiddleName) ||
                    TradingSupport.IsColumnOld(consumer, "PhoneNumber", this.Record.PhoneNumber) ||
                    TradingSupport.IsColumnOld(consumer, "ProvinceId", provinceId) ||
                    TradingSupport.IsColumnOld(consumer, "SocialSecurityNumber", this.Record.SocialSecurityNumber) ||
                    TradingSupport.IsColumnOld(consumer, "Suffix", this.Record.Suffix))
                {
                    updateConsumer = true;
                }
            }
            finally
            {
                consumer.ReleaseLock(dataModelTransaction.TransactionId);
            }

            try
            {
                //workingOrder.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                workingOrderId      = workingOrder.WorkingOrderId;
                workingOrderVersion = workingOrder.RowVersion;
                matches             = workingOrder.GetMatchRows();
            }
            finally
            {
                //workingOrder.ReleaseLock(dataModelTransaction.TransactionId);
            }

            foreach (MatchRow match in matches)
            {
                if (WorkingOrderPersistence.IsSettled(dataModelTransaction, match))
                {
                    throw new FaultException <SecurityFault>(
                              new SecurityFault("Cannot update account that is settled")
                    {
                        FaultCode = ErrorCode.RecordExists
                    },
                              "Cannot update account that is settled");
                }
            }

            // We need write access to the containing blotter in order to add a record to it.
            if (!TradingSupport.HasAccess(dataModelTransaction, PersistenceHelper.GetBlotterForConsumer(dataModelTransaction, consumerId), AccessRight.Write))
            {
                throw new SecurityException("Current user does not have write access to the original blotter");
            }

            if (updateConsumer)
            {
                dataModel.UpdateConsumer(
                    this.Record.Address1 != null ? (object)this.Record.Address1 : DBNull.Value,
                    this.Record.Address2 != null ? (object)this.Record.Address2 : DBNull.Value,
                    this.Record.BankAccountNumber != null ? (object)this.Record.BankAccountNumber : DBNull.Value,
                    this.Record.BankRoutingNumber != null ? (object)this.Record.BankRoutingNumber : DBNull.Value,
                    this.Record.City != null ? (object)this.Record.City : DBNull.Value,
                    consumerId,
                    new object[] { consumerId },
                    this.Record.DateOfBirth != null ? (object)this.Record.DateOfBirth.Value : DBNull.Value,
                    null,
                    null,
                    this.Record.FirstName != null ? (object)this.Record.FirstName : DBNull.Value,
                    this.Record.IsEmployed != null ? (object)this.Record.IsEmployed.Value : DBNull.Value,
                    this.Record.LastName != null ? (object)this.Record.LastName : DBNull.Value,
                    this.Record.MiddleName != null ? (object)this.Record.MiddleName : DBNull.Value,
                    this.Record.PhoneNumber != null ? (object)StringUtilities.CleanUpAlphaNumericString(this.Record.PhoneNumber) : DBNull.Value,
                    this.Record.PostalCode != null ? (object)this.Record.PostalCode : DBNull.Value,
                    provinceId,
                    consumerVersion,
                    this.Record.Salutation,
                    StringUtilities.CleanUpAlphaNumericString(this.Record.SocialSecurityNumber),
                    this.Record.Suffix != null ? (object)this.Record.Suffix : DBNull.Value);
            }

            if (updateConsumerTrust)
            {
                dataModel.UpdateConsumerTrust(
                    null,
                    consumerTrustId,
                    new object[] { consumerTrustId },
                    null,
                    null,
                    consumerTrustVersion,
                    this.Record.SavingsAccount,
                    this.Record.SavingsBalance,
                    this.Record.Tag != null ? (object)this.Record.Tag : DBNull.Value,
                    null,
                    null);
            }

            if (updateEntity)
            {
                dataModel.UpdateEntity(
                    null,
                    null,
                    entityId,
                    new object[] { entityId },
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    modified,
                    this.Record.SavingsEntityCode,
                    entityVersion,
                    null,
                    null);
            }

            if (updateSecurity)
            {
                dataModel.UpdateSecurity(
                    null,
                    countryId,
                    null,
                    null,
                    null,
                    1,
                    1,
                    securityVersion,
                    securityId,
                    new object[] { securityId },
                    null,
                    null,
                    null);
            }

            dataModel.UpdateWorkingOrder(
                null,
                this.Record.Blotter,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                modified,
                TradingSupport.UserId,
                null,
                workingOrderVersion,
                null,
                null,
                dollarsId,
                null,
                null,
                StatusMap.FromCode(Status.New),
                null,
                null,
                null,
                null,
                null,
                null,
                modified,
                workingOrderId,
                new object[] { workingOrderId });

            return(consumerId);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Extract information from the settlementRow to send to GCS
        /// </summary>
        /// <param name="rawSettlementRow"></param>
        private void ProcessSettlement(ConsumerTrustSettlementRow rawSettlementRow)
        {
            List <PaymentInfo> paymentInfoList  = new List <PaymentInfo>();
            String             gcsAccountNumber = String.Empty;

            try
            {
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    // This provides a context for any transactions.
                    DataModelTransaction dataModelTransaction = DataModelTransaction.Current;

                    if (rawSettlementRow != null)
                    {
                        rawSettlementRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        bool settlementDeletedOrDetached = false;
                        try
                        {
                            settlementDeletedOrDetached = rawSettlementRow.RowState == DataRowState.Deleted ||
                                                          rawSettlementRow.RowState == DataRowState.Detached;
                        }
                        finally
                        {
                            rawSettlementRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }

                        //If the settlement was removed by the time we got to this, then there is no need to continue
                        if (settlementDeletedOrDetached == true)
                        {
                            return;
                        }
                    }

                    RowLockingWrapper <ConsumerTrustSettlementRow> settlementRow = new RowLockingWrapper <ConsumerTrustSettlementRow>(rawSettlementRow, dataModelTransaction);
                    settlementRow.AcquireReaderLock();
                    try
                    {
                        //We need GCS account id for this payment.  We cannot find a GCS account number then we cannot process this payment.
                        Guid creditCardId = Guid.Empty;
                        ConsumerTrustNegotiationRow negotiationRow = settlementRow.TypedRow.ConsumerTrustNegotiationRow;
                        negotiationRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        try
                        {
                            creditCardId = negotiationRow.CreditCardId;
                        }
                        finally
                        {
                            negotiationRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                            //no longer usable
                            negotiationRow = null;
                        }

                        //HACK - add error reporting
                        if (creditCardId == Guid.Empty)
                        {
                            return;
                        }

                        //Determine the consumer
                        Guid          consumerId    = Guid.Empty;
                        CreditCardRow creditcardRow = DataModel.CreditCard.CreditCardKey.Find(creditCardId);
                        creditcardRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        try
                        {
                            consumerId = creditcardRow.ConsumerId;
                        }
                        finally
                        {
                            creditcardRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                            //no longer usable
                            creditcardRow = null;
                        }

                        //HACK - add error reporting
                        if (consumerId == Guid.Empty)
                        {
                            return;
                        }

                        //Determine the consumerTrust
                        ConsumerTrustRow consumerTrustRow = null;
                        ConsumerRow      consumerRow      = DataModel.Consumer.ConsumerKey.Find(consumerId);
                        consumerRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        try
                        {
                            consumerTrustRow = consumerRow.GetConsumerTrustRows_NoLockCheck().First();
                        }
                        finally
                        {
                            consumerRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                            //no longer usable
                            consumerRow = null;
                        }

                        //HACK - add error reporting
                        if (consumerTrustRow == null)
                        {
                            return;
                        }

                        consumerTrustRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        try
                        {
                            gcsAccountNumber = (consumerTrustRow.IsSavingsAccountNull()) ? String.Empty : consumerTrustRow.SavingsAccount;
                        }
                        finally
                        {
                            consumerTrustRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                            //no longer usable
                            consumerTrustRow = null;
                        }

                        //HACK - add error reporting
                        if (String.IsNullOrEmpty(gcsAccountNumber))
                        {
                            return;
                        }


                        foreach (ConsumerTrustPaymentRow paymentRow in settlementRow.TypedRow.GetConsumerTrustPaymentRows())
                        {
                            paymentRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                            try
                            {
                                if (paymentRow.RowState != DataRowState.Deleted &&
                                    paymentRow.RowState != DataRowState.Detached)
                                {
                                    paymentInfoList.Add(new PaymentInfo(paymentRow));
                                }
                            }
                            finally
                            {
                                paymentRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                            }
                        }
                    }
                    finally
                    {
                        settlementRow.ReleaseReaderLock();
                    }
                }
            }
            catch (Exception ex)
            {
                EventLog.Error(ex);
            }

            if (String.IsNullOrEmpty(gcsAccountNumber) == false && paymentInfoList.Count != 0)
            {
                SendPaymentsToGCS(gcsAccountNumber, paymentInfoList);
            }
        }
        /// <summary>
        /// Delete a WorkingOrderRow.
        /// </summary>
        /// <param name="dataModel">The data model.</param>
        /// <param name="transaction">The current transaction.</param>
        /// <param name="workingOrderRow">The working order row to delete.</param>
        /// <returns>Error code of any failure, or Success.</returns>
        public ErrorCode DeleteRow(DataModel dataModel, DataModelTransaction transaction, WorkingOrderRow workingOrderRow)
        {
            SecurityRow securityRow       = null;
            EntityRow   securityEntityRow = null;

            MatchRow[]         matchRows;
            ConsumerDebtRow[]  consumerDebtRows;
            ConsumerTrustRow[] consumerTrustRows;
            CreditCardRow      creditCardRow = null;
            ConsumerRow        consumerRow   = null;
            Guid    blotterId;
            Guid    securityEntityId         = Guid.Empty;
            Int64   securityEntityRowVersion = 0;
            Guid    consumerId           = Guid.Empty;
            Int64   consumerRowVersion   = 0;
            Guid    creditCardId         = Guid.Empty;
            Int64   creditCardRowVersion = 0;
            Boolean consumerStillInUse   = false;

            workingOrderRow.AcquireWriterLock(transaction.TransactionId, DataModel.LockTimeout);
            if (workingOrderRow.RowState == DataRowState.Deleted ||
                workingOrderRow.RowState == DataRowState.Detached)
            {
                workingOrderRow.ReleaseLock(transaction.TransactionId);
                return(ErrorCode.RecordNotFound);
            }
            else
            {
                transaction.AddLock(workingOrderRow);
            }
            blotterId   = workingOrderRow.BlotterId;
            securityRow = workingOrderRow.SecurityRowByFK_Security_WorkingOrder_SecurityId;
            matchRows   = workingOrderRow.GetMatchRows();

            if (matchRows != null)
            {
                foreach (MatchRow matchRow in matchRows)
                {
                    if (IsSettled(transaction, matchRow))
                    {
                        return(ErrorCode.RecordExists);
                    }
                }
            }

            if (!DataModelFilters.HasAccess(transaction, TradingSupport.UserId, blotterId, AccessRight.Write))
            {
                workingOrderRow.ReleaseLock(transaction.TransactionId);
                return(ErrorCode.AccessDenied);
            }
            securityRow.AcquireWriterLock(transaction.TransactionId, DataModel.LockTimeout);
            if (securityRow.RowState == DataRowState.Deleted ||
                securityRow.RowState == DataRowState.Detached)
            {
                workingOrderRow.ReleaseLock(transaction.TransactionId);
                securityRow.ReleaseWriterLock(transaction.TransactionId);
                return(ErrorCode.RecordNotFound);
            }
            securityEntityRow = securityRow.EntityRow;
            consumerDebtRows  = securityRow.GetConsumerDebtRows();
            consumerTrustRows = securityRow.GetConsumerTrustRows();
            securityRow.ReleaseWriterLock(transaction.TransactionId);

            securityEntityRow.AcquireWriterLock(transaction);
            if (securityEntityRow.RowState == DataRowState.Deleted ||
                securityEntityRow.RowState == DataRowState.Detached)
            {
                workingOrderRow.ReleaseLock(transaction.TransactionId);
                securityEntityRow.ReleaseLock(transaction.TransactionId);
                return(ErrorCode.RecordNotFound);
            }
            securityEntityId         = securityEntityRow.EntityId;
            securityEntityRowVersion = securityEntityRow.RowVersion;
            securityEntityRow.ReleaseLock(transaction.TransactionId);

            if (consumerTrustRows.Length > 0 && consumerDebtRows.Length > 0)
            {
                EventLog.Warning("Deleting a working order associated with both ConsumerDebt and ConsumerTrust rows");
            }
            else if (consumerDebtRows.Length > 1)
            {
                EventLog.Warning("Deleting a working order associated with more than one ConsumerDebt row");
            }
            else if (consumerTrustRows.Length > 1)
            {
                EventLog.Warning("Deleting a working order associated with more than one ConsumerTrust row");
            }

            if (consumerDebtRows.Length == 1)
            {
                ConsumerDebtRow consumerDebtRow = consumerDebtRows[0];

                consumerDebtRow.AcquireWriterLock(transaction);
                if (consumerDebtRow.RowState == DataRowState.Deleted ||
                    consumerDebtRow.RowState == DataRowState.Detached)
                {
                }
                else
                {
                    creditCardRow = consumerDebtRow.CreditCardRow;
                    consumerRow   = consumerDebtRow.ConsumerRow;
                }
                consumerDebtRow.ReleaseLock(transaction.TransactionId);
            }
            else if (consumerTrustRows.Length == 1)
            {
                ConsumerTrustRow consumerTrustRow = consumerTrustRows[0];

                consumerTrustRow.AcquireWriterLock(transaction);
                if (consumerTrustRow.RowState == DataRowState.Deleted ||
                    consumerTrustRow.RowState == DataRowState.Detached)
                {
                }
                else
                {
                    consumerRow = consumerTrustRow.ConsumerRow;
                }
                consumerTrustRow.ReleaseLock(transaction.TransactionId);
            }

            if (consumerRow != null)
            {
                consumerRow.AcquireWriterLock(transaction);
                if (consumerRow.RowState == DataRowState.Deleted ||
                    consumerRow.RowState == DataRowState.Detached)
                {
                    consumerRow = null;
                }
                else
                {
                    consumerStillInUse = consumerRow.GetConsumerDebtRows().Length > 1;
                    consumerId         = consumerRow.ConsumerId;
                    consumerRowVersion = consumerRow.RowVersion;
                }
                consumerRow.ReleaseLock(transaction.TransactionId);
            }

            if (creditCardRow != null)
            {
                creditCardRow.AcquireWriterLock(transaction);
                if (creditCardRow.RowState == DataRowState.Deleted ||
                    creditCardRow.RowState == DataRowState.Detached)
                {
                    creditCardRow = null;
                }
                else
                {
                    creditCardId         = creditCardRow.ConsumerId;
                    creditCardRowVersion = creditCardRow.RowVersion;
                }
                creditCardRow.ReleaseLock(transaction.TransactionId);
            }

            //gonna get the lock on the workingOrder and let the txn commit/rollback get rid of it
            //this will basically wrap the delete row
            //action in a critical section because the first
            //reader lock in the method is on the workingOrder row
            //workingOrderRow.AcquireWriterLock(transaction.TransactionId, DataModel.LockTimeout);
            if (workingOrderRow.RowState == DataRowState.Deleted ||
                workingOrderRow.RowState == DataRowState.Detached)
            {
                workingOrderRow.ReleaseLock(transaction.TransactionId);
                return(ErrorCode.RecordNotFound);
            }
            //securityRow.AcquireWriterLock(transaction.TransactionId, DataModel.LockTimeout);
            //if(securityRow.RowState == DataRowState.Deleted ||
            //        securityRow.RowState == DataRowState.Detached)
            //{
            //    workingOrderRow.ReleaseLock(transaction.TransactionId);
            //    return ErrorCode.RecordNotFound;
            //}
            if (creditCardRow != null && consumerStillInUse)
            {
                dataModel.DestroyCreditCard(new object[] { creditCardId }, creditCardRowVersion);
            }
            if (consumerRow != null && !consumerStillInUse)
            {
                dataModel.DestroyConsumer(new object[] { consumerId }, consumerRowVersion);
            }

            dataModel.DestroyEntity(new object[] { securityEntityId }, securityEntityRowVersion);

            return(ErrorCode.Success);
        }