Ejemplo n.º 1
0
        protected override void Process()
        {
            _monitoring.Notify(Name, 0);
            _atShipmentCostsProduct = PfaAmericaTodayConfiguration.Current.ShipmentCostsProduct;
            _atReturnCostsProduct   = PfaAmericaTodayConfiguration.Current.ReturnCostsProduct;

            _atKialaShipmentCostsProduct = PfaAmericaTodayConfiguration.Current.KialaShipmentCostsProduct;
            _atKialaReturnCostsProduct   = PfaAmericaTodayConfiguration.Current.KialaReturnCostsProduct;

            var config = GetConfiguration();

            _connectorIDs = GetConfiguration().AppSettings.Settings["atConnectorID"].Value.Split(',').Select(int.Parse).ToList();

            var vendorID = int.Parse(config.AppSettings.Settings["ATVendorID"].Value);
            //var connectorID = int.Parse(config.AppSettings.Settings["atConnectorID"].Value);

            var cjpCode = GetConfiguration().AppSettings.Settings["CJPDiscountCode"].Try(c => c.Value, "CJP");

            NetworkExportUtility util = new NetworkExportUtility();

            using (var unit = GetUnitOfWork())
            {
                try
                {
                    _returnCodes = (from c in unit.Scope.Repository <Connector>().GetAll().ToList()
                                    where _connectorIDs.Contains(c.ConnectorID)
                                    select new
                    {
                        c.ConnectorID,
                        Code = c.ConnectorSettings.GetValueByKey <int?>("ReturnCodeOverride", null)
                    }).Where(c => c.Code != null).ToDictionary(p => p.ConnectorID, p => p.Code.Value);

                    var fileLocation = config.AppSettings.Settings["DatColLocationAT"].Value;
                    if (string.IsNullOrEmpty(fileLocation))
                    {
                        throw new Exception("No DatColLocation vendorsetting");
                    }

#if DEBUG
                    fileLocation = @"D:\Concentrator_TESTING";
#endif

                    var userName = config.AppSettings.Settings["DatColLocationUserNameAT"].Value;
                    if (string.IsNullOrEmpty(userName))
                    {
                        throw new Exception("No DatColLocation UserName");
                    }

                    var password = config.AppSettings.Settings["DatColLocationPasswordAT"].Value;
                    if (string.IsNullOrEmpty(password))
                    {
                        throw new Exception("No DatColLocation Password");
                    }

#if !DEBUG
                    fileLocation = util.ConnectorNetworkPath(fileLocation, "M:", userName, password);
#endif
                    var salesSlip   = unit.Scope.Repository <VendorSetting>().GetAll(x => x.SettingKey == "SalesslipNumber" && x.VendorID == vendorID).FirstOrDefault();
                    var salesSlipNr = 0;

                    if (salesSlip == null)
                    {
                        salesSlip = new VendorSetting()
                        {
                            SettingKey = "SalesslipNumber",
                            Value      = salesSlipNr.ToString(),
                            VendorID   = vendorID
                        };
                        unit.Scope.Repository <VendorSetting>().Add(salesSlip);
                    }
                    else
                    {
                        salesSlipNr = int.Parse(salesSlip.Value);

                        if (salesSlipNr == 9999)
                        {
                            salesSlipNr = 0;
                        }
                    }

                    var ledgerRepo = unit.Scope.Repository <OrderLedger>();

                    var timeStamp = DateTime.Now.ToString("yyMMddhhmm");

                    var repositoryOL = unit.Scope.Repository <OrderLine>();

                    foreach (var connector in _connectorIDs)
                    {
                        LoadOrderLines(repositoryOL, connector);
                    }

                    if (!HasOrdersToProcess())
                    {
                        util.DisconnectNetworkPath(fileLocation); //disconnect the path
                        return;                                   //shortcircuit here if there are no orders to process
                    }


                    using (var engine = new MultiRecordEngine(typeof(DatColReceiveRegular), typeof(DatColNormalSales), typeof(DatColReturn)))
                    {
                        var file   = Path.Combine(fileLocation, string.Format("datcol.{0}", timeStamp));
                        var okFile = Path.Combine(fileLocation, string.Format("datcol.{0}.ok", timeStamp));

                        if (!File.Exists(file))
                        {
                            File.Create(file).Dispose();
                        }

                        engine.BeginAppendToFile(file);

                        #region Orders
                        ///contains all order lines
                        linestoProcess.GroupBy(c => c.OrderID).ToList().ForEach(orderLinesCollection =>
                        {
                            string shopOrderNumber  = string.Empty;
                            decimal totalAmount     = 0;
                            DateTime timeStampOrder = DateTime.Now;

                            foreach (var line in orderLinesCollection)
                            {
                                var barcode = line.Product.ProductBarcodes.FirstOrDefault(x => x.BarcodeType.HasValue && x.BarcodeType.Value == 0);
                                var pfaCode = line.Product.ProductBarcodes.Where(c => c.BarcodeType == (int)BarcodeTypes.PFA).FirstOrDefault();
                                var articleSizeColorArray = line.Product.VendorItemNumber.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                var va = line.Product.VendorAssortments.FirstOrDefault(x => x.VendorID == line.DispatchedToVendorID);

                                var productPriceEnt = va.Try(c => c.VendorPrices.FirstOrDefault(), null);

                                var productPrice = productPriceEnt != null
                  ? va.VendorPrices.FirstOrDefault().Price.Value : (line.Price.HasValue ? Convert.ToDecimal(line.Price.Value) : 0);

                                var specialPrice = (va != null && va.VendorPrices.FirstOrDefault() != null && va.VendorPrices.FirstOrDefault().SpecialPrice.HasValue ? va.VendorPrices.FirstOrDefault().SpecialPrice.Value : 0);

                                var articleCode = string.Empty;
                                var colorCode   = string.Empty;
                                if (articleSizeColorArray.Count() > 0)
                                {
                                    articleCode = articleSizeColorArray[0].PadLeft(13, '0');
                                }
                                if (articleSizeColorArray.Count() > 1)
                                {
                                    colorCode = articleSizeColorArray[1].PadLeft(3, '0');
                                }
                                var sizeCode = (pfaCode != null ? pfaCode.Barcode.PadLeft(4, '0') : string.Empty);

                                if (line.OrderLedgers.Any(c => c.Status == (int)OrderLineStatus.ProcessedKasmut && c.Quantity.Value == line.Quantity))
                                {
                                    continue;
                                }

                                int quantityToProcess = 0;
                                int quantityProcessed = 0;

                                if (line.OrderLedgers.Any(c => c.Status == (int)OrderLineStatus.ProcessedKasmut))
                                {
                                    var ledg          = line.OrderLedgers.FirstOrDefault(c => c.Status == (int)OrderLineStatus.ProcessedKasmut);
                                    quantityToProcess = line.Quantity - ledg.Quantity.Value;
                                    quantityProcessed = ledg.Quantity.Value;
                                }

                                var discount    = DatcolHelper.GetDiscount(line, quantityToProcess);
                                var lineRevenue = DatcolHelper.GetUnformattedRevenue(line, quantityProcessed, quantityToProcess);
                                timeStampOrder  = line.Order.ReceivedDate.ToLocalTime();
                                totalAmount    += (decimal)lineRevenue;
                                shopOrderNumber = getShopNumberByConnector(line.Order.Connector);

                                DatColNormalSales sale = new DatColNormalSales()
                                {
                                    ShopAndPosNr     = string.Format("{0} 01", shopOrderNumber),
                                    SalesslipNumber  = salesSlipNr,
                                    DateStamp        = timeStampOrder,
                                    Quantity         = quantityToProcess == 0 ? line.Quantity : quantityToProcess,
                                    ReceivedFrom     = (int)Math.Round(line.BasePrice.Value * 100),
                                    MarkdownValue    = (int)Math.Round((decimal)(line.BasePrice - line.UnitPrice) * 100),
                                    Discount         = discount,
                                    Revenue          = DatcolHelper.FormatRevenueForDatcol(lineRevenue),
                                    ArticleColorSize = String.Format("{0}{1}{2}", articleCode, colorCode, sizeCode),
                                    Barcode          = barcode != null ? barcode.Barcode : string.Empty,
                                    VatCode          = DatcolHelper.GetBTWCode(articleCode).ToString(),
                                    RecordType       = GetRecordType(line),
                                    FixedField1      = GetDiscountCode(line, cjpCode, discount),
                                    FixedField2      = (int)Math.Round(GetDiscountFromSet(line) * 100),
                                    FixedField3      = GetRecordType(line) == "02" ? "101" : "000"
                                };

                                line.SetStatus(OrderLineStatus.ProcessedExportNotification, ledgerRepo, useStatusOnNonAssortmentItems: true);
                                engine.WriteNext(sale);
                            }
                            DatcolHelper.SaveDatcolLink(orderLinesCollection.First().Order, shopOrderNumber, timeStampOrder, totalAmount, salesSlipNr, "Sales order");
                            DatcolHelper.IncrementSalesSlipNumber(ref salesSlipNr);
                        });

                        _monitoring.Notify(Name, 10);
                        #endregion

                        engine.Flush();

                        salesSlip.Value = salesSlipNr.ToString();

                        unit.Save();

                        #region Cancellations
                        var cancelledStatus = (int)OrderLineStatus.Cancelled;


                        //preliminary : check for cancellation of shipment
                        //if at least one line was cancelled from an order
                        foreach (var order in cancelledLinesToProcess.Select(c => c.Order).Distinct().ToList()) //unit.Scope.Repository<Order>().GetAll(c => cancelLines.Any(l => l.OrderID == c.OrderID)).ToList())
                        {
                            //get its order lines without the ones that are non-assortment
                            var  originalOrderLines = order.OrderLines.Where(c => !c.Product.IsNonAssortmentItem.HasValue || (c.Product.IsNonAssortmentItem.HasValue && !c.Product.IsNonAssortmentItem.Value)).ToList();
                            bool cancelShipmentLine = true; //always include by default the shipment cost

                            var cancelledLines = order.OrderLines.Where(c => c.OrderLedgers.Any(l => l.Status == cancelledStatus)).ToList();

                            if (originalOrderLines.Count() != cancelledLines.Count) //if not all lines have been cancelled -> move on
                            {
                                continue;
                            }

                            foreach (var line in originalOrderLines)
                            {
                                if (!line.OrderLedgers.Any(c => c.Status == cancelledStatus))
                                {
                                    continue;
                                }
                                if (line.OrderLedgers.FirstOrDefault(c => c.Status == cancelledStatus).Quantity != line.Quantity)
                                {
                                    cancelShipmentLine = false;
                                }
                            }

                            if (cancelShipmentLine)
                            {
                                var l = order.OrderLines.Where(c => c.Product.VendorItemNumber == _atShipmentCostsProduct || c.Product.VendorItemNumber == _atKialaShipmentCostsProduct).FirstOrDefault();

                                if (l != null)
                                {
                                    l.SetStatus(OrderLineStatus.Cancelled, unit.Scope.Repository <OrderLedger>(), 1, true);
                                    cancelledLinesToProcess.Add(l);
                                }
                            }
                        }
                        unit.Save();

                        cancelledLinesToProcess.GroupBy(c => c.OrderID).ToList().ForEach(orderLinesCollection =>
                        {
                            decimal totalAmount     = 0;
                            DateTime timeStampOrder = DateTime.Now;
                            string orderShopNumber  = string.Empty;

                            foreach (var line in orderLinesCollection)
                            {
                                var barcode = line.Product.ProductBarcodes.FirstOrDefault(x => x.BarcodeType.HasValue && x.BarcodeType.Value == 0);
                                var pfaCode = line.Product.ProductBarcodes.Where(c => c.BarcodeType == (int)BarcodeTypes.PFA).FirstOrDefault();
                                var articleSizeColorArray = line.Product.VendorItemNumber.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                var va              = line.Product.VendorAssortments.FirstOrDefault(x => x.VendorID == line.DispatchedToVendorID);
                                var productPrice    = (va != null && va.VendorPrices.FirstOrDefault() != null ? va.VendorPrices.FirstOrDefault().Price.Value : (line.Price.HasValue ? Convert.ToDecimal(line.Price.Value) : 0));
                                var specialPrice    = (va != null && va.VendorPrices.FirstOrDefault() != null && va.VendorPrices.FirstOrDefault().SpecialPrice.HasValue ? va.VendorPrices.FirstOrDefault().SpecialPrice.Value : 0);
                                var productPriceEnt = va.Try(c => c.VendorPrices.FirstOrDefault(), null);
                                var articleCode     = string.Empty;
                                var colorCode       = string.Empty;
                                if (articleSizeColorArray.Count() > 0)
                                {
                                    articleCode = articleSizeColorArray[0].PadLeft(13, '0');
                                }
                                if (articleSizeColorArray.Count() > 1)
                                {
                                    colorCode = articleSizeColorArray[1].PadLeft(3, '0');
                                }
                                var sizeCode = (pfaCode != null ? pfaCode.Barcode.PadLeft(4, '0') : string.Empty);

                                var returnLedger   = line.OrderLedgers.FirstOrDefault(x => x.Status == cancelledStatus);
                                var returnQuantity = (returnLedger != null && returnLedger.Quantity.HasValue) ? returnLedger.Quantity.Value : line.Quantity;
                                DatColReturn sale  = null;
                                var discount       = DatcolHelper.GetDiscount(line, returnQuantity);

                                timeStampOrder  = returnLedger.Try(c => c.LedgerDate, DateTime.Now.ToLocalTime());
                                orderShopNumber = getShopNumberByConnector(line.Order.Connector);
                                var lineRevenue = DatcolHelper.GetUnformatedNegativeRevenue(line, returnQuantity);


                                totalAmount += (decimal)lineRevenue;

                                sale = new DatColReturn()
                                {
                                    ShopAndPosNr     = string.Format("{0} 01", orderShopNumber),
                                    SalesslipNumber  = salesSlipNr,
                                    DateStamp        = timeStampOrder,
                                    Quantity         = -returnQuantity,
                                    ReceivedFrom     = -(int)Math.Round(line.BasePrice.Value * 100),
                                    MarkdownValue    = -(int)Math.Round((decimal)(line.BasePrice - line.UnitPrice) * 100),
                                    Discount         = discount,
                                    Revenue          = DatcolHelper.FormatNegativeRevenueForDatcol(lineRevenue),
                                    ArticleColorSize = String.Format("{0}{1}{2}", articleCode, colorCode, sizeCode),
                                    Barcode          = barcode != null ? barcode.Barcode : string.Empty,
                                    VatCode          = DatcolHelper.GetBTWCode(articleCode).ToString(),
                                    RecordType       = GetRecordType(line),
                                    FixedField1      = GetDiscountCode(line, cjpCode, discount),
                                    FixedField2      = (int)Math.Round(GetDiscountFromSet(line) * 100),
                                    FixedField3      = GetRecordType(line) == "02" ? "101" : "000"
                                };

                                line.SetStatus(OrderLineStatus.ProcessedCancelExportNotification, ledgerRepo, useStatusOnNonAssortmentItems: true);
                                engine.WriteNext(sale);
                            }
                            DatcolHelper.SaveDatcolLink(orderLinesCollection.First().Order, orderShopNumber, timeStampOrder, totalAmount, salesSlipNr, "Cancellation");
                            DatcolHelper.IncrementSalesSlipNumber(ref salesSlipNr);
                            DatcolHelper.SaveDatcolLink(orderLinesCollection.First().Order, orderShopNumber, timeStampOrder, totalAmount, salesSlipNr, "Cancellation");
                        });

                        engine.Flush();
                        _monitoring.Notify(Name, 20);
                        #endregion

                        #region Returns
                        var returnStatus = (int)OrderLineStatus.ProcessedReturnNotification;

                        returnedLinesToProcess.GroupBy(c => c.OrderID).ToList().ForEach(orderLinesCollection =>
                        {
                            decimal totalAmount     = 0;
                            DateTime timeStampOrder = DateTime.Now;
                            string orderShopNumber  = string.Empty;

                            foreach (var line in orderLinesCollection)
                            {
                                var barcode = line.Product.ProductBarcodes.FirstOrDefault(x => x.BarcodeType.HasValue && x.BarcodeType.Value == 0);
                                var pfaCode = line.Product.ProductBarcodes.Where(c => c.BarcodeType == (int)BarcodeTypes.PFA).FirstOrDefault();
                                var articleSizeColorArray = line.Product.VendorItemNumber.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                var va              = line.Product.VendorAssortments.FirstOrDefault(x => x.VendorID == line.DispatchedToVendorID);
                                var productPrice    = (va != null && va.VendorPrices.FirstOrDefault() != null ? va.VendorPrices.FirstOrDefault().Price.Value : (line.Price.HasValue ? Convert.ToDecimal(line.Price.Value) : 0));
                                var specialPrice    = (va != null && va.VendorPrices.FirstOrDefault() != null && va.VendorPrices.FirstOrDefault().SpecialPrice.HasValue ? va.VendorPrices.FirstOrDefault().SpecialPrice.Value : 0);
                                var productPriceEnt = va.Try(c => c.VendorPrices.FirstOrDefault(), null);
                                var articleCode     = string.Empty;
                                var colorCode       = string.Empty;

                                if (articleSizeColorArray.Count() > 0)
                                {
                                    articleCode = articleSizeColorArray[0].PadLeft(13, '0');
                                }
                                if (articleSizeColorArray.Count() > 1)
                                {
                                    colorCode = articleSizeColorArray[1].PadLeft(3, '0');
                                }
                                var sizeCode = (pfaCode != null ? pfaCode.Barcode.PadLeft(4, '0') : string.Empty);

                                var returnLedger   = line.OrderLedgers.FirstOrDefault(x => x.Status == returnStatus);
                                var returnQuantity = (returnLedger != null && returnLedger.Quantity.HasValue) ? returnLedger.Quantity.Value : line.Quantity;
                                DatColReturn sale  = null;

                                int returnOrComplaintCode = 4;
                                var returnCode            = getFixedReturnCode(line.Order.ConnectorID);
                                if (returnCode.HasValue)
                                {
                                    returnOrComplaintCode = returnCode.Value;
                                }

                                timeStampOrder  = returnLedger.Try(c => c.LedgerDate, DateTime.Now.ToLocalTime());
                                orderShopNumber = getShopNumberByConnector(line.Order.Connector);

                                if (line.Product.VendorItemNumber == _atReturnCostsProduct || line.Product.VendorItemNumber == _atKialaReturnCostsProduct)
                                {
                                    var lineRevenue      = line.Price == 0 ? 0 : (decimal)(line.Price - line.LineDiscount.Try(c => c.Value, 0));
                                    var formattedRevenue = (int)Math.Round(lineRevenue * 100);
                                    totalAmount         += (decimal)lineRevenue;
                                    sale = new DatColReturn()
                                    {
                                        ShopAndPosNr     = string.Format("{0} 01", orderShopNumber),
                                        SalesslipNumber  = salesSlipNr,
                                        DateStamp        = timeStampOrder,
                                        Quantity         = returnQuantity,
                                        ReceivedFrom     = (int)Math.Round(line.BasePrice.Try(c => c.Value, 0) * 100),
                                        MarkdownValue    = 0,
                                        Discount         = line.LineDiscount.HasValue ? (int)Math.Round((line.LineDiscount.Value * 100)) : 0,
                                        Revenue          = formattedRevenue,
                                        ArticleColorSize = String.Format("{0}{1}{2}", articleCode, colorCode, sizeCode),
                                        Barcode          = barcode != null ? barcode.Barcode : string.Empty
                                    };
                                }
                                else
                                {
                                    var lineRevenue = DatcolHelper.GetUnformatedNegativeRevenue(line, returnQuantity);

                                    totalAmount += (decimal)lineRevenue;
                                    var discount = DatcolHelper.GetDiscount(line, returnQuantity);

                                    sale = new DatColReturn()
                                    {
                                        ShopAndPosNr     = string.Format("{0} 01", orderShopNumber),
                                        SalesslipNumber  = salesSlipNr,
                                        DateStamp        = timeStampOrder,
                                        Quantity         = -returnQuantity,
                                        ReceivedFrom     = -(int)Math.Round(line.BasePrice.Value * 100),
                                        MarkdownValue    = -(int)Math.Round((decimal)(line.BasePrice - line.UnitPrice) * 100),
                                        Discount         = discount,
                                        Revenue          = DatcolHelper.FormatNegativeRevenueForDatcol(lineRevenue),
                                        ArticleColorSize = String.Format("{0}{1}{2}", articleCode, colorCode, sizeCode),
                                        Barcode          = barcode != null ? barcode.Barcode : string.Empty,
                                        VatCode          = DatcolHelper.GetBTWCode(articleCode).ToString(),
                                        RecordType       = GetRecordType(line),
                                        FixedField1      = GetDiscountCode(line, cjpCode, discount),
                                        FixedField2      = (int)Math.Round(GetDiscountFromSet(line) * 100),
                                        FixedField3      = GetRecordType(line) == "02" ? "101" : "000",
                                        FixedField6      = returnCode.HasValue ? returnCode.Value.ToString("D2") : "04"
                                    };
                                }
                                line.SetStatus(OrderLineStatus.ProcessedReturnExportNotification, ledgerRepo, useStatusOnNonAssortmentItems: true);
                                engine.WriteNext(sale);
                            }
                            DatcolHelper.SaveDatcolLink(orderLinesCollection.First().Order, orderShopNumber, timeStampOrder, totalAmount, salesSlipNr, "Refund");
                            DatcolHelper.IncrementSalesSlipNumber(ref salesSlipNr);
                        });
                        _monitoring.Notify(Name, 30);
                        #endregion

                        if (!File.Exists(okFile))
                        {
                            File.Create(okFile).Dispose();
                        }

                        engine.Flush();
#if !DEBUG
                        util.DisconnectNetworkPath(fileLocation);
#endif
                    }
                    salesSlip.Value = salesSlipNr.ToString();

                    //add time stamp
                    var vendor = unit.Scope.Repository <Vendor>().GetSingle(c => c.VendorID == vendorID);
                    var datcolTimeStampSetting = vendor.VendorSettings.FirstOrDefault(c => c.SettingKey == "DatcolTimeStamp");

                    if (datcolTimeStampSetting == null)
                    {
                        datcolTimeStampSetting = new VendorSetting()
                        {
                            VendorID   = vendorID,
                            SettingKey = "DatcolTimeStamp"
                        };

                        unit.Scope.Repository <VendorSetting>().Add(datcolTimeStampSetting);
                    }
                    datcolTimeStampSetting.Value = DateTime.Now.ToString();

                    unit.Save();
                    _monitoring.Notify(Name, 1);
                }
                catch (Exception e)
                {
                    log.Debug("Something went wrong with the generation of the DATCOLS ", e);
                    _monitoring.Notify(Name, -1);
                }
            }
        }
