示例#1
0
        public async Task <Result> Post([FromBody] UserAddressCreateParam param)
        {
            var user = await _workContext.GetCurrentUserAsync();

            var countryId = (int)CountryWithId.China;
            var provinces = await _countryService.GetProvinceByCache(countryId);

            if (provinces == null || provinces.Count <= 0)
            {
                throw new Exception("省市区数据异常,请联系管理员");
            }

            if (!provinces.Any(c => c.Id == param.StateOrProvinceId && c.Level == StateOrProvinceLevel.Default))
            {
                throw new Exception("所选择省信息不存在");
            }

            if (!provinces.Any(c => c.Id == param.CityId && c.Level == StateOrProvinceLevel.City && c.ParentId == param.StateOrProvinceId))
            {
                throw new Exception("所选择市信息不存在");
            }

            if (param.DistrictId.HasValue)
            {
                if (!provinces.Any(c => c.Id == param.DistrictId && c.Level == StateOrProvinceLevel.District && c.ParentId == param.CityId))
                {
                    throw new Exception("所选择区/县信息不存在");
                }
            }

            var address = new Address()
            {
                AddressLine1      = param.AddressLine1,
                ContactName       = param.ContactName,
                Phone             = param.Phone,
                CountryId         = countryId,
                StateOrProvinceId = param.DistrictId ?? param.CityId, // 存储最小结构数据
            };
            var userAddress = new UserAddress()
            {
                Address     = address,
                UserId      = user.Id,
                AddressType = AddressType.Shipping
            };

            _userAddressRepository.Add(userAddress);

            var tran = _userAddressRepository.BeginTransaction();
            await _userAddressRepository.SaveChangesAsync();

            if (param.IsDefault)
            {
                var dbUser = await _userRepository.FirstOrDefaultAsync(user.Id);

                dbUser.DefaultShippingAddress = userAddress;
                await _userRepository.SaveChangesAsync();
            }
            tran.Commit();
            return(Result.Ok());
        }
示例#2
0
        public async Task <Result> CurrentUser()
        {
            var user = await _workContext.GetCurrentUserAsync();

            if (user == null)
            {
                return(Result.Fail("Error"));
            }
            var result = new AccountResult()
            {
                UserId               = user.Id,
                UserName             = user.UserName,
                Culture              = user.Culture,
                Email                = StringHelper.EmailEncryption(user.Email),
                EmailConfirmed       = user.EmailConfirmed,
                FullName             = user.FullName,
                LastActivityOn       = user.LastActivityOn,
                LastIpAddress        = user.LastIpAddress,
                LastLoginOn          = user.LastLoginOn,
                PhoneNumber          = StringHelper.PhoneEncryption(user.PhoneNumber),
                PhoneNumberConfirmed = user.PhoneNumberConfirmed,
                Avatar               = user.AvatarUrl,
                NotifyCount          = 20
            };

            return(Result.Ok(result));
        }
        public async Task <Result> AddToCart([FromBody] AddToCartParam model)
        {
            var currentUser = await _workContext.GetCurrentUserAsync();

            await _cartService.AddToCart(currentUser.Id, model.ProductId, model.Quantity);

            var cart = await _cartService.GetActiveCartDetails(currentUser.Id);

            return(Result.Ok(cart));
        }
示例#4
0
        public async Task <Result> Get()
        {
            var currentUser = await _workContext.GetCurrentUserAsync();

            var query      = _warehouseRepository.Query();
            var warehouses = await query.Select(x => new
            {
                x.Id,
                x.Name
            }).ToListAsync();

            return(Result.Ok(warehouses));
        }
