Ejemplo n.º 1
0
        internal static bool CheckPostingForAuthorized(InvoiceInformationDto invoiceInformation = null, CashInformationDto cashInformation = null, RevaluationInformationDto revalInformation = null, CounterpartyInformationDto counterpartyInformation = null)
        {
            if (invoiceInformation != null)
            {
                return(invoiceInformation.AuthorizedForPosting);
            }

            if (revalInformation != null)
            {
                return(true);
            }

            if (counterpartyInformation != null)
            {
                return(true);
            }

            return(cashInformation.AuthorizedForPosting);
        }
Ejemplo n.º 2
0
        internal static async Task <PostingStatus> GetAccountingDocumentStatus(AccountingSetupDto accountingSetup, IAccountingDocumentQueries accountingQuerie, AccountingDocument accountingDocument, string company, DateTime companyDate, InvoiceInformationDto invoiceInformation = null, CashInformationDto cashInformation = null, RevaluationInformationDto revalInformation = null, CounterpartyInformationDto counterpartyInformation = null)
        {
            accountingDocument.ErrorMessage = string.Empty;

            if (invoiceInformation != null)
            {
                if (!CheckPostingForAuthorized(invoiceInformation))
                {
                    return(PostingStatus.Incomplete);
                }
            }
            else if (cashInformation != null)
            {
                if (!CheckPostingForAuthorized(null, cashInformation))
                {
                    return(PostingStatus.Incomplete);
                }
            }
            else if (revalInformation != null)
            {
                if (!CheckPostingForAuthorized(null, null, revalInformation))
                {
                    return(PostingStatus.Incomplete);
                }
            }
            else if (counterpartyInformation != null)
            {
                if (!CheckPostingForAuthorized(null, null, null, counterpartyInformation))
                {
                    return(PostingStatus.Incomplete);
                }
            }

            if (CheckSanityCheck(accountingDocument))
            {
                if (CheckFxRateConverted(accountingDocument))
                {
                    bool ifInterface = await CheckIfInterface(accountingQuerie, accountingDocument.TransactionDocumentId, company);

                    MappingErrorMessages messages = await CheckMappingError(accountingQuerie, accountingDocument.AccountingDocumentLines, company, accountingDocument.TransactionDocumentTypeId);

                    if (ifInterface)
                    {
                        if (!messages.C2CCode)
                        {
                            accountingDocument.ErrorMessage = "C2C Code Is NULL ;";
                        }

                        if (!messages.CostAlternativeCode)
                        {
                            accountingDocument.ErrorMessage += "Cost Alternative Code Is NULL ;";
                        }

                        if (!messages.TaxInterfaceCode)
                        {
                            accountingDocument.ErrorMessage += "Tax Interface Code Is NULL ;";
                        }

                        if (!messages.NominalAlternativeAccount)
                        {
                            accountingDocument.ErrorMessage += "Nominal Alternative Code Is NULL ;";
                        }

                        if (!messages.DepartmentAlternativeCode)
                        {
                            accountingDocument.ErrorMessage += "Department Alternative Code Is NULL ;";
                        }

                        if (!string.IsNullOrEmpty(accountingDocument.ErrorMessage))
                        {
                            return(PostingStatus.MappingError);
                        }
                    }

                    if (MandatoryFieldValidation(accountingDocument))
                    {
                        accountingDocument.ErrorMessage = "Mandatory Field Missing";

                        return(PostingStatus.Held);
                    }

                    if (CheckFutureDate(accountingDocument, companyDate))
                    {
                        accountingDocument.ErrorMessage = "Future document date";
                        return(PostingStatus.Held);
                    }
                    if (!IsMonthOpenForAccounting(accountingSetup.LastMonthClosed, accountingDocument.AccountingDate, accountingSetup.NumberOfOpenPeriod))
                    {
                        accountingDocument.ErrorMessage = "Period is not open for accounting";
                        return(PostingStatus.Held);
                    }

                    return(PostingStatus.Authorised);
                }
                else
                {
                    accountingDocument.ErrorMessage = "No Fxrate found";
                    return(PostingStatus.Held);
                }
            }
            else
            {
                accountingDocument.ErrorMessage = "Unbalanced document";
                return(PostingStatus.Held);
            }
        }
        private async Task <IEnumerable <AccountingDocumentLine> > CreateAccountingDocumentLines(
            int docTypeId, Company company, AccountingSetupDto accountingSetup, FxRateInformation fxRates,
            IEnumerable <Vat> vats = null, InvoiceInformationDto invoiceInformation = null,
            IEnumerable <SectionsInformationDto> sectionsInformation = null, CashInformationDto cashInformation = null,
            ManualJournalDocumentDto manualJournal       = null, RevaluationInformationDto revalInformation     = null,
            MonthEndTADocumentDto monthEndTADocument     = null,
            FxSettlementDocumentDto fxSettlementDocument = null)
        {
            List <AccountingDocumentLine> accountingDocumentLines = new List <AccountingDocumentLine>();

            AccountingDocumentLine accountingDocumentLine;

            int postingLineId = 1;

            switch (docTypeId)
            {
            case (int)DocumentType.PI:
            case (int)DocumentType.SI:
            case (int)DocumentType.CN:
            case (int)DocumentType.DN:

                // Nominal
                InvoiceFunction invoiceFunction = CommonRules.CheckInvoiceType(invoiceInformation.InvoiceType);
                for (int index = 0; index < invoiceInformation.InvoiceLines.Count(); index++)
                {
                    if (invoiceFunction == InvoiceFunction.Washout)
                    {
                        if (invoiceInformation.InvoiceLines.ToList()[index].Type == (int)Entities.ContractType.CommercialSale)
                        {
                            // [WASHOUT_E6] For washout E6, we expect to have only one 1 to 1 washout (ie we must have only one line for a purchase
                            // contract, and one line for a sales contract)
                            // This rule is also implemented in UpdateAccountingDocumentStatusToPostedCommandHandler.CalculateAmountUpdatesForWashoutInvoice
                            accountingDocumentLine = await CreateAccountingDocumentLineForInvoice(AccountingDocumentLineType.Nominal, invoiceInformation, sectionsInformation, vats, company, accountingSetup, fxRates, postingLineId, index, null);

                            accountingDocumentLines.Add(accountingDocumentLine);
                            postingLineId++;
                        }
                    }
                    else if (invoiceFunction == InvoiceFunction.Cancelled)
                    {
                        accountingDocumentLine = await CreateAccountingDocumentLineForInvoice(AccountingDocumentLineType.Nominal, invoiceInformation, sectionsInformation, vats, company, accountingSetup, fxRates, postingLineId, index, null);

                        accountingDocumentLines.Add(accountingDocumentLine);
                        postingLineId++;
                    }
                    else
                    {
                        accountingDocumentLine = await CreateAccountingDocumentLineForInvoice(AccountingDocumentLineType.Nominal, invoiceInformation, sectionsInformation, vats, company, accountingSetup, fxRates, postingLineId, index, null);

                        accountingDocumentLines.Add(accountingDocumentLine);
                        postingLineId++;
                    }
                }

                // Tax
                for (int index = 0; index < vats.Count(); index++)
                {
                    accountingDocumentLine = await CreateAccountingDocumentLineForInvoice(AccountingDocumentLineType.Tax, invoiceInformation, sectionsInformation, vats, company, accountingSetup, fxRates, postingLineId, index, accountingDocumentLines);

                    accountingDocumentLines.Add(accountingDocumentLine);
                    postingLineId++;
                }

                // Client
                accountingDocumentLine = await CreateAccountingDocumentLineForInvoice(AccountingDocumentLineType.Client, invoiceInformation, sectionsInformation, vats, company, accountingSetup, fxRates, postingLineId, 0, accountingDocumentLines);

                accountingDocumentLine.SourceInvoiceId = invoiceInformation.InvoiceId;
                accountingDocumentLines.Add(accountingDocumentLine);

                break;

            case (int)DocumentType.CP:
            case (int)DocumentType.CI:

                AccountingDocumentLine accountingDocumentLineForDocumentReference = new AccountingDocumentLine();

                accountingDocumentLine = await CreateAccountingDocumentLineForSimpleCash(AccountingDocumentLineType.Client, docTypeId, cashInformation, company, fxRates, postingLineId, accountingSetup);

                // Note: this is here for simple cash. There is no secondary reference, as at that time, the cash is no matched...
                accountingDocumentLines.Add(accountingDocumentLine);

                // Nominal
                postingLineId++;
                accountingDocumentLine = await CreateAccountingDocumentLineForSimpleCash(AccountingDocumentLineType.Nominal, docTypeId, cashInformation, company, fxRates, postingLineId, accountingSetup);

                accountingDocumentLines.Add(accountingDocumentLine);

                if (cashInformation.AdditionalCosts != null && cashInformation.AdditionalCosts.Any())
                {
                    for (int index = 0; index < cashInformation.AdditionalCosts.Count(); index++)
                    {
                        postingLineId++;
                        AccountingDocumentLine accountingDocumentLineForAdditionalCosts = new AccountingDocumentLine();
                        AdditionalCostsDto     additionalCostsDto = cashInformation.AdditionalCosts.ToList()[index];
                        accountingDocumentLineForAdditionalCosts.PostingLineId         = postingLineId;
                        accountingDocumentLineForAdditionalCosts.AccountLineTypeId     = (int)AccountLineType.L;
                        accountingDocumentLineForAdditionalCosts.Amount                = additionalCostsDto.CostDirectionId == (int)Entities.CostDirectionType.Pay ? cashInformation.AdditionalCosts.ToList()[index].Amount : -cashInformation.AdditionalCosts.ToList()[index].Amount;
                        accountingDocumentLineForAdditionalCosts.AccountReference      = additionalCostsDto.AccountReference;
                        accountingDocumentLineForAdditionalCosts.CostTypeCode          = additionalCostsDto.CostTypeCode;
                        accountingDocumentLineForAdditionalCosts.AssociatedAccountCode = accountingDocumentLine.AssociatedAccountCode;
                        accountingDocumentLineForAdditionalCosts.DepartmentId          = accountingDocumentLine.DepartmentId;
                        accountingDocumentLineForAdditionalCosts.Narrative             = additionalCostsDto.Narrative;
                        accountingDocumentLineForAdditionalCosts.AccountingCategoryId  = (int)AccountingCategory.N;
                        accountingDocumentLineForAdditionalCosts.Amount                = Math.Round(accountingDocumentLineForAdditionalCosts.Amount, CommonRules.RoundDecimals);
                        accountingDocumentLineForAdditionalCosts.ClientAccount         = null;
                        accountingDocumentLineForAdditionalCosts.SourceCostLineId      = cashInformation.AdditionalCosts.ToList()[index].CashAdditionalCostId;
                        decimal?amountInUSD = accountingDocumentLineForAdditionalCosts.Amount;

                        if (additionalCostsDto.CurrencyCode != null && additionalCostsDto.CurrencyCode.ToUpperInvariant() != CommonRules.BaseCurrency)
                        {
                            amountInUSD = (await _foreignExchangeRateService.Convert(additionalCostsDto.CurrencyCode, CommonRules.BaseCurrency, accountingDocumentLineForAdditionalCosts.Amount, cashInformation.DocumentDate)).ConvertedValue;
                        }

                        accountingDocumentLineForAdditionalCosts = await CommonRules.CalculateFunctionalAndStatutoryCurrency(_foreignExchangeRateService, accountingDocumentLineForAdditionalCosts, amountInUSD, fxRates, company, CommonRules.BaseCurrency, CommonRules.RoundDecimals);

                        accountingDocumentLines.Add(accountingDocumentLineForAdditionalCosts);
                    }
                }

                break;

            case (int)DocumentType.MJL:
                foreach (ManualJournalLineDto manualJournalLine in manualJournal.ManualJournalLines)
                {
                    accountingDocumentLine = await CreateAccountingDocumentLineForManualJournal(docTypeId, company, manualJournal, fxRates, manualJournalLine, postingLineId, accountingSetup);

                    accountingDocumentLines.Add(accountingDocumentLine);
                    postingLineId++;
                }

                break;

            case (int)DocumentType.MTA:

                if (manualJournal != null && (manualJournal.TATypeId == (int)TAType.ManualTemporaryAdjustment || manualJournal.TATypeId == (int)TAType.ManualMarkToMarket))
                {
                    IEnumerable <ManualJournalLineDto> manualJournalLines = manualJournal.ManualJournalLines.OrderBy(x => x.AccrualNumber);

                    int?previousAccuralNumber = manualJournal.ManualJournalLines.FirstOrDefault().AccrualNumber;

                    foreach (ManualJournalLineDto manualJournalLine in manualJournalLines)
                    {
                        if (previousAccuralNumber != manualJournalLine.AccrualNumber)
                        {
                            postingLineId         = 1;
                            previousAccuralNumber = manualJournalLine.AccrualNumber;
                        }

                        accountingDocumentLine = await CreateAccountingDocumentLineForManualJournal(docTypeId, company, manualJournal, fxRates, manualJournalLine, postingLineId, accountingSetup);

                        accountingDocumentLines.Add(accountingDocumentLine);

                        if (previousAccuralNumber == manualJournalLine.AccrualNumber)
                        {
                            postingLineId++;
                        }

                        previousAccuralNumber = manualJournalLine.AccrualNumber;
                    }
                }

                else if (monthEndTADocument != null && (monthEndTADocument.TATypeId == (int)TAType.MonthEndTemporaryAdjustment || monthEndTADocument.TATypeId == (int)TAType.FxDealMonthTemporaryAdjustment))
                {
                    IEnumerable <MonthEndTALineDto> monthEndLines = monthEndTADocument.MonthEndTALines.OrderBy(x => x.AccrualNumber);

                    foreach (MonthEndTALineDto monthEndLine in monthEndLines)
                    {
                        accountingDocumentLine = await CreateAccountingDocumentLineForMonthEndTA(docTypeId, company, monthEndTADocument, fxRates, monthEndLine, postingLineId);

                        if (monthEndTADocument.TATypeId == (int)TAType.FxDealMonthTemporaryAdjustment)
                        {
                            postingLineId++;
                            accountingDocumentLine.AccountingCategoryId = (int)AccountingCategory.N;
                            accountingDocumentLine.AccountLineTypeId    = (int)AccountLineType.L;
                        }

                        accountingDocumentLines.Add(accountingDocumentLine);
                    }
                }

                break;

            case (int)DocumentType.FJ:
                accountingDocumentLine = await CreateAccountingDocumentLineForFJDocument(docTypeId, postingLineId, accountingSetup, AccountLineType.B, company, fxRates, fxSettlementDocument);

                accountingDocumentLines.Add(accountingDocumentLine);
                postingLineId++;

                accountingDocumentLine = await CreateAccountingDocumentLineForFJDocument(docTypeId, postingLineId, accountingSetup, AccountLineType.L, company, fxRates, fxSettlementDocument);

                accountingDocumentLines.Add(accountingDocumentLine);
                break;
            }

            return(accountingDocumentLines);
        }
