예제 #1
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);
            }
        }
예제 #2
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);
                }
            }
        }
예제 #3
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);
        }
예제 #4
0
        protected override void Process()
        {
            using (var unit = GetUnitOfWork())
            {
                NetworkExportUtility util = new NetworkExportUtility();

                var config = GetConfiguration();

                var pathToExportTo = config.AppSettings.Settings["PFAImagePath"].Value;
#if DEBUG
                pathToExportTo = @"D:\ImagesPFA";
#endif
                var baseConcentratorImagePath = ConfigurationManager.AppSettings["FTPMediaDirectory"];


                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");
                }
#if !DEBUG
                pathToExportTo = util.ConnectorNetworkPath(pathToExportTo, "K:", userName, password);
#endif
                var products = unit.Scope.Repository <Product>().GetAll(c => c.SourceVendorID == _vendorID && c.IsConfigurable && c.ParentProductID == null && c.ProductMedias.Any()).ToList();
#if DEBUG
                products = products.Where(c => c.VendorItemNumber.Contains("84B4860001")).ToList();
#endif

                log.Debug(string.Format("Found {0} products to process", products.Count));

                int count = 0;
                foreach (var product in products) //config products
                {
                    if (count % 100 == 0)
                    {
                        log.Debug(string.Format("Processed {0} products", count));
                    }
                    count++;

                    var image = product.ProductMedias.Where(c => c.Sequence == 0).ToList().FirstOrDefault();

                    if (image == null)
                    {
                        continue;
                    }

                    var concentratorPath = Path.Combine(baseConcentratorImagePath, image.MediaPath);

                    if (!File.Exists(concentratorPath))
                    {
                        continue;                       //short circuit in case of problems
                    }
                    var destinationFileName = string.Format("{0}.png", product.VendorItemNumber);

                    try
                    {
                        File.Copy(concentratorPath, Path.Combine(pathToExportTo, destinationFileName), true);
                    }
                    catch (Exception e)
                    {
                        log.Debug(e);
                    }
                }

#if !DEBUG
                util.DisconnectNetworkPath(pathToExportTo);
#endif
            }
        }
