示例#1
0
        public async Task <ExpenseDto> CreateExpenseForUserAsync(ExpenseDto expense, string userId)
        {
            var newExpense = new Expense
            {
                Name        = expense.Name,
                OrderNumber = expense.OrderNumber,
                Price       = expense.Price,
                UserId      = userId
            };

            await _context.Expenses.AddAsync(newExpense);

            await _context.SaveChangesAsync();

            expense.Id          = newExpense.Id;
            expense.Name        = newExpense.Name;
            expense.OrderNumber = newExpense.OrderNumber;
            expense.Price       = newExpense.Price;

            return(expense);
        }
示例#2
0
        public IActionResult CreateExpense(ExpenseDto expenseDto)
        {
            // BART: would probably use extensions here to get claims that are used frequently.
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            // BART: code duplicated a lot, would move to action filters, however all this is under authorization attribute, meaning that if userId is null there is something wrong with auth server or transform logic, probably cleaner to delete this check as it seems unnecessary.
            if (string.IsNullOrEmpty(userId))
            {
                return(Unauthorized());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var createdExpense = _expensesRepository.CreateExpense(_expensesMapper.Map(expenseDto, userId));

            return(CreatedAtAction(nameof(GetExpense), new { id = createdExpense.Id.ToString() },
                                   _expensesMapper.Map(createdExpense)));
        }
示例#3
0
        public async Task <ExpenseDto> AddExpenseAsync(ExpenseDto expenseDto, string userId)
        {
            try
            {
                var expense = _mapper.Map <Expense>(expenseDto);
                expense.Id     = null;
                expense.Date   = expense.Date.Date;
                expense.UserId = userId;
                expense.Main   = await IsExpenseMain(expenseDto, userId);

                await _expenseRepository.CreateAsync(expense);

                await _expenseRepository.SaveAsync();

                return(_mapper.Map <ExpenseDto>(expense));
            }
            catch (RepositoryException e)
            {
                throw new ExpenseException("Cannot add expense", e, 400);
            }
        }
示例#4
0
        public IActionResult UpdateExpense(ExpenseDto expenseDto)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (string.IsNullOrEmpty(userId))
            {
                return(Unauthorized());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (_expensesRepository.UpdateExpense(_expensesMapper.Map(expenseDto, userId)))
            {
                return(NoContent());
            }

            return(NotFound());
        }
        public async Task <ExpenseDto> GetExpenseById(int Id)
        {
            if (Id == default)
            {
                throw new ArgumentException($"{Id} is not a vaild identifier.");
            }

            ExpenseEntityDesign expenseEntity = await _expenseRepository.GetExpenseById(Id);

            ExpenseDto expense = new ExpenseDto();

            if (expenseEntity.Name == null && expenseEntity.Amount == 0)
            {
                throw new Exception("Invalid Id");
            }

            expense.Name        = expenseEntity.Name;
            expense.Amount      = expenseEntity.Amount;
            expense.Description = expenseEntity.Description;
            expense.ExpenseDate = expenseEntity.ExpenseDate;

            return(expense);
        }
示例#6
0
        public void CanCalculateExpectedTotals()
        {
            ExpenseDto expenseDto = new ExpenseDto
            {
                Expense = new ExpenseDataDtoBuilder()
                          .WithCostCentre("DEV002")
                          .WithTotal(1024.01m)
                          .Build()
            };
            VendorDto      vendorDto      = new VendorDtoBuilder().Build();
            DescriptionDto descriptionDto = new DescriptionDtoBuilder().Build();
            EventDateDto   eventDateDto   = new EventDateDtoBuilder().Build();

            Expense expense = ExpenseMapper.Map(expenseDto, vendorDto, descriptionDto, eventDateDto);

            expense.CostCentre.Should().Be(expenseDto.Expense.CostCentre);
            expense.TotalInclGst.Should().Be(expenseDto.Expense.Total);
            expense.TotalExclGst.Should().Be(890.44m);
            expense.GstAmount.Should().Be(133.57m);
            expense.Vendor.Should().Be(vendorDto.Vendor);
            expense.Description.Should().Be(descriptionDto.Description);
            expense.EventDate.Should().Be(eventDateDto.Date);
        }
        public IActionResult Create([FromForm] ExpenseCreateViewModel vm)
        {
            if (!TryValidateModel(vm))
            {
                return(View(vm));
            }

            var newExpense = new ExpenseDto
            {
                Description = vm.Description,
                Date        = vm.Date,
                Value       = vm.Value,
                Categorie   = vm.Categorie
            };

            if (vm.Photo != null)
            {
                newExpense.PhotoUrl = _photoService.UploadPhoto(vm.Photo);
            }

            _expensesService.Create(newExpense);
            return(RedirectToAction(nameof(Index)));
        }
示例#8
0
        public async Task <ExpenseDto> EditExpenseAsync(ExpenseDto expenseDto, string userId)
        {
            var expense = await _expenseRepository.FindByIdAsync(expenseDto.Id);

            if (!expense.UserId.Equals(userId, StringComparison.OrdinalIgnoreCase))
            {
                throw new ExpenseException("Cannot find expense", 404);
            }

            expense.Value       = expenseDto.Value;
            expense.Date        = expenseDto.Date;
            expense.CategoryId  = expenseDto.CategoryId;
            expense.Description = expenseDto.Description;

            var result = await _expenseRepository.SaveAsync();

            if (result < 1)
            {
                throw new ExpenseException("Cannot edit expense", 400);
            }

            return(_mapper.Map <ExpenseDto>(expense));
        }
示例#9
0
        private ExpenseDto ExtractAndDeserializeExpenseXmlElement(string messageContent)
        {
            ExpenseDto expenseDto = ExtractAndDeserializeXmlElement <ExpenseDto>(messageContent, ExpenseConstants.Expense);

            if (expenseDto != null)
            {
                return(expenseDto);
            }

            CostCentreDto    costCentre    = ExtractAndDeserializeXmlElement <CostCentreDto>(messageContent, ExpenseConstants.CostCentre);
            TotalDto         total         = ExtractAndDeserializeXmlElement <TotalDto>(messageContent, ExpenseConstants.Total);
            PaymentMethodDto paymentMethod = ExtractAndDeserializeXmlElement <PaymentMethodDto>(messageContent, ExpenseConstants.PaymentMethod);

            return(new ExpenseDto
            {
                Expense = new ExpenseDataDto
                {
                    CostCentre = costCentre?.CostCentre,
                    Total = total.Total,
                    PaymentMethod = paymentMethod?.PaymentMethod
                }
            });
        }
示例#10
0
        public HttpResponseMessage PostExpense(ExpenseDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            var existingExpenseReport = Uow.ExpenseReports.Include(e => e.Employee).GetById(dto.ExpenseReportId);

            if (existingExpenseReport.Employee.UserId != User.Identity.Name)
            {
                // Trying to modify a record that does not belong to the user
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            var expense = new Model.Expense {
                ExpenseReport = existingExpenseReport
            };

            dto.UpdateEntity(expense);

            try
            {
                Uow.Expenses.Add(expense);
                Uow.Commit();
                dto.ExpenseId = expense.Id;
            }
            catch (Exception exp)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, exp.Message));
            }

            var response = Request.CreateResponse(HttpStatusCode.Created, dto);

            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = dto.ExpenseId }));
            return(response);
        }
