public IEnumerable<Entry> GetTransactions()
 {
     using (var context = new SpendingReportEntities())
     {
         return context.Entries.ToList();
     }
 }
 public TransactionCategoriesModel GetTransactionCategoriesById(int id)
 {
     using (var context = new SpendingReportEntities())
     {
         var category = context.TransactionCategories.FirstOrDefault(i => i.Id == id);
         var result = category.EntityToModel();
         return result;
     }
 }
 public IList<SpendingReport.Service.Models.Cars.Car> GetCarsByUserId(int userId)
 {
     try
     {
         using (var context = new SpendingReportEntities())
         {
             var cars = context.Cars.Where(i => i.UserId == userId).ToList();
             return cars.EntityToModel();
         }
     }
     catch (Exception ex)
     {
         throw new Exception("Error occured in getting cars!", ex);
     }
 }
Beispiel #4
0
 public static User GetUserByIDWithCars(int UserId)
 {
     //todo:otestovat static
     try
     {
         using (var context = new SpendingReportEntities())
         {
             var currentUser = context.Users.Include("Cars").FirstOrDefault(t => t.Id == UserId);
             if (currentUser == null)
                 throw new Exception("Používateľ nebol nájdený!");
             return currentUser;
         }
     }
     catch (Exception e)
     {
         throw (e);
     }
 }
 public SpendingReport.Service.Models.Cars.Car GetCarById(int Id)
 {
     try
     {
         using (var context = new SpendingReportEntities())
         {
             var car = context.Cars.SingleOrDefault(i => i.Id == Id);
             car.Trips.Add(context.Trips.Where(i => i.CarId == Id).OrderBy(i => i.Date).FirstOrDefault());
             car.TankStatuses.Add(context.TankStatuses.Include("Fueling").Include("Fueling.Purchase").Include("Fueling.Purchase.FuelStation").Where(i => i.CarId == Id).OrderBy(i => i.Date).FirstOrDefault());
             car.Purchases.Add(context.Purchases.Include("Fueling").Include("Fueling.TankStatus").Include("FuelStation").Where(i => i.CarId == Id).OrderBy(i => i.Date).FirstOrDefault());
             car.Purchases.Add(context.Purchases.Include("Fueling").Include("Fueling.TankStatus").Include("FuelStation").Where(i => i.CarId == Id).Where(i => i.Fueling != null).OrderBy(i => i.Date).FirstOrDefault());
             return car.EntityToModel();
         }
     }
     catch (Exception ex)
     {
         throw new Exception(string.Format("Error occured in getting CarAttributes with Id: {0}!", Id), ex);
     }
 }
 public TransactionsModel GetTransactionsByUserID(int? userId, int categoryId, int skip, int? take)
 {
     try
     {
         using (var context = new SpendingReportEntities())
         {
             var transactions = context.Entries
                 .Include("DestinationAccount")
                 .Include("DestinationAccount.Bank")
                 .Include("AmountInfo")
                 .OrderBy(a => a.DatePosted).ToList();
             if (userId.HasValue)
             {
                 transactions =
                     transactions.Where(e => e.SourceAccount.User.Id == userId).ToList();
             }
             if (categoryId > 0)
             {
                 var category = context.TransactionCategories.SingleOrDefault(i => i.Id == categoryId);
                 transactions = transactions.Where(e => e.TransactionCategories.Contains(category)).ToList();
             }
             var resultTransactions = new List<Transaction>();
             if (!take.HasValue)
                 take = transactions.Count();
             foreach (var item in transactions.Skip(skip).Take(take.Value))
             {
                 var transaction = item.EntityToModel();
                 resultTransactions.Add(transaction);
             }
             var result = new TransactionsModel
             {
                 TotalItems = transactions.Count(),
                 Transactions = resultTransactions
             };
             return result;
         }
     }
     catch (Exception e)
     {
         throw (e);
     }
 }
 public IEnumerable<TransactionCategoriesModel> GetAllTransactionCategories(bool withNames = true)
 {
     using (var context = new SpendingReportEntities())
     {
         IList<TransactionCategory> categories;
         if (withNames)
             categories = context.TransactionCategories.Include("CategoryNames").ToList();
         else
         {
             categories = context.TransactionCategories.ToList();
         }
         var result = new List<TransactionCategoriesModel>();
         foreach (var transactionCategory in categories)
         {
             var desc = transactionCategory.EntityToModel();
             result.Add(desc);
         }
         return result;
     }
 }
 public void AddNewCar(int userId, SpendingReport.Service.Models.Cars.CarAttributes carAttributes)
 {
     try
     {
         using (var context = new SpendingReportEntities())
         {
             var currentUser = UserHelpers.GetUserByIDWithCars(userId);
             if (currentUser == null)
                 throw new Exception("Používateľ nebol nájdený!");
             var newCar = new Car
             {
                 Name = carAttributes.Name,
                 TankSize = carAttributes.TankSize
             };
             currentUser.Cars.Add(newCar);
             context.SaveChanges();
         }
     }
     catch (Exception ex)
     {
         throw new Exception("Nastaka chyba pri pridavani noveho auta!", ex);
     }
 }
        public bool AddTransactionCategory(CategoryModel model)
        {
            try
            {
                using (var context = new SpendingReportEntities())
                {
                    TransactionCategory category = null;
                    var name = new CategoryName()
                    {
                        Description = model.Description
                    };
                    context.CategoryNames.Add(name);
                    if (model.Id != 0)
                    {
                        category = context.TransactionCategories.FirstOrDefault(i => i.Id == model.Id);
                    }
                    if (category == null)
                    {
                        category = context.TransactionCategories.FirstOrDefault(i => i.Name == model.Name) ??
                                      CreateTransactionCategory(context);
                    }
                    category.Name = model.Name;

                    category.CategoryNames.Add(name);
                    context.SaveChanges();

                    //todo: async
                    UpdateCategories(model.Description, category.Id);
                }

                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("Error occured in add transaction description!", ex);
            }
        }
        public Import SaveData(Import bankPayments, int UserId)
        {
            Import ImportWithPocessedTransactions;

            try
            {
                using (var context = new SpendingReportEntities())
                {
                    //if (!bankPayments.Bank.BankID.HasValue)
                    //{
                    //    return -1;
                    //}

                    //entity.Bank bank = context.Banks.FirstOrDefault(t => t.BankCode == bankPayments.Bank.BankID);
                    var currentUser = Helpers.UserHelpers.GetUserByID(UserId);
                    entity.BankAccount SourceAccount;
                    SourceAccount = currentUser.BankAccounts.FirstOrDefault(t => t.IBAN == bankPayments.Account.IBan);
                    if (SourceAccount == null)
                    {
                        SourceAccount = new entity.BankAccount
                        {
                            IBAN = bankPayments.Account.IBan,
                            AccountNumber = (long)bankPayments.Account.AccountID
                        };
                        SourceAccount.Bank =
                            context.Banks.FirstOrDefault(t => t.BankCode == bankPayments.Account.Bank.BankID) ?? new entity.Bank
                            {
                                BankCode = (short)bankPayments.Account.Bank.BankID,
                                Name=String.Empty
                            };
                        currentUser.BankAccounts.Add(SourceAccount);
                        context.BankAccounts.Add(SourceAccount);
                    }

                    ImportWithPocessedTransactions = new Import
                    {
                        Account = new data.ImportedBankAccount
                        {
                            Bank = bankPayments.Account.Bank,
                            AccountID = bankPayments.Account.AccountID,
                            IBan = bankPayments.Account.IBan,
                            Payments = new List<ImportedPayment>()
                        },//bankPayments.Account,
                        From = bankPayments.From,
                        To = bankPayments.To
                    };

                    //entity.Bank bank = context.Banks.FirstOrDefault(t => t.BankCode == bankPayments.Account.Bank.BankID);
                    using (var dbTransaction = context.Database.BeginTransaction())
                    {
                        foreach (Payment transaction in bankPayments.Account.Payments)
                        {

                            if (IsTransactionExist(context, transaction))
                            {
                                //ImportedPayment tr = new ImportedPayment(false);
                                //tr.VariableSymbol = transaction.VariableSymbol;
                                //ImportWithPocessedTransactions.Account.Payments.Add(tr);
                                ImportedPayment tr = transaction as ImportedPayment;
                                tr.Imported = false;
                                ImportWithPocessedTransactions.Account.Payments.Add(tr);
                                continue;
                            }
                            entity.Entry newTransaction = new entity.Entry
                            {
                                ConstantSymbol = transaction.ConstantSymbol,
                                VariableSymbol = transaction.VariableSymbol,
                                SpecificSymbol = transaction.SpecificSymbol,
                                Reference = transaction.Reference,
                                DateAvailable = transaction.DateAvailable,
                                DatePosted = transaction.DatePosted,
                                Memo = transaction.Description,
                                Name = transaction.TransactionName,
                                DateAdded = DateTime.Now,
                                AmountInfo = new entity.AmountInfo
                                {
                                    Amount = Math.Abs(transaction.TransactionAmount.Amount),
                                    Currency = transaction.TransactionAmount.Currency
                                },
                                //Bank = GetBank(context, transaction.BankName.Localise())
                            };
                            var account =
                                context.BankAccounts.FirstOrDefault(t => t.IBAN == transaction.BankAccount.IBan);
                            if (account != null)
                            {
                                newTransaction.DestinationAccountId = account.Id;
                            }
                            else
                            {
                                newTransaction.DestinationAccount = new entity.BankAccount
                                {
                                    AccountNumber = (long?) transaction.BankAccount.AccountID,
                                    //BankCode = (short?) transaction.BankAccount.BankID,
                                    IBAN = transaction.BankAccount.IBan,
                                    Bank =
                                        (transaction?.BankAccount?.Bank?.BankID.HasValue != null &&
                                         transaction.BankAccount.Bank.BankID.HasValue)
                                            ? GetBank(context, transaction.BankAccount.Bank.BankID.Value)
                                            : null,
                                    UserId = null
                                };
                            }
                            if (transaction.TransactionAmount.Type != AmountType.NotDefined)
                            {
                                newTransaction.AmountInfo.Type = transaction.TransactionAmount.Type == AmountType.Credit
                                    ? GetTransactionType(context, "Credit")
                                    : GetTransactionType(context, "Debit");
                            }
                            else
                            {
                                newTransaction.AmountInfo.Type = transaction.TransactionAmount.Amount < 0
                                    ? GetTransactionType(context, "Debit")
                                    : GetTransactionType(context, "Credit");
                            }
                            SourceAccount.Entries.Add(newTransaction);
                            ImportedPayment importedTr = transaction as ImportedPayment; //new ImportedPayment(true);
                            importedTr.Imported = true;

                            //importedTr.VariableSymbol = transaction.VariableSymbol;
                            ImportWithPocessedTransactions.Account.Payments.Add(importedTr);
                            //Payment tran = new Payment();
                            //tran.VariableSymbol = transaction.VariableSymbol;
                            //ImportWithPocessedTransactions.Account.Payments.Add(tran);
                            //break;
                            context.SaveChanges();
                        }
                        dbTransaction.Commit();
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception("Nastala chyba pri ukladani importu!", e);
            }
            return ImportWithPocessedTransactions;
        }
 private TransactionCategory CreateTransactionCategory(SpendingReportEntities context)
 {
     var category = new TransactionCategory();
     context.TransactionCategories.Add(category);
     return category;
 }
 /// <summary>
 /// Checks if transaction allready exists in the database.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="transaction">The transaction.</param>
 /// <returns></returns>
 private bool IsTransactionExist(SpendingReportEntities context, Payment transaction)
 {
     var date = transaction.DateAvailable;
     var item =
         context.Entries.Where(
             t =>
                 t.AmountInfo.Amount == transaction.TransactionAmount.Amount && t.Name == transaction.TransactionName &&
                 t.Memo == transaction.Description &&
                 t.DateAvailable == date);
     return item.Any();
 }
 /// <summary>
 /// Gets the type of the transaction.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="type">The type.</param>
 /// <returns></returns>
 private entity.Type GetTransactionType(SpendingReportEntities context, string type)
 {
     return context.Types.FirstOrDefault(
         item => item.TypeName.ToLower().Trim() == type.ToLower().Trim());
 }
 private entity.Bank GetBank(SpendingReportEntities context, ushort bankCode)
 {
     return context.Banks.FirstOrDefault(
         item => item.BankCode == bankCode);
 }
 private entity.Bank GetBank(SpendingReportEntities context, string Name)
 {
     return context.Banks.FirstOrDefault(
         item => item.Name.ToLower().Trim() == Name.ToLower().Trim());
 }
        private IEnumerable<Entry> GetTransactionsByCategory(string description, SpendingReportEntities context)
        {
            try
            {
                IOrderedQueryable<Entry> transactions = context.Entries.Where(
                    e => e.Memo.Contains(description) || e.Name.Contains(description))
                    .Include("DestinationAccount")
                    .Include("DestinationAccount.Bank")
                    .Include("AmountInfo")
                    .OrderBy(a => a.DatePosted);

                return transactions;

            }
            catch (Exception ex)
            {
                throw new Exception("Error occured in getting all transactions.", ex);
            }
        }
 public void UpdateAllCategories()
 {
     try
     {
         using (var context = new SpendingReportEntities())
         {
             var categories = context.TransactionCategories;
             foreach (var transactionCategory in categories)
             {
                 UpdateCategories(transactionCategory);
             }
         }
     }
     catch (Exception ex)
     {
         throw new Exception("Error occured in update categories!", ex);
     }
 }
        private void UpdateCategories(string Description, int transactionCategoryID)
        {
            using (var context = new SpendingReportEntities())
            {
                TransactionCategory transactionCategory;
                try
                {
                    transactionCategory =
                        context.TransactionCategories.SingleOrDefault(i => i.Id == transactionCategoryID);
                }
                catch (Exception ex)
                {
                    throw new Exception("There are more transaction descriptions with id: " + transactionCategoryID, ex);
                }
                var transactions = GetTransactionsByCategory(Description, context);
                foreach (var transaction in transactions)
                {
                    if (!transaction.TransactionCategories.Contains(transactionCategory))
                    {
                        transaction.TransactionCategories.Add(transactionCategory);
                    }

                }
                context.SaveChanges();
            }
        }