public static void SetReviewedStatus(IUnitOfWork db,
                                             long emailId,
                                             bool newReviewedStatus,
                                             IOrderHistoryService orderHistorySerivce,
                                             string orderNumber,
                                             DateTime when,
                                             long?by)
        {
            var email = db.Emails.Get(emailId);

            var fromReviwedStatus = email.IsReviewed;

            email.IsReviewed = newReviewedStatus;
            db.Commit();

            DTOOrder order = null;

            if (!String.IsNullOrEmpty(orderNumber))
            {
                order = db.Orders.GetByOrderIdAsDto(orderNumber);
            }

            orderHistorySerivce.AddRecord(order?.Id ?? 0,
                                          OrderHistoryHelper.EmailReviewedStatusChangedKey,
                                          fromReviwedStatus,
                                          email.Id.ToString(),
                                          email.IsReviewed,
                                          null,
                                          by);
        }
        public void UpdateOrderAddressValidationStatus(IUnitOfWork db,
                                                       long orderId,
                                                       long?by)
        {
            var dbOrder = db.Orders.GetById(orderId);

            AddressDTO correctedAddress = null;
            var        sourceAddress    = db.Orders.GetAddressInfo(orderId);// dbOrder.GetAddressDto();
            var        checkResults     = CheckAddress(CallSource.Service,
                                                       db,
                                                       sourceAddress,
                                                       orderId,
                                                       out correctedAddress);

            var checkStatus  = (int)Core.Models.AddressValidationStatus.None;
            var stampsStatus = checkResults.FirstOrDefault(r => r.AdditionalData != null &&
                                                           r.AdditionalData.Any() &&
                                                           r.AdditionalData[0] == OrderNotifyType.AddressCheckStamps.ToString());

            if (stampsStatus != null) //Get main checker status (by default: stamps.com)
            {
                checkStatus = stampsStatus.Status;
            }

            if (dbOrder.AddressValidationStatus != checkStatus) //NOTE: If changed then reset dismiss status
            {
                _orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.DismissAddressWarnKey, dbOrder.IsDismissAddressValidation, false, by);

                dbOrder.AddressValidationStatus      = checkStatus;
                dbOrder.IsDismissAddressValidation   = false;
                dbOrder.DismissAddressValidationBy   = null;
                dbOrder.DismissAddressValidationDate = null;
            }
            db.Commit();
        }
        public bool UpdateOrder(IUnitOfWork db, ShippingDTO shipping)
        {
            _log.Info("Update order: id=" + shipping.OrderId + ", orderId=" + shipping.AmazonIdentifier + ", marketId=" + shipping.MarketOrderId);

            var dbOrder = db.Orders.Get(shipping.OrderId);

            if (dbOrder.OrderStatus == OrderStatusEnumEx.Unshipped)
            {
                _log.Info("Order status changed: " + dbOrder.OrderStatus + " => " + OrderStatusEnumEx.Shipped);
                _orderHistory.AddRecord(dbOrder.Id, OrderHistoryHelper.StatusChangedKey, dbOrder.OrderStatus, OrderStatusEnumEx.Shipped, null);

                dbOrder.OrderStatus = OrderStatusEnumEx.Shipped;
            }
            db.Commit();

            return(true);
        }
        public void ProcessResult(CheckResult result, Order dbOrder)
        {
            if (result.IsSuccess)
            {
                _log.Info("Insure enabled");

                _orderHistory.AddRecord(dbOrder.Id, OrderHistoryHelper.IsInsuredKey, dbOrder.IsInsured, true, null);

                dbOrder.IsInsured    = true;
                dbOrder.InsuredValue = dbOrder.TotalPrice;
            }
        }
        public static void SetRefundLocked(IUnitOfWork db,
                                           IOrderHistoryService orderHistorySerivce,
                                           long id,
                                           bool onRefundLockedStatus,
                                           DateTime when,
                                           long?by)
        {
            var order = db.Orders.GetById(id);

            orderHistorySerivce.AddRecord(id, OrderHistoryHelper.OnRefundLockedKey, order.IsRefundLocked, onRefundLockedStatus, by);

            order.IsRefundLocked = onRefundLockedStatus;
            //order.IsRefundLockedDate = when;
            db.Commit();
        }
        public static void SetOnHold(IUnitOfWork db,
                                     IOrderHistoryService orderHistorySerivce,
                                     long id,
                                     bool onHoldStatus,
                                     DateTime when,
                                     long?by)
        {
            var order = db.Orders.GetById(id);

            orderHistorySerivce.AddRecord(id, OrderHistoryHelper.OnHoldKey, order.OnHold, onHoldStatus, by);

            order.OnHold           = onHoldStatus;
            order.OnHoldUpdateDate = when;
            db.Commit();
        }
        public List <MessageString> ProcessApplyResult(ApplyOrderResult applyResult,
                                                       IUnitOfWork db,
                                                       ILogService log,
                                                       ITime time,
                                                       IOrderSynchronizer synchronizer,
                                                       AddressChecker addressChecker,
                                                       IOrderHistoryService orderHistoryService,
                                                       IWeightService weightService,
                                                       long?by)
        {
            var results = new List <MessageString>();

            if (applyResult.RateRecalcRequested)
            {
                var dtoOrder = db.ItemOrderMappings.GetOrderWithItems(weightService, OrderId, unmaskReferenceStyle: false, includeSourceItems: true);

                try
                {
                    RetryHelper.ActionWithRetries(() => synchronizer.UIUpdate(db,
                                                                              dtoOrder,
                                                                              isForceOverride: false,
                                                                              keepActiveShipping: true,
                                                                              keepCustomShipping: applyResult.ShipmentProviderChanged ? false : true,
                                                                              switchToMethodId: null),
                                                  log,
                                                  2,
                                                  300,
                                                  RetryModeType.Normal,
                                                  true);

                    orderHistoryService.AddRecord(dtoOrder.Id, OrderHistoryHelper.RecalculateRatesKey, null, true, by);
                }
                catch (Exception ex)
                {
                    results.Add(MessageString.Error("", "An unexpected error has occurred. Please try again. Detail: " + ex.Message));
                }
            }

            if (applyResult.AddressValidationRequested)
            {
                addressChecker.UpdateOrderAddressValidationStatus(db, EntityId, null);
            }

            return(results);
        }
        public static void CancelOrder(IUnitOfWork db,
                                       ILogService log,
                                       ITime time,
                                       ISystemActionService actionService,
                                       IOrderHistoryService orderHistoryService,
                                       long orderId,
                                       long?by)
        {
            var dbOrder = db.Orders.Get(orderId);

            if (dbOrder != null)
            {
                var orderItems = db.OrderItemSources.GetWithListingInfo().Where(oi => oi.OrderId == orderId).ToList();
                var itemIdList = orderItems.Where(oi => !String.IsNullOrEmpty(oi.SourceMarketId))
                                 .Select(oi => oi.SourceMarketId)
                                 .ToList();

                log.Info("Items to cancel: " + String.Join(";", itemIdList));

                db.OrderNotifies.Add(new OrderNotify()
                {
                    OrderId    = dbOrder.Id,
                    Type       = (int)OrderNotifyType.CancellationRequest,
                    Status     = 1,
                    Message    = "Email cancelation from web page",
                    CreateDate = time.GetAppNowTime(),
                });
                db.Commit();

                orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.CancellationRequestKey, null, true, by);

                SystemActionHelper.AddCancelationActionSequences(db,
                                                                 actionService,
                                                                 dbOrder.Id,
                                                                 dbOrder.AmazonIdentifier,
                                                                 String.Join(";", itemIdList),
                                                                 null,
                                                                 null,
                                                                 null,
                                                                 null,
                                                                 by,
                                                                 CancelReasonType.Manually);
            }
        }
        public static MessageResult RemoveFromBatch(IUnitOfWork db,
                                                    ILogService log,
                                                    ISystemActionService systemAction,
                                                    IOrderHistoryService orderHistoryService,
                                                    IBatchManager batchManager,
                                                    long batchId,
                                                    long orderId,
                                                    long?by)
        {
            var batch = db.OrderBatches.GetAsDto(batchId);
            var order = db.Orders.GetAll().FirstOrDefault(o => o.Id == orderId);

            if (batch.IsClosed && !batchManager.CanBeRemovedFromBatch(order))
            {
                if (!AccessManager.IsAdmin)
                {
                    return(MessageResult.Error("Batch was closed"));
                }
            }
            if (batch.IsLocked)
            {
                if (!AccessManager.IsAdmin)
                {
                    return(MessageResult.Error("Batch was locked"));
                }
            }

            if (order != null)
            {
                var previoudBatchId = order.BatchId;

                order.BatchId = null;

                batchManager.CheckRemovedOrder(db, log, systemAction, order, null, by);

                db.Commit();

                orderHistoryService.AddRecord(order.Id, OrderHistoryHelper.AddToBatchKey, previoudBatchId, batch.Name, null, null, by);

                return(MessageResult.Success());
            }
            return(MessageResult.Error("No order"));
        }
        public static ValueResult <long> AddOrdersToBatch(IUnitOfWork db,
                                                          IOrderHistoryService orderHistoryService,
                                                          long?batchId,
                                                          string orderIds,
                                                          DateTime when,
                                                          long?by)
        {
            if (!string.IsNullOrEmpty(orderIds) && batchId.HasValue)
            {
                var batch = db.OrderBatches.GetAsDto(batchId.Value);
                if (batch.IsClosed)
                {
                    if (!AccessManager.IsSuperAdmin)
                    {
                        return(ValueResult <long> .Error("Batch was closed", batchId.Value));
                    }
                }
                if (batch.IsLocked)
                {
                    if (!AccessManager.IsAdmin)
                    {
                        return(ValueResult <long> .Error("Batch was locked", batchId.Value));
                    }
                }

                var stringOrderIdList = orderIds.Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var orderIdList       = stringOrderIdList.Select(long.Parse).ToList();

                db.OrderBatches.AddOrdersToBatch(batchId.Value, orderIdList, when, by);

                foreach (var orderId in orderIdList)
                {
                    orderHistoryService.AddRecord(orderId, OrderHistoryHelper.AddToBatchKey, null, null, batchId, batch.Name, by);
                }

                return(ValueResult <long> .Success("Batch was created", batchId.Value));
            }

            return(ValueResult <long> .Error("Order list is empty"));
        }