示例#5
0
        public async Task <Result> CheckoutByCart(int?userAddressId)
        {
            var user = await _workContext.GetCurrentUserAsync();

            var customerId = user.Id;
            var cart       = await _cartRepository.Query()
                             .Where(x => x.CustomerId == customerId && x.IsActive)
                             .Include(c => c.Items)
                             .FirstOrDefaultAsync();

            if (cart == null || cart.Items == null || cart.Items.Where(c => c.IsChecked).Count() <= 0)
            {
                throw new Exception("请选择商品");
            }
            if (cart.Items.Where(c => c.IsChecked).Any(c => c.Quantity <= 0))
            {
                throw new Exception("商品数量必须大于0");
            }
            var param = new CheckoutParam()
            {
                CustomerId    = customerId,
                UserAddressId = userAddressId,
            };

            param.Items = cart.Items.Where(c => c.IsChecked).Select(c => new CheckoutItemParam()
            {
                ProductId = c.ProductId,
                Quantity  = c.Quantity
            }).ToList();

            var data = await _orderService.OrderCheckout(param);

            return(Result.Ok(data));
        }
示例#6
0
        public async Task <OrderCreateResult> OrderCreateByCart(int cartId, OrderCreateBaseParam param, string adminNote = null)
        {
            if (param == null)
            {
                throw new Exception("参数异常");
            }

            var user = await _workContext.GetCurrentUserAsync();

            var customerId = param.CustomerId;

            return(await OrderCrateByCart2(cartId, param, adminNote));

            // TODO 下单锁
            //var isLocker = _locker.PerformActionWithLock(OrderKeys.CustomerCreateOrderLock + customerId, TimeSpan.FromSeconds(10),
            //    async () => await OrderCrateByCart2(cartId, param, adminNote));

            //if (!isLocker)
            //{
            //    throw new Exception("正在下单,请勿重复操作");
            //}
        }
示例#7
0
        public async Task <Result> Clear()
        {
            var user = await _workContext.GetCurrentUserAsync();

            var list = await _productRecentlyViewedRepository.Query()
                       .Where(c => c.CustomerId == user.Id)
                       .ToListAsync();

            foreach (var item in list)
            {
                item.IsDeleted = true;
            }
            await _productRecentlyViewedRepository.SaveChangesAsync();

            return(Result.Ok());
        }
        public async Task <Result <ShipmentQueryResult> > Get(long id)
        {
            var shipment = await _shipmentRepository.Query()
                           .Include(c => c.Order)
                           .Include(c => c.CreatedBy)
                           .Include(c => c.Items).ThenInclude(c => c.OrderItem)
                           .Select(c => new ShipmentQueryResult
            {
                Id             = c.Id,
                AdminComment   = c.AdminComment,
                CreatedBy      = c.CreatedBy.FullName,
                TrackingNumber = c.TrackingNumber,
                DeliveredOn    = c.DeliveredOn,
                OrderId        = c.OrderId,
                OrderNo        = c.Order.No.ToString(),
                OrderStatus    = c.Order.OrderStatus,
                ShippingStatus = c.Order.ShippingStatus,
                ShippedOn      = c.ShippedOn,
                TotalWeight    = c.TotalWeight,
                Items          = c.Items.Select(x => new ShipmentQueryItemResult()
                {
                    Id              = x.Id,
                    CreatedOn       = x.CreatedOn,
                    UpdatedOn       = x.UpdatedOn,
                    Quantity        = x.Quantity,
                    OrderItemId     = x.OrderItemId,
                    ProductId       = x.ProductId,
                    ShipmentId      = x.ShipmentId,
                    OrderedQuantity = x.OrderItem.Quantity,
                    ProductMediaUrl = x.OrderItem.ProductMediaUrl,
                    ProductName     = x.OrderItem.ProductName,
                    ShippedQuantity = x.OrderItem.ShippedQuantity,
                }).ToList()
            })
                           .FirstOrDefaultAsync(x => x.Id == id);

            var currentUser = await _workContext.GetCurrentUserAsync();

            return(Result.Ok(shipment));
        }
