Example #1
0
 /// <summary>
 /// Raises event 'OrderChanged'
 /// </summary>
 protected virtual void OnOrderChanged()
 {
     if (OrderChanged != null)
     {
         OrderChanged.Invoke(this, System.EventArgs.Empty);
     }
 }
        public void ChangeOrdinal(int oldIndex, int newIndex)
        {
            //var priorIndex = oldIndex;
            //var latterIndex = newIndex;

            //var changedItem = Items[oldIndex];
            //if (newIndex < oldIndex)
            //{
            //    // add one to where we delete, because we're increasing the index by inserting
            //    priorIndex += 1;
            //}
            //else
            //{
            //    // add one to where we insert, because we haven't deleted the original yet
            //    latterIndex += 1;
            //}

            //Items.Insert(latterIndex, changedItem);
            //Items.RemoveAt(priorIndex);

            // using MoveItem is simpler and it automatically updates the UI, Call of OnCollectionChanged not neccessary
            if (oldIndex == newIndex)
            {
                return;
            }
            this.MoveItem(oldIndex, newIndex);

            OrderChanged?.Invoke(this, EventArgs.Empty);

            // this call is not needed if you use MoveItem (see above)
            //OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, changedItem, newIndex, oldIndex));
        }
Example #3
0
        public async Task AddPayment(Payment payment)
        {
            var newPayment = _mapper.Map <Model.Payment>(payment);

            await Task.Run(() =>
            {
                _paymentRepository.AddPayment(newPayment);
                _paymentRepository.Save();

                var order = _orderRepository.GetOrderByOrderId(payment.OrderId);
                order.Payments.Add(newPayment);
                _orderRepository.AddPayment(newPayment);
                _orderRepository.Save();

                OrderChanged orderChanged = new OrderChanged()
                {
                    OrderId   = order.OrderId,
                    StoreName = order.Store.Name,
                    State     = "Paid"
                };

                //notificar publish Order Changed
                _orderChangedService.SendMessagesAsync(orderChanged);
            });
        }
        public void ChangeOrdinal(int oldIndex, int newIndex)
        {
            var priorIndex  = oldIndex;
            var latterIndex = newIndex;

            var changedItem = Items[oldIndex];

            if (newIndex < oldIndex)
            {
                // add one to where we delete, because we're increasing the index by inserting
                priorIndex += 1;
            }
            else
            {
                // add one to where we insert, because we haven't deleted the original yet
                latterIndex += 1;
            }

            Items.Insert(latterIndex, changedItem);
            Items.RemoveAt(priorIndex);

            OrderChanged?.Invoke(this, EventArgs.Empty);

            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, changedItem, newIndex, oldIndex));
        }
        private async Task CancelFailedPaymentOrders(CancellationToken stoppingToken)
        {
            var durationToCancel    = DateTimeOffset.Now.AddMinutes(-5);
            var failedPaymentOrders = _orderRepository.Query().Where(x =>
                                                                     (x.OrderStatus == OrderStatus.PendingPayment || x.OrderStatus == OrderStatus.PaymentFailed) &&
                                                                     x.UpdatedOn < durationToCancel);

            foreach (var order in failedPaymentOrders)
            {
                _orderService.CancelOrder(order);
                var orderStatusChanged = new OrderChanged
                {
                    OrderId   = order.Id,
                    OldStatus = OrderStatus.PendingPayment,
                    NewStatus = OrderStatus.Canceled,
                    UserId    = SystemUserId,
                    Order     = order,
                    Note      = "System canceled"
                };

                await _mediator.Publish(orderStatusChanged, stoppingToken);
            }

            await _orderRepository.SaveChangesAsync();
        }
Example #6
0
        private void OnCountChanged(object sender, DecimalValueChangedEventArgs e)
        {
            DecimalValueChangedEventArgs args =
                new DecimalValueChangedEventArgs(e.Id, e.OldValue, e.NewValue, MenuItemName.Orders);

            CountChanged?.Invoke(this, args);
            OrderChanged?.Invoke(sender, e);
        }
