Exemplo n.º 1
0
        public async Task <CreateOrderResponse> CreateOrderAsync(CreateOrderRequest request)
        {
            var result = new CreateOrderResponse();
            var errors = Enumerable.Empty <string>() as ICollection <string>;

            try
            {
                var spec = new ValidCreateOrderRequestSpecification();
                if (spec.IsSatisfiedBy(request, ref errors))
                {
                    await this.dataGateway.InsertOrderAsync(request.AsEntity());
                }
                else
                {
                    result.SetError(Errors.CreateValidationError, errors);
                }
            }
            catch (Exception ex)
            {
                this.logger.WriteException(ex);
                throw new OrderServiceException(ex);
            }

            return(result);
        }
Exemplo n.º 2
0
        public CreateOrderResponse CreateOrder(CreateOrderRequest request)
        {
            if (request == null)
            {
                AddNotification("CreateOrderRequest", "CreateOrderRequest inválido");
                return(null);
            }


            var order = new Order(
                request.IdUser,
                Mapper.Map <Divinus.Domain.Arguments.Order.Address, Divinus.Domain.Entities.Address>(request.Address),
                Mapper.Map <List <Divinus.Domain.Arguments.Order.Food>, List <Divinus.Domain.Entities.Food> >(request.PurchaseOrder),
                request.PaymentMethod,
                request.TotalValue);

            if (order.IsInvalid())
            {
                AddNotifications(order);
                return(null);
            }

            long orderNumber             = _repositoryOrder.InsertOrder(order);
            CreateOrderResponse response = new CreateOrderResponse();

            response.OrderNumber = orderNumber;
            return(response);
        }
Exemplo n.º 3
0
        public void AddOrderTest()
        {
            OrderManager manager  = OrderManagerFactory.Create();
            DateTime     date     = DateTime.Parse("5/29/4017");
            Orders       newOrder = new Orders();

            newOrder.OrderNumber            = 1;
            newOrder.Name                   = "Eckberg";
            newOrder.State                  = "OH";
            newOrder.TaxRate                = 6.25M;
            newOrder.PrductType             = "Carpet";
            newOrder.Area                   = 100M;
            newOrder.CostPerSqureFoot       = 2.25M;
            newOrder.LaborCostPerSquareFoot = 2.10M;
            newOrder.MaterialCost           = 450M;
            newOrder.LaborCost              = 420M;
            newOrder.Tax   = 54.38M;
            newOrder.Total = 924.38M;

            CreateOrderResponse response = manager.CreateOrder(newOrder, date);
            var orders = manager.GetAllOrders(date);

            Assert.AreEqual(2, orders.Orders.Count);

            Orders check = orders.Orders[1];

            Assert.AreEqual("Eckberg", check.Name);
            Assert.AreEqual("OH", check.State);
        }
Exemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="enterpriseOrderId"></param>
        /// <param name="oldXMSOrderId"></param>
        /// <param name="_orderInfo"></param>
        /// <returns></returns>
        public CreateOrderResponse createOrder2(string enterpriseOrderId, string oldXMSOrderId, string typeId, P_Order _orderInfo)
        {
            CreateOrderResponse _res = null;

            try
            {
                if (_orderInfo.IsNonHT == 1)
                {
                    _res = handler.createOrder(
                        enterpriseOrderId, oldXMSOrderId, typeId, _orderInfo.details.deliverTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), _orderInfo.foods.foodFee.ToString(), _orderInfo.foods.packageFee.ToString(),
                        _orderInfo.foods.sendFee.ToString(), "0", _orderInfo.foods.allPrice.ToString(), _orderInfo.hospital.invoiceTitle + " - " + _orderInfo.hospital.dutyParagraph,
                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), _orderInfo.details.remark,
                        _orderInfo.details.consignee, _orderInfo.details.attendCount.ToString(), _orderInfo.hospital.city, "1", _orderInfo.details.phone, _orderInfo.hospital.address + " - " + _orderInfo.details.deliveryAddress, _orderInfo.foods.resId,
                        string.Empty, _orderInfo.hospital.longitude, _orderInfo.hospital.latitude, _orderInfo.hospital.hospital, _orderInfo.PO, "99999", string.Empty, _orderInfo.userid, _orderInfo.foods.foods.Select(a => a.ToFoodRequest()).ToArray());
                }
                else
                {
                    _res = handler.createOrder(
                        enterpriseOrderId, oldXMSOrderId, typeId, _orderInfo.details.deliverTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), _orderInfo.foods.foodFee.ToString(), _orderInfo.foods.packageFee.ToString(),
                        _orderInfo.foods.sendFee.ToString(), "0", _orderInfo.foods.allPrice.ToString(), _orderInfo.hospital.invoiceTitle,
                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), _orderInfo.details.remark,
                        _orderInfo.details.consignee, _orderInfo.details.attendCount.ToString(), _orderInfo.hospital.city, "1", _orderInfo.details.phone, _orderInfo.hospital.address + " - " + _orderInfo.details.deliveryAddress, _orderInfo.foods.resId,
                        string.Empty, _orderInfo.hospital.longitude, _orderInfo.hospital.latitude, _orderInfo.hospital.hospital, _orderInfo.CnCode, _orderInfo.meeting.budgetTotal.ToString(),
                        string.Empty, _orderInfo.meeting.userId, _orderInfo.foods.foods.Select(a => a.ToFoodRequest()).ToArray());
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("OpenApi.createOrder2", ex);
            }
            return(_res);
        }
Exemplo n.º 5
0
        public virtual CreateOrderResponse CreateOrder(CreateOrderRequest request)
        {
            var response = new CreateOrderResponse();

            try {
                // Raise Initialization Event
                var initialization = CreateOrderInitialization;
                if (initialization != null)
                {
                    initialization(request, response);
                }
                // Raise Execute Event
                var execute = CreateOrderExecute;
                if (execute != null)
                {
                    response = execute(request);
                }
                // Raise Complete Event
                var complete = CreateOrderComplete;
                if (complete != null)
                {
                    complete(request, response);
                }
            }
            catch (Exception exception) {
                // Raise Error Event
                var error = CreateOrderError;
                if (error != null)
                {
                    error(request, response, exception);
                }
            }
            return(response);
        }
Exemplo n.º 6
0
        public async Task <CreateOrderResponse> CreateOrderAsync(CreateOrderRequest request)
        {
            var result = new CreateOrderResponse();
            ICollection <string> errors = new Collection <string>();

            try
            {
                //// Validate using Specification classes. You can leverage factories to inject
                //// your specifications if it touches the database
                var spec = new ValidCreateOrderRequestSpecification();
                if (spec.IsSatisfiedBy(request, ref errors))
                {
                    //// Decouple Service Models from Shared models i.e. Create `AsEntity` extension to convert vice-versa
                    await this.dataGateway.InsertOrderAsync(request.AsEntity());
                }
                else
                {
                    //// Communicate Specification-added errors, and return appropriate error.
                    result.SetError(Errors.CreateValidationError, errors);
                }
            }
            catch (Exception ex)
            {
                //// Log and Wrap exception then rethrow
                this.logger.WriteException(ex);
                throw new OrderServiceException(ex);
            }

            return(result);
        }
