public static void AddSalesReturnTransactionToDatabase(SalesReturnTransaction salesReturnTransaction)
        {
            IsLastSaveSuccessful = false;

            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();

                AttachSalesReturnTransactionPropertiesToDatabaseContext(context, ref salesReturnTransaction);

                var lines = salesReturnTransaction.SalesReturnTransactionLines.ToList();
                salesReturnTransaction.SalesReturnTransactionLines.Clear();
                foreach (var salesReturnTransactionLine in lines)
                {
                    salesReturnTransactionLine.SalesReturnTransaction = salesReturnTransaction;
                    AddSalesReturnTransactionLineToDatabaseContext(context, salesReturnTransactionLine);
                    DecreaseSalesReturnTransactionLineItemSoldOrReturnedInDatabaseContext(context,
                        salesReturnTransactionLine);
                    InceaseSalesReturnTransactionLineItemStockInDatabaseContext(context, salesReturnTransactionLine);
                    context.SaveChanges();
                }

                AddSalesReturnTransactionLedgerTransactionsToDatabaseContext(context, salesReturnTransaction);
                // Deduct member's points
                ts.Complete();
            }

            IsLastSaveSuccessful = true;
        }
Ejemplo n.º 2
0
        public void Close(BackgroundWorker worker)
        {
            using (var context = new ERPContext())
            {
                var items = context.Inventory.ToList();

                var index = 1;
                foreach (var item in items)
                {
                    foreach (var warehouse in _warehouses)
                    {
                        var beginningBalance = GetBeginningBalance(context, warehouse, item);
                        var endingBalance = GetEndingBalance(context, warehouse, item, beginningBalance);
                        SetEndingBalance(context, warehouse, item, endingBalance);
                    }

                    var status = index++ * (items.Count / 100) - 1;
                    if (status < 0) status = 0;
                    worker.ReportProgress(status);
                }

                context.SaveChanges();
            }

            MessageBox.Show("Successfully closed stock!", "Succecss", MessageBoxButton.OK);
        }
        public static void AddPurchaseReturnTransactionToDatabase(PurchaseReturnTransaction purchaseReturnTransaction)
        {
            IsLastSaveSuccessful = false;

            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();
                AttachPurchaseReturnTransactionPropertiesToDatabaseContext(context, ref purchaseReturnTransaction);
                purchaseReturnTransaction.PurchaseTransaction.Supplier.PurchaseReturnCredits +=
                    purchaseReturnTransaction.NetTotal;

                decimal totalCOGS = 0;
                var lines = purchaseReturnTransaction.PurchaseReturnTransactionLines.ToList();
                purchaseReturnTransaction.PurchaseReturnTransactionLines.Clear();
                foreach (var purchaseReturnTransactionLine in lines)
                {
                    if (!IsThereEnoughLineItemStockInDatabaseContext(context, purchaseReturnTransactionLine)) return;
                    purchaseReturnTransactionLine.PurchaseReturnTransaction = purchaseReturnTransaction;
                    AddPurchaseReturnTransactionLineToDatabaseContext(context, purchaseReturnTransactionLine);
                    DecreasePurchaseReturnTransactionLineItemStockInDatabaseContext(context, purchaseReturnTransactionLine);
                    totalCOGS += CalculateLineCOGSFromDatabaseContext(context, purchaseReturnTransactionLine);
                    IncreasePurchaseReturnTransactionLineItemSoldOrReturnedInDatabaseContext(context, purchaseReturnTransactionLine);
                    context.SaveChanges();
                }

                AddPurchaseReturnTransactionLedgerTransactionToDatabaseContext(context, purchaseReturnTransaction, totalCOGS);
                ts.Complete();
            }

            IsLastSaveSuccessful = true;
        }
Ejemplo n.º 4
0
 public static void AddCustomerAlongWithItsLedgerToDatabase(Customer customer)
 {
     using (var context = new ERPContext())
     {
         context.Customers.Add(customer);
         context.SaveChanges();
     }
 }
Ejemplo n.º 5
0
 public static void ActivateItemInDatabase(Item item)
 {
     using (var context = new ERPContext())
     {
         context.Entry(item).State = EntityState.Modified;
         item.IsActive = true;
         context.SaveChanges();
     }
 }
Ejemplo n.º 6
0
        public bool CreateEmployee(Employee model)
        {
            ERPContext db = new ERPContext();

            db.employees.Add(model);
            db.SaveChanges();
            return(true);

            ;
        }
Ejemplo n.º 7
0
        private TblVoucherMaster AddVoucherMaster(ERPContext context, TblPurchaseInvoice purchaseinvoice, TblBranch branch, decimal?voucherTypeId, string paymentType)
        {
            try
            {
                var _voucherMaster = new TblVoucherMaster();
                _voucherMaster.BranchCode        = purchaseinvoice.BranchCode;
                _voucherMaster.BranchName        = branch.BranchName;
                _voucherMaster.VoucherDate       = purchaseinvoice.PurchaseInvDate;
                _voucherMaster.VoucherTypeIdMain = voucherTypeId;
                _voucherMaster.VoucherTypeIdSub  = 35;
                _voucherMaster.VoucherNo         = purchaseinvoice.PurchaseInvNo;
                _voucherMaster.Amount            = purchaseinvoice.GrandTotal;
                _voucherMaster.PaymentType       = paymentType;//accountLedger.CrOrD
                _voucherMaster.Narration         = "Purchase Invoice";
                _voucherMaster.ServerDate        = DateTime.Now;
                _voucherMaster.UserId            = purchaseinvoice.UserId;
                _voucherMaster.UserName          = purchaseinvoice.UserName;
                _voucherMaster.EmployeeId        = -1;

                context.TblVoucherMaster.Add(_voucherMaster);
                if (context.SaveChanges() > 0)
                {
                    return(_voucherMaster);
                }
                #region comment
                //var _voucherMaster = new TblVoucherMaster();
                //_voucherMaster.BranchCode = invoice.BranchCode;
                //_voucherMaster.BranchName = _branch.BranchName;
                //_voucherMaster.VoucherDate = invoice.InvoiceDate;
                //_voucherMaster.VoucherTypeIdMain = _vouchertType.VoucherTypeId;
                //_voucherMaster.VoucherTypeIdSub = 35;
                //_voucherMaster.VoucherNo = invoice.InvoiceNo;
                //_voucherMaster.Amount  = invoice.GrandTotal;
                //_voucherMaster.PaymentType = _accountLedger.CrOrDr;
                //_voucherMaster.Narration = "Sales Invoice";
                //_voucherMaster.ServerDate = DateTime.Now;
                //_voucherMaster.UserId = invoice.UserId;
                //_voucherMaster.UserName = invoice.UserName;
                //_voucherMaster.EmployeeId = -1;

                //repo.TblVoucherMaster.Add(_voucherMaster);
                //if(!(repo.SaveChanges() > 0))
                //{
                //    dbTransaction.Rollback();
                //    return false;
                //}
                #endregion

                return(null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 8
0
        private static void RecordEditedPurchaseTransactionTotalCOGSChangedLedgerTransactionInDatabaseContext(
            ERPContext context, PurchaseTransaction editedPurchaseTransaction, decimal totalCOGSChanged)
        {
            var purchaseTransactionTotalCOGSChangedLedgerTransaction = new LedgerTransaction();

            LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, UtilityMethods.GetCurrentDate().Date, editedPurchaseTransaction.PurchaseID, "Purchase Transaction Adjustment (COGS)");
            context.SaveChanges();

            if (totalCOGSChanged > 0)
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Cost of Goods Sold", "Debit", totalCOGSChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Inventory", "Credit", totalCOGSChanged);
            }
            else
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Inventory", "Debit", -totalCOGSChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Cost of Goods Sold", "Credit", -totalCOGSChanged);
            }
            context.SaveChanges();
        }