Example #7
0
 private void EventsInit()
 {
     OrderDishez.CollectionChanged   += ((sender, e) => { Order.DishPackages = OrderDishez.ToList(); OrderChanged?.Invoke(); }); //OrderDishez_CollectionChanged;
     OrderDishez.ItemPropertyChanged += ((sender, e) => { OrderChanged?.Invoke(); });
     Order.PropertyChanged           += ((sender, e) =>
     {
         OrderChanged?.Invoke();
     });
 }
Example #8
0
 internal void OnUpdateOrder(string portfolio, string securityId, SmartOrderState state, SmartOrderAction action, SmartOrderType type,
                             SmartOrderValidity validity, double price, double volume, double stop, double balance, DateTime time, string smartOrderId,
                             string orderIdStr, int status, int transactionId)
 {
     // http://www.itinvest.ru/forum/index.php?showtopic=63063&st=0&p=242023&#entry242023
     OrderChanged.SafeInvoke(portfolio, securityId, state,
                             action, type, validity == SmartOrderValidity.Day, price.ToDecimal(), (int)volume,
                             stop.ToDecimal(), (int)balance, time, smartOrderId, orderIdStr.To <long>(), status, transactionId);
 }
Example #9
0
        /// <summary>
        ///     Sortear aleatoriamente a ordem dos participantes.
        /// </summary>
        public void Sort()
        {
            var index = 0;

            _positions = _positions
                         .OrderBy(a => Guid.NewGuid())
                         .ToDictionary(a => a.Key, a => index++);
            this.MakeChildrenOrganized(control => _positions[control]);
            OrderChanged?.Invoke();
        }
Example #10
0
        public async Task ChangeOrder(OrderChanged orderChanged)
        {
            var order = _mapper.Map <Model.Order>(orderChanged);

            await Task.Run(() =>
            {
                _orderRepository.Update(order);
                _orderRepository.Save();
            });
        }
Example #11
0
 void NotifyOrderChanged()
 {
     try
     {
         OrderChanged?.Invoke(this, new BfxChildOrderEventArgs(this));
     }
     catch (Exception ex)
     {
         Debug.WriteLine($"Exception occuted in user handler. {ex.Message}");
     }
 }
        public override void ChangeOrder(int oldFlatIndex, int newFlatIndex)
        {
            if (newFlatIndex == 0)
            {
                return;
            }

            var moveDirection   = oldFlatIndex < newFlatIndex ? MoveDirection.Down : MoveDirection.Up;
            var priorFlatIndex  = oldFlatIndex;
            var latterFlatIndex = newFlatIndex;

            var oldGroup = GetGroupFromFlatIndex(priorFlatIndex, moveDirection);
            var newGroup = GetGroupFromFlatIndex(latterFlatIndex, moveDirection);

            var changedItem = GetItemFromFlatIndex(priorFlatIndex);

            if (moveDirection == MoveDirection.Up)
            {
                // add one to where we delete, because we're increasing the index by inserting
                if (oldGroup.Equals(newGroup))
                {
                    priorFlatIndex += 1;
                }
            }
            else
            {
                // add one to where we insert, because we haven't deleted the original yet
                latterFlatIndex += 1;
            }

            var priorNestedIndex  = GetNestedItemIndexFromFlatIndex(priorFlatIndex);
            var latterNestedIndex = GetNestedItemIndexFromFlatIndex(latterFlatIndex);


            newGroup.Insert(latterNestedIndex, changedItem);
            ((IList)oldGroup).RemoveAt(priorNestedIndex);

            //if (AutoOrdinals) {
            //	oldGroup.ResetOrdinals(OrdinalType.Nested);

            //	if (newGroup != oldGroup) {
            //		newGroup.ResetOrdinals(OrdinalType.Nested);
            //	}
            //}

            OrderChanged?.Invoke(
                this,
                new GroupedOrderableCollectionChangedEventArgs(changedItem,
                                                               oldGroup,
                                                               newGroup,
                                                               priorNestedIndex,
                                                               latterNestedIndex)
                );
        }
