public void SaveTransaction(Transaction transaction)
 {
     var saveSuccess = _transactionsRepository.SaveTransaction(transaction);
     if (saveSuccess)
     {
         var distributionSuccess= _transactionsLogic.DistributeTransactionCashback(transaction);
         if (distributionSuccess)
         {
             _transactionsRepository.SaveChangesMade();
         }
         else
         {
             _transactionsRepository.RejectChanges();
         }
     }
     else
     {
         _transactionsRepository.RejectChanges();
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public bool DistributeTransactionCashback(Transaction transaction)
        {
            try
            {
                // del 100% esto es la comision total
                var cashBackPercentajeAssignable = transaction.Comision;//transaction.Amount*transaction.Company.CashBackPercentage/100;
                // Este seria el 30% para soluciones AR
                var solucionesArAmount = cashBackPercentajeAssignable*SOLUCIONES_AR_PERCENTAJE;
                UpdateSolucionesArUser(solucionesArAmount);
                // Este seria el 70% del que los usuarios van a tomar sus %
                var forUsersAmount = cashBackPercentajeAssignable - solucionesArAmount;
                var moneyForRealUser = forUsersAmount * REAL_USER_PERCENTAJE;

                // Los usuarios
                var customer = _usersRepository.GetUserById(transaction.UserId);
                var parentUser = customer.UserReference;
                var forSeniorMoney = forUsersAmount*SENIOR_USER_PERCENTAJE;
                if (parentUser != null && parentUser.Enabled)
                {
                    if (parentUser.RelationshipType.Description.Equals(MASTER) ||
                        parentUser.RelationshipType.Description.Equals(SENIOR))
                    {

                        parentUser.Cashback += forSeniorMoney;
                        _usersRepository.UpdateUser(parentUser);
                    }
                    else
                    {
                        _usersRepository.UpdateUser(UpdateSolucionesArUser(forSeniorMoney));
                    }
                    var grandParentUser = parentUser.UserReference;
                    var forMasterMoney = forUsersAmount*MASTER_USER_PERCENTAJE;
                    if (grandParentUser != null && grandParentUser.Enabled)
                    {
                        if (grandParentUser.RelationshipType.Description.Equals(MASTER))
                        {
                            grandParentUser.Cashback += forMasterMoney;
                            _usersRepository.UpdateUser(grandParentUser);
                        }
                        else
                        {
                            _usersRepository.UpdateUser(UpdateSolucionesArUser(forMasterMoney));
                        }
                    }
                    else
                    {
                        _usersRepository.UpdateUser(UpdateSolucionesArUser(forMasterMoney));
                    }
                }
                else
                {
                    _usersRepository.UpdateUser(UpdateSolucionesArUser(forUsersAmount - moneyForRealUser));
                }

                // Calculo del cashback para el usuario que hizo la compra

                customer.Cashback += moneyForRealUser;
                customer.Points += transaction.Points;
                _usersRepository.UpdateUser(customer);
                _usersRepository.SaveChangesMade();
                return true;
            }
            catch (Exception)
            {
                _usersRepository.RejectChanges();
                _transactionsRepository.RejectChanges();
                return false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public bool SaveTransactionsFromFile(string filename, string sheetName)
        {
            try
            {
                //Using Npoi instead of the office components
                ISheet sheet;
                if (filename.Substring(filename.LastIndexOf('.')).ToLower() == EXCEL_2007_EXTENSION)
                {
                    XSSFWorkbook workbook;
                    using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
                    {
                        workbook = new XSSFWorkbook(file);
                    }
                    sheet = workbook.GetSheet(sheetName);
                }
                else
                {
                    HSSFWorkbook workbook;
                    using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
                    {
                        workbook = new HSSFWorkbook(file);
                    }
                    sheet = workbook.GetSheet(sheetName);
                }

                var transactionsList = new List<dynamic>();
                for (int row = 1; row <= sheet.LastRowNum; row++)
                {
                    if (sheet.GetRow(row) != null) //null is when the row only contains empty cells
                    {
                        var theRow = sheet.GetRow(row);
                        var transaction = new
                                              {
                                                  campana = theRow.GetCell(0).StringCellValue,
                                                  factura = theRow.GetCell(1).StringCellValue,
                                                  fecha = theRow.GetCell(2).DateCellValue,
                                                  monto = theRow.GetCell(3).NumericCellValue,
                                                  puntos = theRow.GetCell(4).NumericCellValue,
                                                  comision = theRow.GetCell(5).NumericCellValue,
                                                  vendedor = theRow.GetCell(6).StringCellValue,
                                              };
                        transactionsList.Add(transaction);

                    }
                }
                //string connectionString =
                //    string.Format(
                //        filename.Substring(filename.LastIndexOf('.')).ToLower() == EXCEL_2007_EXTENSION
                //            ? EXCEL_2007_CONNECTION_STRING
                //            : EXCEL_2005_CONNECTION_STRING, filename);

                //var adapter = new OleDbDataAdapter(string.Format(SELECT_ALL_QUERY, sheetName), connectionString);
                //var dataSet = new DataSet();

                //adapter.Fill(dataSet, DATA_TABLE_NAME);

                //var reportData = dataSet.Tables[DATA_TABLE_NAME].AsEnumerable();

                //var transactionsList =
                //    reportData.Where(y => y.Field<string>("Campaña") != null)
                //        .Select(
                //            x => new
                //            {
                //                campana = x.Field<string>("Campaña"),
                //                factura = x.Field<string>("Factura"),
                //                fecha = x.Field<DateTime>("Fecha"),
                //                monto = x.Field<double>("Monto"),
                //                puntos = x.Field<double>("Puntos"),
                //                comision = x.Field<double>("Comision"),
                //                vendedor = x.Field<string>("Vendedor"),
                //            }).
                //        ToList(); //o por nombre de columna.
                foreach (var individualTransaction in transactionsList)
                {
                    int cedNumber = GetCedNumberFromString(individualTransaction.vendedor);
                    var customer = _usersRepository.GetUserByIdentificationNumber(cedNumber);

                    var company = _companiesRepository.GetCompany(individualTransaction.campana);

                    var transaction = new Transaction
                                          {
                                              Amount = individualTransaction.monto,
                                              BillBarCode = individualTransaction.factura,
                                              UserId = customer.UserId,
                                              Points = (int) individualTransaction.puntos,
                                              TransactionDate = Convert.ToDateTime(individualTransaction.fecha),
                                              CompanyId = company.CompanyId,
                                              CreatetedAt = DateTime.Now,
                                              UpdatedAt = DateTime.Now,
                                              Comision = individualTransaction.comision,
                                          };
                    if (_transactionsRepository.SaveTransaction(transaction))
                    {
                        if (!DistributeTransactionCashback(transaction))
                        {
                            _transactionsRepository.RejectChanges();
                        }
                    }
                    else
                    {
                        //send error
                        _usersRepository.RejectChanges();
                        _transactionsRepository.RejectChanges();
                        return false;

                    }

                }
                _transactionsRepository.SaveChangesMade();
                _usersRepository.SaveChangesMade();
                return true;
            }
            catch (Exception ex)
            {
                //TODO: enviar algun error
                _usersRepository.RejectChanges();
                _transactionsRepository.RejectChanges();
                Console.WriteLine(ex.Message);
                return false;
            }
        }
 public bool SaveTransaction(Transaction transaction)
 {
     var result = _databaseModel.Transactions.Add(transaction);
     //_databaseModel.SaveChanges();
     return result != null;
 }
        public ActionResult Save(EditViewModel editFormModel)
        {
            if (ModelState.IsValid)
            {
                Transaction transaction;
                var company = _companiesManagement.GetCompany(editFormModel.Company.CompanyId);
                var comision = editFormModel.Comision < 0.0000001
                                   ? editFormModel.Amount*company.CashBackPercentaje/100
                                   : editFormModel.Comision;
                if (editFormModel.TransactionId == 0)
                {

                    transaction = new Transaction
                        {
                            TransactionId = 0,
                            Amount = editFormModel.Amount,
                            BillBarCode = editFormModel.BillBarCode,
                            CreatetedAt = DateTime.Now,
                            UpdatedAt = DateTime.Now,
                            TransactionDate = Convert.ToDateTime(editFormModel.TransactionDate),
                            UserId = editFormModel.Customer.UserId,
                            Points = editFormModel.Points,
                            CompanyId = editFormModel.Company.CompanyId,
                            Comision = comision,
                        };
                    _transactionsManagement.SaveTransaction(transaction);
                    return RedirectToAction("Index");
                }

                transaction = _transactionsManagement.GetTransaction(editFormModel.TransactionId);
                transaction.BillBarCode = editFormModel.BillBarCode;
                transaction.Amount = editFormModel.Amount;
                transaction.UserId = editFormModel.Customer.UserId;
                transaction.Points = editFormModel.Points;
                transaction.CompanyId = editFormModel.Company.CompanyId;
                transaction.TransactionDate = Convert.ToDateTime(editFormModel.TransactionDate);
                transaction.UpdatedAt = DateTime.Now;
                transaction.Comision = comision;
                _transactionsManagement.UpdateTransaction();
                return RedirectToAction("Index");
            }

            //editViewModel.CustomersList = GetAvailableUsersList();
            var usersList = GetAvailableUsersList();
            var usersToShow = GenerateUsersToShowList(usersList);
            editFormModel.CompaniesList = _companiesManagement.GetCompaniesList();
            editFormModel.UsersToShowList = usersToShow;
            return View("Edit", editFormModel);
        }