Ejemplo n.º 9
0
        public IHttpActionResult Post([FromBody] Daily model)
        {
            _db = new ERPContext();



            model.TotalAmount = 0;


            if (ModelState.IsValid)
            {
                if (model.Id == 0)
                {
                    model.Open        = true;
                    model.CreatedDate = DateTime.UtcNow;
                    _db.Dailies.Add(model);
                    _db.SaveChanges();
                    var filePath =
                        HttpContext.Current.Server.MapPath("~/Uploads/DailyFiles/Daily-" + model.Id);
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                }
                else
                {
                    var daily = _db.Dailies.Find(model.Id);
                    if (daily != null)
                    {
                        daily.Open            = model.Open;
                        daily.Name            = model.Name;
                        daily.ClosedDate      = model.ClosedDate;
                        daily.CheckGP         = model.CheckGP;
                        daily.DailyDay        = model.DailyDay;
                        daily.ExpensessTypeId = model.ExpensessTypeId;
                        _db.SaveChanges();
                    }
                }
            }
            return(Ok(new { msg = "success" }));
        }
Ejemplo n.º 10
0
        private static void SetPurchaseTransactionInDatabaseContextToEditedPurchaseTransactionProperties(ERPContext context, PurchaseTransaction editedPurchaseTransaction)
        {
            var transactionFromDatabase = context.PurchaseTransactions
                                          .Include("Supplier")
                                          .Include("PurchaseTransactionLines")
                                          .Include("PurchaseTransactionLines.Item")
                                          .Include("PurchaseTransactionLines.Warehouse")
                                          .Single(e => e.PurchaseID.Equals(editedPurchaseTransaction.PurchaseID));

            transactionFromDatabase.Date       = editedPurchaseTransaction.Date;
            transactionFromDatabase.DueDate    = editedPurchaseTransaction.DueDate;
            transactionFromDatabase.DOID       = editedPurchaseTransaction.DOID;
            transactionFromDatabase.Note       = editedPurchaseTransaction.Note;
            transactionFromDatabase.Tax        = editedPurchaseTransaction.Tax;
            transactionFromDatabase.GrossTotal = editedPurchaseTransaction.GrossTotal;
            transactionFromDatabase.Discount   = editedPurchaseTransaction.Discount;
            transactionFromDatabase.Total      = editedPurchaseTransaction.Total;
            var currentUser = Application.Current.TryFindResource("CurrentUser") as User;

            if (currentUser != null)
            {
                transactionFromDatabase.User = context.Users.Single(user => user.Username.Equals(currentUser.Username));
            }

            foreach (var line in transactionFromDatabase.PurchaseTransactionLines.ToList())
            {
                context.PurchaseTransactionLines.Remove(line);
                context.SaveChanges();
            }

            foreach (var editedLine in editedPurchaseTransaction.PurchaseTransactionLines)
            {
                editedLine.PurchaseTransaction = transactionFromDatabase;
                editedLine.Item      = context.Inventory.Single(item => item.ID.Equals(editedLine.Item.ID));
                editedLine.Warehouse = context.Warehouses.Single(warehouse => warehouse.ID.Equals(editedLine.Warehouse.ID));
                context.PurchaseTransactionLines.Add(editedLine);
                context.SaveChanges();
            }

            context.SaveChanges();
        }
Ejemplo n.º 11
0
        private static void AttachPurchaseTransactionPropertiesToDatabaseContext(ERPContext context, PurchaseTransaction purchaseTransaction)
        {
            purchaseTransaction.Supplier = context.Suppliers.Single(supplier => supplier.ID.Equals(purchaseTransaction.Supplier.ID));
            var currentUser = Application.Current.TryFindResource("CurrentUser") as User;

            if (currentUser != null)
            {
                purchaseTransaction.User = context.Users.Single(user => user.Username.Equals(currentUser.Username));
            }
            context.PurchaseTransactions.Add(purchaseTransaction);
            context.SaveChanges();
        }
Ejemplo n.º 12
0
        public SaveResult Complete()
        {
            SaveResult SaveResult = new SaveResult {
            };

            SaveResult.Result       = 0;
            SaveResult.ErrorMessage = string.Empty;

            try
            {
                SaveResult.Result = _context.SaveChanges();   //attempt to save changes to DB
                SaveResult.Result = 1;                        //if success set to 1
                return(SaveResult);
            }
            catch (DbEntityValidationException e)             //if fails record the error message
            {
                foreach (var error in e.EntityValidationErrors)
                {
                    System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                                       error.Entry.Entity.GetType().Name, error.Entry.State);
                    foreach (var validation_error in error.ValidationErrors)
                    {
                        System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                                           validation_error.PropertyName, validation_error.ErrorMessage);
                    }
                }
                SaveResult.ErrorMessage = e.Message;
                return(SaveResult);
            }
            catch (DbUpdateException e)
            {
                System.Diagnostics.Debug.WriteLine(e.InnerException);

                System.Data.Entity.Core.UpdateException update_error = (System.Data.Entity.Core.UpdateException)e.InnerException;
                System.Data.SqlClient.SqlException      error        = (System.Data.SqlClient.SqlException)update_error.InnerException;

                SaveResult.ErrorMessage = error.Message;
                return(SaveResult);
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                SaveResult.ErrorMessage = e.Message;
                return(SaveResult);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                SaveResult.ErrorMessage = e.Message;
                return(SaveResult);
            }
        }
Ejemplo n.º 13
0
        private static void AddStockAdjustmentDecrementLedgerTransactionToDatabase(ERPContext context, StockAdjustmentTransaction stockAdjustmentTransaction, decimal totalCOGSAdjustment)
        {
            var ledgerTransaction = new LedgerTransaction();

            if (!LedgerTransactionHelper.AddTransactionToDatabase(context, ledgerTransaction, UtilityMethods.GetCurrentDate().Date,
                                                                  stockAdjustmentTransaction.StockAdjustmentTransactionID, "Stock Adjustment (Decrement)"))
            {
                return;
            }
            context.SaveChanges();
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, ledgerTransaction, "Cost of Goods Sold", "Debit", totalCOGSAdjustment);
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, ledgerTransaction, "Inventory", "Credit", totalCOGSAdjustment);
        }
        private static void AddSalesReturnTransactionLedgerTransactionsToDatabaseContext(ERPContext context,
                                                                                         SalesReturnTransaction salesReturnTransaction)
        {
            var totalCOGS =
                salesReturnTransaction.SalesReturnTransactionLines.ToList()
                .Sum(salesReturnTransactionLine => salesReturnTransactionLine.CostOfGoodsSold);

            // Record the corresponding ledger transactions in the database
            var ledgerTransaction1 = new LedgerTransaction();
            var ledgerTransaction2 = new LedgerTransaction();

            if (
                !LedgerTransactionHelper.AddTransactionToDatabase(context, ledgerTransaction1,
                                                                  UtilityMethods.GetCurrentDate().Date, salesReturnTransaction.SalesReturnTransactionID,
                                                                  "Sales Return"))
            {
                return;
            }
            context.SaveChanges();
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, ledgerTransaction1,
                                                                 "Sales Returns and Allowances", "Debit", salesReturnTransaction.NetTotal);
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, ledgerTransaction1,
                                                                 "Cash", "Credit", salesReturnTransaction.NetTotal);

            if (
                !LedgerTransactionHelper.AddTransactionToDatabase(context, ledgerTransaction2,
                                                                  UtilityMethods.GetCurrentDate().Date, salesReturnTransaction.SalesReturnTransactionID,
                                                                  "Sales Return"))
            {
                return;
            }
            context.SaveChanges();
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, ledgerTransaction2, "Inventory", "Debit",
                                                                 totalCOGS);
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, ledgerTransaction2, "Cost of Goods Sold",
                                                                 "Credit", totalCOGS);

            context.SaveChanges();
        }