Example #13
0
        private void RaiseOrderChanged(Order order)
        {
            OrderChanged.SafeInvoke(order);

            var multiEvt = OrdersChanged;

            if (multiEvt == null)
            {
                return;
            }

            multiEvt.SafeInvoke(new[] { order });
        }
        public void ChangeOrdinal(int oldIndex, int newIndex)
        {
            if (oldIndex == newIndex)
            {
                return;
            }

            var priorIndex  = oldIndex;
            var latterIndex = newIndex;

            var changedItem = Items[oldIndex];

            if (newIndex < oldIndex)
            {
                // add one to where we delete, because we're increasing the index by inserting
                priorIndex += 1;
            }
            else
            {
                // add one to where we insert, because we haven't deleted the original yet
                latterIndex += 1;
            }

            Items.Insert(latterIndex, changedItem);
            Items.RemoveAt(priorIndex);

            OrderChanged?.Invoke(this, EventArgs.Empty);

            OnCollectionChanged(
                new NotifyCollectionChangedEventArgs(
                    NotifyCollectionChangedAction.Move,
                    changedItem,
                    newIndex,
                    oldIndex));

            if (Items is IEnumerable <Alarm> alarms)
            {
                if (alarms != null)
                {
                    int i = 0;
                    foreach (var alarm in alarms)
                    {
                        alarm.Index = i++;
                    }
                }

                App.AlarmService.SaveAlarmsAtLocal(alarms);
            }
        }
Example #15
0
        public async Task <Result> OnHold(int id, [FromBody] OrderOnHoldParam param)
        {
            var currentUser = await _workContext.GetCurrentUserAsync();

            var order = await _orderRepository
                        .Query()
                        .Where(c => c.Id == id).FirstOrDefaultAsync();

            if (order == null)
            {
                return(Result.Fail("订单不存在"));
            }

            if (order.OrderStatus == OrderStatus.OnHold)
            {
                return(Result.Fail("订单已挂起"));
            }

            var orderNotSs = new OrderStatus[] { OrderStatus.Canceled, OrderStatus.Complete };

            if (orderNotSs.Contains(order.OrderStatus))
            {
                return(Result.Fail("当前订单状态不允许挂起"));
            }

            var oldStatus = order.OrderStatus;

            order.OrderStatus  = OrderStatus.OnHold;
            order.OnHoldReason = param?.Reason;
            order.UpdatedOn    = DateTime.Now;
            order.UpdatedBy    = currentUser;
            await _orderRepository.SaveChangesAsync();

            var orderStatusChanged = new OrderChanged
            {
                OrderId   = order.Id,
                OldStatus = oldStatus,
                NewStatus = order.OrderStatus,
                Order     = order,
                UserId    = currentUser.Id,
                Note      = "挂起订单"
            };
            await _mediator.Publish(orderStatusChanged);

            return(Result.Ok());
        }
        private async Task ChangeOrderUpCommandExecutionAsync(object parameter)
        {
            var changeOrderUpCommand       = new ChangeActivityRecordOrder(ActivityRecord.Id, ActivityRecord.Order + 1);
            var changeOrderUpCommandResult = await _dispatcher.DispatchCommandAndGetResultAsync(changeOrderUpCommand);

            if (changeOrderUpCommandResult.Successful == false)
            {
                // TODO
                return;
            }

            ActivityRecord = ActivityRecord with {
                Order = ActivityRecord.Order + 1
            };
            RaisePropertyChanged(nameof(ActivityRecord));
            RaisePropertyChanged(nameof(Order));

            await OrderChanged?.Invoke();
        }
