Example #1
0
        private async Task <bool> CreateOrderItemsOfOrder(
            IEnumerable <OrderItem> orderItems,
            Order order,
            IEnumerable <ProductTier> productTiers
            )
        {
            var checkValidOrderItemsResult = CheckValidOrderItems(
                orderItems,
                productTiers);

            if (checkValidOrderItemsResult.IsSuccess == false)
            {
                throw new Exception("Danh sách sản phẩm trong đơn hàng không hợp lệ");
            }

            /** Add the rest info to each order item */
            orderItems = orderItems.Select(item =>
            {
                // get product tier to get current price
                var productTier = productTiers
                                  .SingleOrDefault(x => x.Id == item.ProductTierId);

                item.OrderId     = order.Id;
                item.SinglePrice = productTier.PricePerKg;

                return(item);
            });

            await _context.OrderItems.AddRangeAsync(orderItems);

            var created = await _context.SaveChangesAsync();

            return(created > 0);
        }
Example #2
0
        /** ChangeOrderStatusToPayed */
        public async Task <bool> ChangeOrderToPayed(Order order)
        {
            order.IsPayed = true;
            _context.Orders
            .Update(order);
            var updated = await _context.SaveChangesAsync();

            return(updated > 0);
        }
Example #3
0
        private bool CheckValidCanceledOrder(Order order)
        {
            /** Only can cancel order when its status is New */
            if (order.OrderStatus != OrderStatus.New)
            {
                throw new Exception("Chỉ được phép huỷ đơn hàng khi đơn hàng đó chưa bàn giao cho thủ kho (trạng thái = New)");
            }

            return(true);
        }
Example #4
0
        /** CHANGE ORDER TO SUCCEEDED */
        public async Task <UpdateResult <Order> > ChangeOrderToSucceeded(Order order)
        {
            if (order.OrderStatus != OrderStatus.Delivering)
            {
                return(new UpdateResult <Order>
                {
                    IsSuccess = false,
                    Errors = new List <string>()
                    {
                        "Đơn hàng chưa thể hoàn thành vì chưa được giao"
                    }
                });
            }

            /** Update order status */
            order.OrderStatus = OrderStatus.Succeeded;

            /** IF payment is COD then update IsPayed to true */
            if (order.PaymentMethod.Method == MethodOfPayment.COD)
            {
                order.IsPayed = true;
            }

            _context.Orders
            .Update(order);
            var updated = await _context.SaveChangesAsync();

            if (!(updated > 0))
            {
                return(new UpdateResult <Order>
                {
                    IsSuccess = false,
                    Errors = new List <string>()
                    {
                        "Xác nhận đơn hàng thành công có lỗi, xin thử lại"
                    }
                });
            }

            return(new UpdateResult <Order>
            {
                IsSuccess = true
            });
        }
Example #5
0
 private void PrepareOrderInfo(
     Order order,
     IEnumerable <OrderItem> orderItems,
     IEnumerable <ProductTier> productTiers,
     int customerId
     )
 {
     order.OrderStatus = OrderStatus.New;
     order.IsPayed     = false;
     order.TotalAmount = CalculateOrderTotalAmount(orderItems, productTiers);
     order.Currency    = PriceCurrency.VND;
     order.Code        = Regex.Replace(
         Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "");
     order.IsCustomerReceive = false;
     order.IsDeleted         = false;
     order.CreatedAt         = DateTime.UtcNow;
     order.UpdatedAt         = DateTime.UtcNow;
     order.CustomerId        = customerId;
 }
Example #6
0
        /** HAND OVER ORDER TO STORAGE MANAGER */
        public async Task <UpdateResult <Order> > HandOverOrderToStorageManager(Order order)
        {
            /** Only change order status to processing with the current status is New */
            if (order.OrderStatus != OrderStatus.New)
            {
                return(new UpdateResult <Order>
                {
                    IsSuccess = false,
                    Errors = new List <string>()
                    {
                        "Chỉ có thể bàn giao những đơn hàng mới tạo (trạng thái = New)"
                    }
                });
            }

            /** Change status to Processing */
            order.OrderStatus = OrderStatus.Processing;

            _context.Orders.Update(order);
            var updated = await _context.SaveChangesAsync();

            bool isUpdateSucceeded = updated > 0;

            if (!isUpdateSucceeded)
            {
                return(new UpdateResult <Order>
                {
                    IsSuccess = false,
                    Errors = new List <string>()
                    {
                        "Bàn giao hoá đơn bị lỗi, xin thử lại"
                    }
                });
            }

            return(new UpdateResult <Order>
            {
                IsSuccess = true
            });
        }
