Exemplo n.º 1
0
 protected TNTImporter(Vendor vendor, IUnitOfWork unit, IAuditLogAdapter log)
 {
     Documents = new Dictionary <String, XDocument>();
     Log       = log;
     Unit      = unit;
     Vendor    = vendor;
 }
Exemplo n.º 2
0
 public OrderExporter(Connector connector, IAuditLogAdapter logger, Configuration configuration, Action <int> notifyOrderCount)
 {
     Connector         = connector;
     Logger            = logger;
     Configuration     = configuration;
     _notifyOrderCount = notifyOrderCount;
 }
Exemplo n.º 3
0
        public BaseExporter(Connector connector, IAuditLogAdapter logger)
        {
            Connector = connector;
            Logger    = logger;
            //If OverwriteStockUpdateParentConnectorBehavior is set, the stock will be set for each connector, regardless of parent-child relationship
            RequiresStockUpdate = (!connector.ParentConnectorID.HasValue || connector.ConnectorSettings.GetValueByKey <bool>("OverwriteStockUpdateParentConnectorBehavior", false));



            var version = connector.ConnectorSettings.GetValueByKey <string>("MagentoVersion", string.Empty);

            UsesShortDescAsName                = connector.ConnectorSettings.GetValueByKey <bool>("UsesShortDescAsName", false);
            MagentoIgnoreCategoryDisabling     = connector.ConnectorSettings.GetValueByKey <bool>("MagentoIgnoreCategoryDisabling", false); //If true: is_active won't be disabled
            IgnoreProductStatusUpdates         = Connector.ConnectorSettings.GetValueByKey <bool>("IgnoreProductStatusUpdates", false);
            UsesStoreCodesUniqueOnWebsiteLevel = Connector.ConnectorSettings.GetValueByKey <bool>("StoreCodesUniqueOnWebsiteLevel", false);

            if (string.IsNullOrEmpty(version))
            {
                Version = MagentoVersion.Version_15;
            }
            else
            {
                try
                {
                    Version = (MagentoVersion)Enum.Parse(typeof(MagentoVersion), version);
                }
                catch (Exception e)
                {
                    Version = MagentoVersion.Version_15;
                }
            }
        }
Exemplo n.º 4
0
        public BaseExporter(Connector connector, IAuditLogAdapter logger)
        {
            Connector           = connector;
            Logger              = logger;
            RequiresStockUpdate = !connector.ParentConnectorID.HasValue;

            var version = connector.ConnectorSettings.GetValueByKey <string>("MagentoVersion", string.Empty);

            UsesShortDescAsName                = connector.ConnectorSettings.GetValueByKey <bool>("UsesShortDescAsName", false);
            MagentoIgnoreCategoryDisabling     = connector.ConnectorSettings.GetValueByKey <bool>("MagentoIgnoreCategoryDisabling", false); //If true: is_active won't be disabled
            IgnoreProductStatusUpdates         = Connector.ConnectorSettings.GetValueByKey <bool>("IgnoreProductStatusUpdates", false);
            UsesStoreCodesUniqueOnWebsiteLevel = Connector.ConnectorSettings.GetValueByKey <bool>("StoreCodesUniqueOnWebsiteLevel", false);

            if (string.IsNullOrEmpty(version))
            {
                Version = MagentoVersion.Version_15;
            }
            else
            {
                try
                {
                    Version = (MagentoVersion)Enum.Parse(typeof(MagentoVersion), version);
                }
                catch (Exception e)
                {
                    Version = MagentoVersion.Version_15;
                }
            }
        }
Exemplo n.º 5
0
        public ReportBuilder(
            IAuditLogAdapter auditLogAdapter,
            IAuditLogStorageSinkAdapter auditExportAdapter,
            IComputeEngineAdapter computeEngineAdapter,
            AuditLogSources sources,
            IEnumerable <string> projectIds,
            DateTime startDate)
        {
            var now = DateTime.UtcNow;

            if (startDate >= now)
            {
                throw new ArgumentException("Invalid start date");
            }
            else if ((now - startDate).TotalDays > MaxPeriod)
            {
                throw new ArgumentException("Start date is too far in the past");
            }

            this.sources              = sources;
            this.projectIds           = projectIds;
            this.auditLogAdapter      = auditLogAdapter;
            this.auditExportAdapter   = auditExportAdapter;
            this.computeEngineAdapter = computeEngineAdapter;

            this.builder = new InstanceSetHistoryBuilder(startDate, now);
        }
 public AuditLogStorageSinkAdapter(
     IStorageAdapter storageAdapter,
     IAuditLogAdapter auditLogAdapter)
 {
     this.storageAdapter  = storageAdapter;
     this.auditLogAdapter = auditLogAdapter;
 }
Exemplo n.º 7
0
        public ImageExporter(Connector connector, IAuditLogAdapter logger, Configuration configuration, string serializationPath = "")
            : base(connector, logger)
        {
            Connector = connector;
            Logger    = logger;

            _serializationPath = serializationPath;
        }