Exemplo n.º 7
0
        public CreateOrderResponse Create(CreateOrderDto createOrderDto)
        {
            //get by ids
            var books = booksService.GetByIds(createOrderDto.BookIds);

            //create new order object
            var newOrder = new Order
            {
                Name       = createOrderDto.Name,
                Address    = createOrderDto.Address,
                Email      = createOrderDto.Email,
                Phone      = createOrderDto.Phone,
                BookOrders = createOrderDto.BookIds.Select(x => new BookOrders {
                    BookId = x
                }).ToList(),
                FullPrice = books.Sum(x => x.Price),
                OrderCode = Helper.RandomString(6)
            };

            //save
            ordersRepository.Create(newOrder);

            var response = new CreateOrderResponse();

            response.OrderCode = newOrder.OrderCode;
            return(response);
        }
        public void TestAddResponse(int year, int month, int day, string customerName, int orderNumber, string state, decimal taxRate, string productType, decimal area,
                                    decimal costPerSquareFoot, decimal laborCostPerSquareFoot, decimal materialCost, decimal laborCost, decimal tax, decimal total, bool expectedResult)
        {
            OrderManager manager = OrderManagerFactory.Create();
            Order        ord     = new Order();

            ord.Date                   = new DateTime(year, month, day);
            ord.CustomerName           = customerName;
            ord.OrderNumber            = orderNumber;
            ord.State                  = state;
            ord.TaxRate                = taxRate;
            ord.ProductType            = productType;
            ord.Area                   = area;
            ord.CostPerSquareFoot      = costPerSquareFoot;
            ord.LaborCostPerSquareFoot = laborCostPerSquareFoot;
            ord.MaterialCost           = materialCost;
            ord.LaborCost              = laborCost;
            ord.Tax   = tax;
            ord.Total = total;
            CreateOrderResponse response = manager.CreateOrder(ord);

            if (response.Success)
            {
                Assert.IsNotNull(response.order);
                Assert.AreEqual(response.order.CustomerName, customerName);
                Assert.AreEqual(response.order.Date, ord.Date);
                Assert.AreEqual(response.order.State, state);
                Assert.AreEqual(response.order.Area, area);
            }
            Assert.AreEqual(expectedResult, response.Success);
        }
Exemplo n.º 9
0
        public JsonResult Create(OrderDetailView vm)
        {
            CreateOrderRequest request         = new CreateOrderRequest();
            GetCustomerRequest customerRequest = new GetCustomerRequest();

            customerRequest.CustomerID = vm.CustomerCustomerID;
            request.Customer           = _customerService.GetCustomer(customerRequest).Customer;
            GetEmployeeRequest employeeRequest = new GetEmployeeRequest();

            employeeRequest.EmployeeID = vm.EmployeeEmployeeID;
            request.Employee           = _employeeService.GetEmployee(employeeRequest).Employee;
            request.OrderDate          = vm.OrderDate;
            request.RequiredDate       = vm.RequiredDate;
            request.ShippedDate        = vm.ShippedDate;
            GetShipperRequest shipperRequest = new GetShipperRequest();

            shipperRequest.ShipperID = vm.ShipperShipperID;
            request.Shipper          = _shipperService.GetShipper(shipperRequest).Shipper;
            request.Freight          = vm.Freight;
            request.ShipName         = vm.ShipName;
            request.ShipAddress      = vm.ShipAddress;
            request.ShipCity         = vm.ShipCity;
            request.ShipRegion       = vm.ShipRegion;
            request.ShipPostalCode   = vm.ShipPostalCode;
            request.ShipCountry      = vm.ShipCountry;
            CreateOrderResponse response = _orderService.CreateOrder(request);

            return(Json(response));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Put([FromBody] CreateOrderRequest newOrder)
        {
            var order = new Order
            {
                SubmittedOn = newOrder.SubmittedOn,
                CreatedOn   = DateTime.UtcNow,
                OrderId     = newOrder.OrderId
            };

            var response = new CreateOrderResponse();

            try
            {
                orderContext.Orders.Add(order);

                await orderContext.SaveChangesAsync();

                response.NewOrder = order;

                return(Accepted(response));
            }
            catch (Exception ex)
            {
                response.Errors = new List <string> {
                    ex.Message
                };
                return(BadRequest(response));
            }
        }
Exemplo n.º 11
0
        public async Task <CreateOrderResponse> CreateOrderAsync(CreateOrderRequest request)
        {
            var response = new CreateOrderResponse {
                Code = 200
            };

            try
            {
                await this.gateway.InsertOrderAsync(request.Order.AsEntity());

                var senderBuilder         = new SenderEmailBuilder(request.Order.SenderEmail, request.Order.SenderName, request.Order.RecipientName, request.Order.ProductName, request.Order.ProductPrice, request.Order.OrderQuantity);
                var senderEmailMessage    = EmailDirector.ConstructEmail(senderBuilder);
                var recipientBuilder      = new RecipientEmailBuilder(request.Order.RecipientEmail, request.Order.RecipientName, request.Order.SenderName, request.Order.ProductName, request.Order.ProductPrice, request.Order.OrderQuantity);
                var recipientEmailMessage = EmailDirector.ConstructEmail(recipientBuilder);

                await this.emailSender.SendEmail(senderEmailMessage);

                await this.emailSender.SendEmail(recipientEmailMessage);
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex.Message);
                response.Code = 500;
            }

            return(response);
        }
