async Task <string> GenerateNo(UnitPaymentCorrectionNote model, bool supplierImport, int clientTimeZoneOffset)
        {
            string Year         = model.CorrectionDate.ToOffset(new TimeSpan(clientTimeZoneOffset, 0, 0)).ToString("yy");
            string Month        = model.CorrectionDate.ToOffset(new TimeSpan(clientTimeZoneOffset, 0, 0)).ToString("MM");
            string supplier_imp = "NRL";

            if (supplierImport == true)
            {
                supplier_imp = "NRI";
            }
            string divisionName  = model.DivisionName;
            string division_name = "T";

            if (divisionName.ToUpper() == "GARMENT")
            {
                division_name = "G";
            }

            string no      = $"{Year}-{Month}-{division_name}-{supplier_imp}-";
            int    Padding = 3;

            var lastNo = await this.dbSet.Where(w => w.UPCNo.StartsWith(no) && !w.IsDeleted).OrderByDescending(o => o.UPCNo).FirstOrDefaultAsync();

            if (lastNo == null)
            {
                return(no + "1".PadLeft(Padding, '0'));
            }
            else
            {
                int lastNoNumber = Int32.Parse(lastNo.UPCNo.Replace(no, "")) + 1;
                return(no + lastNoNumber.ToString().PadLeft(Padding, '0'));
            }
        }
        private async Task <int> AddCorrections(UnitPaymentCorrectionNote model, string username)
        {
            var internalPOFacade = serviceProvider.GetService <InternalPurchaseOrderFacade>();
            int count            = 0;

            foreach (var item in model.Items)
            {
                var fulfillment = await dbContext.InternalPurchaseOrderFulfillments.AsNoTracking()
                                  .FirstOrDefaultAsync(x => x.UnitPaymentOrderId == model.UPOId && x.UnitPaymentOrderDetailId == item.UPODetailId);

                if (fulfillment != null)
                {
                    fulfillment.Corrections.Add(new InternalPurchaseOrderCorrection()
                    {
                        CorrectionDate              = model.CorrectionDate,
                        CorrectionNo                = model.UPCNo,
                        CorrectionPriceTotal        = item.PriceTotalAfter,
                        CorrectionQuantity          = item.Quantity,
                        CorrectionRemark            = model.Remark,
                        UnitPaymentCorrectionId     = model.Id,
                        UnitPaymentCorrectionItemId = item.Id
                    });

                    count += await internalPOFacade.UpdateFulfillmentAsync(fulfillment.Id, fulfillment, username);
                }
            }

            return(count);
        }