Exemplo n.º 8
0
        public void GetAvailableDispatchAdvices(Vendor vendor, IAuditLogAdapter log, string logPath, IUnitOfWork unit)
        {
            try
            {
                FtpManager AcknowledgementManager = new FtpManager(vendor.VendorSettings.GetValueByKey("VSNFtpUrl", string.Empty),
                                                                   "orderresponse/",
                                                                   vendor.VendorSettings.GetValueByKey("VSNUser", string.Empty),
                                                                   vendor.VendorSettings.GetValueByKey("VSNPassword", string.Empty), false, false, log);

                ProcessNotifications(AcknowledgementManager, OrderResponseTypes.Acknowledgement, log, vendor, logPath, unit);
            }
            catch (Exception ex)
            {
                log.AuditWarning("Acknowledment VSN failed", ex);
            }

            try
            {
                FtpManager ShipmentNotificationManager = new FtpManager(vendor.VendorSettings.GetValueByKey("VSNFtpUrl", string.Empty),
                                                                        "pakbonnen/",
                                                                        vendor.VendorSettings.GetValueByKey("VSNUser", string.Empty),
                                                                        vendor.VendorSettings.GetValueByKey("VSNPassword", string.Empty), false, false, log);

                ProcessNotifications(ShipmentNotificationManager, OrderResponseTypes.ShipmentNotification, log, vendor, logPath, unit);
            }
            catch (Exception ex)
            {
                log.Warn("Shipment Notification VSN failed", ex);
            }

            try
            {
                FtpManager InvoiceNotificationManager = new FtpManager(vendor.VendorSettings.GetValueByKey("VSNFtpUrl", string.Empty),
                                                                       vendor.VendorSettings.GetValueByKey("InvoicePath", string.Empty) + "/",
                                                                       vendor.VendorSettings.GetValueByKey("VSNUser", string.Empty),
                                                                       vendor.VendorSettings.GetValueByKey("VSNPassword", string.Empty), false, false, log);

                ProcessInvoiceNotifications(InvoiceNotificationManager, OrderResponseTypes.InvoiceNotification, log, vendor, logPath, unit);
            }
            catch (Exception ex)
            {
                log.AuditWarning("Invoice Notification VSN failed", ex);
            }

            try
            {
                FtpManager CancelNotificationManager = new FtpManager(vendor.VendorSettings.GetValueByKey("VSNFtpUrl", string.Empty),
                                                                      "cancellations/",
                                                                      vendor.VendorSettings.GetValueByKey("VSNUser", string.Empty),
                                                                      vendor.VendorSettings.GetValueByKey("VSNPassword", string.Empty), false, false, log);

                ProcessNotifications(CancelNotificationManager, OrderResponseTypes.CancelNotification, log, vendor, logPath, unit);
            }
            catch (Exception ex)
            {
                log.AuditWarning("Cancel Notification VSN failed", ex);
            }
        }
 public ConfirmShipmentService(
     IOrderRepository orderRepository,
     IArchiveService archiveService,
     IAuditLogAdapter log, IVendorRepository vendorRepo, INotificationHelper notificationHelper)
 {
     _orderRepo          = orderRepository;
     _archiveService     = archiveService;
     _log                = log;
     _vendorRepo         = vendorRepo;
     _notificationHelper = notificationHelper;
 }
Exemplo n.º 10
0
        public XmlAssortmentRepository(int vendorID, IUnitOfWork unit, IAuditLogAdapter log)
        {
            Log       = log;
            Unit      = unit;
            Documents = new Dictionary <string, XDocument>();

            _vendorSetting = Unit
                             .Scope
                             .Repository <VendorSetting>()
                             .GetAll(x => x.VendorID == vendorID)
                             .ToDictionary(item => item.SettingKey, item => item.Value);
        }
Exemplo n.º 11
0
        public void GetAvailableDispatchAdvices(Vendor vendor, IAuditLogAdapter log, String logPath, IUnitOfWork unit)
        {
            var shipmentNotificationImporter = new ShipmentNotificationImporter(vendor, unit, log);

            shipmentNotificationImporter.Execute(GetSourceUri(vendor), vendor);

            var returnNotificationImporter = new ReturnNotificationImporter(vendor, unit, log);

            returnNotificationImporter.Execute(GetSourceUri(vendor), vendor);

            var receivedNotificationImporter = new ReceivedNotificationImporter(vendor, unit, log);

            receivedNotificationImporter.Execute(GetSourceUri(vendor), vendor);
        }
Exemplo n.º 12
0
        public PickTicketService(
            IAuditLogAdapter log,
            IArchiveService archiveService,
            IOrderRepository orderRepo, IVendorRepository vendorRepo,
            IProductRepository productRepo, IOrderHelper orderHelper)
        {
            _log         = log;
            _orderRepo   = orderRepo;
            _productRepo = productRepo;
            _orderHelper = orderHelper;
            _vendorRepo  = vendorRepo;

            _archiveService = archiveService;
        }
Exemplo n.º 13
0
        public ConcentratorPlugin()
        {
            log = new AuditLogAdapter(log4net.LogManager.GetLogger(Name), new AuditLog(new ConcentratorAuditLogProvider()));
            //log = log4net.LogManager.GetLogger(Name);
            environment = Environments.Environments.Current;

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ConcentratorVendorID"]))
            {
                concentratorVendorID = int.Parse(ConfigurationManager.AppSettings["ConcentratorVendorID"].ToString());
            }
            else
            {
                log.Warn("No ConcentratorVendorID set in configuration file");
            }
        }
