Exemplo n.º 1
0
        public async Task <IActionResult> PutExpenses(long id, Expenses expenses)
        {
            if (id != expenses.Id)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
Exemplo n.º 2
0
        public async Task <IReadOnlyList <Statement> > DeleteByInvoiceIdAsync(Guid invoiceId)
        {
            var statements = _expensesContext.Statements.Where(i => i.InvoiceId == invoiceId).ToList();

            _expensesContext.Statements.RemoveRange(statements);
            await _expensesContext.SaveChangesAsync();

            return(statements);
        }
Exemplo n.º 3
0
        private async Task UpdateItemAsync(BudgetPlanningItem budgetPlanningItem)
        {
            var item = db.BudgetPlanningItems.Find(budgetPlanningItem.Id);

            if (item != null)
            {
                db.BudgetPlanningItems.AddOrUpdate(budgetPlanningItem);
                await db.SaveChangesAsync();
            }
        }
        public async Task <IActionResult> PostExpense([FromBody] PostExpenseRequest request)
        {
            _dbContext.Add(new Expense()
            {
                Amount      = request.Amount,
                Description = request.Description,
                ExternalId  = request.ExpenseId
            });

            await _dbContext.SaveChangesAsync();

            return(Ok());
        }
        //create User
        public async Task <User> CreatedUserAsync(User user)
        {
            try
            {
                user.Password = GenerateHashedPassword(user.Password);
                _context.Users.Add(user);
                await _context.SaveChangesAsync();

                return(user);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
            public async Task <ExpenseTypeDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var user = await _context.Users.SingleAsync(x => x.Email == _currentUser.EmailId,
                                                            cancellationToken);

                if (await _context.ExpenseTypes.AnyAsync(
                        x => x.Name == request.Name && x.User == user,
                        cancellationToken))
                {
                    throw new HttpException(
                              HttpStatusCode.BadRequest,
                              new
                    {
                        Error = $"There is already a type with name {request.Name}."
                    });
                }

                var expenseType = new ExpenseType(
                    request.Name,
                    request.Description,
                    user);

                await _context.ExpenseTypes.AddAsync(
                    expenseType,
                    cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                return(new ExpenseTypeDto(
                           expenseType.Id,
                           expenseType.Name,
                           expenseType.Description));
            }
Exemplo n.º 7
0
            public async Task <UserDetailsDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                try
                {
                    new RegionInfo(request.CurrencyRegionName);
                }
                catch
                {
                    throw new HttpException(
                              HttpStatusCode.BadRequest,
                              new { Error = "Display currency is not yet supported" });
                }

                var user = await _context.Users.SingleAsync(
                    x => x.Email == _currentUser.EmailId,
                    cancellationToken);

                user.SystemName         = request.SystemName;
                user.CurrencyRegionName = request.CurrencyRegionName;
                user.UseDarkMode        = request.UseDarkMode;

                await _context.SaveChangesAsync(cancellationToken);

                return(new UserDetailsDto(
                           user.SystemName,
                           user.CurrencyRegionName,
                           user.UseDarkMode));
            }
        //create new expense
        public async Task <Expense> CreateExpenseAsync(Expense newExpense)
        {
            try
            {
                newExpense.Date = DateTime.Today;
                await _userValidationRepository.IsUserValid(newExpense.UserId);

                _context.Expenses.Add(newExpense);
                await _context.SaveChangesAsync();

                return(newExpense);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 9
0
        public async Task Add(Category category)
        {
            var entity = new CategoryEntity
            {
                Id = category.Name
            };

            _context.Categories.Add(entity);
            await _context.SaveChangesAsync();
        }
Exemplo n.º 10
0
        public async Task <ActionResult> NewCharge(ChargeModel chargeModel)
        {
            var employee = await this.GetEmployee();

            var employeeId = employee.Item1;

            ViewBag.UserName = employee.Item2;

            if (ModelState.IsValid)
            {
                db.Charges.Add(chargeModel.ConvertToDbCharge(employeeId));
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(chargeModel));
        }
Exemplo n.º 11
0
        public async Task Add(Expense expense)
        {
            var entity = new ExpenseEntity
            {
                Amount     = expense.Amount,
                CategoryId = expense.Category,
            };

            _context.Expenses.Add(entity);
            await _context.SaveChangesAsync();

            expense.Id = entity.Id;
        }
Exemplo n.º 12
0
        public async Task <IHttpActionResult> PostCategory(BudgetItem budgetItem)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string userId = User.Identity.GetUserId();

            budgetItem.UserId = userId;

            db.BudgetItems.Add(budgetItem);
            await db.SaveChangesAsync();

            return(Ok());
        }
Exemplo n.º 13
0
            public async Task <UserDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var email = GetIdentifierFromExpiredToken(request.Token).Value;

                var user = await _context.Users.Include(u => u.RefreshTokens)
                           .SingleAsync(
                    x => x.Email == email && !x.Archived,
                    cancellationToken);

                if (user == null)
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }

                if (!user.IsValidRefreshToken(request.RefreshToken))
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }

                var refreshToken = _jwtTokenGenerator.GenerateRefreshToken();

                user.RemoveRefreshToken(request.RefreshToken);
                user.AddRefreshToken(
                    refreshToken,
                    user.Id);
                var token = await _jwtTokenGenerator.CreateToken(user.Email);

                await _context.SaveChangesAsync(cancellationToken);

                return(new UserDto(
                           user.FirstName,
                           user.LastName,
                           user.FullName,
                           user.SystemName,
                           user.Email,
                           token,
                           refreshToken,
                           user.CurrencyRegionName,
                           user.UseDarkMode));
            }
            public async Task <Unit> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var expenseCategory = await _context.ExpenseCategories.FirstOrDefaultAsync(
                    x => x.Id == request.Id,
                    cancellationToken);

                if (expenseCategory == null)
                {
                    throw new Exception("Not Found");
                }

                expenseCategory.Archive();
                await _context.SaveChangesAsync(cancellationToken);

                return(Unit.Value);
            }