Exemplo n.º 12
0
        public CreateOrderResponse Calculation(DateTime Date, string CustomerName, string State, string ProductType, decimal Area)
        {
            CreateOrderResponse response = new CreateOrderResponse();

            response.order = new Order();
            if (Date == DateTime.Today)
            {
                response.Success = false;
                response.Message = $"Error: The {Date} has to be in the future";
                return(response);
            }
            if (!CustomerName.All(c => char.IsLetterOrDigit(c) || c == ',' || c == '-'))
            {
                response.Success = false;
                response.Message = "Not a valid name character";
                return(response);
            }
            if (_taxes.FirstOrDefault(a => a.StateName.ToLower() == State) == null)
            {
                response.Success = false;
                response.Message = "That was not a valid state";
                return(response);
            }
            if (_products.FirstOrDefault(p => p.ProductType.ToLower() == ProductType) == null)
            {
                response.Success = false;
                response.Message = "We do not sell that product";
                return(response);
            }
            if (Area < 100)
            {
                response.Success = false;
                response.Message = $"{Area} must be a minimun of 100 square feet";
                return(response);
            }

            response.Success            = true;
            response.order.Date         = Date;
            response.order.CustomerName = CustomerName;
            response.order.State        = State;
            decimal taxRate = _taxes.FirstOrDefault(a => a.StateName.ToLower() == State).TaxRate;

            response.order.TaxRate     = taxRate;
            response.order.ProductType = ProductType;
            response.order.Area        = Area;
            decimal costPerSquareFoot = _products.FirstOrDefault(p => p.ProductType.ToLower() == ProductType).CostPerSquareFoot;

            response.order.CostPerSquareFoot = costPerSquareFoot;
            decimal laborCostPerSquareFoot = _products.FirstOrDefault(l => l.ProductType.ToLower() == ProductType).LaborCostPerSquareFoot;

            response.order.LaborCostPerSquareFoot = laborCostPerSquareFoot;


            response.order.MaterialCost = response.order.Area * costPerSquareFoot;
            response.order.LaborCost    = response.order.Area * laborCostPerSquareFoot;
            response.order.Tax          = (response.order.MaterialCost + response.order.LaborCost) * (taxRate / 100);
            response.order.Total        = response.order.MaterialCost + response.order.LaborCost + response.order.Tax;

            return(response);
        }
        public ActionResult PlaceOrder(FormCollection collection)
        {
            CreateOrderResponse response = CreateOrderResponse(collection);

            return(RedirectToAction("CreatePaymentFor", "Payment",
                                    new { orderId = response.Order.Id }));
        }
Exemplo n.º 14
0
        public IActionResult CancelOrder([FromRoute] long id)
        {
            Order order = orderService.CancelOrder(id);
            CreateOrderResponse createOrderResponse = new CreateOrderResponse(order.Id);

            return(Ok(createOrderResponse));
        }
Exemplo n.º 15
0
        public override CreateOrderResponse OnCreateOrderExecute(CreateOrderRequest request)
        {
            var budgetFactory = new BudgetFactory();
            var response      = new CreateOrderResponse();

            try
            {
                var budget = budgetFactory.CreateBudget(request.Items, request.ClientCode, request.CnpjCpf, false, false);
                if (budget.Items != null && budget.Items.Any())
                {
                    response.Order = budgetFactory.CreateBudget(budget.Items.FirstOrDefault().BudgetId, request.PaymentConditionCode);
                }
                else
                {
                    throw new Exception("Nenhum item foi criado no orçamento");
                }
            }
            catch (Exception ex)
            {
                response.Exception = ex;
                response.Message   = ex.Message;
            }

            return(response);
        }