示例#9
0
        public async Task <IList <UserAddressShippingResult> > GetList(int?userAddressId = null)
        {
            var user = await _workContext.GetCurrentUserAsync();

            var countryId = (int)CountryWithId.China;
            var provinces = await _countryService.GetProvinceByCache(countryId);

            if (provinces == null || provinces.Count <= 0)
            {
                throw new Exception("省市区数据异常,请联系管理员");
            }

            var query = _userAddressRepository
                        .Query()
                        .Include(c => c.Address).ThenInclude(c => c.Country)
                        .Where(x => x.AddressType == AddressType.Shipping && x.UserId == user.Id);

            if (userAddressId.HasValue && userAddressId.Value > 0)
            {
                query = query.Where(c => c.Id == userAddressId.Value);
            }

            var list = await query.Select(x => new UserAddressShippingResult
            {
                UserAddressId     = x.Id,
                AddressId         = x.AddressId,
                ContactName       = x.Address.ContactName,
                Phone             = x.Address.Phone,
                AddressLine1      = x.Address.AddressLine1,
                ZipCode           = x.Address.ZipCode,
                CountryId         = x.Address.CountryId,
                CountryName       = x.Address.Country.Name,
                StateOrProvinceId = x.Address.StateOrProvinceId,
                UpdatedOn         = x.Address.UpdatedOn
            }).ToListAsync();

            foreach (var item in list)
            {
                item.IsDefault = item.UserAddressId == user.DefaultShippingAddressId;

                var first = provinces.FirstOrDefault(c => c.Id == item.StateOrProvinceId);
                if (first != null)
                {
                    StateOrProvinceDto pro = null, city = null, district = null;
                    if (first.Level == StateOrProvinceLevel.Default)
                    {
                        pro = first;
                    }
                    else if (first.Level == StateOrProvinceLevel.City)
                    {
                        city = first;
                        pro  = provinces.FirstOrDefault(c => c.Id == city?.ParentId);
                    }
                    else if (first.Level == StateOrProvinceLevel.District)
                    {
                        district = first;
                        city     = provinces.FirstOrDefault(c => c.Id == district?.ParentId);
                        pro      = provinces.FirstOrDefault(c => c.Id == city?.ParentId);
                    }
                    item.StateOrProvinceId   = pro?.Id ?? 0;
                    item.StateOrProvinceName = pro?.Name;
                    item.CityId       = city?.Id ?? 0;
                    item.CityName     = city?.Name;
                    item.DistrictId   = district?.Id;
                    item.DistrictName = district?.Name;
                }
            }
            var result = list.OrderByDescending(c => c.IsDefault).ThenByDescending(c => c.UpdatedOn).ToList();

            return(result);
        }