示例#11
0
        public bool AddExpense(ExpenseDto locationDto)
        {
            if (locationDto != null)
            {
                using (EAharaDB context = new EAharaDB())
                {
                    if (locationDto.Id > 0)
                    {
                        var data = context.Expenses.FirstOrDefault(x => x.Id == locationDto.Id);
                        if (data != null)
                        {
                            data.Name = locationDto.Name;

                            context.Entry(data).Property(x => x.Name).IsModified = true;

                            context.SaveChanges();
                            return(true);
                        }
                        return(false);
                    }
                    else
                    {
                        Expense location = new Expense();

                        location.Name     = locationDto.Name;
                        location.IsActive = true;

                        context.Expenses.Add(location);

                        context.SaveChanges();
                        return(true);
                    }
                }
            }
            return(false);
        }
示例#12
0
        public JsonResult Update(ExpenseDto data)
        {
            var response = new DataResponeCommon();

            try
            {
                if (_expenseService.Update(data))
                {
                    response.Statu   = StatuCodeEnum.OK;
                    response.Message = "Cập nhật thành công!";
                }
                else
                {
                    response.Statu   = StatuCodeEnum.InternalServerError;
                    response.Message = "Cập nhật không thành công!";
                }
            }
            catch (Exception e)
            {
                response.Statu   = StatuCodeEnum.InternalServerError;
                response.Message = e.Message;
            }
            return(Json(response));
        }
