Esempio n. 1
0
        public async Task <Order> PlaceOrderAsync(CreateOrderInput orderInput, int clientId)
        {
            if (!CategoryIsValid(orderInput.CategoryId))
            {
                throw new BadInputException("category is not supported");
            }

            if (await ordersRepository.FirstOrDefaultAsync(o => o.ClientId == clientId && o.StatusId < 3) != null)
            {
                throw new BadInputException("client already has an actual order");
            }

            var order = mapper.Map <Order>(orderInput);

            order.ClientId      = clientId;
            order.BeginningTime = DateTime.Now;
            order.StatusId      = (int)OrdersStatuses.Awaiting;
            order.Rate          = 0;

            order.Location = new Point(new Coordinate(orderInput.Location.Longitude, orderInput.Location.Latitude))
            {
                SRID = 4326
            };

            int orderId = await ordersRepository.InsertWithIdAsync(order);

            return(await ordersRepository.FirstOrDefaultAsync(o => o.Id == orderId));
        }
Esempio n. 2
0
    protected virtual Task <CreateFlashSaleOrderEto> PrepareCreateFlashSaleOrderEtoAsync(
        FlashSalePlanCacheItem plan, Guid resultId, CreateOrderInput input,
        Guid userId, DateTime now, string hashToken)
    {
        var planEto = ObjectMapper.Map <FlashSalePlanCacheItem, FlashSalePlanEto>(plan);

        planEto.TenantId = CurrentTenant.Id;

        var eto = new CreateFlashSaleOrderEto()
        {
            TenantId        = CurrentTenant.Id,
            PlanId          = plan.Id,
            UserId          = userId,
            PendingResultId = resultId,
            StoreId         = plan.StoreId,
            CreateTime      = now,
            CustomerRemark  = input.CustomerRemark,
            Plan            = planEto,
            HashToken       = hashToken
        };

        foreach (var item in input.ExtraProperties)
        {
            eto.ExtraProperties.Add(item.Key, item.Value);
        }

        return(Task.FromResult(eto));
    }
Esempio n. 3
0
        public CreateOrderOutput AddItemByOrderId([FromBody] CreateOrderInput input)
        {
            decimal           sum    = 0;
            CreateOrderOutput output = new CreateOrderOutput();

            if (input == null)
            {
                output.Status = "INPUT_IS_NULL";
            }
            else
            {
                Order order = _db.Orders.Where(e => e.Id.Equals(input.OrderId) && e.Deleted == false && e.Status == 1).FirstOrDefault();
                if (order == null)
                {
                    output.Status = "ORDER_NOT_EXIST";
                }
                else
                {
                    if (input.Items != null)
                    {
                        foreach (CreateOrderItem item in input.Items)
                        {
                            OrderItem orderItem = order.OrderItems.Where(e => e.MenuItem.Id.Equals(item.ItemId) && e.Deleted == false).FirstOrDefault();
                            MenuItem  menuItem  = _db.MenuItems.Where(e => e.Id.Equals(item.ItemId) && e.Deleted == false).FirstOrDefault();
                            sum += (decimal)item.Quantity * menuItem.Price;
                            if (orderItem == null)
                            {
                                OrderItem newItem = new OrderItem()
                                {
                                    Order     = order,
                                    MenuItem  = menuItem,
                                    UnitPrice = menuItem.Price,
                                    Quantity  = item.Quantity
                                };

                                if (order.OrderItems == null)
                                {
                                    order.OrderItems = new List <OrderItem>();
                                }

                                order.OrderItems.Add(newItem);
                            }
                            else
                            {
                                orderItem.Quantity += item.Quantity;
                            }

                            output.Status = "OK";
                            _db.SaveChanges();
                        }
                    }

                    output.Status = "OK";
                    order.Amount += sum;
                    _db.SaveChanges();
                }
            }

            return(output);
        }