Exemplo n.º 16
0
        public object Post(CreateOrder request)
        {
            CreateOrderResponse rsp = new CreateOrderResponse();

            _wxService.CreateOrders(request, rsp);
            return(rsp);
        }
Exemplo n.º 17
0
        public IActionResult CreateOrder([FromBody] CreateOrderRequest request)
        {
            OrderDetails        orderDetails        = new OrderDetails(request.CustomerId, request.OrderTotal);
            Order               order               = orderService.CreateOrder(orderDetails);
            CreateOrderResponse createOrderResponse = new CreateOrderResponse(order.Id);

            return(Ok(createOrderResponse));
        }
Exemplo n.º 18
0
        /// <summary>
        /// 统一下单接口
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public void CreateOrders(CreateOrder request, CreateOrderResponse response)
        {
            DateTime dt         = DateTime.Now;
            string   timeStart  = string.Format("{0:yyyyMMddHHmmss}", dt);
            string   timeExpire = string.Format("{0:yyyyMMddHHmmss}", dt.AddSeconds(300));
            SortedDictionary <string, string> ht = new SortedDictionary <string, string>
            {
                { "appid", ConfigurationManager.AppSettings["APPID"] },
                { "mch_id", ConfigurationManager.AppSettings["MCHID"] },
                { "device_info", "WEB" },
                { "nonce_str", RandomHelper.GenerateString(32) },
                { "sign_type", "MD5" },
                { "body", request.Body },
                { "detail", request.Detail },
                { "attach", request.Attach },
                { "out_trade_no", request.OutTradeNo },
                { "fee_type", "CNY" },
                { "total_fee", "" + request.TotalFee },
                { "spbill_create_ip", request.SpbillCreateIp },
                { "time_start", timeStart },
                { "time_expire", timeExpire },
                { "goods_tag", request.GoodsTag },
                { "notify_url", ConfigurationManager.AppSettings["NOTIFYURL"] },
                { "trade_type", "JSAPI" },
                { "openid", request.Openid },
                { "product_id", request.ProductId }
            };

            if (string.IsNullOrEmpty(request.LimitPay))
            {
                if (request.LimitPay == "no_credit")
                {
                    ht.Add("limit_pay", "no_credit");
                }
            }

            string sign = Md5Helper.UserMd5(WxPayHelper.CreateSign(ht));

            ht.Add("sign", sign);
            string    postXml  = WxPayHelper.CreateXmlRequest(ht);
            string    wxResult = HttpRequestUtil.HttpPost(UrlUnifiedorder, postXml);
            Hashtable htt      = XmlAndJsonToHash.XmlToHashTable(wxResult);

            wxResult = JsonHelper.ToJson(htt);
            CoResponse tr = JsonHelper.Deserialize <CoResponse>(wxResult);

            response.ResponseStatus.ErrorCode = tr.return_code;
            response.ResponseStatus.Message   = tr.return_msg;
            if (tr.return_code == "SUCCESS" && tr.result_code == "SUCCESS")
            {
                response.PrepayId = tr.prepay_id;
            }
            else
            {
                response.ResponseStatus.ErrorCode = tr.err_code;
                response.ResponseStatus.Message   = tr.err_code_des;
            }
        }
Exemplo n.º 19
0
        public CreateOrderResponse CreateOrder(Order order)
        {
            CreateOrderResponse response = new CreateOrderResponse();

            response.order = order;
            _orderRepository.SaveOrder(order);
            response.Success = true;
            return(response);
        }