Exemplo n.º 14
0
        public Int32 DispatchOrders(Dictionary <Order, List <OrderLine> > orders, Vendor vendor, IAuditLogAdapter log, IUnitOfWork unit)
        {
            Log    = log;
            Unit   = unit;
            Vendor = vendor;

            PaymentMethodDescriptions = ((from u in unit.Scope.Repository <PaymentMethod>().GetAll().ToList()
                                          select new
            {
                Code = u.Code,
                Values = (from p in u.PaymentMethodDescriptions
                          select p).ToList()
            }).ToDictionary(c => c.Code, c => c.Values));

            var archiveDirectory = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "Archive"));

            if (!archiveDirectory.Exists)
            {
                archiveDirectory.Create();
            }

            var ftpManager = new FtpManager(GetDestinationUri(vendor), log, usePassive: true);

            foreach (var order in orders)
            {
                var fileName = CreateXmlFileName(order.Key);

                var document = CreatePickTicket(order.Key, order.Value);

                document.Save(Path.Combine(archiveDirectory.FullName, fileName));

                if (document.Element("Pickticket").Element("PickticketDetail") != null)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        document.Save(memoryStream);

                        ftpManager.Upload(memoryStream.Reset(), fileName);
                    }
                }
            }

            return(-1);
        }
Exemplo n.º 15
0
        public void LogOrder(object orderInformation, int vendorID, string fileName, IAuditLogAdapter log)
        {
            try
            {
                var logPath = ConfigurationManager.AppSettings["ConcentratorOrderLog"];

                logPath = Path.Combine(logPath, DateTime.Now.ToString("yyyyMMdd"), vendorID.ToString());

                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }

                ((XDocument)orderInformation).Save(Path.Combine(logPath, fileName));
            }
            catch (Exception ex)
            {
                log.AuditError("Failed to log order information for " + vendorID, ex);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes a new pipeline and appies all the rules to the order lines.
        /// The VendorOrderLines Dict is populated
        /// </summary>
        /// <param name="OrderLines">A list of order lines to be dispatched</param>
        /// <param name="context">A data context instance to use for lookup and marking of the dispatched orderlines</param>
        /// <param name="VendorIDs">All vendor ids to include when applying the rules.Defaults to all assortment vendors</param>
        public RulePipeline(List <OrderLine> OrderLines, IUnitOfWork unit, List <int> VendorIDs, IAuditLogAdapter log)
        {
            orderLines = OrderLines;
            this.unit  = unit;
            this.log   = log;

            if (VendorIDs == null)
            {
                var v = this.unit.Scope.Repository <Vendor>().GetAll().ToList();

                vendors   = v;
                vendorIDs = v.Where(x => ((VendorType)x.VendorType).Has(VendorType.Assortment) && x.IsActive && x.OrderDispatcherType != null).Select(x => x.VendorID).ToList();
            }
            else
            {
                vendorIDs = VendorIDs;
            }


            VendorOrderLines = new Dictionary <int, List <OrderLine> >();
            Exceptions       = new List <Exception>();
            LoadVendorOrderRules();
        }
Exemplo n.º 17
0
        public void GetAvailableDispatchAdvices(Vendor vendor, IAuditLogAdapter log, string logPath, IUnitOfWork unit)
        {
            FtpManager AcknowledgementManager = new FtpManager(vendor.VendorSettings.GetValueByKey("AlphaFtpUrl", string.Empty),
                                                               vendor.VendorSettings.GetValueByKey("AlphaRemoteResponseDirectory", string.Empty),
                                                               vendor.VendorSettings.GetValueByKey("AlphaUserName", string.Empty),
                                                               vendor.VendorSettings.GetValueByKey("AlphaPassword", string.Empty), false, false, null);

            ProcessNotifications(AcknowledgementManager, OrderResponseTypes.Acknowledgement, log, vendor, logPath, unit);

            FtpManager ShipmentNotificationManager = new FtpManager(vendor.VendorSettings.GetValueByKey("AlphaFtpUrl", string.Empty),
                                                                    vendor.VendorSettings.GetValueByKey("AlphaRemoteDispadviceDirectory", string.Empty),
                                                                    vendor.VendorSettings.GetValueByKey("AlphaUserName", string.Empty),
                                                                    vendor.VendorSettings.GetValueByKey("AlphaPassword", string.Empty), false, false, null);

            ProcessNotifications(ShipmentNotificationManager, OrderResponseTypes.ShipmentNotification, log, vendor, logPath, unit);

            FtpManager InvoiceNotificationManager = new FtpManager(vendor.VendorSettings.GetValueByKey("AlphaFtpUrl", string.Empty),
                                                                   vendor.VendorSettings.GetValueByKey("AlphaRemoteInvoiceDirectory", string.Empty),
                                                                   vendor.VendorSettings.GetValueByKey("AlphaUserName", string.Empty),
                                                                   vendor.VendorSettings.GetValueByKey("AlphaPassword", string.Empty), false, false, null);

            ProcessNotifications(InvoiceNotificationManager, OrderResponseTypes.InvoiceNotification, log, vendor, logPath, unit);
        }
Exemplo n.º 18
0
        public int DispatchOrders(Dictionary <Concentrator.Objects.Models.Orders.Order, List <OrderLine> > orderLines, Vendor vendor, IAuditLogAdapter log, IUnitOfWork unit)
        {
            try
            {
                var    orders = new BasOrderExporter().GetOrder(orderLines, vendor);
                int    msgID  = 0;
                string ediUrl = vendor.VendorSettings.GetValueByKey("EDIUrl", string.Empty);

                if (string.IsNullOrEmpty(ediUrl))
                {
                    throw new Exception("Unable process orders empty EDI url for BasDispatcher");
                }

                foreach (var order in orders)
                {
                    StringBuilder     requestString = new StringBuilder();
                    XmlWriterSettings settings      = new XmlWriterSettings();
                    settings.Encoding = Encoding.UTF8;
                    using (XmlWriter xw = XmlWriter.Create(requestString, settings))
                    {
                        xw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
                        XmlSerializer           serializer = new XmlSerializer(typeof(WebOrderRequest));
                        XmlSerializerNamespaces nm         = new XmlSerializerNamespaces();
                        nm.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                        serializer.Serialize(xw, order, nm);

                        XmlDocument document = new XmlDocument();
                        document.LoadXml(requestString.ToString());
                        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ediUrl);
                        request.Method = "POST";

                        HttpPostState state = new HttpPostState(orderLines, order.WebOrderDetails.Select(x => x.CustomerReference), request);

                        byte[] byteData = UTF8Encoding.UTF8.GetBytes(document.OuterXml);
                        using (Stream s = request.GetRequestStream())
                        {
                            s.Write(byteData, 0, byteData.Length);
                        }

                        IAsyncResult result = request.BeginGetResponse(HttpCallBack, state);
                        result.AsyncWaitHandle.WaitOne();

                        if (order.WebOrderHeader != null && !string.IsNullOrEmpty(order.WebOrderHeader.CustomerOrderReference))
                        {
                            LogOrder(document, vendor.VendorID, string.Format("{0}.xml", order.WebOrderHeader.WebSiteOrderNumber), log);
                        }
                    }
                }
                return(msgID);
            }
            catch (Exception e)
            {
                throw new Exception("Bas dispatching failed", e);
            }
        }