Esempio n. 4
0
        public async Task <GraphQLResponse <CreateOrder> > CreateOrderCorp(CreateOrderInput createOrderInput)
        {
            if (!IsLogged)
            {
                throw new Exception("Usuario não logado");
            }

            var req = new GraphQLRequest
            {
                Query     = @"mutation ($createOrderInput: createOrderMutationInput!) {
                          createOrder(input: $createOrderInput) {
                            success
                            errors {
                            field
                            message
                            }
                            }
                        }",
                Variables = new
                {
                    createOrderInput
                }
            };


            var graphQLResponse = await _client.SendMutationAsync <CreateOrder>(req);

            return(graphQLResponse);
        }
        public async Task CreateOrderAsync(CreateOrderInput input)
        {
            var orderId = Claptrap.State.Identity.Id;

            // throw exception if order already created
            if (StateData.OrderCreated)
            {
                throw new BizException($"order with order id already created : {orderId}");
            }

            // get items from cart
            var cartGrain = _grainFactory.GetGrain <ICartGrain>(input.CartId);
            var items     = await cartGrain.GetItemsAsync();

            // update inventory for each sku
            foreach (var(skuId, count) in items)
            {
                var skuGrain = _grainFactory.GetGrain <ISkuGrain>(skuId);
                await skuGrain.UpdateInventoryAsync(-count);
            }

            // remove all items from cart
            await cartGrain.RemoveAllItemsAsync();

            // create a order
            var evt = this.CreateEvent(new OrderCreatedEvent
            {
                UserId = input.UserId,
                Skus   = items
            });
            await Claptrap.HandleEventAsync(evt);
        }
Esempio n. 6
0
        private void CreateOrderInputValidate(CreateOrderInput createOrderInput)
        {
            if (string.IsNullOrWhiteSpace(createOrderInput.ProductCode))
            {
                throw new ValidationException(nameof(createOrderInput.ProductCode));
            }
            if (createOrderInput.Quantity <= 0)
            {
                throw new InvalidQuantityException();
            }
            var productInfo = _productService.GetProductInfo(createOrderInput.ProductCode);

            if (productInfo == null)
            {
                throw new ProductNotFoundException();
            }
            if (productInfo.Stock == 0)
            {
                throw new InsufficientProductInStockException();
            }
            if (productInfo.Stock < createOrderInput.Quantity)
            {
                throw new InsufficientProductInStockException();
            }
        }
Esempio n. 7
0
        public async Task <GetOrderOutput> Create(CreateOrderInput input)
        {
            // 扣减库存
            var product = await _productAppService.DeductStock(new DeductStockInput()
            {
                Quantity  = input.Quantity,
                ProductId = input.ProductId
            });

            // 创建订单
            var order = input.MapTo <Domain.Orders.Order>();

            order.Amount = product.UnitPrice * input.Quantity;
            order        = await Create(order);

            RpcContext.GetContext().SetAttachment("orderId", order.Id);

            //扣减账户余额
            var deductBalanceInput = new DeductBalanceInput()
            {
                OrderId = order.Id, AccountId = input.AccountId, OrderBalance = order.Amount
            };
            var orderBalanceId = await _accountAppService.DeductBalance(deductBalanceInput);

            if (orderBalanceId.HasValue)
            {
                RpcContext.GetContext().SetAttachment("orderBalanceId", orderBalanceId.Value);
            }

            return(order.MapTo <GetOrderOutput>());
        }
Esempio n. 8
0
 private void UpdateProductStock(CreateOrderInput createOrderInput)
 {
     _productService.UpdateProductStock(new UpdateProductStockInput
     {
         ProductCode = createOrderInput.ProductCode,
         Quantity    = createOrderInput.Quantity
     });
 }
        public async Task <IActionResult> PlaceOrderAsync([FromBody] CreateOrderInput input)
        {
            var orderId    = Guid.NewGuid().ToString("N");
            var orderGrain = _grainFactory.GetGrain <IOrderGrain>(orderId);
            await orderGrain.CreateOrderAsync(input);

            return(Json("ok"));
        }
Esempio n. 10
0
 public async Task <CreateOrderOutput> CreateOrderAsync(CreateOrderInput input, CallContext context = default)
 {
     return(await Task.FromResult(new CreateOrderOutput
     {
         OrderId = input.OrderId,
         OrderName = input.OrderName,
     }));
 }
