예제 #1
0
        public async Task <int> AutoJournalVBRequest(VBFormDto form)
        {
            var externalPurchaseOrders     = _dbContext.ExternalPurchaseOrders.Where(entity => form.EPOIds.Contains(entity.Id)).Select(entity => new { entity.Id, entity.IncomeTaxId, entity.UseIncomeTax, entity.IncomeTaxName, entity.IncomeTaxRate, entity.CurrencyCode, entity.IncomeTaxBy, entity.SupplierIsImport }).ToList();
            var externalPurchaseOrderItems = _dbContext.ExternalPurchaseOrderItems.Where(entity => form.EPOIds.Contains(entity.EPOId)).Select(entity => new { entity.Id, entity.EPOId, entity.PRId, entity.UnitId }).ToList();
            var epoItemIds = externalPurchaseOrderItems.Select(element => element.Id).ToList();
            var externalPurchaseOrderDetails = _dbContext.ExternalPurchaseOrderDetails.Where(entity => epoItemIds.Contains(entity.EPOItemId)).Select(entity => new { entity.Id, entity.EPOItemId, entity.DealQuantity, entity.PricePerDealUnit, entity.IncludePpn }).ToList();

            var purchaseRequestIds = externalPurchaseOrderItems.Select(element => element.PRId).ToList();
            var purchaseRequests   = _dbContext.PurchaseRequests.Where(w => purchaseRequestIds.Contains(w.Id)).Select(s => new { s.Id, s.CategoryCode, s.CategoryId, s.UnitId, s.DivisionId }).ToList();

            var journalTransactionToPost = new JournalTransaction()
            {
                Date        = form.Date,
                Description = "Approval VB",
                ReferenceNo = form.DocumentNo,
                Status      = "POSTED",
                Items       = new List <JournalTransactionItem>()
            };

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

            foreach (var externalPurchaseOrderDetail in externalPurchaseOrderDetails)
            {
                var externalPurchaseOrderItem = externalPurchaseOrderItems.FirstOrDefault(element => element.Id == externalPurchaseOrderDetail.EPOItemId);
                var externalPurchaseOrder     = externalPurchaseOrders.FirstOrDefault(element => element.Id == externalPurchaseOrderItem.EPOId);
                var purchaseRequest           = purchaseRequests.FirstOrDefault(element => element.Id == externalPurchaseOrderItem.PRId);

                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";
                    }
                }

                int.TryParse(purchaseRequest.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(purchaseRequest.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 = "0";
                    }
                }

                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"
                    };
                }

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

                var currency = await _currencyProvider.GetCurrencyByCurrencyCode(externalPurchaseOrder.CurrencyCode);

                var currencyRate = currency != null?currency.Rate.GetValueOrDefault() : 1;

                var basePrice  = externalPurchaseOrderDetail.PricePerDealUnit * externalPurchaseOrderDetail.DealQuantity * currencyRate;
                var totalPrice = basePrice;

                if (!externalPurchaseOrderDetail.IncludePpn)
                {
                    totalPrice += basePrice * 0.1;
                }

                if (externalPurchaseOrder.UseIncomeTax && externalPurchaseOrder.IncomeTaxBy.ToUpper() == "SUPPLIER")
                {
                    totalPrice -= basePrice * (incomeTaxRate / 100);
                }


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



                journalCreditItems.Add(new JournalTransactionItem()
                {
                    COA = new COA()
                    {
                        Code = currency.Code.ToUpper() == "IDR" ? $"1011.00.{division.COACode}.{unit.COACode}" : $"1012.00.{division.COACode}.{unit.COACode}"
                    },
                    Credit = (decimal)totalPrice
                });
            }

            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)),
                Credit = 0
            }).ToList();
            journalTransactionToPost.Items.AddRange(journalDebitItems);

            journalCreditItems = journalCreditItems.GroupBy(grouping => grouping.COA.Code).Select(s => new JournalTransactionItem()
            {
                COA = new COA()
                {
                    Code = s.Key
                },
                Debit  = 0,
                Credit = s.Sum(sum => Math.Round(sum.Credit.GetValueOrDefault(), 4))
            }).ToList();
            journalTransactionToPost.Items.AddRange(journalCreditItems);

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

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

            return((int)response.StatusCode);
        }