Ejemplo n.º 4
0
        internal static async Task <AccountingDocument> CreateAccountingDocument(
            IMasterDataService masterDataService,
            long userId,
            bool postOpClosedPrivilege,
            long docId,
            int docTypeId,
            string baseCurrency,
            FxRateConversion fxRate,
            AccountingSetupDto accountingSetup,
            InvoiceInformationDto invoiceInformation = null,
            CashInformationDto cashInformation       = null,
            DateTime?blDate = null,
            ManualJournalDocumentDto manualJournal             = null,
            RevaluationInformationDto revalInformation         = null,
            MonthEndTADocumentDto monthEndTADocument           = null,
            CounterpartyInformationDto counterpartyInformation = null,
            CashForCounterpartyDto cashForCounterpartyDto      = null,
            FxSettlementDocumentDto fxSettlementDocument       = null)
        {
            AccountingDocument accountingDocument = new AccountingDocument();

            accountingDocument.UserCreator           = userId;
            accountingDocument.TransactionDocumentId = docId;
            accountingDocument.ProvinceId            = null;
            accountingDocument.OriginalReferenceId   = null;

            if (fxRate.FxCurrency.ToUpperInvariant() == baseCurrency)
            {
                accountingDocument.Roe     = 1;
                accountingDocument.RoeType = "M";
            }
            else
            {
                FxRate fxRateUSD = await masterDataService.GetFxRateAsync(fxRate.FxDate, fxRate.FxCurrency);

                accountingDocument.Roe     = fxRateUSD != null ? fxRateUSD.Rate : null;
                accountingDocument.RoeType = fxRateUSD != null ? fxRateUSD.CurrencyRoeType : null;
            }

            accountingDocument.TransactionDocumentTypeId = docTypeId;
            accountingDocument.AcknowledgementDate       = null;

            switch (docTypeId)
            {
            case (int)DocumentType.PI:
            case (int)DocumentType.SI:
            case (int)DocumentType.CN:
            case (int)DocumentType.DN:
                accountingDocument.CurrencyCode      = invoiceInformation.Currency;
                accountingDocument.AccountingPeriod  = CommonRules.CalculateAccountPeriod(accountingSetup, invoiceInformation.InvoiceDate, postOpClosedPrivilege);
                accountingDocument.DocumentDate      = invoiceInformation.InvoiceDate;
                accountingDocument.ValueDate         = invoiceInformation.InvoiceDueDate;
                accountingDocument.GLDate            = blDate;
                accountingDocument.OriginalValueDate = invoiceInformation.InvoiceDueDate;
                accountingDocument.AccountingDate    = CommonRules.CalculateAccountPeriod(accountingSetup, invoiceInformation.InvoiceDate, postOpClosedPrivilege);

                break;

            case (int)DocumentType.CP:
            case (int)DocumentType.CI:
                if (counterpartyInformation != null && cashForCounterpartyDto.CashTypeId == (int)CashSelectionType.PaymentDifferentClient && cashForCounterpartyDto.JLTypeId == (int)JLType.CounterPartyTransfer)
                {
                    accountingDocument.CurrencyCode      = counterpartyInformation.CurrencyCode;
                    accountingDocument.AccountingPeriod  = CommonRules.CalculateAccountPeriod(accountingSetup, counterpartyInformation.DocumentDate, postOpClosedPrivilege);
                    accountingDocument.DocumentDate      = counterpartyInformation.DocumentDate;
                    accountingDocument.ValueDate         = counterpartyInformation.ValueDate == null ? counterpartyInformation.DocumentDate : (DateTime)counterpartyInformation.ValueDate;
                    accountingDocument.GLDate            = counterpartyInformation.DocumentDate;
                    accountingDocument.OriginalValueDate = counterpartyInformation.ValueDate == null ? counterpartyInformation.DocumentDate : (DateTime)counterpartyInformation.ValueDate;
                    accountingDocument.AccountingDate    = CommonRules.CalculateAccountPeriod(accountingSetup, counterpartyInformation.DocumentDate, postOpClosedPrivilege);
                }
                else
                {
                    accountingDocument.CurrencyCode      = cashInformation.Currency;
                    accountingDocument.AccountingPeriod  = CommonRules.CalculateAccountPeriod(accountingSetup, cashInformation.DocumentDate, postOpClosedPrivilege);
                    accountingDocument.DocumentDate      = cashInformation.DocumentDate;
                    accountingDocument.ValueDate         = cashInformation.ValueDate;
                    accountingDocument.GLDate            = cashInformation.DocumentDate;
                    accountingDocument.OriginalValueDate = cashInformation.ValueDate;
                    accountingDocument.AccountingDate    = CommonRules.CalculateAccountPeriod(accountingSetup, cashInformation.DocumentDate, postOpClosedPrivilege);
                }

                break;

            case (int)DocumentType.MTA:
            case (int)DocumentType.MJL:
                if (monthEndTADocument != null && (monthEndTADocument.TATypeId == (int)TAType.MonthEndTemporaryAdjustment || monthEndTADocument.TATypeId == (int)TAType.FxDealMonthTemporaryAdjustment))
                {
                    accountingDocument.CurrencyCode      = monthEndTADocument.CurrencyCode;
                    accountingDocument.ValueDate         = monthEndTADocument.ValueDate;
                    accountingDocument.DocumentDate      = new DateTime(accountingDocument.ValueDate.Value.Year, accountingDocument.ValueDate.Value.Month, 1).AddDays(-1);
                    accountingDocument.AccountingPeriod  = monthEndTADocument.AccountingPeriod.Value;
                    accountingDocument.GLDate            = monthEndTADocument.MonthEndTALines.FirstOrDefault().BLDate;
                    accountingDocument.OriginalValueDate = (DateTime)monthEndTADocument.ValueDate;
                    accountingDocument.AccountingDate    = accountingDocument.DocumentDate.Year == monthEndTADocument.AccountingPeriod.Value.Year && accountingDocument.DocumentDate.Month == monthEndTADocument.AccountingPeriod.Value.Month ? accountingDocument.DocumentDate : new DateTime(monthEndTADocument.AccountingPeriod.Value.Year, monthEndTADocument.AccountingPeriod.Value.Month, 1);
                }
                else
                {
                    accountingDocument.CurrencyCode      = manualJournal.CurrencyCode;
                    accountingDocument.AccountingPeriod  = manualJournal.AccountingPeriod;
                    accountingDocument.DocumentDate      = manualJournal.DocumentDate;
                    accountingDocument.GLDate            = manualJournal.DocumentDate;
                    accountingDocument.OriginalValueDate = manualJournal.ValueDate == null ? manualJournal.DocumentDate : (DateTime)manualJournal.ValueDate;
                    accountingDocument.AccountingDate    = manualJournal.DocumentDate;

                    if (docTypeId == (int)DocumentType.MTA)
                    {
                        accountingDocument.ValueDate = manualJournal.ValueDate == null ? new DateTime(manualJournal.DocumentDate.Year, manualJournal.DocumentDate.Month, 1).AddMonths(1) : (DateTime)manualJournal.ValueDate;
                    }

                    if (docTypeId == (int)DocumentType.MJL)
                    {
                        accountingDocument.ValueDate = manualJournal.ValueDate == null ? manualJournal.DocumentDate : manualJournal.ValueDate;
                    }
                }

                break;

            case (int)DocumentType.FJ:
                accountingDocument.DocumentReference = fxSettlementDocument.DocumentReference;
                if (fxSettlementDocument.IsNdf)
                {
                    accountingDocument.ValueDate = fxSettlementDocument.NdfAgreedDate;
                }
                else
                {
                    accountingDocument.ValueDate = fxSettlementDocument.MaturityDate;
                }
                accountingDocument.DocumentDate      = fxSettlementDocument.MaturityDate;
                accountingDocument.GLDate            = fxSettlementDocument.MaturityDate;
                accountingDocument.OriginalValueDate = fxSettlementDocument.DocumentDate;
                if (fxSettlementDocument != null && fxSettlementDocument.FxSettlementDocumentTypeId != FxSettlementDocumentType.FxDeal)
                {
                    accountingDocument.CurrencyCode = fxSettlementDocument.SettlementCurrencyCode;
                }
                else
                {
                    accountingDocument.CurrencyCode = fxSettlementDocument.CurrencyCode;
                }

                break;
            }

            return(accountingDocument);
        }
        private async Task <AccountingDocument> GetInformationForRevaluation(
            bool postOpClosedPrivilege,
            long transactionDocumentId,
            int docTypeId,
            AccountingSetupDto accountingSetup,
            Company company,
            DateTime companyDate,
            RevaluationInformationDto revalInformation)
        {
            AccountingDocument accountingDocument = null;

            if (accountingSetup != null)
            {
                // Creating the accounting header
                accountingDocument = new AccountingDocument()
                {
                    UserCreator           = _identityService.GetUserAtlasId(),
                    TransactionDocumentId = transactionDocumentId,
                    ProvinceId            = null,
                    OriginalReferenceId   = null,
                    Roe     = 1,
                    RoeType = "D",
                    TransactionDocumentTypeId = docTypeId,
                    AcknowledgementDate       = null,
                    CurrencyCode      = revalInformation.CurrencyCode,
                    DocumentDate      = revalInformation.PaymentDocumentDate,
                    ValueDate         = revalInformation.PaymentDocumentDate,
                    GLDate            = revalInformation.PaymentDocumentDate,
                    AccountingPeriod  = CommonRules.CalculateAccountPeriod(accountingSetup, revalInformation.PaymentDocumentDate, postOpClosedPrivilege),
                    AccountingDate    = CommonRules.CalculateAccountPeriod(accountingSetup, revalInformation.PaymentDocumentDate, postOpClosedPrivilege),
                    OriginalValueDate = revalInformation.PaymentDocumentDate
                };

                var documentReference = revalInformation.ExistingDocumentMatchingInfo.FirstOrDefault(b => b.TransactionDocumentId == transactionDocumentId).DocumentReference;

                // Creation of a copy of the document matching in which we will:
                // - update the roe of the values in all ccies
                // - sign the value in a "Accounting lines" oriented way
                List <InputInfoLinesForRevaluation> inputInfoLinesForRevaluationList = new List <InputInfoLinesForRevaluation>();
                foreach (var item in revalInformation.DocumentMatchingForMatchedDocuments)
                {
                    int inversionFactor = 1;
                    switch ((TransactionDocumentType)item.TransactionDocumentTypeId)
                    {
                    case TransactionDocumentType.CashReceipt:
                    case TransactionDocumentType.PurchaseInvoice:
                    case TransactionDocumentType.CreditNote:
                        inversionFactor = -1;
                        break;

                    case TransactionDocumentType.CashPay:
                    case TransactionDocumentType.SalesInvoice:
                    case TransactionDocumentType.DebitNote:
                    case TransactionDocumentType.ManualRegularJournal:
                        inversionFactor = 1;
                        break;
                    }

                    var inputInfoLinesForRevaluation = new InputInfoLinesForRevaluation()
                    {
                        DepartmentId         = item.DepartmentId,
                        AccountingLineTypeId = item.AccountingLineTypeId,
                        Amount = item.Amount * inversionFactor,
                        FunctionalCcyAmount = item.FunctionalCcyAmount * inversionFactor,
                        StatutoryCcyAmount  = item.StatutoryCcyAmount * inversionFactor,
                    };

                    // Rounding the converted values to 2 digits (only if currencies are not the same)
                    if (revalInformation.MatchingCurrency != company.FunctionalCurrencyCode)
                    {
                        inputInfoLinesForRevaluation.FunctionalCcyAmount = Math.Round(inputInfoLinesForRevaluation.FunctionalCcyAmount.Value, 2, MidpointRounding.AwayFromZero); // the default rounding option for .NET is MidPointRounding.ToEven, but that this option does not produce the desired result for some of values: -1119.965 was getting rounded to -1119.96 instead of -1119.97
                    }

                    if (revalInformation.MatchingCurrency != company.StatutoryCurrencyCode)
                    {
                        inputInfoLinesForRevaluation.StatutoryCcyAmount = Math.Round(inputInfoLinesForRevaluation.StatutoryCcyAmount.Value, 2, MidpointRounding.AwayFromZero); // the default rounding option for .NET is MidPointRounding.ToEven, but that this option does not produce the desired result for some of values: -1119.965 was getting rounded to -1119.96 instead of -1119.97
                    }

                    inputInfoLinesForRevaluationList.Add(inputInfoLinesForRevaluation);
                }

                // Summing by department and accountinglinetype
                var revaluationJournalClientListOne = inputInfoLinesForRevaluationList.GroupBy(d => new { d.DepartmentId, d.AccountingLineTypeId })
                                                      .Select(g => new
                {
                    g.Key.DepartmentId,
                    g.Key.AccountingLineTypeId,
                    Amount = g.Sum(s => s.Amount),
                    FunctionalCcyAmount = g.Sum(s => s.FunctionalCcyAmount),
                    StatutoryCcyAmount  = g.Sum(s => s.StatutoryCcyAmount),
                }).ToList();

                // Creation of the lines
                List <AccountingDocumentLine> accountingDocumentLines = new List <AccountingDocumentLine>();
                int postingLineId = 1;
                foreach (var item in revaluationJournalClientListOne)
                {
                    if (item.FunctionalCcyAmount.Value == 0 &&
                        item.StatutoryCcyAmount.Value == 0)
                    {
                        // We dont create reval lines if there is no difference in the values
                        continue;
                    }

                    AccountingDocumentLine accountingDocLine = new AccountingDocumentLine();
                    accountingDocLine.AssociatedAccountId  = revalInformation.CounterpartyId;
                    accountingDocLine.CostTypeCode         = revalInformation.CostTypeCode;
                    accountingDocLine.CostTypeId           = revalInformation.CostTypeId;
                    accountingDocLine.PaymentTermId        = null;
                    accountingDocLine.PaymentTermCode      = null;
                    accountingDocLine.DepartmentId         = item.DepartmentId;
                    accountingDocLine.AccountReferenceId   = null;
                    accountingDocLine.ClientAccountId      = revalInformation.CounterpartyId;
                    accountingDocLine.AccountReference     = accountingSetup.NominalCostTypeInfo.Where(x => x.CostTypeCode == revalInformation.CostTypeCode).FirstOrDefault().NominalAccountCode;
                    accountingDocLine.PostingLineId        = postingLineId;
                    accountingDocLine.AccountingCategoryId = (int)AccountingCategory.C;
                    accountingDocLine.AccountLineTypeId    = item.AccountingLineTypeId;
                    accountingDocLine.AccountReference     = item.AccountingLineTypeId == (int)AccountLineType.V ? accountingSetup.PurchaseLedgerControlClientCreditors : accountingSetup.SalesLedgerControlClientDebtors;
                    accountingDocLine.ClientReference      = null;
                    accountingDocLine.Narrative            = "Revaluation For Match";
                    accountingDocLine.Amount             = (-1) * item.Amount;
                    accountingDocLine.FunctionalCurrency = (-1) * item.FunctionalCcyAmount;
                    accountingDocLine.StatutoryCurrency  = (-1) * item.StatutoryCcyAmount;

                    //Diff Client
                    if (revalInformation.DifferentClientMatchFlagId != null)
                    {
                        var secRef = revalInformation.DocumentMatchingForMatchedDocuments.FirstOrDefault(i => i.DocumentType == DocumentType.MJL)?.DocumentReference;
                        accountingDocLine.SecondaryDocumentReference = secRef ?? revalInformation.CashByPickingReference;
                    }
                    else
                    {
                        accountingDocLine.SecondaryDocumentReference = revalInformation.CashByPickingReference;
                    }

                    postingLineId++;
                    accountingDocumentLines.Add(accountingDocLine);
                }

                var accLinesOfTypeClient = revaluationJournalClientListOne.GroupBy(d => d.DepartmentId)
                                           .Select(g => new
                {
                    DepartmentId        = g.Key,
                    Amount              = (-1) * g.Sum(s => s.Amount),
                    FunctionalCcyAmount = (-1) * g.Sum(s => s.FunctionalCcyAmount),
                    StatutoryCcyAmount  = (-1) * g.Sum(s => s.StatutoryCcyAmount),
                }).ToList();

                foreach (var accLineOfTypeClient in accLinesOfTypeClient)
                {
                    if (accLineOfTypeClient.FunctionalCcyAmount.Value == 0 &&
                        accLineOfTypeClient.StatutoryCcyAmount.Value == 0)
                    {
                        // We dont create reval lines if there is no difference in the values
                        continue;
                    }

                    AccountingDocumentLine accountingDocumentLineFormanualDocumentMatching = new AccountingDocumentLine();
                    accountingDocumentLineFormanualDocumentMatching.CostTypeCode         = revalInformation.CostTypeCode;
                    accountingDocumentLineFormanualDocumentMatching.CostTypeId           = revalInformation.CostTypeId;
                    accountingDocumentLineFormanualDocumentMatching.PaymentTermId        = null;
                    accountingDocumentLineFormanualDocumentMatching.PaymentTermCode      = null;
                    accountingDocumentLineFormanualDocumentMatching.DepartmentId         = accLineOfTypeClient.DepartmentId;
                    accountingDocumentLineFormanualDocumentMatching.PostingLineId        = postingLineId;
                    accountingDocumentLineFormanualDocumentMatching.AccountingCategoryId = (int)AccountingCategory.N;
                    accountingDocumentLineFormanualDocumentMatching.AssociatedAccountId  = revalInformation.CounterpartyId;
                    accountingDocumentLineFormanualDocumentMatching.AccountLineTypeId    = (int)AccountLineType.L;
                    accountingDocumentLineFormanualDocumentMatching.ClientReference      = null;
                    accountingDocumentLineFormanualDocumentMatching.Narrative            = "Revaluation For Match";
                    accountingDocumentLineFormanualDocumentMatching.Amount             = 0;
                    accountingDocumentLineFormanualDocumentMatching.FunctionalCurrency = -accLineOfTypeClient.FunctionalCcyAmount;
                    accountingDocumentLineFormanualDocumentMatching.StatutoryCurrency  = -accLineOfTypeClient.StatutoryCcyAmount;

                    //Diff Client
                    if (revalInformation.DifferentClientMatchFlagId != null)
                    {
                        var secRef = revalInformation.DocumentMatchingForMatchedDocuments.FirstOrDefault(i => i.DocumentType == DocumentType.MJL)?.DocumentReference;
                        accountingDocumentLineFormanualDocumentMatching.SecondaryDocumentReference = secRef ?? revalInformation.CashByPickingReference;
                    }
                    else
                    {
                        accountingDocumentLineFormanualDocumentMatching.SecondaryDocumentReference = revalInformation.CashByPickingReference;
                    }

                    accountingDocumentLineFormanualDocumentMatching.AccountReference      = revalInformation.AccountNumber;
                    accountingDocumentLineFormanualDocumentMatching.ClientReference       = null;
                    accountingDocumentLineFormanualDocumentMatching.AssociatedAccountCode = revalInformation.CounterpartyCode;

                    postingLineId++;
                    accountingDocumentLines.Add(accountingDocumentLineFormanualDocumentMatching);
                }

                accountingDocument.AccountingDocumentLines = accountingDocumentLines;
                accountingDocument.StatusId = PostingStatus.Authorised;
            }

            return(accountingDocument);
        }