public ActionResult History()
        {
            if (Session["userId"] == null || Session["userId"].ToString() == "")
            {
                return(RedirectToAction("Index", "Home"));
            }
            ModelContext       context         = new ModelContext();
            List <Transaction> transactionList = context.Transactions.ToList();

            List <TransactionDetail> list = new List <TransactionDetail>();

            foreach (Transaction t in transactionList)
            {
                if (t.EmailId == Session["userId"].ToString())
                {
                    TransactionDetail temp = new TransactionDetail();
                    temp.TransactionId = t.TransactionId;
                    temp.ServiceName   = context.Services.Find(t.ServiceId).Name;
                    temp.StartDate     = context.Services.Find(t.ServiceId).StartDate;
                    temp.Amount        = context.Services.Find(t.ServiceId).Amount;

                    list.Add(temp);
                }
            }
            return(View(list));
        }
        public IHttpActionResult PutTransactionDetail(int id, TransactionDetail transactionDetail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != transactionDetail.TransactionID)
            {
                return(BadRequest());
            }

            db.Entry(transactionDetail).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TransactionDetailExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public void Delete(int id)
        {
            TransactionDetail detail = context.TransactionDetails.SingleOrDefault(x => x.Id == id);

            context.TransactionDetails.Remove(detail);
            context.SaveChanges();
        }
예제 #4
0
        /// <summary>
        /// Faz uma recorrência.
        /// </summary>
        public ResponseBase Recurring(String merchantId, String merchantKey, String referenceNum, decimal chargeTotal
                                      , String creditCardNumber, String expMonth, String expYear, String cvvInd, String cvvNumber, String processorId
                                      , String numberOfInstallments, String chargeInterest, String ipAddress, String action
                                      , String startDate, String frequency, String period, String installments, String failureThreshold
                                      , String currencyCode)
        {
            FillRecurringBase(merchantId, merchantKey, referenceNum, chargeTotal, processorId, numberOfInstallments
                              , chargeInterest, ipAddress, action, startDate, frequency, period, installments
                              , failureThreshold, currencyCode);
            //ATENCAO: installments é o campo a ser usado (numberOfInstallments é referente ao Parcelamento)

            TransactionDetail detail = this.request.Order.RecurringPayment.TransactionDetail;

            PayType payType = detail.PayType;

            CreditCard creditCard = new CreditCard();

            payType.CreditCard = creditCard;

            creditCard.CvvInd    = cvvInd;
            creditCard.CvvNumber = cvvNumber;
            creditCard.ExpMonth  = expMonth;
            creditCard.ExpYear   = expYear;
            creditCard.Number    = creditCardNumber;

            return(new Utils().SendRequest <TransactionRequest>(this.request, this.Environment));
        }