Exemplo n.º 19
0
        private void ProcessNotifications(FtpManager manager, OrderResponseTypes responseType, IAuditLogAdapter log, Vendor vendor, string logPath, IUnitOfWork unit)
        {
            foreach (var file in manager)
            {
                try
                {
                    using (MemoryStream fileStream = new MemoryStream(ReadFully(file.Data)))
                    {
                        string fileName = "VSN_" + responseType.ToString() + "_" + Guid.NewGuid() + ".csv";
                        using (FileStream s = File.Create(Path.Combine(logPath, fileName)))
                        {
                            s.Write(fileStream.ToArray(), 0, (int)fileStream.Length);
                        }

                        int orderID = 0;
                        var parser  = GetCSVFile(fileStream, responseType);

                        var groupedOrders = (from p in parser
                                             group p by p["CustomerReference"] into od
                                             select new
                        {
                            OrderID = od.Key,
                            OrderInf = od.ToList()
                        }).ToDictionary(x => x.OrderID, x => x.OrderInf);

                        string vsnResponseType = responseType.ToString();
                        foreach (var orderResp in groupedOrders)
                        {
                            int.TryParse(orderResp.Key, out orderID);

                            var order = unit.Scope.Repository <Concentrator.Objects.Models.Orders.Order>().GetSingle(o => o.OrderID == orderID);

                            OrderResponse response = null;

                            if (order != null)
                            {
                                var responseHeader   = orderResp.Value.FirstOrDefault();
                                int orderLineCounter = 0;

                                switch (responseType)
                                {
                                case OrderResponseTypes.Acknowledgement:
                                    #region Acknowledgement
                                    response = new OrderResponse()
                                    {
                                        Currency             = "EUR",
                                        ResponseType         = responseType.ToString(),
                                        OrderID              = orderID,
                                        OrderDate            = DateTime.ParseExact(responseHeader[VSNAcknowledgement.OrderDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                        VendorDocumentNumber = responseHeader[VSNAcknowledgement.SalesOrderID.ToString()]
                                    };

                                    foreach (var line in orderResp.Value)
                                    {
                                        int    lineReference  = 0;
                                        string referenceField = line[VSNAcknowledgement.CustomerLineReference.ToString()];
                                        if (referenceField.Contains('/'))
                                        {
                                            int.TryParse(referenceField.Split('/')[0], out lineReference);
                                        }
                                        else
                                        {
                                            int.TryParse(referenceField, out lineReference);
                                        }

                                        //int.TryParse(line[VSNAcknowledgement.CustomerLineReference.ToString()], out lineReference);

                                        OrderLine oLine = order.OrderLines.Where(x => x.OrderLineID == lineReference).FirstOrDefault();

                                        if (oLine == null)
                                        {
                                            string vendorItemNumber = line[VSNAcknowledgement.EANNumber.ToString()];
                                            oLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber).FirstOrDefault();
                                        }

                                        if (oLine != null && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType))
                                        {
                                            OrderResponseLine rLine = new OrderResponseLine()
                                            {
                                                OrderResponse    = response,
                                                Backordered      = StatusCodes(line[VSNAcknowledgement.StatusCode.ToString()]) == VSNStatusCode.Backorder ? int.Parse(line[VSNAcknowledgement.Quantity.ToString()]) : 0,
                                                Cancelled        = StatusCodes(line[VSNAcknowledgement.StatusCode.ToString()]) == VSNStatusCode.Canceled ? int.Parse(line[VSNAcknowledgement.Quantity.ToString()]) : 0,
                                                Ordered          = oLine.GetDispatchQuantity(),
                                                Description      = line[VSNAcknowledgement.ProductName.ToString()],
                                                Invoiced         = 0,
                                                Barcode          = line[VSNAcknowledgement.EANNumber.ToString()],
                                                OrderLine        = oLine,
                                                Price            = ((decimal)(oLine.Price.HasValue ? oLine.Price.Value : 0)),
                                                Processed        = false,
                                                Shipped          = StatusCodes(line[VSNAcknowledgement.StatusCode.ToString()]) == VSNStatusCode.Picklist ? int.Parse(line[VSNAcknowledgement.Quantity.ToString()]) : 0,
                                                VendorItemNumber = line[VSNAcknowledgement.ProductCode.ToString()],
                                                Remark           = string.Format("ReleaseDate {0}", line[VSNAcknowledgement.ReleaseDate.ToString()])
                                            };

                                            unit.Scope.Repository <OrderResponseLine>().Add(rLine);
                                            orderLineCounter++;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    #endregion
                                    break;

                                case OrderResponseTypes.CancelNotification:
                                    #region CancelNotification
                                    response = new OrderResponse()
                                    {
                                        Currency             = "EUR",
                                        ResponseType         = responseType.ToString(),
                                        OrderID              = orderID,
                                        OrderDate            = DateTime.ParseExact(responseHeader[VSNCancel.OrderDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                        VendorDocumentNumber = responseHeader[VSNCancel.SalesOrderID.ToString()],
                                        VendorDocumentDate   = DateTime.ParseExact(responseHeader[VSNCancel.Timestamp.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture)
                                    };

                                    foreach (var line in orderResp.Value)
                                    {
                                        int    lineReference  = 0;
                                        string referenceField = line[VSNCancel.CustomerLineReference.ToString()];
                                        if (referenceField.Contains('/'))
                                        {
                                            int.TryParse(referenceField.Split('/')[0], out lineReference);
                                        }
                                        else
                                        {
                                            int.TryParse(referenceField, out lineReference);
                                        }

                                        OrderLine oLine = order.OrderLines.Where(x => x.OrderLineID == lineReference).FirstOrDefault();

                                        if (oLine == null)
                                        {
                                            string vendorItemNumber = line[VSNAcknowledgement.EANNumber.ToString()];
                                            oLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber).FirstOrDefault();
                                        }

                                        if (oLine != null && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType))
                                        {
                                            OrderResponseLine rLine = new OrderResponseLine()
                                            {
                                                OrderResponse    = response,
                                                Backordered      = 0,
                                                Cancelled        = int.Parse(line[VSNCancel.Quantity.ToString()]),
                                                Ordered          = oLine.GetDispatchQuantity(),
                                                Description      = line[VSNCancel.ProductName.ToString()],
                                                Invoiced         = 0,
                                                Barcode          = line[VSNCancel.EANNumber.ToString()],
                                                OrderLine        = oLine,
                                                Price            = ((decimal)(oLine.Price.HasValue ? oLine.Price.Value : 0)),
                                                Processed        = false,
                                                Shipped          = 0,
                                                VendorItemNumber = line[VSNCancel.ProductCode.ToString()],
                                                Remark           = line[VSNCancel.SalesOrderLineCancelReason.ToString()]
                                            };

                                            unit.Scope.Repository <OrderResponseLine>().Add(rLine);
                                            orderLineCounter++;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    #endregion
                                    break;

                                case OrderResponseTypes.ShipmentNotification:
                                    #region ShipmentNotification
                                    response = new OrderResponse()
                                    {
                                        Currency             = "EUR",
                                        ResponseType         = responseType.ToString(),
                                        OrderID              = orderID,
                                        OrderDate            = DateTime.ParseExact(responseHeader[VSNShipment.OrderDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                        VendorDocumentNumber = responseHeader[VSNShipment.SalesOrderID.ToString()],
                                        ShippingNumber       = responseHeader[VSNShipment.PackListID.ToString()],
                                        ReqDeliveryDate      = DateTime.ParseExact(responseHeader[VSNShipment.PacklistDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture)
                                    };

                                    Customer cus = order.ShippedToCustomer;

                                    if (cus.CustomerName != responseHeader[VSNShipment.AddressName.ToString()] ||
                                        cus.CustomerAddressLine1 != responseHeader[VSNShipment.Street.ToString()] ||
                                        cus.HouseNumber != responseHeader[VSNShipment.HouseNumber.ToString()] ||
                                        cus.PostCode.Replace(" ", "").ToUpper() != responseHeader[VSNShipment.ZipCode.ToString()].Replace(" ", "").ToUpper() ||
                                        cus.City.ToUpper() != responseHeader[VSNShipment.City.ToString()] ||
                                        (!string.IsNullOrEmpty(responseHeader[VSNShipment.CountryName.ToString()]) && cus.Country != responseHeader[VSNShipment.CountryName.ToString()]))
                                    {
                                        cus = new Customer()
                                        {
                                            CustomerName         = responseHeader[VSNShipment.AddressName.ToString()],
                                            CustomerAddressLine1 = responseHeader[VSNShipment.Street.ToString()],
                                            HouseNumber          = responseHeader[VSNShipment.HouseNumber.ToString()],
                                            PostCode             = responseHeader[VSNShipment.ZipCode.ToString()],
                                            Country = responseHeader[VSNShipment.CountryName.ToString()],
                                            City    = responseHeader[VSNShipment.City.ToString()]
                                        }
                                    }
                                    ;

                                    response.ShippedToCustomer = cus;

                                    foreach (var line in orderResp.Value)
                                    {
                                        int    lineReference  = 0;
                                        string referenceField = line[VSNShipment.CustomerLineReference.ToString()];
                                        if (referenceField.Contains('/'))
                                        {
                                            int.TryParse(referenceField.Split('/')[0], out lineReference);
                                        }
                                        else
                                        {
                                            int.TryParse(referenceField, out lineReference);
                                        }

                                        OrderLine oLine = order.OrderLines.Where(x => x.OrderLineID == lineReference).FirstOrDefault();

                                        if (oLine == null)
                                        {
                                            string vendorItemNumber = line[VSNAcknowledgement.EANNumber.ToString()];
                                            oLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber).FirstOrDefault();
                                        }

                                        if (oLine != null && (!oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType) ||
                                                              (!string.IsNullOrEmpty(line[VSNShipment.LabelReference.ToString()]) && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == responseType.ToString() && !string.IsNullOrEmpty(x.TrackAndTrace)))))
                                        {
                                            OrderResponseLine rLine = new OrderResponseLine()
                                            {
                                                OrderResponse     = response,
                                                Backordered       = 0,
                                                Cancelled         = 0,
                                                Ordered           = oLine.GetDispatchQuantity(),
                                                Description       = line[VSNShipment.ProductName.ToString()],
                                                Invoiced          = 0,
                                                Barcode           = line[VSNShipment.EANNumber.ToString()],
                                                OrderLine         = oLine,
                                                Price             = ((decimal)(oLine.Price.HasValue ? oLine.Price.Value : 0)),
                                                Processed         = false,
                                                Shipped           = int.Parse(line[VSNShipment.Quantity.ToString()]),
                                                VendorItemNumber  = line[VSNShipment.ProductCode.ToString()],
                                                NumberOfUnits     = line[VSNShipment.PackageType.ToString()] == "Doos" ? int.Parse(line[VSNShipment.PackageCount.ToString()]) : 0,
                                                NumberOfPallets   = line[VSNShipment.PackageType.ToString()] != "Doos" ? int.Parse(line[VSNShipment.PackageCount.ToString()]) : 0,
                                                Unit              = line[VSNShipment.PackageType.ToString()],
                                                Remark            = string.Format("ReleaseDate {0}", line[VSNShipment.ReleaseDate.ToString()]),
                                                TrackAndTrace     = line[VSNShipment.LabelReference.ToString()],
                                                TrackAndTraceLink = string.IsNullOrEmpty(line[VSNShipment.LabelReference.ToString()]) ? string.Empty : BuildTrackAndTraceNumber(line[VSNShipment.LabelReference.ToString()], responseHeader[VSNShipment.ZipCode.ToString()].Replace(" ", "").ToUpper())
                                            };

                                            unit.Scope.Repository <OrderResponseLine>().Add(rLine);
                                            orderLineCounter++;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    #endregion
                                    break;
                                }

                                if (orderLineCounter > 0)
                                {
                                    response.VendorID       = vendor.VendorID;
                                    response.ReceiveDate    = DateTime.Now;
                                    response.VendorDocument = parser.Document;
                                    response.DocumentName   = fileName;
                                    if (!response.VendorDocumentDate.HasValue)
                                    {
                                        response.VendorDocumentDate = DateTime.Now;
                                    }

                                    response.ReceiveDate = DateTime.Now;

                                    unit.Scope.Repository <OrderResponse>().Add(response);
                                }
                            }
                        }


                        unit.Save();
                        manager.Delete(file.FileName);
                    }
                }
                catch (Exception ex)
                {
                    log.AuditError("Error reading file", ex);
                }
            }
        }
Exemplo n.º 20
0
        public int DispatchOrders(Dictionary <Concentrator.Objects.Models.Orders.Order, List <OrderLine> > orderLines, Vendor vendor, IAuditLogAdapter log, IUnitOfWork unit)
        {
            try
            {
                var orderDoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
                                             new XElement("SalesOrders",
                                                          from o in orderLines
                                                          select new XElement("SalesOrder",
                                                                              new XElement("CustomerCode", vendor.VendorSettings.GetValueByKey("VSNUser", string.Empty)),
                                                                              new XElement("Reference", o.Key.OrderID),
                                                                              new XElement("DeliveryDate", DateTime.Now.ToString("dd-MM-yyyy")),
                                                                              new XElement("DeliveryAddress",
                                                                                           new XElement("AddressName", o.Key.ShippedToCustomer.CustomerName),
                                                                                           new XElement("Street", o.Key.ShippedToCustomer.CustomerAddressLine1),
                                                                                           new XElement("HouseNumber", o.Key.ShippedToCustomer.HouseNumber),
                                                                                           new XElement("ZipCode", o.Key.ShippedToCustomer.PostCode.Length < 7 ? o.Key.ShippedToCustomer.PostCode.Substring(0, 4) + " " + o.Key.ShippedToCustomer.PostCode.Substring(4, 2).ToUpper() : o.Key.ShippedToCustomer.PostCode.ToUpper()),
                                                                                           new XElement("City", o.Key.ShippedToCustomer.City),
                                                                                           new XElement("CountryCode", o.Key.ShippedToCustomer.Country)),
                                                                              from ol in o.Value
                                                                              let vendorAss = VendorUtility.GetMatchedVendorAssortment(unit.Scope.Repository <VendorAssortment>(), vendor.VendorID, ol.ProductID.Value)
                                                                                              let purchaseLine = ol.OrderResponseLines.Where(x => x.OrderLineID == ol.OrderLineID && x.OrderResponse.ResponseType == OrderResponseTypes.PurchaseAcknowledgement.ToString()).FirstOrDefault()
                                                                                                                 select new XElement("SalesOrderLine",
                                                                                                                                     new XElement("ProductCode", vendorAss.CustomItemNumber),
                                                                                                                                     new XElement("Quantity", ol.GetDispatchQuantity()),
                                                                                                                                     new XElement("Reference", ol.OrderLineID + "/" + ol.Order.WebSiteOrderNumber)//(purchaseLine != null ? purchaseLine.VendorItemNumber : vendorAss.ProductID.ToString()))
                                                                                                                                     )
                                                                              )
                                                          )
                                             );

                var ftp = new FtpManager(vendor.VendorSettings.GetValueByKey("VSNFtpUrl", string.Empty), "orders/",
                                         vendor.VendorSettings.GetValueByKey("VSNUser", string.Empty),
                                         vendor.VendorSettings.GetValueByKey("VSNPassword", string.Empty), false, false, log);
                var fileName = String.Format("{0}.xml", DateTime.Now.ToString("yyyyMMddhhmmss"));

                using (var inStream = new MemoryStream())
                {
                    using (XmlWriter writer = XmlWriter.Create(inStream))
                    {
                        orderDoc.WriteTo(writer);
                        writer.Flush();
                    }
                    ftp.Upload(inStream, fileName);
                }

                LogOrder(orderDoc, vendor.VendorID, fileName, log);

                return(-1);
            }
            catch (Exception e)
            {
                throw new Exception("VSN dispatching failed", e);
            }
        }
Exemplo n.º 21
0
 static VSNDispatcher()
 {
     log = new AuditLogAdapter(log4net.LogManager.GetLogger(typeof(VSNDispatcher)), new AuditLog(new ConcentratorAuditLogProvider()));
 }
Exemplo n.º 22
0
        private void ProcessInvoiceNotifications(FtpManager manager, OrderResponseTypes responseType, IAuditLogAdapter log, Vendor vendor, string logPath, IUnitOfWork unit)
        {
            foreach (var file in manager)
            {
                try
                {
                    using (MemoryStream fileStream = new MemoryStream(ReadFully(file.Data)))
                    {
                        string fileName = "VSN_" + responseType.ToString() + "_" + Guid.NewGuid() + ".csv";
                        string filePath = Path.Combine(logPath, fileName);
                        using (FileStream s = File.Create(filePath))
                        {
                            s.Write(fileStream.ToArray(), 0, (int)fileStream.Length);
                        }

                        using (System.IO.TextReader readFile = new StreamReader(filePath))
                        {
                            string line = string.Empty;

                            using (MemoryStream salesLines = new MemoryStream(),
                                   salesInvoiceTotal = new MemoryStream(),
                                   salesInvoiceGrandTotal = new MemoryStream())
                            {
                                using (
                                    StreamWriter sw = new StreamWriter(salesLines),
                                    sw2 = new StreamWriter(salesInvoiceTotal),
                                    sw3 = new StreamWriter(salesInvoiceGrandTotal))
                                {
                                    int lineCount = 0;
                                    while ((line = readFile.ReadLine()) != null)
                                    {
                                        lineCount++;

                                        if (line.Contains("SalesInvoiceLine") || lineCount == 1)
                                        {
                                            sw.WriteLine(line);
                                        }
                                        else if (line.Contains("SalesInvoiceTotal"))
                                        {
                                            sw2.WriteLine(line);
                                        }
                                        else if (line.Contains("SalesInvoiceGrandTotal"))
                                        {
                                            sw3.WriteLine(line);
                                        }
                                        else if (!line.Contains("SalesInvoiceLine") && lineCount > 1 && !line.Contains("SalesInvoiceGrandTotal"))
                                        {
                                            sw3.WriteLine(line);
                                        }
                                    }

                                    sw.Flush();
                                    salesLines.Position = 0;
                                    sw2.Flush();
                                    salesInvoiceTotal.Position = 0;
                                    sw3.Flush();
                                    salesInvoiceGrandTotal.Position = 0;

                                    var parser                  = GetInvoiceCSVFile(salesLines, typeof(VSNInvoice)).ToList();
                                    var invoiveTotalParser      = GetInvoiceCSVFile(salesInvoiceTotal, typeof(VSNInvoiceTotal));
                                    var invoiceGrandTotalParser = GetInvoiceCSVFile(salesInvoiceGrandTotal, typeof(VSNInvoiceGrandTotal));

                                    var firstOrderInInvoice = parser.FirstOrDefault();
                                    var invoiceTotals       = invoiveTotalParser.ToList();
                                    int orderLineCounter    = 0;

                                    var totalAmount   = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVATIncluded.ToString()]));
                                    var totalExVat    = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVATExcluded.ToString()]));
                                    var vatAmount     = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVAT.ToString()]));
                                    var vatPercentage = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.VATPercentage.ToString()]));
                                    var shipmentCost  = invoiceTotals.Where(x => x[VSNInvoiceTotal.SalesInvoiceTotal.ToString()].Trim().ToLower() == "orderkosten").Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVATExcluded.ToString()]));

                                    #region InvoiceNotification
                                    var           vsnResponseType = responseType.ToString();
                                    var           vsnInvoiceID    = firstOrderInInvoice[VSNInvoice.SalesInvoiceID.ToString()];
                                    OrderResponse response        = unit.Scope.Repository <OrderResponse>().GetSingle(x => x.VendorID == vendor.VendorID && x.InvoiceDocumentNumber == vsnInvoiceID && x.ResponseType == vsnResponseType);

                                    if (response == null)
                                    {
                                        response = new OrderResponse()
                                        {
                                            Currency     = "EUR",
                                            ResponseType = responseType.ToString(),
                                            //OrderID = orderID,
                                            VendorDocumentNumber     = string.Empty,
                                            InvoiceDate              = DateTime.ParseExact(firstOrderInInvoice[VSNInvoice.InvoiceDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                            InvoiceDocumentNumber    = firstOrderInInvoice[VSNInvoice.SalesInvoiceID.ToString()],
                                            ShippingNumber           = firstOrderInInvoice[VSNInvoice.PacklistID.ToString()],
                                            PaymentConditionCode     = firstOrderInInvoice[VSNInvoice.PatymentConditionName.ToString()],
                                            ReqDeliveryDate          = DateTime.ParseExact(firstOrderInInvoice[VSNInvoice.PacklistDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                            PaymentConditionDiscount = firstOrderInInvoice[VSNInvoice.DiscountPercentage.ToString()],
                                            TotalAmount              = totalAmount,
                                            TotalExVat    = totalExVat,
                                            VatAmount     = vatAmount,
                                            VatPercentage = vatPercentage,
                                            ShipmentCost  = shipmentCost
                                        };
                                    }

                                    foreach (var p in parser)
                                    {
                                        try
                                        {
                                            int    lineReference  = 0;
                                            string referenceField = p[VSNInvoice.LineCustomerReference.ToString()];
                                            if (referenceField.Contains('/'))
                                            {
                                                int.TryParse(referenceField.Split('/')[0], out lineReference);
                                            }
                                            else
                                            {
                                                int.TryParse(referenceField, out lineReference);
                                            }

                                            OrderLine oLine = unit.Scope.Repository <OrderLine>().GetSingle(x => x.OrderLineID == lineReference);

                                            if (oLine != null && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType))
                                            {
                                                OrderResponseLine rLine = new OrderResponseLine()
                                                {
                                                    OrderResponse = response,
                                                    Backordered   = 0,
                                                    Cancelled     = 0,
                                                    Ordered       = oLine.GetDispatchQuantity(),
                                                    Invoiced      = int.Parse(p[VSNInvoice.Quantity.ToString()]),
                                                    Barcode       = p[VSNInvoice.EANNumberProduct.ToString()],
                                                    OrderLine     = oLine,
                                                    Price         = decimal.Parse(p[VSNInvoice.PriceDiscountIncluded.ToString()]),
                                                    VatAmount     = decimal.Parse(p[VSNInvoice.LineTotal.ToString()]),
                                                    vatPercentage = decimal.Parse(p[VSNInvoice.VATPercentage.ToString()]),
                                                    CarrierCode   = p[VSNInvoice.DeliveryMethodName.ToString()],
                                                    Processed     = false,
                                                    Shipped       = 0,
                                                    Remark        = p[VSNInvoice.CustomerReference.ToString()]
                                                };

                                                unit.Scope.Repository <OrderResponseLine>().Add(rLine);
                                                orderLineCounter++;
                                            }

                                            #endregion
                                        }
                                        catch (Exception)
                                        {
                                            log.AuditError("Failed to invoice line for VSN");
                                        }
                                    }

                                    if (orderLineCounter > 0)
                                    {
                                        response.VendorID       = vendor.VendorID;
                                        response.ReceiveDate    = DateTime.Now;
                                        response.VendorDocument = parser + invoiveTotalParser.Document + invoiceGrandTotalParser.Document;
                                        response.DocumentName   = fileName;
                                        if (!response.VendorDocumentDate.HasValue)
                                        {
                                            response.VendorDocumentDate = DateTime.Now;
                                        }

                                        response.ReceiveDate = DateTime.Now;

                                        unit.Scope.Repository <OrderResponse>().Add(response);
                                    }

                                    unit.Save();
                                    manager.Delete(file.FileName);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.AuditError("Error reading file", ex);
                }
            }
        }
