/// <summary> /// Автоматическая привязка Платёжных документов к Заявкам /// </summary> public void AutoBinding(fmCPRRepaymentTask RepaymentTask) { foreach (fmCSAStatementAccount sa in this.StatementOfAccounts) { sa.AutoBinding(RepaymentTask); } }
public fmCPRRepaymentJurnal( Session session, fmCPRRepaymentTask repaymentTask, fmCDocRCB paymentDocument, fmCPRPaymentRequest paymentRequest, crmBankAccount bankAccount, Decimal sumIn, Decimal sumObligationIn, Decimal sumOut, Decimal sumObligationOut, DateTime paymentDate, csValuta valutaPayment, csValuta valutaObligation, CRM.Contract.Analitic.PlaneFact planFact) : base(session) { this.RepaymentTask = repaymentTask; this.PaymentDocument = paymentDocument; this.PaymentRequest = paymentRequest; this.BankAccount = bankAccount; this.SumIn = sumIn; this.SumObligationIn = sumObligationIn; this.SumOut = sumOut; this.SumObligationOut = sumObligationOut; this.ValutaPayment = valutaPayment; this.ValutaObligation = valutaObligation; this.PaymentDate = paymentDate; this.PlaneFact = planFact; }
/// <summary> /// Закрытие неопознанноого платежа /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CloseUnknownAction_Execute(object sender, SimpleActionExecuteEventArgs e) { current = View.CurrentObject as fmCPRRepaymentTask; if (current == null) { return; } current.CloseUnknownPayment(); ObjectSpace.CommitChanges(); }
public void AutoBinding(fmCPRRepaymentTask RepaymentTask) { foreach (fmCSAStatementAccountDoc sad in this.PayInDocs) { fmCDocRCB paymentDoc = sad.PaymentDocument; paymentDoc.AutoBinding(BankAccount, RepaymentTask); } foreach (fmCSAStatementAccountDoc sad in this.PayOutDocs) { fmCDocRCB paymentDoc = sad.PaymentDocument; paymentDoc.AutoBinding(BankAccount, RepaymentTask); } }
private void RemoveRequest_Execute(object sender, SimpleActionExecuteEventArgs e) { current = View.CurrentObject as fmCPRRepaymentTask.PaymentRequestListItem; if (current == null) { return; } fmCPRRepaymentTask repaymentTask = current.RepaymentTask; if (repaymentTask == null) { return; } repaymentTask.RemoveRequestFromLineStructure(current.PaymentRequest); }
public fmCPRRepaymentTaskLine(Session session, int level, fmCPRPaymentRequestObligation levelObject, fmCPRPaymentRequest paymentRequest, DateTime paymentDate, Decimal operationJournalSum, Decimal requestSum, fmCPRRepaymentTask repaymentTask, fmCPRRepaymentTaskLine parentLine) //, Boolean isCashFlowRegister) : base(session) { _PaymentRequest = paymentRequest; _PaymentDate = paymentDate; _OperationJournalSum = operationJournalSum; _RequestSum = requestSum; _RepaymentTask = repaymentTask; _Level = level; _LevelObject = levelObject; //_IsCashFlowRegister = isCashFlowRegister; if (parentLine != null) { parentLine.Lines.Add(this); } }
/// <summary> /// Привязать созданную заявку, включить в список всех заявок /// </summary> /// <param name="obj"></param> private void BindRequest(fmCPRPaymentRequest request, IObjectSpace workOS) { if (View.CurrentObject as fmCPRRepaymentTask == null) { return; } if (request == null) { return; } fmCPRRepaymentTask task = View.CurrentObject as fmCPRRepaymentTask; fmCPRRepaymentTask nTask = workOS.GetObject <fmCPRRepaymentTask>(task); // Включение в список заявок в задаче nTask.AddRequestToAll(request, true); // обработка nTask.DoBindingRequest(request, true, 0); }
/// <summary> /// Создать и открыть объект fmCPRRepaymentTask в модальном окне /// </summary> private void ManualBinding_Execute(object sender, SimpleActionExecuteEventArgs e) { fmCSAStatementAccountDoc current = e.CurrentObject as fmCSAStatementAccountDoc; if (current == null) { return; } //fmCPRRepaymentTask RT = ObjectSpace.CreateObject<fmCPRRepaymentTask>(); //IObjectSpace objectSpace = ObjectSpace.CreateNestedObjectSpace(); // Frame.Application.CreateObjectSpace(); IObjectSpace objectSpace = Application.CreateObjectSpace(); // Create object //fmCPRRepaymentTask nestedRT = objectSpace.GetObject<fmCPRRepaymentTask>(RT); fmCPRRepaymentTask nestedRT = objectSpace.CreateObject <fmCPRRepaymentTask>(); if (current.StatementAccountIn != null) { nestedRT.BankAccount = objectSpace.GetObject <crmBankAccount>(current.StatementAccountIn.BankAccount); } else if (current.StatementAccountOut.BankAccount != null) { nestedRT.BankAccount = objectSpace.GetObject <crmBankAccount>(current.StatementAccountOut.BankAccount); } nestedRT.PaymentDocument = objectSpace.GetObject <fmCDocRCB>(current.PaymentDocument); nestedRT.FillRepaymentTaskLines(); nestedRT.FillRequestList(); // Show object string DetailViewId = Frame.Application.FindDetailViewId(nestedRT.GetType()); //BaseObject passedObj = nestedRT; // objectSpace.GetObject<BaseObject>(rt); TargetWindow openMode = TargetWindow.NewModalWindow; DetailView dv = Frame.Application.CreateDetailView(objectSpace, DetailViewId, true, nestedRT); ShowViewParameters svp = new ShowViewParameters() { CreatedView = dv, TargetWindow = openMode, Context = TemplateContext.View, CreateAllControllers = true }; e.ShowViewParameters.Assign(svp); }
/// <summary> /// Сделать привязку выбранной заявки /// </summary> private void ManualBinding_Execute(object sender, SimpleActionExecuteEventArgs e) { current = View.CurrentObject as fmCPRRepaymentTask.PaymentRequestListItem; if (current == null) { return; } fmCPRRepaymentTask repaymentTask = current.RepaymentTask; if (repaymentTask == null) { return; } repaymentTask.ManualBinding(current); //repaymentTask.FillRepaymentTaskLines(); //task.FillRequestList(); //ObjectSpace.CommitChanges(); }
public static fmCPRPaymentRequest CreateRequest(IObjectSpace workOS, fmCPRRepaymentTask repaymentTask, Type objType, FinRequestKind requestKind) { if (repaymentTask == null) { return(null); } fmCPRPaymentRequest req = workOS.CreateObject(objType) as fmCPRPaymentRequest; if (req != null) { req.State = PaymentRequestStates.OPEN; //req.ExtDocDate = DateTime.Now; req.Date = DateTime.Now; if (repaymentTask.PaymentDocument != null) { fmCDocRCB doc = repaymentTask.PaymentDocument; fmCDocRCB nDoc = workOS.GetObject <fmCDocRCB>(doc); if (nDoc.PaymentPayerRequisites != null) { req.PartyPaySender = nDoc.PaymentPayerRequisites.Party; } if (nDoc.PaymentReceiverRequisites != null) { req.PartyPayReceiver = nDoc.PaymentReceiverRequisites.Party; } // req.Number = nDoc.DocNumber; req.ExtDocNumber = nDoc.DocNumber; req.ExtDocDate = nDoc.DocDate; // req.Date = DateTime.Now; req.Summ = nDoc.PaymentCost; // По умолчанию указывваем полную сумму платёжного документа req.PayDate = nDoc.GetAccountDateChange(); req.PaymentValuta = nDoc.GetAccountValuta(); //req.Valuta = nDoc.GetAccountValuta(); // По умолчания указываем валюту платежа в качестве валюты обязательств req.Comment = nDoc.PaymentFunction; // Случай финансовой заявки fmCPRPaymentRequestFinOrder reqFin = req as fmCPRPaymentRequestFinOrder; if (reqFin != null) { reqFin.FinanceRequestKind = requestKind; if (requestKind == FinRequestKind.BANK_COMISSION || requestKind == FinRequestKind.PAYMENT_PERCENTS) { if (nDoc.PaymentReceiverRequisites.Party == null && nDoc.PaymentReceiverRequisites.BankAccount != null && nDoc.PaymentReceiverRequisites.BankAccount != null && nDoc.PaymentReceiverRequisites.BankAccount.Bank != null) { nDoc.PaymentReceiverRequisites.Party = nDoc.PaymentReceiverRequisites.BankAccount.Bank.Party; } } if (requestKind == FinRequestKind.RECEIVING_PERCENTS) { if (nDoc.PaymentPayerRequisites.Party == null && nDoc.PaymentPayerRequisites.BankAccount != null && nDoc.PaymentPayerRequisites.BankAccount != null && nDoc.PaymentPayerRequisites.BankAccount.Bank != null) { nDoc.PaymentPayerRequisites.Party = nDoc.PaymentPayerRequisites.BankAccount.Bank.Party; } } if (requestKind == FinRequestKind.PURSHASE_CURRENCY || requestKind == FinRequestKind.SALE_CURRENCY) { if (repaymentTask.BankAccount == nDoc.PaymentPayerRequisites.BankAccount) { if (nDoc.PaymentReceiverRequisites.Party == null && nDoc.PaymentReceiverRequisites.BankAccount != null && nDoc.PaymentReceiverRequisites.BankAccount != null && nDoc.PaymentReceiverRequisites.BankAccount.Bank != null) { nDoc.PaymentReceiverRequisites.Party = nDoc.PaymentReceiverRequisites.BankAccount.Bank.Party; } } else if (repaymentTask.BankAccount == nDoc.PaymentReceiverRequisites.BankAccount) { if (nDoc.PaymentPayerRequisites.Party == null && nDoc.PaymentPayerRequisites.BankAccount != null && nDoc.PaymentPayerRequisites.BankAccount != null && nDoc.PaymentPayerRequisites.BankAccount.Bank != null) { nDoc.PaymentPayerRequisites.Party = nDoc.PaymentPayerRequisites.BankAccount.Bank.Party; } } } reqFin.SetSum(nDoc.PaymentCost); reqFin.State = PaymentRequestStates.FINANCE_PAYMENT; // ПОзволено редактирование Заказа, статьи, суммы //nDoc.State = PaymentDocProcessingStates.PROCESSED; } } } return(req); }
private void CreateCFRegisterRecord(Session ssn, ForCashFlowRecord cashFlowRecord) //, crmCParty ourParty) { { crmCashFlowRegister cfr = new crmCashFlowRegister(ssn); fmCPRRepaymentTask repaymentTask = cashFlowRecord.repaymentTask; fmCDocRCB paymentDoc = cashFlowRecord.paymentDoc; fmCPRPaymentRequest paymentRequest = cashFlowRecord.paymentRequest; Guid token = paymentRequest.Oid; cfr.Token = token; cfr.Section = CashFlowRegisterSection.REPAYMENT_JOURNAL; cfr.SourceGUID = repaymentTask.Oid; // Будет пустой GUID cfr.SourceType = repaymentTask.GetType(); cfr.PaymentDocument = paymentDoc; cfr.BankAccount = repaymentTask.BankAccount; cfr.Bank = repaymentTask.BankAccount.Bank; cfr.OperationDate = cashFlowRecord.date; fmCPRPaymentRequestContract paymentRequestContract = paymentRequest as fmCPRPaymentRequestContract; //if (paymentRequestContract != null && paymentRequestContract.ContractDeal != null) { // cfr.Contract = paymentRequestContract.ContractDeal.Contract; //} if (paymentRequestContract != null) { cfr.Contract = paymentRequestContract.Contract; cfr.ContractDeal = paymentRequestContract.ContractDeal; } cfr.fmOrder = cashFlowRecord.paymentRequestObligation.Order; cfr.CostItem = cashFlowRecord.paymentRequestObligation.CostItem; cfr.Subject = (cashFlowRecord.paymentRequestObligation.Order != null) ? cashFlowRecord.paymentRequestObligation.Order.Subject : null; cfr.PrimaryParty = paymentRequest.PartyPaySender; cfr.ContragentParty = paymentRequest.PartyPayReceiver; //cfr.ObligationUnit = //cfr.PaymentItem = cfr.ValutaPayment = paymentDoc.GetAccountValuta(); cfr.ValutaObligation = cashFlowRecord.paymentRequestObligation.Valuta; // В валюте платежа //cfr.SumIn = this.PaymentDocument.GetSumIn(this.BankAccount); //cfr.SumOut = this.PaymentDocument.GetSumOut(this.BankAccount); /* * if (paymentDoc.PaymentReceiverRequisites.INN == ourParty.INN) { // && this.PaymentDocument.PaymentReceiverRequisites.StatementOfAccount.BankAccount == this.BankAccount) { * cfr.SumIn = paymentDoc.PaymentCost; * } * if (paymentDoc.PaymentPayerRequisites.INN == ourParty.INN) { // && this.PaymentDocument.PaymentPayerRequisites.StatementOfAccount.BankAccount == this.BankAccount) { * cfr.SumOut = paymentDoc.PaymentCost; * } */ if (paymentDoc.PaymentReceiverRequisites.BankAccount == cashFlowRecord.repaymentJournalRecord.BankAccount) // && this.PaymentDocument.PaymentReceiverRequisites.StatementOfAccount.BankAccount == this.BankAccount) { //cfr.SumIn = cashFlowRecord.repaymentJournalRecord.SumIn; { cfr.SumIn = cashFlowRecord.sum; } if (paymentDoc.PaymentPayerRequisites.BankAccount == cashFlowRecord.repaymentJournalRecord.BankAccount) // && this.PaymentDocument.PaymentPayerRequisites.StatementOfAccount.BankAccount == this.BankAccount) { //cfr.SumOut = cashFlowRecord.repaymentJournalRecord.SumOut; { cfr.SumOut = cashFlowRecord.sum; } // В валюте обязательств /* * if (paymentDoc.PaymentReceiverRequisites.INN == ourParty.INN) { // && this.PaymentDocument.PaymentReceiverRequisites.StatementOfAccount.BankAccount == this.BankAccount) { * cfr.SumObligationIn = cashFlowRecord.sum; * } * if (paymentDoc.PaymentPayerRequisites.INN == ourParty.INN) { // && this.PaymentDocument.PaymentPayerRequisites.StatementOfAccount.BankAccount == this.BankAccount) { * cfr.SumObligationOut = cashFlowRecord.sum; * } */ if (paymentDoc.PaymentReceiverRequisites.BankAccount == cashFlowRecord.repaymentJournalRecord.BankAccount) // && this.PaymentDocument.PaymentReceiverRequisites.StatementOfAccount.BankAccount == this.BankAccount) { //cfr.SumObligationIn = cashFlowRecord.sum; { cfr.SumObligationIn = Math.Round(cfr.SumIn * csCNMValutaCourse.GetCrossCourceOnDate(ssn, paymentDoc.GetAccountDateChange(), cfr.ValutaPayment, cfr.ValutaObligation), 4); } if (paymentDoc.PaymentPayerRequisites.BankAccount == cashFlowRecord.repaymentJournalRecord.BankAccount) // && this.PaymentDocument.PaymentPayerRequisites.StatementOfAccount.BankAccount == this.BankAccount) { //cfr.SumObligationOut = cashFlowRecord.sum; { cfr.SumObligationOut = Math.Round(cfr.SumOut * csCNMValutaCourse.GetCrossCourceOnDate(ssn, paymentDoc.GetAccountDateChange(), cfr.ValutaPayment, cfr.ValutaObligation), 4); } // В рублях try { cfr.SumInAcc = Math.Round(cfr.SumIn * csCNMValutaCourse.GetCrossCourceOnDate(ssn, paymentDoc.GetAccountDateChange(), cfr.ValutaPayment, GetValutaByCode(ssn, "RUB")), 4); cfr.SumOutAcc = Math.Round(cfr.SumOut * csCNMValutaCourse.GetCrossCourceOnDate(ssn, paymentDoc.GetAccountDateChange(), cfr.ValutaPayment, GetValutaByCode(ssn, "RUB")), 4); } catch { } cfr.PaymentRequestObligationGUID = cashFlowRecord.paymentRequestObligationGUID; //if (this.PaymentReceiverRequisites.INN == OurParty.INN && this.PaymentReceiverRequisites.StatementOfAccount.BankAccount == bankAccount) { // Res = this.PaymentCost; //} }
private void DistributeSum(Session ssn, fmCPRRepaymentJurnal repaymentJournalRecord) { // Задача привязки fmCPRRepaymentTask repaymentTask = new fmCPRRepaymentTask(ssn); fmCDocRCB paymentDoc = repaymentJournalRecord.PaymentDocument; repaymentTask.BankAccount = repaymentJournalRecord.BankAccount; repaymentTask.PaymentDocument = paymentDoc; //repaymentTask.FillRepaymentTaskLines(); //repaymentTask.FillRequestList(); // Сумма, которую надо распределить между обязательствами заявки Decimal distributeSum = 0; // repaymentJournalRecord.SumOut; //GetSumRepaymentJournal(ssn, paymentDoc); if (paymentDoc.PaymentReceiverRequisites.BankAccount == repaymentJournalRecord.BankAccount) // && this.PaymentDocument.PaymentReceiverRequisites.StatementOfAccount.BankAccount == this.BankAccount) { { distributeSum = repaymentJournalRecord.SumIn; } if (paymentDoc.PaymentPayerRequisites.BankAccount == repaymentJournalRecord.BankAccount) // && this.PaymentDocument.PaymentPayerRequisites.StatementOfAccount.BankAccount == this.BankAccount) { { distributeSum = repaymentJournalRecord.SumOut; } if (distributeSum == 0) { return; } List <ForCashFlowRecord> cashFlowRecordList = new List <ForCashFlowRecord>(); // Применяем механизм пропорциональной разбивки Decimal intermediateDistributeSum = 0; if (distributeSum != 0) { Decimal totalOblSum = 0; foreach (fmCPRPaymentRequestObligation pro in repaymentJournalRecord.PaymentRequest.PaySettlmentOfObligations) { totalOblSum += pro.Summ; } foreach (fmCPRPaymentRequestObligation pro in repaymentJournalRecord.PaymentRequest.PaySettlmentOfObligations) { Decimal proSum = Math.Round((pro.Summ / totalOblSum) * distributeSum, 4); // Пишем в промежуточный объект ForCashFlowRecord ForCashFlowRecord cashFlowRecord = new ForCashFlowRecord(); cashFlowRecord.repaymentJournalRecord = repaymentJournalRecord; cashFlowRecord.paymentDoc = paymentDoc; cashFlowRecord.repaymentTask = repaymentTask; cashFlowRecord.paymentRequest = repaymentJournalRecord.PaymentRequest; cashFlowRecord.paymentRequestObligation = pro; cashFlowRecord.sum = proSum; cashFlowRecord.date = paymentDoc.GetAccountDateChange(); cashFlowRecord.paymentRequestObligationGUID = pro.Oid; cashFlowRecordList.Add(cashFlowRecord); intermediateDistributeSum += proSum; } } // Разница между distributeSum и суммой по подуровню в результате ошибки округления Decimal diff = intermediateDistributeSum - distributeSum; if (diff != 0) { // Внесение поправки: нахождение самого большого по модулю значения и изменение этого значения // (без помощи linq) Decimal valueMax = 0; for (int i = 0; i < cashFlowRecordList.Count(); i++) { if (Math.Abs(cashFlowRecordList[i].sum) > valueMax) { valueMax = Math.Abs(cashFlowRecordList[i].sum); } } for (int i = 0; i < cashFlowRecordList.Count(); i++) { if (Math.Abs(cashFlowRecordList[i].sum) == valueMax) { cashFlowRecordList[i].sum -= diff; break; } } } CreateCFRegisterRecords(ssn, cashFlowRecordList); //, GetOurParty(ssn)); }
/// <summary> /// Ручная привязка по кнопке /// </summary> /// <param name="RepaymentTask"></param> public virtual void ManualBinding(fmCPRRepaymentTask RepaymentTask) { // Алгоритм. Из задачи RepaymentTask выбирается Платёжный документ, }
public virtual void AutoBinding(crmBankAccount BankAccount, fmCPRPaymentRequest PaymentRequest, fmCPRRepaymentTask RepaymentTask) { // Привязка с распределением счетов // Проверка на уже связанность заявки XPQuery <fmCPRRepaymentJurnal> repaymentJurnalExists = new XPQuery <fmCPRRepaymentJurnal>(this.Session); var queryRepaymentJurnalExists = from repaymentJurnal in repaymentJurnalExists where repaymentJurnal.PaymentDocument == this select repaymentJurnal; if (queryRepaymentJurnalExists.Count() > 0) { DevExpress.XtraEditors.XtraMessageBox.Show("Заявка уже привязана"); return; } // Проверка на превышение сумм if (RepaymentTask.RepaymentRegisterSum + PaymentRequest.Summ > RepaymentTask.OperationRegisterSum) { DevExpress.XtraEditors.XtraMessageBox.Show("Сумма связанных заявок превысит сумму по документам выписки. Привязка невозможна."); return; } // Наша организация crmCParty OurParty = GetOurParty(); // Привязка в принципе возможна, т.е. выбранная заявка добавляется в fmCPRRepaymentJurnal fmCPRRepaymentJurnal newRepaymentJournalRecord = new fmCPRRepaymentJurnal(Session); newRepaymentJournalRecord.BankAccount = BankAccount; //newRepaymentJournalRecord.PaymentDate = newRepaymentJournalRecord.PaymentDocument = this; newRepaymentJournalRecord.PaymentRequest = PaymentRequest; newRepaymentJournalRecord.PlaneFact = CRM.Contract.Analitic.PlaneFact.FACT; if (OurParty.INN == PaymentRequest.PartyPayReceiver.INN) { newRepaymentJournalRecord.SumIn = PaymentRequest.Summ; } if (OurParty.INN == PaymentRequest.PartyPaySender.INN) { newRepaymentJournalRecord.SumOut = PaymentRequest.Summ; } newRepaymentJournalRecord.ValutaObligation = PaymentRequest.Valuta; // Валюта обязательств newRepaymentJournalRecord.ValutaPayment = PaymentRequest.PaymentValuta; // Валюта платежа // Обновление таблицы RepaymentTaskLines // Удаление всех записей из fmCPRRepaymentTaskLine Session.Delete(RepaymentTask.RepaymentTaskLines); //Session.PurgeDeletedObjects(); // Журнал привязок XPQuery <fmCPRRepaymentJurnal> repaymentJurnals = new XPQuery <fmCPRRepaymentJurnal>(this.Session); var queryRepaymentJurnals = from repaymentJurnal in repaymentJurnals where repaymentJurnal.PaymentDocument == this select repaymentJurnal; var queryGroupRepaymentJurnals = from repaymentJurnal in queryRepaymentJurnals group repaymentJurnal by new { repaymentJurnal.PaymentRequest } into grj select new { PaymentRequest = grj.Key.PaymentRequest, GroupSumIn = grj.Sum(row => row.SumIn), GroupSumOut = grj.Sum(row => row.SumOut) }; foreach (var grj in queryGroupRepaymentJurnals) { // Добавляем запись в fmCPRRepaymentTaskLine fmCPRRepaymentTaskLine newLine = new fmCPRRepaymentTaskLine(Session); newLine.RepaymentTask = RepaymentTask; RepaymentTask.RepaymentTaskLines.Add(newLine); newLine.PaymentRequest = PaymentRequest; newLine.RequestSum = grj.GroupSumIn + grj.GroupSumOut; // Одна из них равна 0 } }
public virtual void AutoBinding(crmBankAccount BankAccount, fmCPRRepaymentTask RepaymentTask) { // Несколько замечаний. // Сопоставление ведётся только с уже существующими заявками в статусе IN_PAY. // Для данного платёжного документа выбираются только такие заявки, в которых Плательщик и Получатель // соответствуют таковым в платёжном документе. // Часть суммы платёжного документа, не покрытая заявками, должна равняться части суммы Заявки, не истраченной // на Платёжные документы. // Распределение средств Заявки из предыдущего пункта происходит по дням в операционном журнале. // Список счетов "нашей" организации XPQuery <crmBankAccount> ourBankAccounts = new XPQuery <crmBankAccount>(Session); var OurBankAccounts = (from bankAccount in ourBankAccounts where bankAccount.PrefferedParty.Code == GetOurParty().Code //"2518" select bankAccount).ToList <crmBankAccount>(); DateTime DateAccountChanged = (this.ReceivedByPayerBankDate != DateTime.MinValue) ? this.ReceivedByPayerBankDate : ((this.DeductedFromPayerAccount != DateTime.MinValue) ? this.DeductedFromPayerAccount : DateTime.MinValue); csValuta paymentValuta = crmBankAccount.GetValutaByBankAccount(Session, BankAccount); // Сумма Платёжного документа по OperationJournal (в валюте платежа) Decimal operationPaymentDocSumIn = 0, operationPaymentDocSumOut = 0; GetPaymentDocSumByOperationJournal(this, BankAccount, out operationPaymentDocSumIn, out operationPaymentDocSumOut); // @@@@@@@@@@@ Добавить проверку по BankAccount // Одна из сумм operationPaymentDocSumIn или operationPaymentDocSumOut обязательно равна 0 // Сумма Платёжного документа по RepaymentJournal (в валюте платежа - это величины SumIn и SumOut) Decimal repaymentDocSumIn = 0, repaymentDocSumOut = 0; GetPaymentDocSumByRepaymentJournal(this, BankAccount, out repaymentDocSumIn, out repaymentDocSumOut); // @@@@@@@@@@@ Добавить проверку по BankAccount // Одна из сумм repaymentDocSumIn или repaymentDocSumOut также обязательно равна 0 // Величина непокрытия Платёжного документа Заявками (все суммы в валюте платежа) Decimal deltaDocSumIn = operationPaymentDocSumIn - repaymentDocSumIn; Decimal deltaDocSumOut = operationPaymentDocSumOut - repaymentDocSumOut; if (Decimal.Compare(Math.Abs(deltaDocSumIn) + Math.Abs(deltaDocSumOut), _Accuracy) <= 0) { return; // Всё сопоставлено уже с точностью до _Accuracy - так условились! } // Одна (или обе) из сумм deltaDocSumIn или deltaDocSumOut также равна (равны) 0 Decimal deltaDocSum = deltaDocSumIn + deltaDocSumOut; // !!!!!!! ПЕРЕСМОТРЕТЬ ????????? // Поиск подходящей заявки (Статус, Плательщик, Получатель, остаточные суммы) XPQuery <fmCPRPaymentRequest> paymentRequests = new XPQuery <fmCPRPaymentRequest>(Session, true); var queryPaymentRequests = from paymentRequest in paymentRequests where (paymentRequest.State == PaymentRequestStates.IN_PAYMENT || paymentRequest.State == PaymentRequestStates.IN_BANK) && paymentRequest.PartyPayReceiver == this.PaymentReceiverRequisites.Party && paymentRequest.PartyPaySender == this.PaymentPayerRequisites.Party && OurBankAccounts.Contains <crmBankAccount>(this.PaymentPayerRequisites.BankAccount) && // Означает РАСХОД DateAccountChanged.Date >= paymentRequest.Date.Date //&& DateAccountChanged.Date < paymentRequest.Date.AddDays(3).Date select paymentRequest; foreach (var paymentRequest in queryPaymentRequests) { // Отбраковка: // (1) сумма заявки не должна быть исчерпана полностью, // (2) остаточная сумма должна равняться величине непокрытия Платёжного документа Decimal paymentRequestSumIn = 0, paymentRequestSumOut = 0; // Эти суммы в валюте платежа Decimal paymentRequestSumObligationIn = 0, paymentRequestSumObligationOut = 0; // Эти суммы в валюте обязательств GetPaymentRequestSumByRepaymentJournal( paymentRequest, BankAccount, out paymentRequestSumIn, out paymentRequestSumOut, out paymentRequestSumObligationIn, out paymentRequestSumObligationOut ); // Величина неиспользованности Заявки !!!!!!!! ПЕРЕСМОТРЕТЬ !!!!!!!!!!! // Поясение о вычислении неиспользованности. Сумма в заявке - это в валюте обязательств, чтобы её сравнить // с суммой платежа, надо перевести по кросс-курсу к валюте платежа и уже полученную сумму сравнить. Вопрос: на // какой день брать курс? Предлагается брать DateAccountChanged //Decimal deltaRequestSum = GetRequestSumByCourse(paymentRequest, paymentRequest.Valuta); // В валюте платежа Decimal deltaRequestSum = GetRequestSumByCourse(paymentRequest, paymentValuta); // В валюте платежа if (this.PaymentPayerRequisites.BankAccount == BankAccount) { deltaRequestSum -= paymentRequestSumOut; } else if (this.PaymentReceiverRequisites.BankAccount == BankAccount) { deltaRequestSum -= paymentRequestSumIn; } if (Decimal.Compare(Math.Abs(deltaRequestSum), _Accuracy) <= 0) { continue; // Переход к следующей заявке (тогда у заявки должен был бы быть статус PAYED и она не должна была попасть в рассмотрение - это предусловие контракта) } // Сравнение с точностью до 1 копейки if (Decimal.Compare(Math.Abs(deltaDocSum - deltaRequestSum), _Accuracy) <= 0) { // Создаём задачу привязки Session uow = this.Session; //using (UnitOfWork uow = new UnitOfWork(Session.ObjectLayer)) { fmCPRRepaymentTask task = new fmCPRRepaymentTask(uow); task.BankAccount = BankAccount; task.PaymentDocument = this; task.FillRepaymentTaskLines(); task.FillRequestList(); task.DoBindingRequest(paymentRequest, true, 0); //uow.CommitChanges(); //} // Поскольку заявка исчерпана, то меняем ей статус paymentRequest.State = PaymentRequestStates.PAYED; this.State = PaymentDocProcessingStates.PROCESSED; // Заявка и документ выписки полностью взаимопокрылись, поэтому break; } } }
public virtual void AutoBinding(fmCSAStatementAccountDoc StatementAccountDoc, fmCPRRepaymentTask RepaymentTask) { fmCSAStatementAccount statement = null; statement = StatementAccountDoc.PaymentPayerRequisites.StatementOfAccount; if (statement != null && statement.BankAccount != null) { AutoBinding(statement.BankAccount, RepaymentTask); } //if (statement == null) { statement = StatementAccountDoc.PaymentReceiverRequisites.StatementOfAccount; //} if (statement != null && statement.BankAccount != null) { AutoBinding(statement.BankAccount, RepaymentTask); } }