Esempio n. 11
0
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <returns></returns>
        public async Task <OrderListDto> CreateOrder(CreateOrderInput input)
        {
            var customer = await _customerRepository.FirstOrDefaultAsync(c => c.Id == input.CustomerId);

            if (customer == null)
            {
                throw new UserFriendlyException("该账户不存在");
            }
            var product = await _productRepository.FirstOrDefaultAsync(c => c.Id == input.ProductId);

            if (product == null)
            {
                throw new UserFriendlyException("该产品不存在");
            }
            var price      = product.CustomerPrices.First(c => c.CustomerId == customer.Id);
            var totalPrice = price.Price * input.Count;

            if (customer.Balance < totalPrice)
            {
                throw new UserFriendlyException("账户下余额不足,请充值后再试");
            }
            var dto = new Order()
            {
                CustomerId  = input.CustomerId,
                OrderNum    = Guid.NewGuid().ToString("N"),
                State       = null, PayState = false,
                Count       = input.Count,
                TotalPrice  = totalPrice,
                ProductId   = product.Id,
                Price       = price.Price,
                ProductName = product.ProductName,
                LevelOne    = product.LevelOne.Name,
                LevelTwo    = product.LevelTwo.Name,
                Profile     = product.Profile
            };

            if (!product.RequireForm)
            {
                var cost = new CustomerCost()
                {
                    Balance    = customer.Balance,
                    CustomerId = customer.Id
                };
                customer.Balance   -= dto.TotalPrice;
                cost.Cost           = dto.TotalPrice;
                cost.CurrentBalance = customer.Balance;
                await _costRepository.InsertAsync(cost);

                dto.PayState = true;
            }
            dto = await _ordeRepository.InsertAsync(dto);

            await CurrentUnitOfWork.SaveChangesAsync();

            return(dto.MapTo <OrderListDto>());
        }
Esempio n. 12
0
        public void When_Product_NotFound()
        {
            CreateOrderInput createOrderInput = new CreateOrderInput
            {
                ProductCode = "P1",
                Quantity    = 10
            };

            Assert.Throws <ProductNotFoundException>(() => orderService.CreateOrder(createOrderInput));
        }
Esempio n. 13
0
        public async Task <GetOrderOutput> OrderCreateConfirm(CreateOrderInput input)
        {
            var orderId = RpcContext.GetContext().GetAttachment("orderId");
            var order   = await _orderDomainService.GetById(orderId.To <long>());

            order.Status = OrderStatus.Payed;
            order        = await _orderDomainService.Update(order);

            return(order.MapTo <GetOrderOutput>());
        }
Esempio n. 14
0
 public async Task <CreateOrderOutput> CreateOrderAsync(CreateOrderInput request, CallContext context = default)
 {
     return(await Task.FromResult(new CreateOrderOutput
     {
         BuyerId = request.BuyerId,
         BuyerName = request.BuyerName,
         OrderId = request.OrderId,
         OrderName = request.OrderName,
     }));
 }
Esempio n. 15
0
        public void When_Quantity_IsLessThanZero()
        {
            CreateOrderInput createOrderInput = new CreateOrderInput
            {
                ProductCode = "P1",
                Quantity    = -10
            };

            Assert.Throws <InvalidQuantityException>(() => orderService.CreateOrder(createOrderInput));
        }
Esempio n. 16
0
 public override Task <CreateOrderOutPut> CreateOrder(CreateOrderInput request, ServerCallContext context)
 {
     return(Task.FromResult(new CreateOrderOutPut
     {
         BuyerId = request.BuyerId,
         BuyerName = request.BuyerName,
         OrderId = request.OrderId,
         OrderName = request.OrderName,
     }));
 }
Esempio n. 17
0
        public async Task CreateOrderAsync(CreateOrderInput input)
        {
            var order = new Order(GuidGenerator.Create(), input.CustomerId);

            foreach (var item in input.OrderLines)
            {
                order.AddProduct(item.ProductId, item.Count);
            }
            await _orderRepository.InsertAsync(order);
        }
    public async Task OrderAsync_Throw_Exception_When_Not_PreOrder()
    {
        var plan = await CreateFlashSalePlanAsync();

        var createOrderInput = new CreateOrderInput();

        (await AppService.OrderAsync(plan.Id, createOrderInput)
         .ShouldThrowAsync <BusinessException>())
        .Code.ShouldBe(FlashSalesErrorCodes.PreOrderExpired);
    }