Example #7
0
        private void HandleStripePaymentIfPaymentMethodIsStripe(
            Entities.PaymentMethod chosenPaymentMethod,
            Order order,
            string stripeSecretKey
            )
        {
            if (chosenPaymentMethod.Method == MethodOfPayment.Stripe)
            {
                /** If payment by Stripe */
                StripeConfiguration.ApiKey = stripeSecretKey;

                var options = new PaymentIntentCreateOptions
                {
                    Amount   = (long?)order.TotalAmount,
                    Currency = "vnd",
                };
                var stripeService = new PaymentIntentService();
                var paymentIntent = stripeService.Create(options);
                order.PaymentIntentId    = paymentIntent.Id;
                order.StripeClientSecret = paymentIntent.ClientSecret;
            }
        }
Example #8
0
        public async Task <IActionResult> Create(
            [FromBody] CreateOrderRequest createModel
            )
        {
            var      requestedUserId   = int.Parse(HttpContext.GetUserIdFromRequest());
            DateTime IdealShipTimeDate = string.IsNullOrEmpty(createModel.IdealShipTime) == false
                ? DateTime.ParseExact(createModel.IdealShipTime, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
                : DateTime.UtcNow;

            Order orderEntity = new Order
            {
                IdealShipTime   = IdealShipTimeDate,
                IsGift          = createModel.IsGift,
                Notes           = createModel.Notes,
                AddressId       = createModel.AddressId,
                PaymentMethodId = createModel.PaymentMethodId
            };

            var createResult = await _orderService.CreateAsync(
                orderEntity,
                requestedUserId,
                _appSettings.Value.StripeSecretKey
                );

            if (createResult.IsSuccess == false)
            {
                return(BadRequest(createResult.Errors));
            }

            var orderResponse = _mapper.Map <OrderResponse>(orderEntity);

            var locationUri = _uriService.GetByIdUri(
                ApiRoutes.Order.GetById.Replace("{orderId}", orderEntity.Id.ToString())
                );

            return(Created(locationUri,
                           new Response <OrderResponse>(orderResponse)));
        }
Example #9
0
        /** CREATE ASYNC */
        public async Task <CreateResult <Order> > CreateAsync(
            Order order,
            int requestedUserId,
            string stripeSecretKey)
        {
            var customer = await _context.Customers
                           .Where(c => c.UserId == requestedUserId)
                           .Include(c => c.Cart)
                           .Include(c => c.User)
                           .FirstOrDefaultAsync();

            var chosenPaymentMethod = await _context.PaymentMethods
                                      .SingleOrDefaultAsync(x => x.Id == order.PaymentMethodId);

            /** Get all products in cart of customer to create order */
            var cartDetails = await GetListCartDetailToPay(customer.Cart.Id);

            if (cartDetails.Count() == 0)
            {
                return(new CreateResult <Order>
                {
                    IsSuccess = false,
                    Errors = new List <string>()
                    {
                        "Bạn không có sản phẩm trong giỏ hàng để thanh toán"
                    }
                });
            }

            /** Get all product tiers in order items from db to use */
            var productTiers = await GetListProductTierFromCartDetails(cartDetails);

            List <OrderItem> orderItems = CreateListOrderItemFromProductsInCart(
                cartDetails,
                productTiers
                );

            PrepareOrderInfo(
                order,
                orderItems,
                productTiers,
                customer.Id);

            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    /** Handle stripe payment (if choose) */
                    HandleStripePaymentIfPaymentMethodIsStripe(
                        chosenPaymentMethod,
                        order,
                        stripeSecretKey
                        );

                    /** Create order */
                    await _context.Orders.AddAsync(order);

                    var orderCreated = await _context.SaveChangesAsync();

                    if (!(orderCreated > 0))
                    {
                        transaction.Dispose();
                        throw new Exception("Thanh toán giỏ hàng thất bại, xin thử lại");
                    }

                    /** Create order items */
                    bool isCreateOrderItemsSuccess = await CreateOrderItemsOfOrder(
                        orderItems,
                        order,
                        productTiers
                        );

                    if (!isCreateOrderItemsSuccess)
                    {
                        transaction.Dispose();
                        throw new Exception("Thanh toán giỏ hàng thất bại, xin thử lại");
                    }

                    /** Clear all cart items after pay cart (after create order) */
                    var areAllCartDetailsCleared = await ClearAllCartItemsAfterPayCart(
                        cartDetails
                        );

                    if (!areAllCartDetailsCleared)
                    {
                        transaction.Dispose();
                        throw new Exception("Thanh toán giỏ hàng thất bại, xin thử lại");
                    }

                    await transaction.CommitAsync();
                }
                catch (Exception e)
                {
                    return(new CreateResult <Order>
                    {
                        IsSuccess = false,
                        Errors = new List <string>()
                        {
                            e.Message.ToString()
                        }
                    });
                }
            }

            /** Send mail to user */
            string orderMailTemplate = _emailTemplateService
                                       .CreateOrderHtmlTempalteToSendMailToCustomer(
                order.Code,
                order.TotalAmount,
                order.CreatedAt,
                orderItems,
                productTiers,
                customer.Name,
                customer.User.Email
                );

            _emailService.SendMail(
                customer.User.Email,
                customer.Name,
                $"Đơn hàng của khách hàng '{customer.Name}' vào {order.CreatedAt.ToString("dd/MM/y yyy HH:mm:ss")}",
                orderMailTemplate
                );

            return(new CreateResult <Order>
            {
                IsSuccess = true,
                EntityReturn = order
            });
        }