Exemplo n.º 15
0
            public async Task <UserDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var user = await _context.Users.SingleOrDefaultAsync(
                    x => x.Email == request.Email && !x.Archived,
                    cancellationToken);

                if (user == null)
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }

                if (!user.Hash.SequenceEqual(
                        _passwordHasher.Hash(
                            request.Password,
                            user.Salt)))
                {
                    throw new HttpException(
                              HttpStatusCode.Unauthorized,
                              new { Error = "Invalid credentials." });
                }
                // generate refresh token
                var refreshToken = _jwtTokenGenerator.GenerateRefreshToken();

                user.AddRefreshToken(refreshToken, user.Id);

                var token = await _jwtTokenGenerator.CreateToken(request.Email);

                await _context.SaveChangesAsync(cancellationToken);

                return(new UserDto(
                           user.FirstName,
                           user.LastName,
                           user.FullName,
                           user.SystemName,
                           user.Email,
                           token,
                           refreshToken,
                           user.CurrencyRegionName,
                           user.UseDarkMode));
            }
Exemplo n.º 16
0
        public async Task <IActionResult> Create([Bind("ExpenseId,Name,Description,Created,DateFor,Value,Paid,PaidDate,PaidValue,IAmPayer,InteractorId")] Expense expense)
        {
            expense.Created = DateTime.UtcNow;
            if (ModelState.IsValid)
            {
                _context.Add(expense);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["InteractorId"] = new SelectList(_context.Set <Interactor>(), "InteractorId", "Name", expense.InteractorId);
            return(View(expense));
        }
Exemplo n.º 17
0
            public async Task <UserDetailsDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var user = await _context.Users.SingleAsync(
                    x => x.Email == _currentUser.EmailId,
                    cancellationToken);

                user.SystemName         = request.SystemName;
                user.CurrencyRegionName = request.CurrencyRegionName;
                user.UseDarkMode        = request.UseDarkMode;

                await _context.SaveChangesAsync(cancellationToken);

                return(new UserDetailsDto(
                           user.SystemName,
                           user.CurrencyRegionName,
                           user.UseDarkMode));
            }
Exemplo n.º 18
0
            public async Task <ProfileDetailsDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var user = await _context.Users.SingleAsync(
                    x => x.Email == _currentUser.EmailId,
                    cancellationToken);

                user.UpdateName(
                    request.FirstName,
                    request.LastName);

                await _context.SaveChangesAsync(cancellationToken);

                return(new ProfileDetailsDto(
                           user.FirstName,
                           user.LastName,
                           user.FullName));
            }