Ejemplo n.º 15
0
        private TblStockInformation AddStockInformation(ERPContext context, TblPurchaseInvoice invoice, TblBranch _branch, TblProduct _product, decimal?qty, decimal?rate)
        {
            try
            {
                //using(ERPContext context=new ERPContext())
                //{
                var _stockInformation = new TblStockInformation();

                _stockInformation.BranchId      = _branch.BranchId;
                _stockInformation.BranchCode    = _branch.BranchCode;
                _stockInformation.ShiftId       = invoice.ShiftId;
                _stockInformation.VoucherNo     = invoice.VoucherNo;
                _stockInformation.VoucherTypeId = invoice.VoucherTypeId;
                _stockInformation.InvoiceNo     = invoice.PurchaseInvNo;
                _stockInformation.ProductId     = _product.ProductId;
                _stockInformation.ProductCode   = _product.ProductCode;
                _stockInformation.InwardQty     = qty;
                _stockInformation.Rate          = rate;

                context.TblStockInformation.Add(_stockInformation);
                if (context.SaveChanges() > 0)
                {
                    return(_stockInformation);
                }

                #region Comment
                //var _stockInformation = new TblStockInformation();

                //_stockInformation.BranchId = _branch.BranchId;
                //_stockInformation.BranchCode = _branch.BranchCode;
                //_stockInformation.ShiftId = invoice.ShiftId;
                //_stockInformation.VoucherNo = invoice.VoucherNo;
                //_stockInformation.VoucherTypeId = invoice.VoucherTypeId;
                //_stockInformation.InvoiceNo = invoice.InvoiceNo;
                //_stockInformation.ProductId = _product.ProductId;
                //_stockInformation.ProductCode = _product.ProductCode;
                //_stockInformation.OutwardQty = invdtl.Qty > 0 ? invdtl.Qty : invdtl.FQty;
                //_stockInformation.Rate = invdtl.Rate;

                //repo.TblStockInformation.Add(_stockInformation);
                //repo.SaveChanges();
                #endregion

                return(null);
                //  }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 internal ErpUser GetByLogin(ErpUser erpUser)
 {
     using (var _dbContext = new ERPContext())
     {
         var userModel = _dbContext.ErpUsers.FirstOrDefault(p => p.Username == erpUser.Username && p.Password == erpUser.Password);
         if (userModel != null)
         {
             userModel.Token         = Guid.NewGuid();
             userModel.LastLoginDate = DateTime.Now;
             _dbContext.SaveChanges();
         }
         return(userModel);
     }
 }
Ejemplo n.º 17
0
        public TblAccountLedgerTransactions AddAccountLedgerTransactions(ERPContext context, TblBankReceiptMaster bankReceiptMaster, TblVoucherDetail _voucherDetail, DateTime?invoiceDate, bool isdebit = true)
        {
            try
            {
                var _accountLedgerTransactions = new TblAccountLedgerTransactions
                {
                    BranchId        = _voucherDetail.BranchId,
                    BranchCode      = _voucherDetail.BranchCode,
                    BranchName      = _voucherDetail.BranchName,
                    TransactionDate = invoiceDate,
                    // _accountLedgerTransactions.TransactionType = _voucherDetail.TransactionType;
                    VoucherAmount = _voucherDetail.Amount
                };
                if (isdebit == true)
                {
                    _accountLedgerTransactions.VoucherDetailId = _voucherDetail.VoucherDetailId;
                    _accountLedgerTransactions.LedgerId        = _voucherDetail.ToLedgerId;
                    _accountLedgerTransactions.LedgerCode      = _voucherDetail.ToLedgerCode;
                    _accountLedgerTransactions.LedgerName      = _voucherDetail.ToLedgerName;
                    _accountLedgerTransactions.TransactionType = _voucherDetail.TransactionType;
                    _accountLedgerTransactions.DebitAmount     = _accountLedgerTransactions.VoucherAmount;
                    _accountLedgerTransactions.CreditAmount    = Convert.ToDecimal("0.00");
                }
                else
                {
                    _accountLedgerTransactions.VoucherDetailId = _voucherDetail.VoucherDetailId;
                    _accountLedgerTransactions.LedgerId        = bankReceiptMaster.BankLedgerId;
                    _accountLedgerTransactions.LedgerCode      = bankReceiptMaster.BankLedgerCode;
                    _accountLedgerTransactions.LedgerName      = bankReceiptMaster.BankLedgerName;
                    _accountLedgerTransactions.TransactionType = "Credit";
                    _accountLedgerTransactions.CreditAmount    = _accountLedgerTransactions.VoucherAmount;
                    _accountLedgerTransactions.DebitAmount     = Convert.ToDecimal("0.00");
                }


                context.TblAccountLedgerTransactions.Add(_accountLedgerTransactions);
                if (context.SaveChanges() > 0)
                {
                    return(_accountLedgerTransactions);
                }


                return(null);
                //  }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 18
0
        public void Cadastrar(UsuarioDTO NovoUsuario)
        {
            Usuario Usuario = new Usuario(NovoUsuario);

            if (contexto.Usuarios.Select(x => x.Email == NovoUsuario.Email || x.CPF == NovoUsuario.CPF).Count() > 0)
            {
                throw new Exception("O Email ou o CPF já estão cadastrados.");
            }
            else
            {
                contexto.Usuarios.Add(Usuario);
                contexto.SaveChanges();
            }
        }
Ejemplo n.º 19
0
 public void Add(TEntity entity)
 {
     if (entity == null)
     {
         throw new ArgumentNullException("entity");
     }
     _entities.Add(entity);
     _context.SaveChanges();
 }
Ejemplo n.º 20
0
        private static void CloseRevenueOrExpenseAccountToRetainedEarnings(LedgerAccount account, ERPContext context)
        {
            var retainedEarnings = context.Ledger_Accounts
                                   .Include("LedgerGeneral")
                                   .Include("LedgerAccountBalances")
                                   .Include("LedgerTransactionLines")
                                   .Single(e => e.Name.Equals("Retained Earnings"));

            if (account.Class.Equals("Expense"))
            {
                var amount      = account.LedgerGeneral.Debit - account.LedgerGeneral.Credit;
                var transaction = new LedgerTransaction();

                LedgerTransactionHelper.AddTransactionToDatabase(context, transaction, UtilityMethods.GetCurrentDate().Date, "Closing Entry", account.Name);
                context.SaveChanges();
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, transaction, account.Name, "Credit", amount);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, transaction, retainedEarnings.Name, "Debit", amount);

                account.LedgerGeneral.Credit -= amount;
            }

            else if (account.Class.Equals("Revenue"))
            {
                var amount      = account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                var transaction = new LedgerTransaction();

                if (!LedgerTransactionHelper.AddTransactionToDatabase(context, transaction, UtilityMethods.GetCurrentDate().Date, "Closing Entry", account.Name))
                {
                    return;
                }
                context.SaveChanges();
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, transaction, account.Name, "Debit", amount);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, transaction, retainedEarnings.Name, "Credit", amount);

                account.LedgerGeneral.Debit -= amount;
            }
        }
Ejemplo n.º 21
0
 public void UpdateInventory(int warehouseId, string sku, int quantity)
 {
     using (ERPContext context = new ERPContext(m_connectionString))
     {
         var q = from ebayOnHandle in context.EbayOnhandle
                 where ebayOnHandle.GoodsSn == sku
                 where ebayOnHandle.StoreId == warehouseId
                 select ebayOnHandle;
         if (q.Count() == 1)
         {
             q.First().GoodsCount = quantity;
             context.SaveChanges();
         }
     }
 }