Example #10
0
        /** CANCLE ORDER ASYNC */
        public async Task <UpdateResult <Order> > CancelOrderAsync(
            Order order,
            CancelOrderReport cancelOrderReport)
        {
            var customer = await _context.Customers
                           .Where(c => c.Id == order.CustomerId)
                           .Include(c => c.User)
                           .FirstOrDefaultAsync();

            try
            {
                if (!CheckValidCanceledOrder(order))
                {
                    throw new Exception("Huỷ đơn hàng bị lỗi, xin thử lại");
                }

                using (var transaction = _context.Database.BeginTransaction())
                {
                    try
                    {
                        /** Update status of order to Canceled */
                        order.OrderStatus = OrderStatus.Canceled;
                        _context.Orders.Update(order);
                        var updated = await _context.SaveChangesAsync();

                        if (!(updated > 0))
                        {
                            transaction.Dispose();
                            return(new UpdateResult <Order>
                            {
                                IsSuccess = false,
                                Errors = new List <string>()
                                {
                                    "Huỷ hoá đơn không thành công, xin thử lại"
                                }
                            });
                        }

                        /** Create CancelOrderReport */
                        cancelOrderReport.OrderId   = order.Id;
                        cancelOrderReport.CreatedAt = DateTime.UtcNow;
                        cancelOrderReport.IsDeleted = false;
                        await _context.CancelOrderReports.AddAsync(cancelOrderReport);

                        var created = await _context.SaveChangesAsync();

                        if (!(created > 0))
                        {
                            transaction.Dispose();
                            return(new UpdateResult <Order>
                            {
                                IsSuccess = false,
                                Errors = new List <string>()
                                {
                                    "Huỷ hoá đơn không thành công, xin thử lại"
                                }
                            });
                        }

                        await transaction.CommitAsync();
                    }
                    catch (Exception e)
                    {
                        return(new UpdateResult <Order>
                        {
                            IsSuccess = false,
                            Errors = new List <string>()
                            {
                                e.Message.ToString()
                            }
                        });
                    }
                }
            }
            catch (Exception e)
            {
                return(new UpdateResult <Order>
                {
                    IsSuccess = false,
                    Errors = new List <string>()
                    {
                        e.Message.ToString()
                    }
                });
            }

            /** Send mail to customer */
            string cancelOrderTemplate = _emailTemplateService
                                         .CancelOrderTemplate(
                customer.Name,
                order.Code,
                cancelOrderReport.CancelReason
                );

            _emailService.SendMail(
                customer.User.Email,
                customer.Name,
                $"Huỷ hoá đơn {order.Code} tại Banana Boys Fruit",
                cancelOrderTemplate
                );

            return(new UpdateResult <Order>
            {
                IsSuccess = true
            });
        }