Example #17
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            string strcmd = @"  UPDATE [Order]
                                SET ReceiverName = @ReceiverName
                                WHERE OrderID = @orderID 

                                UPDATE [Order]
                                SET ReceiverMobile = @ReceiverMobile 
                                WHERE OrderID = @orderID

                                UPDATE [Order]
                                SET ReceiverTel =@ReceiverTel 
                                WHERE OrderID = @orderID

                                UPDATE [Order]
                                SET ReceiptAddress =  @ReceiptAddress
                                WHERE OrderID = @orderID";
            List <SqlParameter> sqlParameters = new List <SqlParameter>();

            sqlParameters.Add(SqlHelper.CreateParameter("@orderID", SqlDbType.VarChar, 14, orderID));
            sqlParameters.Add(SqlHelper.CreateParameter("@ReceiverName", SqlDbType.NVarChar, 30, this.tbxName.Text));
            sqlParameters.Add(SqlHelper.CreateParameter("@ReceiverMobile", SqlDbType.VarChar, 30, this.tbxPhone.Text));
            sqlParameters.Add(SqlHelper.CreateParameter("@ReceiverTel", SqlDbType.VarChar, 30, this.tbxTel.Text));
            sqlParameters.Add(SqlHelper.CreateParameter("@ReceiptAddress", SqlDbType.NVarChar, 256, this.tbxAddress.Text));
            SqlHelper.ExecuteNonQuery(strcmd, sqlParameters);

            OrderChangedDao ocDao = new OrderChangedDao();
            OrderChanged    oc    = new OrderChanged();

            oc.OrderID = orderID;
            oc.OrderChangedCategoryCode = "P";
            oc.RequestDate   = DateTime.Now;
            oc.RequesterRole = "P";
            oc.RequesterID   = Common.ContainerForm.BuyerLoginAccount.EmployeeID;
            ocDao.UpdateOrderChanged(oc);

            OrderForm frm = new OrderForm();

            Common.ContainerForm.NextForm(frm);
        }
Example #18
0
        public void ChangeOrdinal(int oldIndex, int newIndex)
        {
            T changed = Items[oldIndex];

            if (newIndex < oldIndex)
            {
                // add one to where we delete because we're increasing
                // the index by inserting
                oldIndex += 1;
            }
            else
            {
                // add one to where we insert, because we haven't deleted
                // the original
                newIndex += 1;
            }

            Items.Insert(newIndex, changed);
            Items.RemoveAt(oldIndex);

            OrderChanged?.Invoke(this, EventArgs.Empty);
        }
Example #19
0
            protected override void OnDragDrop(DragEventArgs drgevent)
            {
                CustomButtonIB btn = (CustomButtonIB)drgevent.Data.GetData(typeof(CustomButtonIB));
                MyFlowPanel    dst = this;
                MyFlowPanel    src = btn?.Parent as MyFlowPanel;

                if (btn != null && src != null && dst != null && src == dst)
                {
                    drgevent.Effect = DragDropEffects.Move;

                    int oldindex = dst.Controls.GetChildIndex(btn);
                    OrderChanged?.Invoke(oldindex, dragInsertIndex);
                    dragInsertIndex = -1;
                }
                else
                {
                    drgevent.Effect = DragDropEffects.None;
                    dragInsertIndex = -1;
                }

                base.OnDragDrop(drgevent);
            }