Ejemplo n.º 22
0
        private static void RecordEditedPurchaseTransactionNetTotalChangedLedgerTransactionInDatabaseContext(ERPContext context, PurchaseTransaction editedPurchaseTransaction, decimal valueChanged)
        {
            var purchaseTransactionNetTotalChangedLedgerTransaction = new LedgerTransaction();

            LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction,
                                                             UtilityMethods.GetCurrentDate().Date, editedPurchaseTransaction.PurchaseID, "Purchase Transaction Adjustment");
            context.SaveChanges();

            if (valueChanged > 0)
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction, "Inventory",
                                                                     "Debit", valueChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction,
                                                                     $"{editedPurchaseTransaction.Supplier.Name} Accounts Payable", "Credit", valueChanged);
            }
            else
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction,
                                                                     $"{editedPurchaseTransaction.Supplier.Name} Accounts Payable", "Debit", -valueChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction, "Inventory",
                                                                     "Credit", -valueChanged);
            }
            context.SaveChanges();
        }
Ejemplo n.º 23
0
        public static void AddStockAdjustmentTransactionToDatabase(StockAdjustmentTransaction stockAdjustmentTransaction)
        {
            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();
                var stockAdjustmentPurchaseTransaction = MakeNewstockAdjustmentPurchaseTransaction(context, stockAdjustmentTransaction);

                decimal totalCOGSAdjustment = 0;

                var isThereDecreaseAdjustmentLine = false;
                var isThereIncreaseAdjustmentLine = false;

                foreach (var line in stockAdjustmentTransaction.AdjustStockTransactionLines)
                {
                    AttachLineToDatabaseContext(context, line);

                    if (line.Quantity < 0)
                    {
                        isThereDecreaseAdjustmentLine = true;
                        DecreaseStock(context, line.Warehouse, line.Item, line.Quantity);
                        totalCOGSAdjustment += CalculateCOGS(context, line.Item, -line.Quantity);
                        IncreaseSoldOrReturned(context, line.Item, -line.Quantity);
                    }

                    else
                    {
                        isThereIncreaseAdjustmentLine = true;
                        IncreaseStock(context, line.Warehouse, line.Item, line.Quantity);
                        AddLineToStockAdjustmentPurchaseTransaction(line, stockAdjustmentPurchaseTransaction);
                    }
                }

                if (isThereDecreaseAdjustmentLine)
                {
                    AddStockAdjustmentDecrementLedgerTransactionToDatabase(context, stockAdjustmentTransaction, totalCOGSAdjustment);
                }

                if (isThereIncreaseAdjustmentLine)
                {
                    context.PurchaseTransactions.Add(stockAdjustmentPurchaseTransaction);
                }

                AddStockAdjustmentTransactionToDatabaseContext(context, stockAdjustmentTransaction);
                context.SaveChanges();
                ts.Complete();
            }
        }
Ejemplo n.º 24
0
        public static void MakePayment(PurchaseTransaction purchaseTransaction, decimal paymentAmount,
            decimal useCreditsAmount, string paymentMode)
        {
            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();

                context.Entry(purchaseTransaction).State = EntityState.Modified;
                purchaseTransaction.Paid += paymentAmount + useCreditsAmount;
                purchaseTransaction.Supplier.PurchaseReturnCredits -= useCreditsAmount;

                RecordPaymentLedgerTransactionInDatabaseContext(context, purchaseTransaction, paymentAmount, paymentMode);

                context.SaveChanges();
                ts.Complete();
            }
        }