示例#10
0
        public async Task <Result> Post([FromBody] OrderCreateParam model)
        {
            if (model == null)
            {
                throw new Exception("参数异常");
            }
            if (model.Items == null || model.Items.Count <= 0)
            {
                throw new Exception("请添加商品");
            }
            if (model.Items.Any(c => c.Quantity <= 0))
            {
                throw new Exception("购买商品数量必须>0");
            }

            var user = await _workContext.GetCurrentUserAsync();

            var customer = await _userRepository.FirstOrDefaultAsync(model.CustomerId);

            if (customer == null)
            {
                throw new Exception("客户不存在");
            }

            var order = new Order()
            {
                OrderStatus       = OrderStatus.New,
                CreatedBy         = user,
                UpdatedBy         = user,
                CustomerId        = model.CustomerId,
                AdminNote         = model.AdminNote,
                OrderNote         = model.OrderNote,
                ShippingMethod    = model.ShippingMethod,
                PaymentType       = model.PaymentType,
                ShippingFeeAmount = model.ShippingFeeAmount,
                OrderTotal        = model.OrderTotal,
                DiscountAmount    = model.DiscountAmount,
            };

            OrderAddress orderShipping = null;
            OrderAddress orderBilling  = null;

            if (model.ShippingUserAddressId.HasValue && model.ShippingUserAddressId.Value > 0)
            {
                orderShipping = await this.UserAddressToOrderAddress(model.ShippingUserAddressId.Value, customer.Id, AddressType.Shipping, order);
            }
            if (model.BillingUserAddressId.HasValue && model.BillingUserAddressId.Value > 0)
            {
                orderBilling = await this.UserAddressToOrderAddress(model.BillingUserAddressId.Value, customer.Id, AddressType.Billing, order);
            }

            if (model.ShippingAddress != null && orderShipping == null)
            {
                orderShipping = new OrderAddress()
                {
                    Order             = order,
                    AddressType       = AddressType.Shipping,
                    AddressLine1      = model.ShippingAddress.AddressLine1,
                    AddressLine2      = model.ShippingAddress.AddressLine2,
                    City              = model.ShippingAddress.City,
                    Company           = model.ShippingAddress.Company,
                    ContactName       = model.ShippingAddress.ContactName,
                    CountryId         = model.ShippingAddress.CountryId,
                    Email             = model.ShippingAddress.Email,
                    Phone             = model.ShippingAddress.Phone,
                    StateOrProvinceId = model.ShippingAddress.StateOrProvinceId,
                    ZipCode           = model.ShippingAddress.ZipCode
                };
            }
            if (model.BillingAddress != null && orderBilling == null)
            {
                orderBilling = new OrderAddress()
                {
                    Order             = order,
                    AddressType       = AddressType.Billing,
                    AddressLine1      = model.BillingAddress.AddressLine1,
                    AddressLine2      = model.BillingAddress.AddressLine2,
                    City              = model.BillingAddress.City,
                    Company           = model.BillingAddress.Company,
                    ContactName       = model.BillingAddress.ContactName,
                    CountryId         = model.BillingAddress.CountryId,
                    Email             = model.BillingAddress.Email,
                    Phone             = model.BillingAddress.Phone,
                    StateOrProvinceId = model.BillingAddress.StateOrProvinceId,
                    ZipCode           = model.BillingAddress.ZipCode
                };
            }

            var productIds = model.Items.Select(c => c.Id).Distinct();
            var products   = await _productRepository.Query()
                             .Include(c => c.ThumbnailImage)
                             .Where(c => productIds.Contains(c.Id)).ToListAsync();

            if (productIds.Count() <= 0)
            {
                throw new Exception("商品不存在");
            }

            var stocks = await _stockRepository.Query().Where(c => productIds.Contains(c.ProductId)).ToListAsync();

            var addStockHistories = new List <StockHistory>();

            foreach (var item in products)
            {
                var first = model.Items.FirstOrDefault(c => c.Id == item.Id);
                if (first == null)
                {
                    throw new Exception($"产品[{item.Name}]不存在");
                }

                if (!item.IsPublished)
                {
                    throw new Exception($"产品[{item.Name}]未发布");
                }
                if (!item.IsAllowToOrder)
                {
                    throw new Exception($"产品[{item.Name}]不允许购买");
                }

                OrderStockDoWorker(stocks, addStockHistories, item, user, -first.Quantity, order, "创建订单");

                var orderItem = new OrderItem()
                {
                    Order           = order,
                    Product         = item,
                    ItemWeight      = 0,
                    ItemAmount      = first.Quantity * first.ProductPrice - first.DiscountAmount,
                    Quantity        = first.Quantity,
                    ProductPrice    = first.ProductPrice,
                    DiscountAmount  = first.DiscountAmount,
                    CreatedBy       = user,
                    UpdatedBy       = user,
                    ProductName     = item.Name,
                    ProductMediaUrl = item.ThumbnailImage?.Url
                };
                order.OrderItems.Add(orderItem);
            }

            order.SubTotal             = order.OrderItems.Sum(c => c.Quantity * c.ProductPrice);
            order.SubTotalWithDiscount = order.OrderItems.Sum(c => c.DiscountAmount);
            _orderRepository.Add(order);

            // Unable to save changes because a circular dependency was detected in the data to be saved
            // https://github.com/aspnet/EntityFrameworkCore/issues/11888
            // https://docs.microsoft.com/zh-cn/ef/core/saving/transactions
            // https://stackoverflow.com/questions/40073149/entity-framework-circular-dependency-for-last-entity
            using (var transaction = _orderRepository.BeginTransaction())
            {
                await _orderRepository.SaveChangesAsync();

                order.ShippingAddress = orderShipping;
                order.BillingAddress  = orderBilling;
                await _orderRepository.SaveChangesAsync();

                var orderCreated = new OrderCreated
                {
                    OrderId = order.Id,
                    Order   = order,
                    UserId  = order.CreatedById,
                    Note    = order.OrderNote
                };
                await _mediator.Publish(orderCreated);

                await _stockRepository.SaveChangesAsync();

                if (addStockHistories.Count > 0)
                {
                    _stockHistoryRepository.AddRange(addStockHistories);
                    await _stockHistoryRepository.SaveChangesAsync();
                }
                transaction.Commit();
            }

            //TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }
            //using (var ts = new TransactionScope())
            //{
            //    ts.Complete();
            //}
            return(Result.Ok());
        }
        public async Task Handle(UserSignedIn user, CancellationToken cancellationToken)
        {
            var guestUser = await _workContext.GetCurrentUserAsync();

            await _cartService.MigrateCart(guestUser.Id, user.UserId);
        }
