private static void SetReportTable(Document document, DetailCreditBalanceReportViewModel viewModel, int timezoneOffset, bool isImport, bool isForeignCurrency)
        {
            var table = new PdfPTable(10)
            {
                WidthPercentage = 95
            };

            table.SetWidths(new float[] { 10f, 10f, 10f, 10f, 10f, 10f, 10f, 10f, 10f, 10f });

            SetReportTableHeader(table);

            var cell = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            var cellAlignRight = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_RIGHT,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            var cellAlignLeft = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            var listReports = viewModel.Reports.Where(item => item.CategoryName != null).OrderBy(order => order.CategoryLayoutIndex).GroupBy(x => x.CategoryName).ToList();
            var summaryUnit = new Dictionary <string, decimal>();

            foreach (var items in listReports)
            {
                //var accountingUnitName = cat.Select(x => x.AccountingUnitName).FirstOrDefault();
                //cellAlignLeft.Phrase = new Phrase(accountingUnitName, _smallerBoldFont);
                //cellAlignLeft.Colspan = 18;
                //table.AddCell(cellAlignLeft);

                //var totalUnit = new Dictionary<string, decimal>();
                //var totalCurrency = new Dictionary<string, Dictionary<string, decimal>>();
                //decimal total = 0;
                var totalCurrencies = new Dictionary <string, decimal>();
                foreach (var element in items)
                {
                    cell.Phrase = new Phrase(element.UPODate.GetValueOrDefault().AddHours(timezoneOffset).ToString("dd-MM-yyyy"), _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(element.UPONo, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(element.URNNo, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(element.InvoiceNo, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(element.SupplierName, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(element.CategoryName, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(element.AccountingUnitName, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(element.DueDate.GetValueOrDefault().AddHours(timezoneOffset).ToString("dd-MM-yyyy"), _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(element.CurrencyCode, _smallerFont);
                    table.AddCell(cell);

                    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", element.Total), _smallerFont);
                    table.AddCell(cellAlignRight);

                    // Currency summary
                    if (totalCurrencies.ContainsKey(element.CurrencyCode))
                    {
                        totalCurrencies[element.CurrencyCode] += element.Total;
                    }
                    else
                    {
                        totalCurrencies.Add(element.CurrencyCode, element.Total);
                    }

                    //if (element.AccountingUnitName != null)
                    //{
                    //    if (totalUnit.ContainsKey(element.AccountingUnitName))
                    //        totalUnit[element.AccountingUnitName] += element.Total;
                    //    else
                    //        totalUnit.Add(element.AccountingUnitName, element.Total);

                    //    if (totalCurrency.ContainsKey(element.CurrencyCode))
                    //    {

                    //        //totalCurrency[element.CurrencyCode]["DPP"] += element.TotalSaldo;
                    //        totalCurrency[element.CurrencyCode]["Total"] += element.Total;
                    //    }
                    //    else
                    //    {
                    //        totalCurrency.Add(element.CurrencyCode, new Dictionary<string, decimal>()
                    //    {
                    //        //{"DPP", element.TotalSaldo },
                    //        {"Total", element.Total }
                    //    });
                    //    }
                    //}

                    //total += element.Total;
                }

                //if (totalCurrency.Count() > 0)
                //    cellAlignRight.Phrase = new Phrase("JUMLAH", _smallerBoldFont);
                //    cellAlignRight.Colspan = 8;
                //    cellAlignRight.Rowspan = totalCurrency.Count();
                //    table.AddCell(cellAlignRight);
                //    cellAlignRight.Colspan = 1;
                //    cellAlignRight.Rowspan = 1;
                //    foreach (var v in totalCurrency)
                //    {
                //        cell.Phrase = new Phrase(v.Key, _smallerBoldFont);
                //        table.AddCell(cell);

                //        foreach (var x in v.Value)
                //        {
                //            cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", x.Value), _smallerBoldFont);
                //            table.AddCell(cellAlignRight);
                //        }
                //    }
                //    //cellAlignRight.Phrase = new Phrase("", _smallerBoldFont);
                //    //cellAlignRight.Colspan = 17;
                //    //table.AddCell(cellAlignRight);
                //    //cellAlignRight.Colspan = 1;

                //    //cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", total), _smallerBoldFont);
                //    //table.AddCell(cellAlignRight);

                //if (totalUnit.Count() > 0)
                //    foreach (var v in totalUnit)
                //    {
                //        //cellAlignRight.Phrase = new Phrase(accountingUnitName, _smallerBoldFont);
                //        //cellAlignRight.Colspan = 14;
                //        //table.AddCell(cellAlignRight);
                //        //cellAlignRight.Colspan = 1;

                //    //    cell.Colspan = 1;
                //    //    cell.Phrase = new Phrase(v.Key, _smallerBoldFont);
                //    //    table.AddCell(cell);

                //    //    cell.Phrase = new Phrase("", _smallerBoldFont);
                //    //    table.AddCell(cell);

                //    //    cell.Phrase = new Phrase("", _smallerBoldFont);
                //    //    table.AddCell(cell);

                //    //    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", v.Value), _smallerBoldFont);
                //    //    table.AddCell(cellAlignRight);

                //      if (summaryUnit.ContainsKey(v.Key))
                //            summaryUnit[v.Key] += v.Value;
                //        else
                //            summaryUnit.Add(v.Key, v.Value);
                //    }
                foreach (var totalCurrency in totalCurrencies)
                {
                    cell.Colspan = 7;
                    cell.Phrase  = new Phrase();
                    table.AddCell(cell);
                    cell.Colspan = 1;

                    cell.Phrase = new Phrase("JUMLAH", _smallerBoldFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(totalCurrency.Key, _smallerBoldFont);
                    table.AddCell(cell);

                    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", totalCurrency.Value), _smallerBoldFont);
                    table.AddCell(cellAlignRight);
                }
            }

            document.Add(table);

            document.Add(new Paragraph("\n"));

            //Older Summary PDF
            //var summaryTable = new PdfPTable(5)
            //{
            //    WidthPercentage = 95,

            //};

            //var widthSummaryTable = new List<float>() { 2f, 1f, 2f,1f,2f };
            //summaryTable.SetWidths(widthSummaryTable.ToArray());

            ////summaryTable.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER });

            //if (isForeignCurrency || isImport)
            //    summaryTable.AddCell(GetUnitSummaryValasTable(viewModel.AccountingUnitSummaries));
            //else
            //    summaryTable.AddCell(GetUnitSummaryTable(viewModel.AccountingUnitSummaries));


            //summaryTable.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER });

            //if (isForeignCurrency || isImport)
            //    summaryTable.AddCell(GetCategoryValasTable(viewModel.CategorySummaries));
            //else
            //    summaryTable.AddCell(GetCategorySummaryTable(viewModel.CategorySummaries));

            ////summaryTable.AddCell(GetCategorySummaryTable(viewModel.AccountingUnitSummaries, viewModel.AccountingUnitSummaryTotal));
            ////summaryTable.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER });
            ////summaryTable.AddCell(GetUnitSummaryTable(summaryUnit));

            //summaryTable.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER });

            //summaryTable.AddCell(GetCurrencySummaryTable(viewModel.CurrencySummaries));



            //document.Add(summaryTable);

            //New PDF Summary
            var currencyTable = new PdfPTable(5)
            {
                WidthPercentage = 95,
            };

            var leftTable = new PdfPTable(1)
            {
                WidthPercentage = 95,
            };
            var centerTable = new PdfPTable(1)
            {
                WidthPercentage = 95,
            };
            var rightTable = new PdfPTable(1)
            {
                WidthPercentage = 95,
            };

            var leftTableCell = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_TOP,
                Border = Rectangle.NO_BORDER
            };
            var centerTableCell = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_TOP,
                Border = Rectangle.NO_BORDER
            };
            var RightTableCell = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_TOP,
                Border = Rectangle.NO_BORDER
            };

            var currencyWidthTable = new List <float>()
            {
                3f, 1f, 3f, 1f, 3f
            };

            currencyTable.SetWidths(currencyWidthTable.ToArray());

            //UnitSummary
            if (isForeignCurrency || isImport)
            {
                leftTable.AddCell(GetUnitSummaryValasTable(viewModel.AccountingUnitSummaries));
            }
            else
            {
                leftTable.AddCell(GetUnitSummaryTable(viewModel.AccountingUnitSummaries));
            }

            leftTableCell.AddElement(leftTable);
            currencyTable.AddCell(leftTableCell);

            currencyTable.AddCell(new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            });


            //CategorySummary
            if (isForeignCurrency || isImport)
            {
                centerTable.AddCell(GetCategoryValasTable(viewModel.CategorySummaries));
            }
            else
            {
                centerTable.AddCell(GetCategorySummaryTable(viewModel.CategorySummaries));
            }

            centerTableCell.AddElement(centerTable);
            currencyTable.AddCell(centerTableCell);

            currencyTable.AddCell(new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            });

            //CurrencySummary
            rightTable.AddCell(GetCurrencySummaryTable(viewModel.CurrencySummaries));
            RightTableCell.AddElement(rightTable);
            currencyTable.AddCell(RightTableCell);

            //RightTableCell.AddElement(rightTable);
            //currencyTable.AddCell(RightTableCell);

            document.Add(currencyTable);
        }
        public static MemoryStream Generate(DetailCreditBalanceReportViewModel viewModel, int timezoneOffset, DateTimeOffset?dateTo, bool isImport, bool isForeignCurrency, int accountingUnitId, int divisionId)
        {
            //var d1 = dateFrom.GetValueOrDefault().ToUniversalTime();
            var d2 = (dateTo.HasValue ? dateTo.Value : DateTimeOffset.MaxValue).ToUniversalTime();

            var document = new Document(PageSize.A4.Rotate(), 5, 5, 25, 25);
            var stream   = new MemoryStream();

            PdfWriter.GetInstance(document, stream);
            document.Open();

            var unitName     = "SEMUA UNIT";
            var divisionName = "SEMUA DIVISI";
            var separator    = " - ";

            if (accountingUnitId > 0 && divisionId == 0)
            {
                var summary = viewModel.Reports.FirstOrDefault();
                if (summary != null)
                {
                    unitName     = $"UNIT {summary.AccountingUnitName}";
                    separator    = "";
                    divisionName = "";
                }
                else
                {
                    unitName     = "";
                    separator    = "";
                    divisionName = "";
                }
            }
            else if (divisionId > 0 && accountingUnitId == 0)
            {
                var summary = viewModel.Reports.FirstOrDefault();
                if (summary != null)
                {
                    divisionName = $"DIVISI {summary.DivisionName}";
                    separator    = "";
                    unitName     = "";
                }
                else
                {
                    divisionName = "";
                    separator    = "";
                    unitName     = "";
                }
            }
            else if (accountingUnitId > 0 && divisionId > 0)
            {
                var summary = viewModel.Reports.FirstOrDefault();
                if (summary != null)
                {
                    unitName     = $"UNIT {summary.AccountingUnitName}";
                    separator    = " - ";
                    divisionName = $"DIVISI {summary.DivisionName}";
                }
                else
                {
                    divisionName = "";
                    separator    = "";
                    unitName     = "";
                }
            }

            SetHeader(document, d2, timezoneOffset, isImport, isForeignCurrency, unitName, separator, divisionName);
            document.Add(new Paragraph("\n"));
            SetReportTable(document, viewModel, timezoneOffset, isImport, isForeignCurrency);
            //document.Add(new Paragraph("\n"));
            //SetCategoryCurrencySummaryTable(document, viewModel.CategorySummaries, viewModel.CategorySummaryTotal, viewModel.CurrencySummaries);
            //SetFooter(document);

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
        public async Task <DetailCreditBalanceReportViewModel> GetReportData(int categoryId, int accountingUnitId, int divisionId, DateTimeOffset?dateTo, bool isImport, bool isForeignCurrency)
        {
            var d2 = (dateTo.HasValue ? dateTo.Value : DateTime.MaxValue).ToUniversalTime();

            var unitReceiptNoteItems   = _dbContext.UnitReceiptNoteItems.AsQueryable();
            var unitReceiptNotes       = _dbContext.UnitReceiptNotes.AsQueryable();
            var unitPaymentOrderItems  = _dbContext.UnitPaymentOrderItems.AsQueryable();
            var unitPaymentOrders      = _dbContext.UnitPaymentOrders.AsQueryable();
            var externalPurchaseOrders = _dbContext.ExternalPurchaseOrders.AsQueryable();
            var purchaseRequests       = _dbContext.PurchaseRequests.AsQueryable();

            var query = from unitReceiptNoteItem in unitReceiptNoteItems

                        join unitReceiptNote in unitReceiptNotes on unitReceiptNoteItem.URNId equals unitReceiptNote.Id into urnWithItems
                        from urnWithItem in urnWithItems.DefaultIfEmpty()

                        join unitPaymentOrderItem in unitPaymentOrderItems on urnWithItem.Id equals unitPaymentOrderItem.URNId into urnUPOItems
                        from urnUPOItem in urnUPOItems.DefaultIfEmpty()

                        join unitPaymentOrder in unitPaymentOrders on urnUPOItem.UPOId equals unitPaymentOrder.Id into upoWithItems
                        from upoWithItem in upoWithItems.DefaultIfEmpty()

                        join externalPurchaseOrder in externalPurchaseOrders on unitReceiptNoteItem.EPOId equals externalPurchaseOrder.Id into urnEPOs
                        from urnEPO in urnEPOs.DefaultIfEmpty()

                        join purchaseRequest in purchaseRequests on unitReceiptNoteItem.PRId equals purchaseRequest.Id into urnPRs
                        from urnPR in urnPRs.DefaultIfEmpty()

                        // Additional
                        //join epoDetail in _dbContext.ExternalPurchaseOrderDetails on unitReceiptNoteItem.EPODetailId equals epoDetail.Id into joinExternalPurchaseOrderDetails
                        //from urnEPODetail in joinExternalPurchaseOrderDetails.DefaultIfEmpty()

                        //where urnWithItem != null && urnWithItem.ReceiptDate != null
                        //&& urnEPO != null && urnEPO.PaymentDueDays != null
                        //&& urnWithItem.ReceiptDate.AddDays(Convert.ToInt32(urnEPO.PaymentDueDays)) <= d2
                        //&& upoWithItem != null && upoWithItem.IsPaid == false && urnEPO != null && urnEPO.SupplierIsImport == isImport

                        //where upoWithItem != null && !upoWithItem.IsPaid && (urnWithItem.SupplierIsImport == isImport) && urnWithItem.ReceiptDate.AddDays(Convert.ToInt32(urnEPO.PaymentDueDays)) <= d2

                        select new DetailCreditBalanceReport
            {
                CurrencyId    = urnEPO.CurrencyId,
                CurrencyCode  = urnEPO.CurrencyCode,
                CurrencyRate  = urnEPO.CurrencyRate,
                CategoryId    = urnPR.CategoryId,
                CategoryCode  = urnPR.CategoryCode,
                CategoryName  = urnPR.CategoryName,
                UnitId        = urnPR.UnitId,
                UnitCode      = urnPR.UnitCode,
                UnitName      = urnPR.UnitName,
                DivisionId    = urnPR.DivisionId,
                DivisionCode  = urnPR.DivisionCode,
                DivisionName  = urnPR.DivisionName,
                IsImport      = urnWithItem.SupplierIsImport,
                IsPaid        = upoWithItem != null && upoWithItem.IsPaid,
                DebtPrice     = unitReceiptNoteItem.PricePerDealUnit,
                DebtQuantity  = unitReceiptNoteItem.ReceiptQuantity,
                DebtTotal     = unitReceiptNoteItem.PricePerDealUnit * unitReceiptNoteItem.ReceiptQuantity,
                DueDate       = urnWithItem.ReceiptDate.AddDays(Convert.ToInt32(urnEPO.PaymentDueDays)),
                IncomeTaxBy   = urnEPO.IncomeTaxBy,
                UseIncomeTax  = urnEPO.UseIncomeTax,
                IncomeTaxRate = urnEPO.IncomeTaxRate,
                UseVat        = urnEPO.UseVat,

                UPODate      = urnUPOItem.UnitPaymentOrder.Date,
                UPONo        = urnUPOItem.UnitPaymentOrder != null ? urnUPOItem.UnitPaymentOrder.UPONo : "",
                URNNo        = unitReceiptNoteItem.UnitReceiptNote != null ? unitReceiptNoteItem.UnitReceiptNote.URNNo : "",
                InvoiceNo    = urnUPOItem.UnitPaymentOrder != null ? urnUPOItem.UnitPaymentOrder.InvoiceNo : "",
                SupplierName = unitReceiptNoteItem.UnitReceiptNote.SupplierName,
                //urnPR.CategoryName,
                //AccountingUnitName =
                //DueDate = urnWithItem != null && urnWithItem.ReceiptDate != null && urnEPO != null ? urnWithItem.ReceiptDate.AddDays(Convert.ToInt32(urnEPO.PaymentDueDays)) : DateTimeOffset.Now,
                //urnEPODetail.ExternalPurchaseOrderItem.ExternalPurchaseOrder.CurrencyCode,
                //TotalSaldo = unitReceiptNoteItem.PricePerDealUnit * unitReceiptNoteItem.ReceiptQuantity,

                //urnPR.CategoryId,
                //urnPR.DivisionName,
                //unitReceiptNoteItem.UnitReceiptNote.UnitId,
                //urnPR.DivisionId,
                //urnEPODetail.ExternalPurchaseOrderItem.ExternalPurchaseOrder.UseVat,
                //ReceiptQuantity = unitReceiptNoteItem.ReceiptQuantity,
                //EPOPricePerDealUnit = urnEPODetail.PricePerDealUnit,
                //unitReceiptNoteItem.IncomeTaxBy,
                //urnEPO.UseIncomeTax,
                //urnEPO.IncomeTaxRate,
            };

            query = query.Where(entity => !entity.IsPaid && (entity.IsImport == isImport) && entity.DueDate <= d2);

            if (categoryId > 0)
            {
                query = query.Where(entity => entity.CategoryId == categoryId.ToString());
            }

            //if (accountingUnitId > 0)
            //{
            //    var unitFilterIds = await _currencyProvider.GetUnitsIdsByAccountingUnitId(accountingUnitId);
            //    if (unitFilterIds.Count() > 0)
            //    {
            //        query = query.Where(unitReceiptNote => unitFilterIds.Contains(unitReceiptNote.UnitId));
            //    }
            //}

            if (accountingUnitId > 0)
            {
                var unitIds = _units.Where(unit => unit.AccountingUnitId == accountingUnitId).Select(unit => unit.Id.ToString()).ToList();
                if (unitIds.Count == 0)
                {
                    // intentionally added to make the query returns empty data
                    unitIds.Add("0");
                }
                query = query.Where(entity => unitIds.Contains(entity.UnitId));
            }

            if (divisionId > 0)
            {
                query = query.Where(entity => entity.DivisionId == divisionId.ToString());
            }

            if (!isForeignCurrency && !isImport)
            {
                query = query.Where(entity => entity.CurrencyCode.ToUpper() == "IDR" && !entity.IsImport);
            }
            else if (isForeignCurrency)
            {
                query = query.Where(entity => entity.CurrencyCode.ToUpper() != "IDR" && !entity.IsImport);
            }
            else if (isImport)
            {
                query = query.Where(entity => entity.IsImport);
            }

            //var queryResult = query.OrderByDescending(item => item.DueDate).ToList();
            var queryResult = query.ToList();

            //var currencyTuples = queryResult.Select(item => new Tuple<string, DateTimeOffset>(item.CurrencyCode, item.Date));
            //var currencies = await _currencyProvider.GetCurrencyByCurrencyCodeDateList(currencyTuples);

            //var unitIds = queryResult.Select(item =>
            //{
            //    int.TryParse(item.UnitId, out var unitId);
            //    return unitId;
            //}).Distinct().ToList();
            //var units = await _currencyProvider.GetUnitsByUnitIds(unitIds);
            //var accountingUnits = await _currencyProvider.GetAccountingUnitsByUnitIds(unitIds);

            //var itemCategoryIds = queryResult.Select(item =>
            //{
            //    int.TryParse(item.CategoryId, out var itemCategoryId);
            //    return itemCategoryId;
            //}).Distinct().ToList();
            //var categories = await _currencyProvider.GetCategoriesByCategoryIds(itemCategoryIds);
            //var accountingCategories = await _currencyProvider.GetAccountingCategoriesByCategoryIds(itemCategoryIds);


            var reportResult = new DetailCreditBalanceReportViewModel();

            foreach (var element in queryResult)
            {
                //var currency = currencies.FirstOrDefault(f => f.Code == item.CurrencyCode);
                double.TryParse(element.IncomeTaxRate, NumberStyles.Any, CultureInfo.InvariantCulture, out var incomeTaxRate);
                var debtTotal = element.DebtTotal;

                var category            = _categories.FirstOrDefault(_category => _category.Id.ToString() == element.CategoryId);
                var categoryLayoutIndex = 0;
                if (category != null)
                {
                    categoryLayoutIndex = category.ReportLayoutIndex;
                }

                var accountingUnitName = "-";
                var unit = _units.FirstOrDefault(_unit => _unit.Id.ToString() == element.UnitId);
                if (unit != null)
                {
                    var accountingUnit = _accountingUnits.FirstOrDefault(_accountingUnit => _accountingUnit.Id == unit.AccountingUnitId);
                    if (accountingUnit != null)
                    {
                        accountingUnitName = accountingUnit.Name;
                    }
                }

                if (element.UseVat)
                {
                    debtTotal += element.DebtTotal * 0.1;
                }

                if (element.UseIncomeTax && element.IncomeTaxBy.ToUpper() == "SUPPLIER")
                {
                    debtTotal -= element.DebtTotal * (incomeTaxRate / 100);
                }

                //int.TryParse(element.UnitId, out var unitId);
                //var unit = _units.FirstOrDefault(entity => entity.Id == unitId);
                //var accountingUnit = new AccountingUnit();
                //if (unit != null)
                //{
                //    accountingUnit = accountingUnits.FirstOrDefault(element => element.Id == unit.AccountingUnitId);
                //}

                //int.TryParse(item.CategoryId, out var itemCategoryId);
                //var category = categories.FirstOrDefault(element => element.Id == itemCategoryId);
                //var accountingCategory = new AccountingCategory();
                //if (category != null)
                //{
                //    accountingCategory = accountingCategories.FirstOrDefault(element => element.Id == category.AccountingCategoryId);
                //}

                //var category = _categories.FirstOrDefault(_category => _category.Id.ToString() == item.CategoryId);
                //var categoryLayoutIndex = 0;
                //if (category != null)
                //    categoryLayoutIndex = category.ReportLayoutIndex;

                //decimal dpp = 0;
                //decimal dppCurrency = 0;
                //decimal ppn = 0;
                //decimal ppnCurrency = 0;

                //double currencyRate = 1;
                //var currencyCode = "IDR";

                //decimal totalDebt = 0;
                //decimal totalDebtIDR = 0;
                //decimal incomeTax = 0;
                //decimal.TryParse(item.IncomeTaxRate, out var incomeTaxRate);


                //if (item.UseVat)
                //    ppn = (decimal)(item.EPOPricePerDealUnit * item.ReceiptQuantity * 0.1);

                //if (currency != null && !currency.Code.Equals("IDR"))
                //{
                //    currencyRate = currency.Rate.GetValueOrDefault();
                //    dpp = (decimal)(item.EPOPricePerDealUnit * item.ReceiptQuantity);
                //    dppCurrency = dpp * (decimal)currencyRate;
                //    ppnCurrency = ppn * (decimal)currencyRate;
                //    currencyCode = currency.Code;
                //}
                //else
                //    dpp = (decimal)(item.EPOPricePerDealUnit * item.ReceiptQuantity);

                //if (item.UseIncomeTax)
                //    incomeTax = (decimal)(item.EPOPricePerDealUnit * item.ReceiptQuantity) * incomeTaxRate / 100;

                //if (item.IncomeTaxBy == "Supplier")
                //{
                //    totalDebtIDR = (dpp + ppn - incomeTax) * (decimal)currencyRate;
                //    totalDebt = dpp + ppn - incomeTax;
                //}
                //else
                //{
                //    totalDebtIDR = (dpp + ppn) * (decimal)currencyRate;
                //    totalDebt = dpp + ppn;
                //}

                var reportItem = new DetailCreditBalanceReport()
                {
                    UPODate             = element.UPODate,
                    UPONo               = element.UPONo,
                    URNNo               = element.URNNo,
                    InvoiceNo           = element.InvoiceNo,
                    SupplierName        = element.SupplierName,
                    CategoryName        = element.CategoryName,
                    AccountingUnitName  = accountingUnitName,
                    DueDate             = element.DueDate,
                    CurrencyCode        = element.CurrencyCode,
                    Total               = (decimal)debtTotal,
                    TotalIDR            = (decimal)debtTotal * (decimal)element.CurrencyRate,
                    CategoryId          = element.CategoryId,
                    DivisionName        = element.DivisionName,
                    CategoryLayoutIndex = categoryLayoutIndex,
                    //TotalSaldo = (decimal)item.TotalSaldo
                    //CategoryCode = item.CategoryCode,
                    //AccountingCategoryName = accountingCategory.Name,
                    //AccountingCategoryCode = accountingCategory.Code,
                    //AccountingLayoutIndex = accountingCategory.AccountingLayoutIndex,
                    //CurrencyRate = (decimal)currencyRate,
                    //DONo = item.DONo,
                    //DPP = dpp,
                    //DPPCurrency = dppCurrency,
                    //VATNo = item.VatNo,
                    //IPONo = item.PONo,
                    //VAT = ppn,
                    //VATCurrency = ppnCurrency,
                    //Total = dpp * (decimal)currencyRate,
                    //ProductName = item.ProductName,
                    //SupplierCode = item.SupplierCode,
                    //UnitName = item.UnitName,
                    //UnitCode = item.UnitCode,
                    //AccountingUnitCode = accountingUnit.Code,
                    //IsUseVat = item.UseVat,
                    //PIBDate = item.PibDate,
                    //PIBNo = item.PibNo,
                    //PIBBM = (decimal)item.ImportDuty,
                    //PIBIncomeTax = (decimal)item.TotalIncomeTaxAmount,
                    //PIBVat = (decimal)item.TotalVatAmount,
                    //PIBImportInfo = item.ImportInfo,
                    //Remark = item.Remark,
                    //Quantity = item.ReceiptQuantity,
                    //IsPaid = item.IsPaid
                    //Saldo = (decimal)item.Saldo,
                };

                reportResult.Reports.Add(reportItem);
            }

            reportResult.AccountingUnitSummaries = reportResult.Reports
                                                   .GroupBy(report => new { report.AccountingUnitName, report.CurrencyCode })
                                                   .Select(report => new SummaryDCB()
            {
                AccountingUnitName = report.Key.AccountingUnitName,
                CurrencyCode       = report.Key.CurrencyCode,
                SubTotal           = report.Sum(sum => sum.Total),
                SubTotalIDR        = report.Sum(sum => sum.TotalIDR),
            })
                                                   .OrderBy(order => order.AccountingUnitName).ToList();

            reportResult.CurrencySummaries = reportResult.Reports
                                             .GroupBy(report => new { report.CurrencyCode })
                                             .Select(report => new SummaryDCB()
            {
                CurrencyCode = report.Key.CurrencyCode,
                SubTotal     = report.Sum(sum => sum.Total),
                SubTotalIDR  = report.Sum(sum => sum.TotalIDR)
            })
                                             .OrderBy(order => order.CurrencyCode).ToList();

            //reportResult.Reports = reportResult.Reports
            reportResult.Reports = reportResult.Reports
                                   .GroupBy(
                key => new
            {
                key.URNNo,
                key.UPONo,
                key.UPODate,
                key.InvoiceNo,
                key.SupplierName,
                key.CategoryName,
                key.AccountingUnitName,
                key.DueDate,
                key.CurrencyCode,
                key.CategoryId,
                key.DivisionName,
                key.CategoryLayoutIndex
            },
                val => val,
                (key, val) => new DetailCreditBalanceReport()
            {
                URNNo               = key.URNNo,
                UPONo               = key.UPONo,
                UPODate             = key.UPODate,
                InvoiceNo           = key.InvoiceNo,
                SupplierName        = key.SupplierName,
                CategoryName        = key.CategoryName,
                AccountingUnitName  = key.AccountingUnitName,
                DueDate             = key.DueDate,
                CurrencyCode        = key.CurrencyCode,
                Total               = val.Sum(s => s.Total),
                TotalIDR            = val.Sum(s => s.TotalIDR),
                CategoryId          = key.CategoryId,
                DivisionName        = key.DivisionName,
                CategoryLayoutIndex = key.CategoryLayoutIndex
            })
                                   .OrderBy(order => order.CategoryLayoutIndex).ToList();

            reportResult.GrandTotal = reportResult.Reports.Sum(sum => sum.Total);
            reportResult.AccountingUnitSummaryTotal = reportResult.AccountingUnitSummaries.Sum(summary => summary.SubTotal);

            return(reportResult);
        }