Exemple #11
0
        public long CreateBatch(IUnitOfWork db,
                                BatchType batchType,
                                string batchName,
                                IList <long> orderIdList,
                                DateTime when,
                                long?by)
        {
            _log.Info("CreateBatch, batchName=" + batchName + ", type=" + batchType);

            var batchId = db.OrderBatches.CreateBatch(batchName,
                                                      batchType,
                                                      orderIdList,
                                                      when,
                                                      by);

            foreach (var orderId in orderIdList)
            {
                _orderHistoryService.AddRecord(orderId, OrderHistoryHelper.AddToBatchKey, null, null, batchId, batchName, by);
            }

            return(batchId);
        }
        public static MessageResult RemoveMultipleFromBatch(IUnitOfWork db,
                                                            ILogService log,
                                                            ISystemActionService systemAction,
                                                            IOrderHistoryService orderHistoryService,
                                                            IBatchManager batchManager,
                                                            long batchId,
                                                            string orderIds,
                                                            long?toBatchId,
                                                            bool?removeOnHold)
        {
            var           by         = AccessManager.UserId;
            var           wasChanged = false;
            var           hasClosed  = false;
            var           fromBatch  = db.OrderBatches.GetAsDto(batchId);
            OrderBatchDTO toBatch    = null;

            if (toBatchId.HasValue)
            {
                toBatch = db.OrderBatches.GetAsDto(toBatchId.Value);
            }

            if (fromBatch.IsClosed || (toBatch != null && toBatch.IsClosed))
            {
                if (!AccessManager.CanEditSystemInfo() && !AccessManager.IsAdmin)
                {
                    hasClosed = true;
                }
            }
            if (fromBatch.IsLocked || (toBatch != null && toBatch.IsLocked))
            {
                if (!AccessManager.IsAdmin)
                {
                    return(MessageResult.Error("Source or distination batch was locked"));
                }
            }

            var orders = db.Orders.GetFiltered(o => o.BatchId == batchId);

            if (!string.IsNullOrEmpty(orderIds) && !removeOnHold.HasValue)
            {
                var stringOrderIdList = orderIds.Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var orderIdList       = stringOrderIdList.Select(long.Parse).ToList();
                foreach (var orderId in orderIdList)
                {
                    var order = orders.FirstOrDefault(o => o.Id == orderId);
                    if (order != null)
                    {
                        if (!hasClosed || batchManager.CanBeRemovedFromBatch(order) || AccessManager.IsAdmin)
                        {
                            order.BatchId = toBatchId;

                            batchManager.CheckRemovedOrder(db, log, systemAction, order, toBatchId, by);

                            orderHistoryService.AddRecord(order.Id, OrderHistoryHelper.AddToBatchKey, fromBatch.Id, fromBatch.Name, toBatch?.Id, toBatch?.Name, by);

                            wasChanged = true;
                        }
                    }
                }
            }
            else if (removeOnHold.HasValue && removeOnHold.Value)
            {
                var onHoldOrders = orders.Where(o => o.OnHold).ToList();
                foreach (var order in onHoldOrders)
                {
                    if (!hasClosed || batchManager.CanBeRemovedFromBatch(order))
                    {
                        order.BatchId = toBatchId;

                        batchManager.CheckRemovedOrder(db, log, systemAction, order, toBatchId, by);

                        orderHistoryService.AddRecord(order.Id, OrderHistoryHelper.AddToBatchKey, fromBatch.Id, fromBatch.Name, toBatch?.Id, toBatch?.Name, by);

                        wasChanged = true;
                    }
                }
            }

            db.Commit();

            if (!wasChanged && hasClosed)
            {
                return(MessageResult.Error("Source or distination batch was closed"));
            }
            if (!wasChanged)
            {
                return(MessageResult.Error("Order list is empty"));
            }
            return(MessageResult.Success());
        }
