private async Task AutoCreateJournalTransaction(UnitPaymentCorrectionNote unitPaymentCorrection)
        {
            foreach (var unitPaymentCorrectionItem in unitPaymentCorrection.Items)
            {
                var unitReceiptNote = dbContext.UnitReceiptNotes.Where(entity => entity.URNNo == unitPaymentCorrectionItem.URNNo).Include(entity => entity.Items).FirstOrDefault();

                var jsonSerializerSettings = new JsonSerializerSettings
                {
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };

                var divisions   = JsonConvert.DeserializeObject <List <IdCOAResult> >(_jsonDivisions ?? "[]", jsonSerializerSettings);
                var units       = JsonConvert.DeserializeObject <List <IdCOAResult> >(_jsonUnits ?? "[]", jsonSerializerSettings);
                var categories  = JsonConvert.DeserializeObject <List <CategoryCOAResult> >(_jsonCategories ?? "[]", jsonSerializerSettings);
                var incomeTaxes = JsonConvert.DeserializeObject <List <IncomeTaxCOAResult> >(_jsonIncomeTaxes ?? "[]", jsonSerializerSettings);

                var purchaseRequestIds = unitReceiptNote.Items.Select(s => s.PRId).ToList();
                var purchaseRequests   = dbContext.PurchaseRequests.Where(w => purchaseRequestIds.Contains(w.Id)).Select(s => new { s.Id, s.CategoryCode, s.CategoryId }).ToList();

                var externalPurchaseOrderIds = unitReceiptNote.Items.Select(s => s.EPOId).ToList();
                var externalPurchaseOrders   = dbContext.ExternalPurchaseOrders.Where(w => externalPurchaseOrderIds.Contains(w.Id)).Select(s => new { s.Id, s.IncomeTaxId, s.UseIncomeTax, s.IncomeTaxName, s.IncomeTaxRate, s.CurrencyCode, s.CurrencyRate }).ToList();



                var externalPurchaseOrderDetailIds = unitReceiptNote.Items.Select(s => s.EPODetailId).ToList();
                var externalPurchaseOrderDetails   = dbContext.ExternalPurchaseOrderDetails.Where(w => externalPurchaseOrderDetailIds.Contains(w.Id)).Select(s => new { s.Id, s.ProductId, TotalPrice = s.PricePerDealUnit * s.DealQuantity, s.DealQuantity }).ToList();

                //var postMany = new List<Task<HttpResponseMessage>>();

                //var journalTransactionsToPost = new List<JournalTransaction>();

                var journalTransactionToPost = new JournalTransaction()
                {
                    Date        = unitPaymentCorrection.CorrectionDate,
                    Description = $"Nota Koreksi {unitReceiptNote.URNNo}",
                    ReferenceNo = unitPaymentCorrection.UPCNo,
                    Status      = "POSTED",
                    Items       = new List <JournalTransactionItem>()
                };

                int.TryParse(unitReceiptNote.DivisionId, out var divisionId);
                var division = divisions.FirstOrDefault(f => f.Id.Equals(divisionId));
                if (division == null)
                {
                    division = new IdCOAResult()
                    {
                        COACode = "0"
                    };
                }
                else
                {
                    if (string.IsNullOrEmpty(division.COACode))
                    {
                        division.COACode = "0";
                    }
                }


                int.TryParse(unitReceiptNote.UnitId, out var unitId);
                var unit = units.FirstOrDefault(f => f.Id.Equals(unitId));
                if (unit == null)
                {
                    unit = new IdCOAResult()
                    {
                        COACode = "00"
                    };
                }
                else
                {
                    if (string.IsNullOrEmpty(unit.COACode))
                    {
                        unit.COACode = "00";
                    }
                }


                var journalDebitItems  = new List <JournalTransactionItem>();
                var journalCreditItems = new List <JournalTransactionItem>();

                foreach (var unitReceiptNoteItem in unitReceiptNote.Items)
                {
                    var purchaseRequest        = purchaseRequests.FirstOrDefault(f => f.Id.Equals(unitReceiptNoteItem.PRId));
                    var externalPurchaseOrder  = externalPurchaseOrders.FirstOrDefault(f => f.Id.Equals(unitReceiptNoteItem.EPOId));
                    var unitPaymentOrderDetail = dbContext.UnitPaymentOrderDetails.FirstOrDefault(entity => entity.URNItemId == unitReceiptNoteItem.Id);

                    //double.TryParse(externalPurchaseOrder.IncomeTaxRate, out var incomeTaxRate);

                    //var currency = await _currencyProvider.GetCurrencyByCurrencyCode(externalPurchaseOrder.CurrencyCode);
                    //var currencyTupples = new Tuple<>
                    var currencyTuples = new List <Tuple <string, DateTimeOffset> > {
                        new Tuple <string, DateTimeOffset>(externalPurchaseOrder.CurrencyCode, unitPaymentCorrection.CorrectionDate)
                    };
                    var currency = await _currencyProvider.GetCurrencyByCurrencyCodeDateList(currencyTuples);

                    var currencyRate = currency != null && currency.FirstOrDefault() != null ? (decimal)currency.FirstOrDefault().Rate.GetValueOrDefault() : (decimal)externalPurchaseOrder.CurrencyRate;

                    //if (!externalPurchaseOrder.UseIncomeTax)
                    //    incomeTaxRate = 1;
                    //var externalPurchaseOrderDetail = externalPurchaseOrderDetails.FirstOrDefault(f => f.Id.Equals(item.EPODetailId));
                    var externalPOPriceTotal = externalPurchaseOrderDetails.Where(w => w.ProductId.Equals(unitReceiptNoteItem.ProductId) && w.Id.Equals(unitReceiptNoteItem.EPODetailId)).Sum(s => s.TotalPrice);



                    int.TryParse(purchaseRequest.CategoryId, out var categoryId);
                    var category = categories.FirstOrDefault(f => f.Id.Equals(categoryId));
                    if (category == null)
                    {
                        category = new CategoryCOAResult()
                        {
                            ImportDebtCOA = "9999.00",
                            LocalDebtCOA  = "9999.00",
                            PurchasingCOA = "9999.00",
                            StockCOA      = "9999.00"
                        };
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(category.ImportDebtCOA))
                        {
                            category.ImportDebtCOA = "9999.00";
                        }
                        if (string.IsNullOrEmpty(category.LocalDebtCOA))
                        {
                            category.LocalDebtCOA = "9999.00";
                        }
                        if (string.IsNullOrEmpty(category.PurchasingCOA))
                        {
                            category.PurchasingCOA = "9999.00";
                        }
                        if (string.IsNullOrEmpty(category.StockCOA))
                        {
                            category.StockCOA = "9999.00";
                        }
                    }

                    double.TryParse(externalPurchaseOrder.IncomeTaxRate, out var incomeTaxRate);

                    var grandTotal = (decimal)0.0;
                    if (unitPaymentCorrection.CorrectionType == "Harga Total")
                    {
                        grandTotal = (decimal)((unitPaymentCorrectionItem.PriceTotalAfter - unitPaymentCorrectionItem.PriceTotalBefore) * unitPaymentCorrectionItem.Quantity);
                    }
                    else if (unitPaymentCorrection.CorrectionType == "Harga Satuan")
                    {
                        grandTotal = (decimal)(unitPaymentCorrectionItem.PricePerDealUnitAfter - unitPaymentCorrectionItem.PricePerDealUnitBefore);
                    }
                    else if (unitPaymentCorrection.CorrectionType == "Jumlah")
                    {
                        grandTotal = (decimal)(unitPaymentOrderDetail.QuantityCorrection * unitPaymentOrderDetail.PricePerDealUnit);
                    }

                    if (grandTotal != 0)
                    {
                        if (unitPaymentCorrection.useIncomeTax)
                        {
                            int.TryParse(externalPurchaseOrder.IncomeTaxId, out var incomeTaxId);
                            var incomeTax = incomeTaxes.FirstOrDefault(f => f.Id.Equals(incomeTaxId));

                            if (incomeTax == null || string.IsNullOrWhiteSpace(incomeTax.COACodeCredit))
                            {
                                incomeTax = new IncomeTaxCOAResult()
                                {
                                    COACodeCredit = "9999.00"
                                };
                            }

                            var incomeTaxTotal = (decimal)incomeTaxRate / 100 * grandTotal;

                            journalDebitItems.Add(new JournalTransactionItem()
                            {
                                COA = new COA()
                                {
                                    Code = unitReceiptNote.SupplierIsImport ? $"{category.ImportDebtCOA}.{division.COACode}.{unit.COACode}" : $"{category.LocalDebtCOA}.{division.COACode}.{unit.COACode}"
                                },
                                Debit = incomeTaxTotal
                            });

                            journalCreditItems.Add(new JournalTransactionItem()
                            {
                                COA = new COA()
                                {
                                    Code = $"{incomeTax.COACodeCredit}.{division.COACode}.{unit.COACode}"
                                },
                                Credit = incomeTaxTotal
                            });
                        }

                        if (unitPaymentCorrection.useVat)
                        {
                            var inVATCOA = "1509.00";
                            var totalVAT = (decimal)0.1 * grandTotal;
                            journalCreditItems.Add(new JournalTransactionItem()
                            {
                                COA = new COA()
                                {
                                    Code = unitReceiptNote.SupplierIsImport ? $"{category.ImportDebtCOA}.{division.COACode}.{unit.COACode}" : $"{category.LocalDebtCOA}.{division.COACode}.{unit.COACode}"
                                },
                                Credit = totalVAT
                            });

                            journalDebitItems.Add(new JournalTransactionItem()
                            {
                                COA = new COA()
                                {
                                    Code = $"{inVATCOA}.{division.COACode}.{unit.COACode}"
                                },
                                Debit  = totalVAT,
                                Remark = unitPaymentCorrection.VatTaxCorrectionNo
                            });
                        }

                        if (unitReceiptNote.SupplierIsImport && ((decimal)externalPOPriceTotal * currencyRate) > 100000000)
                        {
                            //Purchasing Journal Item
                            journalDebitItems.Add(new JournalTransactionItem()
                            {
                                COA = new COA()
                                {
                                    Code = $"{category.PurchasingCOA}.{division.COACode}.{unit.COACode}"
                                },
                                Debit  = grandTotal,
                                Remark = $"- {unitReceiptNoteItem.ProductName}"
                            });

                            //Debt Journal Item
                            journalCreditItems.Add(new JournalTransactionItem()
                            {
                                COA = new COA()
                                {
                                    Code = $"{category.ImportDebtCOA}.{division.COACode}.{unit.COACode}"
                                },
                                Credit = grandTotal,
                                Remark = $"- {unitReceiptNoteItem.ProductName}"
                            });

                            //Stock Journal Item
                            journalDebitItems.Add(new JournalTransactionItem()
                            {
                                COA = new COA()
                                {
                                    Code = $"{category.StockCOA}.{division.COACode}.{unit.COACode}"
                                },
                                Debit  = grandTotal,
                                Remark = $"- {unitReceiptNoteItem.ProductName}"
                            });

                            //Purchasing Journal Item
                            journalCreditItems.Add(new JournalTransactionItem()
                            {
                                COA = new COA()
                                {
                                    Code = $"{category.PurchasingCOA}.{division.COACode}.{unit.COACode}"
                                },
                                Credit = grandTotal,
                                Remark = $"- {unitReceiptNoteItem.ProductName}"
                            });
                        }
                        else
                        {
                            //Purchasing Journal Item
                            journalDebitItems.Add(new JournalTransactionItem()
                            {
                                COA = new COA()
                                {
                                    Code = $"{category.PurchasingCOA}.{division.COACode}.{unit.COACode}"
                                },
                                Debit  = grandTotal,
                                Remark = $"- {unitReceiptNoteItem.ProductName}"
                            });

                            if (SpecialCategoryCode.Contains(category.Code))
                            {
                                //Stock Journal Item
                                journalDebitItems.Add(new JournalTransactionItem()
                                {
                                    COA = new COA()
                                    {
                                        Code = $"{category.StockCOA}.{division.COACode}.{unit.COACode}"
                                    },
                                    Debit  = grandTotal,
                                    Remark = $"- {unitReceiptNoteItem.ProductName}"
                                });
                            }


                            //Debt Journal Item
                            journalCreditItems.Add(new JournalTransactionItem()
                            {
                                COA = new COA()
                                {
                                    Code = unitReceiptNote.SupplierIsImport ? $"{category.ImportDebtCOA}.{division.COACode}.{unit.COACode}" : $"{category.LocalDebtCOA}.{division.COACode}.{unit.COACode}"
                                },
                                Credit = grandTotal,
                                Remark = $"- {unitReceiptNoteItem.ProductName}"
                            });

                            if (SpecialCategoryCode.Contains(category.Code))
                            {
                                //Purchasing Journal Item
                                journalCreditItems.Add(new JournalTransactionItem()
                                {
                                    COA = new COA()
                                    {
                                        Code = $"{category.PurchasingCOA}.{division.COACode}.{unit.COACode}"
                                    },
                                    Credit = grandTotal,
                                    Remark = $"- {unitReceiptNoteItem.ProductName}"
                                });
                            }
                        }
                    }
                }


                journalDebitItems = journalDebitItems.GroupBy(grouping => grouping.COA.Code).Select(s => new JournalTransactionItem()
                {
                    COA = new COA()
                    {
                        Code = s.Key
                    },
                    Debit  = s.Sum(sum => Math.Round(sum.Debit.GetValueOrDefault(), 4)) > 0 ? s.Sum(sum => Math.Abs(Math.Round(sum.Debit.GetValueOrDefault(), 4))) : 0,
                    Credit = s.Sum(sum => Math.Round(sum.Debit.GetValueOrDefault(), 4)) > 0 ? 0 : s.Sum(sum => Math.Abs(Math.Round(sum.Debit.GetValueOrDefault(), 4))),
                    Remark = string.Join("\n", s.Select(grouped => grouped.Remark).ToList())
                }).ToList();
                journalTransactionToPost.Items.AddRange(journalDebitItems);

                journalCreditItems = journalCreditItems.GroupBy(grouping => grouping.COA.Code).Select(s => new JournalTransactionItem()
                {
                    COA = new COA()
                    {
                        Code = s.Key
                    },
                    Credit = s.Sum(sum => Math.Round(sum.Credit.GetValueOrDefault(), 4)) > 0 ? s.Sum(sum => Math.Abs(Math.Round(sum.Credit.GetValueOrDefault(), 4))) : 0,
                    Debit  = s.Sum(sum => Math.Round(sum.Credit.GetValueOrDefault(), 4)) > 0 ? 0 : s.Sum(sum => Math.Abs(Math.Round(sum.Credit.GetValueOrDefault(), 4))),
                    Remark = string.Join("\n", s.Select(grouped => grouped.Remark).ToList())
                }).ToList();
                journalTransactionToPost.Items.AddRange(journalCreditItems);

                if (journalTransactionToPost.Items.Any(item => item.COA.Code.Split(".").FirstOrDefault().Equals("9999")))
                {
                    journalTransactionToPost.Status = "DRAFT";
                }

                if (journalTransactionToPost.Items.Count > 0)
                {
                    var journalTransactionUri = "journal-transactions";
                    var httpClient            = (IHttpClientService)serviceProvider.GetService(typeof(IHttpClientService));
                    var response = await httpClient.PostAsync($"{APIEndpoint.Finance}{journalTransactionUri}", new StringContent(JsonConvert.SerializeObject(journalTransactionToPost).ToString(), Encoding.UTF8, General.JsonMediaType));

                    response.EnsureSuccessStatusCode();
                }
            }
        }
        public async Task <LocalPurchasingBookReportViewModel> GetReportData(string no, string unit, string categoryCode, DateTime?dateFrom, DateTime?dateTo, bool isValas)
        {
            var d1 = dateFrom.GetValueOrDefault().ToUniversalTime();
            var d2 = (dateTo.HasValue ? dateTo.Value : DateTime.Now).ToUniversalTime();

            var query = from urnWithItem in dbContext.UnitReceiptNoteItems

                        join pr in dbContext.PurchaseRequests on urnWithItem.PRId equals pr.Id into joinPurchaseRequest
                        from urnPR in joinPurchaseRequest.DefaultIfEmpty()

                        join epoDetail in dbContext.ExternalPurchaseOrderDetails on urnWithItem.EPODetailId equals epoDetail.Id into joinExternalPurchaseOrder
                        from urnEPODetail in joinExternalPurchaseOrder.DefaultIfEmpty()

                        join upoItem in dbContext.UnitPaymentOrderItems on urnWithItem.URNId equals upoItem.URNId into joinUnitPaymentOrder
                        from urnUPOItem in joinUnitPaymentOrder.DefaultIfEmpty()

                        where urnWithItem.UnitReceiptNote.ReceiptDate >= d1 && urnWithItem.UnitReceiptNote.ReceiptDate <= d2 && !urnWithItem.UnitReceiptNote.SupplierIsImport
                        select new
            {
                // PR Info
                urnPR.CategoryCode,
                urnPR.CategoryName,

                urnWithItem.PRId,
                urnWithItem.UnitReceiptNote.DOId,
                urnWithItem.UnitReceiptNote.DONo,
                urnWithItem.UnitReceiptNote.URNNo,
                URNId = urnWithItem.UnitReceiptNote.Id,
                urnWithItem.ProductName,
                urnWithItem.UnitReceiptNote.ReceiptDate,
                urnWithItem.UnitReceiptNote.SupplierName,
                urnWithItem.UnitReceiptNote.SupplierIsImport,
                urnWithItem.UnitReceiptNote.UnitCode,
                urnWithItem.UnitReceiptNote.UnitName,
                urnWithItem.EPODetailId,
                urnWithItem.PricePerDealUnit,
                urnWithItem.ReceiptQuantity,
                urnWithItem.Uom,

                // EPO Info
                urnEPODetail.ExternalPurchaseOrderItem.PONo,
                urnEPODetail.ExternalPurchaseOrderItem.ExternalPurchaseOrder.UseVat,
                EPOPricePerDealUnit = urnEPODetail.PricePerDealUnit,
                urnEPODetail.ExternalPurchaseOrderItem.ExternalPurchaseOrder.CurrencyCode,

                // UPO Info
                urnUPOItem.UnitPaymentOrder.InvoiceNo,
                urnUPOItem.UnitPaymentOrder.UPONo,
                urnUPOItem.UnitPaymentOrder.VatNo
            };


            //var query = dbSet
            //    .Where(urn => urn.ReceiptDate >= d1.ToUniversalTime() && urn.ReceiptDate.ToUniversalTime() <= d2 && !urn.SupplierIsImport);

            if (isValas)
            {
                query = query.Where(urn => urn.CurrencyCode != IDRCurrencyCode);
            }
            else
            {
                query = query.Where(urn => urn.CurrencyCode == IDRCurrencyCode);
            }

            if (!string.IsNullOrWhiteSpace(no))
            {
                query = query.Where(urn => urn.URNNo == no);
            }

            if (!string.IsNullOrWhiteSpace(unit))
            {
                query = query.Where(urn => urn.UnitCode == unit);
            }

            //var prIds = query.SelectMany(urn => urn.Items.Select(s => s.PRId)).ToList();

            if (!string.IsNullOrWhiteSpace(categoryCode))
            {
                query = query.Where(urn => urn.CategoryCode == categoryCode);
            }

            var queryResult = query.OrderByDescending(item => item.ReceiptDate).ToList();
            //var currencyCodes = queryResult.Select(item => item.CurrencyCode).ToList();
            var currencyTuples = queryResult.Select(item => new Tuple <string, DateTimeOffset>(item.CurrencyCode, item.ReceiptDate));
            var currencies     = await _currencyProvider.GetCurrencyByCurrencyCodeDateList(currencyTuples);

            var reportResult = new LocalPurchasingBookReportViewModel();

            foreach (var item in queryResult)
            {
                //var purchaseRequest = purchaseRequests.FirstOrDefault(f => f.Id.Equals(urnItem.PRId));
                //var unitPaymentOrder = unitPaymentOrders.FirstOrDefault(f => f.URNId.Equals(urnItem.URNId));
                //var epoItem = epoItems.FirstOrDefault(f => f.epoDetailIds.Contains(urnItem.EPODetailId));
                //var epoDetail = epoItem.Details.FirstOrDefault(f => f.Id.Equals(urnItem.EPODetailId));
                var currency = currencies.FirstOrDefault(f => f.Code.Equals(item.CurrencyCode));

                decimal dpp         = 0;
                decimal dppCurrency = 0;
                decimal ppn         = 0;

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

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



                var reportItem = new PurchasingReport()
                {
                    CategoryName = item.CategoryName,
                    CategoryCode = item.CategoryCode,
                    CurrencyRate = (decimal)currencyRate,
                    DONo         = item.DONo,
                    DPP          = dpp,
                    DPPCurrency  = dppCurrency,
                    InvoiceNo    = item.InvoiceNo,
                    VATNo        = item.VatNo,
                    IPONo        = item.PONo,
                    VAT          = ppn,
                    Total        = (dpp + dppCurrency + ppn) * (decimal)currencyRate,
                    ProductName  = item.ProductName,
                    ReceiptDate  = item.ReceiptDate,
                    SupplierName = item.SupplierName,
                    UnitName     = item.UnitName,
                    UPONo        = item.UPONo,
                    URNNo        = item.URNNo,
                    IsUseVat     = item.UseVat,
                    CurrencyCode = currencyCode,
                    Quantity     = item.ReceiptQuantity,
                    Uom          = item.Uom
                };

                reportResult.Reports.Add(reportItem);
            }

            reportResult.CategorySummaries = reportResult.Reports
                                             .GroupBy(report => new { report.CategoryCode })
                                             .Select(report => new Summary()
            {
                Category = report.Key.CategoryCode,
                SubTotal = report.Sum(sum => sum.Total)
            }).OrderBy(order => order.Category).ToList();
            reportResult.CurrencySummaries = reportResult.Reports
                                             .GroupBy(report => new { report.CurrencyCode })
                                             .Select(report => new Summary()
            {
                CurrencyCode = report.Key.CurrencyCode,
                SubTotal     = report.Sum(sum => sum.DPP + sum.DPPCurrency + sum.VAT)
            }).OrderBy(order => order.CurrencyCode).ToList();
            reportResult.Reports              = reportResult.Reports;
            reportResult.GrandTotal           = reportResult.Reports.Sum(sum => sum.Total);
            reportResult.CategorySummaryTotal = reportResult.CategorySummaries.Sum(categorySummary => categorySummary.SubTotal);

            #region Old Query
            //if (prIds.Count > 0)
            //{
            //    var purchaseRequestQuery = dbContext.PurchaseRequests.AsQueryable();


            //    if (purchaseRequestQuery.Count() > 0)
            //    {
            //        //var purchaseRequests = purchaseRequestQuery.Select(pr => new { pr.Id, pr.CategoryName, pr.CategoryCode }).ToList();
            //        //prIds = purchaseRequests.Select(pr => pr.Id).ToList();
            //        //var categories = purchaseRequests.Select(pr => pr.CategoryCode).Distinct().ToList();

            //        //var urnIds = query.Select(urn => urn.Id).ToList();
            //        //var urnItems = dbContext.UnitReceiptNoteItems
            //        //    .Include(urnItem => urnItem.UnitReceiptNote)
            //        //    .Where(urnItem => urnIds.Contains(urnItem.URNId) && prIds.Contains(urnItem.PRId))
            //        //    .Select(urnItem => new
            //        //    {
            //        //        urnItem.PRId,
            //        //        urnItem.UnitReceiptNote.DOId,
            //        //        urnItem.UnitReceiptNote.DONo,
            //        //        urnItem.UnitReceiptNote.URNNo,
            //        //        URNId = urnItem.UnitReceiptNote.Id,
            //        //        urnItem.ProductName,
            //        //        urnItem.UnitReceiptNote.ReceiptDate,
            //        //        urnItem.UnitReceiptNote.SupplierName,
            //        //        urnItem.UnitReceiptNote.UnitCode,
            //        //        urnItem.EPODetailId,
            //        //        urnItem.PricePerDealUnit,
            //        //        urnItem.ReceiptQuantity,
            //        //        urnItem.Uom
            //        //    })
            //        //    .ToList();

            //        //var epoDetailIds = urnItems.Select(urnItem => urnItem.EPODetailId).ToList();
            //        //var epoItemIds = dbContext.ExternalPurchaseOrderDetails
            //        //    .Include(epoDetail => epoDetail.ExternalPurchaseOrderItem)
            //        //    .Where(epoDetail => epoDetailIds.Contains(epoDetail.Id))
            //        //    .Select(epoDetail => epoDetail.ExternalPurchaseOrderItem.Id)
            //        //    .ToList();
            //        var epoItems = dbContext.ExternalPurchaseOrderItems
            //            .Include(epoItem => epoItem.ExternalPurchaseOrder)
            //            .Where(epoItem => epoItemIds.Contains(epoItem.Id))
            //            .Select(epoItem => new
            //            {
            //                epoItem.PONo,
            //                epoDetailIds = epoItem.Details.Select(epoDetail => epoDetail.Id).ToList(),
            //                epoItem.ExternalPurchaseOrder.CurrencyCode,
            //                epoItem.ExternalPurchaseOrder.UseVat,
            //                Details = epoItem.Details.Select(epoDetail => new { epoDetail.PricePerDealUnit, epoDetail.Id }).ToList()
            //            })
            //            .ToList();

            //        var unitPaymentOrders = dbContext.UnitPaymentOrderItems
            //            .Include(upoItem => upoItem.UnitPaymentOrder)
            //            .Where(upoItem => urnIds.Contains(upoItem.URNId))
            //            .Select(upoItem => new
            //            {
            //                upoItem.URNId,
            //                upoItem.UnitPaymentOrder.InvoiceNo,
            //                upoItem.UnitPaymentOrder.UPONo,
            //                upoItem.UnitPaymentOrder.VatNo
            //            });

            //        var currencyCodes = epoItems.Select(epoItem => epoItem.CurrencyCode).Distinct().ToList();
            //        var currencies = await _currencyProvider.GetCurrencyByCurrencyCodeList(currencyCodes);

            //        var reportResult = new LocalPurchasingBookReportViewModel();
            //        foreach (var urnItem in urnItems)
            //        {
            //            var purchaseRequest = purchaseRequests.FirstOrDefault(f => f.Id.Equals(urnItem.PRId));
            //            var unitPaymentOrder = unitPaymentOrders.FirstOrDefault(f => f.URNId.Equals(urnItem.URNId));
            //            var epoItem = epoItems.FirstOrDefault(f => f.epoDetailIds.Contains(urnItem.EPODetailId));
            //            var epoDetail = epoItem.Details.FirstOrDefault(f => f.Id.Equals(urnItem.EPODetailId));
            //            var currency = currencies.FirstOrDefault(f => f.Code.Equals(epoItem.CurrencyCode));

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

            //            //default IDR
            //            double currencyRate = 1;
            //            var currencyCode = "IDR";
            //            if (currency != null && !currency.Code.Equals("IDR"))
            //            {
            //                dppCurrency = (decimal)(epoDetail.PricePerDealUnit * urnItem.ReceiptQuantity);
            //                currencyRate = currency.Rate.GetValueOrDefault();
            //                currencyCode = currency.Code;
            //            }
            //            else
            //                dpp = (decimal)(epoDetail.PricePerDealUnit * urnItem.ReceiptQuantity);

            //            if (epoItem.UseVat)
            //                ppn = (decimal)(epoDetail.PricePerDealUnit * urnItem.ReceiptQuantity * 0.1);



            //            var reportItem = new PurchasingReport()
            //            {
            //                CategoryName = purchaseRequest.CategoryName,
            //                CategoryCode = purchaseRequest.CategoryCode,
            //                CurrencyRate = (decimal)currencyRate,
            //                DONo = urnItem.DONo,
            //                DPP = dpp,
            //                DPPCurrency = dppCurrency,
            //                InvoiceNo = unitPaymentOrder?.InvoiceNo,
            //                VATNo = unitPaymentOrder?.VatNo,
            //                IPONo = epoItem.PONo,
            //                VAT = ppn,
            //                Total = (dpp + dppCurrency + ppn) * (decimal)currencyRate,
            //                ProductName = urnItem.ProductName,
            //                ReceiptDate = urnItem.ReceiptDate,
            //                SupplierName = urnItem.SupplierName,
            //                UnitName = urnItem.UnitCode,
            //                UPONo = unitPaymentOrder?.UPONo,
            //                URNNo = urnItem.URNNo,
            //                IsUseVat = epoItem.UseVat,
            //                CurrencyCode = currencyCode,
            //                Quantity = urnItem.ReceiptQuantity,
            //                Uom = urnItem.Uom
            //            };

            //            reportResult.Reports.Add(reportItem);
            //        }

            //        reportResult.CategorySummaries = reportResult.Reports
            //            .GroupBy(report => new { report.CategoryCode })
            //            .Select(report => new Summary()
            //            {
            //                Category = report.Key.CategoryCode,
            //                SubTotal = report.Sum(sum => sum.Total)
            //            }).OrderBy(order => order.Category).ToList();
            //        reportResult.CurrencySummaries = reportResult.Reports
            //            .GroupBy(report => new { report.CurrencyCode })
            //            .Select(report => new Summary()
            //            {
            //                CurrencyCode = report.Key.CurrencyCode,
            //                SubTotal = report.Sum(sum => sum.DPP + sum.DPPCurrency + sum.VAT)
            //            }).OrderBy(order => order.CurrencyCode).ToList();
            //        reportResult.Reports = reportResult.Reports.OrderByDescending(order => order.ReceiptDate).ToList();
            //        reportResult.GrandTotal = reportResult.Reports.Sum(sum => sum.Total);
            //        reportResult.CategorySummaryTotal = reportResult.CategorySummaries.Sum(categorySummary => categorySummary.SubTotal);

            //        return reportResult;
            //    }
            //}
            #endregion

            return(reportResult);
        }
        //public async Task<LocalPurchasingBookReportViewModel> GetReportData(string no, string unit, string categoryCode, DateTime? dateFrom, DateTime? dateTo)
        //{
        //    var d1 = dateFrom.GetValueOrDefault().ToUniversalTime();
        //    var d2 = (dateTo.HasValue ? dateTo.Value : DateTime.Now).ToUniversalTime();

        //    var query = from urnWithItem in dbContext.UnitReceiptNoteItems

        //                join pr in dbContext.PurchaseRequests on urnWithItem.PRId equals pr.Id into joinPurchaseRequest
        //                from urnPR in joinPurchaseRequest.DefaultIfEmpty()

        //                join epoDetail in dbContext.ExternalPurchaseOrderDetails on urnWithItem.EPODetailId equals epoDetail.Id into joinExternalPurchaseOrder
        //                from urnEPODetail in joinExternalPurchaseOrder.DefaultIfEmpty()

        //                join upoItem in dbContext.UnitPaymentOrderItems on urnWithItem.URNId equals upoItem.URNId into joinUnitPaymentOrder
        //                from urnUPOItem in joinUnitPaymentOrder.DefaultIfEmpty()

        //                where urnWithItem.UnitReceiptNote.ReceiptDate >= d1 && urnWithItem.UnitReceiptNote.ReceiptDate <= d2 && urnWithItem.UnitReceiptNote.SupplierIsImport
        //                select new
        //                {
        //                    // PR Info
        //                    urnPR.CategoryCode,
        //                    urnPR.CategoryName,

        //                    urnWithItem.PRId,
        //                    urnWithItem.UnitReceiptNote.DOId,
        //                    urnWithItem.UnitReceiptNote.DONo,
        //                    urnWithItem.UnitReceiptNote.URNNo,
        //                    URNId = urnWithItem.UnitReceiptNote.Id,
        //                    urnWithItem.ProductName,
        //                    urnWithItem.UnitReceiptNote.ReceiptDate,
        //                    urnWithItem.UnitReceiptNote.SupplierName,
        //                    urnWithItem.UnitReceiptNote.SupplierCode,
        //                    urnWithItem.UnitReceiptNote.UnitCode,
        //                    urnWithItem.UnitReceiptNote.UnitName,
        //                    urnWithItem.EPODetailId,
        //                    urnWithItem.PricePerDealUnit,
        //                    urnWithItem.ReceiptQuantity,
        //                    urnWithItem.Uom,

        //                    // EPO Info
        //                    urnEPODetail.ExternalPurchaseOrderItem.PONo,
        //                    urnEPODetail.ExternalPurchaseOrderItem.ExternalPurchaseOrder.UseVat,
        //                    EPOPricePerDealUnit = urnEPODetail.PricePerDealUnit,
        //                    urnEPODetail.ExternalPurchaseOrderItem.ExternalPurchaseOrder.CurrencyCode,

        //                    // UPO Info
        //                    urnUPOItem.UnitPaymentOrder.InvoiceNo,
        //                    urnUPOItem.UnitPaymentOrder.UPONo,
        //                    urnUPOItem.UnitPaymentOrder.VatNo,
        //                    urnUPOItem.UnitPaymentOrder.PibNo
        //                };


        //    //var query = dbSet
        //    //    .Where(urn => urn.ReceiptDate >= d1.ToUniversalTime() && urn.ReceiptDate.ToUniversalTime() <= d2 && !urn.SupplierIsImport);

        //    if (!string.IsNullOrWhiteSpace(no))
        //        query = query.Where(urn => urn.URNNo == no);

        //    if (!string.IsNullOrWhiteSpace(unit))
        //        query = query.Where(urn => urn.UnitCode == unit);

        //    //var prIds = query.SelectMany(urn => urn.Items.Select(s => s.PRId)).ToList();

        //    if (!string.IsNullOrWhiteSpace(categoryCode))
        //        query = query.Where(urn => urn.CategoryCode == categoryCode);

        //    var queryResult = query.OrderByDescending(item => item.ReceiptDate).ToList();
        //    //var currencyCodes = queryResult.Select(item => item.CurrencyCode).ToList();
        //    //var receiptDates = queryResult.Select(item => item.ReceiptDate).ToList();
        //    var currencyTuples = queryResult.Select(item => new Tuple<string, DateTimeOffset>(item.CurrencyCode, item.ReceiptDate));
        //    var currencies = await _currencyProvider.GetCurrencyByCurrencyCodeDateList(currencyTuples);

        //    var reportResult = new LocalPurchasingBookReportViewModel();
        //    foreach (var item in queryResult)
        //    {
        //        //var purchaseRequest = purchaseRequests.FirstOrDefault(f => f.Id.Equals(urnItem.PRId));
        //        //var unitPaymentOrder = unitPaymentOrders.FirstOrDefault(f => f.URNId.Equals(urnItem.URNId));
        //        //var epoItem = epoItems.FirstOrDefault(f => f.epoDetailIds.Contains(urnItem.EPODetailId));
        //        //var epoDetail = epoItem.Details.FirstOrDefault(f => f.Id.Equals(urnItem.EPODetailId));
        //        var currency = currencies.FirstOrDefault(f => f.Code == item.CurrencyCode);

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

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

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



        //        var reportItem = new PurchasingReport()
        //        {
        //            CategoryName = item.CategoryName,
        //            CategoryCode = item.CategoryCode,
        //            CurrencyRate = (decimal)currencyRate,
        //            DONo = item.DONo,
        //            DPP = dpp,
        //            DPPCurrency = dppCurrency,
        //            InvoiceNo = item.InvoiceNo,
        //            VATNo = item.VatNo,
        //            IPONo = item.PONo,
        //            VAT = ppn,
        //            Total = (dpp + dppCurrency + ppn) * (decimal)currencyRate,
        //            ProductName = item.ProductName,
        //            ReceiptDate = item.ReceiptDate,
        //            SupplierName = item.SupplierCode + " - " + item.SupplierName,
        //            UnitName = item.UnitName,
        //            UPONo = item.UPONo,
        //            URNNo = item.URNNo,
        //            IsUseVat = item.UseVat,
        //            CurrencyCode = currencyCode,
        //            PIBNo = item.PibNo
        //        };
        //        reportItem.PIBBM = reportItem.Total * 0.1m;

        //        reportResult.Reports.Add(reportItem);
        //    }

        //    reportResult.CategorySummaries = reportResult.Reports
        //                .GroupBy(report => new { report.CategoryCode })
        //                .Select(report => new Summary()
        //                {
        //                    Category = report.Key.CategoryCode,
        //                    SubTotal = report.Sum(sum => sum.Total)
        //                }).OrderBy(order => order.Category).ToList();
        //    reportResult.CurrencySummaries = reportResult.Reports
        //        .GroupBy(report => new { report.CurrencyCode })
        //        .Select(report => new Summary()
        //        {
        //            CurrencyCode = report.Key.CurrencyCode,
        //            SubTotal = report.Sum(sum => sum.DPP + sum.DPPCurrency + sum.VAT)
        //        }).OrderBy(order => order.CurrencyCode).ToList();
        //    reportResult.Reports = reportResult.Reports;
        //    reportResult.GrandTotal = reportResult.Reports.Sum(sum => sum.Total);
        //    reportResult.CategorySummaryTotal = reportResult.CategorySummaries.Sum(categorySummary => categorySummary.SubTotal);

        //    #region Old Query
        //    //if (prIds.Count > 0)
        //    //{
        //    //    var purchaseRequestQuery = dbContext.PurchaseRequests.AsQueryable();


        //    //    if (purchaseRequestQuery.Count() > 0)
        //    //    {
        //    //        //var purchaseRequests = purchaseRequestQuery.Select(pr => new { pr.Id, pr.CategoryName, pr.CategoryCode }).ToList();
        //    //        //prIds = purchaseRequests.Select(pr => pr.Id).ToList();
        //    //        //var categories = purchaseRequests.Select(pr => pr.CategoryCode).Distinct().ToList();

        //    //        //var urnIds = query.Select(urn => urn.Id).ToList();
        //    //        //var urnItems = dbContext.UnitReceiptNoteItems
        //    //        //    .Include(urnItem => urnItem.UnitReceiptNote)
        //    //        //    .Where(urnItem => urnIds.Contains(urnItem.URNId) && prIds.Contains(urnItem.PRId))
        //    //        //    .Select(urnItem => new
        //    //        //    {
        //    //        //        urnItem.PRId,
        //    //        //        urnItem.UnitReceiptNote.DOId,
        //    //        //        urnItem.UnitReceiptNote.DONo,
        //    //        //        urnItem.UnitReceiptNote.URNNo,
        //    //        //        URNId = urnItem.UnitReceiptNote.Id,
        //    //        //        urnItem.ProductName,
        //    //        //        urnItem.UnitReceiptNote.ReceiptDate,
        //    //        //        urnItem.UnitReceiptNote.SupplierName,
        //    //        //        urnItem.UnitReceiptNote.UnitCode,
        //    //        //        urnItem.EPODetailId,
        //    //        //        urnItem.PricePerDealUnit,
        //    //        //        urnItem.ReceiptQuantity,
        //    //        //        urnItem.Uom
        //    //        //    })
        //    //        //    .ToList();

        //    //        //var epoDetailIds = urnItems.Select(urnItem => urnItem.EPODetailId).ToList();
        //    //        //var epoItemIds = dbContext.ExternalPurchaseOrderDetails
        //    //        //    .Include(epoDetail => epoDetail.ExternalPurchaseOrderItem)
        //    //        //    .Where(epoDetail => epoDetailIds.Contains(epoDetail.Id))
        //    //        //    .Select(epoDetail => epoDetail.ExternalPurchaseOrderItem.Id)
        //    //        //    .ToList();
        //    //        var epoItems = dbContext.ExternalPurchaseOrderItems
        //    //            .Include(epoItem => epoItem.ExternalPurchaseOrder)
        //    //            .Where(epoItem => epoItemIds.Contains(epoItem.Id))
        //    //            .Select(epoItem => new
        //    //            {
        //    //                epoItem.PONo,
        //    //                epoDetailIds = epoItem.Details.Select(epoDetail => epoDetail.Id).ToList(),
        //    //                epoItem.ExternalPurchaseOrder.CurrencyCode,
        //    //                epoItem.ExternalPurchaseOrder.UseVat,
        //    //                Details = epoItem.Details.Select(epoDetail => new { epoDetail.PricePerDealUnit, epoDetail.Id }).ToList()
        //    //            })
        //    //            .ToList();

        //    //        var unitPaymentOrders = dbContext.UnitPaymentOrderItems
        //    //            .Include(upoItem => upoItem.UnitPaymentOrder)
        //    //            .Where(upoItem => urnIds.Contains(upoItem.URNId))
        //    //            .Select(upoItem => new
        //    //            {
        //    //                upoItem.URNId,
        //    //                upoItem.UnitPaymentOrder.InvoiceNo,
        //    //                upoItem.UnitPaymentOrder.UPONo,
        //    //                upoItem.UnitPaymentOrder.VatNo
        //    //            });

        //    //        var currencyCodes = epoItems.Select(epoItem => epoItem.CurrencyCode).Distinct().ToList();
        //    //        var currencies = await _currencyProvider.GetCurrencyByCurrencyCodeList(currencyCodes);

        //    //        var reportResult = new LocalPurchasingBookReportViewModel();
        //    //        foreach (var urnItem in urnItems)
        //    //        {
        //    //            var purchaseRequest = purchaseRequests.FirstOrDefault(f => f.Id.Equals(urnItem.PRId));
        //    //            var unitPaymentOrder = unitPaymentOrders.FirstOrDefault(f => f.URNId.Equals(urnItem.URNId));
        //    //            var epoItem = epoItems.FirstOrDefault(f => f.epoDetailIds.Contains(urnItem.EPODetailId));
        //    //            var epoDetail = epoItem.Details.FirstOrDefault(f => f.Id.Equals(urnItem.EPODetailId));
        //    //            var currency = currencies.FirstOrDefault(f => f.Code.Equals(epoItem.CurrencyCode));

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

        //    //            //default IDR
        //    //            double currencyRate = 1;
        //    //            var currencyCode = "IDR";
        //    //            if (currency != null && !currency.Code.Equals("IDR"))
        //    //            {
        //    //                dppCurrency = (decimal)(epoDetail.PricePerDealUnit * urnItem.ReceiptQuantity);
        //    //                currencyRate = currency.Rate.GetValueOrDefault();
        //    //                currencyCode = currency.Code;
        //    //            }
        //    //            else
        //    //                dpp = (decimal)(epoDetail.PricePerDealUnit * urnItem.ReceiptQuantity);

        //    //            if (epoItem.UseVat)
        //    //                ppn = (decimal)(epoDetail.PricePerDealUnit * urnItem.ReceiptQuantity * 0.1);



        //    //            var reportItem = new PurchasingReport()
        //    //            {
        //    //                CategoryName = purchaseRequest.CategoryName,
        //    //                CategoryCode = purchaseRequest.CategoryCode,
        //    //                CurrencyRate = (decimal)currencyRate,
        //    //                DONo = urnItem.DONo,
        //    //                DPP = dpp,
        //    //                DPPCurrency = dppCurrency,
        //    //                InvoiceNo = unitPaymentOrder?.InvoiceNo,
        //    //                VATNo = unitPaymentOrder?.VatNo,
        //    //                IPONo = epoItem.PONo,
        //    //                VAT = ppn,
        //    //                Total = (dpp + dppCurrency + ppn) * (decimal)currencyRate,
        //    //                ProductName = urnItem.ProductName,
        //    //                ReceiptDate = urnItem.ReceiptDate,
        //    //                SupplierName = urnItem.SupplierName,
        //    //                UnitName = urnItem.UnitCode,
        //    //                UPONo = unitPaymentOrder?.UPONo,
        //    //                URNNo = urnItem.URNNo,
        //    //                IsUseVat = epoItem.UseVat,
        //    //                CurrencyCode = currencyCode,
        //    //                Quantity = urnItem.ReceiptQuantity,
        //    //                Uom = urnItem.Uom
        //    //            };

        //    //            reportResult.Reports.Add(reportItem);
        //    //        }

        //    //        reportResult.CategorySummaries = reportResult.Reports
        //    //            .GroupBy(report => new { report.CategoryCode })
        //    //            .Select(report => new Summary()
        //    //            {
        //    //                Category = report.Key.CategoryCode,
        //    //                SubTotal = report.Sum(sum => sum.Total)
        //    //            }).OrderBy(order => order.Category).ToList();
        //    //        reportResult.CurrencySummaries = reportResult.Reports
        //    //            .GroupBy(report => new { report.CurrencyCode })
        //    //            .Select(report => new Summary()
        //    //            {
        //    //                CurrencyCode = report.Key.CurrencyCode,
        //    //                SubTotal = report.Sum(sum => sum.DPP + sum.DPPCurrency + sum.VAT)
        //    //            }).OrderBy(order => order.CurrencyCode).ToList();
        //    //        reportResult.Reports = reportResult.Reports.OrderByDescending(order => order.ReceiptDate).ToList();
        //    //        reportResult.GrandTotal = reportResult.Reports.Sum(sum => sum.Total);
        //    //        reportResult.CategorySummaryTotal = reportResult.CategorySummaries.Sum(categorySummary => categorySummary.SubTotal);

        //    //        return reportResult;
        //    //    }
        //    //}
        //    #endregion

        //    return reportResult;
        //}

        public async Task <LocalPurchasingBookReportViewModel> GetReportData(string no, string unit, string categoryCode, DateTime?dateFrom, DateTime?dateTo)
        {
            var d1 = dateFrom.GetValueOrDefault().ToUniversalTime();
            var d2 = (dateTo.HasValue ? dateTo.Value : DateTime.Now).ToUniversalTime();

            var query = from urnWithItem in dbContext.UnitReceiptNoteItems

                        join pr in dbContext.PurchaseRequests on urnWithItem.PRId equals pr.Id into joinPurchaseRequest
                        from urnPR in joinPurchaseRequest.DefaultIfEmpty()

                        join epoDetail in dbContext.ExternalPurchaseOrderDetails on urnWithItem.EPODetailId equals epoDetail.Id into joinExternalPurchaseOrder
                        from urnEPODetail in joinExternalPurchaseOrder.DefaultIfEmpty()

                        join upoItem in dbContext.UnitPaymentOrderItems on urnWithItem.URNId equals upoItem.URNId into joinUnitPaymentOrder
                        from urnUPOItem in joinUnitPaymentOrder.DefaultIfEmpty()

                        where urnWithItem.UnitReceiptNote.ReceiptDate >= d1 && urnWithItem.UnitReceiptNote.ReceiptDate <= d2 && urnWithItem.UnitReceiptNote.SupplierIsImport
                        select new
            {
                // PR Info
                urnPR.CategoryCode,
                urnPR.CategoryName,

                urnWithItem.PRId,
                urnWithItem.UnitReceiptNote.DOId,
                urnWithItem.UnitReceiptNote.DONo,
                urnWithItem.UnitReceiptNote.URNNo,
                URNId = urnWithItem.UnitReceiptNote.Id,
                urnWithItem.ProductName,
                urnWithItem.UnitReceiptNote.ReceiptDate,
                urnWithItem.UnitReceiptNote.SupplierName,
                urnWithItem.UnitReceiptNote.SupplierCode,
                urnWithItem.UnitReceiptNote.UnitCode,
                urnWithItem.UnitReceiptNote.UnitName,
                urnWithItem.EPODetailId,
                urnWithItem.PricePerDealUnit,
                urnWithItem.ReceiptQuantity,
                urnWithItem.Uom,

                // EPO Info
                urnEPODetail.ExternalPurchaseOrderItem.PONo,
                urnEPODetail.ExternalPurchaseOrderItem.ExternalPurchaseOrder.UseVat,
                EPOPricePerDealUnit = urnEPODetail.PricePerDealUnit,
                urnEPODetail.ExternalPurchaseOrderItem.ExternalPurchaseOrder.CurrencyCode,

                // UPO Info
                urnUPOItem.UnitPaymentOrder.InvoiceNo,
                urnUPOItem.UnitPaymentOrder.UPONo,
                urnUPOItem.UnitPaymentOrder.VatNo,
                urnUPOItem.UnitPaymentOrder.PibNo,
                urnUPOItem.UnitPaymentOrder.PibDate,
                urnPR.Remark
            };


            //var query = dbSet
            //    .Where(urn => urn.ReceiptDate >= d1.ToUniversalTime() && urn.ReceiptDate.ToUniversalTime() <= d2 && !urn.SupplierIsImport);

            query = query.Where(urn => urn.CurrencyCode != "IDR");
            if (!string.IsNullOrWhiteSpace(no))
            {
                query = query.Where(urn => urn.URNNo == no);
            }

            if (!string.IsNullOrWhiteSpace(unit))
            {
                query = query.Where(urn => urn.UnitCode == unit);
            }

            //var prIds = query.SelectMany(urn => urn.Items.Select(s => s.PRId)).ToList();

            if (!string.IsNullOrWhiteSpace(categoryCode))
            {
                query = query.Where(urn => urn.CategoryCode == categoryCode);
            }

            var queryResult = query.OrderByDescending(item => item.ReceiptDate).ToList();
            //var currencyCodes = queryResult.Select(item => item.CurrencyCode).ToList();
            //var receiptDates = queryResult.Select(item => item.ReceiptDate).ToList();
            var currencyTuples = queryResult.GroupBy(item => new { item.CurrencyCode, item.ReceiptDate }).Select(item => new Tuple <string, DateTimeOffset>(item.Key.CurrencyCode, item.Key.ReceiptDate));
            var currencies     = await _currencyProvider.GetCurrencyByCurrencyCodeDateList(currencyTuples);

            var reportResult = new LocalPurchasingBookReportViewModel();

            foreach (var item in queryResult)
            {
                //var purchaseRequest = purchaseRequests.FirstOrDefault(f => f.Id.Equals(urnItem.PRId));
                //var unitPaymentOrder = unitPaymentOrders.FirstOrDefault(f => f.URNId.Equals(urnItem.URNId));
                //var epoItem = epoItems.FirstOrDefault(f => f.epoDetailIds.Contains(urnItem.EPODetailId));
                //var epoDetail = epoItem.Details.FirstOrDefault(f => f.Id.Equals(urnItem.EPODetailId));
                var currency = currencies.FirstOrDefault(f => f.Code == item.CurrencyCode);

                decimal dpp         = 0;
                decimal dppCurrency = 0;
                decimal ppn         = 0;

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

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



                var reportItem = new PurchasingReport()
                {
                    CategoryName = item.CategoryName,
                    CategoryCode = item.CategoryCode,
                    CurrencyRate = (decimal)currencyRate,
                    DONo         = item.DONo,
                    DPP          = dpp,
                    DPPCurrency  = dppCurrency,
                    InvoiceNo    = item.InvoiceNo,
                    VATNo        = item.VatNo,
                    IPONo        = item.PONo,
                    VAT          = ppn,
                    Total        = (dpp + dppCurrency + ppn) * (decimal)currencyRate,
                    ProductName  = item.ProductName,
                    ReceiptDate  = item.ReceiptDate,
                    SupplierName = item.SupplierCode + " - " + item.SupplierName,
                    UnitName     = item.UnitName,
                    UnitCode     = item.UnitCode,
                    UPONo        = item.UPONo,
                    URNNo        = item.URNNo,
                    IsUseVat     = item.UseVat,
                    CurrencyCode = currencyCode,
                    PIBNo        = item.PibNo,
                    PIBDate      = item.PibDate,
                    Remark       = item.Remark,
                    Quantity     = item.ReceiptQuantity
                };
                reportItem.PIBBM = reportItem.Total * 0.1m;

                reportResult.Reports.Add(reportItem);
            }

            reportResult.CategorySummaries = reportResult.Reports
                                             .GroupBy(report => new { report.CategoryCode })
                                             .Select(report => new Summary()
            {
                Category = report.Key.CategoryCode,
                SubTotal = report.Sum(sum => sum.Total)
            }).OrderBy(order => order.Category).ToList();
            reportResult.CurrencySummaries = reportResult.Reports
                                             .GroupBy(report => new { report.CurrencyCode })
                                             .Select(report => new Summary()
            {
                CurrencyCode = report.Key.CurrencyCode,
                SubTotal     = report.Sum(sum => sum.DPP + sum.DPPCurrency + sum.VAT)
            }).OrderBy(order => order.CurrencyCode).ToList();
            reportResult.Reports              = reportResult.Reports;
            reportResult.GrandTotal           = reportResult.Reports.Sum(sum => sum.Total);
            reportResult.CategorySummaryTotal = reportResult.CategorySummaries.Sum(categorySummary => categorySummary.SubTotal);

            return(reportResult);
        }