示例#12
0
        public async Task <Result> Get(int id)
        {
            var user = await _workContext.GetCurrentUserAsync();

            var query = _orderRepository.Query()
                        .Include(c => c.OrderItems)
                        .Include(c => c.Customer)
                        .Where(c => c.CustomerId == user.Id && c.Id == id);

            var subQuery = _reviewRepository.Query().Where(c => c.EntityTypeId == (int)EntityTypeWithId.Product && c.SourceId == id && c.SourceType == ReviewSourceType.Order);
            var result   = await query.Select(c => new CustomerOrderQueryResult
            {
                Id = c.Id,
                No = c.No.ToString(),
                BillingAddressId  = c.BillingAddressId,
                CancelOn          = c.CancelOn,
                CancelReason      = c.CancelReason,
                CreatedOn         = c.CreatedOn,
                CustomerId        = c.CustomerId,
                CustomerName      = c.Customer.FullName,
                DiscountAmount    = c.DiscountAmount,
                OrderNote         = c.OrderNote,
                OrderStatus       = c.OrderStatus,
                OrderTotal        = c.OrderTotal,
                PaymentFeeAmount  = c.PaymentFeeAmount,
                PaymentMethod     = c.PaymentMethod,
                PaymentOn         = c.PaymentOn,
                PaymentType       = c.PaymentType,
                ShippingAddressId = c.ShippingAddressId,
                ShippingFeeAmount = c.ShippingFeeAmount,
                ShippingMethod    = c.ShippingMethod,
                ShippingStatus    = c.ShippingStatus,
                UpdatedOn         = c.UpdatedOn,
                Items             = c.OrderItems.Select(x => new CustomerOrderItemQueryResult
                {
                    OrderId         = x.OrderId,
                    DiscountAmount  = x.DiscountAmount,
                    ItemAmount      = x.ItemAmount,
                    ItemWeight      = x.ItemWeight,
                    Note            = x.Note,
                    Id              = x.Id,
                    ProductId       = x.ProductId,
                    ProductMediaUrl = x.ProductMediaUrl,
                    ProductName     = x.ProductName,
                    ProductPrice    = x.ProductPrice,
                    Quantity        = x.Quantity,
                    ShippedQuantity = x.ShippedQuantity,
                    IsReviewed      = subQuery.Any(y => y.EntityId == x.ProductId)
                }),
                ItemsTotal     = c.OrderItems.Sum(x => x.Quantity),
                ItemsCount     = c.OrderItems.Count,
                PaymentEndOn   = c.PaymentEndOn,
                DeliveredEndOn = c.DeliveredEndOn
            }).FirstOrDefaultAsync();

            if (result?.ShippingAddressId != null)
            {
                result.Address = await _orderService.GetOrderAddress(result.ShippingAddressId.Value);
            }
            return(Result.Ok(result));
        }