Ejemplo n.º 1
0
 public TrustNegotiationInfo(ConsumerTrustNegotiationRow consumerTrustNegotiationRow)
 {
     this.AccountBalance                = consumerTrustNegotiationRow.AccountBalance;
     this.BlotterId                     = consumerTrustNegotiationRow.BlotterId;
     this.CreditCardId                  = consumerTrustNegotiationRow.CreditCardId;
     this.MatchId                       = consumerTrustNegotiationRow.MatchId;
     this.CounterPaymentLength          = consumerTrustNegotiationRow.CounterPaymentLength;
     this.CounterPaymentStartDateLength = consumerTrustNegotiationRow.CounterPaymentStartDateLength;
     this.CounterPaymentStartDateUnitId = consumerTrustNegotiationRow.CounterPaymentStartDateUnitId;
     this.CounterSettlementUnitId       = consumerTrustNegotiationRow.CounterSettlementUnitId;
     this.CounterSettlementValue        = consumerTrustNegotiationRow.CounterSettlementValue;
     this.IsRead  = consumerTrustNegotiationRow.IsRead;
     this.IsReply = consumerTrustNegotiationRow.IsReply;
 }
Ejemplo n.º 2
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>
        ///
        /// </summary>
        /// <param name="dataModelTransaction"></param>
        /// <param name="moveToInfo"></param>
        /// <param name="consumerTrustNegotiationRow"></param>
        private static void CollectSettlementData(DataModelTransaction dataModelTransaction, MoveToInfo moveToInfo, ConsumerTrustNegotiationRow consumerTrustNegotiationRow)
        {
            foreach (ConsumerTrustSettlementRow settlementRow in consumerTrustNegotiationRow.GetConsumerTrustSettlementRows())
            {
                settlementRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                try
                {
                    moveToInfo.settlementRows.Add(new BaseRecord()
                    {
                        RowId = settlementRow.ConsumerTrustSettlementId, RowVersion = settlementRow.RowVersion
                    });

                    //Get  payment method rows to move
                    foreach (ConsumerTrustSettlementPaymentMethodRow consumerTrustSettlementPaymentMethodRow in settlementRow.GetConsumerTrustSettlementPaymentMethodRows())
                    {
                        consumerTrustSettlementPaymentMethodRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        try
                        {
                            moveToInfo.consumerTrustSettlementPaymentMethodRows.Add(new BaseRecord()
                            {
                                RowId = consumerTrustSettlementPaymentMethodRow.ConsumerTrustSettlementPaymentMethodId, RowVersion = consumerTrustSettlementPaymentMethodRow.RowVersion
                            });
                        }
                        finally
                        {
                            consumerTrustSettlementPaymentMethodRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }

                    //Get payment rows to move
                    foreach (ConsumerTrustPaymentRow settlementRowPaymentMethodRow in settlementRow.GetConsumerTrustPaymentRows())
                    {
                        settlementRowPaymentMethodRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        try
                        {
                            moveToInfo.consumerTrustPaymentRows.Add(new BaseRecord()
                            {
                                RowId = settlementRowPaymentMethodRow.ConsumerTrustPaymentId, RowVersion = settlementRowPaymentMethodRow.RowVersion
                            });
                        }
                        finally
                        {
                            settlementRowPaymentMethodRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }
                }
                finally
                {
                    settlementRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Copies information from the ConsumerTrustNegotiation record.
        /// </summary>
        /// <param name="consumerDebtNegotiationRow">The source row.</param>
        public NegotiationItem(ConsumerTrustNegotiationRow consumerTrustNegotiationRow)
        {
            // This extracts the negotiation information from the source record.
            this.AccountBalance                = consumerTrustNegotiationRow.AccountBalance;
            this.CounterPaymentLength          = consumerTrustNegotiationRow.CounterPaymentLength;
            this.CounterPaymentStartDateLength = consumerTrustNegotiationRow.CounterPaymentStartDateLength;
            this.CounterPaymentStartDateUnitId = consumerTrustNegotiationRow.CounterPaymentStartDateUnitId;
            this.CounterSettlementUnitId       = consumerTrustNegotiationRow.CounterSettlementUnitId;
            this.CounterSettlementValue        = consumerTrustNegotiationRow.CounterSettlementValue;
            this.MatchId                     = consumerTrustNegotiationRow.MatchId;
            this.OfferPaymentLength          = consumerTrustNegotiationRow.OfferPaymentLength;
            this.OfferPaymentStartDateLength = consumerTrustNegotiationRow.OfferPaymentStartDateLength;
            this.OfferPaymentStartDateUnitId = consumerTrustNegotiationRow.OfferPaymentStartDateUnitId;
            this.OfferSettlementUnitId       = consumerTrustNegotiationRow.OfferSettlementUnitId;
            this.OfferSettlementValue        = consumerTrustNegotiationRow.OfferSettlementValue;

            // One side may be quoting in days and the other side may be quoting in months.  In order to compare the two quotes to see if there is a match, the
            // time units must be decoded for each side.
            TimeUnit counterTimeUnit = default(TimeUnit);
            TimeUnit offerTimeUnit   = default(TimeUnit);

            lock (DataModel.SyncRoot)
            {
                // Find the time units quoted by the debt negotiator.
                TimeUnitRow counterTimeUnitRow = DataModel.TimeUnit.TimeUnitKey.Find(this.CounterPaymentStartDateUnitId);
                counterTimeUnit = counterTimeUnitRow.TimeUnitCode;

                // Find the time units quoted by the debt holder.
                TimeUnitRow offerTimeUnitRow = DataModel.TimeUnit.TimeUnitKey.Find(this.OfferPaymentStartDateUnitId);
                offerTimeUnit = offerTimeUnitRow.TimeUnitCode;

                StatusRow statusRow = DataModel.Status.StatusKey.Find(consumerTrustNegotiationRow.StatusId);
                this.StatusCode = statusRow.StatusCode;
            }

            // Convert the time unit qoted by the debt negotiator into a standard number of days.
            switch (counterTimeUnit)
            {
            case TimeUnit.Days:
                this.CounterDays = this.CounterPaymentStartDateLength;
                break;

            case TimeUnit.Months:
                this.CounterDays = this.CounterPaymentStartDateLength * 30;
                break;

            case TimeUnit.Weeks:
                this.CounterDays = this.CounterPaymentStartDateLength * 7;
                break;
            }

            // Convert the time unit quoted by the debt holder into a standard number of days.
            switch (offerTimeUnit)
            {
            case TimeUnit.Days:
                this.OfferDays = this.OfferPaymentStartDateLength;
                break;

            case TimeUnit.Months:
                this.OfferDays = this.OfferPaymentStartDateLength * 30;
                break;

            case TimeUnit.Weeks:
                this.OfferDays = this.OfferPaymentStartDateLength * 7;
                break;
            }
        }
        /// <summary>
        /// Evaluates whether a given working order is eligible for a cross with another order.
        /// </summary>
        /// <param name="key">The key of the object to be handled.</param>
        /// <param name="parameters">A generic list of paraneters to the handler.</param>
        public static void MergeDocument(Object[] key, params Object[] parameters)
        {
            // Extract the strongly typed variables from the generic parameters.
            Guid consumerDebtSettlementId = (Guid)key[0];

            // This structure will collect the information required for the merge operation.
            MergeInfo mergeInfo = new MergeInfo();

            mergeInfo.ConsumerDebtSettlementId = consumerDebtSettlementId;

            // An instance of the data model is required for CRUD operations.
            DataModel dataModel = new DataModel();

            // If two counterparties agree on a transaction then a settlement report is generated from the Word Template associated with the Consumer Debt
            // Entity.
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromHours(1)))
            {
                // This provides a context for any transactions.
                DataModelTransaction dataModelTransaction = DataModelTransaction.Current;

                // It is important to minimize the locking for these transactions since they will drag the system performance down and create deadlock
                // sitiations if too many are held for too long.
                BlotterRow blotterRow = null;
                ConsumerDebtSettlementRow  consumerDebtSettlementRow  = null;
                ConsumerDebtNegotiationRow consumerDebtNegotiationRow = null;
                MatchRow        matchRow        = null;
                CreditCardRow   creditCardRow   = null;
                WorkingOrderRow workingOrderRow = null;

                try
                {
                    // The ConsumerDebtSettlement row is where the search for the Settlement Information begins.
                    consumerDebtSettlementRow = DataModel.ConsumerDebtSettlement.ConsumerDebtSettlementKey.Find(consumerDebtSettlementId);
                    consumerDebtSettlementRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                    // There is no need to generate a report on a settlement that isn't new.  This will momentarily lock the status table so we
                    // can see if the settlement is new.
                    try
                    {
                        consumerDebtSettlementRow.StatusRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        if (consumerDebtSettlementRow.StatusRow.StatusCode != Status.New)
                        {
                            return;
                        }
                    }
                    finally
                    {
                        consumerDebtSettlementRow.StatusRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }

                    // The RowVersion is needed to update the record with the new PDF report.
                    mergeInfo.RowVersion = consumerDebtSettlementRow.RowVersion;

                    // The negotiation row contains the link to the base matching row.
                    consumerDebtNegotiationRow = consumerDebtSettlementRow.ConsumerDebtNegotiationRow;
                    consumerDebtNegotiationRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                    // The base matching row is where we'll find the working order.
                    matchRow = consumerDebtNegotiationRow.MatchRow;
                    matchRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                    // The working order row is where the blotter can be found.
                    workingOrderRow = matchRow.WorkingOrderRow;
                    workingOrderRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                    // And the blotter will lead us to the Entity hierarchy which is where we'll find the rules.
                    blotterRow = workingOrderRow.BlotterRow;
                    blotterRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                    // The 'Pending' status is applied to the Settlement after the letter has been generated.  The status needs to be picked up while we're
                    // still locking and reading tables.
                    StatusRow statusRow = DataModel.Status.StatusKeyStatusCode.Find(Status.Pending);
                    try
                    {
                        statusRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        mergeInfo.StatusId = statusRow.StatusId;
                    }
                    finally
                    {
                        statusRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }

                    //Find the consumerDebt to find the credit Card to get the origianl creditor
                    ConsumerTrustNegotiationRow trustNegotiation = null;
                    MatchRow contraWorMatchRow = DataModel.Match.MatchKey.Find(matchRow.ContraMatchId);
                    contraWorMatchRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                    try
                    {
                        trustNegotiation = contraWorMatchRow.GetConsumerTrustNegotiationRows()[0];
                    }
                    finally
                    {
                        if (contraWorMatchRow != null)
                        {
                            contraWorMatchRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }

                    //Consumer Debt Row
                    trustNegotiation.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                    try
                    {
                        creditCardRow = trustNegotiation.CreditCardRow;
                    }
                    finally
                    {
                        if (trustNegotiation != null)
                        {
                            trustNegotiation.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }


                    creditCardRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                    // There is only going to be one Debt Class record 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 blotterRow.GetDebtClassRows())
                    {
                        // This variable will keep track of our current location as we crawl up the hierarchy.  It is important to release the records as soon
                        // as possible to reduce the likelyhood of a deadlock.
                        DebtClassRow currentDebtClassRow = debtClassRow;
                        DebtClassRow nextDebtClassRow    = null;

                        // This flag will be set when a Debt Class in the hierarchy contains a Debt Rule.
                        Boolean isFound = false;

                        // 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
                        {
                            try
                            {
                                // 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);

                                // If the current Debt Class has no rule then the Entity Hierarchy is used to find the parent element.
                                if (currentDebtClassRow.IsSettlementTemplateNull())
                                {
                                    // 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(currentDebtClassRow.DebtClassId);

                                    try
                                    {
                                        // Each entity needs to be locked before the relation can be used.
                                        entityRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                                        // This will find each relation in the hierarchy which uses the current node as a child.
                                        foreach (EntityTreeRow entityTreeRow in entityRow.GetEntityTreeRowsByFK_Entity_EntityTree_ChildId())
                                        {
                                            try
                                            {
                                                // Lock the relation down before navigating to the parent.
                                                entityTreeRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                                                // This is the parent entity of the current entity in the crawl up the hierarchy.
                                                EntityRow parentEntityRow = entityTreeRow.EntityRowByFK_Entity_EntityTree_ParentId;

                                                try
                                                {
                                                    // 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);

                                                    // In practice, there will be zero or one blotter rows.  The iteration makes it easier to check both
                                                    // conditions.
                                                    foreach (BlotterRow parentBlotterRow in parentEntityRow.GetBlotterRows())
                                                    {
                                                        try
                                                        {
                                                            // The blotter must be locked before iterating through the Debt Classes that may be associated
                                                            // with the blotter.
                                                            parentBlotterRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                                                            // 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 parentBlotterRow.GetDebtClassRows())
                                                            {
                                                                try
                                                                {
                                                                    // 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.
                                                                    parentDebtClassRow.AcquireReaderLock(
                                                                        dataModelTransaction.TransactionId,
                                                                        DataModel.LockTimeout);
                                                                    nextDebtClassRow = parentDebtClassRow;
                                                                }
                                                                finally
                                                                {
                                                                    // The locks are released after the parent Debt Class is found.
                                                                    parentDebtClassRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                                                                }
                                                            }
                                                        }
                                                        finally
                                                        {
                                                            // The locks are released after the each level of the hierarchy is checked.
                                                            parentBlotterRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                                                        }
                                                    }
                                                }
                                                finally
                                                {
                                                    // The parent Entity record is released after each level of the hiearchy is examined for a parent.
                                                    parentEntityRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                                                }
                                            }
                                            finally
                                            {
                                                // The relationship record is released after each level of the hierarchy is examined for a parent.
                                                entityTreeRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                                            }
                                        }
                                    }
                                    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);
                                    }
                                }
                                else
                                {
                                    // The template has been found and converted back to a Microsoft Word template.
                                    mergeInfo.SourceDocument = Convert.FromBase64String(currentDebtClassRow.SettlementTemplate);

                                    // This will cause the loop to exit.
                                    isFound = true;
                                }
                            }
                            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);
                            }

                            // 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 (isFound == false && currentDebtClassRow != null);
                    }

                    // AccountBalance
                    mergeInfo.Dictionary.Add(
                        "AccountBalance",
                        String.Format("{0:$#,##0.00}",
                                      consumerDebtSettlementRow.AccountBalance));

                    // CreatedDate
                    mergeInfo.Dictionary.Add("CreatedDate", consumerDebtSettlementRow.CreatedTime);

                    // Original Creditor
                    mergeInfo.Dictionary.Add(
                        "DebtHolder",
                        creditCardRow.IsDebtHolderNull() ? null : creditCardRow.DebtHolder);

                    // DebtorAccountNumber
                    mergeInfo.Dictionary.Add(
                        "DebtorAccountNumber",
                        consumerDebtSettlementRow.IsDebtorAccountNumberNull() ? null : consumerDebtSettlementRow.DebtorAccountNumber);

                    // DebtorBankAccountNumber
                    mergeInfo.Dictionary.Add(
                        "DebtorBankAccountNumber",
                        consumerDebtSettlementRow.IsDebtorBankAccountNumberNull() ? null : consumerDebtSettlementRow.DebtorBankAccountNumber);

                    // DebtorBankRoutingNumber
                    mergeInfo.Dictionary.Add(
                        "DebtorBankRoutingNumber",
                        consumerDebtSettlementRow.IsDebtorBankRoutingNumberNull() ? null : consumerDebtSettlementRow.DebtorBankRoutingNumber);

                    // DebtorAddress1
                    mergeInfo.Dictionary.Add(
                        "DebtorAddress1",
                        consumerDebtSettlementRow.IsDebtorAddress1Null() ? null : consumerDebtSettlementRow.DebtorAddress1);

                    // DebtorAddress2
                    mergeInfo.Dictionary.Add(
                        "DebtorAddress2",
                        consumerDebtSettlementRow.IsDebtorAddress2Null() ? null : consumerDebtSettlementRow.DebtorAddress2);

                    // DebtorCity
                    mergeInfo.Dictionary.Add(
                        "DebtorCity",
                        consumerDebtSettlementRow.IsDebtorCityNull() ? null : consumerDebtSettlementRow.DebtorCity);

                    // DebtorFirstName
                    mergeInfo.Dictionary.Add(
                        "DebtorFirstName",
                        consumerDebtSettlementRow.IsDebtorFirstNameNull() ? null : consumerDebtSettlementRow.DebtorFirstName);

                    // DebtorLastName
                    mergeInfo.Dictionary.Add(
                        "DebtorLastName",
                        consumerDebtSettlementRow.IsDebtorLastNameNull() ? null : consumerDebtSettlementRow.DebtorLastName);

                    // DebtorMiddleName
                    mergeInfo.Dictionary.Add(
                        "DebtorMiddleName",
                        consumerDebtSettlementRow.IsDebtorMiddleNameNull() ? null : consumerDebtSettlementRow.DebtorMiddleName);

                    // DebtorOriginalAccountNumber
                    mergeInfo.Dictionary.Add(
                        "DebtorOriginalAccountNumber",
                        consumerDebtSettlementRow.DebtorOriginalAccountNumber);

                    // DebtorPostalCode
                    mergeInfo.Dictionary.Add(
                        "DebtorPostalCode",
                        consumerDebtSettlementRow.IsDebtorPostalCodeNull() ? null : consumerDebtSettlementRow.DebtorPostalCode);

                    // DebtorProvince
                    String debtorProvince = null;
                    if (!consumerDebtSettlementRow.IsDebtorProvinceIdNull())
                    {
                        ProvinceRow provinceRow = consumerDebtSettlementRow.ProvinceRowByFK_Province_ConsumerDebtSettlement_DebtorProvinceId;
                        try
                        {
                            provinceRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                            debtorProvince = provinceRow.Abbreviation;
                        }
                        finally
                        {
                            provinceRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }
                    mergeInfo.Dictionary.Add("DebtorProvinceAbbreviation", debtorProvince);

                    // DebtorSalutation
                    mergeInfo.Dictionary.Add(
                        "DebtorSalutation",
                        consumerDebtSettlementRow.IsDebtorSalutationNull() ? null : consumerDebtSettlementRow.DebtorSalutation);

                    // DebtorSuffix
                    mergeInfo.Dictionary.Add(
                        "DebtorSuffix",
                        consumerDebtSettlementRow.IsDebtorSuffixNull() ? null : consumerDebtSettlementRow.DebtorSuffix);


                    // PayeeAddress1
                    mergeInfo.Dictionary.Add(
                        "PayeeAddress1",
                        consumerDebtSettlementRow.IsPayeeAddress1Null() ? null : consumerDebtSettlementRow.PayeeAddress1);

                    // PayeeAddress2
                    mergeInfo.Dictionary.Add(
                        "PayeeAddress2",
                        consumerDebtSettlementRow.IsPayeeAddress2Null() ? null : consumerDebtSettlementRow.PayeeAddress2);

                    // PayeeCity
                    mergeInfo.Dictionary.Add(
                        "PayeeCity",
                        consumerDebtSettlementRow.IsPayeeCityNull() ? null : consumerDebtSettlementRow.PayeeCity);

                    // PayeeCompanyName
                    mergeInfo.Dictionary.Add(
                        "PayeeCompanyName",
                        consumerDebtSettlementRow.IsPayeeCompanyNameNull() ? null : consumerDebtSettlementRow.PayeeCompanyName);

                    // PayeeContactName
                    mergeInfo.Dictionary.Add(
                        "PayeeContactName",
                        consumerDebtSettlementRow.IsPayeeContactNameNull() ? null : consumerDebtSettlementRow.PayeeContactName);

                    // PayeeDepartment
                    mergeInfo.Dictionary.Add(
                        "PayeeDepartment",
                        consumerDebtSettlementRow.IsPayeeDepartmentNull() ? null : consumerDebtSettlementRow.PayeeDepartment);

                    // PayeeEmail
                    mergeInfo.Dictionary.Add(
                        "PayeeEmail",
                        consumerDebtSettlementRow.IsPayeeEmailNull() ? null : consumerDebtSettlementRow.PayeeEmail);

                    // PayeeFax
                    mergeInfo.Dictionary.Add(
                        "PayeeFax",
                        consumerDebtSettlementRow.IsPayeeFaxNull() ? null : consumerDebtSettlementRow.PayeeFax);

                    // PayeeForBenefitOf
                    mergeInfo.Dictionary.Add(
                        "PayeeForBenefitOf",
                        consumerDebtSettlementRow.IsPayeeForBenefitOfNull() ? null : consumerDebtSettlementRow.PayeeForBenefitOf);

                    // PayeePhone
                    mergeInfo.Dictionary.Add(
                        "PayeePhone",
                        consumerDebtSettlementRow.IsPayeePhoneNull() ? null : consumerDebtSettlementRow.PayeePhone);

                    // PayeePostalCode
                    mergeInfo.Dictionary.Add(
                        "PayeePostalCode",
                        consumerDebtSettlementRow.IsPayeePostalCodeNull() ? null : consumerDebtSettlementRow.PayeePostalCode);

                    // PayeeProvince
                    String payeeProvince = null;
                    if (!consumerDebtSettlementRow.IsPayeeProvinceIdNull())
                    {
                        ProvinceRow provinceRow = consumerDebtSettlementRow.ProvinceRowByFK_Province_ConsumerDebtSettlement_PayeeProvinceId;
                        try
                        {
                            provinceRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                            payeeProvince = provinceRow.Abbreviation;
                        }
                        finally
                        {
                            provinceRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }
                    mergeInfo.Dictionary.Add("PayeeProvinceAbbreviation", payeeProvince);

                    // PaymentLength
                    mergeInfo.Dictionary.Add("PaymentLength", consumerDebtSettlementRow.PaymentLength);

                    // PaymentStartDate
                    mergeInfo.Dictionary.Add("PaymentStartDate", consumerDebtSettlementRow.PaymentStartDate.ToLocalTime().ToLongDateString());

                    // PayeeBankAccountNumber
                    mergeInfo.Dictionary.Add(
                        "PayeeBankAccountNumber",
                        consumerDebtSettlementRow.IsPayeeBankAccountNumberNull() ? null : consumerDebtSettlementRow.PayeeBankAccountNumber);

                    // PayeeBankRoutingNumber
                    mergeInfo.Dictionary.Add(
                        "PayeeBankRoutingNumber",
                        consumerDebtSettlementRow.IsPayeeBankRoutingNumberNull() ? null : consumerDebtSettlementRow.PayeeBankRoutingNumber);

                    // SettlementAmount
                    mergeInfo.Dictionary.Add("SettlementAmount", consumerDebtSettlementRow.SettlementAmount);

                    // SettlementPercent
                    mergeInfo.Dictionary.Add("SettlementPercent", consumerDebtSettlementRow.SettlementAmount / consumerDebtSettlementRow.AccountBalance);

                    // TermPaymentAmount
                    mergeInfo.Dictionary.Add("TermPaymentAmount", consumerDebtSettlementRow.SettlementAmount / consumerDebtSettlementRow.PaymentLength);

                    // The payment methods is modeled as a vector which makes it difficult to add as a single merge field.  To work around this, each of the
                    // possible payment methods are described in the data dictionary using the form 'Is{PaymentMethodName}'.  The Word Merge process should look for
                    // the presence of these fields to generate a block of text for the instructions for each of the payment methods.  This iteration will
                    // collect all the possible payment method types in an array and assume that they don't exist (i.e. set them to a Boolean value of 'false')
                    // until they're found in the settlement instructions.
                    foreach (PaymentMethodTypeRow paymentMethodTypeRow in DataModel.PaymentMethodType)
                    {
                        try
                        {
                            paymentMethodTypeRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                            mergeInfo.Dictionary.Add(String.Format("Is{0}", paymentMethodTypeRow.Name.Replace(" ", String.Empty)), false);
                        }
                        finally
                        {
                            paymentMethodTypeRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }

                    // This iteration will cycle through all the payment methods in the settlement and set them to be true.  The result is a dictionary of all
                    // possible payment methods with the ones included in this settlement set to be the Boolean value of 'true'.
                    foreach (ConsumerDebtSettlementPaymentMethodRow consumerDebtSettlementPaymentMethodRow in
                             consumerDebtSettlementRow.GetConsumerDebtSettlementPaymentMethodRows())
                    {
                        try
                        {
                            // Each of the payment methods in the settlement are modeled as a list that is associated with the settlement.  This will lock each
                            // of the items in the list in turn and examine the parent 'PaymentMethodType' record to construct a mail-merge tag.
                            consumerDebtSettlementPaymentMethodRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                            PaymentMethodTypeRow paymentMethodTypeRow = DataModel.PaymentMethodType.PaymentMethodTypeKey.Find(
                                consumerDebtSettlementPaymentMethodRow.PaymentMethodTypeId);

                            try
                            {
                                // Once the parent MethodType is found a tag is added to the dictionary.  The presence of the 'Is<PaymentMethodType>' item in
                                // the dictionary means that the given payment method is acceptable for this settlement.
                                paymentMethodTypeRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                                mergeInfo.Dictionary[String.Format("Is{0}", paymentMethodTypeRow.Name.Replace(" ", String.Empty))] = true;
                            }
                            finally
                            {
                                // The parent payment method type row is not needed any longer.
                                paymentMethodTypeRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                            }
                        }
                        finally
                        {
                            // Release the payment method row.
                            consumerDebtSettlementPaymentMethodRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }
                }
                finally
                {
                    // The CreditCardRow is no longer needed.
                    if (creditCardRow != null && creditCardRow.IsReaderLockHeld(dataModelTransaction.TransactionId))
                    {
                        creditCardRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }

                    // The ConsumerDebtSettlementRow is no longer needed.
                    if (consumerDebtSettlementRow != null)
                    {
                        consumerDebtSettlementRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }

                    // The ConsumerDebtNegotiation Row is no longer needed.
                    if (consumerDebtNegotiationRow != null)
                    {
                        consumerDebtNegotiationRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }

                    // The MatchRow is no longer needed.
                    if (matchRow != null)
                    {
                        matchRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }

                    // The WorkingOrderRow is no longer needed.
                    if (workingOrderRow != null)
                    {
                        workingOrderRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }

                    // The BlotterRow is no longer needed.
                    if (blotterRow != null)
                    {
                        blotterRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }
                }

                MemoryStream memoryStream = null;

                try
                {
                    // At this point, all the data has been collected and the record locks released.  It is time to merge the document.
                    memoryStream = SettlementDocumentFactory.iMailMerge.CreateDocument(mergeInfo.SourceDocument, mergeInfo.Dictionary);
                }
                catch (Exception exception)
                {
                    EventLog.Error("There was a problem creating the settlement letter. \n Details: {0}, {1}", exception.Message, exception.StackTrace);
                }

                if (memoryStream != null)
                {
                    // Update the settlement with the newly generated PFD file.
                    dataModel.UpdateConsumerDebtSettlement(
                        null,
                        null,
                        null,
                        null,
                        new Object[] { consumerDebtSettlementId },
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        mergeInfo.RowVersion,
                        null,
                        Convert.ToBase64String(memoryStream.ToArray()),
                        mergeInfo.StatusId);
                }

                // If we reached here the transaction was successful.
                transactionScope.Complete();
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Reset the negotiation to a "in negotiation" state.
        /// </summary>
        /// <param name="consumerTrustNegotiations">The the negotiations to reset.</param>
        internal static void Reject(ConsumerTrustNegotiationInfo[] consumerTrustNegotiations)
        {
            // An instance of the shared data model is required to use its methods.
            DataModel dataModel = new DataModel();

            // The business logic requires the current time and the user identifier for auditing.
            Guid     createUserId   = TradingSupport.UserId;
            DateTime createDateTime = DateTime.UtcNow;
            DateTime modifiedTime   = createDateTime;
            Guid     modifiedUserId = createUserId;


            // This Web Method comes with an implicit transaction that is linked to its execution.
            DataModelTransaction dataModelTransaction = DataModelTransaction.Current;

            // This method can handle a batch of updates in a single transaction.
            foreach (ConsumerTrustNegotiationInfo consumerTrustNegotiationInfo in consumerTrustNegotiations)
            {
                List <ConsumerTrustNegotiationPaymentMethodTypeInfo> counterItems = new List <ConsumerTrustNegotiationPaymentMethodTypeInfo>();

                // The blotter is not passed in from the client but is used
                Guid   blotterId = Guid.Empty;
                Status negotiationStatus;
                TrustNegotiationInfo trustNegotiationInfo = null;
                // This is the next negotiation in the batch to be updated.
                ConsumerTrustNegotiationRow consumerTrustNegotiationRow =
                    DataModel.ConsumerTrustNegotiation.ConsumerTrustNegotiationKey.Find(consumerTrustNegotiationInfo.ConsumerTrustNegotiationId);

                try
                {
                    // Lock the current negotation record for reading.  The data model doesn't support reader lock promotion, so the programming model is to
                    // lock the database, collect the data, release the locks and then write.  This model is especially important when iterating through a
                    // large batch to prevent the number of locks from growing to large.
                    consumerTrustNegotiationRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                    // The blotter identifier is used for access control and is not passed in by the client.
                    blotterId            = consumerTrustNegotiationRow.BlotterId;
                    negotiationStatus    = StatusMap.FromId(consumerTrustNegotiationRow.StatusId);
                    trustNegotiationInfo = new TrustNegotiationInfo(consumerTrustNegotiationRow);

                    // Determine whether the client has the right to modify this record.
                    if (!TradingSupport.HasAccess(dataModelTransaction, blotterId, AccessRight.Write))
                    {
                        throw new FaultException <FluidTrade.Core.SecurityFault>(new SecurityFault("You do not have write access to the selected object."));
                    }

                    // The payment methods are maintained as a vector associated with the negotiation record.  This will lock each of the records and read the
                    // payment methods into a data structure so the locks don't need to be held when it is time to write
                    foreach (var consumerTrustNegotiationOfferPaymentMethodRow
                             in consumerTrustNegotiationRow.GetConsumerTrustNegotiationCounterPaymentMethodRows())
                    {
                        try
                        {
                            // Temporarily lock the record containing the payment method.
                            consumerTrustNegotiationOfferPaymentMethodRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);


                            // This list is used to delete the payment methods that are no longer part of this negotiation.
                            counterItems.Add(
                                new ConsumerTrustNegotiationPaymentMethodTypeInfo(
                                    consumerTrustNegotiationOfferPaymentMethodRow.PaymentMethodTypeId,
                                    consumerTrustNegotiationOfferPaymentMethodRow.ConsumerTrustNegotiationCounterPaymentMethodId,
                                    consumerTrustNegotiationOfferPaymentMethodRow.RowVersion));
                        }
                        finally
                        {
                            // At this point the payment method isn't needed.
                            consumerTrustNegotiationOfferPaymentMethodRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }

                    MatchRow matchRow = DataModel.Match.MatchKey.Find(trustNegotiationInfo.MatchId);
                    try
                    {
                        matchRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        trustNegotiationInfo.MatchRowVersion = matchRow.RowVersion;
                        trustNegotiationInfo.ContraMatchId   = matchRow.ContraMatchId;
                    }
                    finally
                    {
                        matchRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }

                    MatchRow contraMatchRow = DataModel.Match.MatchKey.Find(trustNegotiationInfo.ContraMatchId);
                    try
                    {
                        contraMatchRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                        trustNegotiationInfo.ContraMatchRowVersion = contraMatchRow.RowVersion;
                    }
                    finally
                    {
                        contraMatchRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    }
                }
                finally
                {
                    // At this point, the negotiation record isn't needed.  It is critical to release the reader locks before attempting a write.
                    consumerTrustNegotiationRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }


                // At this point, all the data for this operation has been collected and the CRUD operations can be invoked to finish the update.  Note that
                // the counter party information is not modified here, but is done through the Chinese wall.
                Guid newNegotiationId = Guid.NewGuid();
                dataModel.CreateConsumerTrustNegotiation(
                    trustNegotiationInfo.AccountBalance,
                    trustNegotiationInfo.BlotterId,
                    newNegotiationId,
                    trustNegotiationInfo.CounterPaymentLength,
                    trustNegotiationInfo.CounterPaymentStartDateLength,
                    trustNegotiationInfo.CounterPaymentStartDateUnitId,
                    trustNegotiationInfo.CounterSettlementUnitId,
                    trustNegotiationInfo.CounterSettlementValue,
                    createDateTime,
                    createUserId,
                    trustNegotiationInfo.CreditCardId,
                    trustNegotiationInfo.IsRead,
                    trustNegotiationInfo.IsReply,
                    trustNegotiationInfo.MatchId,
                    modifiedTime,
                    modifiedUserId,
                    consumerTrustNegotiationInfo.PaymentLength,
                    consumerTrustNegotiationInfo.PaymentStartDateLength,
                    consumerTrustNegotiationInfo.PaymentStartDateUnitId,
                    consumerTrustNegotiationInfo.SettlementUnitId,
                    consumerTrustNegotiationInfo.SettlementValue,
                    StatusMap.FromCode(Status.Rejected),
                    out trustNegotiationInfo.Version);

                // This will add the payment methods to the negotiation that are not already there.
                foreach (Guid paymentMethodTypeId in consumerTrustNegotiationInfo.PaymentMethodTypes)
                {
                    dataModel.CreateConsumerTrustNegotiationOfferPaymentMethod(
                        blotterId,
                        newNegotiationId,
                        Guid.NewGuid(),
                        paymentMethodTypeId);
                }

                foreach (ConsumerTrustNegotiationPaymentMethodTypeInfo consumerTrustNegotiationPaymentMethodTypeInfo in counterItems)
                {
                    dataModel.UpdateConsumerTrustNegotiationCounterPaymentMethod(
                        blotterId,
                        null,
                        new Object[] { consumerTrustNegotiationPaymentMethodTypeInfo.ConsumerTrustNegotiationOfferPaymentMethodId },
                        newNegotiationId,
                        consumerTrustNegotiationPaymentMethodTypeInfo.PaymentMethodInfoId,
                        consumerTrustNegotiationPaymentMethodTypeInfo.RowVersion);
                }

                //Reset the Match Status Id.  This is required so the match engine will redo the match.  The
                //match engine does not recalculate if it is not in the initial three stages of - Valid, Partial, ValidwithFunds
                dataModel.UpdateMatch(
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    new object[] { trustNegotiationInfo.MatchId },
                    trustNegotiationInfo.MatchRowVersion,
                    StatusMap.FromCode(Status.ValidMatch),
                    null);

                //Reset the Contra Match Status Id
                dataModel.UpdateMatch(
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    new object[] { trustNegotiationInfo.ContraMatchId },
                    trustNegotiationInfo.ContraMatchRowVersion,
                    StatusMap.FromCode(Status.ValidMatch),
                    null);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Updates the state of a collection of Trust Negotiation settlement records.
        /// </summary>
        internal static void Update(ConsumerTrustNegotiationIsReadInfo[] consumerTrustNegotiationIsReads)
        {
            // An instance of the shared data model is required to use its methods.
            DataModel dataModel = new DataModel();

            // This Web Method comes with an implicit transaction that is linked to its execution.
            DataModelTransaction dataModelTransaction = DataModelTransaction.Current;

            // This method can handle a batch of updates in a single transaction.
            foreach (ConsumerTrustNegotiationIsReadInfo consumerTrustNegotiationIsReadInfo in consumerTrustNegotiationIsReads)
            {
                try
                {
                    if (consumerTrustNegotiationIsReadInfo != null && consumerTrustNegotiationIsReadInfo.ConsumerTrustNegotiationId != Guid.Empty)
                    {
                        // The blotter is not passed in from the client but is used to validate the users access to this record.
                        Guid  blotterId  = Guid.Empty;
                        Int64 version    = 0;
                        Int64 rowVersion = 0;

                        // This is the next negotiation in the batch to be updated.
                        ConsumerTrustNegotiationRow consumerTrustNegotiationRow =
                            DataModel.ConsumerTrustNegotiation.ConsumerTrustNegotiationKey.Find(consumerTrustNegotiationIsReadInfo.ConsumerTrustNegotiationId);

                        try
                        {
                            // Lock the current negotation record for reading.  The data model doesn't support reader lock promotion, so the programming model is to
                            // lock the database, collect the data, release the locks and then write.  This model is especially important when iterating through a
                            // large batch to prevent the number of locks from growing to large.
                            consumerTrustNegotiationRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);

                            // The blotter identifier is used for access control and is not passed in by the client.
                            blotterId = consumerTrustNegotiationRow.BlotterId;
                            version   = consumerTrustNegotiationRow.Version;
                            //Use the current rowversion to update.  This is to avoid an concurrency error. The client may not have
                            //gotten the updated row if they made a change before the IsRead fired of.  Since this is a benign change
                            //we can safely update the row and let the change trickle back on update.
                            rowVersion = consumerTrustNegotiationRow.RowVersion;

                            if (rowVersion != consumerTrustNegotiationIsReadInfo.RowVersion)
                            {
                                EventLog.Warning("ConsumerTrustNegotiaion ISRead incompatible rowVersions. Expected {0}, Got {1}. Using {0}",
                                                 consumerTrustNegotiationIsReadInfo.RowVersion, rowVersion);
                            }

                            // Determine whether the client has the right to modify this record.
                            if (!TradingSupport.HasAccess(dataModelTransaction, blotterId, AccessRight.Read))
                            {
                                throw new FaultException <FluidTrade.Core.SecurityFault>(new SecurityFault("You do not have read access to the selected object."));
                            }
                        }
                        finally
                        {
                            // At this point, the negotiation record isn't needed.  It is critical to release the reader locks before attempting a write.
                            if (consumerTrustNegotiationRow != null)
                            {
                                consumerTrustNegotiationRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                            }
                        }

                        // At this point, all the data for this operation has been collected and the CRUD operations can be invoked to finish the update.  Note that
                        // the counter party information is not modified here, but is done through the Chinese wall.
                        dataModel.UpdateConsumerTrustNegotiation(
                            null,
                            null,
                            null,
                            new object[] { consumerTrustNegotiationIsReadInfo.ConsumerTrustNegotiationId },
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            consumerTrustNegotiationIsReadInfo.IsRead,
                            false,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            rowVersion,
                            null,
                            version);
                    }
                }
                catch (FaultException <FluidTrade.Core.SecurityFault> faultException)
                {
                    //Throw this back to the client because we cannot handle this
                    throw faultException;
                }
                catch (Exception ex)
                {
                    //We will log the exception and try to carry on.
                    EventLog.Error(ex);
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Update a Consumer Trust Negotiation Record.
        /// </summary>
        internal static void Update(ConsumerTrustNegotiationInfo[] consumerTrustNegotiations)
        {
            // An instance of the shared data model is required to use its methods.
            DataModel dataModel = new DataModel();

            // The business logic requires the current time and the user identifier for auditing.
            Guid     createUserId   = TradingSupport.UserId;
            DateTime createDateTime = DateTime.UtcNow;
            DateTime modifiedTime   = createDateTime;
            Guid     modifiedUserId = createUserId;

            // This Web Method comes with an implicit transaction that is linked to its execution.
            DataModelTransaction dataModelTransaction = DataModelTransaction.Current;

            // This method can handle a batch of updates in a single transaction.
            foreach (ConsumerTrustNegotiationInfo consumerTrustNegotiationInfo in consumerTrustNegotiations)
            {
                // The payment methods available to this negotiation is a vector.  Rather than delete everything and re-add it anytime an update is made, a
                // list of changes is constructed: new payment methods are added, obsolete payment methods are deleted and the ones that haven't changed are
                // left alone.  These list help to work out the differences.
                List <ConsumerTrustNegotiationPaymentMethodTypeInfo> counterItems = new List <ConsumerTrustNegotiationPaymentMethodTypeInfo>();

                // The blotter is not passed in from the client but is used
                Guid blotterId = Guid.Empty;
                TrustNegotiationInfo trustNegotiationInfo = null;
                // This is the next negotiation in the batch to be updated.
                ConsumerTrustNegotiationRow consumerTrustNegotiationRow =
                    DataModel.ConsumerTrustNegotiation.ConsumerTrustNegotiationKey.Find(consumerTrustNegotiationInfo.ConsumerTrustNegotiationId);

                Guid  matchId         = Guid.Empty;
                Int64 originalVersion = Int64.MinValue;
                // Lock the current negotation record for reading.  The data model doesn't support reader lock promotion, so the programming model is to
                // lock the database, collect the data, release the locks and then write.  This model is especially important when iterating through a
                // large batch to prevent the number of locks from growing to large.
                consumerTrustNegotiationRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                try
                {
                    matchId         = consumerTrustNegotiationRow.MatchId;
                    originalVersion = consumerTrustNegotiationRow.Version;
                }
                finally
                {
                    consumerTrustNegotiationRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                    consumerTrustNegotiationRow = null;
                }

                //Determine the most recent Negotiation to grab the counter payment methods.


                Int64    maxVersion = Int64.MinValue;
                MatchRow matchRow   = DataModel.Match.MatchKey.Find(matchId);
                matchRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                try
                {
                    foreach (ConsumerTrustNegotiationRow versionRow in matchRow.GetConsumerTrustNegotiationRows())
                    {
                        try
                        {
                            versionRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                            if (versionRow.Version > maxVersion)
                            {
                                maxVersion = versionRow.Version;
                                consumerTrustNegotiationRow = versionRow;
                            }
                        }
                        finally
                        {
                            versionRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }
                }
                finally
                {
                    matchRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }


                consumerTrustNegotiationRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);
                try
                {
                    //Check for rowversion
                    if (originalVersion != consumerTrustNegotiationRow.Version)
                    {
                        throw new global::System.ServiceModel.FaultException <FluidTrade.Core.OptimisticConcurrencyFault>(
                                  new global::FluidTrade.Core.OptimisticConcurrencyFault("ConsumerTrustNegotiation",
                                                                                         new object[] { consumerTrustNegotiationInfo.ConsumerTrustNegotiationId }),
                                  new FaultReason("Negotiation is busy.  Please try again!"));
                    }


                    // The blotter identifier is used for access control and is not passed in by the client.
                    blotterId            = consumerTrustNegotiationRow.BlotterId;
                    trustNegotiationInfo = new TrustNegotiationInfo(consumerTrustNegotiationRow);

                    // Determine whether the client has the right to modify this record.
                    if (!TradingSupport.HasAccess(dataModelTransaction, blotterId, AccessRight.Write))
                    {
                        throw new FaultException <FluidTrade.Core.SecurityFault>(new SecurityFault("You do not have write access to the selected object."));
                    }

                    // The payment methods are maintained as a vector associated with the negotiation record.  This will lock each of the records and read the
                    // payment methods into a data structure so the locks don't need to be held when it is time to write
                    foreach (var consumerTrustNegotiationOfferPaymentMethodRow
                             in consumerTrustNegotiationRow.GetConsumerTrustNegotiationCounterPaymentMethodRows())
                    {
                        try
                        {
                            // Temporarily lock the record containing the payment method.
                            consumerTrustNegotiationOfferPaymentMethodRow.AcquireReaderLock(dataModelTransaction.TransactionId, DataModel.LockTimeout);


                            // This list is used to delete the payment methods that are no longer part of this negotiation.
                            counterItems.Add(
                                new ConsumerTrustNegotiationPaymentMethodTypeInfo(
                                    consumerTrustNegotiationOfferPaymentMethodRow.PaymentMethodTypeId,
                                    consumerTrustNegotiationOfferPaymentMethodRow.ConsumerTrustNegotiationCounterPaymentMethodId,
                                    consumerTrustNegotiationOfferPaymentMethodRow.RowVersion));
                        }
                        finally
                        {
                            // At this point the payment method isn't needed.
                            consumerTrustNegotiationOfferPaymentMethodRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                        }
                    }
                }
                finally
                {
                    // At this point, the negotiation record isn't needed.  It is critical to release the reader locks before attempting a write.
                    consumerTrustNegotiationRow.ReleaseReaderLock(dataModelTransaction.TransactionId);
                }

                // At this point, all the data for this operation has been collected and the CRUD operations can be invoked to finish the update.  Note that
                // the counter party information is not modified here, but is done through the Chinese wall.
                Guid newNegotiationId = Guid.NewGuid();
                dataModel.CreateConsumerTrustNegotiation(
                    trustNegotiationInfo.AccountBalance,
                    trustNegotiationInfo.BlotterId,
                    newNegotiationId,
                    trustNegotiationInfo.CounterPaymentLength,
                    trustNegotiationInfo.CounterPaymentStartDateLength,
                    trustNegotiationInfo.CounterPaymentStartDateUnitId,
                    trustNegotiationInfo.CounterSettlementUnitId,
                    trustNegotiationInfo.CounterSettlementValue,
                    createDateTime,
                    createUserId,
                    trustNegotiationInfo.CreditCardId,
                    trustNegotiationInfo.IsRead,
                    trustNegotiationInfo.IsReply,
                    trustNegotiationInfo.MatchId,
                    modifiedTime,
                    modifiedUserId,
                    consumerTrustNegotiationInfo.PaymentLength,
                    consumerTrustNegotiationInfo.PaymentStartDateLength,
                    consumerTrustNegotiationInfo.PaymentStartDateUnitId,
                    consumerTrustNegotiationInfo.SettlementUnitId,
                    consumerTrustNegotiationInfo.SettlementValue,
                    consumerTrustNegotiationInfo.StatusId,
                    out trustNegotiationInfo.Version);

                // This will add the payment methods to the negotiation that are not already there.
                foreach (Guid paymentMethodTypeId in consumerTrustNegotiationInfo.PaymentMethodTypes)
                {
                    dataModel.CreateConsumerTrustNegotiationOfferPaymentMethod(
                        blotterId,
                        newNegotiationId,
                        Guid.NewGuid(),
                        paymentMethodTypeId);
                }

                //Since we cannot create new counter payments, we will update the existing ones.
                foreach (ConsumerTrustNegotiationPaymentMethodTypeInfo consumerTrustNegotiationPaymentMethodTypeInfo in counterItems)
                {
                    dataModel.UpdateConsumerTrustNegotiationCounterPaymentMethod(
                        blotterId,
                        null,
                        new Object[] { consumerTrustNegotiationPaymentMethodTypeInfo.ConsumerTrustNegotiationOfferPaymentMethodId },
                        newNegotiationId,
                        consumerTrustNegotiationPaymentMethodTypeInfo.PaymentMethodInfoId,
                        consumerTrustNegotiationPaymentMethodTypeInfo.RowVersion);
                }
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="row"></param>
 public ConsumerTrustNegotiation(ConsumerTrustNegotiationRow row)
 {
     this.BlotterId  = row.BlotterId;
     this.RowId      = row.ConsumerTrustNegotiationId;
     this.RowVersion = row.RowVersion;
 }
Ejemplo n.º 10
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);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates a new SettlementInfo instance.
        /// </summary>
        public SettlementItem(Guid matchId)
        {
            // Initialize the object.
            this.ChatItemList          = new List <ChatItem>();
            this.CounterPaymentMethods = new List <Guid>();
            this.OfferPaymentMethods   = new List <Guid>();

            // The data model must be locked in order to navigate the data.  The main idea here is to find the chat items and the negotiation elements
            // associated with this match and send that data to the foreground where it can be displayed.
            lock (DataModel.SyncRoot)
            {
                // This dialog will only handle matches that have this identifier.
                MatchRow matchRow = DataModel.Match.MatchKey.Find(matchId);

                if (matchRow == null)
                {
                    this.Status = Status.Deleted;
                }
                else
                {
                    // The status code drives the state of many of the controls in the console.
                    this.Status = matchRow.StatusRow.StatusCode;

                    // 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;
                    ConsumerTrustNegotiationRow consumerTrustNegotiationRow = null;
                    foreach (ConsumerTrustNegotiationRow versionRow in matchRow.GetConsumerTrustNegotiationRows())
                    {
                        if (versionRow.Version > maxVersion)
                        {
                            maxVersion = versionRow.Version;
                            consumerTrustNegotiationRow = versionRow;
                        }
                    }

                    // Extract the scalar items used in the negotiation of a settlement.
                    this.NegotiationItem = new NegotiationItem(consumerTrustNegotiationRow);

                    // The Offer Payment Methods are a vector and need to be copied iteratively.
                    foreach (ConsumerTrustNegotiationOfferPaymentMethodRow paymentMethod in
                             consumerTrustNegotiationRow.GetConsumerTrustNegotiationOfferPaymentMethodRows())
                    {
                        this.OfferPaymentMethods.Add(paymentMethod.PaymentMethodTypeId);
                    }

                    // The Conter Offer Payment methods are also a vector.
                    foreach (ConsumerTrustNegotiationCounterPaymentMethodRow paymentMethod in
                             consumerTrustNegotiationRow.GetConsumerTrustNegotiationCounterPaymentMethodRows())
                    {
                        this.CounterPaymentMethods.Add(paymentMethod.PaymentMethodTypeId);
                    }

                    // When the console is initialized it is populated with every dialog item that has occurred for this match.
                    foreach (ChatRow chatRow in matchRow.GetChatRows())
                    {
                        ChatItem chatItem = new ChatItem();
                        chatItem.CreatedTime = chatRow.CreatedTime;
                        chatItem.IsReply     = chatRow.IsReply;
                        chatItem.MatchId     = matchId;
                        chatItem.Message     = chatRow.Message;
                        this.ChatItemList.Add(chatItem);
                    }
                }
            }
        }