Ejemplo n.º 25
0
        public TblAccountLedgerTransactions AddAccountLedgerTransactions(ERPContext context, TblVoucherDetail _voucherDetail, DateTime?invoiceDate)
        {
            try
            {
                //using(ERPContext context=new ERPContext())
                //{
                var _accountLedgerTransactions = new TblAccountLedgerTransactions
                {
                    VoucherDetailId = _voucherDetail.VoucherDetailId,
                    LedgerId        = _voucherDetail.ToLedgerId,
                    LedgerCode      = _voucherDetail.ToLedgerCode,
                    LedgerName      = _voucherDetail.ToLedgerName,
                    BranchId        = _voucherDetail.BranchId,
                    BranchCode      = _voucherDetail.BranchCode,
                    BranchName      = _voucherDetail.BranchName,
                    TransactionDate = invoiceDate,
                    TransactionType = _voucherDetail.TransactionType,
                    VoucherAmount   = _voucherDetail.Amount
                };

                if (_accountLedgerTransactions.TransactionType.Equals("dedit", StringComparison.OrdinalIgnoreCase))
                {
                    _accountLedgerTransactions.DebitAmount  = _accountLedgerTransactions.VoucherAmount;
                    _accountLedgerTransactions.CreditAmount = Convert.ToDecimal("0.00");
                }
                else if (_accountLedgerTransactions.TransactionType.Equals("credit", StringComparison.OrdinalIgnoreCase))
                {
                    _accountLedgerTransactions.CreditAmount = _accountLedgerTransactions.VoucherAmount;
                    _accountLedgerTransactions.DebitAmount  = Convert.ToDecimal("0.00");
                }

                context.TblAccountLedgerTransactions.Add(_accountLedgerTransactions);
                if (context.SaveChanges() > 0)
                {
                    return(_accountLedgerTransactions);
                }


                return(null);
                //  }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 26
0
        public static void MakePayment(PurchaseTransaction purchaseTransaction, decimal paymentAmount,
                                       decimal useCreditsAmount, string paymentMode)
        {
            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();

                context.Entry(purchaseTransaction).State = EntityState.Modified;
                purchaseTransaction.Paid += paymentAmount + useCreditsAmount;
                purchaseTransaction.Supplier.PurchaseReturnCredits -= useCreditsAmount;

                RecordPaymentLedgerTransactionInDatabaseContext(context, purchaseTransaction, paymentAmount, paymentMode);

                context.SaveChanges();
                ts.Complete();
            }
        }
Ejemplo n.º 27
0
        private static void IncreaseLineItemStockInDatabaseContext(ERPContext context, PurchaseTransactionLine line)
        {
            var stockFromDatabase = context.Stocks.SingleOrDefault(
                stock => stock.ItemID.Equals(line.Item.ID) && stock.WarehouseID.Equals(line.Warehouse.ID));

            if (stockFromDatabase == null)
            {
                context.Stocks.Add(new Stock {
                    Item = line.Item, Warehouse = line.Warehouse, Pieces = line.Quantity
                });
                context.SaveChanges();
            }
            else
            {
                stockFromDatabase.Pieces += line.Quantity;
            }
        }
Ejemplo n.º 28
0
        public TblVoucherDetail AddVoucherDetails(ERPContext context, TblInvoiceMasterReturn invoiceReturn, TblBranch _branch, TblVoucherMaster _voucherMaster, TblAccountLedger _accountLedger, decimal?productRate, bool isFromInvoiceDetials = true)
        {
            try
            {
                //using(ERPContext context=new ERPContext())
                //{
                var _voucherDetail = new TblVoucherDetail
                {
                    VoucherMasterId   = _voucherMaster.VoucherMasterId,
                    VoucherDetailDate = _voucherMaster.VoucherDate,
                    BranchId          = _branch.BranchId,
                    BranchCode        = invoiceReturn.BranchCode,
                    BranchName        = invoiceReturn.BranchName
                };
                if (isFromInvoiceDetials)
                {
                    _voucherDetail.FromLedgerId   = invoiceReturn.LedgerId;
                    _voucherDetail.FromLedgerCode = invoiceReturn.LedgerCode;
                    _voucherDetail.FromLedgerName = invoiceReturn.LedgerName;
                }
                //To ledger  clarifiaction on selecion of product

                _voucherDetail.ToLedgerId      = _accountLedger.LedgerId;
                _voucherDetail.ToLedgerCode    = _accountLedger.LedgerCode;
                _voucherDetail.ToLedgerName    = _accountLedger.LedgerName;
                _voucherDetail.Amount          = productRate;
                _voucherDetail.TransactionType = _accountLedger.CrOrDr;
                _voucherDetail.CostCenter      = _accountLedger.BranchCode;
                _voucherDetail.ServerDate      = DateTime.Now;
                _voucherDetail.Narration       = $"Sales Invoice {_accountLedger.LedgerName} A /c: {_voucherDetail.TransactionType}";

                context.TblVoucherDetail.Add(_voucherDetail);
                if (context.SaveChanges() > 0)
                {
                    return(_voucherDetail);
                }


                return(null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 29
0
        private void Increase_Day_Button_Clicked(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show(
                    $"The date now is: {UtilityMethods.GetCurrentDate().ToString("dd-MM-yyyy")} \n Confirm increasing day?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
            {
                return;
            }

            using (var context = new ERPContext())
            {
                var currentDate = context.Dates.FirstOrDefault(x => x.Name.Equals("Current"));
                if (currentDate != null)
                {
                    currentDate.DateTime = currentDate.DateTime.AddDays(1);
                }
                context.SaveChanges();
            }
        }
Ejemplo n.º 30
0
 public static void AddSupplierAlongWithItsLedgerToDatabase(Supplier supplier)
 {
     var context = new ERPContext();
     try
     {
         context.Suppliers.Add(supplier);
         CreateAndAddSupplierLedgerToDatabaseContext(context, supplier);
         context.SaveChanges();
     }
     catch
     {
         MessageBox.Show("The supplier's name is already being used.", "Invalid Supplier", MessageBoxButton.OK);
     }
     finally
     {
         context.Dispose();
     }
 }
Ejemplo n.º 31
0
        public static void AddSupplierAlongWithItsLedgerToDatabase(Supplier supplier)
        {
            var context = new ERPContext();

            try
            {
                context.Suppliers.Add(supplier);
                CreateAndAddSupplierLedgerToDatabaseContext(context, supplier);
                context.SaveChanges();
            }
            catch
            {
                MessageBox.Show("The supplier's name is already being used.", "Invalid Supplier", MessageBoxButton.OK);
            }
            finally
            {
                context.Dispose();
            }
        }
Ejemplo n.º 32
0
        public static void AddStockAdjustmentTransactionToDatabase(StockAdjustmentTransaction stockAdjustmentTransaction)
        {
            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();
                var stockAdjustmentPurchaseTransaction = MakeNewstockAdjustmentPurchaseTransaction(context, stockAdjustmentTransaction);

                decimal totalCOGSAdjustment = 0;

                var isThereDecreaseAdjustmentLine = false;
                var isThereIncreaseAdjustmentLine = false;

                foreach (var line in stockAdjustmentTransaction.AdjustStockTransactionLines)
                {
                    AttachLineToDatabaseContext(context, line);

                    if (line.Quantity < 0)
                    {
                        isThereDecreaseAdjustmentLine = true;
                        DecreaseStock(context, line.Warehouse, line.Item, line.Quantity);
                        totalCOGSAdjustment += CalculateCOGS(context, line.Item, -line.Quantity);
                        IncreaseSoldOrReturned(context, line.Item, -line.Quantity);
                    }

                    else
                    {
                        isThereIncreaseAdjustmentLine = true;
                        IncreaseStock(context, line.Warehouse, line.Item, line.Quantity);
                        AddLineToStockAdjustmentPurchaseTransaction(line, stockAdjustmentPurchaseTransaction);
                    }
                }

                if (isThereDecreaseAdjustmentLine)
                    AddStockAdjustmentDecrementLedgerTransactionToDatabase(context, stockAdjustmentTransaction, totalCOGSAdjustment);

                if (isThereIncreaseAdjustmentLine)
                    context.PurchaseTransactions.Add(stockAdjustmentPurchaseTransaction);

                AddStockAdjustmentTransactionToDatabaseContext(context, stockAdjustmentTransaction);
                context.SaveChanges();
                ts.Complete();
            }
        }
Ejemplo n.º 33
0
        private TblStockTransferMaster AddStockTransferMaster(ERPContext context, TblStockTransferMaster stockTransferMaster)
        {
            try
            {
                stockTransferMaster.FromBranchName = GetBranch(stockTransferMaster.FromBranchCode)?.BranchName;
                stockTransferMaster.ToBranchName   = GetBranch(stockTransferMaster.ToBranchCode)?.BranchName;
                context.TblStockTransferMaster.Add(stockTransferMaster);
                if (context.SaveChanges() > 0)
                {
                    return(stockTransferMaster);
                }

                return(null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 34
0
        public void EditCustomerMaster_Data(CustomerMaster customermaster, string username, string password)
        {
            CustomerMaster cust_Mstr = context.CustomerMaster.FirstOrDefault(a => a.CustomerCode == customermaster.CustomerCode);

            if (cust_Mstr != null)
            {
                cust_Mstr.CustomerName = customermaster.CustomerName;
                cust_Mstr.Location     = customermaster.Location;
                cust_Mstr.ModifiedBy   = username;
                cust_Mstr.ModifiedDate = DateTime.Now;

                context.SaveChanges();
            }
        }
Ejemplo n.º 35
0
        private TblStockTransferDetail AddStockTransferDetail(ERPContext context, TblStockTransferDetail stockTransferDetail, TblStockTransferMaster stockTransferMaster)
        {
            try
            {
                stockTransferDetail.StockTransferDetailId    = null;
                stockTransferDetail.StockTransferMasterId    = stockTransferMaster.StockTransferMasterId;
                stockTransferDetail.StockTransferDetailsDate = stockTransferMaster.StockTransferDate;
                context.TblStockTransferDetail.Add(stockTransferDetail);
                if (context.SaveChanges() > 0)
                {
                    return(stockTransferDetail);
                }

                return(null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Authentication user
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool Login(string username, string password)
        {
            if (_context.users.ToList().Count < 1)
            {
                Users admin = new Users
                {
                    username = "******",
                    password = "******",
                    isActive = true,
                };
                _context.users.Add(admin);
                _context.SaveChanges();
            }

            Users user = _context.users.FirstOrDefault <Users>(item => item.username.Equals(username) &&
                                                               item.password.Equals(password) &&
                                                               item.isActive);

            return(user != null ? true : false);
        }
Ejemplo n.º 37
0
        private static void RemoveLineFromDatabase(LedgerTransactionLine deletedLine)
        {
            using (var context = new ERPContext())
            {
                var firstLine = context.Ledger_Transaction_Lines
                                .Include("LedgerAccount")
                                .Single(line => line.LedgerTransactionID.Equals(deletedLine.LedgerTransaction.ID) &&
                                        line.LedgerAccountID.Equals(deletedLine.LedgerAccount.ID));
                var oppostieLine = context.Ledger_Transaction_Lines
                                   .Include("LedgerAccount")
                                   .Single(line => line.LedgerTransactionID.Equals(deletedLine.LedgerTransaction.ID) &&
                                           !line.LedgerAccountID.Equals(deletedLine.LedgerAccount.ID));
                var transactionFromDatabase = context.Ledger_Transactions
                                              .Single(transaction => transaction.ID.Equals(deletedLine.LedgerTransaction.ID));
                var ledgerGeneralFromDatabase = context.Ledger_General
                                                .Single(ledgerGeneral => ledgerGeneral.ID.Equals(deletedLine.LedgerAccount.ID));
                var oppositeLedgerGeneralFromDatabase = context.Ledger_General
                                                        .Single(ledgerGeneral => ledgerGeneral.ID.Equals(oppostieLine.LedgerAccount.ID));

                if (!transactionFromDatabase.Date.Month.Equals(context.Ledger_General.First().Period))
                {
                    MessageBox.Show("This line cannot be deleted as the period has been closed.", "Invalid Command",
                                    MessageBoxButton.OK);
                }

                context.Ledger_Transactions.Remove(transactionFromDatabase);
                context.Ledger_Transaction_Lines.Remove(firstLine);
                context.Ledger_Transaction_Lines.Remove(oppostieLine);
                if (deletedLine.Seq.Equals("Credit"))
                {
                    ledgerGeneralFromDatabase.Debit          -= deletedLine.Amount;
                    oppositeLedgerGeneralFromDatabase.Credit -= deletedLine.Amount;
                }
                else
                {
                    ledgerGeneralFromDatabase.Credit        -= deletedLine.Amount;
                    oppositeLedgerGeneralFromDatabase.Debit -= deletedLine.Amount;
                }
                context.SaveChanges();
            }
        }
Ejemplo n.º 38
0
        private TblStockInformation AddStockInformation(ERPContext context, TblStockTransferDetail stockTransferDetail, TblStockTransferMaster stockTransfertMaster, string branchCode, bool isFromBranch, decimal?voucherTypeID = 29)
        {
            try
            {
                TblStockInformation stockInformation = new TblStockInformation();
                try { stockInformation.BranchId = Convert.ToDecimal(branchCode ?? "0"); } catch { };
                stockInformation.BranchCode      = branchCode;
                stockInformation.UserId          = stockTransfertMaster.UserId;
                stockInformation.ShiftId         = stockTransfertMaster.ShiftId;
                stockInformation.TransactionDate = stockTransfertMaster.StockTransferDate;
                stockInformation.VoucherNo       = string.Empty;
                stockInformation.VoucherTypeId   = voucherTypeID;
                stockInformation.InvoiceNo       = stockTransfertMaster.StockTransferNo;
                stockInformation.ProductId       = stockTransferDetail.ProductId;
                stockInformation.ProductCode     = stockTransferDetail.ProductCode;
                stockInformation.Rate            = stockTransferDetail.Rate;
                if (isFromBranch)
                {
                    stockInformation.OutwardQty = stockTransferDetail.FQty > 0 ? stockTransferDetail.FQty : stockTransferDetail.Qty;
                }
                else
                {
                    stockInformation.InwardQty = stockTransferDetail.FQty > 0 ? stockTransferDetail.FQty : stockTransferDetail.Qty;
                }

                stockInformation.OutwardQty = stockInformation.OutwardQty ?? 0;
                stockInformation.InwardQty  = stockInformation.InwardQty ?? 0;

                context.TblStockInformation.Add(stockInformation);
                if (context.SaveChanges() > 0)
                {
                    return(stockInformation);
                }

                return(null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 39
0
 public static void AddItemToDatabase(Item item)
 {
     var success = true;
     var context = new ERPContext();
     try
     {
         AddItemToDatabaseContext(context, item);
         context.SaveChanges();
     }
     catch
     {
         success = false;
         MessageBox.Show("The item ID is already being used.", "Invalid ID", MessageBoxButton.OK);
     }
     finally
     {
         if (success)
             MessageBox.Show("Successfully added item!", "Success", MessageBoxButton.OK);
         context.Dispose();
     }
 }
Ejemplo n.º 40
0
        public static void AddNewTransactionToDatabase(PurchaseTransaction purchaseTransaction)
        {
            IsLastSaveSuccessful = false;

            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();

                foreach (var line in purchaseTransaction.PurchaseTransactionLines)
                {
                    AttachPurchaseTransactionLineToDatabaseContext(context, line);
                    IncreaseLineItemStockInDatabaseContext(context, line);
                    context.SaveChanges();
                }

                AttachPurchaseTransactionPropertiesToDatabaseContext(context, purchaseTransaction);
                RecordPurchaseLedgerTransactionInDatabaseContext(context, purchaseTransaction);

                ts.Complete();
            }

            IsLastSaveSuccessful = true;
        }
        private static void AddSalesReturnTransactionLedgerTransactionsToDatabaseContext(ERPContext context,
            SalesReturnTransaction salesReturnTransaction)
        {
            var totalCOGS =
                salesReturnTransaction.SalesReturnTransactionLines.ToList()
                    .Sum(salesReturnTransactionLine => salesReturnTransactionLine.CostOfGoodsSold);

            // Record the corresponding ledger transactions in the database
            var ledgerTransaction1 = new LedgerTransaction();
            var ledgerTransaction2 = new LedgerTransaction();

            if (
                !LedgerTransactionHelper.AddTransactionToDatabase(context, ledgerTransaction1,
                    UtilityMethods.GetCurrentDate().Date, salesReturnTransaction.SalesReturnTransactionID,
                    "Sales Return")) return;
            context.SaveChanges();
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, ledgerTransaction1,
                "Sales Returns and Allowances", "Debit", salesReturnTransaction.NetTotal);
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, ledgerTransaction1,
                "Cash", "Credit", salesReturnTransaction.NetTotal);

            if (
                !LedgerTransactionHelper.AddTransactionToDatabase(context, ledgerTransaction2,
                    UtilityMethods.GetCurrentDate().Date, salesReturnTransaction.SalesReturnTransactionID,
                    "Sales Return")) return;
            context.SaveChanges();
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, ledgerTransaction2, "Inventory", "Debit",
                totalCOGS);
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, ledgerTransaction2, "Cost of Goods Sold",
                "Credit", totalCOGS);

            context.SaveChanges();
        }
 private static void AddPurchaseReturnTransactionLedgerTransactionToDatabaseContext(ERPContext context, PurchaseReturnTransaction purchaseReturnTransaction, decimal totalCOGS)
 {
     var purchaseReturnLedgerTransaction = new LedgerTransaction();
     if (!LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseReturnLedgerTransaction, UtilityMethods.GetCurrentDate(), purchaseReturnTransaction.PurchaseReturnTransactionID, "Purchase Return")) return;
     context.SaveChanges();
     LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseReturnLedgerTransaction,
         $"{purchaseReturnTransaction.PurchaseTransaction.Supplier.Name} Accounts Payable", "Debit", purchaseReturnTransaction.NetTotal);
     if (totalCOGS - purchaseReturnTransaction.NetTotal > 0)
         LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseReturnLedgerTransaction, "Cost of Goods Sold", "Debit", totalCOGS - purchaseReturnTransaction.NetTotal);
     LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseReturnLedgerTransaction, "Inventory", "Credit", totalCOGS);
     context.SaveChanges();
 }
Ejemplo n.º 43
0
        private void CloseLiabilityOrRevenueAccount(LedgerAccount account, ERPContext context)
        {
            var periodYearBalances = account.LedgerAccountBalances.First(balance => balance.PeriodYear.Equals(UtilityMethods.GetCurrentDate().Year));
            switch (Period)
            {
                case 1:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance1 += periodYearBalances.BeginningBalance;

                    periodYearBalances.Balance1 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 2:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance2 += periodYearBalances.Balance1;

                    periodYearBalances.Balance2 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 3:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance3 += periodYearBalances.Balance2;

                    periodYearBalances.Balance3 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 4:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance4 += periodYearBalances.Balance3;

                    periodYearBalances.Balance4 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 5:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance5 += periodYearBalances.Balance4;

                    periodYearBalances.Balance5 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 6:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance6 += periodYearBalances.Balance5;

                    periodYearBalances.Balance6 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 7:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance7 += periodYearBalances.Balance6;

                    periodYearBalances.Balance7 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 8:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance8 += periodYearBalances.Balance7;

                    periodYearBalances.Balance8 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 9:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance9 += periodYearBalances.Balance8;

                    periodYearBalances.Balance9 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 10:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance10 += periodYearBalances.Balance9;

                    periodYearBalances.Balance10 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 11:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance11 += periodYearBalances.Balance10;

                    periodYearBalances.Balance11 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
                case 12:
                    if (!account.Class.Equals("Revenue"))
                        periodYearBalances.Balance12 += periodYearBalances.Balance11;

                    periodYearBalances.Balance12 += account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                    account.LedgerGeneral.Debit = 0;
                    account.LedgerGeneral.Credit = 0;
                    break;
            }
            context.SaveChanges();
        }
 private void AddEntryToDatabase()
 {
     using (var ts = new TransactionScope(TransactionScopeOption.Required))
     {
         var context = new ERPContext();
         var transaction = new LedgerTransaction();
         if (!LedgerTransactionHelper.AddTransactionToDatabase(context, transaction, _newEntryDate, _newEntryDescription, _newEntryDescription)) return;
         context.SaveChanges();
         LedgerTransactionHelper.AddTransactionLineToDatabase(context, transaction, _newEntryAccount.Name, _newEntrySequence, _newEntryAmount);
         LedgerTransactionHelper.AddTransactionLineToDatabase(context, transaction, _parentVM.SelectedBank.Name, _newEntrySequence == "Debit" ? "Credit" : "Debit", _newEntryAmount);
         context.SaveChanges();
         ts.Complete();
     }
 }
Ejemplo n.º 45
0
        private static void CloseRevenueOrExpenseAccountToRetainedEarnings(LedgerAccount account, ERPContext context)
        {
            var retainedEarnings = context.Ledger_Accounts
                .Include("LedgerGeneral")
                .Include("LedgerAccountBalances")
                .Include("LedgerTransactionLines")
                .Single(e => e.Name.Equals("Retained Earnings"));

            if (account.Class.Equals("Expense"))
            {
                var amount = account.LedgerGeneral.Debit - account.LedgerGeneral.Credit;
                var transaction = new LedgerTransaction();

                LedgerTransactionHelper.AddTransactionToDatabase(context, transaction, UtilityMethods.GetCurrentDate().Date, "Closing Entry", account.Name);
                context.SaveChanges();
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, transaction, account.Name, "Credit", amount);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, transaction, retainedEarnings.Name, "Debit", amount);

                account.LedgerGeneral.Credit -= amount;
            }

            else if (account.Class.Equals("Revenue"))
            {
                var amount = account.LedgerGeneral.Credit - account.LedgerGeneral.Debit;
                var transaction = new LedgerTransaction();

                if (!LedgerTransactionHelper.AddTransactionToDatabase(context, transaction, UtilityMethods.GetCurrentDate().Date, "Closing Entry", account.Name)) return;
                context.SaveChanges();
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, transaction, account.Name, "Debit", amount);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, transaction, retainedEarnings.Name, "Credit", amount);

                account.LedgerGeneral.Debit -= amount;
            }
        }