示例#13
0
        public HttpResponseMessage PutExpense(int id, ExpenseDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (id != dto.ExpenseId)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            var existingExpense = Uow.Expenses.Include(e => e.ExpenseReport.Employee).GetById(id);

            dto.UpdateEntity(existingExpense);
            if (existingExpense.ExpenseReport.Employee.UserId != User.Identity.Name)
            {
                // Trying to modify a record that does not belong to the user
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            // We don't update images in this controller
            existingExpense.Image = existingExpense.Image;

            try
            {
                Uow.Expenses.Update(existingExpense);
                Uow.Commit();
            }
            catch (DbUpdateConcurrencyException)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }

            return(Request.CreateResponse(HttpStatusCode.OK, dto));
        }
        private ExpenseDto ParseXDocumentToExpenseDto(XDocument document, ref ModelStateDictionary modelState)
        {
            var allElements   = document.Descendants().ToList();
            var totalXElement = allElements.SingleOrDefault(t => t.Name == _configuration["XmlSettings:TotalXmlElementName"]);

            if (totalXElement == null || !decimal.TryParse(totalXElement.Value, out var total))
            {
                modelState.AddModelError(nameof(ExpenseDto.Total), "Total amount is missing or has inappropriate format.");
                return(null);
            }

            var expenseDto = new ExpenseDto {
                Total = total
            };
            var costCentreXElement = allElements.SingleOrDefault(t => t.Name == _configuration["XmlSettings:CostCentreXmlElementName"]);

            if (costCentreXElement != null && !costCentreXElement.IsEmpty)
            {
                expenseDto.CostCentre = costCentreXElement.Value;
            }

            expenseDto.Data = document.Root;
            return(expenseDto);
        }
示例#15
0
 public Task <ExpenseDto> CreateExpenseForUserAsync(ExpenseDto expense, string userId)
 {
     return(_provider.CreateExpenseForUserAsync(expense, userId));
 }
示例#16
0
 public ExpenseDtoBuilder()
 {
     _expenseDto = WithDefaults();
 }
示例#17
0
 public Expense DtoToModel(ExpenseDto dto) => Mapper.Map <Expense>(dto);
示例#18
0
        public async Task <IActionResult> EditExpense([FromBody] ExpenseDto expenseDto)
        {
            var result = await _expenseService.EditExpenseAsync(expenseDto, User.Identity.Name);

            return(Ok(result));
        }
示例#19
0
 public void SetUp()
 {
     _model = new ExpenseDto {
         Data = new object()
     };
 }
示例#20
0
        public async Task <IActionResult> Put(string expenseId, [FromBody] ExpenseDto expenseDto)
        {
            await _expensesRepository.Put(expenseId, expenseDto);

            return(Ok());
        }
示例#21
0
        public async Task <IActionResult> AddExpense([FromBody] ExpenseDto expenseDto)
        {
            var expense = await _expenseService.AddExpenseAsync(expenseDto, User.Identity.Name);

            return(CreatedAtRoute("GetExpense", new { expenseId = expense.Id }, expense));
        }
 public void Update(ExpenseDto expenseDto)
 {
     _expenseByWorkerDao.Update(DtoConverter.Convert(expenseDto));
 }
 public void Add(ExpenseDto expenseDto)
 {
     _expenseByWorkerDao.Add(DtoConverter.Convert(expenseDto));
 }