Ejemplo n.º 2
0
        public bool PurchaseOrders(Concentrator.Objects.Models.Orders.Order order, List <Concentrator.Objects.Models.Orders.OrderLine> orderLines, Concentrator.Objects.Models.Vendors.Vendor administrativeVendor, Concentrator.Objects.Models.Vendors.Vendor vendor, bool directShipment, IUnitOfWork unit, ILog logger)
        {
            var filiaal890StockType = unit.Scope.Repository <VendorStockType>().GetSingle(x => x.StockType == "Filiaal890");

            if (filiaal890StockType == null)
            {
                throw new Exception("Stocklocation Filiaal890 does not exists, skip order process");
            }

            var cmStockType = unit.Scope.Repository <VendorStockType>().GetSingle(x => x.StockType == "CM");

            if (cmStockType == null)
            {
                throw new Exception("Stocklocation CM does not exists, skip order process");
            }

            var transferStockType = unit.Scope.Repository <VendorStockType>().GetSingle(x => x.StockType == "Transfer");

            if (transferStockType == null)
            {
                throw new Exception("Stocklocation Transfer does not exists, skip order process");
            }

            var webShopStockType = unit.Scope.Repository <VendorStockType>().GetSingle(x => x.StockType == "Webshop");

            if (webShopStockType == null)
            {
                throw new Exception("Stocklocation Webshop does not exists, skip order process");
            }

            var fileLocation = vendor.VendorSettings.GetValueByKey("casmutLocation", string.Empty);

            if (string.IsNullOrEmpty(fileLocation))
            {
                throw new Exception("No camutlocation vendorsetting for vendor" + vendor.VendorID);
            }

            #region File Network Location
            NetworkExportUtility util = new NetworkExportUtility();

            var userName = vendor.VendorSettings.GetValueByKey("CasMutLocationUserName", string.Empty);
            if (string.IsNullOrEmpty(userName))
            {
                throw new Exception("No Casmutlocation UserName");
            }

            var password = vendor.VendorSettings.GetValueByKey("CasMutLocationPassword", string.Empty);
            if (string.IsNullOrEmpty(password))
            {
                throw new Exception("No Casmutlocation Password");
            }

#if DEBUG
            fileLocation = @"D:\tmp\CC";
#else
            fileLocation = util.ConnectorNetworkPath(fileLocation, "Y:", userName, password);
#endif
            #endregion

            var triggerFilePath = Path.Combine(fileLocation, "kasmut.oke");



            if (File.Exists(triggerFilePath))
            {
                try
                {
                    File.Delete(triggerFilePath);
                }
                catch (Exception) { }                 //in case in use by PFA process
            }
            using (var engine = new MultiRecordEngine(typeof(Casmut), typeof(DatColNormalSales)))
            {
                var file = Path.Combine(fileLocation, "kasmut");

                if (!File.Exists(file))
                {
                    File.Create(file).Dispose();
                }
                engine.BeginAppendToFile(file);

                orderLines.Where(c => (!c.Product.IsNonAssortmentItem.HasValue || (c.Product.IsNonAssortmentItem.HasValue && !c.Product.IsNonAssortmentItem.Value))).ToList().ForEach(line =>
                {
                    var filiaal890Stock = line.Product.VendorStocks.FirstOrDefault(x => x.VendorStockTypeID == filiaal890StockType.VendorStockTypeID && x.VendorID == 1);
                    if (filiaal890Stock == null)
                    {
                        throw new Exception(string.Format("Stocklocation Filiaal890 does not exists for product {0}, skip order process", line.ProductID));
                    }

                    var cmStock = line.Product.VendorStocks.FirstOrDefault(x => x.VendorStockTypeID == cmStockType.VendorStockTypeID && x.VendorID == 1);
                    if (cmStock == null)
                    {
                        throw new Exception(string.Format("Stocklocation CM does not exists for product {0}, skip order process", line.ProductID));
                    }

                    var transferStock = line.Product.VendorStocks.FirstOrDefault(x => x.VendorStockTypeID == transferStockType.VendorStockTypeID && x.VendorID == 1);
                    if (transferStock == null)
                    {
                        throw new Exception(string.Format("Stocklocation Transfer does not exists for product {0}, skip order process", line.ProductID));
                    }

                    var webshopStock = line.Product.VendorStocks.FirstOrDefault(x => x.VendorStockTypeID == webShopStockType.VendorStockTypeID && x.VendorID == 1);
                    if (webshopStock == null)
                    {
                        throw new Exception(string.Format("Stocklocation Webshop does not exists for product {0}, skip order process", line.ProductID));
                    }
                    try
                    {
                        logger.Info("For order " + order.WebSiteOrderNumber + " and orderline  " + line.OrderLineID);
                        logger.Info("Transfer quantity is " + transferStock.QuantityOnHand);
                        logger.Info("CM quantity is " + cmStock.QuantityOnHand);
                        logger.Info("WMS quantity is " + filiaal890Stock.QuantityOnHand);
                        logger.Info("Desired qty is " + line.Quantity);
                    }
                    catch (Exception)
                    {
                    }
                    int transferQuantity = (filiaal890Stock.QuantityOnHand + transferStock.QuantityOnHand) - line.Quantity;

                    if (transferQuantity < 0)
                    {
                        int transferPrePickQuanity = cmStock.QuantityOnHand - Math.Abs(transferQuantity);
                        int quantityToDispatch     = Math.Abs(transferQuantity);

                        if (transferPrePickQuanity < 0)
                        {
                            quantityToDispatch = Math.Abs(transferQuantity) - Math.Abs(transferPrePickQuanity);
                        }


                        if (quantityToDispatch < Math.Abs(transferQuantity))
                        {
                            int quantityCancelled = Math.Abs(transferQuantity) - quantityToDispatch;

                            line.SetStatus(OrderLineStatus.Cancelled, unit.Scope.Repository <OrderLedger>(), quantityCancelled);

                            CancelLine(line, unit, quantityCancelled, "Out of stock, no CM stock availible");
                        }

                        if (quantityToDispatch > 0)
                        {
                            var barcode = line.Product.ProductBarcodes.FirstOrDefault(x => x.BarcodeType.HasValue && x.BarcodeType.Value == 0);

                            Casmut casmut = new Casmut()
                            {
                                EAN = barcode != null ? barcode.Barcode : string.Empty,
                                PickTicketNumber = line.OrderLineID,
                                PosNumber        = 100,
                                TicketNumber     = line.OrderLineID,
                                SalesDate        = DateTime.Now,
                                ShopNumber       = 890,
                                SKUCount         = quantityToDispatch
                            };

                            line.SetStatus(OrderLineStatus.ProcessedKasmut, unit.Scope.Repository <OrderLedger>(), quantityToDispatch);

                            // If complete quantity is send
                            if (quantityToDispatch == line.Quantity)
                            {
                                line.SetStatus(OrderLineStatus.ProcessedExportNotification, unit.Scope.Repository <OrderLedger>());
                            }

                            casmut.SalesValue = (int)Math.Round((double)(line.UnitPrice.HasValue ? (int)Math.Round((((line.UnitPrice.Value - (line.LineDiscount.HasValue ? line.LineDiscount.Value : 0)) * quantityToDispatch) * 100)) : 0));

                            engine.WriteNext(casmut);
#if DEBUG
                            engine.Flush();
#endif
                            cmStock.QuantityOnHand       = cmStock.QuantityOnHand - quantityToDispatch;
                            transferStock.QuantityOnHand = transferStock.QuantityOnHand + quantityToDispatch;

                            unit.Save();
                        }
                    }

                    filiaal890Stock.QuantityOnHand = filiaal890Stock.QuantityOnHand - line.GetDispatchQuantity();

                    webshopStock.QuantityOnHand = cmStock.QuantityOnHand + transferStock.QuantityOnHand + filiaal890Stock.QuantityOnHand;

                    line.SetStatus(OrderLineStatus.ReadyToOrder, unit.Scope.Repository <OrderLedger>());
                    try
                    {
                        logger.Info("After processing for order " + order.WebSiteOrderNumber + " and orderline  " + line.OrderLineID);
                        logger.Info("Transfer quantity is " + transferStock.QuantityOnHand);
                        logger.Info("CM quantity is " + cmStock.QuantityOnHand);
                        logger.Info("WMS quantity is " + filiaal890Stock.QuantityOnHand);
                    }
                    catch (Exception e)
                    {
                        logger.Debug(e);
                    }
                });

                engine.Flush();

#if !DEBUG
                util.DisconnectNetworkPath(fileLocation);
#endif
            }

            if (!File.Exists(triggerFilePath))
            {
                try
                {
                    File.Create(triggerFilePath);
                }
                catch (Exception) { }
            }
            unit.Save();
            return(false);
        }
