public void GoodItem_ReturnsExpectedSuccessMsg()
            {
                // arrange
                var mockDependents = new MockDependents();
                var testunit       = MakeTestsLogic(true, ref mockDependents);
                var fakeUser       = new UserProfile();
                var testContext    = new UserSelectedContext {
                    BranchId   = "FUT",
                    CustomerId = "234567"
                };
                var testImportFile = new OrderImportFileModel()
                {
                    Options = new OrderImportOptions()
                    {
                        FileFormat      = FileFormat.CSV,
                        IgnoreFirstLine = false,
                        Contents        = FileContentType.ItemOnly,
                        CartName        = "TestCart"
                    },
                    Contents = "123456"
                };
                var expected = "Import Successful.";

                // act
                var results = testunit.ImportOrder(fakeUser, testContext, testImportFile);

                // assert
                results.SuccessMessage
                .Should()
                .Be(expected);
            }
            public void GoodItemAndBadItem_ReturnsExpectedWarningMsg()
            {
                // arrange
                var mockDependents = new MockDependents();
                var testunit       = MakeTestsLogic(true, ref mockDependents);
                var fakeUser       = new UserProfile();
                var testContext    = new UserSelectedContext
                {
                    BranchId   = "FUT",
                    CustomerId = "234567"
                };
                var testImportFile = new OrderImportFileModel()
                {
                    Options = new OrderImportOptions()
                    {
                        FileFormat      = FileFormat.CSV,
                        IgnoreFirstLine = false,
                        Contents        = FileContentType.ItemOnly,
                        CartName        = "TestCart"
                    },
                    Contents = "123456\n234567"
                };
                var expected = "Some items failed to import.  Please check the items in your cart.\r\n";

                // act
                var results = testunit.ImportOrder(fakeUser, testContext, testImportFile);

                // assert
                results.WarningMessage
                .Should()
                .Be(expected);
            }
Beispiel #3
0
        private void ProcessRow(OrderImportFileModel file, UserSelectedContext catalogInfo, UserProfile user, ListModel parList, IExcelDataReader rdr, List <ShoppingCartItem> returnValue)
        {
            string itmNum = DetermineItemNumber(rdr.GetString(_itemNumberColumn)
                                                .PadLeft(6, '0'), file.Options, user, catalogInfo);
            decimal qty = 1;

            if (file.Options.Contents.Equals(FileContentType.ItemQty) |
                file.Options.Contents.Equals(FileContentType.ItemQtyBrokenCase))
            {
                qty = DetermineQuantity(rdr.GetString(_itemNumberColumn)
                                        .PadLeft(6, '0'), rdr.GetString(_quantityColumn), file.Options, parList);
            }
            bool each = false;

            if (file.Options.Contents.Equals(FileContentType.ItemQtyBrokenCase))
            {
                each = DetermineBrokenCaseItem(rdr.GetString(_eachColumn), file.Options);
            }
            returnValue.Add(new ShoppingCartItem {
                ItemNumber = itmNum,
                CatalogId  = catalogInfo.BranchId,
                Quantity   = qty,
                Each       = each
            });
        }
        public async Task <OperationReturnModel <OrderImportModel> > Order()
        {
            OperationReturnModel <OrderImportModel> ret = new OperationReturnModel <OrderImportModel>();

            try
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new InvalidOperationException();
                }

                OrderImportFileModel fileModel = new OrderImportFileModel();

                var provider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (var content in provider.Contents)
                {
                    var file      = content;
                    var paramName = file.Headers.ContentDisposition.Name.Trim('\"');
                    var buffer    = await file.ReadAsByteArrayAsync();

                    var stream = new MemoryStream(buffer);

                    using (var s = new StreamReader(stream))
                    {
                        switch (paramName)
                        {
                        case "file":
                            stream.CopyTo(fileModel.Stream);
                            fileModel.FileName = file.Headers.ContentDisposition.FileName.Trim('\"');
                            stream.Seek(0, SeekOrigin.Begin);     // Return to the start of the stream
                            fileModel.Contents = s.ReadToEnd();
                            break;

                        case "options":
                            fileModel.Options = Newtonsoft.Json.JsonConvert.DeserializeObject <OrderImportOptions>(s.ReadToEnd());
                            break;
                        }
                    }
                }

                if (string.IsNullOrEmpty(fileModel.Contents) || fileModel.Options == null)
                {
                    throw new Exception("Invalid Request");
                }
                else
                {
                    ret.SuccessResponse = importLogic.ImportOrder(this.AuthenticatedUser, this.SelectedUserContext, fileModel);
                    ret.IsSuccess       = true;
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess    = false;
                ret.ErrorMessage = ex.Message;
                _log.WriteErrorLog("Import Order", ex);
            }
            return(ret);
        }
