Пример #1
0
        public void Init(IUnitOfWork db)
        {
            GenderList = new SelectList(db.FeatureValues.GetValuesByFeatureId(StyleFeatureHelper.GENDER).ToList(), "Id", "Value");

            ItemStyleList = new SelectList(db.FeatureValues.GetValuesByFeatureId(StyleFeatureHelper.ITEMSTYLE).ToList(), "Id", "Value");

            var marketplaceList = db.Marketplaces.GetAllAsDto().Where(m => m.IsActive).Select(m => new SelectListItem()
            {
                Text  = MarketHelper.GetMarketName(m.Market, m.MarketplaceId),
                Value = m.Market + "_" + m.MarketplaceId
            });

            MarketplaceList = new SelectList(marketplaceList, "Value", "Text");

            MainLicenseList = db.FeatureValues.GetValuesByFeatureId(StyleFeatureHelper.MAIN_LICENSE).OrderBy(l => l.Value).Select(fv => new SelectListItemEx
            {
                Text        = fv.Value,
                Value       = fv.Id.ToString(),
                ParentValue = fv.Id.ToString()
            }).ToList();

            MainLicenseList.Insert(0, new SelectListItemEx()
            {
                Text        = "No License",
                Value       = "0",
                ParentValue = "0",
            });

            SubLicenseList = db.FeatureValues.GetValuesByFeatureId(StyleFeatureHelper.SUB_LICENSE1).OrderBy(l => l.Value).Select(fv => new SelectListItemEx
            {
                Text        = fv.Value,
                Value       = fv.Id.ToString(),
                ParentValue = fv.ExtendedValue.ToString()
            }).ToList();
        }
Пример #2
0
        public void Check()
        {
            var warningPeriod = DateTime.Now.Subtract(TimeSpan.FromHours(48));
            var minDate       = DateTime.Now.AddMonths(-3);

            var messages = new List <string>();

            using (var db = _dbFactory.GetRWDb())
            {
                var actions = db.SystemActions.GetAllAsDto()
                              .Where(a => a.Type == (int)SystemActionType.UpdateOnMarketReturnOrder
                                     //&& (a.Status == (int) SystemActionStatus.Fail //NOTE: all statuses, in case some of action isn't process
                                     && a.Status != (int)SystemActionStatus.Done &&
                                     a.CreateDate <warningPeriod &&
                                                   a.CreateDate> minDate)
                              .ToList();

                foreach (var action in actions)
                {
                    var      data  = JsonConvert.DeserializeObject <ReturnOrderInput>(action.InputData);
                    DTOOrder order = null;
                    if (data.OrderId > 0)
                    {
                        order = db.Orders.GetAllAsDto().FirstOrDefault(o => o.Id == data.OrderId);
                    }
                    if (order == null)
                    {
                        order = db.Orders.GetAllAsDto().FirstOrDefault(o => o.OrderId == data.OrderNumber);
                    }

                    if (order == null)
                    {
                        _log.Info("Unable to find order: orderId=" + data.OrderId + ", orderNumber=" + data.OrderNumber);
                        continue;
                    }

                    var requestedAmount = data.Items.Sum(i => i.RefundItemPrice
                                                         + (data.IncludeShipping ? i.RefundShippingPrice : 0)
                                                         - (data.DeductShipping ? i.DeductShippingPrice : 0)
                                                         - (data.IsDeductPrepaidLabelCost ? i.DeductPrepaidLabelCost : 0));

                    messages.Add("Order #: " + order.OrderId
                                 + ", market: " + MarketHelper.GetMarketName(order.Market, order.MarketplaceId)
                                 + ", status: " + SystemActionHelper.GetName((SystemActionStatus)action.Status)
                                 + ", amount: " + requestedAmount
                                 + ", create date: " + action.CreateDate);
                }
            }

            if (messages.Any())
            {
                _log.Info(String.Join("\r\n", messages));
                _emailService.SendSystemEmailToAdmin("Support Notification: " + Name + " - To Review (" + messages.Count() + ")",
                                                     "Unprocessed refunds:<br/>" + String.Join("<br/>", messages));
            }
            else
            {
                _emailService.SendSystemEmailToAdmin("Support Notification: " + Name + " - Success", "");
            }
        }
        public void Init(IUnitOfWork db)
        {
            GenderList = new SelectList(db.FeatureValues.GetValuesByFeatureId(StyleFeatureHelper.GENDER).ToList(), "Id", "Value");

            ItemStyleList = new SelectList(db.FeatureValues.GetValuesByFeatureId(StyleFeatureHelper.ITEMSTYLE).ToList(), "Id", "Value");

            SleeveList = new SelectList(db.FeatureValues.GetValuesByFeatureId(StyleFeatureHelper.SLEEVE).ToList(), "Id", "Value");

            DropShipperList = OptionsHelper.DropShipperList;

            HolidayList = new SelectList(db.FeatureValues.GetValuesByFeatureId(StyleFeatureHelper.HOLIDAY).ToList(), "Id", "Value");

            var marketplaceList = db.Marketplaces.GetAllAsDto().Select(m => new SelectListItem()
            {
                Text  = MarketHelper.GetMarketName(m.Market, m.MarketplaceId),
                Value = m.Market + ";" + m.MarketplaceId
            });

            MarketplaceList = new SelectList(marketplaceList, "Value", "Text");

            OnlineStatusList = new SelectList(new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text  = "Online",
                    Value = "Online",
                },
                new SelectListItem()
                {
                    Text  = "Offline",
                    Value = "Offline"
                }
            },
                                              "Value",
                                              "Text");

            MainLicenseList = db.FeatureValues.GetValuesByFeatureId(StyleFeatureHelper.MAIN_LICENSE).OrderBy(l => l.Value).Select(fv => new SelectListItemEx
            {
                Text        = fv.Value,
                Value       = fv.Id.ToString(),
                ParentValue = fv.Id.ToString()
            }).ToList();

            MainLicenseList.Insert(0, new SelectListItemEx()
            {
                Text        = "No License",
                Value       = "0",
                ParentValue = "0",
            });

            SubLicenseList = db.FeatureValues.GetValuesByFeatureId(StyleFeatureHelper.SUB_LICENSE1).OrderBy(l => l.Value).Select(fv => new SelectListItemEx
            {
                Text        = fv.Value,
                Value       = fv.Id.ToString(),
                ParentValue = fv.ExtendedValue.ToString()
            }).ToList();
        }
        public void AddPoints()
        {
            using (var db = _dbFactory.GetRWDb())
            {
                var marketList = new MarketplaceKeeper(_dbFactory, false).GetAll();
                var today      = _time.GetAppNowTime().Date;
                foreach (var market in marketList)
                {
                    var listingErrorCount = (from i in db.Items.GetAll()
                                             join l in db.Listings.GetAll() on i.Id equals l.ItemId
                                             where
                                             l.RealQuantity > 0 &&
                                             !l.IsRemoved &&
                                             (i.ItemPublishedStatus == (int)PublishedStatuses.PublishingErrors ||
                                              i.ItemPublishedStatus == (int)PublishedStatuses.PublishedInProgress) &&
                                             i.Market == market.Market &&
                                             (i.MarketplaceId == market.MarketplaceId || String.IsNullOrEmpty(market.MarketplaceId))
                                             select i.Id
                                             ).Count();

                    var marketTag = market.Market + "_" + market.MarketplaceId;
                    var chart     = db.Charts.GetAll().FirstOrDefault(ch => ch.ChartName == ChartHelper.ListingErrorChartName &&
                                                                      ch.ChartTag == marketTag);

                    if (chart == null)
                    {
                        chart = new Chart()
                        {
                            ChartName     = ChartHelper.ListingErrorChartName,
                            ChartSubGroup = MarketHelper.GetMarketName(market.Market, market.MarketplaceId),
                            ChartTag      = marketTag,
                            CreateDate    = _time.GetAppNowTime()
                        };
                        db.Charts.Add(chart);
                        db.Commit();
                    }

                    var existPoint = db.ChartPoints.GetAll().FirstOrDefault(p => p.ChartId == chart.Id &&
                                                                            p.Date == today);

                    if (existPoint == null)
                    {
                        existPoint = new ChartPoint()
                        {
                            ChartId = chart.Id,
                            Date    = today,
                        };
                        db.ChartPoints.Add(existPoint);
                    }
                    existPoint.Value = listingErrorCount;
                }
                db.Commit();
            }
        }
 private string GetMarketName(string marketValue)
 {
     try
     {
         var parts       = marketValue.Split(":".ToCharArray());
         var market      = Int32.Parse(parts[0]);
         var marketplace = parts[1];
         return(MarketHelper.GetMarketName(market, marketplace));
     }
     catch
     {
         return("n/a");
     }
 }
        public static SalesByDateGraphViewModel Build(IUnitOfWork db, PeriodType periodType, ValueType valueType)
        {
            var result = new SalesByDateGraphViewModel();
            var items  = db.Items.GetSalesInfoByDayAndMarket().ToList();

            var             labels      = new List <string>();
            IList <int>     unitSeries  = new List <int>();
            IList <decimal> priceSeries = new List <decimal>();

            var startDate = DateHelper.GetAppNowTime().Date;

            if (periodType == PeriodType.Day)
            {
                startDate = DateHelper.GetAppNowTime().Date;
            }
            if (periodType == PeriodType.Week)
            {
                startDate = startDate.AddDays(-7);
            }
            if (periodType == PeriodType.Month)
            {
                startDate = startDate.AddDays(-31);
            }

            var periodItems = items.Where(it => it.Date >= startDate).ToList();

            periodItems.Where(pi => pi.Market == (int)MarketType.eBay).ToList().ForEach(pi => pi.MarketplaceId = null);

            var byMarket = periodItems.GroupBy(i => new { i.Market, i.MarketplaceId })
                           .Select(i => new
            {
                Market        = i.Key.Market,
                MarketplaceId = i.Key.MarketplaceId,
                Price         = i.Sum(j => j.Price),
                Quantity      = i.Sum(j => j.Quantity)
            });

            foreach (var item in byMarket)
            {
                labels.Add(MarketHelper.GetMarketName(item.Market, item.MarketplaceId));
                unitSeries.Add(item.Quantity);
                priceSeries.Add(item.Price);
            }
            result.PriceSeries = new [] { priceSeries };
            result.UnitSeries  = new [] { unitSeries };
            result.Labels      = new[] { labels };
            return(result);
        }
        public void Check()
        {
            using (var db = _dbFactory.GetRWDb())
            {
                //var marketplaces = db.Marketplaces
                //    .GetAllAsDto()
                //    .Where(m => m.IsActive && !m.IsHidden)
                //    .OrderBy(m => m.SortOrder)
                //    .ThenBy(m => m.Id)
                //    .ToList();


                var html           = "<table><tr><th>Market</th><th>Critical Disparity</th><th>Total Disparity</tr>";
                var toCheckMarkets = new List <MarketplaceDTO>()
                {
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.Amazon, MarketplaceId = MarketplaceKeeper.AmazonComMarketplaceId
                    },
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.Amazon, MarketplaceId = MarketplaceKeeper.AmazonCaMarketplaceId
                    },
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.AmazonEU, MarketplaceId = MarketplaceKeeper.AmazonUkMarketplaceId
                    },
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.Walmart
                    },
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.WalmartCA
                    },
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.eBay, MarketplaceId = MarketplaceKeeper.eBayPA
                    },
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.eBay, MarketplaceId = MarketplaceKeeper.eBayAll4Kids
                    },
                };


                foreach (var marketplace in toCheckMarkets)
                {
                    var checkPriceQuery = db.Items.GetAllViewActual()
                                          .Where(l => l.Market == marketplace.Market &&
                                                 l.MarketplaceId == marketplace.MarketplaceId &&
                                                 l.AmazonCurrentPrice.HasValue &&
                                                 (l.SalePrice ?? l.CurrentPrice) != l.AmazonCurrentPrice);

                    var totalPriceDisparity    = checkPriceQuery.Count();
                    var criticalPriceDisparity = checkPriceQuery
                                                 .Where(l => (l.SalePrice ?? l.CurrentPrice) > l.AmazonCurrentPrice)
                                                 .Count();

                    html += "<tr><td>" + MarketHelper.GetMarketName(marketplace.Market, marketplace.MarketplaceId) + "</td><td>" + criticalPriceDisparity + "</td><td>" + totalPriceDisparity + "</td></tr>";
                }
                html += "</table>";

                foreach (var marketplace in toCheckMarkets)
                {
                    var skuHtml = "<p>" + MarketHelper.GetMarketName(marketplace.Market, marketplace.MarketplaceId) + "</p>";
                    skuHtml += "<table><tr><th>SKU</th><th>CCEN price</th><th>Market price</th></tr>";
                    var skuList = db.Items.GetAllViewActual()
                                  .Where(l => l.Market == marketplace.Market &&
                                         l.MarketplaceId == marketplace.MarketplaceId &&
                                         l.AmazonCurrentPrice.HasValue &&
                                         l.IsExistOnAmazon == true &&
                                         (l.SalePrice ?? l.CurrentPrice) > l.AmazonCurrentPrice)
                                  .OrderBy(l => l.SKU)
                                  .ThenBy(l => l.Id)
                                  .Select(l => new
                    {
                        SKU         = l.SKU,
                        CCENPrice   = l.SalePrice ?? l.CurrentPrice,
                        MarketPrice = l.AmazonCurrentPrice
                    })
                                  .ToList();

                    foreach (var sku in skuList)
                    {
                        skuHtml += "<tr><td>" + sku.SKU + "</td><td>" + sku.CCENPrice + "</td><td>" + sku.MarketPrice + "</td></tr>";
                    }

                    skuHtml += "</table>";

                    html += "<br/>" + skuHtml;
                }

                _log.Info("Infoes: " + html);
                _emailService.SendSystemEmail("Price disparity",
                                              html,
                                              EmailHelper.SupportDgtexEmail + ", " + EmailHelper.IldarDgtexEmail,
                                              null);
            }
        }
        public void Check()
        {
            using (var db = _dbFactory.GetRWDb())
            {
                //var marketplaces = db.Marketplaces
                //    .GetAllAsDto()
                //    .Where(m => m.IsActive && !m.IsHidden)
                //    .OrderBy(m => m.SortOrder)
                //    .ThenBy(m => m.Id)
                //    .ToList();


                var html           = "<table><tr><th>Market</th><th>Critical Disparity</th><th>Total Disparity</th></tr>";
                var toCheckMarkets = new List <MarketplaceDTO>()
                {
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.Amazon, MarketplaceId = MarketplaceKeeper.AmazonComMarketplaceId
                    },
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.Walmart
                    },
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.WalmartCA
                    },
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.eBay, MarketplaceId = MarketplaceKeeper.eBayPA
                    },
                    new MarketplaceDTO()
                    {
                        Market = (int)MarketType.eBay, MarketplaceId = MarketplaceKeeper.eBayAll4Kids
                    },
                };


                foreach (var marketplace in toCheckMarkets)
                {
                    var checkQtyQuery = db.Items.GetAllViewActual()
                                        .Where(l => l.Market == marketplace.Market &&
                                               l.MarketplaceId == marketplace.MarketplaceId &&
                                               l.AmazonRealQuantity.HasValue &&
                                               l.RealQuantity != l.AmazonRealQuantity);

                    if (marketplace.Market == (int)MarketType.Amazon)
                    {
                        checkQtyQuery = checkQtyQuery.Where(i => !i.IsFBA &&
                                                            !(i.RealQuantity == 30 && i.AmazonRealQuantity == 101));
                    }
                    if (marketplace.Market == (int)MarketType.Walmart)
                    {
                        checkQtyQuery = checkQtyQuery.Where(i => i.ItemPublishedStatus != (int)PublishedStatuses.PublishedInactive &&
                                                            i.ItemPublishedStatus != (int)PublishedStatuses.Unpublished);
                    }

                    var totalQtyDisparity    = checkQtyQuery.Count();
                    var criticalQtyDisparity = checkQtyQuery
                                               .Where(l => l.RealQuantity == 0)
                                               .Count();

                    html += "<tr><td>" + MarketHelper.GetMarketName(marketplace.Market, marketplace.MarketplaceId) + "</td><td>" + criticalQtyDisparity + "</td><td>" + totalQtyDisparity + "</td></tr>";
                }
                html += "</table>";

                foreach (var marketplace in toCheckMarkets)
                {
                    var skuHtml = "<p>" + MarketHelper.GetMarketName(marketplace.Market, marketplace.MarketplaceId) + "</p>";
                    skuHtml += "<table><tr><th>SKU</th><th>CCEN qty</th><th>Market qty</th></tr>";
                    var skuList = db.Listings.GetAll()
                                  .Where(l => l.Market == marketplace.Market &&
                                         l.MarketplaceId == marketplace.MarketplaceId &&
                                         !l.IsRemoved &&
                                         l.AmazonRealQuantity.HasValue &&
                                         l.RealQuantity != l.AmazonRealQuantity &&
                                         l.RealQuantity == 0)
                                  .OrderBy(l => l.SKU)
                                  .ThenBy(l => l.Id)
                                  .Select(l => new
                    {
                        SKU       = l.SKU,
                        CCENQty   = l.RealQuantity,
                        MarketQty = l.AmazonRealQuantity
                    })
                                  .ToList();

                    foreach (var sku in skuList)
                    {
                        skuHtml += "<tr><td>" + sku.SKU + "</td><td>" + sku.CCENQty + "</td><td>" + sku.MarketQty + "</td></tr>";
                    }
                    skuHtml += "</table>";

                    html += "<br/>" + skuHtml;
                }

                _log.Info("Infoes: " + html);
                _emailService.SendSystemEmail("Quantity disparity",
                                              html,
                                              EmailHelper.SupportDgtexEmail + ", " + EmailHelper.IldarDgtexEmail,
                                              null);
            }
        }
Пример #9
0
        public CheckResult Check(IUnitOfWork db, DTOMarketOrder order, IList <ListingOrderDTO> orderItems)
        {
            if (!orderItems.Any())
            {
                return new CheckResult()
                       {
                           IsSuccess = false
                       }
            }
            ;

            var styleItemIds = orderItems.Where(i => i.StyleItemId.HasValue).Select(i => i.StyleItemId).ToList();

            _log.Info("CheckIsOversold: listingIds=" + String.Join(",", orderItems.Select(i => i.ListingId).ToList()));

            var cacheItems = db.StyleItemCaches.GetFiltered(si => styleItemIds.Contains(si.Id)).ToList();

            //var oversoldItems = orderItems.Where(i => i.RealQuantity <= 0).ToList();
            var oversoldItems = cacheItems.Where(ch => ch.RemainingQuantity < 0).ToList();

            if (oversoldItems.Count > 0)
            {
                db.OrderNotifies.Add(
                    ComposeNotify(order.Id,
                                  (int)OrderNotifyType.OversoldItem,
                                  1,
                                  String.Join(",", oversoldItems.Select(s => s.Id).ToList()),
                                  _time.GetAppNowTime()));

                db.Commit();

                var oversoldStyleItemIds = oversoldItems.Select(i => i.Id).ToList();
                var oversoldOrderItems   = orderItems.Where(oi => oi.StyleItemId.HasValue).Where(oi => oversoldStyleItemIds.Contains(oi.StyleItemId.Value)).ToList();

                var text = "Oversold #" + order.OrderId + " at " + DateHelper.ToDateTimeString(order.OrderDate) + " - " + String.Join(", ",
                                                                                                                                      oversoldOrderItems.Select(oi => oi.SKU + " on " + MarketHelper.GetMarketName(order.Market, order.MarketplaceId)));
                _emailService.SendSystemEmail(text,
                                              text,
                                              _settings.GetValue <string>(SettingsHelper.KeyOversoldToNotifiers),
                                              _settings.GetValue <string>(SettingsHelper.KeyOversoldCcNotifiers)
                                              //EmailHelper.RafiEmail + ";" + EmailHelper.IldarDgtexEmail,
                                              //EmailHelper.SupportDgtexEmail);
                                              );

                //Disable listing
                foreach (var oversoldOrderItem in oversoldOrderItems)
                {
                    if (oversoldOrderItem.SourceListingId.HasValue)
                    {
                        _log.Info("Raise price for listingId: " + oversoldOrderItem.SourceListingId);
                        //NOTE: rise price 3x, send qty updates
                        var dbListing = db.Listings.Get(oversoldOrderItem.SourceListingId.Value);
                        dbListing.QuantityUpdateRequested     = true;
                        dbListing.QuantityUpdateRequestedDate = _time.GetAppNowTime();
                        dbListing.RealQuantity             = 0;
                        dbListing.PriceUpdateRequested     = true;
                        dbListing.PriceUpdateRequestedDate = _time.GetAppNowTime();
                        dbListing.CurrentPrice             = dbListing.CurrentPrice * 3;

                        var saleToListings = (from ms in db.StyleItemSaleToMarkets.GetAll()
                                              join sl in db.StyleItemSaleToListings.GetAll() on ms.Id equals sl.SaleToMarketId
                                              where sl.ListingId == dbListing.Id
                                              select ms).ToList();
                        saleToListings.ForEach(sl => sl.SalePrice = 3 * sl.SalePrice);
                        db.Commit();
                    }
                }


                return(new CheckResult()
                {
                    IsSuccess = true
                });
            }

            return(new CheckResult()
            {
                IsSuccess = false
            });
        }
Пример #10
0
        //public static void UpdateSalePrices(IUnitOfWork db,
        //    long styleItemId,
        //    long saleId,
        //    decimal newSalePrice,
        //    decimal? newSFPSalePrice)
        //{
        //    var rateForMarketplace = RateHelper.GetRatesByStyleItemId(db, styleItemId);

        //    var marketPrices = db.StyleItemSaleToMarkets.GetAll().Where(s => s.SaleId == saleId).ToList();
        //    foreach (var marketPrice in marketPrices)
        //    {
        //        if (marketPrice.SalePrice.HasValue)
        //        {
        //            var marketListings = db.StyleItemSaleToListings.GetAll().Where(l => l.SaleToMarketId == )

        //            marketPrice.SalePrice = RateHelper.CalculateForMarket((MarketType) marketPrice.Market,
        //                marketPrice.MarketplaceId,
        //                newSalePrice,
        //                rateForMarketplace[MarketplaceKeeper.AmazonComMarketplaceId],
        //                rateForMarketplace[MarketplaceKeeper.AmazonCaMarketplaceId],
        //                rateForMarketplace[MarketplaceKeeper.AmazonUkMarketplaceId],
        //                rateForMarketplace[MarketplaceKeeper.AmazonAuMarketplaceId],
        //                RateService.GetMarketShippingAmount(MarketType.Amazon, MarketplaceKeeper.AmazonComMarketplaceId),
        //                RateService.GetMarketShippingAmount((MarketType)marketPrice.Market, marketPrice.MarketplaceId),
        //                RateService.GetMarketExtraAmount((MarketType)marketPrice.Market, marketPrice.MarketplaceId));


        //        }
        //    }

        //    db.Commit();
        //}

        public static IList <MarketPriceEditViewModel> GetForStyleItemId(IUnitOfWork db,
                                                                         IDbFactory dbFactory,
                                                                         long styleItemId,
                                                                         decimal?initSalePrice,
                                                                         decimal?initSFPSalePrice)
        {
            var priceService = new PriceService(dbFactory);

            var results         = new List <MarketPriceEditViewModel>();
            var allMarketplaces = UIMarketHelper.GetSalesMarketplaces();
            var allListings     = db.Listings.GetListingsAsListingDto()
                                  .Where(l => l.StyleItemId == styleItemId)
                                  .ToList()
                                  .Where(l => !l.IsFBA)
                                  .ToList();

            var rateForMarketplace = RateHelper.GetRatesByStyleItemId(db, styleItemId);

            var sale            = db.StyleItemSales.GetAllAsDto().FirstOrDefault(s => s.StyleItemId == styleItemId && !s.IsDeleted);
            var checkedListings = new List <StyleItemSaleToListingDTO>();

            if (sale != null)
            {
                checkedListings = db.StyleItemSaleToListings.GetAllAsDto().Where(s => s.SaleId == sale.Id).ToList();
            }

            var checkedMarkets = new List <StyleItemSaleToMarketDTO>();

            if (sale != null)
            {
                checkedMarkets = db.StyleItemSaleToMarkets.GetAllAsDto().Where(s => s.SaleId == sale.Id).ToList();
            }

            foreach (var market in allMarketplaces)
            {
                var checkedMarket = checkedMarkets.FirstOrDefault(l => l.Market == (int)market.Market &&
                                                                  (l.MarketplaceId == market.MarketplaceId || String.IsNullOrEmpty(market.MarketplaceId)));

                var marketListings = allListings
                                     .Where(l => l.Market == (int)market.Market &&
                                            (l.MarketplaceId == market.MarketplaceId ||
                                             String.IsNullOrEmpty(market.MarketplaceId)))
                                     .Select(l => new ListingPriceEditViewModel(l))
                                     .ToList();

                foreach (var listing in marketListings)
                {
                    listing.IsChecked = sale == null ?
                                        ((listing.IsPrime || SkuHelper.IsPrime(listing.SKU)) ? initSFPSalePrice.HasValue : initSalePrice.HasValue) :
                                        checkedListings.Any(l => l.ListingId == listing.ListingId);
                }

                var defaultPrice = //sale == null &&
                                   initSalePrice.HasValue &&
                                   marketListings.Any() ? priceService.GetMarketDefaultPrice(initSalePrice.Value,
                                                                                             market.Market,
                                                                                             market.MarketplaceId,
                                                                                             rateForMarketplace) : (decimal?)null;

                foreach (var marketListing in marketListings)
                {
                    var newDefaultPrice = priceService.ApplyMarketSpecified(defaultPrice,
                                                                            initSFPSalePrice,
                                                                            market.Market,
                                                                            market.MarketplaceId,
                                                                            marketListing.Weight,
                                                                            marketListing.IsPrime,
                                                                            marketListing.IsFBA);

                    if (newDefaultPrice != defaultPrice)
                    {
                        marketListing.OverrideSalePrice = newDefaultPrice;
                    }
                }

                var saleToMarket = new MarketPriceEditViewModel()
                {
                    Id = checkedMarket != null ? checkedMarket.Id : 0,

                    Market         = (MarketType)market.Market,
                    MarketplaceId  = market.MarketplaceId,
                    MarketName     = MarketHelper.GetMarketName((int)market.Market, market.MarketplaceId),
                    MarketCurrency = PriceHelper.GetCurrencySymbol(market.Market, market.MarketplaceId),

                    SalePrice          = checkedMarket != null ? checkedMarket.SalePrice : defaultPrice,
                    SFPSalePrice       = market.MarketplaceId == MarketplaceKeeper.AmazonComMarketplaceId ? initSFPSalePrice : null,
                    SalePercent        = checkedMarket != null ? checkedMarket.SalePercent : null,
                    ApplyToNewListings = checkedMarket != null ? checkedMarket.ApplyToNewListings : false,

                    Listings = marketListings
                };

                results.Add(saleToMarket);
            }

            return(results);
        }