Ejemplo n.º 3
0
        protected override void Process()
        {
            try
            {
                var config = GetConfiguration();

                NetworkExportUtility util = new NetworkExportUtility();
                using (var unit = GetUnitOfWork())
                {
                    var fileLocation = config.AppSettings.Settings["DatColLocation"].Value;

                    if (string.IsNullOrEmpty(fileLocation))
                    {
                        throw new Exception("No DatColLocation vendorsetting");
                    }

                    var userName = config.AppSettings.Settings["DatColLocationUserName"].Value;
                    if (string.IsNullOrEmpty(userName))
                    {
                        throw new Exception("No DatColLocation UserName");
                    }

                    var password = config.AppSettings.Settings["DatColLocationPassword"].Value;
                    if (string.IsNullOrEmpty(password))
                    {
                        throw new Exception("No DatColLocation Password");
                    }

                    fileLocation = util.ConnectorNetworkPath(fileLocation, "Z:", userName, password);

                    var vendorID = int.Parse(config.AppSettings.Settings["ccVendorID"].Value);


#if DEBUG
                    fileLocation = @"E:\Concentrator_TESTING";
#endif

                    var ledgerRepo = unit.Scope.Repository <OrderLedger>();

                    using (var engine = new MultiRecordEngine(typeof(DatColTransfer), typeof(DatColNormalSales)))
                    {
                        var file = Path.Combine(fileLocation, "datcol");


                        if (!File.Exists(file))
                        {
                            File.Create(file).Dispose();
                        }

                        engine.BeginAppendToFile(file);

                        #region Orders
                        var orderlinesReady  = unit.Scope.Repository <OrderLine>().GetAll(x => x.isDispatched && x.OrderLedgers.Any(y => y.Status == (int)OrderLineStatus.ReadyToOrder) && x.Order.PaymentTermsCode == "Shop").ToList();
                        var orderlinesExport = unit.Scope.Repository <OrderLine>().GetAll(x => x.isDispatched && x.OrderLedgers.Any(y => y.Status == (int)OrderLineStatus.ProcessedExportNotification && x.Order.PaymentTermsCode == "Shop")).ToList();

                        var lines = orderlinesReady.Except(orderlinesExport).ToList();

                        lines.GroupBy(c => c.OrderID).ToList().ForEach(orderLinesCollection =>
                        {
                            var order = unit.Scope.Repository <Order>().GetSingle(c => c.OrderID == orderLinesCollection.Key);

                            var salesSlipNr = order.WebSiteOrderNumber.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries)[1];
                            int counter     = 1;
                            foreach (var line in orderLinesCollection)
                            {
                                var barcode = line.Product.ProductBarcodes.FirstOrDefault(x => x.BarcodeType.HasValue && x.BarcodeType.Value == 0);
                                var pfaCode = line.Product.ProductBarcodes.Where(c => c.BarcodeType == (int)BarcodeTypes.PFA).FirstOrDefault();
                                var articleSizeColorArray = line.Product.VendorItemNumber.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                var va           = line.Product.VendorAssortments.FirstOrDefault(x => x.VendorID == line.DispatchedToVendorID);
                                var productPrice = (va != null && va.VendorPrices.FirstOrDefault() != null ? va.VendorPrices.FirstOrDefault().Price.Value : (line.Price.HasValue ? Convert.ToDecimal(line.Price.Value) : 0));
                                var specialPrice = (va != null && va.VendorPrices.FirstOrDefault() != null && va.VendorPrices.FirstOrDefault().SpecialPrice.HasValue ? va.VendorPrices.FirstOrDefault().SpecialPrice.Value : 0);

                                var articleCode = string.Empty;
                                var colorCode   = string.Empty;
                                if (articleSizeColorArray.Count() > 0)
                                {
                                    articleCode = articleSizeColorArray[0].PadLeft(13, '0');
                                }
                                if (articleSizeColorArray.Count() > 1)
                                {
                                    colorCode = articleSizeColorArray[1].PadLeft(3, '0');
                                }
                                var sizeCode = (pfaCode != null ? pfaCode.Barcode.PadLeft(4, '0') : string.Empty);

                                var shopNumber = line.Order.ShippedToCustomer.CompanyName.Replace("X", string.Empty);

                                DatColTransfer sale = new DatColTransfer()
                                {
                                    ShopAndPosNr        = string.Format("{0} 01", shopNumber),
                                    SalesslipNumber     = int.Parse(salesSlipNr),
                                    DateStamp           = DateTime.Now,
                                    Quantity            = line.Quantity,
                                    ReceivedFrom        = 890,
                                    TransferNumber      = string.Format("00{0}{1}", shopNumber, salesSlipNr),
                                    ArticleColorSize    = String.Format("{0}{1}{2}", articleCode, colorCode, sizeCode),
                                    Barcode             = barcode != null ? barcode.Barcode : string.Empty,
                                    MarkdownValue       = (int)Math.Round((decimal)(line.BasePrice - line.UnitPrice) * 100),
                                    OriginalRetailValue = (int)(Math.Round((decimal)(line.Price * 100))),
                                    RecordSequence      = counter * 100
                                };

                                line.SetStatus(OrderLineStatus.ProcessedExportNotification, ledgerRepo);
                                engine.WriteNext(sale);
                                counter++;
                            }
                        });
                        #endregion

                        engine.Flush();
#if !DEBUG
                        util.DisconnectNetworkPath(fileLocation);
#endif
                        unit.Save();
                    }
                }
            }
            catch (Exception ex)
            {
                log.AuditError("Sales order export failed", ex);
            }
        }