Ejemplo n.º 46
0
 private static void ChangeSupplierLedgerAccountNameInDatabaseContext(ERPContext context, Supplier editingSupplier, Supplier editedSupplier)
 {
     var ledgerAccountFromDatabase = GetSupplierLedgerAccountFromDatabaseContext(context, editingSupplier);
     ledgerAccountFromDatabase.Name = $"{editedSupplier.Name} Accounts Payable";
     context.SaveChanges();
 }
Ejemplo n.º 47
0
        private static void RecordPaymentLedgerTransactionInDatabaseContext(ERPContext context, PurchaseTransaction purchaseTransaction, decimal paymentAmount, string paymentMode)
        {
            var accountsPayableName = purchaseTransaction.Supplier.Name + " Accounts Payable";
            var paymentLedgerTransaction = new LedgerTransaction();

            if (!LedgerTransactionHelper.AddTransactionToDatabase(context, paymentLedgerTransaction, UtilityMethods.GetCurrentDate().Date, purchaseTransaction.PurchaseID, "Purchase Payment")) return;
            context.SaveChanges();

            LedgerTransactionHelper.AddTransactionLineToDatabase(context, paymentLedgerTransaction, accountsPayableName, "Debit", paymentAmount);
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, paymentLedgerTransaction, paymentMode, "Credit", paymentAmount);
            context.SaveChanges();
        }