예제 #5
0
        public bool SaveDetail(TransactionViewModel trxData)
        {
            try
            {
                TransactionItem getTransaction = new TransactionItem();
                getTransaction.ID               = trxData.ID;
                getTransaction.NamaKaryawan     = trxData.NamaKaryawan;
                getTransaction.NoFaktur         = trxData.NoFaktur;
                getTransaction.sisaHarga        = trxData.sisaHarga;
                getTransaction.totalHarga       = trxData.totalHarga;
                getTransaction.TanggalMasukData = trxData.TanggalMasukData;
                using (DataContext getData = new DataContext())
                {
                    getData.transaction.Add(getTransaction);
                }
                TransactionDetail trxDetails = new TransactionDetail();
                foreach (var item in trxData.trxDetail)
                {
                    trxDetails.NoFaktur     = trxData.NoFaktur;
                    trxDetails.KodeBarang   = item.kodeBarang;
                    trxDetails.JumlahBarang = item.jumlahBarang;

                    using (DataContext inputData = new DataContext())
                    {
                        inputData.transactionDetail.Add(trxDetails);
                        inputData.SaveChanges();
                    }
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #6
0
        bool IFileSet.Write(ITransaction transaction, PageUpdate update)
        {
            if (transaction == null)
            {
                ulong filePageNumber;
                int   fileIndex;
                GetPageLocation(update.PageNumber, out filePageNumber, out fileIndex);

                return(_dataFiles[fileIndex].Write(filePageNumber, update.Data, update.Offset));
            }

            TransactionDetail transactionDetail;

            lock (_transactions)
            {
                if (!_transactions.TryGetValue(transaction, out transactionDetail))
                {
                    transactionDetail = new TransactionDetail
                    {
                        PendingUpdates = new List <PageUpdate>()
                    };
                    _transactions.Add(transaction, transactionDetail);
                }
            }

            lock (transactionDetail)
                transactionDetail.PendingUpdates.Add(update);

            return(true);
        }
예제 #7
0
        public async Task <bool> PostTransaction(TransactionDetail transaction)
        {
            _unitOfWork.Repository <TransactionDetail>().Add(transaction);

            var vendorIds = new List <int>
            {
                transaction.PaidPartyId,
                transaction.PaidToId
            };

            var vendors = await _unitOfWork.Repository <Vendor>().FindAllBySpecAsync(new VendorSpecification(vendorIds));

            foreach (var vendor in vendors)
            {
                if (vendor.Id == transaction.PaidPartyId)
                {
                    vendor.AmountInHand = transaction.IsExpense
                       ? vendor.AmountInHand - transaction.Amount
                       : vendor.AmountInHand + transaction.Amount;
                }
                if (vendor.Id == transaction.PaidToId)
                {
                    vendor.AmountInHand = transaction.IsExpense
                       ? vendor.AmountInHand + transaction.Amount
                       : vendor.AmountInHand - transaction.Amount;
                }
                vendor.ModfiedOn = DateTime.Now;
            }

            return(await _unitOfWork.Complete() > 0);
        }
예제 #8
0
        public static bool Checkout(int userId)
        {
            List <Cart> carts = GetThisUserCart(userId);

            if (carts.Count == 0)
            {
                return(false);
            }
            else
            {
                TransactionHeader transactionHeader = TransactionHeaderFactory.Create(userId);

                if (TransactionHeaderRepository.InsertTransactionHeader(transactionHeader))
                {
                    int headerId = transactionHeader.Id;

                    for (int i = 0; i < carts.Count(); i++)
                    {
                        TransactionDetail transactionDetail = TransactionDetailFactory.Create(headerId, carts[i].ProductId, carts[i].Quantity);
                        TransactionDetailRepository.InsertTransactionDetail(transactionDetail);
                    }

                    for (int i = 0; i < carts.Count(); i++)
                    {
                        CartRepository.RemoveCart(carts[i]);
                    }

                    return(true);
                }

                return(false);
            }
        }
예제 #9
0
        public ActionResult AddDetail(string TransactionID, string Quantity, string FeeName,
                                      string FeeAmount, string CntrSize, string LocationID)
        {
            int               tid  = Int32.Parse(TransactionID);
            string            unit = Uri.UnescapeDataString(CntrSize);
            TransactionDetail td   = new TransactionDetail();
            Transaction       t    = db.Transactions.Where(x => x.ID == tid).FirstOrDefault();

            td.TransactionID = Int32.Parse(TransactionID);
            td.FeeName       = FeeName;
            td.FeeAmount     = Int32.Parse(FeeAmount);
            td.Quantity      = Int32.Parse(Quantity);
            td.Total         = td.FeeAmount * td.Quantity;
            t.Total         += td.Total;
            td.CntrSize      = unit;
            db.TransactionDetails.Add(td);
            db.SaveChanges();
            if (FeeName.Contains("VanChuyen"))
            {
                for (int i = 0; i < Int32.Parse(Quantity); i++)
                {
                    TransportOrder to = new TransportOrder();
                    to.TransactionID = td.ID;
                    to.LocationID    = Int32.Parse(LocationID);
                    to.CntrSize      = unit;
                    db.TransportOrders.Add(to);
                    db.SaveChanges();
                }
            }
            return(Json(new { success = true, message = "Updated Successfully" }, JsonRequestBehavior.AllowGet));
        }
예제 #10
0
        public ActionResult GetTransactionById(int id)
        {
            TransactionDetail model = null;

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://localhost:44320/api/");
                string token = DeserializeToken();
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                var responseTask = client.GetAsync("transaction/" + id.ToString());
                responseTask.Wait();

                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    var readTask = result.Content.ReadAsAsync <TransactionDetail>();
                    readTask.Wait();

                    model = readTask.Result;
                }
                else
                {
                    ModelState.AddModelError(string.Empty, result.Content.ReadAsStringAsync().Result);
                }
            }
            return(View(model));
        }
예제 #11
0
        public async Task <ActionResult <TransactionDetail> > PostTransactionDetail(TransactionDetail transactionDetail)
        {
            _context.TransactionDetails.Add(transactionDetail);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetTransactionDetail", new { id = transactionDetail.TdetailsNo }, transactionDetail));
        }
예제 #12
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Quantity,QurrentPrice,SubTotal")] TransactionDetail transactionDetail)
        {
            if (id != transactionDetail.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(transactionDetail);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TransactionDetailExists(transactionDetail.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(transactionDetail));
        }
예제 #13
0
 public ProcessShipmentRequest()
 {
     TransactionDetail = new TransactionDetail {
         CustomerTransactionId = "***Ship Request***"
     };
     Version = new VersionId();
 }
예제 #14
0
 public void Create()
 {
     var curvatures = new[] { WingCurvatureTest.Create() };
     TransactionDetail transaction = TransactionDetailTest.Create();
     DividendList      divList     = DividendListTest.CreateDividendList();
     Stock             stock       = CreateStock(CStockId, CName, divList, curvatures, transaction);
 }
예제 #15
0
        public JsonResult GetById(string transactionid)
        {
            TransactionDetail detail = TransactionEngine.GetDetail(transactionid);

            Logger.LogDummyData();
            return(Json(detail));
        }
        /// <summary>
        /// Fill method for populating an entire collection of TransactionDetails
        /// </summary>
        public virtual void Fill(TransactionDetails transactionDetails)
        {
            // create the connection to use
            SqlConnection cnn = new SqlConnection(TransactionDetail.GetConnectionString());


            try
            {
                using (cnn)
                {
                    // open the connection
                    cnn.Open();


                    // create an instance of the reader to fill.
                    SqlDataReader datareader = SqlHelper.ExecuteReader(cnn, "gsp_SelectTransactionDetails");


                    // Send the collection and data to the object factory
                    CreateObjectsFromData(transactionDetails, datareader);


                    // close the connection
                    cnn.Close();
                }


                // nullify the connection
                cnn = null;
            }
            catch (SqlException sqlex)
            {
                throw sqlex;
            }
        }
예제 #17
0
        public ActionResult CreateExternal(FormCollection Form)
        {
            Transaction       transaction = new Transaction();
            TransactionDetail account1    = new TransactionDetail();
            TransactionDetail account2    = new TransactionDetail();

            transaction.TransactionAmount      = Convert.ToDouble(Form["Amount"]);
            transaction.TransactionDate        = Convert.ToDateTime(Form["TransactionDate"]).Date;
            transaction.TransactionDescription = Form["Description"];
            transaction.CompanyId = (int)Session["CompanyId"];

            ServiceFactory.GetTransactionServices().Insert(transaction);

            if (Form["Account_1"] != "none")
            {
                account1.AccountId       = Convert.ToInt32(Form["Account_1"]);
                account1.Amount          = transaction.TransactionAmount;
                account1.TransactionId   = transaction.Id;
                account1.TransactionType = ServiceFactory.GetTransactionTypeServices().Get(Form["Account_1_TransactionType"]).Id;
                ServiceFactory.GetTransactionDetailServices().Insert(account1);
                ServiceFactory.GetAccountServices().CashIn(account1.AccountId, account1.Amount);
            }
            if (Form["Account_2"] != "none")
            {
                account2.AccountId       = Convert.ToInt32(Form["Account_2"]);
                account2.Amount          = transaction.TransactionAmount;
                account2.TransactionId   = transaction.Id;
                account2.TransactionType = ServiceFactory.GetTransactionTypeServices().Get(Form["Account_2_TransactionType"]).Id;
                ServiceFactory.GetTransactionDetailServices().Insert(account2);
                ServiceFactory.GetAccountServices().CashIn(account2.AccountId, account2.Amount);
            }

            return(RedirectToAction("Index"));
        }
예제 #18
0
 public async Task <IActionResult> AVSVerifyRelease([FromBody] RunTransactionModel model)
 {
     try
     {
         //CreditCardData card = new CreditCardData();
         //card.CardNumber = "4000100011112224";
         //card.CardExpiration = "0922";
         //card.CardCode = "123";
         //card.AvsStreet = "123 Main st.";
         //card.AvsZip = "90046";
         //model.transactionRequest.CreditCardData = card;
         //model.transactionRequest.CustReceipt = true;
         //model.transactionRequest.CustReceiptName = "Aaadam Smith";
         model.transactionRequest.Command    = "AuthOnly";
         model.transactionRequest.Software   = "WebApiApp";
         model.transactionRequest.CustomerID = "409";
         TransactionDetail details = new TransactionDetail();
         details.Amount = 0.5;
         //details.Description = "Example QuickSale";
         //details.Invoice = "1286";
         if (model.transactionRequest?.CreditCardData == null)
         {
             string msg = "payment details should not be empty";
             return(BadRequest(msg));
         }
         model.transactionRequest.Details = details;
         dynamic response = await new TransactionManager().AVSPaymentResponse(model);
         return(Ok(response));
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
        /// <summary>
        /// The object factory for a particular data collection instance.
        /// </summary>
        public virtual void CreateObjectsFromData(TransactionDetails transactiondetails, System.Data.DataSet data)
        {
            // Do nothing if we have nothing
            if (data == null || data.Tables.Count == 0 || data.Tables[0].Rows.Count == 0)
            {
                return;
            }


            // Create a local variable for the new instance.
            TransactionDetail newobj = null;

            // Create a local variable for the data row instance.
            System.Data.DataRow dr = null;


            // Iterate through the table rows
            for (int i = 0; i < data.Tables[0].Rows.Count; i++)
            {
                // Get a reference to the data row
                dr = data.Tables[0].Rows[i];
                // Create a new object instance
                newobj = System.Activator.CreateInstance(transactiondetails.ContainsType[0]) as TransactionDetail;
                // Let the instance set its own members
                newobj.SetMembers(ref dr);
                // Add the new object to the collection instance
                transactiondetails.Add(newobj);
            }
        }
        public void DeleteTransactionDetail(TransactionDetailViewModel detail)
        {
            TransactionDetail entity = _transactionDetailRepository.GetById(detail.Id);

            _transactionDetailRepository.Delete(entity);
            _unitOfWork.SaveChanges();
        }
예제 #21
0
        [Fact] // CodePlex 2606
        public void DetectChanges_sets_FKs_if_entity_added_to_two_navigations_on_both_ends()
        {
            var modelBuilder = new DbModelBuilder();

            modelBuilder.Entity <Transaction>();
            modelBuilder.Entity <TransactionDetail>();
            modelBuilder.Entity <Note>();

            using (var context = new DbContext("Context2606", modelBuilder.Build(ProviderRegistry.Sql2008_ProviderInfo).Compile()))
            {
                new DropCreateDatabaseIfModelChanges <DbContext>().InitializeDatabase(context);

                var note = new Note();
                context.Set <Note>().Add(note);
                context.Entry(note).State = EntityState.Unchanged;

                var transaction = new Transaction();
                context.Set <Transaction>().Add(transaction);

                var transactionDetail = new TransactionDetail();
                transactionDetail.Transaction = transaction;
                transactionDetail.Notes.Add(note);
                transaction.TransactionDetails.Add(transactionDetail);
                note.TransactionDetail = transactionDetail;

                Assert.Null(transactionDetail.TransactionId);
                Assert.Null(note.TransactionDetailId);

                context.ChangeTracker.DetectChanges();

                Assert.NotNull(transactionDetail.TransactionId);
                Assert.NotNull(note.TransactionDetailId);
                Assert.Equal(EntityState.Modified, context.Entry(note).State);
            }
        }
예제 #22
0
        private void SearchMember(object sender, EventArgs e)
        {
            List <Member> members = Member.GetList();

            // create list of search items
            List <SearchItem> searchItems =
                members.Select(
                    member =>
                    new SearchItem(member.MemberId, member.MemberName)
            {
                ItemCode = member.MemberCode
            }).
                ToList();

            var searchByCodeWindow = new SearchByCodeWindow(searchItems);

            searchByCodeWindow.ShowDialog();
            if (searchByCodeWindow.DialogResult != true)
            {
                return;
            }
            _member.Find(searchByCodeWindow.SelectedItem.ItemId);
            _transactionDetail.MemberCode = _member.MemberCode;
            _transactionDetail.MemberName = _member.MemberName;

            DataContext = new TransactionDetail();
            DataContext = _transactionDetail;
        }
예제 #23
0
 public bool SaveGuestUsers(GuestUserDetail guestUserDetail, TransactionDetail transactionDetail)
 {
     try
     {
         var countryData = _countryRepository.GetByAltId(guestUserDetail.PhoneCode);
         var newGuest    = _guestDetailRepository.Save(new FIL.Contracts.DataModels.GuestDetail
         {
             TransactionDetailId = transactionDetail.Id,
             Age                    = guestUserDetail.Age.ToString(),
             DocumentNumber         = guestUserDetail.IdentityNumber,
             Email                  = guestUserDetail.Email,
             FirstName              = guestUserDetail.FirstName,
             LastName               = guestUserDetail.LastName,
             CustomerDocumentTypeId = guestUserDetail.IdentityType == 0 ? 1 : guestUserDetail.IdentityType,
             PhoneNumber            = guestUserDetail.PhoneNumber,
             PhoneCode              = countryData == null ? "NA" : countryData.Phonecode.ToString(),
             GenderId               = guestUserDetail.Gender == 0 ? Gender.Male : (Gender)guestUserDetail.Gender,
             IsEnabled              = true,
             CreatedUtc             = DateTime.UtcNow,
             UpdatedUtc             = DateTime.UtcNow
         });
         return(true);
     }
     catch (Exception e)
     {
         _logger.Log(Logging.Enums.LogCategory.Error, e);
         return(false);
     }
 }
예제 #24
0
        public VoucherDataEntryWindow(IVoucher voucherView, TransactionHeader transactionHeader,
                                      TransactionDetail transactionDetail)
        {
            InitializeComponent();

            _member            = new Member();
            _account           = new Account();
            _transactionDetail = (TransactionDetail)transactionDetail.Clone();

            DataContext            = _transactionDetail;
            HeaderGrid.DataContext = transactionHeader;

            _voucherView       = voucherView;
            _transactionHeader = transactionHeader;

            // set proper button caption
            if (_transactionDetail.TransactionDetailId > 0)
            {
                UpdateButton.Content = "Update";
                FormTitle.Content    = Title = "Update Current Detail";
            }
            else
            {
                UpdateButton.Content = "Insert";
                FormTitle.Content    = Title = "Insert New Detail";
            }
        }
예제 #25
0
        public int SaveEditTransactionDetail(TransactionDetail objTD, SqlConnection con, SqlTransaction trans)
        {
            int ID = 0;

            try
            {
                SqlCommand com = new SqlCommand("spInsertUpdateTransDetail", con, trans);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.Add("@TransDID", SqlDbType.Int).Value          = objTD.TransactionDetailID;
                com.Parameters.Add("@TransMID", SqlDbType.Int).Value          = objTD.TransactionMasterID;
                com.Parameters.Add("@AccountID", SqlDbType.Int).Value         = objTD.TransactionAccountID;
                com.Parameters.Add("@CreditAmt", SqlDbType.Money).Value       = objTD.CreditAmount;
                com.Parameters.Add("@DebitAmt", SqlDbType.Money).Value        = objTD.DebitAmount;
                com.Parameters.Add("@Comments", SqlDbType.VarChar, 500).Value = objTD.Comments;

                com.ExecuteNonQuery();

                //if (objTM.AccountID == 0)
                //    ID = ConnectionHelper.GetID(con, "AccountID", "T_Account");
                //else
                //    ID = objTM.AccountID;
                //ID = Convert.ToInt32(com.Parameters["@TransDID"].Value);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(ID);
        }
예제 #26
0
        private void SearchAccount(object sender, EventArgs e)
        {
            List <Account> accounts = Account.GetList();

            // create list of search items
            List <SearchItem> searchItems =
                accounts.Select(
                    account =>
                    new SearchItem(account.AccountId, account.AccountTitle)
            {
                ItemCode = account.AccountCode
            }).ToList();

            var searchByCodeWindow = new SearchByCodeWindow(searchItems);

            searchByCodeWindow.ShowDialog();
            if (searchByCodeWindow.DialogResult != true)
            {
                return;
            }
            _account.Find(searchByCodeWindow.SelectedItem.ItemId);
            _transactionDetail.AccountCode  = _account.AccountCode;
            _transactionDetail.AccountTitle = _account.AccountTitle;

            DataContext = new TransactionDetail(); // to trigger a change in datacontext
            DataContext = _transactionDetail;
        }
예제 #27
0
 public ActionResult DeleteConfirmed(int id)
 {
     TransactionDetail transactiondetail = db.TransactionDetails.Find(id);
     db.TransactionDetails.Remove(transactiondetail);
     db.SaveChanges();
     return RedirectToAction("Index");
 }
        private void CreateWithdrawalTransaction(ItemRequest itemRequest)
        {
            var transaction = new Transaction()
            {
                Id              = new Guid(),
                GuildId         = itemRequest.GuildId,
                CharacterName   = itemRequest.CharacterName,
                TransactionDate = DateTime.Now,
                Type            = "Withdrawal",
                Money           = itemRequest.Gold
            };

            _classicGuildBankDbContext.Transactions.Add(transaction);

            foreach (var itemRequestDetail in itemRequest.Details)
            {
                var transactionDetail = new TransactionDetail()
                {
                    Id            = new Guid(),
                    ItemId        = itemRequestDetail.ItemId,
                    TransactionId = transaction.Id,
                    Quantity      = itemRequestDetail.Quantity
                };

                _classicGuildBankDbContext.TransactionDetails.Add(transactionDetail);
            }
        }
예제 #29
0
        public async Task <IActionResult> PutTransactionDetail(int id, TransactionDetail transactionDetail)
        {
            if (id != transactionDetail.TdetailsNo)
            {
                return(BadRequest());
            }

            _context.Entry(transactionDetail).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TransactionDetailExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
예제 #30
0
        public ActionResult Withdraw(TransactionDetail obj)
        {
            int AccountNumber          = Convert.ToInt32(obj.AccountNumber);
            var AccData2               = _context.Accounts.Where(x => x.AccountNumber == AccountNumber).FirstOrDefault();
            TransactionDetail AccData  = new TransactionDetail();
            PassBook          AccData3 = new PassBook();

            if (AccData2 != null)
            {
                AccData2.AccountNumber = obj.AccountNumber;
                AccData2.Balance       = AccData2.Balance - obj.Amount;
                // AccData.TimeofTransaction = DateTime.Now;
                _context.Entry(AccData2).State = EntityState.Modified;
                _context.SaveChanges();
            }

            AccData.AccountNumber     = AccData2.AccountNumber;
            AccData.Amount            = obj.Amount;
            AccData.TimeofTransaction = DateTime.Now;

            AccData3.AccountNumber     = AccData2.AccountNumber;
            AccData3.Amount            = obj.Amount;
            AccData3.TimeofTransaction = DateTime.Now;
            AccData3.Mode = "Withdraw";
            _context.TransactionDetails.Add(AccData);
            _context.SaveChanges();
            _context.PassBooks.Add(AccData3);
            _context.SaveChanges();

            TempData["Message"] = " Amount Withdrawl of Rs. " + Convert.ToString(AccData.Amount) + " was Successful ";

            return(RedirectToAction("../Home/Redirect"));
        }
        public void btnSave_Click(object sender, EventArgs e)
        {
            var a = new TransactionMain();
            var l = new List<TransactionDetail>();
            a.transaction_id = transaction_id;
            a.transaction_comment = txtComments.Text;
            a.transaction_date = txtTransactionDate.Text == "" ? DateTime.Now : Convert.ToDateTime(txtTransactionDate.Text);
            a.transaction_title = txtTitle.Text;
            a.account_id = account_id;
            a.amount = 0;
            a.is_active = chkIsActive.Checked ? "1" : "0";
            {//gather transaction details, so we'll have the amount on the main transaction record, we'll save the details afteward
                foreach (EditText et in amounts)
                {
                    var td = new TransactionDetail();
                    td.account_id = account_id;
                    td.fund_id = Convert.ToString(et.Tag);
                    td.comment = et.Text;
                    var s = Misc.ValSum(et.Text);
                    td.amount = a.is_active == "1" ? s : 0;
                    a.amount += s;
                    l.Add(td);
                }
            }
            if (a.transaction_id == "")
            {
                a.transaction_id = Guid.NewGuid().ToString();
                transaction_id = a.transaction_id;

                Db.AddTransaction(a);
            }
            else
            {
                Db.UpdateTransaction(a);
            }
            foreach (var li in l)
                li.transaction_id = transaction_id;
            Db.AddTransactionDetails(l);
            SetResult(Result.Ok);
            Finish();
        }
        public void InsertTransaction(TransactionViewModel parentTransaction,
            List<TransactionDetailViewModel> detailTransactionList, int userId)
        {
            Reference refTable = _referenceRepository.GetMany(r => r.Code == DbConstant.REF_TRANSTBL_MANUAL).FirstOrDefault();

            DateTime currentTime = DateTime.Now;
            Transaction parentEntity = new Transaction();
            Map(parentTransaction, parentEntity);
            parentEntity.CreateUserId = userId;
            parentEntity.CreateDate = currentTime;
            parentEntity.ModifyUserId = userId;
            parentEntity.ModifyDate = currentTime;
            parentEntity.ReferenceTableId = refTable.Id;
            parentEntity.PrimaryKeyValue = -1;
            parentEntity.Status = (int)DbConstant.DefaultDataStatus.Active;
            _transactionRepository.AttachNavigation<User>(parentEntity.CreateUser);
            _transactionRepository.AttachNavigation<User>(parentEntity.ModifyUser);
            _transactionRepository.AttachNavigation<Reference>(parentEntity.PaymentMethod);
            _transactionRepository.AttachNavigation<Reference>(parentEntity.ReferenceTable);
            parentEntity = _transactionRepository.Add(parentEntity);
            _unitOfWork.SaveChanges();

            // update primary key value into previous inserted transaction id
            parentEntity = _transactionRepository.GetById(parentEntity.Id);
            parentEntity.PrimaryKeyValue = parentEntity.Id;
            _transactionRepository.Update(parentEntity);
            _unitOfWork.SaveChanges();

            foreach (var detailTransaction in detailTransactionList)
            {
                TransactionDetail detailEntity = new TransactionDetail();
                Map(detailTransaction, detailEntity);
                detailEntity.ParentId = parentEntity.Id;
                _transactionDetailRepository.AttachNavigation<Transaction>(detailEntity.Parent);
                _transactionDetailRepository.AttachNavigation<JournalMaster>(detailEntity.Journal);
                _transactionDetailRepository.Add(detailEntity);
            }

            _unitOfWork.SaveChanges();
        }
        /// <summary>
        /// Deletes the object.
        /// </summary>
        public virtual void Delete(TransactionDetail deleteObject)
        {
            // create a new instance of the connection
            SqlConnection cnn = new SqlConnection(TransactionDetail.GetConnectionString());
            // create local variable array for the sql parameters
            SqlParameterHash sqlparams = null;

            try
            {
                // discover the parameters
                sqlparams =  SqlHelperParameterCache.GetSpParameterSet(TransactionDetail.GetConnectionString(), "gsp_DeleteTransactionDetail");

                // Store the parameter for the LoanApplicationId attribute.
                sqlparams["@loanApplicationId"].Value = deleteObject.LoanApplicationId;

                using (cnn)
                {
                    // open the connection
                    cnn.Open();

                    // Execute the stored proc to perform the delete on the instance.
                    SqlHelper.ExecuteNonQuery(cnn, CommandType.StoredProcedure, "gsp_DeleteTransactionDetail", sqlparams);

                    // close the connection after usage
                    cnn.Close();
                }

                // nullify the connection var
                cnn = null;
            }
            catch (SqlException sqlex)
            {
                throw sqlex;
            }

            // nullify the reference
            deleteObject = null;
        }
 /// <summary>
 /// Persists the object.
 /// </summary>
 public virtual void Persist(TransactionDetail persistObject)
 {
     // Make a call to the overloaded method with a null transaction
     Persist(persistObject, null);
 }
        /// <summary>
        /// Persists the object.
        /// </summary>
        public virtual void Persist(TransactionDetail persistObject, SqlTransaction sqlTrans)
        {
            // create local variable array for the sql parameters
            SqlParameterHash sqlparams = null;
            // Create a local variable for the connection
            SqlConnection cnn = null;

            // Use the parameter overload or create a new instance
            if (sqlTrans == null)
                cnn = new SqlConnection(TransactionDetail.GetConnectionString());

            try
            {
                // discover the parameters
                if (persistObject.Persisted)
                    sqlparams =  SqlHelperParameterCache.GetSpParameterSet(TransactionDetail.GetConnectionString(), "gsp_UpdateTransactionDetail");
                else
                    sqlparams =  SqlHelperParameterCache.GetSpParameterSet(TransactionDetail.GetConnectionString(), "gsp_CreateTransactionDetail");

                // Store the parameter for the AlterationsImprovementsAndRepairsAmount attribute.
                if (!persistObject.AlterationsImprovementsAndRepairsAmountIsNull)
                    sqlparams["@alterationsImprovementsAndRepairsAmount"].Value = persistObject.AlterationsImprovementsAndRepairsAmount;
                // Store the parameter for the BorrowerPaidDiscountPointsTotalAmount attribute.
                if (!persistObject.BorrowerPaidDiscountPointsTotalAmountIsNull)
                    sqlparams["@borrowerPaidDiscountPointsTotalAmount"].Value = persistObject.BorrowerPaidDiscountPointsTotalAmount;
                // Store the parameter for the EstimatedClosingCostsAmount attribute.
                if (!persistObject.EstimatedClosingCostsAmountIsNull)
                    sqlparams["@estimatedClosingCostsAmount"].Value = persistObject.EstimatedClosingCostsAmount;
                // Store the parameter for the MIAndFundingFeeFinancedAmount attribute.
                if (!persistObject.MIAndFundingFeeFinancedAmountIsNull)
                    sqlparams["@mIAndFundingFeeFinancedAmount"].Value = persistObject.MIAndFundingFeeFinancedAmount;
                // Store the parameter for the MIAndFundingFeeTotalAmount attribute.
                if (!persistObject.MIAndFundingFeeTotalAmountIsNull)
                    sqlparams["@mIAndFundingFeeTotalAmount"].Value = persistObject.MIAndFundingFeeTotalAmount;
                // Store the parameter for the PrepaidItemsEstimatedAmount attribute.
                if (!persistObject.PrepaidItemsEstimatedAmountIsNull)
                    sqlparams["@prepaidItemsEstimatedAmount"].Value = persistObject.PrepaidItemsEstimatedAmount;
                // Store the parameter for the PurchasePriceAmount attribute.
                if (!persistObject.PurchasePriceAmountIsNull)
                    sqlparams["@purchasePriceAmount"].Value = persistObject.PurchasePriceAmount;
                // Store the parameter for the RefinanceIncludingDebtsToBePaidOffAmount attribute.
                if (!persistObject.RefinanceIncludingDebtsToBePaidOffAmountIsNull)
                    sqlparams["@refinanceIncludingDebtsToBePaidOffAmount"].Value = persistObject.RefinanceIncludingDebtsToBePaidOffAmount;
                // Store the parameter for the SalesConcessionAmount attribute.
                if (!persistObject.SalesConcessionAmountIsNull)
                    sqlparams["@salesConcessionAmount"].Value = persistObject.SalesConcessionAmount;
                // Store the parameter for the SellerPaidClosingCostsAmount attribute.
                if (!persistObject.SellerPaidClosingCostsAmountIsNull)
                    sqlparams["@sellerPaidClosingCostsAmount"].Value = persistObject.SellerPaidClosingCostsAmount;
                // Store the parameter for the SubordinateLienAmount attribute.
                if (!persistObject.SubordinateLienAmountIsNull)
                    sqlparams["@subordinateLienAmount"].Value = persistObject.SubordinateLienAmount;
                // Store the parameter for the SubordinateLienHELOCAmount attribute.
                if (!persistObject.SubordinateLienHELOCAmountIsNull)
                    sqlparams["@subordinateLienHELOCAmount"].Value = persistObject.SubordinateLienHELOCAmount;
                // Store the parameter for the FREReserveAmount attribute.
                if (!persistObject.FREReserveAmountIsNull)
                    sqlparams["@fREReserveAmount"].Value = persistObject.FREReserveAmount;
                // Store the parameter for the FREReservesAmount attribute.
                if (!persistObject.FREReservesAmountIsNull)
                    sqlparams["@fREReservesAmount"].Value = persistObject.FREReservesAmount;
                // Store the parameter for the LoanApplicationId attribute.
                sqlparams["@loanApplicationId"].Value = persistObject.LoanApplicationId;
                if (!persistObject.Persisted)
                {
                    // store the create only (historical fixed) values
                }
                else
                {
                    // store the update only (historical changeable) values
                }

                if (sqlTrans == null)
                {
                    // Process using the isolated connection
                    using (cnn)
                    {
                        // open the connection
                        cnn.Open();

                        if (!persistObject.Persisted)
                        {
                            SqlHelper.ExecuteNonQuery(cnn, CommandType.StoredProcedure, "gsp_CreateTransactionDetail", sqlparams);
                        }
                        else
                        {
                            SqlHelper.ExecuteNonQuery(cnn, CommandType.StoredProcedure, "gsp_UpdateTransactionDetail", sqlparams);
                        }

                        // close the connection after usage
                        cnn.Close();
                    }

                    // nullify the connection var
                    cnn = null;
                }
                else
                {
                    // Process using the shared transaction
                    if (!persistObject.Persisted)
                    {
                        SqlHelper.ExecuteNonQuery(sqlTrans, CommandType.StoredProcedure, "gsp_CreateTransactionDetail", sqlparams);
                    }
                    else
                    {
                        SqlHelper.ExecuteNonQuery(sqlTrans, CommandType.StoredProcedure, "gsp_UpdateTransactionDetail", sqlparams);
                    }
                }
            }
            catch (SqlException sqlex)
            {
                throw sqlex;
            }
        }
        public void UpdateTransaction(TransactionViewModel parentTransaction,
            List<TransactionDetailViewModel> detailTransactionList, int userId)
        {
            Transaction parentEntity = _transactionRepository.GetById(parentTransaction.Id);
            Map(parentTransaction, parentEntity);
            parentEntity.ModifyUserId = userId;
            parentEntity.ModifyDate = DateTime.Now;
            _transactionRepository.AttachNavigation<User>(parentEntity.CreateUser);
            _transactionRepository.AttachNavigation<User>(parentEntity.ModifyUser);
            _transactionRepository.AttachNavigation<Reference>(parentEntity.PaymentMethod);
            _transactionRepository.AttachNavigation<Reference>(parentEntity.ReferenceTable);
            _transactionRepository.Update(parentEntity);
            _unitOfWork.SaveChanges();

            foreach (var detailTransaction in detailTransactionList)
            {
                if (detailTransaction.Id > 0)
                {
                    TransactionDetail detailEntity = _transactionDetailRepository.GetById(detailTransaction.Id);
                    Map(detailTransaction, detailEntity);
                    _transactionDetailRepository.AttachNavigation<Transaction>(detailEntity.Parent);
                    _transactionDetailRepository.AttachNavigation<JournalMaster>(detailEntity.Journal);
                    _transactionDetailRepository.Update(detailEntity);
                }
                else
                {
                    TransactionDetail detailEntity = new TransactionDetail();
                    Map(detailTransaction, detailEntity);
                    detailEntity.ParentId = parentEntity.Id;
                    _transactionDetailRepository.AttachNavigation<Transaction>(detailEntity.Parent);
                    _transactionDetailRepository.AttachNavigation<JournalMaster>(detailEntity.Journal);
                    _transactionDetailRepository.Add(detailEntity);
                }
            }
            _unitOfWork.SaveChanges();
        }
        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();
        }
예제 #38
0
        [Fact] // CodePlex 2606
        public void DetectChanges_sets_FKs_if_entity_added_to_two_navigations_on_both_ends()
        {
            var modelBuilder = new DbModelBuilder();
            modelBuilder.Entity<Transaction>();
            modelBuilder.Entity<TransactionDetail>();
            modelBuilder.Entity<Note>();

            using (var context = new DbContext("Context2606", modelBuilder.Build(ProviderRegistry.Sql2008_ProviderInfo).Compile()))
            {
                new DropCreateDatabaseIfModelChanges<DbContext>().InitializeDatabase(context);

                var note = new Note();
                context.Set<Note>().Add(note);
                context.Entry(note).State = EntityState.Unchanged;

                var transaction = new Transaction();
                context.Set<Transaction>().Add(transaction);

                var transactionDetail = new TransactionDetail();
                transactionDetail.Transaction = transaction;
                transactionDetail.Notes.Add(note);
                transaction.TransactionDetails.Add(transactionDetail);
                note.TransactionDetail = transactionDetail;

                Assert.Null(transactionDetail.TransactionId);
                Assert.Null(note.TransactionDetailId);

                context.ChangeTracker.DetectChanges();

                Assert.NotNull(transactionDetail.TransactionId);
                Assert.NotNull(note.TransactionDetailId);
                Assert.Equal(EntityState.Modified, context.Entry(note).State);
            }
        }
        private string TransactionDetailString(TransactionDetail t)
        {
            int intPreviousIndex = -1;
            foreach (int itemChecked in chklstTMSResults.CheckedIndices)
            {
                intPreviousIndex = itemChecked;
                chklstTMSResults.SetItemChecked(itemChecked, false);
            }

            if (chklstTMSResults.SelectedIndex != intPreviousIndex)
                chklstTMSResults.SetItemChecked(chklstTMSResults.SelectedIndex, true);

            string strSummary = "";

            t.TransactionInformation.BankcardData = new BankcardData();
            t.TransactionInformation.BankcardData.AVSResult = new AVSResult();
            //Batch Summary
            strSummary = strSummary + "CompleteTransaction CWS object : " + "OBJECT\r\n";
            strSummary = strSummary + (t.CompleteTransaction.SerializedTransaction == null ? "CompleteTransaction Serialized : NOT AVAILABLE\r\n" : "CompleteTransaction Serialized : " + t.CompleteTransaction.SerializedTransaction + "\r\n");
            //Family Information
            strSummary = strSummary + "Family Information \r\n";
            strSummary = strSummary + "FamilyId : " + t.FamilyInformation.FamilyId + "\r\n";
            strSummary = strSummary + "FamilySequenceCount : " + t.FamilyInformation.FamilySequenceCount + "\r\n";
            strSummary = strSummary + "FamilySequenceNumber : " + t.FamilyInformation.FamilySequenceNumber + "\r\n";
            strSummary = strSummary + "FamilyState : " + t.FamilyInformation.FamilyState + "\r\n";
            strSummary = strSummary + "NetAmount : " + t.FamilyInformation.NetAmount + "\r\n";
            //Transaction Information
            strSummary = strSummary + "Transaction Information\r\n";
            strSummary = strSummary + "Amount : " + t.TransactionInformation.Amount + "\r\n";
            strSummary = strSummary + "ApprovalCode : " + t.TransactionInformation.ApprovalCode + "\r\n";
            //TransactionInformation.BankcardData
            strSummary = strSummary + "AVSResult Summary";
            strSummary = strSummary + " - ActualResult : " + t.TransactionInformation.BankcardData.AVSResult.ActualResult + "\r\n";
            strSummary = strSummary + " - AddressResult : " + t.TransactionInformation.BankcardData.AVSResult.AddressResult + "\r\n";
            strSummary = strSummary + " - PostalCodeResult : " + t.TransactionInformation.BankcardData.AVSResult.PostalCodeResult + "\r\n";
            strSummary = strSummary + "CardType : " + t.TransactionInformation.BankcardData.CardType + "\r\n";
            strSummary = strSummary + "CVResult : " + t.TransactionInformation.BankcardData.CVResult + "\r\n";
            strSummary = strSummary + "BatchId : " + t.TransactionInformation.BatchId + "\r\n";
            strSummary = strSummary + "CaptureDateTime : " + t.TransactionInformation.CaptureDateTime + "\r\n";
            strSummary = strSummary + "CaptureState : " + t.TransactionInformation.CaptureState + "\r\n";
            strSummary = strSummary + "CaptureStatusMessage : " + t.TransactionInformation.CaptureStatusMessage + "\r\n";
            strSummary = strSummary + "CapturedAmount : " + t.TransactionInformation.CapturedAmount + "\r\n";
            strSummary = strSummary + "CustomerId : " + t.TransactionInformation.CustomerId + "\r\n";
            if (t.TransactionInformation.ElectronicCheckData != null)
            {
				//TransactionInformation.ElectronicCheckData
				strSummary = strSummary + "Electronic Check Data";
				strSummary = strSummary + " - CheckNumber : " + t.TransactionInformation.ElectronicCheckData.CheckNumber + "\r\n";
				strSummary = strSummary + " - MaskedAccountNumber : " + t.TransactionInformation.ElectronicCheckData.MaskedAccountNumber + "\r\n";
				strSummary = strSummary + " - TransactionType : " + t.TransactionInformation.ElectronicCheckData.TransactionType + "\r\n";
			}
            strSummary = strSummary + "IsAcknowledged : " + t.TransactionInformation.IsAcknowledged + "\r\n";
            strSummary = strSummary + "MaskedPAN : " + t.TransactionInformation.MaskedPAN + "\r\n";
            strSummary = strSummary + "MerchantProfileId : " + t.TransactionInformation.MerchantProfileId + "\r\n";
            strSummary = strSummary + "OriginatorTransactionId : " + t.TransactionInformation.OriginatorTransactionId + "\r\n";
            strSummary = strSummary + "ServiceId : " + t.TransactionInformation.ServiceId + "\r\n";
            strSummary = strSummary + "ServiceKey : " + t.TransactionInformation.ServiceKey + "\r\n";
            strSummary = strSummary + "ServiceTransactionId : " + t.TransactionInformation.ServiceTransactionId + "\r\n";
            strSummary = strSummary + "Status : " + t.TransactionInformation.Status + "\r\n";
            strSummary = strSummary + "TransactionClass : " + t.TransactionInformation.TransactionClassTypePair.TransactionClass + "    ";
            strSummary = strSummary + "TransactionType : " + t.TransactionInformation.TransactionClassTypePair.TransactionType + "\r\n";
            strSummary = strSummary + "TransactionId : " + t.TransactionInformation.TransactionId + "\r\n";
            strSummary = strSummary + "TransactionState : " + t.TransactionInformation.TransactionState + "\r\n";
            strSummary = strSummary + "TransactionStatusCode : " + t.TransactionInformation.TransactionStatusCode + "\r\n";
            strSummary = strSummary + "TransactionTimestamp : " + t.TransactionInformation.TransactionTimestamp + "\r\n";
            strSummary = strSummary + "\r\n";

            strSummary = strSummary + "\r\n";
            return strSummary;
        }
 public TransactionDetailVal(TransactionDetail td)
 {
     TD = td;
 }
        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 InsertDebt(TransactionViewModel transaction, decimal purchasingPrice, int userID)
        {
            DateTime serverTime = DateTime.Now;
            Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_PURCHASING).FirstOrDefault();
            transaction.CreateDate = serverTime;
            transaction.ModifyDate = serverTime;
            transaction.CreateUserId = userID;
            transaction.ModifyUserId = userID;
            transaction.TransactionDate = serverTime;
            transaction.TotalTransaction = purchasingPrice.AsDouble();
            transaction.ReferenceTableId = transactionReferenceTable.Id;
            transaction.Status = (int)DbConstant.DefaultDataStatus.Active;
            transaction.Description = "Pembayaran hutang";

            Transaction entity = new Transaction();
            Map(transaction, entity);
            Transaction transactionInserted = _transactionRepository.Add(entity);

            Purchasing purchasingEntity = _purchasingRepository.GetById(transaction.PrimaryKeyValue);
            purchasingEntity.TotalHasPaid += transaction.TotalPayment.AsDecimal();
            if (purchasingEntity.TotalHasPaid == purchasingEntity.TotalPrice)
            {
                purchasingEntity.PaymentStatus = (int)DbConstant.PaymentStatus.Settled;
            }
            _purchasingRepository.Update(purchasingEntity);

            Reference paymentMethod = _referenceRepository.GetById(transaction.PaymentMethodId);

            switch (paymentMethod.Code)
            {
                case DbConstant.REF_DEBT_PAYMENTMETHOD_BANK_EKONOMI:
                case DbConstant.REF_DEBT_PAYMENTMETHOD_BANK_BCA1:
                case DbConstant.REF_DEBT_PAYMENTMETHOD_BANK_BCA2:
                    {
                        // Bank Kredit --> Karena berkurang
                        TransactionDetail detailBank = new TransactionDetail();
                        detailBank.Credit = transaction.TotalPayment.AsDecimal();
                        if (paymentMethod.Code == DbConstant.REF_DEBT_PAYMENTMETHOD_BANK_EKONOMI)
                        {
                            detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.01").FirstOrDefault().Id;
                        }
                        else if (paymentMethod.Code == DbConstant.REF_DEBT_PAYMENTMETHOD_BANK_BCA1)
                        {
                            detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.02").FirstOrDefault().Id;
                        }
                        else if (paymentMethod.Code == DbConstant.REF_DEBT_PAYMENTMETHOD_BANK_BCA2)
                        {
                            detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.03").FirstOrDefault().Id;
                        }
                        detailBank.Parent = transactionInserted;
                        _transactionDetailRepository.Add(detailBank);
                        break;
                    }

                case DbConstant.REF_DEBT_PAYMENTMETHOD_KAS:
                    // Kas Kredit --> Karena berkurang
                    TransactionDetail detailKas = new TransactionDetail();
                    detailKas.Credit = transaction.TotalPayment.AsDecimal();
                    detailKas.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.01.01").FirstOrDefault().Id;
                    detailKas.Parent = transactionInserted;
                    _transactionDetailRepository.Add(detailKas);
                    break;
            }

            TransactionDetail detailDebt = new TransactionDetail();
            detailDebt.Debit = transaction.TotalPayment.AsDecimal();
            detailDebt.JournalId = _journalMasterRepository.GetMany(j => j.Code == "2.01.01.01").FirstOrDefault().Id;
            detailDebt.Parent = transactionInserted;
            _transactionDetailRepository.Add(detailDebt);
            _unitOfWork.SaveChanges();
        }
        private void TransactionDetailString(TransactionDetail t)
        {
            RtxtTMSResults.SelectionColor = Color.Black;

            ColorText("TransactionState : " + t.TransactionInformation.TransactionState + "\r\n", t.TransactionInformation.TransactionState);
            ColorText("TransactionStatusCode : " + t.TransactionInformation.TransactionStatusCode + "\r\n", t.TransactionInformation.TransactionState);

            //CompleteTransaction
            RtxtTMSResults.AppendText("CompleteTransaction CWS object : " + "OBJECT\r\n");
            if ((TransactionDetailFormat)CboTransactionDetailFormat.SelectedItem == TransactionDetailFormat.SerializedCWS)
                TxtTransactionDetailFormat.Text = t.CompleteTransaction.SerializedTransaction;
                //RtxtTMSResults.AppendText((t.CompleteTransaction.SerializedTransaction == null ? "CompleteTransaction Serialized : NOT AVAILABLE\r\n" : "CompleteTransaction Serialized : " + t.CompleteTransaction.SerializedTransaction + "\r\n"));
            //Family Information
            RtxtTMSResults.AppendText("Family Information \r\n");
            RtxtTMSResults.AppendText("FamilyId : " + t.FamilyInformation.FamilyId + "\r\n");
            RtxtTMSResults.AppendText("FamilySequenceCount : " + t.FamilyInformation.FamilySequenceCount + "\r\n");
            RtxtTMSResults.AppendText("FamilySequenceNumber : " + t.FamilyInformation.FamilySequenceNumber + "\r\n");
            RtxtTMSResults.AppendText("FamilyState : " + t.FamilyInformation.FamilyState + "\r\n");
            RtxtTMSResults.AppendText("NetAmount : " + t.FamilyInformation.NetAmount + "\r\n");
            //Transaction Information
            RtxtTMSResults.AppendText("Transaction Information\r\n");
            RtxtTMSResults.AppendText("Amount : " + t.TransactionInformation.Amount + "\r\n");
            RtxtTMSResults.AppendText("ApprovalCode : " + t.TransactionInformation.ApprovalCode + "\r\n");

            //TransactionInformation.BankcardData
            if (t.TransactionInformation.BankcardData != null)
            {
                //TransactionInformation.BankcardData.AVSResult
                if (t.TransactionInformation.BankcardData.AVSResult != null)
                {
                    RtxtTMSResults.AppendText("AVSResult Summary");
                    RtxtTMSResults.AppendText(" - ActualResult : " + t.TransactionInformation.BankcardData.AVSResult.ActualResult + "\r\n");
                    RtxtTMSResults.AppendText(" - AddressResult : " + t.TransactionInformation.BankcardData.AVSResult.AddressResult + "\r\n");
                    RtxtTMSResults.AppendText(" - CardholderNameResult : " + t.TransactionInformation.BankcardData.AVSResult.CardholderNameResult + "\r\n");
                    RtxtTMSResults.AppendText(" - CityResult : " + t.TransactionInformation.BankcardData.AVSResult.CityResult + "\r\n");
                    RtxtTMSResults.AppendText(" - CountryResult : " + t.TransactionInformation.BankcardData.AVSResult.CountryResult + "\r\n");
                    RtxtTMSResults.AppendText(" - PhoneResult : " + t.TransactionInformation.BankcardData.AVSResult.PhoneResult + "\r\n");
                    RtxtTMSResults.AppendText(" - PostalCodeResult : " + t.TransactionInformation.BankcardData.AVSResult.PostalCodeResult + "\r\n");
                    RtxtTMSResults.AppendText(" - StateResult : " + t.TransactionInformation.BankcardData.AVSResult.StateResult + "\r\n");
                }
                //TransactionInformation.BankcardData
                RtxtTMSResults.AppendText("CardType : " + t.TransactionInformation.BankcardData.CardType + "\r\n");
                RtxtTMSResults.AppendText("CVResult : " + t.TransactionInformation.BankcardData.CVResult + "\r\n");
                RtxtTMSResults.AppendText("MaskedPAN : " + t.TransactionInformation.BankcardData.MaskedPAN + "\r\n");
                RtxtTMSResults.AppendText("OrderId : " + t.TransactionInformation.BankcardData.OrderId + "\r\n"); //The order id generated by CWS. This value is often used by service providers for transaction correlation. Expected.
            }
            RtxtTMSResults.AppendText("BatchId : " + t.TransactionInformation.BatchId + "\r\n");
            RtxtTMSResults.AppendText("CapturedAmount : " + t.TransactionInformation.CapturedAmount + "\r\n");
            RtxtTMSResults.AppendText("CaptureDateTime : " + t.TransactionInformation.CaptureDateTime + "\r\n");
            RtxtTMSResults.AppendText("CaptureState : " + t.TransactionInformation.CaptureState + "\r\n");
            RtxtTMSResults.AppendText("CaptureStatusMessage : " + t.TransactionInformation.CaptureStatusMessage + "\r\n");
            RtxtTMSResults.AppendText("CustomerId : " + t.TransactionInformation.CustomerId + "\r\n");
            if (t.TransactionInformation.ElectronicCheckData != null)
            {
                //TransactionInformation.ElectronicCheckData
                RtxtTMSResults.AppendText("Electronic Check Data");
                RtxtTMSResults.AppendText(" - CheckNumber : " + t.TransactionInformation.ElectronicCheckData.CheckNumber + "\r\n");
                RtxtTMSResults.AppendText(" - MaskedAccountNumber : " + t.TransactionInformation.ElectronicCheckData.MaskedAccountNumber + "\r\n");
                RtxtTMSResults.AppendText(" - TransactionType : " + t.TransactionInformation.ElectronicCheckData.TransactionType + "\r\n");
            }
            RtxtTMSResults.AppendText("IsAcknowledged : " + t.TransactionInformation.IsAcknowledged + "\r\n");
            RtxtTMSResults.AppendText("MaskedPAN : " + t.TransactionInformation.MaskedPAN + "\r\n");
            RtxtTMSResults.AppendText("MerchantProfileId : " + t.TransactionInformation.MerchantProfileId + "\r\n");
            RtxtTMSResults.AppendText("OriginatorTransactionId : " + t.TransactionInformation.OriginatorTransactionId + "\r\n");
            RtxtTMSResults.AppendText("Reference : " + t.TransactionInformation.Reference + "\r\n");
            RtxtTMSResults.AppendText("ServiceId : " + t.TransactionInformation.ServiceId + "\r\n");
            RtxtTMSResults.AppendText("ServiceKey : " + t.TransactionInformation.ServiceKey + "\r\n");
            RtxtTMSResults.AppendText("ServiceTransactionId : " + t.TransactionInformation.ServiceTransactionId + "\r\n");
            RtxtTMSResults.AppendText("Status : " + t.TransactionInformation.Status + "\r\n");
            if (t.TransactionInformation.StoredValueData != null)
            {
                //TransactionInformation.ElectronicCheckData
                RtxtTMSResults.AppendText("Electronic Check Data");
                RtxtTMSResults.AppendText(" - CVResult : " + t.TransactionInformation.StoredValueData.CVResult + "\r\n");
                RtxtTMSResults.AppendText(" - CVResult : " + t.TransactionInformation.StoredValueData.CardRestrictionValue + "\r\n");
                RtxtTMSResults.AppendText(" - CVResult : " + t.TransactionInformation.StoredValueData.CardStatus + "\r\n");
                RtxtTMSResults.AppendText(" - CVResult : " + t.TransactionInformation.StoredValueData.NewBalance + "\r\n");
                RtxtTMSResults.AppendText(" - CVResult : " + t.TransactionInformation.StoredValueData.OrderId + "\r\n");
                RtxtTMSResults.AppendText(" - CVResult : " + t.TransactionInformation.StoredValueData.PreviousBalance + "\r\n");
            }
            RtxtTMSResults.AppendText("TransactionClass : " + t.TransactionInformation.TransactionClassTypePair.TransactionClass + "    ");
            RtxtTMSResults.AppendText("TransactionType : " + t.TransactionInformation.TransactionClassTypePair.TransactionType + "\r\n");
            RtxtTMSResults.AppendText("TransactionId : " + t.TransactionInformation.TransactionId + "\r\n");
            RtxtTMSResults.SelectionColor = Color.Black;
            RtxtTMSResults.AppendText("TransactionTimestamp : " + t.TransactionInformation.TransactionTimestamp + "\r\n");
            RtxtTMSResults.AppendText("\r\n");

            RtxtTMSResults.AppendText("\r\n");
        }
        public static void DataImporter()
        {
            BrawijayaWorkshopDbContext contextTemp = new BrawijayaWorkshopDbContext(
                new MySqlConnection(ConfigurationManager.ConnectionStrings["TempConn"].ConnectionString), true);

            BrawijayaWorkshopDbContext contextDest = new BrawijayaWorkshopDbContext(
                new MySqlConnection(ConfigurationManager.ConnectionStrings["DestConn"].ConnectionString), true);
            contextDest.Database.CreateIfNotExists();

            //get all data from temp db
            List<ApplicationModul> ApplicationModulList = contextTemp.ApplicationModuls.ToList();
            List<Role> RoleList = contextTemp.Roles.ToList();
            List<Setting> SettingList = contextTemp.Settings.ToList();
            List<Reference> ReferenceList = contextTemp.References.ToList();
            List<User> UserList = contextTemp.Users.ToList();
            List<JournalMaster> JournalMasterList = contextTemp.JournalMasters.ToList();
            List<Brand> BrandList = contextTemp.Brands.ToList();
            List<BrawijayaWorkshop.Database.Entities.Type> TypeList = contextTemp.Types.ToList();
            List<City> CityList = contextTemp.Cities.ToList();

            List<RoleAccess> RoleAccessList = contextTemp.RoleAccesses.ToList();
            List<UserRole> UserRoleList = contextTemp.UserRoles.ToList();

            List<Customer> CustomerList = contextTemp.Customers.ToList();
            List<VehicleGroup> VehicleGroupList = contextTemp.VehicleGroups.ToList();
            List<Vehicle> VehicleList = contextTemp.Vehicles.ToList();
            List<VehicleDetail> VehicleDetailList = contextTemp.VehicleDetails.ToList();

            List<Mechanic> MechanicList = contextTemp.Mechanics.ToList();

            List<Supplier> SupplierList = contextTemp.Suppliers.ToList();
            List<Sparepart> SparepartList = contextTemp.Spareparts.ToList();
            List<SpecialSparepart> SpecialSparepartList = contextTemp.Wheels.ToList();

            List<SparepartManualTransaction> SparepartManualTransactionList = contextTemp.SparepartManualTransactions.ToList();
            List<Purchasing> PurchasingList = contextTemp.Purchasings.ToList();
            List<PurchasingDetail> PurchasingDetailList = contextTemp.PurchasingDetails.ToList();
            List<PurchaseReturn> PurchaseReturnList = contextTemp.PurchaseReturns.ToList();
            List<PurchaseReturnDetail> PurchaseReturnDetailList = contextTemp.PurchaseReturnDetails.ToList();

            List<SparepartDetail> SparepartDetailList = contextTemp.SparepartDetails.ToList();
            List<SpecialSparepartDetail> SpecialSparepartDetailList = contextTemp.WheelDetails.ToList();
            List<VehicleWheel> VehicleWheelList = contextTemp.VehicleWheels.ToList();

            List<UsedGood> UsedGoodList = contextTemp.UsedGoods.ToList();
            List<UsedGoodTransaction> UsedGoodTransactionList = contextTemp.UsedGoodsTransactions.ToList();

            List<GuestBook> GuestBookList = contextTemp.GuestBooks.ToList();

            List<SPK> SPKList = contextTemp.SPKs.ToList();
            List<SPKDetailSparepart> SPKDetailSparepartList = contextTemp.SPKDetailSpareparts.ToList();
            List<SPKDetailSparepartDetail> SPKDetailSparepartDetailList = contextTemp.SPKDetailSparepartDetails.ToList();
            List<SPKSchedule> SPKScheduleList = contextTemp.SPKSchedules.ToList();
            List<WheelExchangeHistory> WheelExchangeHistoryList = contextTemp.WheelExchangeHistories.ToList();

            List<Invoice> InvoiceList = contextTemp.Invoices.ToList();
            List<InvoiceDetail> InvoiceDetailList = contextTemp.InvoiceDetails.ToList();
            List<SalesReturn> SalesReturnList = contextTemp.SalesReturns.ToList();
            List<SalesReturnDetail> SalesReturnDetailList = contextTemp.SalesReturnDetails.ToList();

            List<Transaction> TransactionList = contextTemp.Transactions.ToList();
            List<TransactionDetail> TransactionDetailList = contextTemp.TransactionDetails.ToList();

            List<BalanceJournal> BalanceJournalList = contextTemp.BalanceJournals.ToList();
            List<BalanceJournalDetail> BalanceJournalDetailList = contextTemp.BalanceJournalDetails.ToList();

            Dictionary<int, int> dictAppModul = new Dictionary<int, int>();
            Dictionary<int, int> dictRole = new Dictionary<int, int>();
            Dictionary<int, int> dictUser = new Dictionary<int, int>();
            Dictionary<int, int> dictCity = new Dictionary<int, int>();
            Dictionary<int, int> dictReference = new Dictionary<int, int>();
            Dictionary<int, int> dictJournalMaster = new Dictionary<int, int>();
            Dictionary<int, int> dictBrand = new Dictionary<int, int>();
            Dictionary<int, int> dictType = new Dictionary<int, int>();
            Dictionary<int, int> dictCustomer = new Dictionary<int, int>();
            Dictionary<int, int> dictVehicleGroup = new Dictionary<int, int>();
            Dictionary<int, int> dictVehicle = new Dictionary<int, int>();
            Dictionary<int, int> dictMechanic = new Dictionary<int, int>();
            Dictionary<int, int> dictSupplier = new Dictionary<int, int>();
            Dictionary<int, int> dictSparepart = new Dictionary<int, int>();
            Dictionary<int, int> dictSpecialSparepart = new Dictionary<int, int>();
            Dictionary<int, int> dictSpManualTrans = new Dictionary<int, int>();
            Dictionary<int, int> dictPurchasing = new Dictionary<int, int>();
            Dictionary<int, int> dictPurchasingDetail = new Dictionary<int, int>();
            Dictionary<int, int> dictPurchaseReturn = new Dictionary<int, int>();
            Dictionary<int, int> dictSparepartDetail = new Dictionary<int, int>();
            Dictionary<int, int> dictSpecialSparepartDetail = new Dictionary<int, int>();
            Dictionary<int, int> dictUsedGood = new Dictionary<int, int>();
            Dictionary<int, int> dictSPK = new Dictionary<int, int>();
            Dictionary<int, int> dictSPKDetailSparepart = new Dictionary<int, int>();
            Dictionary<int, int> dictSPKDetailSparepartDetail = new Dictionary<int, int>();
            Dictionary<int, int> dictInvoice = new Dictionary<int, int>();
            Dictionary<int, int> dictInvoiceDetail = new Dictionary<int, int>();
            Dictionary<int, int> dictSalesReturn = new Dictionary<int, int>();
            Dictionary<int, int> dictTransaction = new Dictionary<int, int>();
            Dictionary<int, int> dictBalanceJournal = new Dictionary<int, int>();

            //applicationmodul
            Console.Write("\nImporting table ApplicationModul");

            foreach (var item in ApplicationModulList)
            {
                int itemOldId = item.Id;
                item.Id = -1;
                ApplicationModul newItem = contextDest.ApplicationModuls.Add(item);
                contextDest.SaveChanges();

                dictAppModul.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table ApplicationModul done, " + ApplicationModulList.Count + " records imported");

            //role
            Console.Write("\nImporting table Role");

            foreach (var item in RoleList)
            {
                int itemOldId = item.Id;
                item.Id = -1;
                Role newItem = contextDest.Roles.Add(item);
                contextDest.SaveChanges();

                dictRole.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table Role done, " + RoleList.Count + " records imported");

            //setting
            Console.Write("\nImporting table setting");

            foreach (var item in SettingList)
            {
                contextDest.Settings.Add(item);
            }
            contextDest.SaveChanges();

            Console.Write("\nImporting table setting done, " + SettingList.Count + " records imported");

            //reference
            Console.Write("\nImporting table Reference");

            foreach (var item in ReferenceList)
            {
                int itemOldId = item.Id;
                Reference newItem = new Reference
                {
                    Id = -1,
                    Code = item.Code,
                    Description = item.Description,
                    Name = item.Name,
                    ParentId = item.ParentId,
                    Value = item.Value
                };

                if (item.ParentId > 0)
                {
                    int newParentId = dictReference[item.ParentId.Value];
                    newItem.ParentId = newParentId;
                }

                Reference insertedReference = contextDest.References.Add(newItem);
                contextDest.SaveChanges();

                dictReference.Add(itemOldId, insertedReference.Id);
            }

            Console.Write("\nImporting table Reference done, " + ReferenceList.Count + " records imported");

            //user
            Console.Write("\nImporting table User");

            foreach (var item in UserList)
            {
                int itemOldId = item.Id;
                item.Id = -1;
                User newItem = contextDest.Users.Add(item);
                contextDest.SaveChanges();

                dictUser.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table User done, " + UserList.Count + " records imported");

            //journalMaster
            Console.Write("\nImporting table JournalMaster");

            foreach (var item in JournalMasterList)
            {
                int itemOldId = item.Id;
                JournalMaster newItem = new JournalMaster
                {
                    Id = -1,
                    Code = item.Code,
                    Name = item.Name,
                    ParentId = item.ParentId,
                };

                if (item.ParentId > 0)
                {
                    int newParentId = dictJournalMaster[item.ParentId.Value];
                    newItem.ParentId = newParentId;
                }

                JournalMaster insertedJournalMaster = contextDest.JournalMasters.Add(newItem);
                contextDest.SaveChanges();

                dictJournalMaster.Add(itemOldId, insertedJournalMaster.Id);
            }

            Console.Write("\nImporting table JournalMaster done, " + JournalMasterList.Count + " records imported");

            //brand
            Console.Write("\nImporting table Brand");

            foreach (var item in BrandList)
            {
                int itemOldId = item.Id;
                item.Id = -1;
                Brand newItem = contextDest.Brands.Add(item);
                contextDest.SaveChanges();

                dictBrand.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table Brand done, " + BrandList.Count + " records imported");

            //type
            Console.Write("\nImporting table Type");

            foreach (var item in TypeList)
            {
                int itemOldId = item.Id;
                item.Id = -1;
                BrawijayaWorkshop.Database.Entities.Type newItem = contextDest.Types.Add(item);
                contextDest.SaveChanges();

                dictType.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table Type done, " + TypeList.Count + " records imported");

            //city
            Console.Write("\nImporting table City");

            foreach (var item in CityList)
            {
                int itemOldId = item.Id;
                item.Id = -1;
                City newItem = contextDest.Cities.Add(item);
                contextDest.SaveChanges();

                dictCity.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table City done, " + CityList.Count + " records imported");

            //role access
            Console.Write("\nImporting table RoleAccess");

            foreach (var item in RoleAccessList)
            {
                RoleAccess newItem = new RoleAccess();
                int role = dictRole[item.RoleId];
                int appModul = dictAppModul[item.ApplicationModulId];

                newItem.Id = -1;
                newItem.RoleId = role;
                newItem.ApplicationModulId = appModul;
                newItem.AccessCode = item.AccessCode;
                contextDest.RoleAccesses.Add(newItem);
            }
            contextDest.SaveChanges();

            Console.Write("\nImporting table RoleAccess done, " + RoleAccessList.Count + " records imported");

            //user role
            Console.Write("\nImporting table UserRole");

            foreach (var item in UserRoleList)
            {
                UserRole newItem = new UserRole();
                int role = dictRole[item.RoleId];
                int user = dictUser[item.UserId];

                newItem.Id = -1;
                newItem.RoleId = role;
                newItem.UserId = user;
                contextDest.UserRoles.Add(newItem);
            }

            Console.Write("\nImporting table UserRole done, " + UserRoleList.Count + " records imported");

            //customer
            Console.Write("\nImporting table Customer");

            foreach (var item in CustomerList)
            {
                int itemOldId = item.Id;
                Customer newItem = new Customer();
                int city = dictCity[item.CityId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.CityId = city;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.Address = item.Address;
                newItem.Code = item.Code;
                newItem.CompanyName = item.CompanyName;
                newItem.ContactPerson = item.ContactPerson;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.PhoneNumber = item.PhoneNumber;
                newItem.Status = item.Status;
                newItem = contextDest.Customers.Add(newItem);
                contextDest.SaveChanges();

                dictCustomer.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table Customer done, " + CustomerList.Count + " records imported");

            //vehicle group
            Console.Write("\nImporting table VehicleGroup");

            foreach (var item in VehicleGroupList)
            {
                int itemOldId = item.Id;
                VehicleGroup newItem = new VehicleGroup();
                int customer = dictCustomer[item.CustomerId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.CustomerId = customer;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Name = item.Name;
                newItem.Status = item.Status;
                newItem = contextDest.VehicleGroups.Add(newItem);
                contextDest.SaveChanges();

                dictVehicleGroup.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table VehicleGroup done, " + VehicleGroupList.Count + " records imported");

            //vehicle
            Console.Write("\nImporting table Vehicle");

            foreach (var item in VehicleList)
            {
                int itemOldId = item.Id;
                Vehicle newItem = new Vehicle();
                int customer = dictCustomer[item.CustomerId];
                int vehicleGroup = dictVehicleGroup[item.VehicleGroupId];
                int brand = dictBrand[item.BrandId];
                int type = dictType[item.TypeId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.CustomerId = customer;
                newItem.VehicleGroupId = vehicleGroup;
                newItem.BrandId = brand;
                newItem.TypeId = type;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.ActiveLicenseNumber = item.ActiveLicenseNumber;
                newItem.Code = item.Code;
                newItem.CreateDate = item.CreateDate;
                newItem.Kilometers = item.Kilometers;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                newItem.YearOfPurchase = item.YearOfPurchase;
                newItem = contextDest.Vehicles.Add(newItem);
                contextDest.SaveChanges();

                dictVehicle.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table Vehicle done, " + VehicleList.Count + " records imported");

            //vehicle detail
            Console.Write("\nImporting table VehicleDetail");

            foreach (var item in VehicleDetailList)
            {
                VehicleDetail newItem = new VehicleDetail();
                int vehicle = dictVehicle[item.VehicleId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.VehicleId = vehicle;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.CreateDate = item.CreateDate;
                newItem.ExpirationDate = item.ExpirationDate;
                newItem.LicenseNumber = item.LicenseNumber;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                contextDest.VehicleDetails.Add(newItem);
            }
            contextDest.SaveChanges();

            Console.Write("\nImporting table VehicleDetail done, " + VehicleDetailList.Count + " records imported");

            //mechanic
            Console.Write("\nImporting table Mechanic");

            foreach (var item in MechanicList)
            {
                int itemOldId = item.Id;
                Mechanic newItem = new Mechanic();
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.Address = item.Address;
                newItem.BaseFee = item.BaseFee;
                newItem.Code = item.Code;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Name = item.Name;
                newItem.PhoneNumber = item.PhoneNumber;
                newItem.Status = item.Status;
                newItem = contextDest.Mechanics.Add(newItem);
                contextDest.SaveChanges();

                dictMechanic.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table Mechanic done, " + MechanicList.Count + " records imported");

            //supplier
            Console.Write("\nImporting table Supplier");

            foreach (var item in SupplierList)
            {
                int itemOldId = item.Id;
                Supplier newItem = new Supplier();
                int city = dictCity[item.CityId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.CityId = city;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.Address = item.Address;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Name = item.Name;
                newItem.PhoneNumber = item.PhoneNumber;
                newItem.Status = item.Status;
                newItem = contextDest.Suppliers.Add(newItem);
                contextDest.SaveChanges();

                dictSupplier.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table Supplier done, " + SupplierList.Count + " records imported");

            //sparepart
            Console.Write("\nImporting table Sparepart");

            foreach (var item in SparepartList)
            {
                int itemOldId = item.Id;
                Sparepart newItem = new Sparepart();
                int category = dictReference[item.CategoryReferenceId];
                int unit = dictReference[item.UnitReferenceId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.CategoryReferenceId = category;
                newItem.UnitReferenceId = unit;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.Code = item.Code;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Name = item.Name;
                newItem.Status = item.Status;
                newItem.StockQty = item.StockQty;
                newItem = contextDest.Spareparts.Add(newItem);
                contextDest.SaveChanges();

                dictSparepart.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table Sparepart done, " + SparepartList.Count + " records imported");

            //special sparepart
            Console.Write("\nImporting table SpecialSparepart");

            foreach (var item in SpecialSparepartList)
            {
                int itemOldId = item.Id;
                SpecialSparepart newItem = new SpecialSparepart();
                int category = dictReference[item.ReferenceCategoryId];
                int sparepart = dictSparepart[item.SparepartId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.ReferenceCategoryId = category;
                newItem.SparepartId = sparepart;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                newItem = contextDest.Wheels.Add(newItem);
                contextDest.SaveChanges();

                dictSpecialSparepart.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table SpecialSparepart done, " + SpecialSparepartList.Count + " records imported");

            //sparepart manual trans
            Console.Write("\nImporting table SparepartManualTransaction");

            foreach (var item in SparepartManualTransactionList)
            {
                int itemOldId = item.Id;
                SparepartManualTransaction newItem = new SparepartManualTransaction();
                int sparepart = dictSparepart[item.SparepartId];
                int type = dictReference[item.UpdateTypeId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.SparepartId = sparepart;
                newItem.UpdateTypeId = type;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Price = item.Price;
                newItem.Qty = item.Qty;
                newItem.Remark = item.Remark;
                newItem.TransactionDate = item.TransactionDate;
                newItem = contextDest.SparepartManualTransactions.Add(newItem);
                contextDest.SaveChanges();

                dictSpManualTrans.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table SparepartManualTransaction done, " + SparepartManualTransactionList.Count + " records imported");

            //purchasing
            Console.Write("\nImporting table Purchasing");

            foreach (var item in PurchasingList)
            {
                int itemOldId = item.Id;
                Purchasing newItem = new Purchasing();
                int paymentMethod = dictReference[item.PaymentMethodId];
                int supplier = dictSupplier[item.SupplierId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.PaymentMethodId = paymentMethod;
                newItem.SupplierId = supplier;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.Code = item.Code;
                newItem.CreateDate = item.CreateDate;
                newItem.Date = item.Date;
                newItem.ModifyDate = item.ModifyDate;
                newItem.PaymentStatus = item.PaymentStatus;
                newItem.Status = item.Status;
                newItem.TotalHasPaid = item.TotalHasPaid;
                newItem.TotalPrice = item.TotalPrice;
                newItem = contextDest.Purchasings.Add(newItem);
                contextDest.SaveChanges();

                dictPurchasing.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table InvPurchasingoice done, " + PurchasingList.Count + " records imported");

            //purchasing detail
            Console.Write("\nImporting table PurchasingDetail");

            foreach (var item in PurchasingDetailList)
            {
                int itemOldId = item.Id;
                PurchasingDetail newItem = new PurchasingDetail();
                int purchasing = dictPurchasing[item.PurchasingId];
                int sparepart = dictSparepart[item.SparepartId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.PurchasingId = purchasing;
                newItem.SparepartId = sparepart;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Price = item.Price;
                newItem.Qty = item.Qty;
                newItem.SerialNumber = item.SerialNumber;
                newItem.Status = item.Status;
                newItem = contextDest.PurchasingDetails.Add(newItem);
                contextDest.SaveChanges();

                dictPurchasingDetail.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table PurchasingDetail done, " + PurchasingDetailList.Count + " records imported");

            //purchasing return
            Console.Write("\nImporting table PurchaseReturn");

            foreach (var item in PurchaseReturnList)
            {
                int itemOldId = item.Id;
                PurchaseReturn newItem = new PurchaseReturn();
                int purchasing = dictPurchasing[item.PurchasingId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.PurchasingId = purchasing;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.Code = item.Code;
                newItem.CreateDate = item.CreateDate;
                newItem.Date = item.Date;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                newItem = contextDest.PurchaseReturns.Add(newItem);
                contextDest.SaveChanges();

                dictPurchaseReturn.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table PurchaseReturn done, " + PurchaseReturnList.Count + " records imported");

            //purchasing return detail
            Console.Write("\nImporting table PurchaseReturnDetail");

            foreach (var item in PurchaseReturnDetailList)
            {
                int itemOldId = item.Id;
                PurchaseReturnDetail newItem = new PurchaseReturnDetail();
                int purchaseReturn = dictPurchaseReturn[item.PurchaseReturnId];
                int pDetail = dictPurchasingDetail[item.PurchasingDetailId];
                int spDetail = dictSparepartDetail[item.SparepartDetailId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.PurchaseReturnId = purchaseReturn;
                newItem.PurchasingDetailId = pDetail;
                newItem.SparepartDetailId = spDetail;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                contextDest.PurchaseReturnDetails.Add(newItem);
            }
            contextDest.SaveChanges();

            Console.Write("\nImporting table PurchaseReturnDetail done, " + PurchaseReturnDetailList.Count + " records imported");

            //sparepart detail
            Console.Write("\nImporting table SparepartDetail");

            foreach (var item in SparepartDetailList)
            {
                int itemOldId = item.Id;
                SparepartDetail newItem = new SparepartDetail();
                int sparepart = dictSparepart[item.SparepartId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.SparepartId = sparepart;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                if (item.PurchasingDetailId.HasValue && item.PurchasingDetailId != null && item.PurchasingDetailId > 0)
                {
                    int pDetail = dictPurchasingDetail[item.PurchasingDetailId.Value];
                    newItem.PurchasingDetailId = pDetail;
                }
                if (item.SparepartManualTransactionId.HasValue && item.SparepartManualTransactionId != null && item.SparepartManualTransactionId > 0)
                {
                    int spManualTrans = dictSpManualTrans[item.SparepartManualTransactionId.Value];
                    newItem.SparepartManualTransactionId = spManualTrans;
                }

                newItem.Code = item.Code;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                newItem = contextDest.SparepartDetails.Add(newItem);
                contextDest.SaveChanges();

                dictSparepartDetail.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table SparepartDetail done, " + SparepartDetailList.Count + " records imported");

            //special sparepart detail
            Console.Write("\nImporting table SpecialSparepartDetail");

            foreach (var item in SpecialSparepartDetailList)
            {
                int itemOldId = item.Id;
                SpecialSparepartDetail newItem = new SpecialSparepartDetail();
                int spDetail = dictSparepartDetail[item.SparepartDetailId];
                int ssp = dictSpecialSparepart[item.SpecialSparepartId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.SparepartDetailId = spDetail;
                newItem.SpecialSparepartId = ssp;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.CreateDate = item.CreateDate;
                newItem.Kilometers = item.Kilometers;
                newItem.ModifyDate = item.ModifyDate;
                newItem.SerialNumber = item.SerialNumber;
                newItem.Status = item.Status;
                newItem = contextDest.WheelDetails.Add(newItem);
                contextDest.SaveChanges();

                dictSpecialSparepartDetail.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table SpecialSparepartDetail done, " + SpecialSparepartDetailList.Count + " records imported");

            //vehicle wheel
            Console.Write("\nImporting table VehicleWheel");

            foreach (var item in VehicleWheelList)
            {
                VehicleWheel newItem = new VehicleWheel();
                int vehicle = dictVehicle[item.VehicleId];
                int sspDetail = dictSpecialSparepartDetail[item.WheelDetailId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.VehicleId = vehicle;
                newItem.WheelDetailId = sspDetail;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Notes = item.Notes;
                newItem.Status = item.Status;
                contextDest.VehicleWheels.Add(newItem);
            }
            contextDest.SaveChanges();

            Console.Write("\nImporting table VehicleWheel done, " + VehicleWheelList.Count + " records imported");

            //used good
            Console.Write("\nImporting table UsedGood");

            foreach (var item in UsedGoodList)
            {
                int itemOldId = item.Id;
                UsedGood newItem = new UsedGood();
                int sparepart = dictSparepart[item.SparepartId];

                newItem.Id = -1;
                newItem.SparepartId = sparepart;

                newItem.Stock = item.Stock;
                newItem.Status = item.Status;
                newItem = contextDest.UsedGoods.Add(newItem);
                contextDest.SaveChanges();

                dictUsedGood.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table UsedGood done, " + UsedGoodList.Count + " records imported");

            //used good trans
            Console.Write("\nImporting table UsedGoodTransaction");

            foreach (var item in UsedGoodTransactionList)
            {
                UsedGoodTransaction newItem = new UsedGoodTransaction();
                int type = dictReference[item.TypeReferenceId];
                int usedGood = dictUsedGood[item.UsedGoodId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.TypeReferenceId = type;
                newItem.UsedGoodId = usedGood;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.CreateDate = item.CreateDate;
                newItem.ItemPrice = item.ItemPrice;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Qty = item.Qty;
                newItem.Remark = item.Remark;
                newItem.TotalPrice = item.TotalPrice;
                newItem.TransactionDate = item.TransactionDate;
                contextDest.UsedGoodsTransactions.Add(newItem);
            }
            contextDest.SaveChanges();

            Console.Write("\nImporting table UsedGoodTransaction done, " + UsedGoodTransactionList.Count + " records imported");

            //guest book
            Console.Write("\nImporting table GuestBook");

            foreach (var item in GuestBookList)
            {
                GuestBook newItem = new GuestBook();
                int vehicle = dictVehicle[item.VehicleId];
                int userCreate = dictUser[item.CreateUserId];
                int userModified = dictUser[item.ModifyUserId];

                newItem.Id = -1;
                newItem.VehicleId = vehicle;
                newItem.CreateUserId = userCreate;
                newItem.ModifyUserId = userModified;

                newItem.CreateDate = item.CreateDate;
                newItem.Description = item.Description;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                contextDest.GuestBooks.Add(newItem);
            }
            contextDest.SaveChanges();

            Console.Write("\nImporting table GuestBook done, " + GuestBookList.Count + " records imported");

            //SPK
            Console.Write("\nImporting table SPK");

            foreach (var item in SPKList)
            {
                int itemOldId = item.Id;

                SPK newItem = new SPK();

                newItem.Id = -1;
                newItem.VehicleId = dictVehicle[item.VehicleId];
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];
                newItem.VehicleGroupId = dictVehicleGroup[item.VehicleGroupId];
                newItem.CategoryReferenceId = dictReference[item.CategoryReferenceId];

                if (item.SPKParentId > 0)
                {
                    newItem.SPKParentId = dictSPK[item.SPKParentId.Value];
                }

                newItem.Description = item.Description;
                newItem.Code = item.Code;
                newItem.isContractWork = item.isContractWork;
                newItem.Contractor = item.Contractor;
                newItem.ContractWorkFee = item.ContractWorkFee;
                newItem.DueDate = item.DueDate;
                newItem.Kilometers = item.Kilometers;
                newItem.StatusApprovalId = item.StatusApprovalId;
                newItem.StatusCompletedId = item.StatusCompletedId;
                newItem.StatusPrintId = item.StatusPrintId;
                newItem.StatusOverLimit = item.StatusOverLimit;
                newItem.Subtotal = item.Subtotal;
                newItem.TotalMechanicFee = item.TotalMechanicFee;
                newItem.TotalSparepartPrice = item.TotalSparepartPrice;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;

                SPK insertedSPK = contextDest.SPKs.Add(newItem);
                contextDest.SaveChanges();

                dictSPK.Add(itemOldId, insertedSPK.Id);
            }

            Console.Write("\nImporting table SPK done, " + SPKList.Count + " records imported");

            //spk detail sparepart
            Console.Write("\nImporting table SPKDetailSparepart");

            foreach (var item in SPKDetailSparepartList)
            {
                int itemOldId = item.Id;
                SPKDetailSparepart newItem = new SPKDetailSparepart();

                newItem.Id = -1;
                newItem.SparepartId = dictSparepart[item.SparepartId];
                newItem.SPKId = dictSPK[item.SPKId];
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.TotalPrice = item.TotalPrice;
                newItem.TotalQuantity = item.TotalQuantity;
                newItem.TotalPriceAfterCommission = item.TotalPriceAfterCommission;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                newItem = contextDest.SPKDetailSpareparts.Add(newItem);
                contextDest.SaveChanges();

                dictSPKDetailSparepart.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table SPKDetailSparepart done, " + SPKDetailSparepartList.Count + " records imported");

            //spk detail sparepart detail
            Console.Write("\nImporting table SPKDetailSparepartDetail");

            foreach (var item in SPKDetailSparepartDetailList)
            {
                int itemOldId = item.Id;
                SPKDetailSparepartDetail newItem = new SPKDetailSparepartDetail();

                newItem.Id = -1;
                newItem.SparepartDetailId = dictSparepartDetail[item.SparepartDetailId];
                newItem.SPKDetailSparepartId = dictSPKDetailSparepart[item.SPKDetailSparepartId];
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                newItem = contextDest.SPKDetailSparepartDetails.Add(newItem);
                contextDest.SaveChanges();

                dictSPKDetailSparepartDetail.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table SPKDetailSparepartDetail done, " + SPKDetailSparepartDetailList.Count + " records imported");

            //spk schedule
            Console.Write("\nImporting table SPKSchedule");

            foreach (var item in SPKScheduleList)
            {
                int itemOldId = item.Id;
                SPKSchedule newItem = new SPKSchedule();

                newItem.Id = -1;
                newItem.SPKId = dictSPK[item.SPKId];
                newItem.MechanicId = dictSPKDetailSparepart[item.MechanicId];
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.Description = item.Description;
                newItem.Date = item.Date;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                newItem = contextDest.SPKSchedules.Add(newItem);
                contextDest.SaveChanges();
            }

            Console.Write("\nImporting table SPKSchedule done, " + SPKScheduleList.Count + " records imported");

            //wheel exchange history
            Console.Write("\nImporting table WheelExchangeHistory");

            foreach (var item in WheelExchangeHistoryList)
            {
                int itemOldId = item.Id;
                WheelExchangeHistory newItem = new WheelExchangeHistory();

                newItem.Id = -1;
                newItem.SPKId = dictSPK[item.SPKId];
                newItem.OriginalWheelId = dictSpecialSparepartDetail[item.OriginalWheelId];
                newItem.ReplaceWheelId = dictSpecialSparepartDetail[item.ReplaceWheelId];
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;
                newItem = contextDest.WheelExchangeHistories.Add(newItem);
                contextDest.SaveChanges();
            }

            Console.Write("\nImporting table WheelExchangeHistory done, " + WheelExchangeHistoryList.Count + " records imported");

            //invoice
            Console.Write("\nImporting table Invoice");

            foreach (var item in InvoiceList)
            {
                int itemOldId = item.Id;
                Invoice newItem = new Invoice();

                newItem.Id = -1;
                newItem.SPKId = dictSPK[item.SPKId];
                newItem.PaymentMethodId = dictReference[item.PaymentMethodId];
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.Code = item.Code;
                newItem.TotalPrice = item.TotalPrice;
                newItem.TotalHasPaid = item.TotalHasPaid;
                newItem.TotalService = item.TotalService;
                newItem.TotalFeeService = item.TotalFeeService;
                newItem.TotalServicePlusFee = item.TotalServicePlusFee;
                newItem.TotalSparepart = item.TotalSparepart;
                newItem.TotalFeeSparepart = item.TotalFeeSparepart;
                newItem.TotalSparepartPlusFee = item.TotalSparepartPlusFee;
                newItem.TotalValueAdded = item.TotalValueAdded;
                newItem.TotalSparepartAndService = item.TotalSparepartAndService;
                newItem.PaymentStatus = item.PaymentStatus;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;

                Invoice insertedInvoice = contextDest.Invoices.Add(newItem);
                contextDest.SaveChanges();

                dictInvoice.Add(itemOldId, insertedInvoice.Id);
            }

            Console.Write("\nImporting table Invoice done, " + InvoiceList.Count + " records imported");

            //invoice detail
            Console.Write("\nImporting table InvoiceDetail");

            foreach (var item in InvoiceDetailList)
            {
                int itemOldId = item.Id;
                InvoiceDetail newItem = new InvoiceDetail();

                newItem.Id = -1;
                newItem.InvoiceId = dictInvoice[item.InvoiceId];
                newItem.SPKDetailSparepartDetailId = dictReference[item.SPKDetailSparepartDetailId];
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.FeePctg = item.FeePctg;
                newItem.SubTotalPrice = item.SubTotalPrice;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;

                newItem = contextDest.InvoiceDetails.Add(newItem);
                contextDest.SaveChanges();

                dictInvoiceDetail.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table InvoiceDetail done, " + InvoiceDetailList.Count + " records imported");

            //sales return
            Console.Write("\nImporting table SalesReturn");

            foreach (var item in SalesReturnList)
            {
                int itemOldId = item.Id;
                SalesReturn newItem = new SalesReturn();

                newItem.Id = -1;
                newItem.InvoiceId = dictInvoice[item.InvoiceId];
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.Code = item.Code;
                newItem.Date = item.Date;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;

                newItem = contextDest.SalesReturns.Add(newItem);
                contextDest.SaveChanges();

                dictSalesReturn.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table SalesReturn done, " + SalesReturnList.Count + " records imported");

            //sales return detail
            Console.Write("\nImporting table SalesReturnDetail");

            foreach (var item in SalesReturnDetailList)
            {
                int itemOldId = item.Id;
                SalesReturnDetail newItem = new SalesReturnDetail();

                newItem.Id = -1;
                newItem.SalesReturnId = dictSalesReturn[item.SalesReturnId];
                newItem.InvoiceDetailId = dictInvoiceDetail[item.InvoiceDetailId];
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;

                newItem = contextDest.SalesReturnDetails.Add(newItem);
                contextDest.SaveChanges();
            }

            Console.Write("\nImporting table SalesReturnDetail done, " + SalesReturnDetailList.Count + " records imported");

            //transaction
            Console.Write("\nImporting table Transaction");

            foreach (var item in TransactionList)
            {
                int itemOldId = item.Id;
                Transaction newItem = new Transaction();

                newItem.Id = -1;
                newItem.ReferenceTableId = dictReference[item.ReferenceTableId];
                newItem.PaymentMethodId = dictReference[item.PaymentMethodId.Value];
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.PrimaryKeyValue = item.PrimaryKeyValue;
                newItem.TotalTransaction = item.TotalTransaction;
                newItem.TotalPayment = item.TotalPayment;
                newItem.Description = item.Description;
                newItem.IsReconciliation = item.IsReconciliation;
                newItem.TransactionDate = item.TransactionDate;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;

                newItem = contextDest.Transactions.Add(newItem);
                contextDest.SaveChanges();

                dictTransaction.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table Transaction done, " + TransactionList.Count + " records imported");

            //transaction detail
            Console.Write("\nImporting table TransactionDetail");

            foreach (var item in TransactionDetailList)
            {
                int itemOldId = item.Id;

                TransactionDetail newItem = new TransactionDetail();

                newItem.Id = -1;
                newItem.JournalId = dictJournalMaster[item.JournalId];
                newItem.ParentId = dictTransaction[item.ParentId];
                //newItem.CreateUserId = dictUser[item.CreateUserId];
                //newItem.ModifyUserId = dictUser[item.ModifyUserId];

                //newItem.CreateDate = item.CreateDate;
                //newItem.ModifyDate = item.ModifyDate;
                //newItem.Status = item.Status;

                newItem = contextDest.TransactionDetails.Add(newItem);
                contextDest.SaveChanges();
            }

            Console.Write("\nImporting table TransactionDetail done, " + TransactionDetailList.Count + " records imported");

            //balance journal
            Console.Write("\nImporting table BalanceJournal");

            foreach (var item in BalanceJournalList)
            {
                int itemOldId = item.Id;
                BalanceJournal newItem = new BalanceJournal();

                newItem.Id = -1;
                newItem.CreateUserId = dictUser[item.CreateUserId];
                newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.Month = item.Month;
                newItem.Year = item.Year;
                newItem.IsFirst = item.IsFirst;
                newItem.CreateDate = item.CreateDate;
                newItem.ModifyDate = item.ModifyDate;
                newItem.Status = item.Status;

                newItem = contextDest.BalanceJournals.Add(newItem);
                contextDest.SaveChanges();

                dictBalanceJournal.Add(itemOldId, newItem.Id);
            }

            Console.Write("\nImporting table BalanceJournal done, " + BalanceJournalList.Count + " records imported");

            //balance journal detail
            Console.Write("\nImporting table BalanceJournalDetail");

            foreach (var item in BalanceJournalDetailList)
            {
                int itemOldId = item.Id;
                BalanceJournalDetail newItem = new BalanceJournalDetail();

                newItem.Id = -1;
                newItem.JournalId = dictJournalMaster[item.JournalId];
                newItem.ParentId = dictBalanceJournal[item.ParentId];
                //newItem.CreateUserId = dictUser[item.CreateUserId];
                //newItem.ModifyUserId = dictUser[item.ModifyUserId];

                newItem.FirstDebit = item.FirstDebit;
                newItem.FirstCredit = item.FirstCredit;
                newItem.MutationDebit = item.MutationDebit;
                newItem.MutationCredit = item.MutationCredit;
                newItem.BalanceAfterMutationDebit = item.BalanceAfterMutationDebit;
                newItem.BalanceAfterMutationCredit = item.BalanceAfterMutationCredit;
                newItem.ReconciliationDebit = item.ReconciliationDebit;
                newItem.ReconciliationCredit = item.ReconciliationCredit;
                newItem.BalanceAfterReconciliationDebit = item.BalanceAfterReconciliationDebit;
                newItem.BalanceAfterReconciliationCredit = item.BalanceAfterReconciliationCredit;
                newItem.ProfitLossDebit = item.ProfitLossDebit;
                newItem.ProfitLossCredit = item.ProfitLossCredit;
                newItem.LastDebit = item.LastDebit;
                newItem.LastCredit = item.LastCredit;
                //newItem.CreateDate = item.CreateDate;
                //newItem.ModifyDate = item.ModifyDate;
                //newItem.Status = item.Status;

                newItem = contextDest.BalanceJournalDetails.Add(newItem);
                contextDest.SaveChanges();
            }

            Console.Write("\nImporting table BalanceJournalDetail done, " + BalanceJournalDetailList.Count + " records imported");

            Console.Write("MOTHA F****N DONE!");
            Console.Read();
        }
        /// <summary>
        /// Fills a single instance with data based on its primary key values.
        /// </summary>
        public virtual void Fill(TransactionDetail transactiondetail, System.Int64 loanApplicationId)
        {
            // create the connection to use
            SqlConnection cnn = new SqlConnection(TransactionDetail.GetConnectionString());
            try
            {
                // discover the sql parameters
                SqlParameterHash sqlparams = SqlHelperParameterCache.GetSpParameterSet(TransactionDetail.GetConnectionString(), "gsp_SelectTransactionDetail");

                using (cnn)
                {
                    // open the connection
                    cnn.Open();

                    // set the parameters
                    sqlparams["@loanApplicationId"].Value = loanApplicationId;

                    // create an instance of the reader to fill.
                    SqlDataReader datareader = SqlHelper.ExecuteReader(cnn, "gsp_SelectTransactionDetail", sqlparams);

                    if (datareader.Read())
                        transactiondetail.SetMembers(ref datareader);

                    cnn.Close(); // close the connection
                }

                // nullify the connection var
                cnn = null;
            }
            catch (SqlException sqlex)
            {
                throw sqlex;
            }
        }
        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 UpdateInvoice(InvoiceViewModel invoice, List<InvoiceDetailViewModel> invoiceDetails, int userId)
        {
            using(var trans = _unitOfWork.BeginTransaction())
            {
                try
                {
                    DateTime serverTime = DateTime.Now;

                    Invoice entity = _invoiceRepository.GetById<int>(invoice.Id);
                    entity.PaymentMethodId = invoice.PaymentMethodId;
                    entity.TotalHasPaid = invoice.TotalHasPaid;
                    entity.TotalPrice = invoice.TotalPrice;

                    entity.TotalService = invoice.TotalService;
                    entity.TotalFeeService = invoice.TotalFeeService;
                    entity.TotalServicePlusFee = invoice.TotalServicePlusFee;
                    entity.TotalSparepart = invoice.TotalSparepart;
                    entity.TotalFeeSparepart = invoice.TotalFeeSparepart;
                    entity.TotalSparepartPlusFee = invoice.TotalSparepartPlusFee;
                    entity.TotalSparepartAndService = invoice.TotalSparepartAndService;
                    entity.TotalValueAdded = invoice.TotalValueAdded;

                    //Map(invoice, entity);
                    entity.ModifyDate = serverTime;
                    entity.ModifyUserId = userId;
                    entity.Status = (int)DbConstant.InvoiceStatus.NotPrinted;

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

                    _invoiceRepository.AttachNavigation(entity.CreateUser); // yang inherit ke base modifier harus ada ini, klo gak user e dobel2
                    _invoiceRepository.AttachNavigation(entity.ModifyUser); // yang inherit ke base modifier harus ada ini, klo gak user e dobel2
                    _invoiceRepository.AttachNavigation(entity.SPK);
                    _invoiceRepository.AttachNavigation(entity.PaymentMethod);

                    _invoiceRepository.Update(entity);
                    _unitOfWork.SaveChanges();

                    foreach (var invoiceDetail in invoiceDetails)
                    {
                        InvoiceDetail entityDetail = _invoiceDetailRepository.GetById<int>(invoiceDetail.Id);
                        entityDetail.FeePctg = invoiceDetail.FeePctg;
                        entityDetail.SubTotalPrice = invoiceDetail.SubTotalPrice;
                        //Map(invoiceDetail, entityDetail);

                        entityDetail.ModifyDate = serverTime;
                        entityDetail.ModifyUserId = userId;

                        _invoiceDetailRepository.AttachNavigation(entityDetail.CreateUser);
                        _invoiceDetailRepository.AttachNavigation(entityDetail.ModifyUser);
                        _invoiceDetailRepository.AttachNavigation(entityDetail.Invoice);
                        _invoiceDetailRepository.AttachNavigation(entityDetail.SPKDetailSparepartDetail);
                        _invoiceDetailRepository.Update(entityDetail);
                    }
                    _unitOfWork.SaveChanges();

                    Reference transactionReferenceTable = _referenceRepository.GetMany(c => c.Code == DbConstant.REF_TRANSTBL_INVOICE).FirstOrDefault();
                    Transaction transaction = _transactionRepository.GetMany(x =>x.ReferenceTableId == transactionReferenceTable.Id &&
                        x.PrimaryKeyValue == invoice.Id).OrderBy(x => x.CreateDate).FirstOrDefault();
                    Reference paymentMethod = _referenceRepository.GetById(invoice.PaymentMethodId);

                    if (transaction != null)
                    {
                        transaction.ModifyDate = serverTime;
                        transaction.ModifyUserId = userId;
                        transaction.TotalTransaction = invoice.TotalPrice.AsDouble();
                        transaction.TotalPayment = invoice.TotalHasPaid.AsDouble();
                        transaction.PaymentMethodId = invoice.PaymentMethodId;
                        _transactionRepository.AttachNavigation(transaction.CreateUser);
                        _transactionRepository.AttachNavigation(transaction.ModifyUser);
                        _transactionRepository.AttachNavigation(transaction.ReferenceTable);
                        _transactionRepository.AttachNavigation(transaction.PaymentMethod);
                        _transactionRepository.Update(transaction);
                        _unitOfWork.SaveChanges();

                        List<TransactionDetail> transactionDetails = _transactionDetailRepository.GetMany(x => x.ParentId == transaction.Id).ToList();
                        foreach (TransactionDetail transactionDetail in transactionDetails)
                        {
                            _transactionDetailRepository.Delete(transactionDetail);
                        }
                        _unitOfWork.SaveChanges();
                    }
                    else
                    {
                        transaction = new Transaction();
                        transaction.CreateDate = serverTime;
                        transaction.CreateUserId = userId;
                        transaction.ModifyDate = serverTime;
                        transaction.ModifyUserId = userId;
                        transaction.Description = "pembayaran invoice";
                        transaction.TotalTransaction = invoice.TotalPrice.AsDouble();
                        transaction.TotalPayment = invoice.TotalHasPaid.AsDouble();
                        transaction.ReferenceTableId = transactionReferenceTable.Id;
                        transaction.PrimaryKeyValue = invoice.Id;
                        transaction.TransactionDate = serverTime;
                        transaction.PaymentMethodId = invoice.PaymentMethodId;
                        transaction.Status = (int)DbConstant.DefaultDataStatus.Active;

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

                    switch (paymentMethod.Code)
                    {
                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_EKONOMI:
                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_BCA1:
                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_BCA2:
                            {
                                // Bank Debet --> Karena bertmbah
                                TransactionDetail detailBank = new TransactionDetail();
                                detailBank.Debit = invoice.TotalHasPaid;
                                if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_EKONOMI)
                                {
                                    detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.01").FirstOrDefault().Id;
                                }
                                else if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_BCA1)
                                {
                                    detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.02").FirstOrDefault().Id;
                                }
                                else if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_BANK_BCA2)
                                {
                                    detailBank.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.03").FirstOrDefault().Id;
                                }
                                detailBank.ParentId = transaction.Id;

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

                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_KAS:
                            // Kas Debit --> Karena bertambah
                            TransactionDetail detailKas = new TransactionDetail();
                            detailKas.Debit = invoice.TotalHasPaid;
                            detailKas.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.01.01").FirstOrDefault().Id;
                            detailKas.ParentId = transaction.Id;

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

                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_KAS:
                            // Kas Debit --> Karena bertambah
                            TransactionDetail detailKasKarenaUangMuka = new TransactionDetail();
                            detailKasKarenaUangMuka.Debit = invoice.TotalHasPaid;
                            detailKasKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.01.01").FirstOrDefault().Id;
                            detailKasKarenaUangMuka.ParentId = transaction.Id;

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

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

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

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

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

                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_EKONOMI:
                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA1:
                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA2:
                            {
                                // Bank Debit --> Karena bertambah
                                TransactionDetail detailBankKarenaUangMuka = new TransactionDetail();
                                detailBankKarenaUangMuka.Debit = invoice.TotalHasPaid;
                                if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_EKONOMI)
                                {
                                    detailBankKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.01").FirstOrDefault().Id;
                                }
                                else if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA1)
                                {
                                    detailBankKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.02").FirstOrDefault().Id;
                                }
                                else if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA2)
                                {
                                    detailBankKarenaUangMuka.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.02.03").FirstOrDefault().Id;
                                }
                                detailBankKarenaUangMuka.ParentId = transaction.Id;

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

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

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

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

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

                        case DbConstant.REF_INVOICE_PAYMENTMETHOD_PIUTANG:
                            TransactionDetail piutang = new TransactionDetail();
                            piutang.Debit = invoice.TotalPrice - invoice.TotalHasPaid;
                            piutang.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.03.01.01").FirstOrDefault().Id;
                            piutang.ParentId = transaction.Id;

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

                    if (paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_EKONOMI ||
                        paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA1 ||
                        paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_BANK_BCA2 ||
                       paymentMethod.Code == DbConstant.REF_INVOICE_PAYMENTMETHOD_UANGMUKA_KAS)
                    {
                        if (invoice.TotalPrice > invoice.TotalHasPaid)
                        {
                            // Piutang Debit --> Karena bertambah
                            TransactionDetail piutang = new TransactionDetail();
                            piutang.Debit = invoice.TotalPrice - invoice.TotalHasPaid;
                            piutang.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.03.01.01").FirstOrDefault().Id;
                            piutang.Parent = transaction;

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

                    // Sales Kredit --> Karena berkurang
                    TransactionDetail sales = new TransactionDetail();
                    sales.Credit = invoice.TotalSparepartAndService;
                    sales.JournalId = _journalMasterRepository.GetMany(j => j.Code == "3.01.01").FirstOrDefault().Id;
                    sales.ParentId = transaction.Id;

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

                    // Service Income Kredit --> Karena berkurang
                    TransactionDetail serviceIncome = new TransactionDetail();
                    serviceIncome.Credit = invoice.TotalValueAdded + invoice.TotalFeeSparepart;
                    serviceIncome.JournalId = _journalMasterRepository.GetMany(j => j.Code == "3.01.04").FirstOrDefault().Id;
                    serviceIncome.ParentId = transaction.Id;

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

                    // HPP Sparepart Debit --> Karena bertambah
                    TransactionDetail hppSparepart = new TransactionDetail();
                    hppSparepart.Debit = invoice.TotalSparepartPlusFee;
                    hppSparepart.JournalId = _journalMasterRepository.GetMany(j => j.Code == "3.04.01").FirstOrDefault().Id;
                    hppSparepart.ParentId = transaction.Id;

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

                    if(invoice.TotalServicePlusFee > 0)
                    {
                        if (entity.SPK.isContractWork)
                        {
                            // HPP Tukang Harian Debit --> Karena bertambah
                            TransactionDetail hppTukang = new TransactionDetail();
                            hppTukang.Debit = invoice.TotalServicePlusFee;
                            hppTukang.JournalId = _journalMasterRepository.GetMany(j => j.Code == "3.04.05").FirstOrDefault().Id;
                            hppTukang.ParentId = transaction.Id;

                            _transactionDetailRepository.AttachNavigation(hppTukang.Journal);
                            _transactionDetailRepository.AttachNavigation(hppTukang.Parent);
                            _transactionDetailRepository.Add(hppTukang);
                        }
                        else
                        {
                            // HPP Tukang Borongan Debit --> Karena bertambah
                            TransactionDetail hppTukang = new TransactionDetail();
                            hppTukang.Debit = invoice.TotalServicePlusFee;
                            hppTukang.JournalId = _journalMasterRepository.GetMany(j => j.Code == "3.04.04").FirstOrDefault().Id;
                            hppTukang.ParentId = transaction.Id;

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

                    // Sparepart Kredit --> Karena berkurang
                    TransactionDetail detailSparepart = new TransactionDetail();
                    detailSparepart.Credit = invoice.TotalSparepart;
                    detailSparepart.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.04.01").FirstOrDefault().Id;
                    detailSparepart.ParentId = transaction.Id;

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

                    if (invoice.TotalServicePlusFee > 0)
                    {
                        // SDM Kredit --> Karena berkurang
                        TransactionDetail detailSDM = new TransactionDetail();
                        detailSDM.Credit = invoice.TotalServicePlusFee;
                        detailSDM.JournalId = _journalMasterRepository.GetMany(j => j.Code == "1.01.04.04").FirstOrDefault().Id;
                        detailSDM.ParentId = transaction.Id;

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

                    _unitOfWork.SaveChanges();

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