Esempio n. 19
0
 private void UpdateCampaignInfo(Guid campaignId, CreateOrderInput createOrderInput, decimal price)
 {
     _campaignService.UpdateCampaignInfo(new UpdateCampaignInfoInput
     {
         CampaignId  = campaignId,
         Quantity    = createOrderInput.Quantity,
         ProductCode = createOrderInput.ProductCode,
         Price       = price
     });
 }
    public async Task OrderAsync_Throw_Exception_When_FlashSaleNotStarted()
    {
        var plan = await CreateFlashSalePlanAsync(timeRange : CreateTimeRange.NotStart);

        var createOrderInput = new CreateOrderInput();
        await AppService.PreOrderAsync(plan.Id);

        (await AppService.OrderAsync(plan.Id, createOrderInput)
         .ShouldThrowAsync <BusinessException>())
        .Code.ShouldBe(FlashSalesErrorCodes.FlashSaleNotStarted);
    }
Esempio n. 21
0
        public async Task <GraphQLResponse <CreateOrder> > CreateOrder(CreateOrderInput createOrderInput)
        {
            if (!IsLogged)
            {
                throw new Exception("Usuario não logado");
            }

            var req = new GraphQLRequest
            {
                Query     = @"mutation ($createOrderInput: createOrderMutationInput!) {
                          createOrder(input: $createOrderInput) {
                            success
                            shop
                        {
                            pk
                              name
                        }
                        orders {
                              pk
                              trackingKey
                              packages {
                                pk
                                status
                                pickupWaypoint {
                                  index
                                  indexDisplay
                                  eta
                                  legDistance
                                }
                                waypoint {
                                  index
                                  indexDisplay
                                  eta
                                  legDistance
                                }
                              }
                            }
                            errors {
                              field
                              message
                            }
                          }
                        }",
                Variables = new
                {
                    createOrderInput
                }
            };


            var graphQLResponse = await _client.SendMutationAsync <CreateOrder>(req);

            return(graphQLResponse);
        }
Esempio n. 22
0
 public async Task <CreateOrderRequestResult> CreateOrderAsync(CreateOrderInput input)
 {
     return(await $"{input.EmpaySettings.ApiEndpointUrl}/ordering/v1/orders"
            .WithOAuthBearerToken(await GetApiAccessTokenAsync(new GetApiAccessTokenInput
     {
         EmpaySettings = input.EmpaySettings,
         Scope = AppPermissions.OrdersWrite
     }).ConfigureAwait(false))
            .PostJsonAsync(input.Request)
            .ReceiveJson <CreateOrderRequestResult>()
            .ConfigureAwait(false));
 }
Esempio n. 23
0
        public async Task <IActionResult> DraftOrderAsync([FromBody] CreateOrderInput input)
        {
            var sumamount          = input.ListItem.Sum(p => p.Amount);
            List <OrderItem> items = new List <OrderItem>();

            input.ListItem.ForEach(p =>
            {
                OrderItem temp     = new OrderItem();
                temp.Amount        = p.Amount;
                temp.Count         = p.Count;
                temp.OrderItemName = p.OrderItemName;
                items.Add(temp);
            });
            Address address = new Address {
                City = "南通", Country = "正余", State = "青正", Street = "测试", ZipCode = "20033"
            };

            MainOrder order = new MainOrder(input.OrderId, input.OrderName, sumamount, address, 0, 0, DateTime.Now, DateTime.MinValue, 1, items);


            using (var transaction = _orderDbContext.Database.BeginTransaction())
            {
                try
                {
                    OrderCreateEvent eventdata = new OrderCreateEvent
                    {
                        OrderId    = order.OrderId,
                        PayDecimal = order.OrderSumAmount,
                        PayedDesc  = "支付描述",
                        Payer      = "Shawn"
                    };
                    _capBus.Publish("Order.services.Payed", eventdata);


                    await _orderDbContext.AddAsync(order);

                    var result = await _orderDbContext.SaveChangesAsync();



                    transaction.Commit();
                }
                catch (Exception e)
                {
                    await transaction.RollbackAsync();

                    return(BadRequest());
                }

                return(Ok());
            }
        }