Ejemplo n.º 4
0
        private void WriteOrders(IEnumerable <OrderLine> orderLines, WebOrderProcessType processType, OrderLineStatus newStatus, string ilnClientNumber)
        {
            using (var engine = new MultiRecordEngine(typeof(DatColEnvelope), typeof(DatColHeader), typeof(DatColDate),
                                                      typeof(DatColOrderLine), typeof(DatColCount)))
            {
                orderLines.GroupBy(c => c.OrderID).ToList().ForEach(orderLinesCollection =>
                {
                    using (Stream memoryStream = new MemoryStream())
                        using (var streamWriter = new StreamWriter(memoryStream))
                        {
                            var saveOrder       = true;
                            _magentoOrderNumber = orderLinesCollection.First().Order.WebSiteOrderNumber;

                            engine.BeginWriteStream(streamWriter);

                            var magentoOrderNumber = orderLinesCollection.First().Order.WebSiteOrderNumber;

                            var envelope = new DatColEnvelope
                            {
                                ILNClientNumber    = ilnClientNumber,
                                ILNSapphNumber     = ILNSapphNumber,
                                MagentoOrderNumber = magentoOrderNumber
                            };
                            engine.WriteNext(envelope);

                            var header = new DatColHeader
                            {
                                MagentoOrderNumber = magentoOrderNumber,
                                ILNSapphNumber     = ILNSapphNumber,
                                ILNClientNumber    = ilnClientNumber,
                                ILNClientNumber2   = ilnClientNumber
                            };
                            engine.WriteNext(header);

                            var date = new DatColDate();
                            engine.WriteNext(date);

                            var orderLineCounter = 0;
                            foreach (var line in orderLinesCollection)
                            {
                                if (line.Product == null)
                                {
                                    saveOrder = false;
                                    continue;
                                }

                                var barcode = line.Product.ProductBarcodes.Where(x => x.BarcodeType.HasValue && x.BarcodeType.Value == 0).Select(x => x).FirstOrDefault();

                                if (barcode == null)
                                {
                                    saveOrder = false;
                                    continue;
                                }

                                decimal totalUnitPriceToProcess;
                                var quantityToProcess = 0;

                                switch (processType)
                                {
                                case WebOrderProcessType.WebOrder:
                                    if (!line.Price.HasValue)
                                    {
                                        throw new ArgumentNullException();
                                    }

                                    var discount = line.LineDiscount.HasValue ? line.LineDiscount.Value : 0;

                                    if (line.ProductID == _shipmentCostProductID)
                                    {
                                        totalUnitPriceToProcess = (decimal)(line.Price);
                                    }
                                    else
                                    {
                                        totalUnitPriceToProcess = (decimal)(line.Price.Value - discount);
                                    }

                                    if (line.OrderLedgers.Any(c => c.Status == (int)OrderLineStatus.ProcessedKasmut))
                                    {
                                        var ledg = line.OrderLedgers.FirstOrDefault(c => c.Status == (int)OrderLineStatus.ProcessedKasmut);
                                        if (ledg != null)
                                        {
                                            if (ledg.Quantity != null)
                                            {
                                                quantityToProcess = line.Quantity - ledg.Quantity.Value;
                                            }
                                        }
                                    }
                                    break;

                                case WebOrderProcessType.CancellationWebOrder:
                                    if (line.ProductID == _returnCostProductID)
                                    {
                                        quantityToProcess       = line.Quantity;
                                        totalUnitPriceToProcess = (decimal)(line.UnitPrice.HasValue ? line.UnitPrice.Value : 0);
                                    }
                                    else
                                    {
                                        var returnLedger  = line.OrderLedgers.FirstOrDefault(x => x.Status == CancelledStatus);
                                        quantityToProcess =
                                            -((returnLedger != null && returnLedger.Quantity.HasValue)
                            ? returnLedger.Quantity.Value
                            : line.Quantity);
                                        totalUnitPriceToProcess = (decimal)(Math.Abs(quantityToProcess) * line.UnitPrice);
                                    }
                                    break;

                                case WebOrderProcessType.ReturnedWebOrder:
                                    if (line.ProductID == _returnCostProductID)
                                    {
                                        quantityToProcess       = line.Quantity;
                                        totalUnitPriceToProcess = (decimal)(line.BasePrice.HasValue ? line.BasePrice.Value : 0);
                                    }
                                    else
                                    {
                                        // if product not ReturnCost
                                        //    Quantity = Returned Quantity (if this not exists)
                                        //               Shipped Quantity
                                        //    Price = Paid price per Product (with discount) * Quantity

                                        var returnLedger  = line.OrderLedgers.FirstOrDefault(x => x.Status == ReturnStatus);
                                        quantityToProcess =
                                            -((returnLedger != null && returnLedger.Quantity.HasValue)
                            ? returnLedger.Quantity.Value
                            : line.Quantity);
                                        totalUnitPriceToProcess = (decimal)(Math.Abs(quantityToProcess) * (line.Price / line.Quantity));
                                    }

                                    break;

                                default:
                                    throw new NotImplementedException();
                                }

                                var orderLine = new DatColOrderLine
                                {
                                    OrderLineNumber = ++orderLineCounter,
                                    Barcode         = barcode.Barcode,
                                    Quantity        = quantityToProcess == 0 ? line.Quantity : quantityToProcess,
                                    TotalUnitPrice  = totalUnitPriceToProcess
                                };
                                engine.WriteNext(orderLine);
                            }
                            var count = new DatColCount
                            {
                                TotalOrderLine = orderLinesCollection.Count(),
                                TotalQuantity  = 0
                            };
                            engine.WriteNext(count);

                            engine.Flush();

                            streamWriter.Flush();

                            string webOrderFile;
                            switch (processType)
                            {
                            case WebOrderProcessType.WebOrder:
                                webOrderFile = WebOrderFileName;
                                break;

                            case WebOrderProcessType.CancellationWebOrder:
                            case WebOrderProcessType.ReturnedWebOrder:
                                webOrderFile = ReturnWebOrderFileName;
                                break;

                            default:
                                throw new NotImplementedException();
                            }

                            if (saveOrder)
                            {
                                var listOfOrderLines = orderLinesCollection.ToDictionary <OrderLine, int, int?>(line => line.OrderLineID, line => null);

                                if (!_orderRepo.UpgradeOrderLinesStatus(listOfOrderLines, newStatus, true))
                                {
                                    _log.Info(string.Format("The system can not upgrade the status of order line {0} to {1}", listOfOrderLines.Keys, newStatus));
                                }
                                else
                                {
                                    var ftpManager = new FtpManager(_ftpSetting.FtpUri, null, false, true);
                                    ftpManager.Upload(memoryStream.Reset(), webOrderFile);
                                }
                            }
                            else
                            {
                                //todo: log corrupt lines
                            }
                        }
                });
            }
        }