示例#24
0
        public async Task <IHttpActionResult> GetExpenseById(int Id)
        {
            ExpenseDto expense = await _expenseService.GetExpenseById(Id);

            return(Ok(expense));
        }
示例#25
0
 public Task <ExpenseDto> UpdateExpenseAsync(ExpenseDto expense)
 {
     return(_provider.UpdateExpenseAsync(expense));
 }
示例#26
0
 public void UpdateExpense(int id, [FromBody] ExpenseDto item)
 {
     _expenseService.UpdateExpense(id, item);
 }
示例#27
0
 public void CreateExpense([FromBody] ExpenseDto item)
 {
     _expenseService.CreateExpense(item);
 }
示例#28
0
 public async Task <IActionResult> UpdateExpense([FromBody] ExpenseDto expense) =>
 Ok(await _expenseService.UpdateExpenseAsync(expense));
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            switch (currentTable)
            {
            case "Worker":
                WorkerDto item = (WorkerDto)dgMain.SelectedItem;

                if (item == null)
                {
                    MessageBox.Show("Choose item from delete", "Worker delete");
                    return;
                }

                MessageBoxResult result = MessageBox.Show("Delete " + item.Name + "?", "Worker delete", MessageBoxButton.YesNo, MessageBoxImage.Warning);

                if (result != MessageBoxResult.Yes)
                {
                    return;
                }

                ProcessFactory.GetWorkerProcess().Delete(item.idWorker);
                MenuItem_Click(sender, e);    //update table
                break;

            case "Division":
                DivisionDto itemDivision = (DivisionDto)dgMain.SelectedItem;

                if (itemDivision == null)
                {
                    MessageBox.Show("Choose item from delete", "Division delete");
                    return;
                }

                MessageBoxResult resultDivision = MessageBox.Show("Delete " + itemDivision.Title + "?", "Division delete", MessageBoxButton.YesNo, MessageBoxImage.Warning);

                if (resultDivision != MessageBoxResult.Yes)
                {
                    return;
                }

                ProcessFactory.GetDivisionProcess().Delete(itemDivision.idDivision);
                MenuItem_Click_1(sender, e);
                break;

            case "ExpenseByWorker":
                ExpenseDto itemExpenseDto = (ExpenseDto)dgMain.SelectedItem;

                if (itemExpenseDto == null)
                {
                    MessageBox.Show("Choose item from delete", "Expense delete");
                    return;
                }

                MessageBoxResult resultExpense = MessageBox.Show("Delete " + itemExpenseDto.Description + "?", "Expense delete", MessageBoxButton.YesNo, MessageBoxImage.Warning);

                if (resultExpense != MessageBoxResult.Yes)
                {
                    return;
                }

                ProcessFactory.GetExpenseByWorkerProcess().Delete(itemExpenseDto.idConsumption);
                MenuItem_Click_3(sender, e);
                break;

            case "TypeExpense":
                TypeExpenseDto itemTypeExpenseDto = (TypeExpenseDto)dgMain.SelectedItem;

                if (itemTypeExpenseDto == null)
                {
                    MessageBox.Show("Choose item from delete", "Type expense delete");
                    return;
                }

                MessageBoxResult resultTypeExpense = MessageBox.Show("Delete " + itemTypeExpenseDto.Title + "?", "Type expense delete", MessageBoxButton.YesNo, MessageBoxImage.Warning);

                if (resultTypeExpense != MessageBoxResult.Yes)
                {
                    return;
                }

                ProcessFactory.GetExpenseByWorkerProcess().Delete(itemTypeExpenseDto.idType);
                MenuItem_Click_4(sender, e);
                break;
            }
        }
示例#30
0
 public async Task <IActionResult> CreateExpenseForUser([FromBody] ExpenseDto expense) =>
 Ok(await _expenseService.CreateExpenseForUserAsync(expense, User.GetIdentifier()));