Exemple #13
0
        private IList <long> RemoveOrdersWithIssue(IUnitOfWork db,
                                                   long[] orderIds,
                                                   IList <OrderShippingInfoDTO> shippingList,
                                                   PrintLabelResult printLabelResult)
        {
            var removedOrderIds = new List <long>();

            //Remove orders w/o shippings
            var orderIdsWoShippings = orderIds.Where(oId => shippingList.All(sh => sh.OrderId != oId)).ToList();

            if (orderIdsWoShippings.Any())
            {
                foreach (var orderId in orderIdsWoShippings)
                {
                    var dbOrder = db.Orders.GetById(orderId);
                    _batchManager.CheckRemovedOrder(db,
                                                    _log,
                                                    _actionService,
                                                    dbOrder,
                                                    null,
                                                    null);
                    dbOrder.BatchId = null;
                    _orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.AddToBatchKey, dbOrder.BatchId, null, null, null, null);
                    removedOrderIds.Add(dbOrder.Id);
                    _log.Info("W/o shipping order was removed from batch, orderId=" + dbOrder.AmazonIdentifier);
                }
                printLabelResult.Messages.Add(
                    new Message(String.Format("{0} - orders w/o selected shipping was removed from batch",
                                              orderIdsWoShippings.Distinct().Count()), MessageTypes.Error));
            }

            //Remove OnHold orders from batch
            var onHoldShippingList = shippingList.Where(sh => sh.OnHold).ToList();

            if (onHoldShippingList.Any())
            {
                foreach (var shipping in onHoldShippingList)
                {
                    var dbOrder = db.Orders.GetById(shipping.OrderId);
                    _batchManager.CheckRemovedOrder(db,
                                                    _log,
                                                    _actionService,
                                                    dbOrder,
                                                    null,
                                                    null);
                    dbOrder.BatchId = null;
                    _orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.AddToBatchKey, dbOrder.BatchId, null, null, null, null);
                    removedOrderIds.Add(dbOrder.Id);
                    _log.Info("OnHold order was removed from batch, orderId=" + dbOrder.AmazonIdentifier);
                }
                printLabelResult.Messages.Add(new Message(String.Format("{0} on hold orders was removed from batch",
                                                                        onHoldShippingList.Select(sh => sh.OrderId).Distinct().Count()), MessageTypes.Error));
            }

            //Removed with Mail label
            var alreadyMailedBatchOrderIds = db.MailLabelInfos.GetAllAsDto().Where(m => orderIds.Contains(m.Id) &&
                                                                                   !m.LabelCanceled &&
                                                                                   !m.CancelLabelRequested)
                                             .Select(m => m.OrderId).ToList();
            var alreadyMailedShippingList = shippingList.Where(sh => alreadyMailedBatchOrderIds.Contains(sh.OrderId)).ToList();

            if (alreadyMailedShippingList.Any())
            {
                foreach (var shipping in alreadyMailedShippingList)
                {
                    shipping.LabelPrintStatus = (int)LabelPrintStatus.AlreadyMailed;

                    var dbOrder = db.Orders.GetById(shipping.OrderId);
                    _orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.AddToBatchKey, dbOrder.BatchId, null, null, null, null);
                    dbOrder.BatchId = null;
                    removedOrderIds.Add(dbOrder.Id);
                    _log.Info("Already mailed order was removed from batch, orderId=" + dbOrder.AmazonIdentifier);
                }
                printLabelResult.Messages.Add(new Message(String.Format("{0} previously processed and mailed orders was removed from batch",
                                                                        alreadyMailedShippingList.Select(sh => sh.OrderId).Distinct().Count()), MessageTypes.Error));
            }

            db.Commit();

            return(removedOrderIds);
        }
        public ApplyOrderResult Apply(ILogService log,
                                      IUnitOfWork db,
                                      IOrderHistoryService orderHistoryService,
                                      IQuantityManager quantityManager,
                                      DateTime when,
                                      long?by)
        {
            var dbOrder                 = db.Orders.GetById(EntityId);
            var addressChanged          = false;
            var shipmentProviderChanged = false;
            var shouldRecalcRates       = dbOrder.IsInsured != IsInsured ||
                                          dbOrder.IsSignConfirmation != IsSignConfirmation;

            var manuallyAddress = ComposeAddressDto();

            //NOTE: empty when fields was readonly
            if (!AddressHelper.IsEmptyManually(manuallyAddress))
            {
                var originalAddress = dbOrder.GetAddressDto();

                addressChanged    = AddressHelper.CompareWithManuallyAllFields(originalAddress, manuallyAddress);
                shouldRecalcRates = shouldRecalcRates || AddressHelper.CompareWithManuallyBigChanges(originalAddress, manuallyAddress);

                if (addressChanged)
                {
                    orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ManuallyPersonNameKey, dbOrder.IsManuallyUpdated ? dbOrder.ManuallyPersonName : dbOrder.PersonName, ManuallyPersonName, by);
                    dbOrder.ManuallyPersonName = ManuallyPersonName;
                    orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ManuallyShippingAddress1Key, dbOrder.IsManuallyUpdated ? dbOrder.ManuallyShippingAddress1 : dbOrder.ShippingAddress1, ManuallyShippingAddress1, by);
                    dbOrder.ManuallyShippingAddress1 = ManuallyShippingAddress1;
                    orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ManuallyShippingAddress2Key, dbOrder.IsManuallyUpdated ? dbOrder.ManuallyShippingAddress2 : dbOrder.ShippingAddress2, ManuallyShippingAddress2, by);
                    dbOrder.ManuallyShippingAddress2 = ManuallyShippingAddress2;
                    orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ManuallyShippingCityKey, dbOrder.IsManuallyUpdated ? dbOrder.ManuallyShippingCity : dbOrder.ShippingCity, ManuallyShippingCity, by);
                    dbOrder.ManuallyShippingCity = ManuallyShippingCity;
                    orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ManuallyShippingCountryKey, dbOrder.IsManuallyUpdated ? dbOrder.ManuallyShippingCountry : dbOrder.ShippingCountry, ManuallyShippingCountry, by);
                    dbOrder.ManuallyShippingCountry = ManuallyShippingCountry;

                    dbOrder.ManuallyShippingState = !ShippingUtils.IsInternational(dbOrder.ManuallyShippingCountry)
                                                    // == "US"
                        ? ManuallyShippingUSState
                        : ManuallyShippingState;

                    orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ManuallyShippingZipKey, dbOrder.IsManuallyUpdated ? dbOrder.ManuallyShippingZip : dbOrder.ShippingZip, ManuallyShippingZip, by);
                    dbOrder.ManuallyShippingZip = StringHelper.TrimWhitespace(ManuallyShippingZip);
                    orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ManuallyShippingZipAddonKey, dbOrder.IsManuallyUpdated ? dbOrder.ManuallyShippingZipAddon : dbOrder.ShippingZipAddon, ManuallyShippingZipAddon, by);
                    dbOrder.ManuallyShippingZipAddon = StringHelper.TrimWhitespace(ManuallyShippingZipAddon);
                    orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ManuallyShippingPhoneKey, dbOrder.IsManuallyUpdated ? dbOrder.ManuallyShippingPhone : dbOrder.ShippingPhone, ManuallyShippingPhone, by);
                    dbOrder.ManuallyShippingPhone = ManuallyShippingPhone;

                    dbOrder.IsManuallyUpdated = true;
                }
                else
                {
                    dbOrder.ManuallyPersonName       = String.Empty;
                    dbOrder.ManuallyShippingAddress1 = String.Empty;
                    dbOrder.ManuallyShippingAddress2 = String.Empty;
                    dbOrder.ManuallyShippingCity     = String.Empty;
                    dbOrder.ManuallyShippingCountry  = String.Empty;

                    dbOrder.ManuallyShippingState    = String.Empty;
                    dbOrder.ManuallyShippingZip      = String.Empty;
                    dbOrder.ManuallyShippingZipAddon = String.Empty;
                    dbOrder.ManuallyShippingPhone    = String.Empty;

                    dbOrder.IsManuallyUpdated = false;
                }
            }

            dbOrder.InsuredValue = InsuredValue;
            orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.IsInsuredKey, dbOrder.IsInsured, IsInsured, by);
            dbOrder.IsInsured = IsInsured;
            orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.IsSignConfirmationKey, dbOrder.IsSignConfirmation, IsSignConfirmation, by);
            dbOrder.IsSignConfirmation = IsSignConfirmation;

            if (ManuallyShipmentProviderType.HasValue)
            {
                if (dbOrder.ShipmentProviderType != ManuallyShipmentProviderType.Value)
                {
                    shipmentProviderChanged = true;
                    shouldRecalcRates       = true;
                }

                orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ShipmentProviderTypeKey, dbOrder.ShipmentProviderType, ManuallyShipmentProviderType, by);
                dbOrder.ShipmentProviderType = ManuallyShipmentProviderType.Value;
            }

            //dbOrder.OnHold = OnHold;

            dbOrder.UpdateDate = when;
            dbOrder.UpdatedBy  = by;

            if (Items.All(i => i.NewListingId > 0)) //NOTE: only when enabled items edit
            {
                var changeNotes        = "";
                var itemSizeWasChanged = false;
                var joinItems          = JoinItems(Items);
                var dbOrderItems       = db.OrderItems.GetAll().Where(i => i.OrderId == dbOrder.Id).ToList();
                var orderItemSources   = db.OrderItemSources.GetAllAsDto().Where(i => i.OrderId == dbOrder.Id).ToList();

                foreach (var item in joinItems)
                {
                    var dbOrderItem = dbOrderItems.FirstOrDefault(im => im.ItemOrderIdentifier == item.ItemOrderId);

                    //NOTE: Get source info for set proprotionally ItemPrice etc.
                    var sourceItemOrderId = item.SourceItemOrderId;
                    var sourceItemMapping = orderItemSources.FirstOrDefault(i => i.ItemOrderIdentifier == sourceItemOrderId);

                    if (dbOrderItem != null)
                    {
                        log.Info("Updated orderItemId=" + item.ItemOrderId + ", qty=" + item.Quantity);
                    }
                    else
                    {
                        log.Info("Added orderItemId=" + item.ItemOrderId + ", qty=" + item.Quantity);
                        dbOrderItem            = db.OrderItemSources.CreateItemFromSourceDto(sourceItemMapping);
                        dbOrderItem.CreateDate = when;

                        db.OrderItems.Add(dbOrderItem);
                    }

                    dbOrderItem.ItemOrderIdentifier = item.ItemOrderId;
                    dbOrderItem.QuantityOrdered     = item.Quantity;
                    dbOrderItem.ListingId           = item.NewListingId;

                    dbOrderItem.SourceListingId           = sourceItemMapping.ListingId;
                    dbOrderItem.SourceItemOrderIdentifier = sourceItemMapping.ItemOrderIdentifier;

                    var newListing = db.Listings.GetViewListingsAsDto(withUnmaskedStyles: false)
                                     .FirstOrDefault(l => l.Id == item.NewListingId);

                    var keepListingUpdateOnlyStyle = newListing.StyleItemId != dbOrderItem.StyleItemId;
                    if (dbOrderItem.Id == 0 ||
                        item.NewListingId != item.ListingId ||
                        keepListingUpdateOnlyStyle)
                    {
                        var oldListing = db.Listings.GetViewListingsAsDto(withUnmaskedStyles: false)
                                         .FirstOrDefault(l => l.Id == sourceItemMapping.ListingId);

                        if (newListing != null && oldListing != null)
                        {
                            itemSizeWasChanged = newListing.StyleItemId != oldListing.StyleItemId;
                            if (itemSizeWasChanged)
                            {
                                var isStyleChanged = newListing.StyleString != oldListing.StyleString;
                                changeNotes += (isStyleChanged ? "Order item" : "Size") + " was changed from: " +
                                               (isStyleChanged ? oldListing.StyleString + " - " : " ") +
                                               SizeHelper.ToVariation(oldListing.StyleSize, oldListing.StyleColor)
                                               + " to: " + (isStyleChanged ? newListing.StyleString + " - " : "") +
                                               SizeHelper.ToVariation(newListing.StyleSize, newListing.StyleColor);

                                dbOrderItem.ReplaceType = (int)ItemReplaceTypes.Change;
                                dbOrderItem.ReplaceDate = when;
                                orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ReplaceItemKey, dbOrderItem.StyleItemId, dbOrderItem.Id.ToString(), newListing.StyleItemId, null, by);

                                var quantityOperation = new QuantityOperationDTO()
                                {
                                    Type            = (int)QuantityOperationType.Lost,
                                    QuantityChanges = new List <QuantityChangeDTO>()
                                    {
                                        new QuantityChangeDTO()
                                        {
                                            StyleId     = oldListing.StyleId.Value,
                                            StyleItemId = oldListing.StyleItemId.Value,
                                            Quantity    = dbOrderItem.QuantityOrdered,
                                            //NOTE: W/o sign means that the qty will be substracted
                                        }
                                    },
                                    Comment = "Order edit, change style/size",
                                };

                                quantityManager.AddQuantityOperation(db,
                                                                     quantityOperation,
                                                                     when,
                                                                     by);
                            }

                            //NOTE: Actualize current style info
                            dbOrderItem.StyleId     = newListing.StyleId;
                            dbOrderItem.StyleItemId = newListing.StyleItemId;
                            dbOrderItem.StyleString = newListing.StyleString;

                            dbOrderItem.SourceStyleString = oldListing.StyleString;
                            dbOrderItem.SourceStyleItemId = oldListing.StyleItemId;
                            dbOrderItem.SourceStyleSize   = oldListing.StyleSize;
                            dbOrderItem.SourceStyleColor  = oldListing.StyleColor;
                        }
                    }

                    if (dbOrderItem.ItemOrderIdentifier != dbOrderItem.SourceItemOrderIdentifier)
                    {
                        var portionCoef = dbOrderItem.QuantityOrdered / (decimal)sourceItemMapping.QuantityOrdered;

                        dbOrderItem.ItemPrice             = sourceItemMapping.ItemPrice * portionCoef;
                        dbOrderItem.ItemPriceInUSD        = sourceItemMapping.ItemPriceInUSD * portionCoef;
                        dbOrderItem.ShippingPrice         = sourceItemMapping.ShippingPrice * portionCoef;
                        dbOrderItem.ShippingPriceInUSD    = sourceItemMapping.ShippingPriceInUSD * portionCoef;
                        dbOrderItem.ShippingDiscount      = sourceItemMapping.ShippingDiscount * portionCoef;
                        dbOrderItem.ShippingDiscountInUSD = sourceItemMapping.ShippingDiscountInUSD * portionCoef;
                    }
                    else //NOTE: m.b. no needed, for now no cases, but can be found in future
                    {
                        dbOrderItem.ItemPrice             = sourceItemMapping.ItemPrice;
                        dbOrderItem.ItemPriceInUSD        = sourceItemMapping.ItemPriceInUSD;
                        dbOrderItem.ShippingPrice         = sourceItemMapping.ShippingPrice;
                        dbOrderItem.ShippingPriceInUSD    = sourceItemMapping.ShippingPriceInUSD;
                        dbOrderItem.ShippingDiscount      = sourceItemMapping.ShippingDiscount;
                        dbOrderItem.ShippingDiscountInUSD = sourceItemMapping.ShippingDiscountInUSD;
                    }
                }
                db.Commit();

                var toRemoveOrderItems = dbOrderItems.Where(oi => joinItems.All(i => i.ItemOrderId != oi.ItemOrderIdentifier) &&
                                                            oi.QuantityOrdered > 0).ToList(); //Keeping cancelled items with qty = 0
                foreach (var toRemove in toRemoveOrderItems)
                {
                    log.Info("Remove orderItem, ordrItemId=" + toRemove.ItemOrderIdentifier
                             + ", qty=" + toRemove.QuantityOrdered);
                    db.OrderItems.Remove(toRemove);

                    itemSizeWasChanged = true;
                }
                db.Commit();

                if (itemSizeWasChanged)
                {
                    shouldRecalcRates = true;

                    Comments.Add(new CommentViewModel()
                    {
                        Comment = changeNotes,
                        Type    = (int)CommentType.ReturnExchange
                    });
                }
            }


            if (!string.IsNullOrEmpty(ManuallyShippingGroupId))
            {
                var groupId   = int.Parse(ManuallyShippingGroupId);
                var shippings = db.OrderShippingInfos.GetByOrderId(EntityId).ToList();
                var previousIsActiveMethodIds = String.Join(";", shippings.Where(sh => sh.IsActive).Select(sh => sh.ShippingMethodId).ToList());
                var hasDropdown = shippings.Where(sh => sh.IsVisible).GroupBy(sh => sh.ShippingMethodId).Count() > 1;
                if (shippings.Any(sh => sh.ShippingGroupId == groupId))
                {
                    foreach (var shipping in shippings)
                    {
                        shipping.IsActive = shipping.ShippingGroupId == groupId;
                        if (hasDropdown) //Keep is visible
                        {
                            shipping.IsVisible = shipping.IsVisible || shipping.ShippingGroupId == groupId;
                        }
                        else
                        {
                            shipping.IsVisible = shipping.ShippingGroupId == groupId;
                        }
                    }
                    var newIsActiveMethodIds = String.Join(";", shippings.Where(sh => sh.IsActive).Select(sh => sh.ShippingMethodId).ToList());
                    orderHistoryService.AddRecord(dbOrder.Id, OrderHistoryHelper.ShippingMethodKey, previousIsActiveMethodIds, newIsActiveMethodIds, by);
                }
                else
                {
                    //Can't change active shipping to not exists
                }
            }
            db.Commit();

            //Update Package Sizes
            var activeShippings = db.OrderShippingInfos.GetByOrderId(EntityId)
                                  .Where(sh => sh.IsActive)
                                  .OrderBy(sh => sh.Id)
                                  .ToList();

            for (var i = 0; i < activeShippings.Count; i++)
            {
                if (Packages != null && i < Packages.Count)
                {
                    if (activeShippings[i].PackageLength != Packages[i].PackageLength)
                    {
                        log.Info("Changed length: " + activeShippings[i].PackageLength + "=>" + Packages[i].PackageLength);
                        activeShippings[i].PackageLength = Packages[i].PackageLength;

                        shouldRecalcRates = true;
                    }
                    if (activeShippings[i].PackageWidth != Packages[i].PackageWidth)
                    {
                        log.Info("Changed width: " + activeShippings[i].PackageWidth + "=>" + Packages[i].PackageWidth);
                        activeShippings[i].PackageWidth = Packages[i].PackageWidth;

                        shouldRecalcRates = true;
                    }
                    if (activeShippings[i].PackageHeight != Packages[i].PackageHeight)
                    {
                        log.Info("Changed height: " + activeShippings[i].PackageHeight + "=>" + Packages[i].PackageHeight);
                        activeShippings[i].PackageHeight = Packages[i].PackageHeight;

                        shouldRecalcRates = true;
                    }
                }
            }
            db.Commit();



            foreach (var comment in Comments)
            {
                if (comment.Id == 0)
                {
                    log.Info("New comment: " + comment.Comment);
                }
            }

            db.OrderComments.AddComments(
                Comments.Select(c => new CommentDTO()
            {
                Id      = c.Id,
                Message = c.Comment,
                Type    = c.Type,
            }).ToList(),
                EntityId,
                when,
                by);

            return(new ApplyOrderResult()
            {
                RateRecalcRequested = shouldRecalcRates,
                AddressValidationRequested = addressChanged ||
                                             dbOrder.AddressValidationStatus == (int)Core.Models.AddressValidationStatus.ExceptionCommunication ||
                                             dbOrder.AddressValidationStatus == (int)Core.Models.AddressValidationStatus.Exception,
                ShipmentProviderChanged = shipmentProviderChanged
            });
        }