Beispiel #5
0
        public OrderImportModel ImportOrder(UserProfile user, UserSelectedContext catalogInfo, OrderImportFileModel file)
        {
            OrderImportModel returnModel = new OrderImportModel();

            ShoppingCart newCart = new ShoppingCart {
                Name     = string.Format("Imported Order - {0}", DateTime.Now.ToString("g")),
                BranchId = catalogInfo.BranchId
            };

            ListModel parList = null;

            List <ShoppingCartItem> items = new List <ShoppingCartItem>();

            try {
                switch (file.Options.FileFormat)
                {
                case FileFormat.CSV:
                    items = ParseDelimitedFile(file, CSV_DELIMITER, user, catalogInfo, parList);
                    break;

                case FileFormat.Tab:
                    items = ParseDelimitedFile(file, TAB_DELIMITER, user, catalogInfo, parList);
                    break;

                case FileFormat.Excel:
                    items = ParseExcelDocument(file, user, catalogInfo, parList);
                    break;
                }
            } catch (Exception e) {
                returnModel.Success = false;
                Error(string.Format(e.Message));
                ExceptionEmail.Send(e, string.Format("User: {0} for customer {1} in {2} failed importing an order from file: {3}.", user.UserId, catalogInfo.CustomerId, catalogInfo.BranchId, file.FileName));
            }

            CalculateCartSupTotal(catalogInfo, newCart, ref items);

            if (_errors.Length < 1)
            {
                if (file.Options.IgnoreZeroQuantities)
                {
                    items = items.Where(i => i.Quantity > 0)
                            .ToList();
                }

                newCart.Items = items;

                returnModel.ListId  = shoppingCartLogic.CreateCart(user, catalogInfo, newCart);
                returnModel.Success = true;
            }

            returnModel.ErrorMessage = _errors.ToString();

            returnModel.SuccessMessage = "Import Successful.";

            StringBuilder warningMsg = new StringBuilder();

            if (_warnings != null && _warnings.Length > 0)
            {
                warningMsg.Append(_warnings);
            }
            returnModel.WarningMessage = warningMsg.ToString();

            return(returnModel);
        }
Beispiel #6
0
        private List <ShoppingCartItem> ParseExcelDocument(OrderImportFileModel file, UserProfile user, UserSelectedContext catalogInfo, ListModel parList)
        {
            List <ShoppingCartItem> returnValue = new List <ShoppingCartItem>();

            IExcelDataReader rdr = null;

            if (Path.GetExtension(file.FileName)
                .Equals(BINARY_EXCEL_EXTENSION, StringComparison.InvariantCultureIgnoreCase))
            {
                rdr = ExcelReaderFactory.CreateBinaryReader(file.Stream);
            }
            else
            {
                rdr = ExcelReaderFactory.CreateOpenXmlReader(file.Stream);
            }

            rdr.Read();
            if (file.Options.IgnoreFirstLine.Equals(false))
            {
                bool itemNumberHeaderFound = false;
                bool quantityHeaderFound   = false;
                bool eachHeaderFound       = false;

                if (rdr.FieldCount > 0)
                {
                    for (int i = 0; i < rdr.FieldCount - 1; i++)
                    {
                        if (rdr.GetString(i)
                            .Equals("item", StringComparison.CurrentCultureIgnoreCase))
                        {
                            _itemNumberColumn     = i;
                            itemNumberHeaderFound = true;
                        }
                        else if (rdr.GetString(i)
                                 .Equals("# Ordered", StringComparison.CurrentCultureIgnoreCase))
                        {
                            _quantityColumn     = i;
                            quantityHeaderFound = true;
                        }
                        else if (rdr.GetString(i)
                                 .Equals("each", StringComparison.CurrentCultureIgnoreCase))
                        {
                            _eachColumn     = i;
                            eachHeaderFound = true;
                        }
                    }
                }

                if (itemNumberHeaderFound.Equals(false) &&
                    quantityHeaderFound.Equals(false) &&
                    eachHeaderFound.Equals(false))
                {
                    ProcessRow(file, catalogInfo, user, parList, rdr, returnValue);
                }
            }

            try {
                while (rdr.Read())
                {
                    ProcessRow(file, catalogInfo, user, parList, rdr, returnValue);
                }
            } catch (Exception ex) {
                eventLogRepository.WriteErrorLog("Bad parse of file", ex);
                _warnings = new StringBuilder();
                _warnings.Append("Some items failed to import.  Please check the items in your cart.");
            }

            if (returnValue.Count == 0)
            {
                throw new ApplicationException("Empty Order; No Products Defined in File");
            }

            return(returnValue);
        }
