示例#1
0
        public List <Collections> GetCollections(List <string> collectionsIds, int count)
        {
            //get collections
            List <Collections> collections = new List <Collections>();

            try
            {
                using (FinPlannerContext _context = new FinPlannerContext())
                {
                    collections = _context
                                  .Collections
                                  .Where(col => collectionsIds.Contains(col.CollectionsId))
                                  .ToList();
                }
            }
            catch (Exception e)
            {
                ExceptionCatcher catcher = new ExceptionCatcher();
                catcher.Catch(e.Message);
            }
            //get accounts
            Account        account  = new Account();
            List <Account> accounts = account.GetAccountIndex(collectionsIds, count);

            //assign accounts
            foreach (Collections item in collections)
            {
                item.Accounts = accounts.Where(x => x.CollectionsId == item.CollectionsId).ToList();
            }
            return(collections);
        }
示例#2
0
        public ReturnModel AddAccount(Account account)
        {
            ReturnModel model = new ReturnModel();

            account.AccountIdentifier = "xxxx" + account.AccountIdentifier;
            using (FinPlannerContext _context = new FinPlannerContext())
            {
                if (account.Id == null)
                {
                    account.Id = Guid.NewGuid().ToString();
                    _context.Account.Add(account);
                }
                else
                {
                    Account account1 = _context.Account.Find(account.Id);
                    account1.Update(account);
                    _context.Entry(account1).State = EntityState.Modified;
                }
                try
                {
                    _context.SaveChanges();
                    model.result = true;
                }
                catch (Exception e)
                {
                    model.result    = false;
                    model.returnStr = e.Message;
                    ExceptionCatcher catcher = new ExceptionCatcher();
                    catcher.Catch(e.Message);
                }
            }
            return(model);;
        }
示例#3
0
            public async Task <YodleeAuthReturn> GetToken(string loginName)
            {
                HttpClient client = new HttpClient();

                client.DefaultRequestHeaders.Add("loginName", loginName);
                client.DefaultRequestHeaders.Add("Api-Version", "1.1");
                var dict = new Dictionary <string, string>();

                dict.Add("clientId", ClientID);
                dict.Add("secret", secret);
                dict.Add("Content-Type", "application/x-www-form-urlencoded");
                var content = new FormUrlEncodedContent(dict);
                HttpResponseMessage response = await client.PostAsync(url + "/auth/token", content);

                if (response.IsSuccessStatusCode)
                {
                    string tokenStr = await response.Content.ReadAsStringAsync();

                    YodleeAuthReturn responseToken = JsonConvert.DeserializeObject <YodleeAuthReturn>(tokenStr);
                    return(responseToken);
                }
                else
                {
                    string tokenStr = await response.Content.ReadAsStringAsync();

                    ExceptionCatcher exceptionCatcher = new ExceptionCatcher();
                    exceptionCatcher.Catch(tokenStr);
                }
                return(null);
            }
示例#4
0
        public async Task <string> getToken(string collectionsId, string userId)
        {
            YodleeAuthReturn authReturn  = new YodleeAuthReturn();
            ReturnModel      returnModel = new ReturnModel();

            if (Check(collectionsId))
            {
                authReturn = await authReturn.GetToken(GetLoginName(collectionsId));

                if (authReturn == null)
                {
                    ExceptionCatcher exceptionCatcher = new ExceptionCatcher();
                    exceptionCatcher.Catch("auth return null ");
                }
                returnModel.returnStr = authReturn.token.accessToken;
            }
            else
            {
                if (userId != "")
                {
                    returnModel = await Register(userId, collectionsId);
                }
            }
            return(returnModel.returnStr);
        }