예제 #5
0
        protected override void Process()
        {
            foreach (Connector connector in base.Connectors.Where(x => ((ConnectorType)x.ConnectorType).Has(ConnectorType.FileExport)))
            {
#if DEBUG
                if (connector.ConnectorID != 10)
                {
                    continue;
                }
#endif
                #region Assortiment
                if (((ConnectorType)connector.ConnectorType).Has(ConnectorType.ShopAssortment) || ((ConnectorType)connector.ConnectorType).Has(ConnectorType.WebAssortment))
                {
                    foreach (var language in connector.ConnectorLanguages)
                    {
                        log.DebugFormat("Start Process XML stock export for {0}", connector.Name);

                        string drive        = connector.ConnectorSettings.GetValueByKey("XmlExportPath", string.Empty);
                        bool   networkDrive = false;
                        //string drive = @"\\SOL\Company_Shares\Database Backup";
                        bool.TryParse(connector.ConnectorSettings.GetValueByKey("IsNetorkDrive", "false"), out networkDrive);
                        NetworkExportUtility util = new NetworkExportUtility();

                        if (networkDrive)
                        {
                            drive = util.ConnectorNetworkPath(drive, "I:");
                        }

                        string path = drive;

                        if (!string.IsNullOrEmpty(path))
                        {
                            AssortmentServiceSoapClient soap = new AssortmentServiceSoapClient();

                            XDocument products = new XDocument(soap.GetStockAssortment(connector.ConnectorID, null));

                            string file = Path.Combine(path, string.Format("stock_{0}.xml", connector.ConnectorID));

                            if (File.Exists(file))
                            {
                                File.Delete(file);
                            }

                            products.Save(file, SaveOptions.DisableFormatting);
                        }
                        else
                        {
                            log.AuditCritical(string.Format("Export stock XML failed for {0}, XmlExportPath not set", connector.Name));
                        }

                        if (networkDrive)
                        {
                            util.DisconnectNetworkPath(drive);
                        }

                        log.DebugFormat("Finish Process XML stock import for {0}", connector.Name);
                    }
                }
                #endregion
            }
        }
    protected override void Process()
    {
      using(var unit = GetUnitOfWork()){
      foreach (ConnectorRelation connectorRelation in unit.Scope.Repository<ConnectorRelation>().GetAll(x => x.IsActive && )
      {
        string drive = connector.ConnectorSettings.GetValueByKey("XmlExportPath", string.Empty);
        bool networkDrive = false;
        //string drive = @"\\SOL\Company_Shares\Database Backup";
        bool.TryParse(connector.ConnectorSettings.GetValueByKey("IsNetorkDrive", "false"), out networkDrive);
        NetworkExportUtility util = new NetworkExportUtility();

        if (networkDrive)
        {
          drive = util.ConnectorNetworkPath(drive);
        }

        string path = drive;
        
        #region Assortiment
        if (((ConnectorType)connector.ConnectorType).Has(ConnectorType.ShopAssortment) || ((ConnectorType)connector.ConnectorType).Has(ConnectorType.WebAssortment))
        {
          foreach (var language in connector.ConnectorLanguages)
          {
            log.DebugFormat("Start Process XML Assortment export for {0} language {1}", connector.Name, language.Language.Name);

            if (!string.IsNullOrEmpty(path))
            {
              AssortmentServiceSoapClient soap = new AssortmentServiceSoapClient();

              XDocument products;
              products = XDocument.Parse(soap.GetAdvancedPricingAssortment(connector.ConnectorID, false, false, null, null, true, language.LanguageID));

              string file = Path.Combine(path, string.Format("products_{0}_{1}.xml", connector.ConnectorID, language.LanguageID));

              if (File.Exists(file))
                File.Delete(file);

              products.Save(file, SaveOptions.DisableFormatting);
            }
            else
            {
              log.AuditCritical(string.Format("Export XML failed for {0}, XmlExportPath not set", connector.Name));
            }

            log.DebugFormat("Finish Process XML Assortment import for {0}", connector.Name);
          }
        }
        #endregion

        #region Images
        if (((ConnectorType)connector.ConnectorType).Has(ConnectorType.Images))
        {
          log.DebugFormat("Start Process XML Image export for {0}", connector.Name);

          if (!string.IsNullOrEmpty(path))
          {
            AssortmentServiceSoapClient soap = new AssortmentServiceSoapClient();

            XDocument products;
            products = XDocument.Parse(soap.GetFTPAssortmentImages(connector.ConnectorID));

            string file = Path.Combine(path, string.Format("Images_{0}.xml", connector.ConnectorID));

            if (File.Exists(file))
              File.Delete(file);

            products.Save(file, SaveOptions.DisableFormatting);
          }
          else
          {
            log.AuditCritical(string.Format("Export XML failed for {0}, XmlExportPath not set", connector.Name));
          }

          log.DebugFormat("Finish Process XML Image import for {0}", connector.Name);
        }
        #endregion

        #region content
        if (((ConnectorType)connector.ConnectorType).Has(ConnectorType.Content))
        {
          foreach (var language in connector.ConnectorLanguages)
          {
            log.DebugFormat("Start Process XML Content export for {0} language {1}", connector.Name, language.Language.Name);

           if (!string.IsNullOrEmpty(path))
            {
              AssortmentServiceSoapClient soap = new AssortmentServiceSoapClient();

              XDocument content = XDocument.Parse(soap.GetAssortmentContentDescriptionsByLanguage(connector.ConnectorID, null, language.LanguageID));

              string contentFile = Path.Combine(path, string.Format("Content_{0}_{1}.xml", connector.ConnectorID, language.LanguageID));

              if (File.Exists(contentFile))
                File.Delete(contentFile);

              content.Save(contentFile, SaveOptions.DisableFormatting);

              XDocument attributes = XDocument.Parse(soap.GetAttributesAssortmentByLanguage(connector.ConnectorID, null, null, language.LanguageID));

              string attributeFile = Path.Combine(path, string.Format("Attribute_{0}_{1}.xml", connector.ConnectorID, language.LanguageID));

              if (File.Exists(attributeFile))
                File.Delete(attributeFile);

              attributes.Save(attributeFile, SaveOptions.DisableFormatting);
            }
            else
            {
              log.AuditCritical(string.Format("Export XML failed for {0}, XmlExportPath not set", connector.Name));
            }

            log.DebugFormat("Finish Process XML Content import for {0} language {1}", connector.Name, language.Language.Name);
          }
        }
        #endregion

        if (networkDrive)
        {
          util.DisconnectNetworkPath(drive);
        }
      }
      }
    }
예제 #7
0
        protected override void Process()
        {
            using (var db = new Database(Connection, "System.Data.SqlClient"))
            {
                PfaCommunicatorRepository repo = new PfaCommunicatorRepository(db);

                var vendorsForCommunication = repo.GetVendorsWithPfaCommunication();

                foreach (var vendor in vendorsForCommunication)
                {
                    string remoteFileLocation = string.Empty;
                    NetworkExportUtility util = new NetworkExportUtility(log);
                    try
                    {
                        log.Info("Checking messages for vendor " + vendor.Name);
                        PFACommunicatorHelper helper = new PFACommunicatorHelper(repo, vendor.VendorID);
                        var messageTypes             = helper.GetMessageTypesForVendor();


                        try
                        {
                            remoteFileLocation = util.ConnectorNetworkPath(messageTypes.RemoteDirectory, "O:", messageTypes.UsernameForRemoteDirectory, messageTypes.PasswordForRemoteDirectory);
                        }
                        catch (Exception e)
                        {
                            throw new InvalidOperationException("Could not connect to remote location");
                        }

                        EnsureLocalDirectoryExists(messageTypes.LocalDirectory);
                        EnsureLocalDirectoryExists(messageTypes.ArchiveDirectory);

                        foreach (var message in messageTypes.Messages)
                        {
                            var localDirectory        = Path.Combine(messageTypes.LocalDirectory, message.LocalSubPath);
                            var localArchiveDirectory = Path.Combine(messageTypes.ArchiveDirectory, message.LocalSubPath);

                            EnsureLocalDirectoryExists(localDirectory);
                            EnsureLocalDirectoryExists(localArchiveDirectory);

                            if (message.Incoming)
                            {
                                SyncLocalMessages(message, remoteFileLocation + "\\", messageTypes.LocalDirectory, localArchiveDirectory);
                            }
                            else
                            {
                                SyncRemoteMessages(message, remoteFileLocation + "\\", messageTypes.LocalDirectory, localArchiveDirectory);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        log.AuditError("Something went wrong with Pfa communication for vendor " + vendor.VendorID, e);
                        throw;
                    }
                    finally
                    {
                        util.DisconnectNetworkPath(remoteFileLocation);
                    }
                }
            }
        }