Exemplo n.º 20
0
        public static async Task <HttpResponseMessage> CreateOrder([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            // Get request body
            var body = await req.Content.ReadAsStringAsync();

            var request = JsonConvert.DeserializeObject <CreateOrderRequest>(body, new JsonConverter[] { new GuidJsonConverter() });

            if (request == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, "No Valid Data submitted."));
            }

            Customer customer = request.Customer;

            var response = new CreateOrderResponse();

            // Register the customer if they dont exist yet
            if (customer.Anonymous || string.IsNullOrEmpty(customer.id))
            {
                // If we're not provided a valid First Name throw an error
                if (string.IsNullOrEmpty(customer.FirstName))
                {
                    response.Message = "No FirstName was provided";
                    return(req.CreateResponse(HttpStatusCode.ExpectationFailed, response));
                }

                // If we're not provided a valid ImageUrl throw an error
                if (string.IsNullOrEmpty(request.Order.CustomerImageUrl))
                {
                    response.Message = "No ImageUrl was provided";
                    return(req.CreateResponse(HttpStatusCode.ExpectationFailed, response));
                }

                // Check for existing customers
                Customer exitingCustomer = await FaceClient.Instance.IdentifyCustomerFace(customer.FaceId);

                if (exitingCustomer == null)
                {
                    customer = await FaceClient.Instance.RegisterNewCustomer(customer, request.Order.CustomerImageUrl);
                }

                else
                {
                    customer.id = exitingCustomer.id;
                }
            }

            // Store the order in the system
            request.Order.CustomerId = customer.id;

            response.Order = await CosmosClient.Instance.SaveOrder(request.Order);

            response.Message = "Order Created";

            return(req.CreateResponse(HttpStatusCode.OK, response));
        }
Exemplo n.º 21
0
        public override void SendOrder(Order order)
        {
            decimal outputVolume = order.Volume;

            if (order.Side == Side.Sell)
            {
                outputVolume = -1 * order.Volume;
            }

            CreateOrderRequst jOrder = new CreateOrderRequst()
            {
                Contract = order.SecurityNameCode,
                Iceberg  = 0,
                Price    = order.Price.ToString(CultureInfo.InvariantCulture),
                Size     = Convert.ToInt64(outputVolume),
                Tif      = "gtc",
                Text     = $"t-{order.NumberUser}"
            };

            string bodyContent = JsonConvert.SerializeObject(jOrder).Replace(" ", "").Replace(Environment.NewLine, "");


            string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
            var    headers   = new Dictionary <string, string>();

            headers.Add("Timestamp", timeStamp);
            headers.Add("KEY", _publicKey);
            headers.Add("SIGN", _signer.GetSignStringRest("POST", _path + _wallet + "/orders", "", bodyContent, timeStamp));

            var result = _requestREST.SendPostQuery("POST", _host + _path + _wallet, "/orders", Encoding.UTF8.GetBytes(bodyContent), headers);



            CreateOrderResponse orderResponse = JsonConvert.DeserializeObject <CreateOrderResponse>(result);

            if (orderResponse.Status == "finished")
            {
                SendLogMessage($"Order num {order.NumberUser} on exchange.", LogMessageType.Trade);
            }
            else if (orderResponse.Status == "open")
            {
                SendLogMessage($"Order num {order.NumberUser} wait to execution on exchange.", LogMessageType.Trade);
            }
            else
            {
                //err_msg
                dynamic errorData = JToken.Parse(result);
                string  errorMsg  = errorData.err_msg;

                SendLogMessage($"Order exchange error num {order.NumberUser} : {errorMsg}", LogMessageType.Error);

                order.State = OrderStateType.Fail;

                OnOrderEvent(order);
            }
        }
Exemplo n.º 22
0
        public static CreateOrderResponse Unmarshall(UnmarshallerContext context)
        {
            CreateOrderResponse createOrderResponse = new CreateOrderResponse();

            createOrderResponse.HttpResponse = context.HttpResponse;
            createOrderResponse.RequestId    = context.StringValue("CreateOrder.RequestId");
            createOrderResponse.OrderID      = context.StringValue("CreateOrder.OrderID");

            return(createOrderResponse);
        }
Exemplo n.º 23
0
        public IActionResult PlaceOrder(IFormCollection collection)
        {
            CreateOrderRequest request = new CreateOrderRequest();

            request.BasketId      = GetBasketId();
            request.CustomerEmail = _cookieAuthentication.GetAuthenticationToken();
            request.DeliveryId    = int.Parse(collection[FormDataKeys.DeliveryAddress.ToString()]);
            CreateOrderResponse response = _orderService.CreateOrder(request);

            return(RedirectToAction("CreatePaymentFor", "Payment", new { orderId = response.Order.Id }));
        }