Ejemplo n.º 48
0
 private static void SaveItemEditsToDatabaseContext(ERPContext context, Item editingItem, Item editedItem)
 {
     editingItem = context.Inventory.Single(item => item.ID.Equals(editingItem.ID));
     DeepCopyItemProperties(editedItem, editingItem);
     editingItem.ItemCategory = context.Categories.Single(category => category.ID.Equals(editingItem.ItemCategory.ID));
     AssignEditedItemSuppliersToEditingSupplier(context, editingItem, editedItem);
     context.SaveChanges();
 }
Ejemplo n.º 49
0
        private static void IncreaseLineItemStockInDatabaseContext(ERPContext context, PurchaseTransactionLine line)
        {
            var stockFromDatabase = context.Stocks.SingleOrDefault(
                stock => stock.ItemID.Equals(line.Item.ID) && stock.WarehouseID.Equals(line.Warehouse.ID));

            if (stockFromDatabase == null)
            {
                context.Stocks.Add(new Stock { Item = line.Item, Warehouse = line.Warehouse, Pieces = line.Quantity });
                context.SaveChanges();
            }
            else
                stockFromDatabase.Pieces += line.Quantity;
        }
Ejemplo n.º 50
0
 private static void SaveCustomerEditsToDatabaseContext(ERPContext context, Customer editingCustomer, Customer editedCustomer)
 {
     editingCustomer = context.Customers.Single(customer => customer.ID.Equals(editingCustomer.ID));
     DeepCopyCustomerProperties(editedCustomer, ref editingCustomer);
     context.SaveChanges();
 }
Ejemplo n.º 51
0
 public static void ActivateSupplierInDatabase(Supplier supplier)
 {
     using (var context = new ERPContext())
     {
         context.Entry(supplier).State = EntityState.Modified;
         supplier.IsActive = true;
         context.SaveChanges();
     }
 }
Ejemplo n.º 52
0
        private static void RecordEditedPurchaseTransactionTotalCOGSChangedLedgerTransactionInDatabaseContext(
            ERPContext context, PurchaseTransaction editedPurchaseTransaction, decimal totalCOGSChanged)
        {
            var purchaseTransactionTotalCOGSChangedLedgerTransaction = new LedgerTransaction();
            LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, UtilityMethods.GetCurrentDate().Date, editedPurchaseTransaction.PurchaseID, "Purchase Transaction Adjustment (COGS)");
            context.SaveChanges();

            if (totalCOGSChanged > 0)
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Cost of Goods Sold", "Debit", totalCOGSChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Inventory", "Credit", totalCOGSChanged);
            }
            else
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Inventory", "Debit", -totalCOGSChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Cost of Goods Sold", "Credit", -totalCOGSChanged);
            }
            context.SaveChanges();
        }
Ejemplo n.º 53
0
 private static void SaveSupplierEditsToDatabaseContext(ERPContext context, Supplier editingSupplier,
     Supplier editedSupplier)
 {
     context.Entry(editingSupplier).State = EntityState.Modified;
     DeepCopySupplierProperties(editedSupplier, editingSupplier);
     context.SaveChanges();
 }
