public void DeleteSalesReturnFunc(int salesReturnID, int userID)
        {
            DateTime serverTime = DateTime.Now;

            Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_SALESRETURN).FirstOrDefault();

            SalesReturn salesReturn = _salesReturnRepository.GetById(salesReturnID);
            salesReturn.Status = (int)DbConstant.DefaultDataStatus.Deleted;
            salesReturn.ModifyDate = serverTime;
            salesReturn.ModifyUserId = userID;

            _salesReturnRepository.AttachNavigation(salesReturn.CreateUser);
            _salesReturnRepository.AttachNavigation(salesReturn.ModifyUser);
            _salesReturnRepository.AttachNavigation(salesReturn.Invoice);
            _salesReturnRepository.Update(salesReturn);
            _unitOfWork.SaveChanges();

            List<SalesReturnDetail> listDetail = _salesReturnDetailRepository.GetMany(x => x.SalesReturnId == salesReturnID).ToList();

            List<ReturnViewModel> listReturn = listDetail
                                    .GroupBy(l => l.InvoiceDetail.SPKDetailSparepartDetail.SparepartDetail.SparepartId)
                                    .Select(cl => new ReturnViewModel
                                    {
                                        SparepartId = cl.First().InvoiceDetail.SPKDetailSparepartDetail.SparepartDetail.SparepartId,
                                        ReturQty = cl.Count(),
                                    }).ToList();
            foreach (var itemDetail in listDetail)
            {
                itemDetail.Status = (int)DbConstant.DefaultDataStatus.Deleted;
                itemDetail.ModifyDate = serverTime;
                itemDetail.ModifyUserId = userID;

                _salesReturnDetailRepository.AttachNavigation(itemDetail.CreateUser);
                _salesReturnDetailRepository.AttachNavigation(itemDetail.ModifyUser);
                _salesReturnDetailRepository.AttachNavigation(itemDetail.SalesReturn);
                _salesReturnDetailRepository.AttachNavigation(itemDetail.InvoiceDetail);
                _salesReturnDetailRepository.Update(itemDetail);

                SparepartDetail spDetail = _sparepartDetailRepository.GetById(itemDetail.InvoiceDetail.SPKDetailSparepartDetail.SparepartDetailId);
                spDetail.Status = (int)DbConstant.SparepartDetailDataStatus.OutPurchase;

                _sparepartDetailRepository.AttachNavigation(spDetail.CreateUser);
                _sparepartDetailRepository.AttachNavigation(spDetail.ModifyUser);
                _sparepartDetailRepository.AttachNavigation(spDetail.PurchasingDetail);
                _sparepartDetailRepository.AttachNavigation(spDetail.Sparepart);
                _sparepartDetailRepository.AttachNavigation(spDetail.SparepartManualTransaction);
                _sparepartDetailRepository.Update(spDetail);
            }

            foreach (var itemReturn in listReturn)
            {
                Sparepart sparepart = _sparepartRepository.GetById(itemReturn.SparepartId);
                sparepart.StockQty -= itemReturn.ReturQty;

                _sparepartRepository.AttachNavigation(sparepart.CreateUser);
                _sparepartRepository.AttachNavigation(sparepart.ModifyUser);
                _sparepartRepository.AttachNavigation(sparepart.CategoryReference);
                _sparepartRepository.AttachNavigation(sparepart.UnitReference);
                _sparepartRepository.Update(sparepart);

                SparepartStockCard stockCard = new SparepartStockCard();
                stockCard.CreateUserId = userID;
                stockCard.CreateDate = serverTime;
                stockCard.PrimaryKeyValue = salesReturn.Id;
                stockCard.ReferenceTableId = transactionReferenceTable.Id;
                stockCard.SparepartId = sparepart.Id;
                stockCard.Description = "Pembatalan Retur Penjualan";
                stockCard.QtyOut = itemReturn.ReturQty;
                SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(sparepart.Id);
                double lastStock = 0;
                if (lastStockCard != null)
                {
                    lastStock = lastStockCard.QtyLast;
                }
                stockCard.QtyFirst = lastStock;
                stockCard.QtyLast = lastStock - stockCard.QtyOut;
                _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                _sparepartStokCardRepository.Add(stockCard);
            }

            _unitOfWork.SaveChanges();

            Transaction transaction = _transactionRepository.GetMany(x => x.PrimaryKeyValue == salesReturnID && x.ReferenceTableId == transactionReferenceTable.Id).FirstOrDefault();
            transaction.Status = (int)DbConstant.DefaultDataStatus.Deleted;
            transaction.ModifyDate = serverTime;
            transaction.ModifyUserId = userID;

            _transactionRepository.AttachNavigation(transaction.CreateUser);
            _transactionRepository.AttachNavigation(transaction.ModifyUser);
            _transactionRepository.AttachNavigation(transaction.PaymentMethod);
            _transactionRepository.AttachNavigation(transaction.ReferenceTable);
            _transactionRepository.Update(transaction);

            Invoice invoice = _invoiceRepository.GetById(salesReturn.InvoiceId);
            if (invoice.TotalPrice != invoice.TotalHasPaid && (invoice.TotalPrice - invoice.TotalHasPaid) >= (decimal)transaction.TotalTransaction)
            {
                invoice.TotalHasPaid -= (decimal)transaction.TotalTransaction;
            }

            if (invoice.TotalPrice == invoice.TotalHasPaid)
            {
                invoice.PaymentStatus = (int)DbConstant.PaymentStatus.Settled;
            }
            else
            {
                invoice.PaymentStatus = (int)DbConstant.PaymentStatus.NotSettled;
            }

            _invoiceRepository.AttachNavigation(invoice.CreateUser);
            _invoiceRepository.AttachNavigation(invoice.ModifyUser);
            _invoiceRepository.AttachNavigation(invoice.PaymentMethod);
            _invoiceRepository.AttachNavigation(invoice.SPK);

            _unitOfWork.SaveChanges();
        }
        public void DeletePurchaseReturn(int purchaseReturnID, int userID)
        {
            using (var trans = _unitOfWork.BeginTransaction())
            {
                try
                {
                    DateTime serverTime = DateTime.Now;

                    Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_PURCHASERETURN).FirstOrDefault();

                    PurchaseReturn purchaseReturn = _purchaseReturnRepository.GetById(purchaseReturnID);
                    purchaseReturn.Status = (int)DbConstant.DefaultDataStatus.Deleted;
                    purchaseReturn.ModifyDate = serverTime;
                    purchaseReturn.ModifyUserId = userID;

                    _purchaseReturnRepository.AttachNavigation(purchaseReturn.CreateUser);
                    _purchaseReturnRepository.AttachNavigation(purchaseReturn.ModifyUser);
                    _purchaseReturnRepository.AttachNavigation(purchaseReturn.Purchasing);
                    _purchaseReturnRepository.Update(purchaseReturn);
                    _unitOfWork.SaveChanges();

                    List<PurchaseReturnDetail> listDetail = _purchaseReturnDetailRepository.GetMany(x => x.PurchaseReturnId == purchaseReturnID).ToList();
                    List<ReturnViewModel> listReturn = listDetail
                                    .GroupBy(l => l.SparepartDetail.Sparepart)
                                    .Select(cl => new ReturnViewModel
                                    {
                                        SparepartId = cl.First().SparepartDetail.SparepartId,
                                        ReturQty = cl.Count(),
                                    }).ToList();

                    foreach (var itemDetail in listDetail)
                    {
                        itemDetail.Status = (int)DbConstant.DefaultDataStatus.Deleted;
                        itemDetail.ModifyDate = serverTime;
                        itemDetail.ModifyUserId = userID;

                        _purchaseReturnDetailRepository.AttachNavigation(itemDetail.CreateUser);
                        _purchaseReturnRepository.AttachNavigation(itemDetail.ModifyUser);
                        _purchaseReturnRepository.AttachNavigation(itemDetail.PurchaseReturn);
                        _purchaseReturnRepository.AttachNavigation(itemDetail.PurchasingDetail);
                        _purchaseReturnRepository.AttachNavigation(itemDetail.SparepartDetail);
                        _purchaseReturnDetailRepository.Update(itemDetail);

                        SparepartDetail spDetail = _sparepartDetailRepository.GetById(itemDetail.SparepartDetailId);
                        spDetail.Status = (int)DbConstant.DefaultDataStatus.Active;

                        _sparepartDetailRepository.AttachNavigation(spDetail.CreateUser);
                        _sparepartDetailRepository.AttachNavigation(spDetail.ModifyUser);
                        _sparepartDetailRepository.AttachNavigation(spDetail.PurchasingDetail);
                        _sparepartDetailRepository.AttachNavigation(spDetail.Sparepart);
                        _sparepartDetailRepository.AttachNavigation(spDetail.SparepartManualTransaction);
                        _sparepartDetailRepository.Update(spDetail);

                    }

                    foreach (var itemReturn in listReturn)
                    {
                        Sparepart sparepart = _sparepartRepository.GetById(itemReturn.SparepartId);
                        sparepart.StockQty += itemReturn.ReturQty;

                        _sparepartRepository.AttachNavigation(sparepart.CreateUser);
                        _sparepartRepository.AttachNavigation(sparepart.ModifyUser);
                        _sparepartRepository.AttachNavigation(sparepart.CategoryReference);
                        _sparepartRepository.AttachNavigation(sparepart.UnitReference);
                        _sparepartRepository.Update(sparepart);

                        SparepartStockCard stockCard = new SparepartStockCard();
                        stockCard.CreateUserId = userID;
                        stockCard.CreateDate = serverTime;
                        stockCard.PrimaryKeyValue = purchaseReturn.Id;
                        stockCard.ReferenceTableId = transactionReferenceTable.Id;
                        stockCard.SparepartId = sparepart.Id;
                        stockCard.Description = "Pembatalan Retur Pembelian";
                        stockCard.QtyIn = itemReturn.ReturQty;
                        SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(sparepart.Id);
                        double lastStock = 0;
                        if (lastStockCard != null)
                        {
                            lastStock = lastStockCard.QtyLast;
                        }
                        stockCard.QtyFirst = lastStock;
                        stockCard.QtyLast = lastStock + stockCard.QtyIn;
                        _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                        _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                        _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                        _sparepartStokCardRepository.Add(stockCard);
                    }

                    _unitOfWork.SaveChanges();

                    Transaction transaction = _transactionRepository.GetMany(x => x.PrimaryKeyValue == purchaseReturnID && x.ReferenceTableId == transactionReferenceTable.Id).FirstOrDefault();
                    transaction.Status = (int)DbConstant.DefaultDataStatus.Deleted;
                    transaction.ModifyDate = serverTime;
                    transaction.ModifyUserId = userID;

                    _transactionRepository.AttachNavigation(transaction.CreateUser);
                    _transactionRepository.AttachNavigation(transaction.ModifyUser);
                    _transactionRepository.AttachNavigation(transaction.PaymentMethod);
                    _transactionRepository.AttachNavigation(transaction.ReferenceTable);
                    _transactionRepository.Update(transaction);

                    Purchasing purchasing = _purchasingRepository.GetById(purchaseReturn.PurchasingId);
                    if (purchasing.TotalPrice != purchasing.TotalHasPaid && (purchasing.TotalPrice - purchasing.TotalHasPaid) >= (decimal)transaction.TotalTransaction)
                    {
                        purchasing.TotalHasPaid -= (decimal)transaction.TotalTransaction;
                    }

                    if (purchasing.TotalPrice == purchasing.TotalHasPaid)
                    {
                        purchasing.PaymentStatus = (int)DbConstant.PaymentStatus.Settled;
                    }
                    else
                    {
                        purchasing.PaymentStatus = (int)DbConstant.PaymentStatus.NotSettled;
                    }

                    _purchasingRepository.AttachNavigation(purchasing.CreateUser);
                    _purchasingRepository.AttachNavigation(purchasing.ModifyUser);
                    _purchasingRepository.AttachNavigation(purchasing.PaymentMethod);
                    _purchasingRepository.AttachNavigation(purchasing.Supplier);

                    _unitOfWork.SaveChanges();
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }
        public void InsertSalesReturnFunc(int invoiceID, List<ReturnViewModel> listReturn, int userID)
        {
            DateTime serverTime = DateTime.Now;

            Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_SALESRETURN).FirstOrDefault();

            SalesReturn salesReturn = new SalesReturn();
            salesReturn.CreateDate = serverTime;
            salesReturn.CreateUserId = userID;
            salesReturn.ModifyDate = serverTime;
            salesReturn.ModifyUserId = userID;
            salesReturn.InvoiceId = invoiceID;
            salesReturn.Date = serverTime;
            salesReturn.Status = (int)DbConstant.DefaultDataStatus.Active;

            string code = "SLR" + "-" + serverTime.Month.ToString() + serverTime.Day.ToString() + "-";
            //get total sales return created today
            List<SalesReturn> todaySLR = _salesReturnRepository.GetMany(s => s.Code.ToString().Contains(code) && s.CreateDate.Year == serverTime.Year).ToList();
            code = code + (todaySLR.Count + 1);
            salesReturn.Code = code;

            _salesReturnRepository.AttachNavigation(salesReturn.CreateUser);
            _salesReturnRepository.AttachNavigation(salesReturn.ModifyUser);
            _salesReturnRepository.AttachNavigation(salesReturn.Invoice);
            salesReturn = _salesReturnRepository.Add(salesReturn);

            _unitOfWork.SaveChanges();

            List<SalesReturnDetail> listReturnDetail = new List<SalesReturnDetail>();

            decimal totalTransaction = 0;
            foreach (var itemReturn in listReturn)
            {
                List<InvoiceDetail> invoiceDetails = _invoiceDetailRepository.GetMany(x => x.SPKDetailSparepartDetail.SparepartDetail.SparepartId == itemReturn.SparepartId
                    && x.InvoiceId == invoiceID
                    && (x.SPKDetailSparepartDetail.SparepartDetail.Status == (int)DbConstant.SparepartDetailDataStatus.OutPurchase
                    || x.SPKDetailSparepartDetail.SparepartDetail.Status == (int)DbConstant.SparepartDetailDataStatus.OutService
                    || x.SPKDetailSparepartDetail.SparepartDetail.Status == (int)DbConstant.SparepartDetailDataStatus.OutInstalled)
                    ).OrderByDescending(x => x.CreateDate)
                    .Take(itemReturn.ReturQty).ToList();

                foreach (var invoiceDetail in invoiceDetails)
                {
                    listReturnDetail.Add(new SalesReturnDetail
                    {
                        CreateDate = serverTime,
                        CreateUserId = userID,
                        ModifyDate = serverTime,
                        ModifyUserId = userID,
                        SalesReturnId = salesReturn.Id,
                        InvoiceDetailId = invoiceDetail.Id,
                        Status = (int)DbConstant.DefaultDataStatus.Active
                    });
                    totalTransaction += invoiceDetail.SubTotalPrice.AsDecimal();

                    SparepartDetail spDetail = _sparepartDetailRepository.GetById(invoiceDetail.SPKDetailSparepartDetail.SparepartDetailId);
                    spDetail.ModifyDate = serverTime;
                    spDetail.ModifyUserId = userID;
                    spDetail.Status = (int)DbConstant.SparepartDetailDataStatus.Active;

                    _sparepartDetailRepository.AttachNavigation(spDetail.CreateUser);
                    _sparepartDetailRepository.AttachNavigation(spDetail.ModifyUser);
                    _sparepartDetailRepository.AttachNavigation(spDetail.PurchasingDetail);
                    _sparepartDetailRepository.AttachNavigation(spDetail.Sparepart);
                    _sparepartDetailRepository.AttachNavigation(spDetail.SparepartManualTransaction);
                    _sparepartDetailRepository.Update(spDetail);
                }
                Sparepart sparepart = _sparepartRepository.GetById(itemReturn.SparepartId);
                sparepart.ModifyDate = serverTime;
                sparepart.ModifyUserId = userID;
                sparepart.StockQty += itemReturn.ReturQty;

                _sparepartRepository.AttachNavigation(sparepart.CreateUser);
                _sparepartRepository.AttachNavigation(sparepart.ModifyUser);
                _sparepartRepository.AttachNavigation(sparepart.CategoryReference);
                _sparepartRepository.AttachNavigation(sparepart.UnitReference);
                _sparepartRepository.Update(sparepart);

                SparepartStockCard stockCard = new SparepartStockCard();
                stockCard.CreateUserId = userID;
                stockCard.CreateDate = serverTime;
                stockCard.PrimaryKeyValue = salesReturn.Id;
                stockCard.ReferenceTableId = transactionReferenceTable.Id;
                stockCard.SparepartId = sparepart.Id;
                stockCard.Description = "Retur Penjualan";
                stockCard.QtyIn = itemReturn.ReturQty;
                SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(sparepart.Id);
                double lastStock = 0;
                if (lastStockCard != null)
                {
                    lastStock = lastStockCard.QtyLast;
                }
                stockCard.QtyFirst = lastStock;
                stockCard.QtyLast = lastStock + stockCard.QtyIn;
                _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                _sparepartStokCardRepository.Add(stockCard);
            }

            _unitOfWork.SaveChanges();

            foreach (var itemReturnDetail in listReturnDetail)
            {
                _salesReturnDetailRepository.AttachNavigation(itemReturnDetail.CreateUser);
                _salesReturnDetailRepository.AttachNavigation(itemReturnDetail.ModifyUser);
                _salesReturnDetailRepository.AttachNavigation(itemReturnDetail.SalesReturn);
                _salesReturnDetailRepository.AttachNavigation(itemReturnDetail.InvoiceDetail);
                _salesReturnDetailRepository.Add(itemReturnDetail);
            }

            Invoice invoice = _invoiceRepository.GetById(salesReturn.InvoiceId);
            invoice.Status = (int)DbConstant.InvoiceStatus.HasReturn;
            invoice.ModifyDate = serverTime;
            invoice.ModifyUserId = userID;
            if (invoice.TotalPrice != invoice.TotalHasPaid && (invoice.TotalPrice - invoice.TotalHasPaid) >= totalTransaction)
            {
                invoice.TotalHasPaid += totalTransaction;
            }

            if (invoice.TotalPrice == invoice.TotalHasPaid)
            {
                invoice.PaymentStatus = (int)DbConstant.PaymentStatus.Settled;
            }
            else
            {
                invoice.PaymentStatus = (int)DbConstant.PaymentStatus.NotSettled;
            }

            _invoiceRepository.AttachNavigation(invoice.CreateUser);
            _invoiceRepository.AttachNavigation(invoice.ModifyUser);
            _invoiceRepository.AttachNavigation(invoice.PaymentMethod);
            _invoiceRepository.AttachNavigation(invoice.SPK);

            _unitOfWork.SaveChanges();

            Transaction transaction = new Transaction();
            transaction.CreateDate = serverTime;
            transaction.CreateUserId = userID;
            transaction.ModifyDate = serverTime;
            transaction.ModifyUserId = userID;
            transaction.PrimaryKeyValue = salesReturn.Id;
            transaction.ReferenceTableId = transactionReferenceTable.Id;
            transaction.TotalPayment = totalTransaction.AsDouble();
            transaction.TotalTransaction = totalTransaction.AsDouble();
            transaction.Status = (int)DbConstant.DefaultDataStatus.Active;
            transaction.Description = "Retur Penjualan";
            transaction.TransactionDate = serverTime;

            _transactionRepository.AttachNavigation(transaction.CreateUser);
            _transactionRepository.AttachNavigation(transaction.ModifyUser);
            _transactionRepository.AttachNavigation(transaction.PaymentMethod);
            _transactionRepository.AttachNavigation(transaction.ReferenceTable);
            transaction = _transactionRepository.Add(transaction);

            _unitOfWork.SaveChanges();

            TransactionDetail transCredit = new TransactionDetail();
            transCredit.Credit = totalTransaction;
            transCredit.ParentId = transaction.Id;
            transCredit.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.03.01.01").FirstOrDefault().Id;

            _transactionDetailRepository.AttachNavigation(transCredit.Journal);
            _transactionDetailRepository.AttachNavigation(transCredit.Parent);
            _transactionDetailRepository.Add(transCredit);

            TransactionDetail transDebit = new TransactionDetail();
            transDebit.Debit = totalTransaction;
            transDebit.ParentId = transaction.Id;
            transDebit.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.04.01").FirstOrDefault().Id;

            _transactionDetailRepository.AttachNavigation(transCredit.Journal);
            _transactionDetailRepository.AttachNavigation(transCredit.Parent);
            _transactionDetailRepository.Add(transDebit);

            _unitOfWork.SaveChanges();
        }
        public void AbortParentSPK(SPKViewModel spk, int userId)
        {
            #region Abort Endorsed SPK
            DateTime serverTime = DateTime.Now;

            SPK entity = _SPKRepository.GetById(spk.Id);
            entity.StatusCompletedId = (int)DbConstant.SPKCompletionStatus.Completed;
            entity.StatusApprovalId = (int)DbConstant.ApprovalStatus.Endorsed;
            entity.Status = (int)DbConstant.DefaultDataStatus.Deleted;
            entity.ModifyDate = serverTime;
            entity.ModifyUserId = userId;

            //_SPKRepository.AttachNavigation<Vehicle>(entity.Vehicle);
            //_SPKRepository.AttachNavigation<User>(entity.ModifyUser);
            //_SPKRepository.AttachNavigation<User>(entity.CreateUser);
            //_SPKRepository.AttachNavigation<Reference>(entity.CategoryReference);
            _SPKRepository.Update(entity);

            foreach (var spkSp in _SPKDetailSparepartRepository.GetMany(sds => sds.SPKId == entity.Id))
            {
                Sparepart sparepart = _sparepartRepository.GetById(spkSp.Sparepart.Id);
                sparepart.StockQty = sparepart.StockQty + spkSp.TotalQuantity;
                sparepart.ModifyDate = serverTime;
                sparepart.ModifyUserId = userId;

                SparepartStockCard stockCard = new SparepartStockCard();
                Reference transactionReferenceTable = _referenceRepository.GetById(spk.CategoryReferenceId);

                stockCard.CreateUserId = userId;
                stockCard.CreateDate = serverTime;
                stockCard.PrimaryKeyValue = spk.Id;
                stockCard.ReferenceTableId = transactionReferenceTable.Id;
                stockCard.SparepartId = spkSp.SparepartId;
                stockCard.Description = "Pembatalan SPK";
                stockCard.QtyIn = spkSp.TotalQuantity;

                SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(spkSp.SparepartId);
                double lastStock = 0;
                if (lastStockCard != null)
                {
                    lastStock = lastStockCard.QtyLast;
                }
                stockCard.QtyFirst = lastStock;
                stockCard.QtyLast = lastStock + stockCard.QtyIn;
                _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                _sparepartStokCardRepository.Add(stockCard);

                //_sparepartRepository.AttachNavigation<User>(sparepart.ModifyUser);
                //_sparepartRepository.AttachNavigation<User>(sparepart.CreateUser);
                //_sparepartRepository.AttachNavigation<Reference>(sparepart.CategoryReference);
                //_sparepartRepository.AttachNavigation<Reference>(sparepart.UnitReference);
                _sparepartRepository.Update(sparepart);
            }

            foreach (var item in _SPKDetailSparepartDetailRepository.GetMany(sdsd => sdsd.SPKDetailSparepart.SPK.Id == entity.Id))
            {
                SparepartDetail sparepartDetail = _sparepartDetailRepository.GetById(item.SparepartDetail.Id);
                sparepartDetail.ModifyDate = serverTime;
                sparepartDetail.ModifyUserId = userId;
                sparepartDetail.Status = (int)DbConstant.SparepartDetailDataStatus.Active;

                //_sparepartDetailRepository.AttachNavigation<User>(sparepartDetail.ModifyUser);
                //_sparepartDetailRepository.AttachNavigation<User>(sparepartDetail.CreateUser);
                //_sparepartDetailRepository.AttachNavigation<Sparepart>(sparepartDetail.Sparepart);
                //_sparepartDetailRepository.AttachNavigation<PurchasingDetail>(sparepartDetail.PurchasingDetail);
                //_sparepartDetailRepository.AttachNavigation<SparepartManualTransaction>(sparepartDetail.SparepartManualTransaction);
                _sparepartDetailRepository.Update(sparepartDetail);
            }

            List<WheelExchangeHistory> wehList = _wheelExchangeHistoryRepository.GetMany(weh => weh.SPKId == spk.Id).ToList();

            foreach (var item in wehList)
            {
                _wheelExchangeHistoryRepository.Delete(item);
            }

            List<SPKSchedule> scheduleList = _SPKScheduleRepository.GetMany(sched => sched.SPKId == spk.Id).ToList();

            foreach (SPKSchedule schedule in scheduleList)
            {
                _SPKScheduleRepository.Delete(schedule);
            }

            _unitOfWork.SaveChanges();
            #endregion
        }
        public void SetAsCompletedSPK(SPKViewModel spk, int userId)
        {
            DateTime serverTime = DateTime.Now;

            SPK entity = _SPKRepository.GetById(spk.Id);
            entity.StatusCompletedId = (int)DbConstant.SPKCompletionStatus.Completed;
            entity.ModifyDate = serverTime;
            entity.ModifyUserId = userId;

            _SPKRepository.Update(entity);

            Invoice invc = new Invoice();
            invc.CreateDate = serverTime;
            invc.ModifyDate = serverTime;
            invc.ModifyUserId = userId;
            invc.CreateUserId = userId;

            invc.Code = spk.Code.Replace("SPK", "INVC");

            invc.TotalSparepart = spk.TotalSparepartPrice;
            invc.TotalFeeSparepart = 0;
            invc.TotalSparepartPlusFee = invc.TotalSparepart + invc.TotalFeeSparepart;

            invc.PaymentStatus = (int)DbConstant.PaymentStatus.NotSettled;
            invc.Status = (int)DbConstant.InvoiceStatus.FeeNotFixed;
            invc.PaymentMethod = _referenceRepository.GetMany(r => r.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_PIUTANG).FirstOrDefault();
            invc.TotalHasPaid = 0;
            invc.SPKId = spk.Id;

            if (spk.isContractWork)
            {
                invc.TotalService = spk.ContractWorkFee;
                invc.TotalFeeService = (spk.ContractWorkFee * (0.2).AsDecimal());
            }
            else
            {
                decimal ServiceFee = 0;

                TimeSpan SPKTimeSpan = serverTime - spk.CreateDate;
                int SPKWorkingDays = Math.Ceiling(SPKTimeSpan.TotalDays).AsInteger();

                for (int i = 0; i < SPKWorkingDays; i++)
                {
                    List<Mechanic> involvedMechanic = (from sched in _SPKScheduleRepository.GetMany(sc => sc.CreateDate.Day == spk.CreateDate.Day + i && sc.SPKId == spk.Id).ToList()
                                                       select sched.Mechanic).ToList();

                    foreach (Mechanic mechanic in involvedMechanic)
                    {
                        int mechanicJobForToday = _SPKScheduleRepository.GetMany(sc => sc.CreateDate.Day == spk.CreateDate.Day + i && sc.MechanicId == mechanic.Id).Count();

                        decimal mechanicFeeForToday = mechanic.BaseFee / mechanicJobForToday;

                        ServiceFee = ServiceFee + mechanicFeeForToday;
                    }
                }

                invc.TotalService = ServiceFee;
                invc.TotalFeeService = 0;
            }
            invc.TotalServicePlusFee = invc.TotalService + invc.TotalFeeService;
            invc.TotalSparepartAndService = invc.TotalSparepartPlusFee + invc.TotalServicePlusFee;
            invc.TotalValueAdded = (invc.TotalSparepartAndService * (0.1).AsDecimal());
            invc.TotalPrice = invc.TotalValueAdded + invc.TotalSparepartAndService;

            _invoiceRepository.AttachNavigation<SPK>(invc.SPK);
            _invoiceRepository.AttachNavigation<Reference>(invc.PaymentMethod);
            Invoice insertedInvoice = _invoiceRepository.Add(invc);

            List<SPKDetailSparepart> SPKSpList = _SPKDetailSparepartRepository.GetMany(sp => sp.SPKId == spk.Id).ToList();
            List<SPKDetailSparepartDetail> SPKSpDetailList = _SPKDetailSparepartDetailRepository.GetMany(spdt => spdt.SPKDetailSparepart.SPKId == spk.Id).ToList();

            foreach (SPKDetailSparepart spkSp in SPKSpList)
            {
                UsedGood foundUsedGood = _usedGoodRepository.GetMany(ug => ug.SparepartId == spkSp.SparepartId && ug.Status == (int)DbConstant.DefaultDataStatus.Active).FirstOrDefault();
                if (foundUsedGood != null)
                {
                    int usedGoodQty = SPKSpDetailList.Where(sp => sp.SparepartDetail.SparepartId == foundUsedGood.SparepartId).ToList().Count;
                    foundUsedGood.Stock = foundUsedGood.Stock + usedGoodQty;
                    _usedGoodRepository.Update(foundUsedGood);
                    _unitOfWork.SaveChanges();

                    UsedGoodTransaction usedGoodTrans = new UsedGoodTransaction();
                    usedGoodTrans.CreateDate = usedGoodTrans.ModifyDate = serverTime;
                    usedGoodTrans.CreateUserId = usedGoodTrans.ModifyUserId = userId;
                    usedGoodTrans.UsedGoodId = foundUsedGood.Id;
                    usedGoodTrans.TransactionDate = spk.CreateDate;
                    usedGoodTrans.Qty = usedGoodQty;
                    usedGoodTrans.ItemPrice = 0;
                    usedGoodTrans.TotalPrice = 0;
                    usedGoodTrans.TypeReferenceId = _referenceRepository.GetMany(r => r.Code == DbConstant.REF_USEDGOOD_TRANSACTION_TYPE_SPK).FirstOrDefault().Id;
                    usedGoodTrans.Remark = string.Format("SPK Code: {0}", spk.Code);
                    _usedGoodTransactionRepository.Add(usedGoodTrans);
                    _unitOfWork.SaveChanges();
                }

                //Replace Vehicle Wheel
                foreach (var item in getCurrentVehicleWheel(spk.Id, spk.VehicleId).Where(w => w.ReplaceWithWheelDetailId > 0))
                {
                    VehicleWheel vw = _vehicleWheelRepository.GetById(item.Id);

                    vw.WheelDetailId = item.ReplaceWithWheelDetailId;
                    vw.ModifyDate = serverTime;
                    vw.ModifyUserId = userId;

                    _vehicleWheelRepository.Update(vw);

                    UsedGood usedWHeel = _usedGoodRepository.GetMany(ug => ug.SparepartId == item.WheelDetail.SparepartDetail.SparepartId).FirstOrDefault();
                    if (usedWHeel != null)
                    {
                        usedWHeel.Stock++;

                        _usedGoodRepository.Update(usedWHeel);
                    }
                }
                _unitOfWork.SaveChanges();

                //Remove Wheel Exchange
                List<WheelExchangeHistory> wehList = _wheelExchangeHistoryRepository.GetMany(weh => weh.SPKId == spk.Id).ToList();

                foreach (var item in wehList)
                {
                    _wheelExchangeHistoryRepository.Delete(item);
                }
                _unitOfWork.SaveChanges();

                //Update Stock Card
                SparepartStockCard stockCard = new SparepartStockCard();
                Reference transactionReferenceTable = _referenceRepository.GetById(spk.CategoryReferenceId);

                stockCard.CreateUserId = userId;
                stockCard.CreateDate = serverTime;
                stockCard.PrimaryKeyValue = spk.Id;
                stockCard.ReferenceTableId = transactionReferenceTable.Id;
                stockCard.SparepartId = spkSp.SparepartId;
                stockCard.Description = "SPK Complete";
                stockCard.QtyOut = SPKSpDetailList.Count;
                SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(spkSp.SparepartId);
                double lastStock = 0;
                if (lastStockCard != null)
                {
                    lastStock = lastStockCard.QtyLast;
                }
                stockCard.QtyFirst = lastStock;
                stockCard.QtyLast = lastStock - stockCard.QtyOut;
                _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                _sparepartStokCardRepository.Add(stockCard);
            }

            foreach (SPKDetailSparepartDetail spkSpDtl in SPKSpDetailList)
            {
                InvoiceDetail invcDtl = new InvoiceDetail();

                invcDtl.Invoice = insertedInvoice;
                invcDtl.SPKDetailSparepartDetail = spkSpDtl;

                if (spkSpDtl.SparepartDetail.PurchasingDetailId > 0)
                {
                    invcDtl.SubTotalPrice = spkSpDtl.SparepartDetail.PurchasingDetail.Price.AsDouble();
                }
                else if (spkSpDtl.SparepartDetail.SparepartManualTransactionId > 0)
                {
                    invcDtl.SubTotalPrice = spkSpDtl.SparepartDetail.SparepartManualTransaction.Price.AsDouble();
                }

                invcDtl.Status = (int)DbConstant.DefaultDataStatus.Active;

                invcDtl.CreateDate = serverTime;
                invcDtl.ModifyDate = serverTime;
                invcDtl.ModifyUserId = userId;
                invcDtl.CreateUserId = userId;

                _invoiceDetailRepository.Add(invcDtl);
            }

            _unitOfWork.SaveChanges();
        }
        public void DeleteVehicle(VehicleViewModel vehicle, int userId)
        {
            DateTime serverTime = DateTime.Now;

            vehicle.ModifyDate = serverTime;
            vehicle.ModifyUserId = userId;
            vehicle.Status = (int)DbConstant.DefaultDataStatus.Deleted;
            Vehicle entity = _vehicleRepository.GetById(vehicle.Id);
            Map(vehicle, entity);

            _vehicleRepository.AttachNavigation(entity.Brand);
            _vehicleRepository.AttachNavigation(entity.Type);
            _vehicleRepository.AttachNavigation(entity.VehicleGroup);
            _vehicleRepository.AttachNavigation(entity.Customer);
            _vehicleRepository.AttachNavigation(entity.CreateUser);
            _vehicleRepository.AttachNavigation(entity.ModifyUser);
            _vehicleRepository.Update(entity);
            _unitOfWork.SaveChanges();

            foreach (var item in _vehicleWheelRepository.GetMany(vw => vw.VehicleId == vehicle.Id && vw.Status ==(int) DbConstant.DefaultDataStatus.Active))
            {
                item.ModifyDate = serverTime;
                item.ModifyUserId = userId;
                item.Status = (int)DbConstant.DefaultDataStatus.Deleted;

                _vehicleWheelRepository.AttachNavigation(item.Vehicle);
                _vehicleWheelRepository.AttachNavigation(item.WheelDetail);
                _vehicleWheelRepository.AttachNavigation(item.CreateUser);
                _vehicleWheelRepository.AttachNavigation(item.ModifyUser);
                _vehicleWheelRepository.Update(item);
                _unitOfWork.SaveChanges();

                SpecialSparepartDetail wdEntity = _specialSparepartDetailRepository.GetById(item.WheelDetailId);
                wdEntity.ModifyDate = serverTime;
                wdEntity.ModifyUserId = userId;
                wdEntity.Status = (int)DbConstant.WheelDetailStatus.Ready;

                _specialSparepartDetailRepository.AttachNavigation(wdEntity.SpecialSparepart);
                _specialSparepartDetailRepository.AttachNavigation(wdEntity.SparepartDetail);
                _specialSparepartDetailRepository.AttachNavigation(wdEntity.CreateUser);
                _specialSparepartDetailRepository.AttachNavigation(wdEntity.ModifyUser);
                _specialSparepartDetailRepository.Update(wdEntity);
                _unitOfWork.SaveChanges();

                SparepartDetail spdEntity = _sparepartDetailRepository.GetById(wdEntity.SparepartDetailId);
                spdEntity.ModifyDate = serverTime;
                spdEntity.ModifyUserId = userId;
                spdEntity.Status = (int)DbConstant.SparepartDetailDataStatus.Active;

                _sparepartDetailRepository.AttachNavigation(spdEntity.Sparepart);
                _sparepartDetailRepository.AttachNavigation(spdEntity.SparepartManualTransaction);
                _sparepartDetailRepository.AttachNavigation(spdEntity.PurchasingDetail);
                _sparepartDetailRepository.AttachNavigation(spdEntity.CreateUser);
                _sparepartDetailRepository.AttachNavigation(spdEntity.ModifyUser);
                _sparepartDetailRepository.Update(spdEntity);
                _unitOfWork.SaveChanges();

                Sparepart spEntity = _sparepartRepository.GetById(wdEntity.SparepartDetail.SparepartId);
                spEntity.ModifyDate = serverTime;
                spEntity.ModifyUserId = userId;
                spEntity.StockQty = spEntity.StockQty + 1;

                _sparepartRepository.AttachNavigation(spEntity.UnitReference);
                _sparepartRepository.AttachNavigation(spEntity.CategoryReference);
                _sparepartRepository.AttachNavigation(spEntity.CreateUser);
                _sparepartRepository.AttachNavigation(spEntity.ModifyUser);
                _sparepartRepository.Update(spEntity);
                _unitOfWork.SaveChanges();

                SparepartStockCard stockCard = new SparepartStockCard();
                Reference transactionReferenceTable = _referenceRepository.GetMany(r => r.Code == DbConstant.MODUL_VEHICLE).FirstOrDefault();

                stockCard.CreateUserId = userId;
                stockCard.CreateDate = serverTime;
                stockCard.PrimaryKeyValue = vehicle.Id;
                stockCard.ReferenceTableId = transactionReferenceTable.Id;
                stockCard.SparepartId = spEntity.Id;
                stockCard.Description = "Delete Vehicle";
                stockCard.QtyIn = 1;

                SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(spEntity.Id);
                double lastStock = 0;
                if (lastStockCard != null)
                {
                    lastStock = lastStockCard.QtyLast;
                }
                stockCard.QtyFirst = lastStock;
                stockCard.QtyLast = lastStock + stockCard.QtyIn;
                _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                _sparepartStokCardRepository.Add(stockCard);
                _unitOfWork.SaveChanges();
            }
        }
        public SPKViewModel InsertSPK(SPKViewModel spk,
            List<SPKDetailSparepartViewModel> spkSparepartList,
            List<SPKDetailSparepartDetailViewModel> spkSparepartDetailList,
            List<VehicleWheelViewModel> vehicleWheelList,
            int userId,
            bool isNeedApproval)
        {
            DateTime serverTime = DateTime.Now;
            Invoice insertedInvoice = new Invoice();
            Reference spkReference = _referenceRepository.GetById(spk.CategoryReferenceId);
            bool isSPKSales = spkReference.Code == DbConstant.REF_SPK_CATEGORY_SALE;

            string code = "SPK-";

            switch (spkReference.Code)
            {
                case DbConstant.REF_SPK_CATEGORY_SERVICE: code = code + "S";
                    break;
                case DbConstant.REF_SPK_CATEGORY_REPAIR: code = code + "P";
                    break;
                case DbConstant.REF_SPK_CATEGORY_SALE: code = code + "L";
                    break;
                case DbConstant.REF_SPK_CATEGORY_INVENTORY: code = code + "I";
                    break;
            }

            code = code + "-" + spk.Vehicle.ActiveLicenseNumber + "-" + serverTime.Month.ToString() + serverTime.Day.ToString() + "-";

            //get total SPK created today
            List<SPK> todaySPK = _SPKRepository.GetMany(s => s.Code.ToString().Contains(code) && s.CreateDate.Year == serverTime.Year).ToList();

            code = code + (todaySPK.Count + 1);

            spk.Code = code;
            spk.CreateDate = serverTime;
            spk.ModifyDate = serverTime;
            spk.ModifyUserId = userId;
            spk.CreateUserId = userId;

            spk.Status = (int)DbConstant.DefaultDataStatus.Active;
            if (isNeedApproval)
            {
                spk.StatusApprovalId = (int)DbConstant.ApprovalStatus.Pending;
                spk.StatusOverLimit = 1;
                spk.StatusPrintId = (int)DbConstant.SPKPrintStatus.Pending;
            }
            else
            {
                spk.StatusApprovalId = (int)DbConstant.ApprovalStatus.Approved;
                spk.StatusOverLimit = 0;
                spk.StatusPrintId = (int)DbConstant.SPKPrintStatus.Printed;
            }

            spk.StatusCompletedId = isSPKSales ? (int)DbConstant.SPKCompletionStatus.Completed : (int)DbConstant.SPKCompletionStatus.InProgress;
            SPK entityChild = new SPK();
            Map(spk, entityChild);

            SPK insertedSPK = _SPKRepository.Add(entityChild);

            if (isSPKSales)
            {
                //insert invoice

                Invoice invc = new Invoice();
                invc.Code = spk.Code.Replace("SPK", "INVC");
                invc.TotalSparepart = spk.TotalSparepartPrice;
                invc.TotalFeeSparepart = 0;
                invc.TotalSparepartPlusFee = invc.TotalSparepart + invc.TotalFeeSparepart;
                invc.TotalService = 0;
                invc.TotalFeeService = 0;
                invc.TotalServicePlusFee = invc.TotalService + invc.TotalFeeService;
                invc.TotalSparepartAndService = invc.TotalSparepartPlusFee + invc.TotalServicePlusFee;
                invc.TotalValueAdded = (invc.TotalSparepartAndService * (0.1).AsDecimal());
                invc.TotalPrice = invc.TotalValueAdded + invc.TotalSparepartAndService;
                invc.PaymentStatus = (int)DbConstant.PaymentStatus.NotSettled;
                invc.Status = (int)DbConstant.InvoiceStatus.FeeNotFixed;
                invc.TotalHasPaid = 0;
                invc.SPK = insertedSPK;
                invc.PaymentMethod = invc.PaymentMethod = _referenceRepository.GetMany(r => r.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_PIUTANG).FirstOrDefault();

                invc.CreateDate = serverTime;
                invc.ModifyDate = serverTime;
                invc.ModifyUserId = userId;
                invc.CreateUserId = userId;

                insertedInvoice = _invoiceRepository.Add(invc);
            }

            foreach (var spkSparepart in spkSparepartList)
            {
                SPKDetailSparepart entitySPKDetailSparepart = new SPKDetailSparepart();
                Sparepart sparepart = _sparepartRepository.GetById(spkSparepart.Sparepart.Id);

                entitySPKDetailSparepart.SparepartId = spkSparepart.SparepartId;
                entitySPKDetailSparepart.TotalPrice = spkSparepart.TotalPrice;
                entitySPKDetailSparepart.TotalQuantity = spkSparepart.TotalQuantity;
                entitySPKDetailSparepart.Sparepart = sparepart;
                entitySPKDetailSparepart.SPK = insertedSPK;

                entitySPKDetailSparepart.CreateDate = serverTime;
                entitySPKDetailSparepart.CreateUserId = userId;
                entitySPKDetailSparepart.ModifyDate = serverTime;
                entitySPKDetailSparepart.ModifyUserId = userId;
                entitySPKDetailSparepart.Status = (int)DbConstant.DefaultDataStatus.Active;

                if (!isNeedApproval)
                {
                    sparepart.StockQty = sparepart.StockQty - spkSparepart.TotalQuantity;
                    sparepart.ModifyDate = serverTime;
                    sparepart.ModifyUserId = userId;

                    _sparepartRepository.Update(sparepart);

                    SparepartStockCard stockCard = new SparepartStockCard();
                    Reference transactionReferenceTable = _referenceRepository.GetById(spk.CategoryReferenceId);

                    stockCard.CreateUserId = userId;
                    stockCard.CreateDate = serverTime;
                    stockCard.PrimaryKeyValue = spk.Id;
                    stockCard.ReferenceTableId = transactionReferenceTable.Id;
                    stockCard.SparepartId = sparepart.Id;
                    stockCard.Description = "SPK";
                    stockCard.QtyOut = spkSparepart.TotalQuantity;

                    SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(sparepart.Id);
                    double lastStock = 0;
                    if (lastStockCard != null)
                    {
                        lastStock = lastStockCard.QtyLast;
                    }
                    stockCard.QtyFirst = lastStock;
                    stockCard.QtyLast = lastStock - stockCard.QtyOut;
                    _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                    _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                    _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                    _sparepartStokCardRepository.Add(stockCard);
                }

                if (isSPKSales)
                {
                    UsedGood foundUsedGood = _usedGoodRepository.GetMany(ug => ug.SparepartId == spkSparepart.SparepartId && ug.Status == (int)DbConstant.DefaultDataStatus.Active).FirstOrDefault();
                    if (foundUsedGood != null)
                    {
                        foundUsedGood.Stock = foundUsedGood.Stock + spkSparepartList.Count;
                        _usedGoodRepository.Update(foundUsedGood);
                    }
                }

                SPKDetailSparepart insertedSPkDetailSparepart = _SPKDetailSparepartRepository.Add(entitySPKDetailSparepart);

                var detailList = spkSparepartDetailList.Where(spd => spd.SparepartDetail.SparepartId == spkSparepart.SparepartId);

                foreach (var spkSparepartDetail in detailList)
                {
                    SPKDetailSparepartDetail entityNewSparepartDetail = new SPKDetailSparepartDetail();

                    entityNewSparepartDetail.CreateDate = serverTime;
                    entityNewSparepartDetail.CreateUserId = userId;
                    entityNewSparepartDetail.ModifyDate = serverTime;
                    entityNewSparepartDetail.ModifyUserId = userId;
                    entityNewSparepartDetail.Status = (int)DbConstant.DefaultDataStatus.Active;

                    entityNewSparepartDetail.SPKDetailSparepart = insertedSPkDetailSparepart;
                    entityNewSparepartDetail.SparepartDetailId = spkSparepartDetail.SparepartDetailId;

                    SPKDetailSparepartDetail insertedSPKSpDtl = _SPKDetailSparepartDetailRepository.Add(entityNewSparepartDetail);

                    if (!isNeedApproval)
                    {
                        SparepartDetail sparepartDetail = _sparepartDetailRepository.GetById(spkSparepartDetail.SparepartDetail.Id);
                        sparepartDetail.ModifyDate = serverTime;
                        sparepartDetail.ModifyUserId = userId;

                        if (spkReference.Code == DbConstant.REF_SPK_CATEGORY_SALE)
                        {
                            sparepartDetail.Status = (int)DbConstant.SparepartDetailDataStatus.OutPurchase;
                        }
                        else
                        {
                            sparepartDetail.Status = (int)DbConstant.SparepartDetailDataStatus.OutService;
                        }

                        _sparepartDetailRepository.Update(sparepartDetail);
                    }

                    //insert invoice detail

                    if (isSPKSales)
                    {
                        InvoiceDetail invcDtl = new InvoiceDetail();

                        invcDtl.Invoice = insertedInvoice;
                        invcDtl.SPKDetailSparepartDetail = insertedSPKSpDtl;

                        if (insertedSPKSpDtl.SparepartDetail.PurchasingDetailId > 0)
                        {
                            invcDtl.SubTotalPrice = insertedSPKSpDtl.SparepartDetail.PurchasingDetail.Price.AsDouble();
                        }
                        else
                        {
                            invcDtl.SubTotalPrice = insertedSPKSpDtl.SparepartDetail.SparepartManualTransaction.Price.AsDouble();
                        }

                        invcDtl.Status = (int)DbConstant.DefaultDataStatus.Active;
                        invcDtl.FeePctg = 0;

                        invcDtl.CreateDate = serverTime;
                        invcDtl.ModifyDate = serverTime;
                        invcDtl.ModifyUserId = userId;
                        invcDtl.CreateUserId = userId;

                        _invoiceDetailRepository.Add(invcDtl);
                    }
                }
            }

            //Wheel Change Handler
            foreach (var item in vehicleWheelList.Where(vw => vw.ReplaceWithWheelDetailId > 0))
            {
                WheelExchangeHistory weh = new WheelExchangeHistory();
                weh.SPK = insertedSPK;
                weh.OriginalWheelId = item.WheelDetailId;
                weh.ReplaceWheelId = item.ReplaceWithWheelDetailId;

                weh.CreateDate = serverTime;
                weh.ModifyDate = serverTime;
                weh.ModifyUserId = userId;
                weh.CreateUserId = userId;

                _wheelExchangeHistoryRepository.Add(weh);

                SpecialSparepartDetail wheel = _specialSparepartDetailRepository.GetById(item.WheelDetailId);
                wheel.Kilometers = spk.Kilometers;
                wheel.ModifyDate = serverTime;
                wheel.ModifyUserId = userId;

                _specialSparepartDetailRepository.Update(wheel);
            }

            // Update Vehicle Kilometers
            Vehicle vehicle = _vehicleRepository.GetById(spk.VehicleId);

            vehicle.Kilometers = spk.Kilometers;
            vehicle.ModifyDate = serverTime;
            vehicle.ModifyUserId = userId;

            _vehicleRepository.Update(vehicle);

            _unitOfWork.SaveChanges();

            SPKViewModel mappedResult = new SPKViewModel();

            return Map(insertedSPK, mappedResult);
        }
        public void InsertVehicle(VehicleViewModel vehicle, DateTime expirationDate,
            List<VehicleWheelViewModel> vehicleWheels, int userId)
        {
            DateTime serverTime = DateTime.Now;

            Vehicle entity = new Vehicle();
            Map(vehicle, entity);
            entity.CreateDate = entity.ModifyDate = serverTime;
            entity.CreateUserId = entity.ModifyUserId = userId;
            entity.Status = (int)DbConstant.DefaultDataStatus.Active;

            _vehicleRepository.AttachNavigation(entity.Brand);
            _vehicleRepository.AttachNavigation(entity.Type);
            _vehicleRepository.AttachNavigation(entity.VehicleGroup);
            _vehicleRepository.AttachNavigation(entity.Customer);
            _vehicleRepository.AttachNavigation(entity.CreateUser);
            _vehicleRepository.AttachNavigation(entity.ModifyUser);
            var insertedVehicle = _vehicleRepository.Add(entity);
            _unitOfWork.SaveChanges();

            VehicleDetail vehicleDetail = new VehicleDetail
            {
                VehicleId = insertedVehicle.Id,
                LicenseNumber = insertedVehicle.ActiveLicenseNumber,
                ExpirationDate = expirationDate,
                CreateDate = serverTime,
                ModifyDate = serverTime,
                ModifyUserId = userId,
                CreateUserId = userId,
                Status = (int)DbConstant.LicenseNumberStatus.Active
            };

            _vehicleDetailRepository.AttachNavigation(vehicleDetail.Vehicle);
            _vehicleDetailRepository.AttachNavigation(vehicleDetail.CreateUser);
            _vehicleDetailRepository.AttachNavigation(vehicleDetail.ModifyUser);
            _vehicleDetailRepository.Add(vehicleDetail);
            _unitOfWork.SaveChanges();

            foreach (var vw in vehicleWheels)
            {
                if (vw.WheelDetailId > 0)
                {
                    VehicleWheel vwEntity = new VehicleWheel();
                    Map(vw, vwEntity);
                    vwEntity.Notes = vw.Notes;
                    vwEntity.WheelDetailId = vw.WheelDetailId;
                    vwEntity.CreateDate = vwEntity.ModifyDate = serverTime;
                    vwEntity.CreateUserId = vwEntity.ModifyUserId = userId;
                    vwEntity.VehicleId = insertedVehicle.Id;
                    vwEntity.Status = (int)DbConstant.DefaultDataStatus.Active;

                    _vehicleWheelRepository.AttachNavigation(vwEntity.Vehicle);
                    _vehicleWheelRepository.AttachNavigation(vwEntity.WheelDetail);
                    _vehicleWheelRepository.AttachNavigation(vwEntity.CreateUser);
                    _vehicleWheelRepository.AttachNavigation(vwEntity.ModifyUser);
                    _vehicleWheelRepository.Add(vwEntity);
                    _unitOfWork.SaveChanges();

                    SpecialSparepartDetail wdEntity = _specialSparepartDetailRepository.GetById(vw.WheelDetailId);
                    wdEntity.ModifyDate = serverTime;
                    wdEntity.ModifyUserId = userId;
                    wdEntity.Status = (int)DbConstant.WheelDetailStatus.Installed;

                    _specialSparepartDetailRepository.AttachNavigation(wdEntity.SpecialSparepart);
                    _specialSparepartDetailRepository.AttachNavigation(wdEntity.SparepartDetail);
                    _specialSparepartDetailRepository.AttachNavigation(wdEntity.CreateUser);
                    _specialSparepartDetailRepository.AttachNavigation(wdEntity.ModifyUser);
                    _specialSparepartDetailRepository.Update(wdEntity);
                    _unitOfWork.SaveChanges();

                    SparepartDetail spdEntity = _sparepartDetailRepository.GetById(wdEntity.SparepartDetailId);
                    spdEntity.ModifyDate = serverTime;
                    spdEntity.ModifyUserId = userId;
                    spdEntity.Status = (int)DbConstant.SparepartDetailDataStatus.OutInstalled;

                    _sparepartDetailRepository.AttachNavigation(spdEntity.Sparepart);
                    _sparepartDetailRepository.AttachNavigation(spdEntity.SparepartManualTransaction);
                    _sparepartDetailRepository.AttachNavigation(spdEntity.PurchasingDetail);
                    _sparepartDetailRepository.AttachNavigation(spdEntity.CreateUser);
                    _sparepartDetailRepository.AttachNavigation(spdEntity.ModifyUser);
                    _sparepartDetailRepository.Update(spdEntity);
                    _unitOfWork.SaveChanges();

                    Sparepart spEntity = _sparepartRepository.GetById(wdEntity.SparepartDetail.SparepartId);
                    spEntity.ModifyDate = serverTime;
                    spEntity.ModifyUserId = userId;
                    spEntity.StockQty = spEntity.StockQty - 1;

                    _sparepartRepository.AttachNavigation(spEntity.UnitReference);
                    _sparepartRepository.AttachNavigation(spEntity.CategoryReference);
                    _sparepartRepository.AttachNavigation(spEntity.CreateUser);
                    _sparepartRepository.AttachNavigation(spEntity.ModifyUser);
                    _sparepartRepository.Update(spEntity);
                    _unitOfWork.SaveChanges();

                    SparepartStockCard stockCard = new SparepartStockCard();
                    Reference transactionReferenceTable = _referenceRepository.GetMany(r => r.Code == DbConstant.MODUL_VEHICLE).FirstOrDefault();

                    stockCard.CreateUserId = userId;
                    stockCard.CreateDate = serverTime;
                    stockCard.PrimaryKeyValue = wdEntity.Id;
                    stockCard.ReferenceTableId = transactionReferenceTable.Id;
                    stockCard.SparepartId = spEntity.Id;
                    stockCard.Description = "Vehicle Insert";
                    stockCard.QtyOut = 1;

                    SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(spEntity.Id);
                    double lastStock = 0;
                    if (lastStockCard != null)
                    {
                        lastStock = lastStockCard.QtyLast;
                    }

                    stockCard.QtyFirst = lastStock;
                    stockCard.QtyLast = lastStock - stockCard.QtyOut;
                    _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                    _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                    _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                    _sparepartStokCardRepository.Add(stockCard);
                    _unitOfWork.SaveChanges();
                }
            }

            _unitOfWork.SaveChanges();
        }
        public void RevertVehicleWheel(int vehicleWheelId, int userId)
        {
            DateTime serverTime = DateTime.Now;

            VehicleWheel vwEntity = _vehicleWheelRepository.GetById(vehicleWheelId);
            vwEntity.ModifyDate = serverTime;
            vwEntity.ModifyUserId = userId;
            vwEntity.Status = (int)DbConstant.DefaultDataStatus.Deleted;

            _vehicleWheelRepository.AttachNavigation(vwEntity.Vehicle);
            _vehicleWheelRepository.AttachNavigation(vwEntity.WheelDetail);
            _vehicleWheelRepository.AttachNavigation(vwEntity.CreateUser);
            _vehicleWheelRepository.AttachNavigation(vwEntity.ModifyUser);
            _vehicleWheelRepository.Update(vwEntity);
            _unitOfWork.SaveChanges();

            SpecialSparepartDetail wdEntity = _specialSparepartDetailRepository.GetById(vwEntity.WheelDetailId);
            wdEntity.ModifyDate = serverTime;
            wdEntity.ModifyUserId = userId;
            wdEntity.Status = (int)DbConstant.WheelDetailStatus.Ready;

            _specialSparepartDetailRepository.AttachNavigation(wdEntity.SpecialSparepart);
            _specialSparepartDetailRepository.AttachNavigation(wdEntity.SparepartDetail);
            _specialSparepartDetailRepository.AttachNavigation(wdEntity.CreateUser);
            _specialSparepartDetailRepository.AttachNavigation(wdEntity.ModifyUser);
            _specialSparepartDetailRepository.Update(wdEntity);
            _unitOfWork.SaveChanges();

            SparepartDetail spdEntity = _sparepartDetailRepository.GetById(wdEntity.SparepartDetailId);
            spdEntity.ModifyDate = serverTime;
            spdEntity.ModifyUserId = userId;
            spdEntity.Status = (int)DbConstant.SparepartDetailDataStatus.Active;

            _sparepartDetailRepository.AttachNavigation(spdEntity.Sparepart);
            _sparepartDetailRepository.AttachNavigation(spdEntity.SparepartManualTransaction);
            _sparepartDetailRepository.AttachNavigation(spdEntity.PurchasingDetail);
            _sparepartDetailRepository.AttachNavigation(spdEntity.CreateUser);
            _sparepartDetailRepository.AttachNavigation(spdEntity.ModifyUser);
            _sparepartDetailRepository.Update(spdEntity);
            _unitOfWork.SaveChanges();

            Sparepart spEntity = _sparepartRepository.GetById(wdEntity.SparepartDetail.SparepartId);
            spEntity.ModifyDate = serverTime;
            spEntity.ModifyUserId = userId;
            spEntity.StockQty = spEntity.StockQty + 1;

            _sparepartRepository.AttachNavigation(spEntity.UnitReference);
            _sparepartRepository.AttachNavigation(spEntity.CategoryReference);
            _sparepartRepository.AttachNavigation(spEntity.CreateUser);
            _sparepartRepository.AttachNavigation(spEntity.ModifyUser);
            _sparepartRepository.Update(spEntity);
            _unitOfWork.SaveChanges();

            SparepartStockCard stockCard = new SparepartStockCard();
            Reference transactionReferenceTable = _referenceRepository.GetMany(r => r.Code == DbConstant.MODUL_VEHICLE).FirstOrDefault();

            stockCard.CreateUserId = userId;
            stockCard.CreateDate = serverTime;
            stockCard.PrimaryKeyValue = wdEntity.Id;
            stockCard.ReferenceTableId = transactionReferenceTable.Id;
            stockCard.SparepartId = spEntity.Id;
            stockCard.Description = "Revert Vehicle Wheel";
            stockCard.QtyIn = 1;

            SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(spEntity.Id);
            double lastStock = 0;
            if (lastStockCard != null)
            {
                lastStock = lastStockCard.QtyLast;
            }
            stockCard.QtyFirst = lastStock;
            stockCard.QtyLast = lastStock + stockCard.QtyIn;
            _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
            _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
            _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
            _sparepartStokCardRepository.Add(stockCard);
            _unitOfWork.SaveChanges();
        }
        public void Approve(PurchasingViewModel purchasing, int userID)
        {
            using (var trans = _unitOfWork.BeginTransaction())
            {
                try
                {
                    DateTime serverTime = DateTime.Now;

                    Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_PURCHASING).FirstOrDefault();

                    List<PurchasingDetail> listPurchasingDetail = _purchasingDetailRepository
                        .GetMany(c => c.PurchasingId == purchasing.Id).ToList();
                    foreach (var purchasingDetail in listPurchasingDetail)
                    {
                        Sparepart sparepartDB = _sparepartRepository.GetById(purchasingDetail.SparepartId);

                        SparepartDetail lastSPDetail = _sparepartDetailRepository.
                            GetMany(c => c.SparepartId == purchasingDetail.SparepartId).OrderByDescending(c => c.Id)
                            .FirstOrDefault();
                        string lastSPID = string.Empty;
                        if (lastSPDetail != null) lastSPID = lastSPDetail.Code;

                        SpecialSparepart specialSparepart = _specialSparepartRepository.GetMany(w => w.SparepartId == sparepartDB.Id && w.Status == (int)DbConstant.DefaultDataStatus.Active).FirstOrDefault();

                        for (int i = 1; i <= purchasingDetail.Qty; i++)
                        {
                            SparepartDetail spDetail = new SparepartDetail();
                            if (string.IsNullOrEmpty(lastSPID))
                            {
                                lastSPID = sparepartDB.Code + "0000000001";
                            }
                            else
                            {
                                lastSPID = sparepartDB.Code + (Convert.ToInt32(lastSPID.Substring(lastSPID.Length - 10)) + 1)
                                    .ToString("D10");
                            }
                            spDetail.PurchasingDetailId = purchasingDetail.Id;
                            spDetail.SparepartId = sparepartDB.Id;
                            spDetail.Code = lastSPID;
                            spDetail.CreateDate = serverTime;
                            spDetail.CreateUserId = userID;
                            spDetail.ModifyUserId = userID;
                            spDetail.ModifyDate = serverTime;
                            spDetail.Status = (int)DbConstant.SparepartDetailDataStatus.Active;

                            _sparepartDetailRepository.AttachNavigation(spDetail.CreateUser);
                            _sparepartDetailRepository.AttachNavigation(spDetail.ModifyUser);
                            _sparepartDetailRepository.AttachNavigation(spDetail.PurchasingDetail);
                            _sparepartDetailRepository.AttachNavigation(spDetail.Sparepart);
                            _sparepartDetailRepository.AttachNavigation(spDetail.SparepartManualTransaction);
                            SparepartDetail insertedSpDetail = _sparepartDetailRepository.Add(spDetail);

                            if (!string.IsNullOrEmpty(purchasingDetail.SerialNumber) && specialSparepart != null)
                            {
                                SpecialSparepartDetail wd = new SpecialSparepartDetail();
                                wd.SerialNumber = purchasingDetail.SerialNumber;
                                wd.CreateUserId = userID;
                                wd.CreateDate = serverTime;
                                wd.ModifyUserId = userID;
                                wd.ModifyDate = serverTime;
                                wd.SpecialSparepartId = specialSparepart.Id;
                                wd.SparepartDetail = insertedSpDetail;
                                wd.Status = (int)DbConstant.WheelDetailStatus.Ready;

                                _specialSparepartDetailRepository.AttachNavigation(spDetail.CreateUser);
                                _specialSparepartDetailRepository.AttachNavigation(spDetail.ModifyUser);
                                _specialSparepartDetailRepository.AttachNavigation(spDetail.PurchasingDetail);
                                _specialSparepartDetailRepository.AttachNavigation(spDetail.Sparepart);
                                _specialSparepartDetailRepository.AttachNavigation(spDetail.SparepartManualTransaction);
                                _specialSparepartDetailRepository.Add(wd);
                            }
                        }

                        purchasingDetail.Status = (int)DbConstant.PurchasingStatus.Active;
                        _purchasingDetailRepository.AttachNavigation(purchasingDetail.CreateUser);
                        _purchasingDetailRepository.AttachNavigation(purchasingDetail.ModifyUser);
                        _purchasingDetailRepository.AttachNavigation(purchasingDetail.Purchasing);
                        _purchasingDetailRepository.AttachNavigation(purchasingDetail.Sparepart);
                        _purchasingDetailRepository.Update(purchasingDetail);

                        Sparepart sparepart = _sparepartRepository.GetById(purchasingDetail.SparepartId);
                        sparepart.StockQty += purchasingDetail.Qty;

                        _sparepartRepository.AttachNavigation(sparepart.CreateUser);
                        _sparepartRepository.AttachNavigation(sparepart.ModifyUser);
                        _sparepartRepository.AttachNavigation(sparepart.CategoryReference);
                        _sparepartRepository.AttachNavigation(sparepart.UnitReference);
                        _sparepartRepository.Update(sparepart);

                        SparepartStockCard stockCard = new SparepartStockCard();
                        stockCard.CreateUserId = userID;
                        stockCard.CreateDate = serverTime;
                        stockCard.PrimaryKeyValue = purchasing.Id;
                        stockCard.ReferenceTableId = transactionReferenceTable.Id;
                        stockCard.SparepartId = sparepart.Id;
                        stockCard.Description = "Purchasing";
                        stockCard.QtyIn = purchasingDetail.Qty;
                        SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(sparepart.Id);
                        double lastStock = 0;
                        if (lastStockCard != null)
                        {
                            lastStock = lastStockCard.QtyLast;
                        }
                        stockCard.QtyFirst = lastStock;
                        stockCard.QtyLast = lastStock + stockCard.QtyIn;
                        _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                        _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                        _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                        _sparepartStokCardRepository.Add(stockCard);

                        _unitOfWork.SaveChanges();
                    }

                    Reference refSelected = _referenceRepository.GetById(purchasing.PaymentMethodId);
                    purchasing.Status = (int)DbConstant.PurchasingStatus.Active;
                    if (refSelected != null &&
                        (refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_BANK_EKONOMI
                        || refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_BANK_BCA1
                        || refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_BANK_BCA2
                        || refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_KAS)
                       )
                    {
                        purchasing.TotalHasPaid = purchasing.TotalPrice;
                    }

                    if (purchasing.TotalHasPaid != purchasing.TotalPrice)
                    {
                        purchasing.PaymentStatus = (int)DbConstant.PaymentStatus.NotSettled;
                    }
                    else
                    {
                        purchasing.PaymentStatus = (int)DbConstant.PaymentStatus.Settled;
                    }
                    Purchasing entity = _purchasingRepository.GetById(purchasing.Id);
                    //Map(purchasing, entity);
                    entity.PaymentStatus = purchasing.PaymentStatus;
                    entity.Status = purchasing.Status;
                    entity.TotalHasPaid = purchasing.TotalHasPaid;
                    entity.TotalPrice = purchasing.TotalPrice;
                    entity.PaymentMethodId = purchasing.PaymentMethodId;
                    _purchasingRepository.AttachNavigation(entity.CreateUser);
                    _purchasingRepository.AttachNavigation(entity.ModifyUser);
                    _purchasingRepository.AttachNavigation(entity.PaymentMethod);
                    _purchasingRepository.AttachNavigation(entity.Supplier);
                    _purchasingRepository.Update(entity);
                    _unitOfWork.SaveChanges();

                    Transaction transaction = new Transaction();
                    transaction.TransactionDate = purchasing.Date;
                    transaction.TotalPayment = Convert.ToDouble(purchasing.TotalHasPaid);
                    transaction.TotalTransaction = Convert.ToDouble(purchasing.TotalPrice);
                    transaction.ReferenceTableId = transactionReferenceTable.Id;
                    transaction.PrimaryKeyValue = purchasing.Id;
                    transaction.CreateDate = serverTime;
                    transaction.CreateUserId = userID;
                    transaction.ModifyUserId = userID;
                    transaction.ModifyDate = serverTime;
                    transaction.Status = (int)DbConstant.DefaultDataStatus.Active;
                    transaction.Description = "Pembelian sparepart";
                    transaction.PaymentMethodId = purchasing.PaymentMethodId;

                    _transactionRepository.AttachNavigation(transaction.CreateUser);
                    _transactionRepository.AttachNavigation(transaction.ModifyUser);
                    _transactionRepository.AttachNavigation(transaction.PaymentMethod);
                    _transactionRepository.AttachNavigation(transaction.ReferenceTable);
                    Transaction transactionInserted = _transactionRepository.Add(transaction);
                    _unitOfWork.SaveChanges();

                    switch (refSelected.Code)
                    {
                        case DbConstant.REF_PURCHASE_PAYMENTMETHOD_BANK_EKONOMI:
                        case DbConstant.REF_PURCHASE_PAYMENTMETHOD_BANK_BCA1:
                        case DbConstant.REF_PURCHASE_PAYMENTMETHOD_BANK_BCA2:
                            {
                                // Bank Kredit --> Karena berkurang
                                TransactionDetail detailBank = new TransactionDetail();
                                detailBank.Credit = purchasing.TotalHasPaid;
                                if (refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_BANK_EKONOMI)
                                {
                                    detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.01").FirstOrDefault().Id;
                                }
                                else if (refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_BANK_BCA1)
                                {
                                    detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.02").FirstOrDefault().Id;
                                }
                                else if (refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_BANK_BCA2)
                                {
                                    detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.03").FirstOrDefault().Id;
                                }
                                detailBank.ParentId = transactionInserted.Id;

                                _transactionDetailRepository.AttachNavigation(detailBank.Journal);
                                _transactionDetailRepository.AttachNavigation(detailBank.Parent);
                                _transactionDetailRepository.Add(detailBank);
                                break;
                            }

                        case DbConstant.REF_PURCHASE_PAYMENTMETHOD_KAS:
                            // Kas Kredit --> Karena berkurang
                            TransactionDetail detailKas = new TransactionDetail();
                            detailKas.Credit = purchasing.TotalHasPaid;
                            detailKas.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.01.01").FirstOrDefault().Id;
                            detailKas.ParentId = transactionInserted.Id;

                            _transactionDetailRepository.AttachNavigation(detailKas.Journal);
                            _transactionDetailRepository.AttachNavigation(detailKas.Parent);
                            _transactionDetailRepository.Add(detailKas);
                            break;

                        case DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_KAS:
                            // Kas Kredit --> Karena berkurang
                            TransactionDetail detailKasKarenaUangMuka = new TransactionDetail();
                            detailKasKarenaUangMuka.Credit = purchasing.TotalHasPaid;
                            detailKasKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.01.01").FirstOrDefault().Id;
                            detailKasKarenaUangMuka.ParentId = transactionInserted.Id;

                            _transactionDetailRepository.AttachNavigation(detailKasKarenaUangMuka.Journal);
                            _transactionDetailRepository.AttachNavigation(detailKasKarenaUangMuka.Parent);
                            _transactionDetailRepository.Add(detailKasKarenaUangMuka);

                            // Uang Muka Debit --> Karena bertambah
                            TransactionDetail detailUangMukaBertambahKarenaKas = new TransactionDetail();
                            detailUangMukaBertambahKarenaKas.Debit = purchasing.TotalHasPaid;
                            detailUangMukaBertambahKarenaKas.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.05.01.01").FirstOrDefault().Id;
                            detailUangMukaBertambahKarenaKas.ParentId = transactionInserted.Id;

                            _transactionDetailRepository.AttachNavigation(detailUangMukaBertambahKarenaKas.Journal);
                            _transactionDetailRepository.AttachNavigation(detailUangMukaBertambahKarenaKas.Parent);
                            _transactionDetailRepository.Add(detailUangMukaBertambahKarenaKas);

                            // Uang Muka Kredit --> Karena berkurang
                            TransactionDetail detailUangMukaBerkurangKarenaKas = new TransactionDetail();
                            detailUangMukaBerkurangKarenaKas.Credit = purchasing.TotalHasPaid;
                            detailUangMukaBerkurangKarenaKas.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.05.01.01").FirstOrDefault().Id;
                            detailUangMukaBerkurangKarenaKas.ParentId = transactionInserted.Id;

                            _transactionDetailRepository.AttachNavigation(detailUangMukaBerkurangKarenaKas.Journal);
                            _transactionDetailRepository.AttachNavigation(detailUangMukaBerkurangKarenaKas.Parent);
                            _transactionDetailRepository.Add(detailUangMukaBerkurangKarenaKas);
                            break;

                        case DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_BANK_EKONOMI:
                        case DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_BANK_BCA1:
                        case DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_BANK_BCA2:
                            {
                                // Bank Kredit --> Karena berkurang
                                TransactionDetail detailBankKarenaUangMuka = new TransactionDetail();
                                detailBankKarenaUangMuka.Credit = purchasing.TotalHasPaid;
                                if (refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_BANK_EKONOMI)
                                {
                                    detailBankKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.01").FirstOrDefault().Id;
                                }
                                else if (refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_BANK_BCA1)
                                {
                                    detailBankKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.02").FirstOrDefault().Id;
                                }
                                else if (refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_BANK_BCA2)
                                {
                                    detailBankKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.03").FirstOrDefault().Id;
                                }
                                detailBankKarenaUangMuka.ParentId = transactionInserted.Id;

                                _transactionDetailRepository.AttachNavigation(detailBankKarenaUangMuka.Journal);
                                _transactionDetailRepository.AttachNavigation(detailBankKarenaUangMuka.Parent);
                                _transactionDetailRepository.Add(detailBankKarenaUangMuka);

                                // Uang Muka Debit --> Karena bertambah
                                TransactionDetail detailUangMukaBertambahKarenaBank = new TransactionDetail();
                                detailUangMukaBertambahKarenaBank.Debit = purchasing.TotalHasPaid;
                                detailUangMukaBertambahKarenaBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.05.01.01").FirstOrDefault().Id;
                                detailUangMukaBertambahKarenaBank.ParentId = transactionInserted.Id;

                                _transactionDetailRepository.AttachNavigation(detailUangMukaBertambahKarenaBank.Journal);
                                _transactionDetailRepository.AttachNavigation(detailUangMukaBertambahKarenaBank.Parent);
                                _transactionDetailRepository.Add(detailUangMukaBertambahKarenaBank);

                                // Uang Muka Kredit --> Karena berkurang
                                TransactionDetail detailUangMukaBerkurangKarenaBank = new TransactionDetail();
                                detailUangMukaBerkurangKarenaBank.Credit = purchasing.TotalHasPaid;
                                detailUangMukaBerkurangKarenaBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.05.01.01").FirstOrDefault().Id;
                                detailUangMukaBerkurangKarenaBank.ParentId = transactionInserted.Id;

                                _transactionDetailRepository.AttachNavigation(detailUangMukaBerkurangKarenaBank.Journal);
                                _transactionDetailRepository.AttachNavigation(detailUangMukaBerkurangKarenaBank.Parent);
                                _transactionDetailRepository.Add(detailUangMukaBerkurangKarenaBank);
                                break;
                            }

                        case DbConstant.REF_PURCHASE_PAYMENTMETHOD_UTANG:
                            TransactionDetail utang = new TransactionDetail();
                            utang.Credit = purchasing.TotalPrice - purchasing.TotalHasPaid;
                            utang.JournalId = _journalMasterRepository.GetMany(j => j.Code == "2.01.01.01").FirstOrDefault().Id;
                            utang.ParentId = transactionInserted.Id;

                            _transactionDetailRepository.AttachNavigation(utang.Journal);
                            _transactionDetailRepository.AttachNavigation(utang.Parent);
                            _transactionDetailRepository.Add(utang);
                            break;
                    }

                    if (refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_BANK_EKONOMI ||
                        refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_BANK_BCA1 ||
                       refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_BANK_BCA2 ||
                       refSelected.Code == DbConstant.REF_PURCHASE_PAYMENTMETHOD_UANGMUKA_KAS)
                    {
                        if (purchasing.TotalPrice > purchasing.TotalHasPaid)
                        {
                            // Utang Kredit --> Karena bertambah
                            TransactionDetail utang = new TransactionDetail();
                            utang.Credit = purchasing.TotalPrice - purchasing.TotalHasPaid;
                            utang.JournalId = _journalMasterRepository.GetMany(j => j.Code == "2.01.01.01").FirstOrDefault().Id;
                            utang.ParentId = transactionInserted.Id;

                            _transactionDetailRepository.AttachNavigation(utang.Journal);
                            _transactionDetailRepository.AttachNavigation(utang.Parent);
                            _transactionDetailRepository.Add(utang);
                        }
                    }

                    // Sparepart Debit --> Karena bertambah
                    TransactionDetail detailSparepart = new TransactionDetail();
                    detailSparepart.Debit = purchasing.TotalPrice;
                    detailSparepart.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.04.01").FirstOrDefault().Id;
                    detailSparepart.ParentId = transactionInserted.Id;

                    _transactionDetailRepository.AttachNavigation(detailSparepart.Journal);
                    _transactionDetailRepository.AttachNavigation(detailSparepart.Parent);
                    _transactionDetailRepository.Add(detailSparepart);

                    _unitOfWork.SaveChanges();

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }
        public void InsertPurchaseReturnFunc(int purchasingID, List<ReturnViewModel> listReturn, int userID)
        {
            DateTime serverTime = DateTime.Now;

            Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_PURCHASERETURN).FirstOrDefault();

            PurchaseReturn purchaseReturn = new PurchaseReturn();
            purchaseReturn.CreateDate = serverTime;
            purchaseReturn.CreateUserId = userID;
            purchaseReturn.ModifyDate = serverTime;
            purchaseReturn.ModifyUserId = userID;
            purchaseReturn.PurchasingId = purchasingID;
            purchaseReturn.Date = serverTime;
            purchaseReturn.Status = (int)DbConstant.DefaultDataStatus.Active;

            string code = "PRR" + "-" + serverTime.Month.ToString() + serverTime.Day.ToString() + "-";
            //get total purchasing return created today
            List<PurchaseReturn> todayPRR = _purchaseReturnRepository.GetMany(s => s.Code.ToString().Contains(code) && s.CreateDate.Year == serverTime.Year).ToList();
            code = code + (todayPRR.Count + 1);
            purchaseReturn.Code = code;

            _purchaseReturnRepository.AttachNavigation(purchaseReturn.CreateUser);
            _purchaseReturnRepository.AttachNavigation(purchaseReturn.ModifyUser);
            _purchaseReturnRepository.AttachNavigation(purchaseReturn.Purchasing);
            purchaseReturn = _purchaseReturnRepository.Add(purchaseReturn);

            _unitOfWork.SaveChanges();

            List<PurchaseReturnDetail> listReturnDetail = new List<PurchaseReturnDetail>();

            decimal totalTransaction = 0;
            foreach (var itemReturn in listReturn)
            {
                PurchasingDetail purchasingDetail = _purchasingDetailRepository.GetMany(x => x.SparepartId == itemReturn.SparepartId && x.PurchasingId == purchasingID).FirstOrDefault();
                List<SparepartDetail> listSpDetail = _sparepartDetailRepository.GetMany(x => x.PurchasingDetailId == purchasingDetail.Id && x.Status == (int)DbConstant.SparepartDetailDataStatus.Active).OrderByDescending(x => x.CreateDate).Take(itemReturn.ReturQty).ToList();

                foreach (var spDetail in listSpDetail)
                {
                    listReturnDetail.Add(new PurchaseReturnDetail
                    {
                        CreateDate = serverTime,
                        CreateUserId = userID,
                        ModifyDate = serverTime,
                        ModifyUserId = userID,
                        PurchaseReturnId = purchaseReturn.Id,
                        PurchasingDetailId = purchasingDetail.Id,
                        SparepartDetailId = spDetail.Id,
                        Status = (int)DbConstant.DefaultDataStatus.Active
                    });
                    totalTransaction += spDetail.PurchasingDetail.Price;

                    spDetail.ModifyDate = serverTime;
                    spDetail.ModifyUserId = userID;
                    spDetail.Status = (int)DbConstant.SparepartDetailDataStatus.Deleted;

                    _sparepartDetailRepository.AttachNavigation(spDetail.CreateUser);
                    _sparepartDetailRepository.AttachNavigation(spDetail.ModifyUser);
                    _sparepartDetailRepository.AttachNavigation(spDetail.PurchasingDetail);
                    _sparepartDetailRepository.AttachNavigation(spDetail.Sparepart);
                    _sparepartDetailRepository.AttachNavigation(spDetail.SparepartManualTransaction);
                    _sparepartDetailRepository.Update(spDetail);
                }

                Sparepart sparepart = _sparepartRepository.GetById(itemReturn.SparepartId);
                sparepart.ModifyDate = serverTime;
                sparepart.ModifyUserId = userID;
                sparepart.StockQty -= itemReturn.ReturQty;

                _sparepartRepository.AttachNavigation(sparepart.CreateUser);
                _sparepartRepository.AttachNavigation(sparepart.ModifyUser);
                _sparepartRepository.AttachNavigation(sparepart.CategoryReference);
                _sparepartRepository.AttachNavigation(sparepart.UnitReference);
                _sparepartRepository.Update(sparepart);

                SparepartStockCard stockCard = new SparepartStockCard();
                stockCard.CreateUserId = userID;
                stockCard.CreateDate = serverTime;
                stockCard.PrimaryKeyValue = purchaseReturn.Id;
                stockCard.ReferenceTableId = transactionReferenceTable.Id;
                stockCard.SparepartId = sparepart.Id;
                stockCard.Description = "Retur Pembelian";
                stockCard.QtyOut = itemReturn.ReturQty;
                SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(sparepart.Id);
                double lastStock = 0;
                if (lastStockCard != null)
                {
                    lastStock = lastStockCard.QtyLast;
                }
                stockCard.QtyFirst = lastStock;
                stockCard.QtyLast = lastStock - stockCard.QtyOut;
                _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                _sparepartStokCardRepository.Add(stockCard);

            }

            Purchasing purchasing = _purchasingRepository.GetById(purchaseReturn.PurchasingId);
            if(purchasing.TotalPrice != purchasing.TotalHasPaid && (purchasing.TotalPrice - purchasing.TotalHasPaid) >= totalTransaction)
            {
                purchasing.TotalHasPaid += totalTransaction;
            }

            if (purchasing.TotalPrice == purchasing.TotalHasPaid)
            {
                purchasing.PaymentStatus = (int)DbConstant.PaymentStatus.Settled;
            }
            else
            {
                purchasing.PaymentStatus = (int)DbConstant.PaymentStatus.NotSettled;
            }

            _purchasingRepository.AttachNavigation(purchasing.CreateUser);
            _purchasingRepository.AttachNavigation(purchasing.ModifyUser);
            _purchasingRepository.AttachNavigation(purchasing.PaymentMethod);
            _purchasingRepository.AttachNavigation(purchasing.Supplier);

            _unitOfWork.SaveChanges();

            foreach (var itemReturnDetail in listReturnDetail)
            {
                _purchaseReturnDetailRepository.AttachNavigation(itemReturnDetail.CreateUser);
                _purchaseReturnRepository.AttachNavigation(itemReturnDetail.ModifyUser);
                _purchaseReturnRepository.AttachNavigation(itemReturnDetail.PurchaseReturn);
                _purchaseReturnRepository.AttachNavigation(itemReturnDetail.PurchasingDetail);
                _purchaseReturnRepository.AttachNavigation(itemReturnDetail.SparepartDetail);
                _purchaseReturnDetailRepository.Add(itemReturnDetail);
            }

            _unitOfWork.SaveChanges();

            Transaction transaction = new Transaction();
            transaction.CreateDate = serverTime;
            transaction.CreateUserId = userID;
            transaction.ModifyDate = serverTime;
            transaction.ModifyUserId = userID;
            transaction.PrimaryKeyValue = purchaseReturn.Id;
            transaction.ReferenceTableId = transactionReferenceTable.Id;
            transaction.TotalPayment = totalTransaction.AsDouble();
            transaction.TotalTransaction = totalTransaction.AsDouble();
            transaction.Status = (int)DbConstant.DefaultDataStatus.Active;
            transaction.Description = "Retur Pembelian";
            transaction.TransactionDate = serverTime;

            _transactionRepository.AttachNavigation(transaction.CreateUser);
            _transactionRepository.AttachNavigation(transaction.ModifyUser);
            _transactionRepository.AttachNavigation(transaction.PaymentMethod);
            _transactionRepository.AttachNavigation(transaction.ReferenceTable);
            transaction = _transactionRepository.Add(transaction);

            _unitOfWork.SaveChanges();

            TransactionDetail transDebit = new TransactionDetail();
            transDebit.Debit = totalTransaction;
            transDebit.ParentId = transaction.Id;
            transDebit.JournalId = _journalMasterRepository.GetMany(j => j.Code == "2.01.01.01").FirstOrDefault().Id;

            _transactionDetailRepository.AttachNavigation(transDebit.Journal);
            _transactionDetailRepository.AttachNavigation(transDebit.Parent);
            _transactionDetailRepository.Add(transDebit);

            TransactionDetail transCredit = new TransactionDetail();
            transCredit.Credit = totalTransaction;
            transCredit.ParentId = transaction.Id;
            transCredit.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.04.01").FirstOrDefault().Id;

            _transactionDetailRepository.AttachNavigation(transCredit.Journal);
            _transactionDetailRepository.AttachNavigation(transCredit.Parent);
            _transactionDetailRepository.Add(transCredit);

            _unitOfWork.SaveChanges();
        }
        public void InsertSparepartManualTransaction(SparepartManualTransactionViewModel sparepartManualTransaction, decimal totalPrice, int userId)
        {
            using (var trans = _unitOfWork.BeginTransaction())
            {
                try
                {
                    DateTime serverTime = DateTime.Now;
                    sparepartManualTransaction.CreateDate = serverTime;
                    sparepartManualTransaction.CreateUserId = userId;
                    sparepartManualTransaction.ModifyDate = serverTime;
                    sparepartManualTransaction.ModifyUserId = userId;
                    sparepartManualTransaction.TransactionDate = serverTime;
                    Reference updateType = _referenceRepository.GetById(sparepartManualTransaction.UpdateTypeId);
                    Sparepart sparepartUpdated = _sparepartRepository.GetById(sparepartManualTransaction.SparepartId);
                    if (updateType != null && sparepartUpdated != null)
                    {
                        SparepartManualTransaction entity = new SparepartManualTransaction();
                        Map(sparepartManualTransaction, entity);

                        _sparepartManualTransactionRepository.AttachNavigation(entity.CreateUser);
                        _sparepartManualTransactionRepository.AttachNavigation(entity.ModifyUser);
                        _sparepartManualTransactionRepository.AttachNavigation(entity.Sparepart);
                        _sparepartManualTransactionRepository.AttachNavigation(entity.UpdateType);
                        SparepartManualTransaction manualTransaction = _sparepartManualTransactionRepository.Add(entity);
                        _unitOfWork.SaveChanges();

                        //Reference referenceTransaction = _referenceRepository.GetMany(x=>x.Code == DbConstant.REF_TRANSTBL_SPAREPARTMANUAL).FirstOrDefault();
                        //Transaction transaction = new Transaction();
                        //transaction.CreateDate = serverTime;
                        //transaction.CreateUserId = userId;
                        //transaction.ModifyDate = serverTime;
                        //transaction.ModifyUserId = userId;
                        //transaction.Description = "Transaksi sparepart manual";
                        //transaction.ReferenceTableId = referenceTransaction.Id;
                        //transaction.PrimaryKeyValue = 0;
                        //transaction.TotalPayment = totalPrice.AsDouble();
                        //transaction.TotalTransaction = totalPrice.AsDouble();
                        //transaction.TransactionDate = serverTime;
                        //transaction.Status = (int)DbConstant.DefaultDataStatus.Active;
                        //transaction =_transactionRepository.Add(transaction);

                        Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_SPAREPARTMANUAL).FirstOrDefault();
                        SparepartStockCard stockCard = new SparepartStockCard();
                        stockCard.CreateUserId = userId;
                        stockCard.CreateDate = serverTime;
                        stockCard.PrimaryKeyValue = manualTransaction.Id;
                        stockCard.ReferenceTableId = transactionReferenceTable.Id;
                        stockCard.SparepartId = manualTransaction.SparepartId;

                        if (updateType.Code == DbConstant.REF_SPAREPART_TRANSACTION_MANUAL_TYPE_PLUS)
                        {
                            stockCard.Description = "Penambahan stok awal";
                            //TransactionDetail transDebit = new TransactionDetail();
                            //transDebit.Debit = totalPrice;
                            //transDebit.JournalId = _journalMasterRepository.GetMany(x => x.Code == "1.01.04.01").FirstOrDefault().Id;
                            //transDebit.Parent = transaction;
                            //_transactionDetailRepository.Add(transDebit);

                            //TransactionDetail transCredit = new TransactionDetail();
                            //transCredit.Credit = totalPrice;
                            //transCredit.JournalId = _journalMasterRepository.GetMany(x => x.Code == "9.9").FirstOrDefault().Id;
                            //transCredit.Parent = transaction;
                            //_transactionDetailRepository.Add(transCredit);

                            sparepartUpdated.StockQty += sparepartManualTransaction.Qty;
                            stockCard.QtyIn = sparepartManualTransaction.Qty;

                            SparepartDetail lastSPDetail = _sparepartDetailRepository.
                            GetMany(c => c.SparepartId == sparepartManualTransaction.SparepartId).OrderByDescending(c => c.Id)
                            .FirstOrDefault();
                            string lastSPID = string.Empty;
                            if (lastSPDetail != null) lastSPID = lastSPDetail.Code;
                            for (int i = 1; i <= sparepartManualTransaction.Qty; i++)
                            {
                                SparepartDetail spDetail = new SparepartDetail();
                                if (string.IsNullOrEmpty(lastSPID))
                                {
                                    lastSPID = sparepartUpdated.Code + "0000000001";
                                }
                                else
                                {
                                    lastSPID = sparepartUpdated.Code + (Convert.ToInt32(lastSPID.Substring(lastSPID.Length - 10)) + 1)
                                        .ToString("D10");
                                }
                                spDetail.SparepartManualTransaction = manualTransaction;
                                spDetail.SparepartId = sparepartUpdated.Id;
                                spDetail.Code = lastSPID;
                                spDetail.CreateDate = serverTime;
                                spDetail.CreateUserId = userId;
                                spDetail.ModifyUserId = userId;
                                spDetail.ModifyDate = serverTime;
                                spDetail.Status = (int)DbConstant.SparepartDetailDataStatus.Active;

                                _sparepartDetailRepository.AttachNavigation(spDetail.CreateUser);
                                _sparepartDetailRepository.AttachNavigation(spDetail.ModifyUser);
                                _sparepartDetailRepository.AttachNavigation(spDetail.PurchasingDetail);
                                _sparepartDetailRepository.AttachNavigation(spDetail.Sparepart);
                                _sparepartDetailRepository.AttachNavigation(spDetail.SparepartManualTransaction);
                                SparepartDetail insertedSpDetail = _sparepartDetailRepository.Add(spDetail);

                                if (!string.IsNullOrEmpty(sparepartManualTransaction.SerialNumber))
                                {
                                    SpecialSparepart specialSparepart = _specialSparepartRepository.GetMany(w => w.SparepartId == sparepartUpdated.Id && w.Status == (int)DbConstant.DefaultDataStatus.Active ).FirstOrDefault();

                                    if (specialSparepart != null)
                                    {
                                        SpecialSparepartDetail wDetail = new SpecialSparepartDetail();
                                        wDetail.SparepartDetail = insertedSpDetail;
                                        wDetail.SpecialSparepartId = specialSparepart.Id;
                                        wDetail.SerialNumber = sparepartManualTransaction.SerialNumber;
                                        wDetail.CreateDate = serverTime;
                                        wDetail.CreateUserId = userId;
                                        wDetail.ModifyUserId = userId;
                                        wDetail.ModifyDate = serverTime;
                                        wDetail.Status = (int)DbConstant.WheelDetailStatus.Ready;

                                        _specialSparepartDetailRepository.AttachNavigation(spDetail.CreateUser);
                                        _specialSparepartDetailRepository.AttachNavigation(spDetail.ModifyUser);
                                        _specialSparepartDetailRepository.AttachNavigation(spDetail.PurchasingDetail);
                                        _specialSparepartDetailRepository.AttachNavigation(spDetail.Sparepart);
                                        _specialSparepartDetailRepository.AttachNavigation(spDetail.SparepartManualTransaction);
                                        _specialSparepartDetailRepository.Add(wDetail);

                                        _unitOfWork.SaveChanges();
                                    }
                                }

                            }
                        }
                        else if (updateType.Code == DbConstant.REF_SPAREPART_TRANSACTION_MANUAL_TYPE_MINUS)
                        {
                            stockCard.Description = "Pengurangan stok awal";
                            //TransactionDetail transCredit = new TransactionDetail();
                            //transCredit.Credit = totalPrice;
                            //transCredit.JournalId = _journalMasterRepository.GetMany(x => x.Code == "1.01.04.01").FirstOrDefault().Id;
                            //transCredit.Parent = transaction;
                            //_transactionDetailRepository.Add(transCredit);

                            //TransactionDetail transDebit = new TransactionDetail();
                            //transDebit.Debit = totalPrice;
                            //transDebit.JournalId = _journalMasterRepository.GetMany(x => x.Code == "9.9").FirstOrDefault().Id;
                            //transDebit.Parent = transaction;
                            //_transactionDetailRepository.Add(transDebit);

                            sparepartUpdated.StockQty -= sparepartManualTransaction.Qty;
                            stockCard.QtyOut = sparepartManualTransaction.Qty;

                            List<SparepartDetail> spDetails = _sparepartDetailRepository.
                            GetMany(c => c.SparepartId == sparepartManualTransaction.SparepartId).OrderByDescending(c => c.Id)
                            .Take(sparepartManualTransaction.Qty).ToList();
                            foreach (var spDetail in spDetails)
                            {
                                spDetail.ModifyUserId = userId;
                                spDetail.ModifyDate = serverTime;
                                spDetail.Status = (int)DbConstant.SparepartDetailDataStatus.Deleted;
                                _sparepartDetailRepository.Update(spDetail);
                            }
                        }

                        SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(manualTransaction.SparepartId);
                        double lastStock = 0;
                        if (lastStockCard != null)
                        {
                            lastStock = lastStockCard.QtyLast;
                        }
                        stockCard.QtyFirst = lastStock;
                        stockCard.QtyLast = lastStock + (stockCard.QtyIn - stockCard.QtyOut);
                        _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                        _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                        _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                        _sparepartStokCardRepository.Add(stockCard);

                        _sparepartRepository.AttachNavigation(sparepartUpdated.CreateUser);
                        _sparepartRepository.AttachNavigation(sparepartUpdated.ModifyUser);
                        _sparepartRepository.AttachNavigation(sparepartUpdated.CategoryReference);
                        _sparepartRepository.AttachNavigation(sparepartUpdated.UnitReference);
                        _sparepartRepository.Update(sparepartUpdated);
                        _unitOfWork.SaveChanges();

                        //transaction.PrimaryKeyValue = manualTransaction.Id;
                        //_transactionRepository.Update(transaction);
                        //_unitOfWork.SaveChanges();
                        trans.Commit();
                    }
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }
        public void UpdateSparepartManualTransaction(SparepartManualTransactionViewModel sparepartManualTransaction, int userId)
        {
            DateTime serverTime = DateTime.Now;
            sparepartManualTransaction.ModifyDate = serverTime;
            sparepartManualTransaction.ModifyUserId = userId;
            Reference updateTypeNew = _referenceRepository.GetById(sparepartManualTransaction.UpdateTypeId);
            SparepartManualTransaction manualTransactionOld = _sparepartManualTransactionRepository.GetById(sparepartManualTransaction.Id);
            Sparepart sparepartUpdated = _sparepartRepository.GetById(sparepartManualTransaction.SparepartId);
            if (manualTransactionOld != null && updateTypeNew != null && sparepartUpdated != null)
            {
                Reference updateTypeOld = _referenceRepository.GetById(manualTransactionOld.UpdateTypeId);

                Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_SPAREPARTMANUAL).FirstOrDefault();
                SparepartStockCard stockCard = new SparepartStockCard();
                stockCard.CreateUserId = userId;
                stockCard.CreateDate = serverTime;
                stockCard.ReferenceTableId = transactionReferenceTable.Id;
                stockCard.PrimaryKeyValue = manualTransactionOld.Id;
                stockCard.SparepartId = sparepartManualTransaction.SparepartId;

                SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(sparepartManualTransaction.SparepartId);
                double lastStock = 0;
                if (lastStockCard != null)
                {
                    lastStock = lastStockCard.QtyLast;
                }

                stockCard.QtyFirst = lastStock;

                if (updateTypeOld.Code == (DbConstant.REF_SPAREPART_TRANSACTION_MANUAL_TYPE_PLUS))
                {
                    stockCard.Description = "Revisi pembatalan penambahan stok awal";
                    stockCard.QtyOut = manualTransactionOld.Qty;
                    sparepartUpdated.StockQty -= manualTransactionOld.Qty;
                }
                else if (updateTypeOld.Code == DbConstant.REF_SPAREPART_TRANSACTION_MANUAL_TYPE_MINUS)
                {
                    stockCard.Description = "Revisi pembatalan pengurangan stok awal";
                    stockCard.QtyIn = manualTransactionOld.Qty;
                    sparepartUpdated.StockQty += manualTransactionOld.Qty;
                }

                stockCard.QtyLast = stockCard.QtyFirst + (stockCard.QtyIn - stockCard.QtyOut);

                _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                _sparepartStokCardRepository.Add(stockCard);
                _unitOfWork.SaveChanges();

                SparepartStockCard revStockCard = new SparepartStockCard();
                revStockCard.CreateUserId = userId;
                revStockCard.CreateDate = serverTime;
                revStockCard.ReferenceTableId = transactionReferenceTable.Id;
                revStockCard.PrimaryKeyValue = manualTransactionOld.Id;
                revStockCard.SparepartId = sparepartManualTransaction.SparepartId;

                lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(sparepartManualTransaction.SparepartId);
                lastStock = 0;
                if (lastStockCard != null)
                {
                    lastStock = lastStockCard.QtyLast;
                }

                revStockCard.QtyFirst = lastStock;

                if (updateTypeNew.Code == DbConstant.REF_SPAREPART_TRANSACTION_MANUAL_TYPE_PLUS)
                {
                    revStockCard.Description = "Revisi penambahan stok awal";
                    revStockCard.QtyIn = sparepartManualTransaction.Qty;
                    sparepartUpdated.StockQty += sparepartManualTransaction.Qty;
                }
                else if (updateTypeNew.Code == DbConstant.REF_SPAREPART_TRANSACTION_MANUAL_TYPE_MINUS)
                {
                    revStockCard.Description = "Revisi pengurangan stok awal";
                    revStockCard.QtyOut = sparepartManualTransaction.Qty;
                    sparepartUpdated.StockQty -= sparepartManualTransaction.Qty;
                }

                revStockCard.QtyLast = revStockCard.QtyFirst + (revStockCard.QtyIn - revStockCard.QtyOut);

                _sparepartStokCardRepository.AttachNavigation(revStockCard.CreateUser);
                _sparepartStokCardRepository.AttachNavigation(revStockCard.Sparepart);
                _sparepartStokCardRepository.AttachNavigation(revStockCard.ReferenceTable);
                _sparepartStokCardRepository.Add(revStockCard);

                SparepartManualTransaction entity = new SparepartManualTransaction();
                Map(sparepartManualTransaction, entity);
                _sparepartManualTransactionRepository.Update(entity);
                _sparepartRepository.Update(sparepartUpdated);
                _unitOfWork.SaveChanges();
            }
        }
        public void DeleteSalesReturn(int salesReturnID, int userID)
        {
            using (var trans = _unitOfWork.BeginTransaction())
            {
                try
                {
                    DateTime serverTime = DateTime.Now;

                    Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_SALESRETURN).FirstOrDefault();
                    SalesReturn salesReturn = _salesReturnRepository.GetById(salesReturnID);
                    salesReturn.Status = (int)DbConstant.DefaultDataStatus.Deleted;
                    salesReturn.ModifyDate = serverTime;
                    salesReturn.ModifyUserId = userID;

                    _salesReturnRepository.AttachNavigation(salesReturn.CreateUser);
                    _salesReturnRepository.AttachNavigation(salesReturn.ModifyUser);
                    _salesReturnRepository.AttachNavigation(salesReturn.Invoice);
                    _salesReturnRepository.Update(salesReturn);
                    _unitOfWork.SaveChanges();

                    List<SalesReturnDetail> listDetail = _salesReturnDetailRepository.GetMany(x => x.SalesReturnId == salesReturnID).ToList();
                    foreach (var itemDetail in listDetail)
                    {
                        itemDetail.Status = (int)DbConstant.DefaultDataStatus.Deleted;
                        itemDetail.ModifyDate = serverTime;
                        itemDetail.ModifyUserId = userID;

                        _salesReturnDetailRepository.AttachNavigation(itemDetail.CreateUser);
                        _salesReturnDetailRepository.AttachNavigation(itemDetail.ModifyUser);
                        _salesReturnDetailRepository.AttachNavigation(itemDetail.SalesReturn);
                        _salesReturnDetailRepository.AttachNavigation(itemDetail.InvoiceDetail);
                        _salesReturnDetailRepository.Update(itemDetail);

                        SparepartDetail spDetail = _sparepartDetailRepository.GetById(itemDetail.InvoiceDetail.SPKDetailSparepartDetail.SparepartDetailId);
                        spDetail.Status = (int)DbConstant.SparepartDetailDataStatus.OutPurchase;

                        _sparepartDetailRepository.AttachNavigation(spDetail.CreateUser);
                        _sparepartDetailRepository.AttachNavigation(spDetail.ModifyUser);
                        _sparepartDetailRepository.AttachNavigation(spDetail.PurchasingDetail);
                        _sparepartDetailRepository.AttachNavigation(spDetail.Sparepart);
                        _sparepartDetailRepository.AttachNavigation(spDetail.SparepartManualTransaction);
                        _sparepartDetailRepository.Update(spDetail);

                        Sparepart sparepart = _sparepartRepository.GetById(spDetail.SparepartId);
                        sparepart.StockQty -= 1;

                        _sparepartRepository.AttachNavigation(sparepart.CreateUser);
                        _sparepartRepository.AttachNavigation(sparepart.ModifyUser);
                        _sparepartRepository.AttachNavigation(sparepart.CategoryReference);
                        _sparepartRepository.AttachNavigation(sparepart.UnitReference);
                        _sparepartRepository.Update(sparepart);

                        SparepartStockCard stockCard = new SparepartStockCard();
                        stockCard.CreateUserId = userID;
                        stockCard.CreateDate = serverTime;
                        stockCard.PrimaryKeyValue = salesReturn.Id;
                        stockCard.ReferenceTableId = transactionReferenceTable.Id;
                        stockCard.SparepartId = sparepart.Id;
                        stockCard.Description = "Pembatalan Retur Penjualan";
                        stockCard.QtyOut = 1;
                        SparepartStockCard lastStockCard = _sparepartStokCardRepository.RetrieveLastCard(sparepart.Id);
                        double lastStock = 0;
                        if (lastStockCard != null)
                        {
                            lastStock = lastStockCard.QtyLast;
                        }
                        stockCard.QtyFirst = lastStock;
                        stockCard.QtyLast = lastStock - stockCard.QtyOut;
                        _sparepartStokCardRepository.AttachNavigation(stockCard.CreateUser);
                        _sparepartStokCardRepository.AttachNavigation(stockCard.Sparepart);
                        _sparepartStokCardRepository.AttachNavigation(stockCard.ReferenceTable);
                        _sparepartStokCardRepository.Add(stockCard);
                    }

                    _unitOfWork.SaveChanges();

                    Transaction transaction = _transactionRepository.GetMany(x => x.PrimaryKeyValue == salesReturnID && x.ReferenceTableId == transactionReferenceTable.Id).FirstOrDefault();
                    transaction.Status = (int)DbConstant.DefaultDataStatus.Deleted;
                    transaction.ModifyDate = serverTime;
                    transaction.ModifyUserId = userID;

                    _transactionRepository.AttachNavigation(transaction.CreateUser);
                    _transactionRepository.AttachNavigation(transaction.ModifyUser);
                    _transactionRepository.AttachNavigation(transaction.PaymentMethod);
                    _transactionRepository.AttachNavigation(transaction.ReferenceTable);
                    _transactionRepository.Update(transaction);

                    _unitOfWork.SaveChanges();
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }