public void GivenOneYardAndThreeFeet_ThenCompareQuantity_ShouldReturnTrue()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.FEET, 3.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.YARD, 1.0);

            Assert.IsTrue(lengthOne.Equals(lengthTwo));
        }
        public void Given36InchAndOneYard_ThenCompareQuantity_ShouldReturnTrue()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.INCH, 36.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.YARD, 1.0);

            Assert.IsTrue(lengthOne.Equals(lengthTwo));
        }
        public void GivenTwelveFeetAndOneInch_ThenCompareQuantity_ShouldReturnTrue()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.FEET, 1.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.INCH, 12.0);

            Assert.IsTrue(lengthTwo.Equals(lengthOne));
        }
        public void GivenOneInchAndOneFeet_ThenCompareQuantity_ShouldNotReturnFalse()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.FEET, 1.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.INCH, 1.0);

            Assert.IsFalse(lengthOne.Equals(lengthTwo));
        }
        public void Given2InchAnd5Centimeter_ThenCompareQuantity_ShouldReturnTrue()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.INCH, 2.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.CENTIMETER, 5.0);

            Assert.IsTrue(lengthOne.Equals(lengthTwo));
        }
        public void Given1gallonAndLitter_ThenCompareQuantity_ShouldReturnEqual()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.LITRE, 3.78);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.GALLON, 1.0);

            Assert.AreEqual(lengthOne, lengthTwo);
        }
        public void GivenZeroLengthCompareAndThreeLengthCompare_ThenCompareQuantity_ShouldReturnNotEquals()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.INCH, 0.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.INCH, 0.3);

            Assert.AreNotEqual(lengthOne, lengthTwo);
        }
        public void Given212FahrenheitAnd100Celsius_ThenCompare_shouldReturnEquals()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.FAHRENHIET, 212.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.CELCIUS, 100.0);

            Assert.AreEqual(lengthOne, lengthTwo);
        }
        public void GivenZeroFeetToZeroFeet_ThenCompareQuantity_ShouldReturnEquals()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.FEET, 0.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.FEET, 0.0);

            Assert.AreEqual(lengthOne, lengthTwo);
        }
        public void GivenZeroLengthCompareAndNullLengthCompare_thenCompareQuantity_ShouldReturnNotEquals()
        {
            QuantityOperation LengthCompareOne = new QuantityOperation(UnitConvertor.INCH, 0.0);
            QuantityOperation LengthCompareTwo = null;

            Assert.AreNotEqual(LengthCompareOne, LengthCompareTwo);
        }
        public void Given1TonneAnd1000Kilogram_ThenCompare_shouldReturnEqualsWithvalue()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.TONNE, 1.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.KILOGRAM, 1000.0);

            Assert.AreEqual(lengthOne, lengthTwo);
        }
        public void GivenZeroInchAndZeroFeet_ThenCompareQuantity_ShouldReturnTrue()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.FEET, 0.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.INCH, 0.0);

            Assert.IsTrue(lengthOne.Equals(lengthTwo));
        }
        public void Given1LitterAnd1000milliLiter_ThenCompareQuantity_ShouldReturnEqual()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.LITRE, 1.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.MILILITRE, 1000.0);

            Assert.AreEqual(lengthTwo, lengthOne);
        }
        public void GivenTwoObjectWithDifferentvaleForLengthCompare_Thencheckedtype_ShouldReturnEquals()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.INCH, 0.0);
            QuantityOperation lengthTwo = new QuantityOperation(UnitConvertor.INCH, 0.7);

            Assert.AreEqual(lengthOne.GetType(), lengthTwo.GetType());
        }
        public void GivenTwoObjects_ThenCheckReference_ShouldReturnFalse()
        {
            QuantityOperation lengthOne = new QuantityOperation(UnitConvertor.FEET, 0.0);
            QuantityOperation lengthTwo = lengthOne;

            Assert.AreEqual(lengthOne, lengthTwo);
        }
        public void GivenLenghtInInchForLengthCompare_ThenCheckReference_ShouldReturnTrue()
        {
            QuantityOperation LengthCompareOne = new QuantityOperation(UnitConvertor.INCH, 0.1);
            QuantityOperation LengthCompareTwo = LengthCompareOne;
            bool toReturn = System.Object.ReferenceEquals(LengthCompareOne, LengthCompareTwo);

            Assert.IsTrue(toReturn);
        }
        public void GivenTwoObjectsForLengthCompare_ThenCheckReference_ShouldReturnFalse()
        {
            QuantityOperation LengthCompareOne = new QuantityOperation(UnitConvertor.INCH, 0.0);
            QuantityOperation LengthCompareTwo = new QuantityOperation(UnitConvertor.INCH, 0.0);
            bool toReturn = System.Object.ReferenceEquals(LengthCompareOne, LengthCompareTwo);

            Assert.IsFalse(toReturn);
        }
        public void Given1TonneAnd1000Gram_ThenAddition_shouldReturnEqualsWithvalue10001Kilogram()
        {
            QuantityOperation lengthOne           = new QuantityOperation(UnitConvertor.TONNE, 1.0);
            QuantityOperation lengthTwo           = new QuantityOperation(UnitConvertor.GRAM, 1000.0);
            QuantityOperation ExpectedInInch      = new QuantityOperation(UnitConvertor.KILOGRAM, 1001);
            QuantityOperation additionOfTwoLength = lengthTwo.AddLength(lengthOne);

            Assert.AreEqual(ExpectedInInch, additionOfTwoLength);
        }
        public void Given1LitterAnd1000MilliLiter_ThenAddition_shouldReturnEqualsWithvalue2Litter()
        {
            QuantityOperation lengthOne           = new QuantityOperation(UnitConvertor.LITRE, 1.0);
            QuantityOperation lengthTwo           = new QuantityOperation(UnitConvertor.MILILITRE, 1000.0);
            QuantityOperation ExpectedInInch      = new QuantityOperation(UnitConvertor.LITRE, 2);
            QuantityOperation additionOfTwoLength = lengthTwo.AddLength(lengthOne);

            Assert.AreEqual(ExpectedInInch, additionOfTwoLength);
        }
        public void Given2InchtAnd24Centimeter_ThenAddition_shouldReturnEquals()
        {
            QuantityOperation lengthOne           = new QuantityOperation(UnitConvertor.INCH, 2.0);
            QuantityOperation lengthTwo           = new QuantityOperation(UnitConvertor.CENTIMETER, 2.5);
            QuantityOperation ExpectedInInch      = new QuantityOperation(UnitConvertor.INCH, 3.0);
            QuantityOperation additionOfTwoLength = lengthTwo.AddLength(lengthOne);

            Assert.AreEqual(ExpectedInInch, additionOfTwoLength);
        }
        public void Given1FeetAnd1Feer_ThenAddition_shouldReturnEquals()
        {
            QuantityOperation lengthOne           = new QuantityOperation(UnitConvertor.FEET, 1.0);
            QuantityOperation lengthTwo           = new QuantityOperation(UnitConvertor.FEET, 1.0);
            QuantityOperation ExpectedInInch      = new QuantityOperation(UnitConvertor.INCH, 24.0);
            QuantityOperation additionOfTwoLength = lengthTwo.AddLength(lengthOne);

            Assert.AreEqual(ExpectedInInch, additionOfTwoLength);
        }
        public void Given1GallontAndLitter_ThenAddition_shouldReturnEqualsWithvalue()
        {
            QuantityOperation lengthOne           = new QuantityOperation(UnitConvertor.GALLON, 1.0);
            QuantityOperation lengthTwo           = new QuantityOperation(UnitConvertor.LITRE, 3.78);
            QuantityOperation ExpectedInInch      = new QuantityOperation(UnitConvertor.LITRE, 7.56);
            QuantityOperation additionOfTwoLength = lengthTwo.AddLength(lengthOne);

            Assert.AreEqual(ExpectedInInch, additionOfTwoLength);
        }
        public long AddQuantityOperation(IUnitOfWork db,
                                         QuantityOperationDTO quantityOperation,
                                         DateTime when,
                                         long?by)
        {
            var operation = new QuantityOperation();

            operation.Type    = (int)quantityOperation.Type;
            operation.OrderId = quantityOperation.OrderId;
            operation.Comment = quantityOperation.Comment;

            operation.CreateDate = when;
            operation.CreatedBy  = by;

            db.QuantityOperations.Add(operation);
            db.Commit();

            foreach (var change in quantityOperation.QuantityChanges)
            {
                var dbChange = new QuantityChange();
                dbChange.QuantityOperationId = operation.Id;

                dbChange.StyleId     = change.StyleId;
                dbChange.StyleItemId = change.StyleItemId;
                dbChange.Quantity    = change.Quantity;

                dbChange.InActive  = change.InActive;
                dbChange.ExpiredOn = change.ExpiredOn;
                dbChange.Tag       = StringHelper.Substring(change.Tag, 50);

                dbChange.CreateDate = when;
                dbChange.CreatedBy  = by;

                db.QuantityChanges.Add(dbChange);

                LogStyleItemQuantity(db,
                                     change.StyleItemId,
                                     change.Quantity,
                                     null,
                                     QuantityChangeSourceType.AddSpecialCase,
                                     operation.Type.ToString(),
                                     dbChange.Id,
                                     StringHelper.Substring(StringHelper.GetFirstNotEmpty(operation.OrderId), 50),
                                     when,
                                     by);
            }
            db.Commit();

            return(operation.Id);
        }
        public void Process()
        {
            using (var db = _dbFactory.GetRWDb())
            {
                IQueryable <Style> styleQuery = from st in db.Styles.GetAll()
                                                where !st.Deleted
                                                orderby st.Id descending
                                                select st;
                var styleList = styleQuery.ToList();

                //var toDate = new DateTime(2016, 9, 23);
                var openBoxList = (from b in db.OpenBoxCountings.GetAll()
                                   join bi in db.OpenBoxCountingItems.GetAll() on b.Id equals bi.BoxId
                                   //where bi.CreateDate <= toDate
                                   select new StyleBoxItemInfo
                {
                    StyleId = b.StyleId,
                    BoxQuantity = b.BoxQuantity,
                    StyleItemId = bi.StyleItemId,
                    Quantity = bi.Quantity,
                    CountingDate = b.CountingDate,
                    BatchTimeStatus = b.BatchTimeStatus,
                    IsProcessed = b.IsProcessed,
                }).ToList();

                var sealedBoxList = (from b in db.SealedBoxCountings.GetAll()
                                     join bi in db.SealedBoxCountingItems.GetAll() on b.Id equals bi.BoxId
                                     //where bi.CreateDate <= toDate
                                     select new StyleBoxItemInfo
                {
                    StyleId = b.StyleId,
                    BoxQuantity = b.BoxQuantity,
                    StyleItemId = bi.StyleItemId,
                    Quantity = bi.BreakDown,
                    CountingDate = b.CountingDate,
                    BatchTimeStatus = b.BatchTimeStatus,
                    IsProcessed = b.IsProcessed,
                }).ToList();

                var checkingFromDate = new DateTime(2017, 8, 1);
                var batchList        = db.OrderBatches.GetBatchesToDisplay(true)
                                       .OrderBy(b => b.CreateDate)
                                       .Where(b => b.CreateDate > checkingFromDate)
                                       .ToList();

                foreach (var style in styleList)
                {
                    var styleOpenBoxes   = openBoxList.Where(b => b.StyleId == style.Id && !b.IsProcessed).ToList();
                    var styleSealedBoxes = sealedBoxList.Where(b => b.StyleId == style.Id && !b.IsProcessed).ToList();

                    if (!styleSealedBoxes.Any() &&
                        !styleOpenBoxes.Any())
                    {
                        continue;
                    }

                    _log.Info("Processing style, StyleId=" + style.StyleID);

                    var styleBoxes = new List <StyleBoxItemInfo>();
                    styleBoxes.AddRange(styleOpenBoxes);
                    styleBoxes.AddRange(styleSealedBoxes);

                    var hasProcessed = openBoxList.Any(b => b.StyleId == style.Id && b.IsProcessed) ||
                                       sealedBoxList.Any(b => b.StyleId == style.Id && b.IsProcessed);

                    _log.Info("hasProcessed=" + hasProcessed);

                    //STEP 1. Get min box date + batch mode
                    var firstBox = styleBoxes.OrderBy(sb => sb.CountingDate).FirstOrDefault();
                    var boxDate  = firstBox.CountingDate;
                    _log.Info("Box date=" + boxDate);
                    var batchTimeStatus  = firstBox.BatchTimeStatus;
                    var nextBoxDay       = boxDate.Date.AddDays(1);
                    var boxDay           = boxDate.Date;
                    var boxPrevious2Week = boxDay.AddDays(-14);

                    var styleItems      = db.StyleItems.GetAll().Where(s => s.StyleId == style.Id).ToList();
                    var styleItemCaches = db.StyleItemCaches.GetForStyleId(style.Id);

                    if (styleItems.Any(si => si.LiteCountingStatus != CountingStatusesEx.Counted))
                    {
                        _log.Info("Skipped not all styleItems marked as Counted, styleId=" + style.StyleID);
                        continue;
                    }

                    #region STEP 2. Calculate pending orders when first boxes came
                    if (!hasProcessed)
                    {
                        //STEP 2.1 Get batch list
                        //Exclude batch with data > box date
                        //Exclude batch depend of "batch mode"
                        //NOTE: the "Main" batch can be created at 11 PM at previous day
                        var batchFromDate = boxDate.Date.AddHours(-3);
                        var batchToDate   = boxDate.Date.AddHours(21);


                        var excludeBatchList = batchList.Where(b => b.CreateDate < batchFromDate).ToList();

                        //NOTE: always BEFORE FIRST BATCH
                        var dayBatches = batchList.Where(b => b.CreateDate >= batchFromDate && b.CreateDate < batchToDate && b.OrdersCount > 0).ToList();
                        if (dayBatches.Count > 0)
                        {
                            if (batchTimeStatus == (int)BatchTimeStatus.BeforeFirst)
                            {
                                //Nothing
                            }
                            if (batchTimeStatus == (int)BatchTimeStatus.AfterFirstBeforeSecond ||
                                batchTimeStatus == (int)BatchTimeStatus.AfterSecond)
                            {
                                excludeBatchList.Add(dayBatches[0]);
                            }
                            if (batchTimeStatus == (int)BatchTimeStatus.AfterSecond)
                            {
                                if (dayBatches.Count > 1)
                                {
                                    excludeBatchList.Add(dayBatches[1]);
                                }
                            }
                        }

                        //STEP 2.2. Get all orders with (box date - 1 week) <= order date <= box date
                        //Get orders outside of exclude batches
                        var excludeBatchIdList = excludeBatchList.Select(b => b.Id).ToList();
                        //NOTE: as result we get the list of orders came till end of day, that In-Pending
                        var pendingOrders =
                            db.Orders.GetAll()
                            .Where(
                                o =>
                                (o.OrderStatus == OrderStatusEnumEx.Shipped ||
                                 o.OrderStatus == OrderStatusEnumEx.Pending) &&
                                (!o.BatchId.HasValue || !excludeBatchIdList.Contains(o.BatchId.Value)) &&
                                o.OrderDate > boxPrevious2Week && o.OrderDate < boxDay).ToList();

                        //Find styleId, styleItemId in these order items

                        _log.Info("Pending orders=" + pendingOrders.Count);
                        var pendingOrderIds = pendingOrders.Select(p => p.Id).ToArray();
                        var orderItems      = db.OrderItems.GetWithListingInfo().Where(i => i.OrderId.HasValue && pendingOrderIds.Contains(i.OrderId.Value)).ToList();
                        //    db.ItemOrderMappings.GetFilteredOrdersWithItems(new OrderSearchFilter()
                        //    {
                        //        EqualOrderIds = pendingOrders.Select(p => p.Id).ToArray()
                        //    }).ToList();
                        //var orderItems =
                        //    pendingOrdersWithItems.Select(o => o.Items).ToList().SelectMany(i => i).ToList();

                        //If > 0, Compose InPendingWhenInventory record
                        if (orderItems.Any(i => i.StyleEntityId == style.Id))
                        {
                            foreach (var si in styleItems)
                            {
                                var sizeQuantity =
                                    orderItems.Where(i => i.StyleItemId == si.Id).Sum(i => i.Quantity);
                                if (sizeQuantity > 0)
                                {
                                    _log.Info(String.Format("Has pending orders items, size={0}({1}), qty={2}", si.Size, si.Id, sizeQuantity));
                                    var operation = new QuantityOperation()
                                    {
                                        Comment    = "Pending orders",
                                        Type       = (int)QuantityOperationType.InPendingWhenInventory,
                                        CreateDate = _time.GetAppNowTime(),
                                    };
                                    db.QuantityOperations.Add(operation);
                                    db.Commit();

                                    db.QuantityChanges.Add(new QuantityChange()
                                    {
                                        QuantityOperationId = operation.Id,
                                        StyleItemId         = si.Id,
                                        StyleId             = si.StyleId,
                                        CreateDate          = _time.GetAppNowTime(),
                                        Quantity            = sizeQuantity,
                                    });
                                    db.Commit();
                                }
                            }
                        }

                        #region STEP 2.3. Checking Kiosk records (Disabled)
                        //NOTE: we use BoxDay as box date, it will be automatically substracted!

                        //var kioskFromDate = boxDate.Date;
                        //var kioskToDate = boxDate.Date.AddDays(1);
                        //var kioskItems = db.Scanned.GetScanItemAsDto()
                        //    .Where(s => s.StyleId == style.Id
                        //        && s.CreateDate > kioskFromDate
                        //        && s.CreateDate < kioskToDate)
                        //    .ToList();

                        ////If > 0, Compose InPendingWhenInventory record
                        //if (kioskItems.Any())
                        //{
                        //    foreach (var si in styleItems)
                        //    {
                        //        var sizeQuantity = kioskItems.Where(i => i.StyleItemId == si.Id).Sum(i => i.Quantity);
                        //        if (sizeQuantity > 0)
                        //        {
                        //            _log.Info("Has pending kiosk items, qty=" + sizeQuantity);
                        //            var operation = new QuantityOperation()
                        //            {
                        //                Comment = "Pending kiosk items",
                        //                Type = (int)QuantityOperationType.InPendingWhenInventory,
                        //                CreateDate = _time.GetAppNowTime(),
                        //            };
                        //            db.QuantityOperations.Add(operation);
                        //            db.Commit();

                        //            db.QuantityChanges.Add(new QuantityChange()
                        //            {
                        //                QuantityOperationId = operation.Id,
                        //                StyleItemId = si.Id,
                        //                StyleId = si.StyleId,
                        //                CreateDate = _time.GetAppNowTime(),
                        //                Quantity = sizeQuantity,
                        //            });
                        //            db.Commit();
                        //        }
                        //    }
                        //}
                        #endregion
                    }
                    #endregion

                    //Mark all exist boxes as archive, set box mode = true
                    var beginCounting  = new DateTime(2017, 10, 15);
                    var existOpenBoxes = db.OpenBoxes.GetByStyleId(style.Id)
                                         .Where(b => b.CreateDate < beginCounting && !b.ReInventory).ToList();
                    foreach (var openBox in existOpenBoxes)
                    {
                        _log.Info("Archive existing OpenBox, Id=" + openBox.Id);
                        openBox.Archived = true;
                    }

                    var existSealedBoxes = db.SealedBoxes.GetByStyleId(style.Id)
                                           .Where(b => b.CreateDate < beginCounting && !b.ReInventory).ToList();;
                    foreach (var sealedBox in existSealedBoxes)
                    {
                        _log.Info("Archive existing SealedBox, Id=" + sealedBox.Id);
                        sealedBox.Archived = true;
                    }
                    db.Commit();

                    foreach (var si in styleItems)
                    {
                        if (si.Quantity != null)
                        {
                            _log.Info(String.Format("Reset Manually Qty, size={0} ({1}) from={2}, at={3}", si.Size, si.Id, si.Quantity, si.QuantitySetDate));
                        }
                        si.Quantity        = null;
                        si.QuantitySetBy   = null;
                        si.QuantitySetDate = null;
                    }
                    db.Commit();

                    //STEP 3.1. Sealed Box
                    var newSealedBoxList = db.SealedBoxCountings.GetByStyleId(style.Id).Where(b => !b.IsProcessed).ToList();
                    var index            = 1;
                    foreach (var box in newSealedBoxList)
                    {
                        var newBoxItems = db.SealedBoxCountingItems.GetAll().Where(sb => sb.BoxId == box.Id).ToList();
                        var when        = _time.GetAppNowTime();
                        var sizePart    = "";
                        if (newBoxItems.Count == 1)
                        {
                            var styleItem = styleItems.FirstOrDefault(s => s.Id == newBoxItems[0].StyleItemId);
                            if (styleItem != null)
                            {
                                sizePart = "-" + styleItem.Size;
                            }
                        }

                        var newDbBox = new SealedBox()
                        {
                            StyleId     = style.Id,
                            BoxBarcode  = style.StyleID + sizePart + "-" + when.ToString("MMMMyyyy") + (index > 1 ? "-" + index : ""),
                            BoxQuantity = box.BoxQuantity,
                            CreateDate  = boxDay, //nextBoxDay
                            CreatedBy   = box.CreatedBy,
                            Owned       = true,
                            ReInventory = true,
                        };
                        db.SealedBoxes.Add(newDbBox);
                        db.Commit();

                        foreach (var boxItem in newBoxItems)
                        {
                            db.SealedBoxItems.Add(new SealedBoxItem()
                            {
                                BoxId       = newDbBox.Id,
                                StyleItemId = boxItem.StyleItemId,
                                BreakDown   = boxItem.BreakDown,

                                CreateDate = boxItem.CreateDate,
                                CreatedBy  = boxItem.CreatedBy
                            });
                        }

                        box.IsProcessed = true;
                        db.Commit();

                        _log.Info("Create SealedBox, name=" + newDbBox.BoxBarcode);

                        index++;
                    }

                    //STEP 3.2. Open Box
                    var newOpenBoxList = db.OpenBoxCountings.GetByStyleId(style.Id).Where(b => !b.IsProcessed).ToList();
                    index = 1;
                    foreach (var box in newOpenBoxList)
                    {
                        var when     = _time.GetAppNowTime();
                        var sizePart = "";

                        var newBoxItems = db.OpenBoxCountingItems.GetAll().Where(sb => sb.BoxId == box.Id).ToList();
                        if (newBoxItems.Count == 1)
                        {
                            var styleItem = styleItems.FirstOrDefault(si => si.Id == newBoxItems[0].StyleItemId);
                            if (styleItem != null)
                            {
                                sizePart = "-" + styleItem.Size;
                            }
                        }

                        var newDbBox = new OpenBox()
                        {
                            StyleId     = style.Id,
                            BoxBarcode  = style.StyleID + sizePart + "-" + when.ToString("MMMMyyyy") + (index > 1 ? "-" + index : ""),
                            BoxQuantity = box.BoxQuantity,
                            CreateDate  = boxDay, //nextBoxDay
                            CreatedBy   = box.CreatedBy,
                            Owned       = true,
                            ReInventory = true,
                        };
                        db.OpenBoxes.Add(newDbBox);
                        db.Commit();

                        foreach (var boxItem in newBoxItems)
                        {
                            db.OpenBoxItems.Add(new OpenBoxItem()
                            {
                                BoxId       = newDbBox.Id,
                                StyleItemId = boxItem.StyleItemId,
                                Quantity    = boxItem.Quantity,

                                CreateDate = boxItem.CreateDate,
                                CreatedBy  = boxItem.CreatedBy
                            });
                        }

                        box.IsProcessed = true;
                        db.Commit();

                        _log.Info("Create OpenBox, name=" + newDbBox.BoxBarcode);

                        index++;
                    }

                    _log.Info("Changes:");
                    foreach (var si in styleItems)
                    {
                        var cache  = styleItemCaches.FirstOrDefault(c => c.Id == si.Id);
                        var boxQty = styleBoxes.Where(b => b.StyleItemId == si.Id).Sum(b => b.BoxQuantity * b.Quantity);
                        _log.Info(si.Size + ": " + (cache != null ? cache.RemainingQuantity.ToString() : "[null]") + "->" + boxQty);
                    }
                }
            }
        }
        public void Import(string filePath)
        {
            _logger.Info("Start importing...");

            StreamReader streamReader = new StreamReader(filePath);
            CsvReader    reader       = new CsvReader(streamReader, new CsvConfiguration
            {
                HasHeaderRecord = true,
                Delimiter       = ";",
                TrimFields      = true,
            });


            var itemResults = new List <ImportItem>();

            using (var db = new UnitOfWork(_logger))
            {
                var allDbStyles     = db.Styles.GetAllAsDto().Where(s => !s.Deleted).ToList();
                var allDbStyleItems = db.StyleItems.GetAllAsDto().ToList();
                var sizeMapping     = db.SizeMappings.GetAllAsDto().ToList();

                while (reader.Read())
                {
                    string styleString = reader.CurrentRecord[0];

                    if (String.IsNullOrEmpty(styleString))
                    {
                        continue;
                    }

                    string size = reader.CurrentRecord[1];
                    if (size != null)
                    {
                        size = size.Replace("SM", "S").Replace("SX", "XS");
                    }

                    int quantity = Int32.Parse(reader.CurrentRecord[2]);

                    var style = allDbStyles.FirstOrDefault(s => s.StyleID == styleString);
                    var sizes = sizeMapping.Where(s => s.ItemSize == size).Select(s => s.StyleSize).ToList();
                    sizes.Add(size);

                    if (style == null)
                    {
                        Console.WriteLine("No style: " + styleString);
                        continue;
                    }

                    var styleItem = allDbStyleItems.FirstOrDefault(s => s.StyleId == style.Id &&
                                                                   sizes.Contains(s.Size));


                    if (styleItem == null)
                    {
                        Console.WriteLine("No size, style=" + styleString + ", size=" + size);
                        continue;
                    }

                    itemResults.Add(new ImportItem()
                    {
                        StyleId     = style.Id,
                        StyleItemId = styleItem.StyleItemId,
                        Quantity    = quantity,
                        Size        = size,
                        StyleString = styleString,
                    });
                }
            }

            Console.WriteLine("Items count=" + itemResults.Count);

            //Insert into Db
            using (var db = new UnitOfWork(_logger))
            {
                var quantityOperation = new QuantityOperation()
                {
                    Type       = (int)QuantityOperationType.Wholesale,
                    Comment    = "From file Isaak_order",
                    CreateDate = DateTime.UtcNow,
                };
                db.QuantityOperations.Add(quantityOperation);
                db.Commit();

                foreach (var item in itemResults)
                {
                    db.QuantityChanges.Add(new QuantityChange()
                    {
                        QuantityOperationId = quantityOperation.Id,
                        Quantity            = item.Quantity,
                        StyleId             = item.StyleId.Value,
                        StyleItemId         = item.StyleItemId.Value,
                        CreateDate          = DateTime.UtcNow
                    });
                }
                db.Commit();
            }
        }