Ejemplo n.º 54
0
        private static void RecordEditedPurchaseTransactionNetTotalChangedLedgerTransactionInDatabaseContext(ERPContext context, PurchaseTransaction editedPurchaseTransaction, decimal valueChanged)
        {
            var purchaseTransactionNetTotalChangedLedgerTransaction = new LedgerTransaction();

            LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction,
                UtilityMethods.GetCurrentDate().Date, editedPurchaseTransaction.PurchaseID, "Purchase Transaction Adjustment");
            context.SaveChanges();

            if (valueChanged > 0)
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction, "Inventory",
                    "Debit", valueChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction,
                    $"{editedPurchaseTransaction.Supplier.Name} Accounts Payable", "Credit", valueChanged);
            }
            else
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction,
                    $"{editedPurchaseTransaction.Supplier.Name} Accounts Payable", "Debit", -valueChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction, "Inventory",
                    "Credit", -valueChanged);
            }
            context.SaveChanges();
        }
Ejemplo n.º 55
0
        public void Close(BackgroundWorker worker)
        {
            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();

                var accounts = context.Ledger_Accounts
                    .Include("LedgerGeneral")
                    .Include("LedgerAccountBalances")
                    .ToList();

                var revenueAndExpenseAccounts = context.Ledger_Accounts
                    .Include("LedgerGeneral")
                    .Include("LedgerAccountBalances")
                    .Where(e => e.Class.Equals("Expense") || e.Class.Equals("Revenue"))
                    .ToList();

                var index = 1;
                var totalAccounts = accounts.Count + revenueAndExpenseAccounts.Count;
                // Close the Revenue and Expense Accounts to Retained Earnings
                foreach (var account in revenueAndExpenseAccounts)
                {
                    if (account.LedgerGeneral.Debit != 0 || account.LedgerGeneral.Credit != 0)
                        CloseRevenueOrExpenseAccountToRetainedEarnings(account, context);

                    worker.ReportProgress(index++ * (totalAccounts / 100));
                }

                foreach (var account in accounts)
                {
                    if (UtilityMethods.GetCurrentDate().Month == 12)
                    {
                        var newBalance = new LedgerAccountBalance { LedgerAccount = account, PeriodYear = UtilityMethods.GetCurrentDate().Year + 1 };
                        context.Ledger_Account_Balances.Add(newBalance);
                    }

                    if (Period != 12) account.LedgerGeneral.Period++;
                    else
                    {
                        account.LedgerGeneral.PeriodYear++;
                        account.LedgerGeneral.Period = 1;
                    }

                    // Close the balances
                    if (account.Class.Equals("Asset") || account.Class.Equals("Expense"))
                        CloseAssetOrExpenseAccount(account, context);                     
                    else
                        CloseLiabilityOrRevenueAccount(account, context);

                    worker.ReportProgress(index++ * (totalAccounts / 100));
                }

                context.SaveChanges();
                ts.Complete();
            }

            OnPropertyChanged("PeriodYear");
            OnPropertyChanged("Period");
        }
Ejemplo n.º 56
0
 private static void AttachPurchaseTransactionPropertiesToDatabaseContext(ERPContext context, PurchaseTransaction purchaseTransaction)
 {
     purchaseTransaction.Supplier = context.Suppliers.Single(supplier => supplier.ID.Equals(purchaseTransaction.Supplier.ID));
     var currentUser = Application.Current.TryFindResource("CurrentUser") as User;
     if (currentUser != null)
         purchaseTransaction.User = context.Users.Single(user => user.Username.Equals(currentUser.Username));
     context.PurchaseTransactions.Add(purchaseTransaction);
     context.SaveChanges();
 }
Ejemplo n.º 57
0
        private void Increase_Day_Button_Clicked(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show(
                $"The date now is: {UtilityMethods.GetCurrentDate().ToString("dd-MM-yyyy")} \n Confirm increasing day?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No) return;

            using (var context = new ERPContext())
            {
                var currentDate = context.Dates.FirstOrDefault(x => x.Name.Equals("Current"));
                if (currentDate != null)
                {
                    currentDate.DateTime = currentDate.DateTime.AddDays(1);
                }
                context.SaveChanges();
            }
        }
        private static void DecreaseSalesReturnTransactionLineItemSoldOrReturnedInDatabaseContext(ERPContext context,
            SalesReturnTransactionLine salesReturnTransactionLine)
        {
            var purchases = context.PurchaseTransactionLines
                .Where(e => e.ItemID.Equals(salesReturnTransactionLine.Item.ID) && e.SoldOrReturned > 0)
                .OrderByDescending(transaction => transaction.PurchaseTransactionID)
                .ThenByDescending(transaction => transaction.Quantity - transaction.SoldOrReturned)
                .ThenByDescending(transaction => transaction.PurchasePrice)
                .ThenByDescending(transaction => transaction.Discount)
                .ThenByDescending(transaction => transaction.WarehouseID);

            var tracker = salesReturnTransactionLine.Quantity;
            foreach (var purchase in purchases)
            {
                if (purchase.SoldOrReturned >= tracker)
                {
                    purchase.SoldOrReturned -= tracker;
                    break;
                }
                if (purchase.SoldOrReturned < tracker)
                {
                    tracker -= purchase.SoldOrReturned;
                    purchase.SoldOrReturned = 0;
                }
            }
            context.SaveChanges();
        }
Ejemplo n.º 59
0
        private static void SetPurchaseTransactionInDatabaseContextToEditedPurchaseTransactionProperties(ERPContext context, PurchaseTransaction editedPurchaseTransaction)
        {
            var transactionFromDatabase = context.PurchaseTransactions
                .Include("Supplier")
                .Include("PurchaseTransactionLines")
                .Include("PurchaseTransactionLines.Item")
                .Include("PurchaseTransactionLines.Warehouse")
                .Single(e => e.PurchaseID.Equals(editedPurchaseTransaction.PurchaseID));

            transactionFromDatabase.Date = editedPurchaseTransaction.Date;
            transactionFromDatabase.DueDate = editedPurchaseTransaction.DueDate;
            transactionFromDatabase.DOID = editedPurchaseTransaction.DOID;
            transactionFromDatabase.Note = editedPurchaseTransaction.Note;
            transactionFromDatabase.Tax = editedPurchaseTransaction.Tax;
            transactionFromDatabase.GrossTotal = editedPurchaseTransaction.GrossTotal;
            transactionFromDatabase.Discount = editedPurchaseTransaction.Discount;
            transactionFromDatabase.Total = editedPurchaseTransaction.Total;
            var currentUser = Application.Current.TryFindResource("CurrentUser") as User;
            if (currentUser != null)
                transactionFromDatabase.User = context.Users.Single(user => user.Username.Equals(currentUser.Username));

            foreach (var line in transactionFromDatabase.PurchaseTransactionLines.ToList())
            {
                context.PurchaseTransactionLines.Remove(line);
                context.SaveChanges();
            }

            foreach (var editedLine in editedPurchaseTransaction.PurchaseTransactionLines)
            {
                editedLine.PurchaseTransaction = transactionFromDatabase;
                editedLine.Item = context.Inventory.Single(item => item.ID.Equals(editedLine.Item.ID));
                editedLine.Warehouse = context.Warehouses.Single(warehouse => warehouse.ID.Equals(editedLine.Warehouse.ID));
                context.PurchaseTransactionLines.Add(editedLine);
                context.SaveChanges();
            }

            context.SaveChanges();
        }
Ejemplo n.º 60
0
 private static void RecordPurchaseLedgerTransactionInDatabaseContext(ERPContext context, PurchaseTransaction purchaseTransaction)
 {
     var purchaseLedgerTransaction = new LedgerTransaction();
     var accountsPayableName = purchaseTransaction.Supplier.Name + " Accounts Payable";
     if (!LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseLedgerTransaction, UtilityMethods.GetCurrentDate().Date, purchaseTransaction.PurchaseID, "Purchase Transaction")) return;
     context.SaveChanges();
     LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseLedgerTransaction, "Inventory", "Debit", purchaseTransaction.Total);
     LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseLedgerTransaction, accountsPayableName, "Credit", purchaseTransaction.Total);
     context.SaveChanges();
 }