Exemplo n.º 24
0
        public async Task <ActionResult <long> > Post(Order order, CancellationToken cancellationToken)
        {
            var request = new CreateOrderRequest
            {
                Order = order
            };

            CreateOrderResponse response = await _mediator.Send(request, cancellationToken);

            return(CreatedAtAction("Post", response.OrderId));
        }
Exemplo n.º 25
0
        public static WebResponse AsWebResponse(this CreateOrderResponse response)
        {
            var result = new WebResponse
            {
                Message    = response.Message,
                ErrorCode  = response.ErrorCode,
                StatusCode = response.StatusCode
            };

            return(result);
        }
Exemplo n.º 26
0
        public int PlaceOrder()
        {
            System.Web.Mvc.FormCollection collection = new System.Web.Mvc.FormCollection();
            Task <string> content = this.Request.Content.ReadAsStringAsync();
            int           body    = JsonConvert.DeserializeObject <int>(content.Result);

            collection.Add(FormDataKeys.DeliveryAddress.ToString(), body.ToString());
            CreateOrderResponse createOrderResponse = this.checkoutController.CreateOrderResponse(collection);

            return(createOrderResponse.Order.Id);
        }
Exemplo n.º 27
0
        public async Task Can_Create_Order()
        {
            var member    = new Member(1, 1, Permission.CanConfirmOrder);
            var createRes = new CreateOrderResponse(1);
            var handler   = CreateHandler(member, createRes);
            var request   = new OpenOrderRequest(1, 1, 1);
            var res       = await handler.Handle(request);

            Assert.IsTrue(res.Success);
            Assert.AreEqual(1, res.Value.OrderId);
        }
Exemplo n.º 28
0
        public static CreateOrderResponse Unmarshall(UnmarshallerContext context)
        {
            CreateOrderResponse createOrderResponse = new CreateOrderResponse();

            createOrderResponse.HttpResponse = context.HttpResponse;
            createOrderResponse.RequestId    = context.StringValue("CreateOrder.RequestId");
            createOrderResponse.Success      = context.BooleanValue("CreateOrder.Success");
            createOrderResponse.Code         = context.StringValue("CreateOrder.Code");
            createOrderResponse.Message      = context.StringValue("CreateOrder.Message");

            return(createOrderResponse);
        }
Exemplo n.º 29
0
        public CreateOrderResponse Create(List <int> itemIds)
        {
            //get items from database with maching ids
            //for testing using hard coded
            var items = new List <Item>
            {
                new Item
                {
                    Id    = 1,
                    Type  = ItemType.Video,
                    Name  = "Comprehensive First Aid Training",
                    Price = 40
                },

                new Item
                {
                    Id    = 2,
                    Type  = ItemType.Book,
                    Name  = "The Girl on the train",
                    Price = 10
                },

                new Item
                {
                    Id    = 2,
                    Type  = ItemType.Membership,
                    Name  = "Book Club",
                    Price = 100
                }
            };
            //get selected items
            var selectedItems = (from i in items
                                 join id in itemIds
                                 on i.Id equals id
                                 select i)
                                .ToList();
            //generate response
            var response = new CreateOrderResponse
            {
                OrderId = DateTime.UtcNow.ToString("hhmmssyyyyMMdd") + "1",
                IsMembershipSubscribed = selectedItems.Any(x => x.Type == ItemType.Membership),
                IsProductPurchased     = selectedItems.Any(x => x.Type != ItemType.Membership)
            };

            if (response.IsMembershipSubscribed)
            {
                //process membership if subscribed
            }

            //process order with selected items
            return(response);
        }
Exemplo n.º 30
0
        OpenOrderHandler CreateHandler(Member member, CreateOrderResponse createOrderResponse = null)
        {
            var uow = new Mock <IOrderingService>();

            uow.Setup(a => a.GetMemberById(It.IsAny <int>()))
            .ReturnsAsync(member);

            uow.Setup(a => a.CreateOrder(It.IsAny <Order>())).ReturnsAsync(createOrderResponse);

            var handler = new OpenOrderHandler(uow.Object);

            return(handler);
        }