Esempio n. 24
0
        public void When_CreateOrder_IsSuccessful()
        {
            CreateProductInput createProductInput = new CreateProductInput
            {
                Code  = "P1",
                Price = 100,
                Stock = 1000,
            };

            CreateProduct(createProductInput);

            CreateOrderInput createOrderInput = new CreateOrderInput
            {
                ProductCode = "P1",
                Quantity    = 10
            };
            var orderResponse = CreateOrder(createOrderInput);

            Assert.AreEqual(HttpStatusCode.OK, orderResponse.StatusCode);

            var getProduct = GetProduct();

            Assert.AreEqual(990, getProduct.Stock);

            CreateCampaignInput createCampaignInput = new CreateCampaignInput
            {
                Name                   = "C1",
                ProductCode            = "P1",
                TargetSalesCount       = 100,
                Duration               = 10,
                PriceManipulationLimit = 20
            };

            CreateCampaign(createCampaignInput);
            IncreaseTime();


            var orderResponse2 = CreateOrder(createOrderInput);

            Assert.AreEqual(HttpStatusCode.OK, orderResponse2.StatusCode);

            var getProduct2 = GetProduct();

            Assert.AreEqual(980, getProduct2.Stock);

            var campaignResponse = GetCampaign(createCampaignInput.Name);

            Assert.AreEqual(createCampaignInput.TargetSalesCount, campaignResponse.TargetSales);
            Assert.AreEqual(createOrderInput.Quantity, campaignResponse.TotalSales);
            Assert.AreEqual(980, campaignResponse.Turnover);
            Assert.AreEqual(98, campaignResponse.AverageItemPrice);
        }
Esempio n. 25
0
        public async Task OrderCreateCancel(CreateOrderInput input)
        {
            var orderId = RpcContext.GetContext().GetAttachment("orderId");

            if (orderId != null)
            {
                // await _orderDomainService.Delete(orderId.To<long>());
                var order = await _orderDomainService.GetById(orderId.To <long>());

                order.Status = OrderStatus.UnPay;
                await _orderDomainService.Update(order);
            }
        }
    public async Task OrderAsync_Throw_Exception_When_FlashSaleIsOver()
    {
        var plan = await CreateFlashSalePlanAsync(timeRange : CreateTimeRange.WillBeExpired);

        var createOrderInput = new CreateOrderInput();
        await AppService.PreOrderAsync(plan.Id);

        await Task.Delay(TimeSpan.FromSeconds(1.2));

        (await AppService.OrderAsync(plan.Id, createOrderInput)
         .ShouldThrowAsync <BusinessException>())
        .Code.ShouldBe(FlashSalesErrorCodes.FlashSaleIsOver);
    }
Esempio n. 27
0
        public async Task <IActionResult> CreateOrder([FromBody] CreateOrderInput orderData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var order = await ordersService.PlaceOrderAsync(orderData, User.GetUserId());

            var orderVM = mapper.Map <CreatedOrderVM>(order);

            return(Ok(orderVM));
        }
Esempio n. 28
0
        private HttpResponseMessage CreateOrder(CreateOrderInput createOrderInput)
        {
            using (var client = new TestStart().Client)
            {
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                var json = JsonConvert.SerializeObject(createOrderInput);
                var data = new StringContent(json, Encoding.UTF8, "application/json");

                var response = client.PostAsync("/api/order", data).Result;

                return(response);
            }
        }
    public async Task OrderAsync_Return_False_When_TryReduceInventory_Failed()
    {
        var plan = await CreateFlashSalePlanAsync();

        var createOrderInput = new CreateOrderInput();
        await AppService.PreOrderAsync(plan.Id);

        FakeFlashSaleInventoryManager.ShouldReduceSuccess = false;

        var result = await AppService.OrderAsync(plan.Id, createOrderInput);

        result.IsSuccess.ShouldBe(false);
        result.FlashSaleResultId.ShouldBeNull();
    }
Esempio n. 30
0
        public void CreateOrder(CreateOrderInput createOrderInput)
        {
            CreateOrderInputValidate(createOrderInput);
            var     productInfo = _productService.GetProductInfo(createOrderInput.ProductCode);
            decimal price       = productInfo.Price * createOrderInput.Quantity;

            _orderRepository.CreateOrder(new Order(createOrderInput.ProductCode, createOrderInput.Quantity, price, productInfo.CampaignId));

            UpdateProductStock(createOrderInput);
            if (productInfo.CampaignId.HasValue)
            {
                UpdateCampaignInfo(productInfo.CampaignId.Value, createOrderInput, price);
            }
        }