Beispiel #7
0
        private List <ShoppingCartItem> ParseDelimitedFile(OrderImportFileModel file, char Delimiter, UserProfile user, UserSelectedContext catalogInfo, ListModel parList)
        {
            List <ShoppingCartItem> returnValue = new List <ShoppingCartItem>();

            int itemNumberColumn = 0;
            int quantityColumn   = 1;
            int eachColumn       = 2;

            //See if we can determine which columns the item number and label exist
            if (file.Options.IgnoreFirstLine)
            {
                List <string> header = file.Contents.Split(new[] {
                    Environment.NewLine,
                    "\n"
                }, StringSplitOptions.None)
                                       .Take(1)
                                       .Select(i => i.Split(Delimiter)
                                               .ToList())
                                       .FirstOrDefault();
                int colCount = 0;
                foreach (string col in header)
                {
                    if (col.Replace("\"", string.Empty)
                        .Equals("item", StringComparison.CurrentCultureIgnoreCase))
                    {
                        itemNumberColumn = colCount;
                    }
                    else if (col.Replace("\"", string.Empty)
                             .Equals("# Ordered", StringComparison.CurrentCultureIgnoreCase))
                    {
                        quantityColumn = colCount;
                    }
                    else if (col.Replace("\"", string.Empty)
                             .Equals("each", StringComparison.CurrentCultureIgnoreCase))
                    {
                        eachColumn = colCount;
                    }
                    colCount++;
                }
            }

            string[] rows = file.Contents.Split(new[] {
                Environment.NewLine,
                "\n"
            }, StringSplitOptions.None);
            //returnValue = rows
            //            .Skip( file.Options.IgnoreFirstLine ? 1 : 0 )
            //            .Where( line => !String.IsNullOrWhiteSpace(line) )
            //            .Select( i => i.Split( Delimiter ) )
            //            .Select( l => new ShoppingCartItem() {
            //                ItemNumber = DetermineItemNumber(l[itemNumberColumn].Replace("\"", string.Empty), file.Options, user, catalogInfo),
            //                Quantity = file.Options.Contents.Equals(FileContentType.ItemQty) ?
            //                    DetermineQuantity(l[itemNumberColumn].Replace("\"", string.Empty), l[quantityColumn].Replace("\"", string.Empty), file.Options, parList) : 1,
            //                Each = file.Options.Contents.Equals(FileContentType.ItemQtyBrokenCase) ? DetermineBrokenCaseItem(l[eachColumn], file.Options) : false,
            //                CatalogId = catalogInfo.BranchId
            //                } )
            //            .Where( x => !string.IsNullOrEmpty( x.ItemNumber ) ).ToList();
            int rownum = 0;

            foreach (string row in rows)
            {
                if (row.Length > 0)
                {
                    if (++rownum == 1 &&
                        file.Options.IgnoreFirstLine) // skip the first row
                    {
                        continue;
                    }
                    string[] vals   = row.Split(Delimiter);
                    string   itmNum = DetermineItemNumber(vals[itemNumberColumn].PadLeft(6, '0'), file.Options, user, catalogInfo);
                    decimal  qty    = 1;
                    if (file.Options.Contents.Equals(FileContentType.ItemQty) |
                        file.Options.Contents.Equals(FileContentType.ItemQtyBrokenCase))
                    {
                        qty = DetermineQuantity(vals[itemNumberColumn].PadLeft(6, '0'), vals[quantityColumn], file.Options, parList);
                    }
                    bool each = false;
                    if (file.Options.Contents.Equals(FileContentType.ItemQtyBrokenCase))
                    {
                        each = DetermineBrokenCaseItem(vals[eachColumn], file.Options);
                    }
                    returnValue.Add(new ShoppingCartItem {
                        ItemNumber = itmNum,
                        CatalogId  = catalogInfo.BranchId,
                        Quantity   = qty,
                        Each       = each
                    });
                }
            }

            return(returnValue);
        }