Example #20
0
        public async Task SendMessagesAsync(OrderChanged orderChanged)
        {
            try
            {
                var config = Configuration
                             .GetSection("serviceBus")
                             .Get <ServiceBusConfiguration>();

                var json    = JsonSerializer.Serialize(orderChanged);
                var message = new Message(Encoding.UTF8.GetBytes(json));

                var topicClient = new TopicClient(config.ConnectionString, config.TopicName);
                await topicClient.SendAsync(message);

                var   closeTask = topicClient.CloseAsync();
                await closeTask;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #21
0
        public async Task <IActionResult> ChangeStatus(long id, [FromBody] OrderStatusForm model)
        {
            var order = _orderRepository.Query().FirstOrDefault(x => x.Id == id);

            if (order == null)
            {
                return(NotFound());
            }

            var currentUser = await _workContext.GetCurrentUser();

            if (!User.IsInRole("admin") && order.VendorId != currentUser.VendorId)
            {
                return(BadRequest(new { error = "You don't have permission to manage this order" }));
            }

            if (Enum.IsDefined(typeof(OrderStatus), model.StatusId))
            {
                var oldStatus = order.OrderStatus;
                order.OrderStatus = (OrderStatus)model.StatusId;
                await _orderRepository.SaveChangesAsync();

                var orderStatusChanged = new OrderChanged
                {
                    OrderId   = order.Id,
                    OldStatus = oldStatus,
                    NewStatus = order.OrderStatus,
                    Order     = order,
                    UserId    = currentUser.Id,
                    Note      = model.Note
                };

                await _mediator.Publish(orderStatusChanged);

                return(Accepted());
            }

            return(BadRequest(new { Error = "unsupported order status" }));
        }
Example #22
0
        private async Task CancelFailedPaymentOrders(CancellationToken stoppingToken)
        {
            var shouldCancelFailedPaymentOrders = _orderRepository.Query().Where(x => x.OrderStatus == OrderStatus.PendingPayment && x.UpdatedOn < DateTimeOffset.Now.AddMinutes(-5));

            foreach (var order in shouldCancelFailedPaymentOrders)
            {
                order.OrderStatus = OrderStatus.Canceled;
                order.UpdatedOn   = DateTimeOffset.Now;
                // TODO Rollback product stock
                var orderStatusChanged = new OrderChanged
                {
                    OrderId   = order.Id,
                    OldStatus = OrderStatus.PendingPayment,
                    NewStatus = OrderStatus.Canceled,
                    UserId    = SystemUserId,
                    Order     = order,
                    Note      = "System cancel"
                };

                await _mediator.Publish(orderStatusChanged, stoppingToken);
            }

            await _orderRepository.SaveChangesAsync();
        }
Example #23
0
            protected override void OnDragDrop(DragEventArgs drgevent)
            {
                CustomButtonIB btn = (CustomButtonIB)drgevent.Data.GetData(typeof(CustomButtonIB));
                MyFlowPanel    dst = this;
                MyFlowPanel    src = btn?.Parent as MyFlowPanel;

                if (btn != null && src != null && dst != null && src == dst)
                {
                    drgevent.Effect = DragDropEffects.Move;

                    Point   p        = dst.PointToClient(new Point(drgevent.X, drgevent.Y));
                    Control item     = dst.GetChildAtPoint(p);
                    int     oldindex = dst.Controls.GetChildIndex(btn);
                    int     newindex = dst.Controls.GetChildIndex(item, false);

                    OrderChanged?.Invoke(oldindex, newindex);
                }
                else
                {
                    drgevent.Effect = DragDropEffects.None;
                }

                base.OnDragDrop(drgevent);
            }
Example #24
0
 private void OnDeletedItem(object sender, EventArgs e)
 {
     SelectEntities();
     OrderChanged?.Invoke(sender, e);
 }
 internal virtual void OnOrderChanged(OrderChangedEventArgs e)
 {
     OrderChanged?.Invoke(this, e);
 }
Example #26
0
 /// <summary>
 /// Fires the OnOrderChanged event.
 /// </summary>
 protected virtual void OnOrderChanged()
 {
     OrderChanged?.Invoke(this, EventArgs.Empty);
     OnListChanged();
 }
Example #27
0
 private void OrderChangedHandler(Order order)
 {
     AddGuiAction(() => OrderChanged.SafeInvoke(order));
 }
Example #28
0
 private void RaiseOrderChanged(Order order)
 {
     OrderChanged?.Invoke(order);
     OrdersChanged?.Invoke(new[] { order });
 }
Example #29
0
        public async Task Cancel(int id, int userId, string reason)
        {
            //var currentUser = await _workContext.GetCurrentUser();
            var order = await _orderRepository.Query()
                        .Include(c => c.OrderItems).ThenInclude(c => c.Product)
                        .Where(c => c.Id == id).FirstOrDefaultAsync();

            if (order == null || order.OrderStatus == OrderStatus.Canceled)
            {
                return;
            }
            var orderSs = new OrderStatus[] { OrderStatus.New, OrderStatus.PendingPayment, OrderStatus.PaymentFailed };

            if (!orderSs.Contains(order.OrderStatus))
            {
                return;
            }

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

            var addStockHistories = new List <StockHistory>();

            //取消订单增加库存
            foreach (var item in order.OrderItems)
            {
                OrderStockDoWorker(stocks, addStockHistories, item.Product, userId, item.Quantity, order, "取消订单");
            }
            var oldStatus = order.OrderStatus;

            order.OrderStatus  = OrderStatus.Canceled;
            order.CancelReason = reason;
            order.UpdatedOn    = DateTime.Now;
            order.UpdatedById  = userId;

            using (var transaction = _orderRepository.BeginTransaction())
            {
                await _orderRepository.SaveChangesAsync();

                var orderStatusChanged = new OrderChanged
                {
                    OrderId   = order.Id,
                    OldStatus = oldStatus,
                    NewStatus = order.OrderStatus,
                    Order     = order,
                    UserId    = userId,
                    Note      = "取消订单"
                };
                await _mediator.Publish(orderStatusChanged);

                await _stockRepository.SaveChangesAsync();

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

            //var orderItems = _orderItemRepository.Query().Include(x => x.Product).Where(x => x.Order.Id == order.Id);
            //foreach (var item in orderItems)
            //{
            //    //if (item.Product.StockTrackingIsEnabled)
            //    //{
            //    //    item.Product.StockQuantity = item.Product.StockQuantity + item.Quantity;
            //    //}
            //    // 库存处理
            //}
        }
Example #30
0
        public async Task <Result> Put(int id, [FromBody] OrderEditParam 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 currentUser = await _workContext.GetCurrentUserAsync();

            var order = await _orderRepository
                        .Query()
                        .Include(c => c.Customer)
                        .Include(c => c.BillingAddress)
                        .Include(c => c.ShippingAddress)
                        .Include(c => c.OrderItems)
                        .Where(c => c.Id == id).FirstOrDefaultAsync();

            if (order == null)
            {
                throw new Exception("订单不存在");
            }

            var user = await _workContext.GetCurrentUserAsync();

            var oldStatus = order.OrderStatus;

            order.ShippingAddressId = model.ShippingAddressId;
            order.BillingAddressId  = model.BillingAddressId;

            if (model.ShippingAddress != null)
            {
                if (order.ShippingAddress == null)
                {
                    order.ShippingAddress = 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
                    };
                }
                else
                {
                    order.ShippingAddress.AddressType       = AddressType.Shipping;
                    order.ShippingAddress.AddressLine1      = model.ShippingAddress.AddressLine1;
                    order.ShippingAddress.AddressLine2      = model.ShippingAddress.AddressLine2;
                    order.ShippingAddress.City              = model.ShippingAddress.City;
                    order.ShippingAddress.Company           = model.ShippingAddress.Company;
                    order.ShippingAddress.ContactName       = model.ShippingAddress.ContactName;
                    order.ShippingAddress.CountryId         = model.ShippingAddress.CountryId;
                    order.ShippingAddress.Email             = model.ShippingAddress.Email;
                    order.ShippingAddress.Phone             = model.ShippingAddress.Phone;
                    order.ShippingAddress.StateOrProvinceId = model.ShippingAddress.StateOrProvinceId;
                    order.ShippingAddress.ZipCode           = model.ShippingAddress.ZipCode;
                }
            }

            if (model.BillingAddress != null)
            {
                if (order.BillingAddress == null)
                {
                    order.BillingAddress = new OrderAddress()
                    {
                        Order             = order,
                        AddressType       = AddressType.Shipping,
                        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
                    };
                }
                else
                {
                    order.BillingAddress.AddressType       = AddressType.Shipping;
                    order.BillingAddress.AddressLine1      = model.BillingAddress.AddressLine1;
                    order.BillingAddress.AddressLine2      = model.BillingAddress.AddressLine2;
                    order.BillingAddress.City              = model.BillingAddress.City;
                    order.BillingAddress.Company           = model.BillingAddress.Company;
                    order.BillingAddress.ContactName       = model.BillingAddress.ContactName;
                    order.BillingAddress.CountryId         = model.BillingAddress.CountryId;
                    order.BillingAddress.Email             = model.BillingAddress.Email;
                    order.BillingAddress.Phone             = model.BillingAddress.Phone;
                    order.BillingAddress.StateOrProvinceId = model.BillingAddress.StateOrProvinceId;
                    order.BillingAddress.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}]不允许购买");
                }

                var productStocks = stocks.Where(c => c.ProductId == item.Id);

                if (order.OrderItems.Any(c => c.ProductId == item.Id))
                {
                    var orderItem = order.OrderItems.First(c => c.ProductId == item.Id);

                    OrderStockDoWorker(stocks, addStockHistories, item, user, orderItem.Quantity - first.Quantity, order, "修改下单商品数量");

                    orderItem.ItemWeight      = 0;
                    orderItem.ItemAmount      = first.Quantity * first.ProductPrice - first.DiscountAmount;
                    orderItem.Quantity        = first.Quantity;
                    orderItem.ProductPrice    = first.ProductPrice;
                    orderItem.DiscountAmount  = first.DiscountAmount;
                    orderItem.UpdatedBy       = user;
                    orderItem.ProductName     = item.Name;
                    orderItem.ProductMediaUrl = item.ThumbnailImage?.Url;
                    orderItem.UpdatedOn       = DateTime.Now;
                }
                else
                {
                    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);
                }
            }
            var deletedProductItems = order.OrderItems.Where(c => !productIds.Contains(c.ProductId));

            foreach (var item in deletedProductItems)
            {
                item.IsDeleted = true;
                item.UpdatedOn = DateTime.Now;
            }

            order.OrderStatus       = model.OrderStatus;
            order.DiscountAmount    = model.DiscountAmount;
            order.OrderTotal        = model.OrderTotal;
            order.OrderNote         = model.OrderNote;
            order.AdminNote         = model.AdminNote;
            order.PaymentType       = model.PaymentType;
            order.ShippingFeeAmount = model.ShippingFeeAmount;
            order.ShippingMethod    = model.ShippingMethod;
            order.ShippingStatus    = model.ShippingStatus;
            order.PaymentMethod     = model.PaymentMethod;
            order.PaymentFeeAmount  = model.PaymentFeeAmount;
            order.PaymentOn         = model.PaymentOn;
            order.ShippedOn         = model.ShippedOn;
            order.DeliveredOn       = model.DeliveredOn;
            order.CancelOn          = model.CancelOn;
            order.CancelReason      = model.CancelReason;
            order.RefundAmount      = model.RefundAmount;
            order.RefundOn          = model.RefundOn;
            order.RefundReason      = model.RefundReason;
            order.RefundStatus      = model.RefundStatus;

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

            using (var transaction = _orderRepository.BeginTransaction())
            {
                await _orderRepository.SaveChangesAsync();

                var orderStatusChanged = new OrderChanged
                {
                    OrderId   = order.Id,
                    OldStatus = oldStatus,
                    NewStatus = order.OrderStatus,
                    Order     = order,
                    UserId    = currentUser.Id,
                    Note      = model.AdminNote
                };
                await _mediator.Publish(orderStatusChanged);

                await _stockRepository.SaveChangesAsync();

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