예제 #2
0
        public async Task <int> AutoJournalVBRequest(VBFormDto form)
        {
            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 unitPaymentOrderItemIds = _dbContext.UnitPaymentOrderItems.Where(entity => form.EPOIds.Contains(entity.UPOId)).Select(entity => entity.Id).ToList();
            var unitPaymentOrders      = _dbContext.UnitPaymentOrders.Where(entity => form.EPOIds.Contains(entity.Id)).ToList();
            var _unitPaymentOrderItems = _dbContext.UnitPaymentOrderItems.Where(entity => form.EPOIds.Contains(entity.UPOId)).ToList();
            var urnNos                = _unitPaymentOrderItems.Select(element => element.URNNo).ToList();
            var _unitReceiptNotes     = _dbContext.UnitReceiptNotes.Where(entity => urnNos.Contains(entity.URNNo)).ToList();
            var unitReceiptIds        = _unitReceiptNotes.Select(element => element.Id).ToList();
            var _unitReceiptNoteItems = _dbContext.UnitReceiptNoteItems.Where(entity => unitReceiptIds.Contains(entity.URNId)).ToList();
            var prIds                         = _unitReceiptNoteItems.Select(element => element.PRId).ToList();
            var _purchaseRequests             = _dbContext.PurchaseRequests.Where(entity => prIds.Contains(entity.Id)).ToList();
            var epoNos                        = _unitReceiptNoteItems.Select(element => element.EPONo).ToList();
            var _externalPurchaseOrders       = _dbContext.ExternalPurchaseOrders.Where(entity => epoNos.Contains(entity.EPONo)).ToList();
            var epoDetailIds                  = _unitReceiptNoteItems.Select(element => element.EPODetailId).ToList();
            var _externalPurchaseOrderDetails = _dbContext.ExternalPurchaseOrderDetails.Where(entity => epoDetailIds.Contains(entity.Id)).ToList();
            //var epoDetailIds = _dbContext.UnitPaymentOrderDetails.Where(entity => unitPaymentOrderItemIds.Contains(entity.UPOItemId)).Select(entity => entity.EPODetailId).ToList();

            //var externalPurchaseOrderItems = _dbContext.ExternalPurchaseOrderItems.Where(entity => form.EPOIds.Contains(entity.EPOId)).Select(entity => new { entity.Id, entity.EPOId, entity.PRId, entity.UnitId }).ToList();
            //var epoItemIds = externalPurchaseOrderItems.Select(element => element.Id).ToList();
            //var epoIds = externalPurchaseOrderItems.Select(element => element.EPOId).ToList();
            //var externalPurchaseOrders = _dbContext.ExternalPurchaseOrders.Where(entity => epoIds.Contains(entity.Id)).Select(entity => new { entity.Id, entity.IncomeTaxId, entity.UseIncomeTax, entity.IncomeTaxName, entity.IncomeTaxRate, entity.CurrencyCode, entity.IncomeTaxBy, entity.SupplierIsImport }).ToList();
            //var externalPurchaseOrderDetails = _dbContext.ExternalPurchaseOrderDetails.Where(entity => epoItemIds.Contains(entity.EPOItemId)).Select(entity => new { entity.Id, entity.EPOItemId, entity.DealQuantity, entity.PricePerDealUnit, entity.IncludePpn }).ToList();

            //var purchaseRequestIds = externalPurchaseOrderItems.Select(element => element.PRId).ToList();
            //var purchaseRequests = _dbContext.PurchaseRequests.Where(w => purchaseRequestIds.Contains(w.Id)).Select(s => new { s.Id, s.CategoryCode, s.CategoryId, s.UnitId, s.DivisionId }).ToList();

            var journalTransactionToPost = new JournalTransaction()
            {
                Date        = form.Date,
                Description = "Auto Journal Clearance VB",
                ReferenceNo = form.DocumentNo,
                Status      = "POSTED",
                Items       = new List <JournalTransactionItem>()
            };

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

            foreach (var unitPaymentOrder in unitPaymentOrders)
            {
                var urnIds           = _unitPaymentOrderItems.Where(element => element.UPOId == unitPaymentOrder.Id).Select(element => element.URNId).ToList();
                var unitReceiptNotes = _unitReceiptNotes.Where(element => urnIds.Contains(element.Id)).ToList();

                foreach (var unitReceiptNote in unitReceiptNotes)
                {
                    var unitReceiptNoteItems = _unitReceiptNoteItems.Where(element => element.URNId == unitReceiptNote.Id).ToList();
                    foreach (var unitReceiptNoteItem in unitReceiptNoteItems)
                    {
                        var purchaseRequest             = _purchaseRequests.FirstOrDefault(element => element.Id == unitReceiptNoteItem.PRId);
                        var externalPurchaseOrder       = _externalPurchaseOrders.FirstOrDefault(element => element.Id == unitReceiptNoteItem.EPOId);
                        var externalPurchaseOrderDetail = _externalPurchaseOrderDetails.FirstOrDefault(element => element.Id == unitReceiptNoteItem.EPODetailId);

                        if (purchaseRequest != null && externalPurchaseOrder != null && externalPurchaseOrderDetail != null)
                        {
                            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";
                                }
                            }

                            int.TryParse(purchaseRequest.CategoryId, out var categoryId);
                            var category = categories.FirstOrDefault(element => element.Id == 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";
                                }
                            }

                            var currency = await GetBICurrency(externalPurchaseOrder.CurrencyCode, unitReceiptNote.ReceiptDate);

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

                            var externalPOPriceTotal = externalPurchaseOrderDetail.PricePerDealUnit * externalPurchaseOrderDetail.DealQuantity;
                            double.TryParse(externalPurchaseOrder.IncomeTaxRate, out var incomeTaxRate);
                            var grandTotal = Convert.ToDecimal(unitReceiptNoteItem.ReceiptQuantity * unitReceiptNoteItem.PricePerDealUnit * (double)currencyRate);

                            var incomeTaxTotal = (decimal)0;
                            var vatTotal       = (decimal)0;
                            if (externalPurchaseOrder.UseIncomeTax && externalPurchaseOrder.IncomeTaxBy.ToUpper() == "SUPPLIER")
                            {
                                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"
                                    };
                                }

                                incomeTaxTotal = (decimal)incomeTaxRate / 100 * grandTotal;

                                //journalDebitItems.Add(new UAT.Data.Models.JournalTransactionItem()
                                //{
                                //    Coa = new ChartsOfAccount()
                                //    {
                                //        Code = unitReceiptNote.SupplierIsImport ? $"{category.ImportDebtCoa}.{division.Coacode}.{unit.Coacode}" : $"{category.LocalDebtCoa}.{division.Coacode}.{unit.Coacode}"
                                //    },
                                //    Debit = incomeTaxTotal
                                //});

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

                                //journalCreditItems.Add(new JournalTransactionItem()
                                //{
                                //    COA = new COA()
                                //    {
                                //        Code = !string.IsNullOrWhiteSpace(form.Bank.AccountCOA) ? $"{form.Bank.AccountCOA}" : $"9999.00.{division.COACode}.{unit.COACode}"
                                //    },
                                //    Credit = incomeTaxTotal
                                //});
                            }

                            if (externalPurchaseOrder.UseVat)
                            {
                                vatTotal = grandTotal * (decimal)0.1;
                            }

                            if (unitReceiptNote.SupplierIsImport && ((decimal)externalPOPriceTotal * currencyRate) > 100000000)
                            {
                                //Purchasing Journal Item
                                //journalDebitItems.Add(new UAT.Data.Models.JournalTransactionItem()
                                //{
                                //    Coa = new ChartsOfAccount()
                                //    {
                                //        Code = $"{category.PurchasingCoa}.{division.Coacode}.{unit.Coacode}"
                                //    },
                                //    Debit = grandTotal,
                                //    Remark = $"- {unitReceiptNoteItem.ProductName}"
                                //});

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

                                journalCreditItems.Add(new JournalTransactionItem()
                                {
                                    COA = new COA()
                                    {
                                        Code = !string.IsNullOrWhiteSpace(form.Bank.AccountCOA) ? $"{form.Bank.AccountCOA}" : $"9999.00.{division.COACode}.{unit.COACode}"
                                    },
                                    Credit = grandTotal - incomeTaxTotal + vatTotal
                                });

                                //Stock Journal Item
                                //journalDebitItems.Add(new UAT.Data.Models.JournalTransactionItem()
                                //{
                                //    Coa = new ChartsOfAccount()
                                //    {
                                //        Code = $"{category.StockCoa}.{division.Coacode}.{unit.Coacode}"
                                //    },
                                //    Debit = grandTotal,
                                //    Remark = $"- {unitReceiptNoteItem.ProductName}"
                                //});

                                //Purchasing Journal Item
                                //journalDebitItems.Add(new UAT.Data.Models.JournalTransactionItem()
                                //{
                                //    Coa = new ChartsOfAccount()
                                //    {
                                //        Code = $"{category.PurchasingCoa}.{division.Coacode}.{unit.Coacode}"
                                //    },
                                //    Debit = grandTotal,
                                //    Remark = $"- {unitReceiptNoteItem.ProductName}"
                                //});
                            }
                            else
                            {
                                //Purchasing Journal Item
                                //journalDebitItems.Add(new UAT.Data.Models.JournalTransactionItem()
                                //{
                                //    Coa = new ChartsOfAccount()
                                //    {
                                //        Code = $"{category.PurchasingCoa}.{division.Coacode}.{unit.Coacode}"
                                //    },
                                //    Debit = grandTotal,
                                //    Remark = $"- {unitReceiptNoteItem.ProductName}"
                                //});

                                if (SpecialCategoryCode.Contains(category.Code))
                                {
                                    //Stock Journal Item
                                    //journalDebitItems.Add(new UAT.Data.Models.JournalTransactionItem()
                                    //{
                                    //    Coa = new ChartsOfAccount()
                                    //    {
                                    //        Code = $"{category.StockCoa}.{division.Coacode}.{unit.Coacode}"
                                    //    },
                                    //    Debit = grandTotal,
                                    //    Remark = $"- {unitReceiptNoteItem.ProductName}"
                                    //});
                                }

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

                                journalCreditItems.Add(new JournalTransactionItem()
                                {
                                    COA = new COA()
                                    {
                                        Code = !string.IsNullOrWhiteSpace(form.Bank.AccountCOA) ? $"{form.Bank.AccountCOA}" : $"9999.00.{division.COACode}.{unit.COACode}"
                                    },
                                    Credit = grandTotal - incomeTaxTotal + vatTotal
                                });

                                //if (SpecialCategoryCode.Contains(category.Code))
                                //{
                                //    //Purchasing Journal Item
                                //    journalDebitItems.Add(new UAT.Data.Models.JournalTransactionItem()
                                //    {
                                //        Coa = new ChartsOfAccount()
                                //        {
                                //            Code = $"{category.PurchasingCoa}.{division.Coacode}.{unit.Coacode}"
                                //        },
                                //        Debit = 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)),
                Credit = 0
            }).ToList();
            journalTransactionToPost.Items.AddRange(journalDebitItems);

            journalCreditItems = journalCreditItems.GroupBy(grouping => grouping.COA.Code).Select(s => new JournalTransactionItem()
            {
                COA = new COA()
                {
                    Code = s.Key
                },
                Debit  = 0,
                Credit = s.Sum(sum => Math.Round(sum.Credit.GetValueOrDefault(), 4))
            }).ToList();
            journalTransactionToPost.Items.AddRange(journalCreditItems);

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

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

            return((int)response.StatusCode);
        }