Exemplo n.º 23
0
 public void CancelOrder(Vendor vendor, IAuditLogAdapter log, string logPath)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 24
0
 public AtPFARepository(string connectionString, IAuditLogAdapter logger)
     : base(connectionString, logger)
 {
 }
Exemplo n.º 25
0
 public ImageExporter(Connector connector, IAuditLogAdapter logger, Configuration configuration)
     : base(connector, logger)
 {
     Connector = connector;
     Logger    = logger;
 }
Exemplo n.º 26
0
 public void GetAvailableDispatchAdvices(Vendor vendor, IAuditLogAdapter log, string logPath, IUnitOfWork unit)
 {
 }
Exemplo n.º 27
0
        string DownloadImage(Uri source, TElSimpleSFTPClient client, string basePath, IAuditLogAdapter Logger)
        {
            string fileName = System.Web.HttpUtility.UrlDecode(source.Segments.Last()).Replace(" ", "");

            string exportFilePath = String.Format(@"{0}\{1}\{2}", fileName.Substring(0, 1),
                                                  fileName.Substring(1, 1),
                                                  fileName);
            string serverPath = String.Format(@"/{0}/{1}/{2}", fileName.Substring(0, 1),
                                              fileName.Substring(1, 1),
                                              fileName);

            string magentoPath = String.Format(@"\{0}\{1}", fileName.Substring(0, 1),
                                               fileName.Substring(1, 1));

            try
            {
                using (WebClient dlClient = new WebClient())
                {
                    using (var stream = new MemoryStream(dlClient.DownloadData(source)))
                    {
                        client.UploadStream(stream, basePath + serverPath, SBUtils.TSBFileTransferMode.ftmOverwrite);
                        //client.SetAttributes(basePath + serverPath, SftpHelper.DefaultAttributes);
                    }
                }
            }
            catch (Exception e)
            {
                return(null);
            }
            return(serverPath);
        }
Exemplo n.º 28
0
        public ProcessPurchaseOrderReceivedConfirmation()
        {
            _log = new AuditLogAdapter(log4net.LogManager.GetLogger("Logger"), new AuditLog(new ConcentratorAuditLogProvider()));

            Bootstrapper();
        }
 public ShipmentNotificationImporter(Vendor vendor, IUnitOfWork unit, IAuditLogAdapter logAdapter)
     : base(vendor, unit, logAdapter)
 {
 }
 public CoolcatPFARepository(string connectionString, string vrdsConnectionString, IAuditLogAdapter logger)
     : base(connectionString, logger)
 {
     _vrdsConnectionString = vrdsConnectionString;
 }