Exemplo n.º 19
0
            public async Task <ExpenseDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var user = await _context.Users.SingleAsync(x => x.Email == _currentUser.EmailId);

                var expenseCategory = await _context.ExpenseCategories.SingleAsync(
                    x => x.Id == request.CategoryId,
                    cancellationToken);

                var expenseType = await _context.ExpenseTypes.SingleAsync(
                    x => x.Id == request.TypeId,
                    cancellationToken);

                var expense = new Expense(
                    request.Date,
                    expenseCategory,
                    _context.ExpenseTypes.SingleOrDefaultAsync(
                        x => x.Id == request.TypeId,
                        cancellationToken).Result,
                    request.Value,
                    request.Comments,
                    user);

                await _context.Expenses.AddAsync(
                    expense,
                    cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                return(new ExpenseDto(
                           expense.Id,
                           expense.Date.ToString("yyyy-MM-dd"),
                           expenseCategory.Id,
                           expenseCategory.Name,
                           expenseCategory.Budget,
                           expenseCategory.ColourHex,
                           expenseType.Id,
                           expenseType.Name,
                           expense.Value,
                           expense.Comments));
            }
            public async Task <ExpenseCategoryDto> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var user = await _context.Users.SingleAsync(x => x.Email == _currentUser.EmailId,
                                                            cancellationToken);

                if (await _context.ExpenseCategories.AnyAsync(
                        x => x.Name == request.Name && x.User == user,
                        cancellationToken))
                {
                    throw new HttpException(
                              HttpStatusCode.BadRequest,
                              new
                    {
                        Error = $"There is already a category with name {request.Name}."
                    });
                }

                var expenseCategory = new ExpenseCategory(
                    request.Name,
                    request.Description,
                    request.Budget,
                    request.ColourHex,
                    user);

                await _context.ExpenseCategories.AddAsync(
                    expenseCategory,
                    cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                return(new ExpenseCategoryDto(
                           expenseCategory.Id,
                           expenseCategory.Name,
                           expenseCategory.Description,
                           expenseCategory.Budget,
                           expenseCategory.ColourHex));
            }
Exemplo n.º 21
0
            public async Task <Unit> Handle(
                Command request,
                CancellationToken cancellationToken)
            {
                var user = await _context.Users.SingleOrDefaultAsync(
                    x => x.Email == request.Email,
                    cancellationToken);

                if (user != null)
                {
                    throw new HttpException(
                              HttpStatusCode.BadRequest,
                              new
                    {
                        Error = $"There is already a user with email {request.Email}."
                    });
                }


                var salt    = Guid.NewGuid().ToByteArray();
                var newUser = new User(
                    request.FirstName,
                    request.LastName,
                    request.Email,
                    _passwordHasher.Hash(
                        "test",
                        salt),
                    salt);

                await _context.Users.AddAsync(
                    newUser,
                    cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                return(Unit.Value);
            }
Exemplo n.º 22
0
        public async Task <IHttpActionResult> PostExpense(Expense expense)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string userId = User.Identity.GetUserId();

            expense.UserId = userId;

            db.Expenses.Add(expense);
            await db.SaveChangesAsync();


            //// Get the settings for the server project.
            //HttpConfiguration config = this.Configuration;
            ////MobileAppSettingsDictionary settings =
            ////    this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();

            //// Get the Notification Hubs credentials for the mobile app.
            //string listenConnectionString = "Endpoint=sb://sergiynotificationhub.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=HL9tpugxzELLM7bz/EH1XqE/uxuGHK+i6X2/jPNVCFY=";
            //string notificationHubName = "XamarinAndroidNotificationsHub";
            ////string notificationHubName = settings.NotificationHubName;
            ////string notificationHubConnection = settings
            ////    .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;

            //var notificationHubConnection = listenConnectionString;


            //// Create a new Notification Hub client.
            //NotificationHubClient hub = NotificationHubClient
            //.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);

            //// Send the message so that all template registrations that contain "messageParam"
            //// receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
            //Dictionary<string, string> templateParams = new Dictionary<string, string>();
            //templateParams["messageParam"] = expense.Name + " was added to the list.";

            //try
            //{
            //    // Send the push notification and log the results.
            //    var result = await hub.SendTemplateNotificationAsync(templateParams);

            //    // Write the success result to the logs.
            //    config.Services.GetTraceWriter().Info(result.State.ToString());
            //}
            //catch (System.Exception ex)
            //{
            //    // Write the failure result to the logs.
            //    config.Services.GetTraceWriter()
            //        .Error(ex.Message, null, "Push.SendAsync Error");
            //}

            //NotificationsSender notificationsSender = new NotificationsSender();

            //var user_Id = HttpContext.Current.User.Identity.GetUserId();
            ////var result = await notificationsSender.SendNotification("fcm", $"Expense {expense.Name} on {expense.Money.ToString()} was added", user_Id);

            //NotificationService notificationService = new NotificationService();

            //var devices = new DevicesContext().Devices.ToList();

            //var neededAndroidDevice = devices.Where((x, y) => x.UserId == user_Id && x.Platform == "Android").FirstOrDefault();
            //notificationService.SendAndroidNotification(neededAndroidDevice.DeviceToken, $"Expense {expense.Name} on {expense.Money.ToString()} was added");

            //var neededAppleDevice = devices.Where((x, y) => x.UserId == userId && x.Platform == "iOS").FirstOrDefault();
            //notificationService.SendAppleNotification(neededAppleDevice.DeviceToken, $"Expense {expense.Name} on {expense.Money.ToString()} was added");

            return(CreatedAtRoute("DefaultApi", new { id = expense.Id }, expense));
        }