public async Task HandleOrderAsync__Order_handle_succeeded__Should_not_throw_any_Exception() { // Attempt to update existent group by adding 2 tickets and exactly 2 places are available. var sightseeingDate = DateTime.Now.AddDays(1).Date.AddHours(12); SetUpForSucceededOrderHandle(sightseeingDate, new Ticket[] { _ticket }); var order = new OrderRequestDto { Customer = new CustomerDto { EmailAddress = "*****@*****.**" }, Tickets = new ShallowTicket[] { new ShallowTicket { DiscountId = "1", SightseeingDate = sightseeingDate, TicketTariffId = "1" }, new ShallowTicket { DiscountId = "2", SightseeingDate = sightseeingDate, TicketTariffId = "2" } } }; var handler = new TicketOrderHandler(_dbServiceFactoryMock.Object, _validatorMock.Object, _logger); // Set _shallowTickets and _customer private variables. await handler.CreateOrderAsync(order); Func <Task> action = async() => await handler.HandleOrderAsync(); await action.Should().NotThrowAsync <Exception>(); handler.Tickets.Should().NotBeEmpty(); }
public async Task <OrderDto?> AddOrder(OrderRequestDto orderRequestDto) { var parkingLots = await parkingLotDbContext.ParkingLots.ToListAsync(); if (parkingLots.Any(parkingLot => parkingLot.Cars.Any(car => car.PlateNumber == orderRequestDto.PlateNumber))) { return(null); } var parkingLot = parkingLots.FirstOrDefault(parkingLot => parkingLot.Name == orderRequestDto.ParkingLotName); if (parkingLot.Capacity > parkingLot.Cars.Count) { var carEntity = new CarEntity(); carEntity.PlateNumber = orderRequestDto.PlateNumber; carEntity.ParkingLotEntity = parkingLot; carEntity.ParkingLotId = parkingLot.Id; parkingLot.Cars.Add(carEntity); //await parkingLotDbContext.Cars.AddAsync(carEntity); var orderDto = new OrderDto(orderRequestDto); var orderEntity = new OrderEntity(orderDto); orderEntity.Status = "Created"; await this.parkingLotDbContext.Orders.AddAsync(orderEntity); await this.parkingLotDbContext.SaveChangesAsync(); return(orderDto); } return(null); }
public async Task <ActionResult <OrderRequestDto> > CreateOrder(OrderRequestDto orderRequestDto) { try { if (orderRequestDto == null) { return(BadRequest()); } var order = _mapper.Map <OrderRequestDto, Order>(orderRequestDto); order.Date = DateTime.Now; var listOrderDetails = _mapper.Map <IList <OrderDetailRequestDto>, IList <OrderDetails> >(orderRequestDto.Details).ToList(); listOrderDetails.ForEach(f => f.Subtotal = f.Quantity * f.Price); order.Total = listOrderDetails.Sum(f => f.Subtotal); order.OrderDetails = listOrderDetails; _orderRepository.Add(order); await _orderRepository.SaveChangesAsync(); return(CreatedAtAction(nameof(CreateOrder), new { id = order.Id }, orderRequestDto)); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the database")); } }
/// <summary> /// Asynchronously creates <see cref="Models.Customer"/> customer and <see cref="Ticket"/> tickets for this particular order. /// Throws exception if argument is invalid or if cannot create ticket order properly. /// </summary> /// <param name="order">The order request data for which a ticket order will be created.</param> /// <exception cref="ArgumentNullException"><paramref name="order"/> is null.</exception> /// <exception cref="ArgumentException"><see cref="OrderRequestDto.Customer"/> or <see cref="OrderRequestDto.Tickets"/> is null.</exception> /// <exception cref="InternalDbServiceException">Cannot create ticket order properly.</exception> public async Task CreateOrderAsync(OrderRequestDto order) { _logger.LogInformation($"Starting method '{nameof(CreateOrderAsync)}'."); if (order is null) { throw new ArgumentNullException(nameof(order), $"Argument {nameof(order)} cannot be null."); } if (order.Tickets is null || order.Customer is null) { throw new ArgumentException($"Argument '{nameof(order)}' has property '{nameof(OrderRequestDto.Customer)}' or '{nameof(OrderRequestDto.Tickets)}' set to null."); } try { var customer = CreateCustomer(order); var savedCustomer = await GetSavedCustomerAsync(customer); if (savedCustomer is null) { _logger.LogDebug("Adding new customer to the database."); _customer = await AddCustomerToDbAsync(customer); } _customer = savedCustomer; _shallowTickets = order.Tickets; _logger.LogInformation($"Finished method '{nameof(CreateOrderAsync)}'."); } catch (InternalDbServiceException ex) { _logger.LogError(ex, $"Customer creation failed. {ex.Message}"); throw; } }
public async Task <ActionResult <Orders> > PostOrders([FromBody] OrderRequestDto orderDto) { var mapper = new MapperConfiguration(cfg => { cfg.CreateMap <DeliveryInfoDto, DeliveryInfos>(); cfg.CreateMap <CustomerDto, Customers>(); cfg.CreateMap <AdditionalDetailsOrderedDto, AdditionalDetailsOrdered>(); cfg.CreateMap <FurnitureOrderRowDto, FurnitureOrderRows>(); cfg.CreateMap <OrderRequestDto, Orders>() .ForMember(o => o.OrderDate, opt => opt.MapFrom(_ => DateTime.Now)) .ForMember(o => o.Status, opt => opt.MapFrom(_ => OrderStatus.Accepted)) .ForMember(o => o.FurnitureOrderRows, opt => opt.MapFrom(o => o.OrderedFurnitures)) .ForPath(o => o.Profit.Money, opt => opt.MapFrom(o => o.TotalPrice / 6)); }).CreateMapper(); var order = mapper.Map <Orders>(orderDto); _context.Orders.Add(order); await _context.SaveChangesAsync(); return(CreatedAtAction("GetOrders", new { id = order.OrderId }, order)); }
public async Task HandleOrderAsync__Attempt_to_update_existent_group_by_adding_to_many_tickets__Should_throw_InvalidOperationException() { // Attempt to update existent group by adding 2 tickets , but only 1 place is available in existent group. var sightseeingDate = DateTime.Now.AddDays(1).Date.AddHours(12); SetUpForFailedUpdate(sightseeingDate); var order = new OrderRequestDto { Customer = new CustomerDto { EmailAddress = "*****@*****.**" }, Tickets = new ShallowTicket[] { new ShallowTicket { DiscountId = "1", SightseeingDate = sightseeingDate, TicketTariffId = "1" }, new ShallowTicket { DiscountId = "2", SightseeingDate = sightseeingDate, TicketTariffId = "2" } } }; var handler = new TicketOrderHandler(_dbServiceFactoryMock.Object, _validatorMock.Object, _logger); // Set _shallowTickets and _customer private variables. await handler.CreateOrderAsync(order); Func <Task> action = async() => await handler.HandleOrderAsync(); await action.Should().ThrowExactlyAsync <InvalidOperationException>(); }
private OrderRequestDto setCustomerDataOnPayment(OrderRequestDto payload) { var payment = payload?.Payment; if (payment == null) { return(payload); } if (String.IsNullOrEmpty(payment.CustomerName)) { payment.CustomerName = payload.CustomerName; } if (String.IsNullOrEmpty(payment.BranchName)) { payment.BranchName = payload.BranchName; } if (String.IsNullOrEmpty(payment.BranchId)) { payment.BranchId = payload.BranchId; } if (String.IsNullOrEmpty(payment.EmployeeName)) { payment.EmployeeName = payload.EmployeeName; } if (String.IsNullOrEmpty(payment.EmployeeId)) { payment.EmployeeId = payload.EmployeeId; } return(payload); }
private void Saver(OrderRequestDto dto) { if (comboBox1.SelectedIndex == 0) { dto.DescriptionOfBreakageDevice.BrokenDevice = Apparat.Утюг; } if (comboBox1.SelectedIndex == 1) { dto.DescriptionOfBreakageDevice.BrokenDevice = Apparat.Микроволновка; } if (comboBox1.SelectedIndex == 2) { dto.DescriptionOfBreakageDevice.BrokenDevice = Apparat.Чайник; } if (comboBox1.SelectedIndex == 3) { dto.DescriptionOfBreakageDevice.BrokenDevice = Apparat.Миксер; } if (comboBox1.SelectedIndex == 4) { dto.DescriptionOfBreakageDevice.BrokenDevice = Apparat.Обогреватель; } if (comboBox1.SelectedIndex == 5) { dto.DescriptionOfBreakageDevice.BrokenDevice = Apparat.Пылесос; } if (comboBox1.SelectedIndex == 6) { dto.DescriptionOfBreakageDevice.BrokenDevice = Apparat.Телевизор; } if (comboBox1.SelectedIndex == 7) { dto.DescriptionOfBreakageDevice.BrokenDevice = Apparat.Другое; } if (comboBox2.SelectedIndex == 0) { dto.Price.Currency = Currency.Rubles; } if (comboBox2.SelectedIndex == 1) { dto.Price.Currency = Currency.Dollars; } if (comboBox2.SelectedIndex == 2) { dto.Price.Currency = Currency.Euro; } if (comboBox2.SelectedIndex == 3) { dto.Price.Currency = Currency.Bitcoins; } if (comboBox2.SelectedIndex == 4) { dto.Price.Currency = Currency.Ethereum; } }
public void End2EndSerializationTest() { var dto = new OrderRequestDto { Filled = new TimeOfRepair() { Filled = DateTime.Today, }, FullName = "Grigoriy Zalyatskiy", DescriptionOfBreakageDevice = new Device() { BrokenDevice = Apparat.Kettle, Breakage = new List <Breakage>() { new Breakage() { BreakageType = DamageType.Burned, Description = "Cгорел датчик температуры" }, new Breakage() { BreakageType = DamageType.Physical, Description = "Оторвалась крышка" }, } }, Price = new Payment() { Currency = Currency.Bitcoins, Price = 0.002, }, Repair = new AdditionalRequirements() { TimeOfRepair = new TimeOfRepair() { Days = 7, }, BuySomeDetailsYourself = false, AdditionalRequests = "Почините, пожалуйста чайник, приходится кипятить воду в кастрюльке без него :(" } }; var tempFileName = Path.GetTempFileName(); try { RideDtoHelper.WriteToFile(tempFileName, dto); var readDto = RideDtoHelper.LoadFromFile(tempFileName); Assert.AreEqual(dto.FullName, readDto.FullName); Assert.AreEqual(dto.Price.Price, readDto.Price.Price); } finally { File.Delete(tempFileName); } }
private void Setter(OrderRequestDto dto)//тут всё сделать наоборот как в сейвере { if (dto.DescriptionOfBreakageDevice.BrokenDevice == Apparat.Утюг) { comboBox1.SelectedIndex = 0; } if (dto.DescriptionOfBreakageDevice.BrokenDevice == Apparat.Микроволновка) { comboBox1.SelectedIndex = 1; } if (dto.DescriptionOfBreakageDevice.BrokenDevice == Apparat.Чайник) { comboBox1.SelectedIndex = 2; } if (dto.DescriptionOfBreakageDevice.BrokenDevice == Apparat.Миксер) { comboBox1.SelectedIndex = 3; } if (dto.DescriptionOfBreakageDevice.BrokenDevice == Apparat.Обогреватель) { comboBox1.SelectedIndex = 4; } if (dto.DescriptionOfBreakageDevice.BrokenDevice == Apparat.Пылесос) { comboBox1.SelectedIndex = 5; } if (dto.DescriptionOfBreakageDevice.BrokenDevice == Apparat.Телевизор) { comboBox1.SelectedIndex = 6; } if (dto.DescriptionOfBreakageDevice.BrokenDevice == Apparat.Другое) { comboBox1.SelectedIndex = 7; } if (dto.Price.Currency == Currency.Rubles) { comboBox2.SelectedIndex = 0; } if (dto.Price.Currency == Currency.Dollars) { comboBox2.SelectedIndex = 1; } if (dto.Price.Currency == Currency.Euro) { comboBox2.SelectedIndex = 2; } if (dto.Price.Currency == Currency.Bitcoins) { comboBox2.SelectedIndex = 3; } if (dto.Price.Currency == Currency.Ethereum) { comboBox2.SelectedIndex = 4; } }
public async Task <string> CreateOrder(string token, OrderRequestDto orderRequestDto) { var notiRequest = new { shop_id = 75661, payment_type_id = 2, note = "", client_order_code = orderRequestDto.CliendOrderCode, required_note = "KHONGCHOXEMHANG", return_phone = "0368345905", return_address = "124 Ngô Quyền, Quang Trung, Hà Đông, Hà Nội", return_district_id = 1542, return_ward_code = "1B1513", to_name = orderRequestDto.Name, to_phone = orderRequestDto.Phone, to_address = orderRequestDto.Address, to_ward_code = orderRequestDto.WardCode, to_district_id = orderRequestDto.DistrictId, cod_amount = orderRequestDto.CodAmount, content = orderRequestDto.Content, service_id = 53321, service_type_id = 2, weight = 500, length = 50, width = 50, height = 15, source = "5sao", items = new[] { new { name = orderRequestDto.Items.Name, code = orderRequestDto.Items.Code, quantity = orderRequestDto.Items.Quantity } } }; var json = JsonConvert.SerializeObject(notiRequest); var data = new StringContent(json, Encoding.UTF8, "application/json"); using var client = new HttpClient(); client.BaseAddress = new Uri("https://dev-online-gateway.ghn.vn/"); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("token", "98bb7369-1162-11eb-a23c-065c95c021cb"); client.DefaultRequestHeaders.Add("ShopId", "75661"); // List data response. var response = await client.PostAsync("/shiip/public-api/v2/shipping-order/create", data); var result = await response.Content.ReadAsStringAsync(); return(result); }
public async Task <ActionResult <OrderDto> > AddOrder(OrderRequestDto orderRequestDto) { OrderDto?orderDto = await orderService.AddOrder(orderRequestDto); if (orderDto == null) { return(BadRequest()); } return(CreatedAtAction(nameof(GetOrderById), new { orderNumber = orderDto.OrderNumber }, orderDto)); }
public IActionResult OrderRequest([FromBody] OrderRequestDto request) { try { return(Ok(_orderRequestServices.OrderRequest(request))); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task CreateOrderAsync__Customer_in_argument_order_is_null__Should_throw_ArgumentException() { var order = new OrderRequestDto { Id = "1", Customer = null, Tickets = new ShallowTicket[] { _shallowTicket } }; var handler = new TicketOrderHandler(_dbServiceFactoryMock.Object, _validatorMock.Object, _logger); Func <Task> action = async() => await handler.CreateOrderAsync(order); await action.Should().ThrowExactlyAsync <ArgumentException>(); }
public async Task <IActionResult> AddOrder(OrderRequestDto order) { int userId = Convert.ToInt32(HttpContext.Items["userId"]); OrderResponseDto orderResponse = await _service.Add(order, userId); return(Ok(new Response <OrderResponseDto> { StatusCode = (int)HttpStatusCode.OK, Message = ResponseMessage.SUCCESSFUL, Data = orderResponse })); }
public async Task <ApiResponse <List <OrderViewDto> > > CreateOrder(OrderRequestDto orderRequestDto) { try { string token = "98bb7369-1162-11eb-a23c-065c95c021cb"; return(new ApiResponse <List <OrderViewDto> >(EnStatusApiReponse.Success, await this.addressService.CreateOrder(token, orderRequestDto))); } catch (Exception ex) { throw ex; } }
public async Task CreateOrderAsync__Cannot_get_saved_customer__Should_throw_InvalidOperationException() { var order = new OrderRequestDto { Id = "1", Customer = new CustomerDto(), Tickets = new ShallowTicket[] { _shallowTicket } }; _customerDbServiceMock.Setup(x => x.GetByAsync(It.IsAny <Expression <Func <Customer, bool> > >())).ThrowsAsync(new InvalidOperationException()); var handler = new TicketOrderHandler(_dbServiceFactoryMock.Object, _validatorMock.Object, _logger); Func <Task> action = async() => await handler.CreateOrderAsync(order); await action.Should().ThrowExactlyAsync <InvalidOperationException>(); }
public async Task <ActionResult <Order> > CreateOrder(OrderRequestDto orderDto) { string buyerEmail = HttpContext.User.GetUserEmail(); DeliveryAddress deliveryAddress = _mapper.Map <DeliveryAddress>(orderDto.DeliveryAddress); Order order = await _orderService.CreateOrderAsync(deliveryAddress, orderDto.DeliveryMethodId, orderDto.BasketId, buyerEmail); if (order == null) { return(BadRequest(new Errors.ApiErrorResponse(400, "order creation faild"))); } return(Ok(order)); }
public async Task <ActionResult <ApiResponseDto> > CreateOrderAsync(OrderRequestDto request) { if (Validate(_orderRequestDtoValidator, request)) { var order = _mapper.Map <Order>(request); await _customerService.CreateIfNotExistsAsync(order.Customer); ApiResponse.Result = await _orderService.CreateOrderAsync(order); } return(StatusCode((int)HttpStatusCode, ApiResponse)); }
private void SetModelToUI(OrderRequestDto dto) { dateTimePicker.Value = dto.TimeOfRepair.Filled; numericUpDown1.Value = dto.TimeOfRepair.Days; dateTimePicker1.Value = dto.TimeOfRepair.RepairTime(dto.TimeOfRepair.Filled); fioTextBox.Text = dto.FullName; textBox1.Text = dto.Repair.AdditionalRequests; checkBox1.Checked = dto.Repair.BuySomeDetailsYourself; numericUpDown2.Value = dto.Price.Price; mainListBox.Items.Clear(); foreach (var e in dto.DescriptionOfBreakageDevice.Breakage) { mainListBox.Items.Add(e); } }
public async Task CreateOrderAsync__Order_create_succeeded__Property_customer_should_return_correct_data() { // Property should return Customer who ordered tickets. // This method set Customer property. var tickets = new ShallowTicket[] { _shallowTicket }; var order = new OrderRequestDto { Id = "1", Customer = new CustomerDto(), Tickets = tickets }; _customerDbServiceMock.Setup(x => x.GetByAsync(It.IsAny <Expression <Func <Customer, bool> > >())).ReturnsAsync(new Customer[] { _customer }); _customerDbServiceMock.Setup(x => x.AddAsync(It.IsAny <Customer>())).ReturnsAsync(_customer); var handler = new TicketOrderHandler(_dbServiceFactoryMock.Object, _validatorMock.Object, _logger); await handler.CreateOrderAsync(order); handler.Customer.Should().BeEquivalentTo(_customer); }
public OrderCreateResponseDto CreateOrder([FromBody] OrderRequestDto requestDto) { //Create order model object from dto var order = new Order { ProductId = requestDto.ProductId, CustomerId = requestDto.CustomerId, OrderDate = requestDto.OrderDate, Quantity = requestDto.Quantity, PricePaid = requestDto.PricePaid, ShippedDate = requestDto.ShippedDate }; // apply all validation to make sure data is valid if (!_customerRepository.isValidCustomer(order.CustomerId)) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Customer Id is required and valid customer Id must be provided")); } if (!_productRepository.isValidProduct(order.ProductId)) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product Id is required and valid product Id must be provided")); } if (order.OrderDate == null) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Order date is required and valid order date must be provided")); } if (order.Quantity < 1) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Quantity is required, must be integer value and greater than 0")); } if (order.PricePaid < 1) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Price paid is required, must be a decimal value and greater than 0")); } // return the Order id created using a response DTO return(new OrderCreateResponseDto { OrderId = _orderRepository.Add(order) }); }
public async Task <OrderResponseDto> Add(OrderRequestDto orderRequest, int userId) { try { var guid = Guid.NewGuid(); OrderResponseDto order = await _repository.Add(userId, orderRequest.bookId, orderRequest.quantity, orderRequest.addressId, guid.ToString()); await _cacheRepository.DeleteAsync(userId.ToString(), orderRequest.bookId); Message message = new Message(new string[] { order.User.Email }, "Order successfully placed!", $"{_emailItems.ItemDetailHtml(order.Book.Title, order.Book.Author, order.Book.Image, order.Book.Price, order.Book.Quantity)+ _emailItems.OrderDetailHtml(order.OrderId, order.OrderedDate, order.Book.Price)}"); _mqServices.AddToQueue(message); return(order); } catch (SqlException e) when(e.Number == SqlErrorNumbers.CONSTRAINT_VOILATION) { throw new BookstoreException("Invalid user!"); } }
public async Task <IActionResult> CreateOrderAsync(OrderRequestDto order) { _logger.LogInformation($"Starting method '{nameof(CreateOrderAsync)}'."); try { await _orderHandler.CreateOrderAsync(order); await _orderHandler.HandleOrderAsync(); var customer = _orderHandler.Customer; var orderedTickets = _orderHandler.Tickets; string orderId = _orderHandler.OrderId; _logger.LogDebug("Mapping to DTOs."); var orderedTicketsDto = MapToDtoEnumerable(orderedTickets); var customerDto = MapToDto(customer); string orderUrl = $"{ControllerPrefix}/{orderId}"; var response = new ResponseWrapper(new OrderResponseDto { Id = orderId, Customer = customerDto, Tickets = orderedTicketsDto }); _logger.LogInformation($"Finished method '{nameof(CreateOrderAsync)}'"); // TODO: Send confirmation email. return(Created(orderUrl, response)); } catch (InvalidOperationException ex) { return(OnInvalidParameterError($"The order cannot be properly handled. {ex.Message}")); } catch (InternalDbServiceException ex) { LogInternalDbServiceException(ex); throw; } catch (Exception ex) { LogUnexpectedException(ex); throw; } }
public IHttpActionResult CreateOrder(OrderRequestDto orderRequest) { bool orderIsValid = false; if (orderRequest.quantity > 0) { using (ForeverDigitalEntities db = new ForeverDigitalEntities()) { try { orderIsValid = db.Products.Any(x => x.product_id == orderRequest.product_id && x.stock_available >= orderRequest.quantity); } catch (System.Exception) { return(Ok(new HttpError("Something went wrong"))); } } } return(Ok(new { IsOrderValid = orderIsValid })); }
public async Task <string> UpdateOrders(OrderRequestDto orderRequestDto) { var notiRequest = new { order_code = orderRequestDto.OrderCode, note = orderRequestDto.Note, to_name = orderRequestDto.Name, to_phone = orderRequestDto.Phone, to_address = orderRequestDto.Address, to_ward_code = orderRequestDto.WardCode, to_district_id = orderRequestDto.DistrictId, cod_amount = orderRequestDto.CodAmount, content = orderRequestDto.Content, source = "5sao", items = new[] { new { name = orderRequestDto.Items.Name, code = orderRequestDto.Items.Code, quantity = orderRequestDto.Items.Quantity } } }; var json = JsonConvert.SerializeObject(notiRequest); var data = new StringContent(json, Encoding.UTF8, "application/json"); using var client = new HttpClient(); client.BaseAddress = new Uri("https://dev-online-gateway.ghn.vn/"); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("token", "98bb7369-1162-11eb-a23c-065c95c021cb"); client.DefaultRequestHeaders.Add("ShopId", "75661"); // List data response. var response = await client.PostAsync("/shiip/public-api/v2/shipping-order/update", data); var result = await response.Content.ReadAsStringAsync(); return(result); }
public VoidResponseDto MakeOrder(OrderRequestDto order) { var tableMeal = RestaurantRepository.GetCurrentTableMealByTableId(order.TableId); if (tableMeal == null) { tableMeal = TableMealFactory.CreateNewTableMeal(order.TableId, order.GuestNumber); RestaurantRepository.Add(tableMeal); } var newOrder = OrderFactory.CreateOrder(tableMeal, order.OrderTypeId); tableMeal.Orders.Add(newOrder); RestaurantRepository.Add(newOrder); foreach (var orderItem in order.Order) { var temp = OrderItemFactory.CreateOrderItem(orderItem.MenuItemId, orderItem.Count); newOrder.OrderItems.Add(temp); } RestaurantRepository.Commit(); return new VoidResponseDto{IsSuccessful = true,}; }
public void SetUp() { _logger = Mock.Of <ILogger <OrdersController> >(); _mapperMock = new Mock <IMapper>(); _orderHandlerMock = new Mock <ITicketOrderHandler>(); _orderData = new OrderRequestDto { Customer = new CustomerDto { EmailAddress = "*****@*****.**", DateOfBirth = DateTime.Now.AddYears(-43) }, Tickets = new ShallowTicket[] { new ShallowTicket { DiscountId = "1", TicketTariffId = "1", SightseeingDate = DateTime.Now.AddDays(1).Date.AddHours(14) }, new ShallowTicket { DiscountId = "2", TicketTariffId = "1", SightseeingDate = DateTime.Now.AddDays(1).Date.AddHours(16) } } }; }
public async Task <List <OrderViewDto> > CreateOrder(string token, OrderRequestDto orderRequestDto) { var response = await this.callApiGHNHelper.CreateOrder(token, orderRequestDto); var result = JsonConvert.DeserializeObject <dynamic>(response); var orders = new List <OrderViewDto>(); //orders.Add(new OrderViewDto //{ // ClientOrderCode = orderRequestDto.CliendOrderCode //}); orders.Add(new OrderViewDto { ClientOrderCode = orderRequestDto.CliendOrderCode, OrderCode = result?.data.order_code, SortCode = result?.data.sort_code, TotalFee = result?.data.total_fee, ExpectedDeliveryTime = result?.data.expected_delivery_time }); return(orders); }
/// <exception cref="ArgumentNullException"><paramref name="order"/> is null.</exception> /// <exception cref="ArgumentException">$"Argument <see cref="OrderRequestDto"/> has property <see cref="OrderRequestDto.Customer"/> set to unexpected null.</exception> private Customer CreateCustomer(OrderRequestDto order) { // NOTE: Maybe a better approach than the current one is to prohibit creating a new customer if they don't order any tickets? if (order is null) { throw new ArgumentNullException(nameof(order), $"Argument {nameof(order)} cannot be null."); } if (order.Customer is null) { throw new ArgumentException($"Argument {nameof(order)} has property {nameof(OrderRequestDto.Customer)} set to unexpected null.", nameof(order)); } return(new Customer { DateOfBirth = order.Customer.DateOfBirth, EmailAddress = order.Customer.EmailAddress, HasFamilyCard = order.Customer.HasFamilyCard, IsChild = order.Customer.IsChild, IsDisabled = order.Customer.IsDisabled }); }
public async Task <IActionResult> Create([FromBody] OrderRequestDto payload) { TextInfo caseFormat = new CultureInfo("en-US", false).TextInfo; var accountId = UserHelper.GetAccountId(User); if (payload == null) { ModelState.AddModelError("order", "The order cannot be blank"); return(BadRequest(Responses.ErrorResponse <PaymentRequest>(ModelState.ToErrors(), StatusMessage.ValidationErrors, ResponseCodes.VALIDATION_ERRORS))); } //call a function that assigns the customer, branch and employee from an order to the payment if empty on the payment payload = setCustomerDataOnPayment(payload); var payment = payload?.Payment; if (payment == null) { ModelState.AddModelError("payment", "There is no payment attached to the order"); return(BadRequest(Responses.ErrorResponse <PaymentRequest>(ModelState.ToErrors(), StatusMessage.ValidationErrors, ResponseCodes.VALIDATION_ERRORS))); } var paymentValidator = new PaymentRequestValidator(_paymentTypeConfiguration); paymentValidator.Validate(payment).AddToModelState(ModelState, null); if (!ModelState.IsValid) { return(BadRequest(Responses.ErrorResponse <PaymentRequest>(ModelState.ToErrors(), StatusMessage.ValidationErrors, ResponseCodes.VALIDATION_ERRORS))); } var orderValidator = new OrderRequestValidator(); orderValidator.Validate(payload).AddToModelState(ModelState, null); if (!ModelState.IsValid) { return(BadRequest(Responses.ErrorResponse <PaymentRequest>(ModelState.ToErrors(), StatusMessage.ValidationErrors, ResponseCodes.VALIDATION_ERRORS))); } var orderRequest = _mapper.Map <OrderRequest>(payload); var paymentRequest = _mapper.Map <PaymentRequest>(payment); paymentRequest.OrderRequestDoc = JsonConvert.SerializeObject(orderRequest); paymentRequest = await _paymentRequestRepository.AddAsync(paymentRequest).ConfigureAwait(false); var paymentTypeClassName = $"Hubtel.PaymentProxy.Services.{caseFormat.ToTitleCase(payment.PaymentType.ToLower())}PaymentService"; var paymentService = (PaymentService)ActivatorUtilities.CreateInstance(_provider, Type.GetType(paymentTypeClassName)); //--> var processPaymentResult = await paymentService.ProcessPayment(paymentRequest).ConfigureAwait(false); if (processPaymentResult.Success) { processPaymentResult.Data.OrderRequestDoc = null; return(Ok(processPaymentResult)); } await _paymentRequestRepository.DeleteByClientReferenceAsync(paymentRequest.ClientReference).ConfigureAwait(false); processPaymentResult.Data = null; return(BadRequest(processPaymentResult)); }
public VoidResponseDto MakeOrder(OrderRequestDto order) { // hardcode CurrentUserHelper.SetCurrentUserId(1); return RestaurantService.MakeOrder(order); }