示例#5
0
        public bool CollectionCycle()
        {
            List <Collections> collections = GetCollections("", "");
            DateTime           date        = DateTime.Now.Date;

            try
            {
                foreach (Collections item in collections)
                {
                    Budget budget = item.Budgets.OrderByDescending(x => x.EndDate).FirstOrDefault();
                    if (budget != null)
                    {
                        if (budget.EndDate <= date)
                        {
                            budget.Duplicate(item);
                        }
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                ExceptionCatcher exception = new ExceptionCatcher();
                exception.Catch(e.Message);
                return(false);
            }
        }
示例#6
0
        public async Task <bool> UpdateAccounts(string collectionsId, List <Account> accounts)
        {
            YodleeAccountModel        model          = new YodleeAccountModel();
            List <YodleeAccountLevel> yodleeAccounts = await model.GetYodleeAccounts(collectionsId);

            try
            {
                using (FinPlannerContext _context = new FinPlannerContext())
                {
                    foreach (Account item in accounts)
                    {
                        if (item.YodleeId == 0 && item.AccountIdentifier != null)
                        {
                            item.YodleeId = yodleeAccounts.Where(x => x.accountNumber == item.AccountIdentifier).Select(x => x.id).FirstOrDefault();
                        }
                        else
                        {
                            YodleeAccountLevel accountLevel = yodleeAccounts.Where(x => x.accountNumber == item.AccountIdentifier).FirstOrDefault();
                            if (accountLevel != null)
                            {
                                if (accountLevel.availableBalance != null)
                                {
                                    item.Available = accountLevel.availableBalance.amount;
                                }
                                else if (accountLevel.availableCredit != null)
                                {
                                    item.Available = accountLevel.availableCredit.amount;
                                }
                                else
                                {
                                    item.Available = accountLevel.balance.amount;
                                }
                            }
                        }
                        _context.Entry(item).State = EntityState.Modified;
                        AccountBalance balance = new AccountBalance()
                        {
                            AccountBalanceId = Guid.NewGuid().ToString(),
                            AccountId        = item.Id,
                            Amount           = item.Available,
                            Date             = DateTime.Now.Date
                        };
                        _context.Add(balance);
                    }

                    _context.SaveChanges();
                }
                return(true);
            }
            catch (Exception e)
            {
                ExceptionCatcher catcher = new ExceptionCatcher();
                catcher.Catch(e.Message);
                return(false);
            }
        }
        private void SendEmail(string ToEmail, string Message, string Subject, string Name)
        {
            SmtpClient client = new SmtpClient(SMTPServer, port)
            {
                UseDefaultCredentials = false,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                Credentials           = new NetworkCredential(FromEmail, password),
                EnableSsl             = true,
                Timeout = 200000
            };
            MailAddress from    = new MailAddress(FromEmail, "Admin", System.Text.Encoding.UTF8);
            MailAddress to      = new MailAddress(ToEmail);
            MailMessage message = new MailMessage(from, to);

            if (Subject == "Confirm your account")
            {
                string text       = "";
                var    webRequest = WebRequest.Create(@"https://storageaccountmoney9367.blob.core.windows.net/emailimages/EmailValidation.txt");
                using (var response = webRequest.GetResponse())
                    using (var content = response.GetResponseStream())
                        using (var reader = new StreamReader(content))
                        {
                            text = reader.ReadToEnd();
                        };
                text         = text.Replace("www.google.com", Message);
                message.Body = text.Replace("[guest_name]", Name);
            }
            else
            {
                message.Body = Message;
            }
            message.Subject         = Subject;
            message.IsBodyHtml      = true;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            EmailStore emailStore = new EmailStore()
            {
                Body         = message.Body,
                To           = to.ToString(),
                From         = from.ToString(),
                EmailDate    = DateTime.Now,
                EmailStoreId = Guid.NewGuid().ToString(),
                Subject      = Subject
            };

            emailStore.Save();
            try
            {
                client.Send(message);
            }
            catch (SmtpException e)
            {
                ExceptionCatcher catcher = new ExceptionCatcher();
                catcher.Catch(e.Message);
            }
        }
示例#8
0
        private async Task <ReturnModel> Register(string userId, string collectionsId)
        {
            YodleeAuthReturn auth = await GetAdminAuth();

            ReturnModel returnModel = new ReturnModel();

            if (auth.token.accessToken != null)
            {
                YodleeModel yodleeModel = new YodleeModel();
                if (!Check(collectionsId))
                {
                    yodleeModel = new YodleeModel(collectionsId, "New");
                }
                else
                {
                    yodleeModel = new YodleeModel(collectionsId, "Get");
                }
                AspNetUsers   user          = new AspNetUsers();
                UserNames     userNames     = user.getNames(userId);
                RegisterModel registerModel = new RegisterModel(yodleeModel.loginName, userNames);

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Api-Version", "1.1");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.token.accessToken);
                StringContent       content  = new StringContent(JsonConvert.SerializeObject(registerModel), Encoding.UTF8, "application/json");
                HttpResponseMessage response = await client.PostAsync(url + "/auth/register", content);

                if (response.IsSuccessStatusCode)
                {
                    YodleeAuthReturn authReturn = new YodleeAuthReturn();
                    authReturn = await authReturn.GetToken(yodleeModel.loginName);

                    returnModel.result    = true;
                    returnModel.returnStr = authReturn.token.accessToken;
                }
                else
                {
                    string tokenStr = await response.Content.ReadAsStringAsync();

                    ExceptionCatcher exceptionCatcher = new ExceptionCatcher();
                    exceptionCatcher.Catch(tokenStr);
                    returnModel.result = false;
                }
            }
            else
            {
                ExceptionCatcher catcher = new ExceptionCatcher();
                catcher.Catch("No Token generated");
                returnModel.result = false;
            }
            return(returnModel);
        }
示例#9
0
 public void BankCharges(Collections collection)
 {
     try
     {
         Budget budget = collection.Budgets.Where(x => x.Simulation == false).OrderByDescending(x => x.EndDate).First();
         double fees   = 0;
         foreach (Account acc in collection.Accounts.Where(x => x.AccountType.Transactional == true))
         {
             fees = fees + acc.MonthlyFee;
             double debt = acc.AccountLimit - acc.Available;
             if (debt > 0)
             {
                 fees = fees + debt * (acc.CreditRate / 12 / 100);
             }
         }
         fees = Math.Round(fees, 2);
         budget.GetBudgetTransacions();
         using (FinPlannerContext _context = new FinPlannerContext())
         {
             if (budget.BudgetTransactions.Where(x => x.CFType.Name == "Bank Charges" && x.Automated == true).Any())
             {
                 BudgetTransaction transaction = budget.BudgetTransactions.Where(x => x.CFType.Name == "Bank Charges" && x.Automated == true).FirstOrDefault();
                 transaction.Amount = fees;
                 _context.Entry(transaction).State = EntityState.Modified;
             }
             else
             {
                 CFClassification  classification = new CFClassification("Expense");
                 CFType            type           = new CFType("Bank Charges");
                 BudgetTransaction transaction    = new BudgetTransaction()
                 {
                     BudgetId            = budget.BudgetId,
                     Automated           = true,
                     BudgetTransactionId = Guid.NewGuid().ToString(),
                     CFClassificationId  = classification.Id,
                     CFTypeId            = type.Id,
                     Name   = "Automated Bank Charges",
                     Amount = fees,
                 };
                 _context.Add(transaction);
             }
             _context.SaveChanges();
         }
     }
     catch (Exception e)
     {
         ExceptionCatcher catcher = new ExceptionCatcher();
         catcher.Catch(e.Message);
     }
 }
        public void Catch(string e)
        {
            ExceptionCatcher catcher = new ExceptionCatcher()
            {
                Id        = Guid.NewGuid().ToString(),
                DateTime  = DateTime.Now,
                Exception = e
            };

            using (FinPlannerContext _context = new FinPlannerContext())
            {
                _context.ExceptionCatcher.Add(catcher);
                _context.SaveChanges();
            }
        }
示例#11
0
 public void Save()
 {
     using (FinPlannerContext _context = new FinPlannerContext())
     {
         _context.EmailStore.Add(this);
         try
         {
             _context.SaveChanges();
         }
         catch (Exception e)
         {
             ExceptionCatcher catcher = new ExceptionCatcher();
             catcher.Catch(e.Message);
         }
     }
 }
示例#12
0
 private string userIdGet(string userid)
 {
     using (FinPlannerContext _context = new FinPlannerContext())
     {
         try
         {
             return(_context.AspNetUsers.Where(x => x.Email == userid).Select(x => x.Id).FirstOrDefault());
         }
         catch (Exception e)
         {
             ExceptionCatcher catcher = new ExceptionCatcher();
             catcher.Catch(e.Message);
             return("error");
         }
     }
 }
示例#13
0
        /// <summary>
        /// The landing page is made up of a series of object this returns a list of the collection ojects high level details
        /// </summary>
        /// <param name="email">Users email address</param>
        /// <returns>Returns a list of index model objetcts</returns>
        public List <IndexModel> GetModel(string email)
        {
            List <IndexModel>     model         = new List <IndexModel>();
            List <string>         collectionIds = new List <string>();
            UserCollectionMapping mapping       = new UserCollectionMapping();
            string userId = "";

            try
            {
                FirebaseUser user = new FirebaseUser();
                userId        = user.GetFirebaseUser(email);
                collectionIds = mapping.getCollectionIds(userId, "firebase");
            }
            catch
            {
                AspNetUsers user = new AspNetUsers();
                userId        = user.getUserId(email);
                collectionIds = mapping.getCollectionIds(userId, "asp");
            }
            Collections        collection  = new Collections();
            Account            account     = new Account();
            Budget             budget      = new Budget();
            List <Collections> collections = collection.GetEagerList(collectionIds);

            foreach (Collections item in collections)
            {
                try
                {
                    IndexModel temp = new IndexModel();
                    temp.Name          = item.Name;
                    temp.CollectionsId = item.CollectionsId;
                    temp.Avaialble     = account.GetAvaialable(item.CollectionsId);
                    temp.Budgeted      = Math.Round(budget.GetBudgetedAmount(item.CollectionsId), 2).ToString("N2");
                    temp.Used          = Math.Round(budget.GetSpentAmount(item.CollectionsId), 2).ToString("N2");
                    temp.isShared      = mapping.IsShared(item.CollectionsId);
                    model.Add(temp);
                }
                catch (Exception e)
                {
                    ExceptionCatcher catcher = new ExceptionCatcher();
                    catcher.Catch(e.Message);
                }
            }
            return(model);
        }
示例#14
0
 public void updateTransaction(string manId, string autoId)
 {
     try
     {
         using (FinPlannerContext _context = new FinPlannerContext())
         {
             ManualCashFlow man = _context.ManualCashFlows.Find(manId);
             man.AutomatedCashFlowId   = autoId;
             _context.Entry(man).State = EntityState.Modified;
             _context.SaveChanges();
         }
     }
     catch (Exception e)
     {
         ExceptionCatcher exceptionCatcher = new ExceptionCatcher();
         exceptionCatcher.Catch(e.Message);
     }
 }
        public void Create(Account account, PaymentModel payment, AccountAmortisation amortisation)
        {
            DateTime end   = account.Maturity;
            DateTime start = DateTime.Now;

            start = new DateTime(start.Year, start.Month, end.Day);
            List <MonthlyAmortisation> monthlies = new List <MonthlyAmortisation>();
            double amount = account.Available;

            for (int i = 0; end.Date > start.AddMonths(i).Date; i++)
            {
                MonthlyAmortisation monthly = new MonthlyAmortisation
                {
                    MonthlyAmortisationId = Guid.NewGuid().ToString(),
                    AccountAmortisationId = amortisation.AccountAmortisationId,
                    Date = start.AddMonths(i),
                    Open = amount
                };
                monthly.Interest   = amount * (account.CreditRate / 12 / 100);
                monthly.Payment    = payment.CostOfLoan;
                monthly.Capital    = monthly.Payment - monthly.Interest;
                monthly.Additional = payment.AdditionalLoan;
                monthly.Close      = amount - monthly.Capital - monthly.Additional;
                monthlies.Add(monthly);
                amount = monthly.Close;
                if (amount < 0)
                {
                    break;
                }
            }
            using (FinPlannerContext _context = new FinPlannerContext())
            {
                _context.AddRange(monthlies);
                try
                {
                    _context.SaveChanges();
                }
                catch (Exception e)
                {
                    ExceptionCatcher catcher = new ExceptionCatcher();
                    catcher.Catch(e.Message);
                }
            }
        }
 public void Update(Account account)
 {
     if (isExists(account.Id))
     {
     }
     else
     {
         AccountAmortisation amortisation = new AccountAmortisation()
         {
             AccountId             = account.Id,
             AccountAmortisationId = Guid.NewGuid().ToString()
         };
         using (FinPlannerContext _context = new FinPlannerContext())
         {
             _context.Add(amortisation);
             try
             {
                 _context.SaveChanges();
             }
             catch (Exception e)
             {
                 ExceptionCatcher catcher = new ExceptionCatcher();
                 catcher.Catch(e.Message);
             }
         }
         PaymentModel payment = new PaymentModel(account, amortisation.AccountAmortisationId);
         using (FinPlannerContext _context = new FinPlannerContext())
         {
             _context.Add(payment);
             try
             {
                 _context.SaveChanges();
             }
             catch (Exception e)
             {
                 ExceptionCatcher catcher = new ExceptionCatcher();
                 catcher.Catch(e.Message);
             }
         }
         MonthlyAmortisation monthly = new MonthlyAmortisation();
         monthly.Create(account, payment, amortisation);
     }
 }
示例#17
0
 public UserNames getNames(string userId)
 {
     using (FinPlannerContext _context = new FinPlannerContext())
     {
         try
         {
             AspNetUsers user = _context.AspNetUsers.Where(x => x.Email == userId).FirstOrDefault();
             return(new UserNames()
             {
                 first = user.firstName, last = user.lastName
             });
         }
         catch (Exception e)
         {
             ExceptionCatcher catcher = new ExceptionCatcher();
             catcher.Catch(e.Message);
             return(new UserNames());
         }
     }
 }
示例#18
0
        public List <BudgetTransaction> GetBudgetTransactions(string budgetId)
        {
            List <BudgetTransaction> transactions = new List <BudgetTransaction>();

            using (FinPlannerContext _context = new FinPlannerContext())
            {
                try
                {
                    transactions = _context.BudgetTransactions.Where(x => x.BudgetId == budgetId).ToList();
                }
                catch (Exception e)
                {
                    ExceptionCatcher catcher = new ExceptionCatcher();
                    catcher.Catch(e.Message);
                }
            }
            foreach (BudgetTransaction item in transactions)
            {
                item.Budget = null;
            }
            return(transactions);
        }
示例#19
0
        public async Task <bool> YodleeAccountConnect()
        {
            List <Collections> collections = GetCollections("", "");
            Account            account     = new Account();
            bool result = true;

            foreach (Collections item in collections.Where(x => x.Accounts.Any()))
            {
                if (item.Accounts.Where(x => x.AccountIdentifier != null).Any())
                {
                    result = await account.UpdateAccounts(item.CollectionsId, item.Accounts.ToList());

                    if (!result)
                    {
                        ExceptionCatcher catcher = new ExceptionCatcher();
                        catcher.Catch("Collestions Id: " + item.CollectionsId);
                    }
                }
                BankCharges(item);
            }
            return(true);
        }
示例#20
0
        /// <summary>
        /// Exlpicit eager articulated list of collection objects
        /// </summary>
        /// <param name="collectionsIds">List of the collection Ids</param>
        /// <returns>Returns a list of collection from the string of Ids supplied</returns>
        public List <Collections> GetEagerList(List <string> collectionsIds)
        {
            List <Collections> collections = new List <Collections>();

            using (FinPlannerContext _context = new FinPlannerContext())
            {
                foreach (string id in collectionsIds)
                {
                    try
                    {
                        collections.Add(_context
                                        .Collections
                                        .Where(x => x.CollectionsId == id)
                                        .FirstOrDefault());
                    }
                    catch (Exception e)
                    {
                        ExceptionCatcher catcher = new ExceptionCatcher();
                        catcher.Catch(e.Message);
                    }
                }
            }
            return(collections);
        }
示例#21
0
 private ReturnModel updateTransaction(AutomatedCashFlow automatedCashFlow)
 {
     using (FinPlannerContext _context = new FinPlannerContext())
     {
         try
         {
             _context.Entry(automatedCashFlow).State = EntityState.Modified;
             _context.SaveChanges();
             return(new ReturnModel()
             {
                 result = true
             });
         }
         catch (Exception e)
         {
             ExceptionCatcher catcher = new ExceptionCatcher();
             catcher.Catch(e.Message);
             return(new ReturnModel()
             {
                 result = false, returnStr = e.Message
             });
         }
     }
 }
示例#22
0
        public bool Create(NewBudgetObj obj)
        {
            string collectionId = obj.CollectionsId;
            //DateTime StartDate = obj.StartDate;
            List <BudgetTransaction> transactions = obj.BudgetTransactions;
            Collections col       = new Collections(collectionId);
            DateTime    EndDate   = new DateTime();
            DateTime    StartDate = DateTime.Now;

            switch (col.DurationType)
            {
            case "Day":
                EndDate = StartDate.AddDays(1);
                break;

            case "Week":
                int dayofweek  = (int)StartDate.DayOfWeek;
                int difference = Math.Abs(dayofweek - col.ResetDay);
                StartDate = StartDate.AddDays(-difference);
                EndDate   = StartDate.AddDays(7);
                break;

            case "Month":
                int day = StartDate.Day;
                if (day == 0)
                {
                    StartDate = new DateTime(StartDate.Year, StartDate.Month, 1).AddMonths(1);
                    StartDate = StartDate.AddDays(-1);
                }
                else if (day >= col.ResetDay)
                {
                    StartDate = new DateTime(StartDate.Year, StartDate.Month, col.ResetDay);
                }
                else
                {
                    StartDate = new DateTime(StartDate.Year, StartDate.Month - 1, col.ResetDay);
                }
                if (col.ResetDay == 28)
                {
                    StartDate = new DateTime(StartDate.Year, StartDate.Month, 1).AddMonths(1);
                    StartDate = StartDate.AddDays(-1);
                }
                EndDate = StartDate.AddMonths(1);
                break;
            }
            if (DateCheck(collectionId, EndDate))
            {
                Budget                   budget = new Budget(collectionId, StartDate, EndDate, false);
                BudgetTransaction        t      = new BudgetTransaction();
                List <BudgetTransaction> list   = t.CreateBudgetTransactions(transactions, budget.BudgetId, budget.CollectionId);
                try
                {
                    using (FinPlannerContext _context = new FinPlannerContext())
                    {
                        _context.Budget.Add(budget);
                        foreach (BudgetTransaction item in list)
                        {
                            _context.BudgetTransactions.Add(item);
                        }
                        _context.SaveChanges();
                    }
                    return(true);
                }
                catch (Exception e)
                {
                    return(false);
                }
            }
            else
            {
                // Now we are simply adding transactions
                using (FinPlannerContext _context = new FinPlannerContext())
                {
                    Budget            budget            = _context.Budget.Where(x => x.CollectionId == collectionId && x.StartDate == StartDate).FirstOrDefault();
                    BudgetTransaction budgetTransaction = new BudgetTransaction();
                    try
                    {
                        List <BudgetTransaction> budgetTransactions = budgetTransaction.GetBudgetTransactions(budget.BudgetId);

                        foreach (BudgetTransaction item in transactions)
                        {
                            //does it exist?
                            bool exists = budgetTransactions
                                          .Where(x => x.BudgetTransactionId == item.BudgetTransactionId)
                                          .Any();
                            //does not exist
                            if (!exists)
                            {
                                _context.BudgetTransactions.Add(new BudgetTransaction(item, budget.BudgetId, budget.CollectionId));
                            }
                            //does exist
                            else
                            {
                                BudgetTransaction newT = _context
                                                         .BudgetTransactions
                                                         .Find(item.BudgetTransactionId);
                                double amount = budgetTransactions
                                                .Where(x => x.BudgetTransactionId == item.BudgetTransactionId)
                                                .Select(x => x.Amount)
                                                .FirstOrDefault();
                                string name = budgetTransactions
                                              .Where(x => x.BudgetTransactionId == item.BudgetTransactionId)
                                              .Select(x => x.Name)
                                              .FirstOrDefault();
                                string typeId = budgetTransactions
                                                .Where(x => x.BudgetTransactionId == item.BudgetTransactionId)
                                                .Select(x => x.CFTypeId)
                                                .FirstOrDefault();
                                //if amount is different
                                if (amount != item.Amount)
                                {
                                    newT.Amount = item.Amount;
                                }
                                //if name is different
                                if (name != item.Name)
                                {
                                    newT.Name = item.Name;
                                }
                                if (typeId != item.CFTypeId)
                                {
                                    newT.CFTypeId = item.CFTypeId;
                                }
                                if (amount != item.Amount || name != item.Name || typeId != item.CFClassificationId)
                                {
                                    _context.Entry(newT).State = EntityState.Modified;
                                }
                            }
                        }
                        //remove deleted items
                        foreach (BudgetTransaction item in budgetTransactions)
                        {
                            //is it in the list
                            bool check = transactions.Where(x => x.BudgetTransactionId == item.BudgetTransactionId).Any();
                            if (!check)
                            {
                                _context.BudgetTransactions.Remove(item);
                            }
                        }
                        _context.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        ExceptionCatcher catcher = new ExceptionCatcher();
                        catcher.Catch(e.Message);
                    }
                }
                return(false);
            }
        }
示例#23
0
        public async Task <bool> UpdateTransactions()
        {
            //Invoke Classes
            CFClassification       classification    = new CFClassification();
            YodleeTransactionModel transactionModel  = new YodleeTransactionModel();
            Collections            collection        = new Collections();
            YodleeTransactionType  transactionType   = new YodleeTransactionType();
            ManualCashFlow         manualCash        = new ManualCashFlow();
            AutomatedCashFlow      automatedCashFlow = new AutomatedCashFlow();
            //Get Static Lists
            List <Collections>      collections     = collection.GetCollections("", "");
            List <CFClassification> classifications = classification.GetList();

            foreach (Collections item in collections.Where(x => x.Accounts.Any()))
            {
                AutomateReturnList returnList = new AutomateReturnList();
                returnList.automateReturns = new List <AutomateReturn>();
                if (item.Accounts.Where(x => x.AccountIdentifier != null).Any())
                {
                    YodleeModel yodlee = new YodleeModel();
                    string      token  = await yodlee.getToken(item.CollectionsId, "");

                    List <YodleeTransactionLevel> transactions = await transactionModel.GetYodleeTransactions(item.CollectionsId, token);

                    if (transactions != null)
                    {
                        DateTime smallest = transactions.Select(x => x.transactionDate).Min();
                        if (smallest > DateTime.MinValue)
                        {
                            smallest = smallest.AddDays(-3);
                        }
                        List <CFType> yodleeTypes = await transactionType.YodleeTransform(token, item.CollectionsId);

                        foreach (Account account in item.Accounts.Where(x => x.YodleeId != 0))
                        {
                            Account tempAccount = account;
                            List <ManualCashFlow> manualFlows = manualCash.GetManualCashFlows(account.Id);
                            foreach (ManualCashFlow m in manualFlows)
                            {
                                m.CFClassification = classifications.Where(x => x.Id == m.CFClassificationId).FirstOrDefault();
                            }
                            account.AutomatedCashFlows = automatedCashFlow.GetAutomatedCashFlows(account.Id, smallest, DateTime.Now.AddDays(1));
                            foreach (YodleeTransactionLevel transaction in transactions.Where(x => x.accountId == account.YodleeId))
                            {
                                if (!account.AutomatedCashFlows.Where(x => x.YodleeId == transaction.id).Any())
                                {
                                    ManualCashFlow manualCashFlow = manualFlows
                                                                    .Where(x => x.AutomatedCashFlowId == null)
                                                                    .Where(x => x.Amount == transaction.amount.amount && x.CFClassification.Name.ToLower() == transaction.categoryType.ToLower() && x.DateBooked > transaction.transactionDate.AddDays(-2) && x.DateBooked < transaction.transactionDate.AddDays(5))
                                                                    .FirstOrDefault();
                                    try
                                    {
                                        returnList.automateReturns.Add(AddTransaction(transaction, account.Id, yodleeTypes, manualCashFlow, classifications, tempAccount));
                                    }
                                    catch (Exception e)
                                    {
                                        ExceptionCatcher catcher = new ExceptionCatcher();
                                        catcher.Catch(e.Message + ";" + JsonConvert.SerializeObject(transaction) + ";" + JsonConvert.SerializeObject(manualCashFlow) + "");
                                    }
                                    if (manualCashFlow != null)
                                    {
                                        manualFlows.Remove(manualCashFlow);
                                    }
                                }
                            }
                            //item.Accounts.Where(x=>x.Id == account.Id).FirstOrDefault() = tempAccount;
                        }
                        try
                        {
                            List <AccountChange>     accChangeList   = new List <AccountChange>();
                            List <AutomatedCashFlow> cashFlows       = new List <AutomatedCashFlow>();
                            List <ManualCashFlow>    manualCashFlows = new List <ManualCashFlow>();
                            //ac
                            foreach (AutomateReturn returnItem in returnList.automateReturns)
                            {
                                if (returnItem.AccountChange.AccountChangeId != "")
                                {
                                    returnItem.AccountChange.Account           = null;
                                    returnItem.AccountChange.AutomatedCashFlow = null;
                                    accChangeList.Add(returnItem.AccountChange);
                                }
                                returnItem.AutomatedCashFlow.Account          = null;
                                returnItem.AutomatedCashFlow.CFClassification = null;
                                cashFlows.Add(returnItem.AutomatedCashFlow);
                                if (returnItem.ManualCashFlow.Id != "")
                                {
                                    manualCashFlows.Add(returnItem.ManualCashFlow);
                                }
                            }
                            using (FinPlannerContext _context = new FinPlannerContext())
                            {
                                _context.AccountChange.AddRange(accChangeList);
                                _context.AutomatedCashFlows.AddRange(cashFlows);
                                foreach (ManualCashFlow manual in manualCashFlows)
                                {
                                    _context.Entry(manual).State = EntityState.Modified;
                                }
                                _context.SaveChanges();
                            }
                        }
                        catch (Exception e)
                        {
                            ExceptionCatcher catcher = new ExceptionCatcher();
                            catcher.Catch(e.Message);
                        }
                    }
                }
            }
            return(true);
        }