Beispiel #3
0
        public IActionResult GetPDF(int id)
        {
            try
            {
                var indexAcceptPdf = Request.Headers["Accept"].ToList().IndexOf("application/pdf");
                identityService.Username = User.Claims.Single(p => p.Type.Equals("username")).Value;
                UnitPaymentCorrectionNote model = _facade.ReadById(id);

                UnitPaymentCorrectionNoteViewModel viewModel = _mapper.Map <UnitPaymentCorrectionNoteViewModel>(model);

                if (indexAcceptPdf < 0)
                {
                    return(Ok(new
                    {
                        apiVersion = ApiVersion,
                        statusCode = General.OK_STATUS_CODE,
                        message = General.OK_MESSAGE,
                        data = viewModel,
                    }));
                }
                else
                {
                    int clientTimeZoneOffset               = int.Parse(Request.Headers["x-timezone-offset"].First());
                    UnitPaymentOrder          spbModel     = _spbFacade.ReadById((int)model.UPOId);
                    UnitPaymentOrderViewModel viewModelSpb = _mapper.Map <UnitPaymentOrderViewModel>(spbModel);
                    var supplier         = _facade.GetSupplier(model.SupplierId);
                    var supplier_address = "";
                    if (supplier != null)
                    {
                        supplier_address = supplier.address;
                    }

                    var temp_date = new DateTimeOffset();
                    foreach (var item in viewModel.items)
                    {
                        Lib.Models.UnitReceiptNoteModel.UnitReceiptNote urnModel = _facade.ReadByURNNo(item.uRNNo);
                        UnitReceiptNoteViewModel viewModelUrn = _mapper.Map <UnitReceiptNoteViewModel>(urnModel);
                        if (viewModelUrn != null && temp_date < viewModelUrn.date)
                        {
                            temp_date = viewModelUrn.date;
                        }
                    }
                    UnitPaymentQuantityCorrectionNotePDFTemplate PdfTemplate = new UnitPaymentQuantityCorrectionNotePDFTemplate();
                    MemoryStream stream = PdfTemplate.GeneratePdfTemplate(viewModel, viewModelSpb, temp_date, supplier_address, identityService.Username, clientTimeZoneOffset);

                    return(new FileStreamResult(stream, "application/pdf")
                    {
                        FileDownloadName = $"{model.UPCNo}.pdf"
                    });
                }
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
        public async Task <int> Create(UnitPaymentCorrectionNote m, string user, int clientTimeZoneOffset = 7)
        {
            int Created = 0;

            using (var transaction = this.dbContext.Database.BeginTransaction())
            {
                try
                {
                    EntityExtension.FlagForCreate(m, user, USER_AGENT);
                    var supplier       = GetSupplier(m.SupplierId);
                    var supplierImport = false;
                    m.SupplierNpwp = null;
                    if (supplier != null)
                    {
                        m.SupplierNpwp = supplier.npwp;
                        supplierImport = supplier.import;
                    }
                    m.UPCNo = await GenerateNo(m, clientTimeZoneOffset, supplierImport, m.DivisionName);

                    if (m.useVat == true)
                    {
                        m.ReturNoteNo = await GeneratePONo(m, clientTimeZoneOffset);
                    }
                    UnitPaymentOrder unitPaymentOrder = this.dbContext.UnitPaymentOrders.Where(s => s.Id == m.UPOId).Include(p => p.Items).ThenInclude(i => i.Details).FirstOrDefault();
                    unitPaymentOrder.IsCorrection = true;

                    foreach (var item in m.Items)
                    {
                        EntityExtension.FlagForCreate(item, user, USER_AGENT);
                        foreach (var itemSpb in unitPaymentOrder.Items)
                        {
                            foreach (var detailSpb in itemSpb.Details)
                            {
                                if (item.UPODetailId == detailSpb.Id)
                                {
                                    detailSpb.QuantityCorrection = detailSpb.QuantityCorrection - item.Quantity;
                                    ExternalPurchaseOrderDetail epoDetail = dbContext.ExternalPurchaseOrderDetails.FirstOrDefault(a => a.Id.Equals(detailSpb.EPODetailId));
                                    epoDetail.DOQuantity -= item.Quantity;
                                }
                            }
                        }
                    }

                    this.dbSet.Add(m);
                    Created = await dbContext.SaveChangesAsync();

                    Created += await AddCorrections(m, user);

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    throw new Exception(e.Message);
                }
            }

            return(Created);
        }
Beispiel #5
0
        public IActionResult GetPDF(int id)
        {
            try
            {
                var indexAcceptPdf = Request.Headers["Accept"].ToList().IndexOf("application/pdf");
                identityService.Username = User.Claims.Single(p => p.Type.Equals("username")).Value;
                UnitPaymentCorrectionNote model = _facade.ReadById(id);

                UnitPaymentCorrectionNoteViewModel viewModel = _mapper.Map <UnitPaymentCorrectionNoteViewModel>(model);

                //if (indexAcceptPdf < 0)
                //{
                //    return Ok(new
                //    {
                //        apiVersion = ApiVersion,
                //        statusCode = General.OK_STATUS_CODE,
                //        message = General.OK_MESSAGE,
                //        data = viewModel,
                //    });
                //}
                //else
                //{
                SupplierViewModel supplier = _facade.GetSupplier(viewModel.supplier._id);

                viewModel.supplier.address = supplier == null ? "" : supplier.address;
                int clientTimeZoneOffset               = int.Parse(Request.Headers["x-timezone-offset"].First());
                UnitPaymentOrder          spbModel     = _spbFacade.ReadById((int)model.UPOId);
                UnitPaymentOrderViewModel viewModelSpb = _mapper.Map <UnitPaymentOrderViewModel>(spbModel);
                DateTimeOffset?           receiptDate  = null;
                var today = new DateTime(1970, 1, 1);
                foreach (var item in model.Items)
                {
                    Lib.Models.UnitReceiptNoteModel.UnitReceiptNote urnModel = _facade.GetUrn(item.URNNo);

                    if (receiptDate == null || urnModel.ReceiptDate > receiptDate)
                    {
                        receiptDate = urnModel == null ? today : urnModel.ReceiptDate;
                    }
                }
                UnitPaymentPriceCorrectionNotePDFTemplate PdfTemplate = new UnitPaymentPriceCorrectionNotePDFTemplate();
                MemoryStream stream = PdfTemplate.GeneratePdfTemplate(viewModel, viewModelSpb, identityService.Username, clientTimeZoneOffset, receiptDate);

                return(new FileStreamResult(stream, "application/pdf")
                {
                    FileDownloadName = $"{model.UPCNo}.pdf"
                });
                //}
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
Beispiel #6
0
        public async Task <int> Create(UnitPaymentCorrectionNote model, bool supplierImport, string username, int clientTimeZoneOffset = 7)
        {
            int Created = 0;

            using (var transaction = this.dbContext.Database.BeginTransaction())
            {
                try
                {
                    EntityExtension.FlagForCreate(model, username, USER_AGENT);

                    model.UPCNo = await GenerateNo(model, supplierImport, clientTimeZoneOffset);

                    if (model.useVat == true)
                    {
                        model.ReturNoteNo = await GeneratePONo(model, clientTimeZoneOffset);
                    }
                    UnitPaymentOrder unitPaymentOrder = this.dbContext.UnitPaymentOrders.FirstOrDefault(s => s.Id == model.UPOId);
                    unitPaymentOrder.IsCorrection = true;

                    foreach (var item in model.Items)
                    {
                        UnitPaymentOrderDetail upoDetail = dbContext.UnitPaymentOrderDetails.FirstOrDefault(s => s.Id == item.UPODetailId);
                        item.PricePerDealUnitBefore          = upoDetail.PricePerDealUnit;
                        item.PriceTotalBefore                = upoDetail.PriceTotal;
                        upoDetail.PricePerDealUnitCorrection = item.PricePerDealUnitAfter;
                        upoDetail.PriceTotalCorrection       = item.PriceTotalAfter;

                        if (item.PriceTotalAfter > 0 && item.PricePerDealUnitAfter <= 0)
                        {
                            upoDetail.PricePerDealUnitCorrection = upoDetail.PricePerDealUnit;
                        }

                        EntityExtension.FlagForCreate(item, username, USER_AGENT);
                    }

                    this.dbSet.Add(model);
                    Created = await dbContext.SaveChangesAsync();

                    Created += await AddCorrections(model, username);

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    throw new Exception(e.Message);
                }
            }

            return(Created);
        }
Beispiel #7
0
        private async Task AutoCreateCreditorAccount(UnitPaymentCorrectionNote unitPaymentCorrectionNote)
        {
            var upoDetailIds            = unitPaymentCorrectionNote.Items.Select(element => element.UPODetailId).ToList();
            var unitPaymentOrderDetails = dbContext.UnitPaymentOrderDetails.Where(entity => upoDetailIds.Contains(entity.Id)).ToList();

            foreach (var unitPaymentCorrectionNoteItem in unitPaymentCorrectionNote.Items)
            {
                var dppAmount = (decimal)0;
                var vatAmount = (decimal)0;
                var unitPaymentOrderDetail = unitPaymentOrderDetails.FirstOrDefault(element => element.Id == unitPaymentCorrectionNoteItem.UPODetailId);

                if (unitPaymentCorrectionNote.CorrectionType == "Harga Total")
                {
                    dppAmount = (decimal)(unitPaymentCorrectionNoteItem.PriceTotalAfter - unitPaymentCorrectionNoteItem.PriceTotalBefore);
                }
                else if (unitPaymentCorrectionNote.CorrectionType == "Harga Satuan")
                {
                    dppAmount = (decimal)(unitPaymentCorrectionNoteItem.PricePerDealUnitAfter - unitPaymentCorrectionNoteItem.PricePerDealUnitBefore);
                }
                else if (unitPaymentCorrectionNote.CorrectionType == "Jumlah")
                {
                    dppAmount = (decimal)(unitPaymentOrderDetail.QuantityCorrection * unitPaymentOrderDetail.PricePerDealUnit);
                }

                if (unitPaymentCorrectionNote.useVat)
                {
                    vatAmount = dppAmount * (decimal)0.1;
                }


                var viewModel = new CreateCreditorAccountViewModel()
                {
                    UnitPaymentCorrectionDPP      = dppAmount,
                    UnitPaymentCorrectionId       = (int)unitPaymentCorrectionNote.Id,
                    UnitPaymentCorrectionMutation = dppAmount + vatAmount,
                    UnitPaymentCorrectionNo       = unitPaymentCorrectionNote.UPCNo,
                    UnitPaymentCorrectionPPN      = vatAmount,
                    UnitReceiptNoteNo             = unitPaymentCorrectionNoteItem.URNNo,
                    UnitPaymentCorrectionDate     = unitPaymentCorrectionNote.CorrectionDate
                };

                var uri        = "creditor-account/unit-payment-correction";
                var httpClient = (IHttpClientService)serviceProvider.GetService(typeof(IHttpClientService));
                var response   = await httpClient.PostAsync($"{APIEndpoint.Finance}{uri}", new StringContent(JsonConvert.SerializeObject(viewModel).ToString(), Encoding.UTF8, General.JsonMediaType));

                response.EnsureSuccessStatusCode();
            }
        }
Beispiel #8
0
        public IActionResult GetPDFNotaRetur(int id)
        {
            try
            {
                var indexAcceptPdf = Request.Headers["Accept"].ToList().IndexOf("application/pdf");

                UnitPaymentCorrectionNote          model     = _facade.ReadById(id);
                UnitPaymentCorrectionNoteViewModel viewModel = _mapper.Map <UnitPaymentCorrectionNoteViewModel>(model);

                if (indexAcceptPdf < 0)
                {
                    return(Ok(new
                    {
                        apiVersion = ApiVersion,
                        statusCode = General.OK_STATUS_CODE,
                        message = General.OK_MESSAGE,
                        data = viewModel,
                    }));
                }
                else
                {
                    int clientTimeZoneOffset = int.Parse(Request.Headers["x-timezone-offset"].First());

                    UnitPaymentQuantityCorrectionNotePDFTemplate PdfTemplate = new UnitPaymentQuantityCorrectionNotePDFTemplate();
                    UnitPaymentOrder          spbModel     = _spbFacade.ReadById((int)model.UPOId);
                    UnitPaymentOrderViewModel viewModelSpb = _mapper.Map <UnitPaymentOrderViewModel>(spbModel);
                    MemoryStream stream = PdfTemplate.GeneratePdfNotaReturTemplate(viewModel, viewModelSpb, clientTimeZoneOffset);

                    return(new FileStreamResult(stream, "application/pdf")
                    {
                        FileDownloadName = $"{model.UPCNo}.pdf"
                    });
                }
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
        async Task <string> GeneratePONo(UnitPaymentCorrectionNote model, int clientTimeZoneOffset)
        {
            string Year  = model.CorrectionDate.ToOffset(new TimeSpan(clientTimeZoneOffset, 0, 0)).ToString("yy");
            string Month = model.CorrectionDate.ToOffset(new TimeSpan(clientTimeZoneOffset, 0, 0)).ToString("MM");



            string no      = $"{Year}-{Month}-NR-";
            int    Padding = 3;

            var lastNo = await this.dbSet.Where(w => w.ReturNoteNo.StartsWith(no) && !w.IsDeleted).OrderByDescending(o => o.ReturNoteNo).FirstOrDefaultAsync();

            if (lastNo == null)
            {
                return(no + "1".PadLeft(Padding, '0'));
            }
            else
            {
                int lastNoNumber = Int32.Parse(lastNo.ReturNoteNo.Replace(no, "")) + 1;
                return(no + lastNoNumber.ToString().PadLeft(Padding, '0'));
            }
        }
Beispiel #10
0
 public IActionResult Get(int id)
 {
     try
     {
         UnitPaymentCorrectionNote          model     = _facade.ReadById(id);
         UnitPaymentCorrectionNoteViewModel viewModel = _mapper.Map <UnitPaymentCorrectionNoteViewModel>(model);
         return(Ok(new
         {
             apiVersion = ApiVersion,
             statusCode = General.OK_STATUS_CODE,
             message = General.OK_MESSAGE,
             data = viewModel,
         }));
     }
     catch (Exception e)
     {
         Dictionary <string, object> Result =
             new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
             .Fail();
         return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
     }
 }
Beispiel #11
0
        public async Task <IActionResult> Create([FromBody] UnitPaymentCorrectionNoteViewModel vm)
        {
            identityService.Token    = Request.Headers["Authorization"].First().Replace("Bearer ", "");
            identityService.Username = User.Claims.Single(p => p.Type.Equals("username")).Value;
            UnitPaymentCorrectionNote m = _mapper.Map <UnitPaymentCorrectionNote>(vm);
            //ValidateService validateService = (ValidateService)_facade.serviceProvider.GetService(typeof(ValidateService));
            IValidateService validateService = (IValidateService)serviceProvider.GetService(typeof(IValidateService));

            try
            {
                validateService.Validate(vm);
                int clientTimeZoneOffset = int.Parse(Request.Headers["x-timezone-offset"].First());
                int result = await _facade.Create(m, vm.supplier.import, identityService.Username, clientTimeZoneOffset);

                if (result.Equals(0) || vm == null)
                {
                    return(StatusCode(500));
                }
                else
                {
                    return(Created(Request.Path, result));
                }
            }
            catch (ServiceValidationExeption e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.BAD_REQUEST_STATUS_CODE, General.BAD_REQUEST_MESSAGE)
                    .Fail(e);
                return(BadRequest(Result));
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
Beispiel #12
0
        public UnitPaymentCorrectionNote GetNewData()
        {
            Lib.Models.UnitPaymentOrderModel.UnitPaymentOrder unitPaymentOrder = Task.Run(() => this.unitPaymentOrderDataUtil.GetTestData()).Result;

            List <UnitPaymentCorrectionNoteItem> unitPaymentCorrectionNoteItem = new List <UnitPaymentCorrectionNoteItem>();

            foreach (var item in unitPaymentOrder.Items)
            {
                foreach (var detail in item.Details)
                {
                    unitPaymentCorrectionNoteItem.Add(new UnitPaymentCorrectionNoteItem
                    {
                        UPODetailId            = detail.Id,
                        URNNo                  = item.URNNo,
                        EPONo                  = detail.EPONo,
                        PRId                   = detail.PRId,
                        PRNo                   = detail.PRNo,
                        PRDetailId             = detail.PRItemId,
                        ProductId              = detail.ProductId,
                        ProductCode            = detail.ProductCode,
                        ProductName            = detail.ProductName,
                        UomId                  = detail.UomId,
                        UomUnit                = detail.UomUnit,
                        PricePerDealUnitBefore = (double)detail.PricePerDealUnitCorrection,
                        PriceTotalBefore       = (double)detail.PriceTotalCorrection
                    });
                }
            }

            UnitPaymentCorrectionNote unitPaymentCorrectionNote = new UnitPaymentCorrectionNote
            {
                DivisionId   = "DivisionId",
                DivisionCode = "DivisionCode",
                DivisionName = "DivisionName",

                SupplierId   = "1",
                SupplierCode = "SupplierCode",
                SupplierName = "SupplierName",

                UPCNo = "18-06-G-NKI-001",
                UPOId = unitPaymentOrder.Id,

                UPONo = "18-08-BPL-P1A-003",

                CorrectionDate = new DateTimeOffset(),

                CorrectionType = "Jumlah",

                InvoiceCorrectionDate = new DateTimeOffset(),
                InvoiceCorrectionNo   = "123456",

                useVat = true,
                VatTaxCorrectionDate = new DateTimeOffset(),
                VatTaxCorrectionNo   = null,

                useIncomeTax            = true,
                IncomeTaxCorrectionDate = new DateTimeOffset(),
                IncomeTaxCorrectionNo   = null,

                ReleaseOrderNoteNo = "123456",
                ReturNoteNo        = "",

                CategoryId   = "CategoryId ",
                CategoryCode = "CategoryCode",
                CategoryName = "CategoryName",

                Remark = null,

                DueDate = new DateTimeOffset(), // ???

                Items = unitPaymentCorrectionNoteItem
            };

            return(unitPaymentCorrectionNote);
        }
        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();
                }
            }
        }