public void Process()
        {
            _vendorSapph = _vendorRepo
                           .GetVendor(SapphVendorName);

            if (_vendorSapph == null)
            {
                _log.AuditError("Vendor Sapph does not exist. Please insert vendor Sapph.");

                return;
            }

            var vendorSettings = _vendorSapph.VendorSettings.ToDictionary(x => x.SettingKey, x => x.Value);

            if (!vendorSettings.ContainsKey(SettingKeyRelatedConnectorID))
            {
                _log.AuditError("SettingKey RelatedConnectorID for vendor Sapph does not exist. Please insert VendorSetting RelatedConnectorID for vendor Sapph.");

                return;
            }

            if (!int.TryParse(vendorSettings[SettingKeyRelatedConnectorID], NumberStyles.Integer, new CultureInfo("en-US"), out _sapphConnectorID))
            {
                _log.AuditError(string.Format("SettingKey RelatedConnectorID for vendor Sapph has not integer value '{0}'. Please change the value.", vendorSettings[SettingKeyRelatedConnectorID]));

                return;
            }

            ProcessNotifications();
        }
        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);
            }
        }
示例#3
0
        public void Execute()
        {
            using (var unit = GetUnitOfWork())
            {
                Concentrator.Objects.Web.Client.Login(Concentrator.Objects.Web.ConcentratorPrincipal.SystemPrincipal);

                var _repoConnectors = unit.Scope.Repository <Connector>();

                // filter connectors based on the optional attribute on Plugin level
                var att = GetType().GetCustomAttributes(typeof(ConnectorSystemAttribute), true);

                if (att.Length > 0)
                {
                    var attributevalue = ((ConnectorSystemAttribute)att[0]).ConnectorSystem;
                    _connectors = _repoConnectors.Include(x => x.ConnectorSettings).Include("ConnectorLanguages.Language").GetAll(c => c.ConnectorSystemID.HasValue && c.ConnectorSystem.Name == attributevalue).ToList();
                }
                else
                {
                    try
                    {
                        _connectors = _repoConnectors.Include(x => x.ConnectorSettings).Include("ConnectorLanguages.Language").GetAll().ToList();
                    }
                    catch (Exception e)
                    {
                        log.Debug(e.InnerException);
                    }
                }

                _vendors = unit.Scope.Repository <Vendor>().GetAll().ToList();
            }
            try
            {
                Process();
            }
            catch (Exception e)
            {
                log.AuditError("Plugin failed " + Name + " .", e);
            }
        }
示例#4
0
        public void Process()
        {
            var vendorSapph = _vendorRepo
                              .GetVendor(SapphVendorName);

            if (vendorSapph == null)
            {
                _log.AuditError("Vendor Sapph does not exist. Please insert vendor Sapph.");

                return;
            }

            var vendorSettings = vendorSapph.VendorSettings.ToDictionary(x => x.SettingKey, x => x.Value);

            if (!vendorSettings.ContainsKey(RelatedConnectorID))
            {
                _log.AuditError("SettingKey RelatedConnectorID for vendor Sapph does not exist. Please insert VendorSetting RelatedConnectorID for vendor Sapph.");

                return;
            }

            if (!int.TryParse(vendorSettings[RelatedConnectorID], NumberStyles.Integer, new CultureInfo("en-US"), out _sapphConnectorID))
            {
                _log.AuditError(string.Format("SettingKey RelatedConnectorID for vendor Sapph has not integer value '{0}'. Please change the value.", vendorSettings[RelatedConnectorID]));

                return;
            }

            if (!vendorSettings.ContainsKey(PathSettingKey))
            {
                _log.AuditError(string.Format("SettingKey '{0}' for vendor Sapph does not exist. Please insert VendorSetting '{0}' for vendor Sapph.", PathSettingKey));

                return;
            }

            if (!vendorSettings.ContainsKey(FtpAddressSettingKey))
            {
                _log.AuditError(string.Format("SettingKey '{0}' for vendor Sapph does not exist. Please insert VendorSetting '{0}' for vendor Sapph.", FtpAddressSettingKey));

                return;
            }

            if (!vendorSettings.ContainsKey(FtpUsernameSettingKey))
            {
                _log.AuditError(string.Format("SettingKey '{0}' for vendor Sapph does not exist. Please insert VendorSetting '{0}' for vendor Sapph.", FtpUsernameSettingKey));

                return;
            }

            if (!vendorSettings.ContainsKey(FtpPasswordSettingKey))
            {
                _log.AuditError(string.Format("SettingKey '{0}' for vendor Sapph does not exist. Please insert VendorSetting '{0}' for vendor Sapph.", FtpPasswordSettingKey));

                return;
            }

#if DEBUG
            _ftpSetting.Path = vendorSettings[PathSettingKey].Replace("Staging", "Test");
#else
            _ftpSetting.Path = vendorSettings[PathSettingKey];
#endif
            _ftpSetting.FtpAddress  = vendorSettings[FtpAddressSettingKey];
            _ftpSetting.FtpUsername = vendorSettings[FtpUsernameSettingKey];
            _ftpSetting.FtpPassword = vendorSettings[FtpPasswordSettingKey];

            ProcessFiles();

            //FillSettings(FtpSettingTypes.PurchaseOrder);

            //ReadPurchaseFile();
        }
示例#5
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);
                }
            }
        }
示例#6
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);
                }
            }
        }
        public void GetAvailableDispatchAdvices(Vendor vendor, IAuditLogAdapter log, string logPath, IUnitOfWork unit)
        {
            var orderStatusPath             = vendor.VendorSettings.GetValueByKey("OrderStatus", string.Empty);
            var ccShipmentCostsProduct      = PfaCoolcatConfiguration.Current.ShipmentCostsProduct;
            var ccReturnCostsProduct        = PfaCoolcatConfiguration.Current.ReturnCostsProduct;
            var ccKialaShipmentCostsProduct = PfaCoolcatConfiguration.Current.KialaShipmentCostsProduct;
            var ccKialaReturnCostsProduct   = PfaCoolcatConfiguration.Current.KialaReturnCostsProduct;
            var connectorIdOfVendorOrders   = vendor.VendorSettings.GetValueByKey <int>("RelatedConnectorID", 0);

            if (connectorIdOfVendorOrders == 0)
            {
                throw new Exception("RelatedConnectorID for this vendor has not been set");
            }

#if DEBUG
            orderStatusPath = @"D:\tmp\cc\out";
#endif

            if (string.IsNullOrEmpty(orderStatusPath))
            {
                throw new Exception("Empty order status path for " + vendor.Name);
            }

            Directory.GetFiles(orderStatusPath).Where(x => x.EndsWith("XML", StringComparison.InvariantCultureIgnoreCase)).ForEach((file, idx) =>
            {
                try
                {
                    XDocument XmlDocument = XDocument.Parse(System.IO.File.ReadAllText(file));

                    Dictionary <string, string> statuses = new Dictionary <string, string>();
                    statuses.Add("Aborted", OrderResponseTypes.CancelNotification.ToString());
                    statuses.Add("Cancel", OrderResponseTypes.CancelNotification.ToString());
                    statuses.Add("Returned", OrderResponseTypes.Return.ToString());
                    statuses.Add("Shipped", OrderResponseTypes.ShipmentNotification.ToString());
                    statuses.Add("Imported", OrderResponseTypes.Acknowledgement.ToString());

                    var resp = (from r in XmlDocument.Root.Elements("Status")
                                group r by new { orderID = r.Element("OrderID").Value, status = r.Element("Status").Value } into grouped
                                let order = unit.Scope.Repository <Order>().GetSingle(x => x.WebSiteOrderNumber == grouped.Key.orderID && x.ConnectorID == connectorIdOfVendorOrders)
                                            where order != null
                                            select new Concentrator.Objects.Models.Orders.OrderResponse()
                    {
                        ResponseType = statuses.ContainsKey(grouped.Key.status) ? statuses[grouped.Key.status] : grouped.Key.status,
                        Vendor = vendor,
                        ReceiveDate = DateTime.Now.ToUniversalTime(),
                        Order = order,
                        VendorDocument = Path.GetFileName(file),                                                                                                                                                                                        // XmlDocument.ToString(),
                        VendorDocumentNumber = grouped.Key.status,
                        OrderResponseLines = (from l in XmlDocument.Root.Elements("Status").Where(c => c.Element("OrderID").Value == grouped.Key.orderID && c.Element("Status").Value == grouped.Key.status).GroupBy(c => c.Element("ProductID").Value) //grouped.GroupBy(c => c.Element("ProductID"))
                                              let line = l.First()
                                                         let lineID = string.IsNullOrEmpty(line.Element("LineID").Value) ? 0 : int.Parse(line.Element("LineID").Value)
                                                                      let OrderLine = lineID == 0 ? null : unit.Scope.Repository <OrderLine>().GetSingle(x => x.OrderLineID == lineID)
                                                                                      let quantity = l.Sum(c => int.Parse(c.Element("Quantity").Value))
                                                                                                     select new OrderResponseLine()
                        {
                            OrderLineID = lineID,
                            Ordered = OrderLine == null ? 1 : OrderLine.GetDispatchQuantity(),
                            Backordered = grouped.Key.status == "Backorder" ? quantity : 0,
                            Cancelled = (grouped.Key.status == "Aborted" || grouped.Key.status == "Cancel") ? quantity : 0,
                            Shipped = grouped.Key.status == "Shipped" ? quantity : 0,
                            Remark = grouped.Key.status,
                            Invoiced = 0,
                            Delivered = quantity,
                            Price = 0,
                            TrackAndTrace = line.Element("Reference").Value,
                            VendorItemNumber = line.Element("ProductID").Value
                        }).Distinct().ToList()
                    });


                    if (resp.Count() == 0) //found files but not for this vendor
                    {
                        return;
                    }

                    resp.ForEach((response, ridx) =>
                    {
                        var linesWithoutOrderLine = response.OrderResponseLines.Where(c => c.OrderLineID == 0 || c.VendorItemNumber == ccReturnCostsProduct || c.VendorItemNumber == ccKialaReturnCostsProduct).ToList();

                        if (linesWithoutOrderLine.Count() != 0)
                        {
                            foreach (var orderLine in linesWithoutOrderLine)
                            {
                                //add those orderlines
                                var order         = unit.Scope.Repository <Order>().GetSingle(c => c.WebSiteOrderNumber == response.Order.WebSiteOrderNumber);
                                var existingOline = unit.Scope.Repository <OrderLine>().GetSingle(c => c.OrderID == order.OrderID && c.Product.VendorItemNumber == orderLine.VendorItemNumber);
                                var product       = unit.Scope.Repository <Product>().GetSingle(c => c.VendorItemNumber == orderLine.VendorItemNumber);
                                var price         = product.VendorAssortments.FirstOrDefault(c => c.VendorID == vendor.VendorID).VendorPrices.FirstOrDefault(); //take default price if this scenario occurs

                                if (orderLine.VendorItemNumber == ccReturnCostsProduct || orderLine.VendorItemNumber == ccKialaReturnCostsProduct)
                                {
                                    existingOline = new OrderLine()
                                    {
                                        Order = order,
                                        CustomerItemNumber = orderLine.VendorItemNumber,
                                        ProductID          = product.ProductID,
                                        Quantity           = 1,
                                        BasePrice          = (double)price.Price.Try(c => c.Value, 0),
                                        UnitPrice          = (double)price.Price.Try(c => c.Value, 0),
                                        LineDiscount       = 0,
                                        isDispatched       = true,
                                        Price = (double)price.Price.Try(c => c.Value, 0)
                                    };

                                    unit.Scope.Repository <OrderLine>().Add(existingOline);
                                    unit.Save();
                                }
                                else
                                {
                                    if (existingOline == null)
                                    {
                                        existingOline = new OrderLine()
                                        {
                                            Order = order,
                                            CustomerItemNumber = orderLine.VendorItemNumber,
                                            ProductID          = product.ProductID,
                                            Quantity           = 1,
                                            BasePrice          = (double)price.Price.Try(c => c.Value, 0),
                                            UnitPrice          = (double)price.Price.Try(c => c.Value, 0),
                                            LineDiscount       = 0,
                                            isDispatched       = true,
                                            Price = (double)price.Price.Try(c => c.Value, 0)
                                        };

                                        unit.Scope.Repository <OrderLine>().Add(existingOline);
                                        unit.Save();
                                    }
                                }
                                orderLine.OrderLineID = existingOline.OrderLineID;
                            }
                        }

                        unit.Scope.Repository <Concentrator.Objects.Models.Orders.OrderResponse>().Add(response);
                        unit.Save();
                    });

                    FileInfo inf  = new FileInfo(file);
                    var processed = Path.Combine(orderStatusPath, "Processed");

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

                    var path = Path.Combine(processed, inf.Name);

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

                    File.Move(file, path);
                }
                catch (Exception ex)
                {
                    FileInfo inf = new FileInfo(file);

                    String path = Path.Combine(orderStatusPath, inf.FullName);

                    File.Move(path, Path.ChangeExtension(path, ".xml.err"));

                    using (FileStream logFile = File.Create(Path.Combine(Path.ChangeExtension(path, ".log"))))
                    {
                        String text = ex.Message;

                        using (StreamWriter writer = new StreamWriter(logFile, Encoding.UTF8))
                        {
                            writer.WriteLine("Error processing dispatch for vendor: " + vendor.Name);
                            writer.WriteLine(String.Empty);
                            writer.WriteLine(text);
                        }
                    }

                    log.AuditError("Error process dispatch " + vendor.Name, ex);
                }
            });
        }
示例#8
0
        private void ProcessNotifications(FtpManager manager, OrderResponseTypes responseType, IAuditLogAdapter log, Vendor vendor, string logPath, IUnitOfWork unit)
        {
            foreach (var file in manager)
            {
                bool error = false;
                try
                {
                    if (!file.FileName.EndsWith(".XML"))
                    {
                        continue;
                    }

                    using (var reader = XmlReader.Create(file.Data))
                    {
                        reader.MoveToContent();
                        XDocument xdoc = XDocument.Load(reader);

                        string fileName = "Alpha_" + responseType.ToString() + "_" + Guid.NewGuid() + ".xml";

                        xdoc.Save(Path.Combine(logPath, fileName));

                        var orderDocuments = xdoc.Root.Elements("Order");

                        if (responseType == OrderResponseTypes.InvoiceNotification)
                        {
                            orderDocuments = xdoc.Root.Element("Invoice").Element("Orders").Elements("Order");
                        }

                        int orderID = 0;

                        foreach (var orderDocument in orderDocuments)
                        {
                            if (orderDocument.Element("Reference").Value.Contains('/'))
                            {
                                int.TryParse(orderDocument.Element("Reference").Value.Split('/')[0], out orderID);
                            }
                            else
                            {
                                int.TryParse(orderDocument.Element("Reference").Value, out orderID);
                            }

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

                            if (order != null)
                            {
                                OrderResponse response = null;

                                if (responseType == OrderResponseTypes.InvoiceNotification)
                                {
                                    response = new OrderResponse()
                                    {
                                        OrderID                             = order.OrderID,
                                        ResponseType                        = responseType.ToString(),
                                        VendorDocument                      = xdoc.ToString(),
                                        InvoiceDocumentNumber               = xdoc.Root.Element("Invoice").Attribute("ID").Value,
                                        InvoiceDate                         = DateTime.Parse(xdoc.Root.Element("Invoice").Element("InvDate").Value),
                                        VatPercentage                       = decimal.Parse(xdoc.Root.Element("Invoice").Element("VatPercentage").Value),
                                        VatAmount                           = decimal.Parse(xdoc.Root.Element("Invoice").Element("VatAmount").Value),
                                        TotalGoods                          = decimal.Parse(xdoc.Root.Element("Invoice").Element("TotalGoods").Value),
                                        AdministrationCost                  = decimal.Parse(xdoc.Root.Element("Invoice").Element("AdministrationCost").Value),
                                        DropShipmentCost                    = decimal.Parse(xdoc.Root.Element("Invoice").Element("DropShipmentCost").Value),
                                        ShipmentCost                        = decimal.Parse(xdoc.Root.Element("Invoice").Element("ShipmentCost").Value),
                                        TotalExVat                          = decimal.Parse(xdoc.Root.Element("Invoice").Element("TotalExVat").Value),
                                        TotalAmount                         = decimal.Parse(xdoc.Root.Element("Invoice").Element("TotalAmount").Value),
                                        PaymentConditionDays                = int.Parse(xdoc.Root.Element("Invoice").Element("PaymentConditionDays").Value),
                                        PaymentConditionDiscount            = xdoc.Root.Element("Invoice").Element("PaymentConditionDiscount").Value,
                                        PaymentConditionDiscountDescription = xdoc.Root.Element("Invoice").Element("PaymentConditionDescription").Value,
                                        DespAdvice                          = orderDocument.Element("DespAdvice").Value,
                                        VendorDocumentNumber                = orderDocument.Attribute("ID").Value
                                    };
                                }
                                else
                                {
                                    if (responseType == OrderResponseTypes.Acknowledgement)
                                    {
                                        response = new OrderResponse()
                                        {
                                            OrderID              = order.OrderID,
                                            ResponseType         = responseType.ToString(),
                                            VendorDocument       = xdoc.ToString(),
                                            AdministrationCost   = decimal.Parse(orderDocument.Element("AdministrationCost").Value),
                                            DropShipmentCost     = decimal.Parse(orderDocument.Element("DropShipmentCost").Value),
                                            ShipmentCost         = decimal.Parse(orderDocument.Element("ShipmentCost").Value),
                                            OrderDate            = DateTime.Parse(orderDocument.Element("OrderDate").Value),
                                            VendorDocumentNumber = orderDocument.Attribute("ID").Value
                                        };
                                    }

                                    if (responseType == OrderResponseTypes.ShipmentNotification)
                                    {
                                        response = new OrderResponse()
                                        {
                                            OrderID              = order.OrderID,
                                            ResponseType         = responseType.ToString(),
                                            VendorDocument       = xdoc.ToString(),
                                            OrderDate            = DateTime.Parse(orderDocument.Element("OrderDate").Value),
                                            ReqDeliveryDate      = DateTime.Parse(orderDocument.Element("ReqDelDate").Value),
                                            ShippingNumber       = orderDocument.Element("ShippingNr").Value,
                                            DespAdvice           = orderDocument.Element("DespAdvice").Value,
                                            TrackAndTrace        = orderDocument.Element("TrackAndTrace").Element("TrackAndTraceID").Value,
                                            TrackAndTraceLink    = orderDocument.Element("TrackAndTrace").Element("TrackAndTraceURL").Value,
                                            VendorDocumentNumber = orderDocument.Attribute("ID").Value
                                        };
                                    }
                                }

                                response.VendorID           = vendor.VendorID;
                                response.ReceiveDate        = DateTime.Now;
                                response.VendorDocument     = orderDocument.ToString();
                                response.VendorDocumentDate = DateTime.Now;
                                response.DocumentName       = fileName;
                                unit.Scope.Repository <OrderResponse>().Add(response);

                                foreach (var line in orderDocument.Elements("OrderLines").Elements("OrderLine"))
                                {
                                    OrderLine orderLine = null;
                                    if (line.Element("ReferenceOrderLine") != null)
                                    {
                                        orderLine = order.OrderLines.Where(x => x.OrderLineID == int.Parse(line.Element("ReferenceOrderLine").Value)).FirstOrDefault();
                                    }

                                    if (orderLine == null)
                                    {
                                        string vendorItemNumber = line.Elements("Item").Where(x => x.Attribute("Type").Value == "O").Try(x => x.FirstOrDefault().Value, string.Empty);
                                        orderLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber.Replace("\n", "")).FirstOrDefault();
                                    }


                                    if (orderLine != null)
                                    {
                                        int invoiced    = 0;
                                        int ordered     = 0;
                                        int backordered = 0;
                                        int shipped     = 0;
                                        int deliverd    = 0;

                                        if (responseType != OrderResponseTypes.InvoiceNotification)
                                        {
                                            ordered = line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Ordered") != null?
                                                      int.Parse(line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Ordered").FirstOrDefault().Value) : 0;

                                            if (responseType == OrderResponseTypes.ShipmentNotification)
                                            {
                                                shipped = line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Shipped") != null?
                                                          int.Parse(line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Shipped").FirstOrDefault().Value) : 0;
                                            }

                                            if (responseType == OrderResponseTypes.Acknowledgement)
                                            {
                                                int reserved = line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Reserved") != null?
                                                               int.Parse(line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Reserved").FirstOrDefault().Value) : 0;

                                                backordered = ordered - reserved;
                                            }

                                            deliverd = line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Delivered") != null?
                                                       int.Parse(line.Elements("Quantity").Where(x => x.Attribute("Type").Value == "Delivered").FirstOrDefault().Value) : 0;
                                        }
                                        else
                                        {
                                            invoiced = line.Elements("Quantity").Where(x => x.Attribute("Type") == null) != null?
                                                       int.Parse(line.Elements("Quantity").Where(x => x.Attribute("Type") == null).FirstOrDefault().Value) : 0;
                                        }

                                        //Type of itemnumber:
                                        //"S" = Internal itemnumber
                                        //"O" = OEM number
                                        //"C" = Customer number
                                        //"E" = "EAN number"

                                        OrderResponseLine responseLine = new OrderResponseLine()
                                        {
                                            OrderResponse = response,
                                            OrderLineID   = orderLine.OrderLineID,
                                            Ordered       = ordered != 0 ? ordered : orderLine.Quantity,
                                            Backordered   = backordered,
                                            Delivered     = deliverd,
                                            Cancelled     = responseType != OrderResponseTypes.InvoiceNotification ? orderLine.GetDispatchQuantity() - ordered : 0,
                                            Shipped       = shipped,
                                            Invoiced      = invoiced,
                                            Unit          = line.Element("Unit").Value,
                                            Price         = line.Element("Price") != null?decimal.Parse(line.Element("Price").Value) : 0,
                                                                VendorLineNumber = line.Attribute("ID").Value,
                                                                VendorItemNumber = line.Elements("Item").Where(x => x.Attribute("Type").Value == "S").Try(x => x.FirstOrDefault().Value, string.Empty),
                                                                OEMNumber        = line.Elements("Item").Where(x => x.Attribute("Type").Value == "O").Try(x => x.FirstOrDefault().Value, string.Empty),
                                                                Barcode          = line.Elements("Item").Where(x => x.Attribute("Type").Value == "E").Try(x => x.FirstOrDefault().Value, string.Empty),
                                                                Description      = line.Element("Description").Value
                                        };

                                        if (line.Element("ReqDelDate") != null)
                                        {
                                            responseLine.DeliveryDate = DateTime.Parse(line.Element("ReqDelDate").Value);
                                        }

                                        unit.Scope.Repository <OrderResponseLine>().Add(responseLine);
                                    }
                                }
                            }
                            else
                            {
                                log.AuditInfo("Received response does not match any order, ignore response");
                                manager.MarkAsError(file.FileName);
                                error = true;
                                continue;
                            }
                        }

                        unit.Save();
                        if (!error)
                        {
                            manager.Delete(file.FileName);
                        }
                    }
                }
                catch (Exception e)
                {
                    log.AuditError("Error reading file", e);
                    //manager.MarkAsError(file.FileName);
                }
            }
        }
示例#9
0
        public DataTable[] Process()
        {
            try
            {
                string path = xlsPath;

                OleDbConnection       con     = null;
                System.Data.DataTable exceldt = null;

                try
                {
                    if (path.Contains(".xlsx"))
                    {
                        con =
                            new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path +
                                                ";Extended Properties=\"Excel 12.0;HDR=YES;\"");
                    }

                    else if (path.Contains(".xls"))
                    {
                        con =
                            new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path +
                                                ";Extended Properties=Excel 8.0");
                    }

                    else
                    {
                        log.Error("Foutief bestand");
                        return(null);
                    }

                    con.Open();

                    using (exceldt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))
                    {
                        if (exceldt == null)
                        {
                            log.AuditError("Fout verwerken file: Ongeldig tablad");
                        }

                        String[] excelSheets = new String[exceldt.Rows.Count];
                        log.AuditInfo(string.Format("Found {0} worksheets in excel", exceldt.Rows.Count));
                        int i = 0;

                        DataTable[] tables = new DataTable[exceldt.Rows.Count];
                        // Add the sheet name to the string array.
                        foreach (DataRow row in exceldt.Rows)
                        {
                            excelSheets[i] = row["TABLE_NAME"].ToString();

                            string           sheet = row["TABLE_NAME"].ToString();
                            OleDbDataAdapter da    = null;
                            DataTable        dt    = null;

                            da = new OleDbDataAdapter(string.Format("select * from [{0}]", sheet), con);
                            dt = new DataTable();
                            da.Fill(dt);

                            // exceldt.
                            tables[i] = dt;
                            i++;
                        }
                        return(tables);
                    }
                    if (con != null)
                    {
                        con.Close();
                        con.Dispose();
                    }

                    //File.(path, Path.Combine(ConfigurationManager.AppSettings["ExcelProcessedDirectory"], e.Name + "-" + Guid.NewGuid()));
                }
                catch (IOException ex)
                {
                    log.AuditFatal("Fout verwerken file: " + ex.Message);
                    //File.Move(e.FullPath, Path.Combine(ConfigurationManager.AppSettings["ExcelErrorDirectory"], e.Name + "-" + Guid.NewGuid()));
                }
                catch (Exception ex)
                {
                    log.AuditFatal("Fout verwerken file: " + ex.Message);

                    //if (File.Exists(e.FullPath))
                    //  File.Move(e.FullPath, Path.Combine(ConfigurationManager.AppSettings["ExcelErrorDirectory"], e.Name + "-" + Guid.NewGuid()));
                    //Logging.UserMail("Fout bij het verwerken van de excel order, de naam van het tabblad dient 'EDI_Order_V2' te zijn. Of u maakt gebruik van een verouderde versie, vraag uw accountmanager naar de nieuwe EDI Excel template", mailLog.Mailaddress, DocumentType.Excel);
                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                        con.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                log.AuditFatal(ex.InnerException);
            }
            return(null);
        }
        public int DispatchOrders(Dictionary <Concentrator.Objects.Models.Orders.Order, List <OrderLine> > orderLines, Vendor vendor, IAuditLogAdapter log, IUnitOfWork unit)
        {
            var vendorID = vendor.VendorID;

            List <string> orders = new List <string>();

            //List<Offer> offers = new List<Offer>();

            using (RetailerSoapClient client = new RetailerSoapClient())
            {
                AuthenticationHeader authHeader = new AuthenticationHeader();

                authHeader.Username = vendor.VendorSettings.GetValueByKey("ArvatoUserName", string.Empty);
                authHeader.Password = vendor.VendorSettings.GetValueByKey("ArvatoPassword", string.Empty);

                foreach (var order in orderLines.Keys)
                {
                    var Order = unit.Scope.Repository <Concentrator.Objects.Models.Orders.Order>().GetSingle(o => o.OrderID == order.OrderID);

                    try
                    {
                        //***Begin order reserveration request***///
                        if (client.BeginOrderReservationRequest(authHeader, order.OrderID.ToString()) == "OK")
                        {
                            log.Info("Successfully begun order reservation");

                            Order_Shipment_Request orderShiptMentRequest = new Order_Shipment_Request();
                            orderShiptMentRequest.Order_ID = order.OrderID.ToString();

                            Shipment shipment = new Shipment();

                            List <Shipment_Item> shipmentItems = new List <Shipment_Item>();

                            //Track shipmentitem amount
                            int shipmentItemsCount = 0;

                            //Counter for loop
                            int count = 0;

                            //Total ESD product price
                            decimal totalPrice = 0;

                            //Total price for items who need shipping
                            decimal totalShipmentPrice = 0;

                            //List of items that need to be shipped
                            List <OrderLine> orderLineReserved = new List <OrderLine>();

                            foreach (var detail in orderLines[order])
                            {
                                var orderLine = (from line in Order.OrderLines
                                                 where line.OrderLineID == detail.OrderLineID
                                                 select line).FirstOrDefault();

                                var relatedProducts = (from prod in orderLine.Product.RelatedProductsRelated
                                                       select prod).ToList();

                                //var productType = orderLine.Product.ProductAttributeValues.Where(value => value.Value)
                                var vendorAssortment = unit.Scope.Repository <VendorAssortment>().GetAll(assortment => assortment.VendorID == vendor.VendorID && assortment.ProductID == orderLine.ProductID).FirstOrDefault();

                                var Offer_ID             = vendorAssortment.ActivationKey.ToString();
                                var Shipment_ReferenceID = vendorAssortment.ShipmentRateTableReferenceID;
                                var Zone_ReferenceID     = vendorAssortment.ZoneReferenceID;
                                var Price = (vendorAssortment.VendorPrices.FirstOrDefault() != null ? vendorAssortment.VendorPrices.FirstOrDefault().Price.Value : (decimal)orderLine.Price) * 100;
                                totalPrice += Price;
                                var Quantity = orderLine.GetDispatchQuantity();

                                //check if product is primary
                                var productType =
                                    orderLine.Product.ProductAttributeValues.Where(
                                        name => name.ProductAttributeMetaData.AttributeCode == "Product_Type").FirstOrDefault().Value;

                                if (productType == "Supplementary")
                                {
                                    shipmentItems.Add(new Shipment_Item
                                    {
                                        Line_Item_ID = orderLine.OrderLineID.ToString(),
                                        Quantity     = Quantity.ToString()
                                    });
                                    shipmentItemsCount++;
                                }

                                ////***Add order item***//
                                XDocument addOrderItemResponse =
                                    XDocument.Parse(client.AddOrderItemRequest(authHeader, order.OrderID.ToString(),
                                                                               orderLine.OrderLineID.ToString(), Offer_ID, (decimal)Price,
                                                                               "EUR", Quantity, "", ""));

                                int relCount = 1;
                                foreach (var relatedProduct in relatedProducts)
                                {
                                    //check if product is supplementary
                                    var relProductType =
                                        relatedProduct.SourceProduct.ProductAttributeValues.Where(
                                            name => name.ProductAttributeMetaData.AttributeCode == "Product_Type").FirstOrDefault().Value;

                                    var relatedProductPrice = relatedProduct.SourceProduct.VendorAssortments.FirstOrDefault().VendorPrices.FirstOrDefault().Price;

                                    var relVendorAssortment = unit.Scope.Repository <VendorAssortment>().GetAllAsQueryable(assortment => assortment.VendorID == vendor.VendorID && assortment.ProductID == relatedProduct.ProductID);

                                    var relOffer_ID = relVendorAssortment.FirstOrDefault().ActivationKey.ToString();

                                    XDocument addRelatedOrderItemResponse =
                                        XDocument.Parse(client.AddOrderItemRequest(authHeader, order.OrderID.ToString(),
                                                                                   (orderLine.OrderLineID.ToString() + "_" +
                                                                                    relCount.ToString()), relOffer_ID, relatedProductPrice.Value,
                                                                                   "EUR", Quantity, "", ""));

                                    if (relProductType == "Supplementary")
                                    {
                                        totalShipmentPrice += relatedProductPrice.Value;

                                        shipmentItems.Add(new Shipment_Item
                                        {
                                            Line_Item_ID = (orderLine.OrderLineID.ToString() + "_" + relCount.ToString()),
                                            Quantity     = Quantity.ToString()
                                        });
                                        shipmentItemsCount++;
                                    }
                                    relCount++;
                                }

                                var status = (from orderResponseStatus in addOrderItemResponse.Element("Order_Fulfillment_Reservation").Elements()
                                              where orderResponseStatus.Name == "Order_Status"
                                              select orderResponseStatus).FirstOrDefault();

                                log.InfoFormat("Order item {0} status {1}", orderLine.OrderLineID.ToString(), status.Value);

                                //set item status
                                if (status.Value.Equals("Reserved"))
                                {
                                    orderLineReserved.Add(orderLine);
                                    var item = unit.Scope.Repository <OrderLine>().GetSingle(prod => prod.OrderLineID == orderLine.OrderLineID);

                                    item.SetStatus(OrderLineStatus.Processed, unit.Scope.Repository <OrderLedger>());
                                }

                                shipment.Zone_Reference_ID = Zone_ReferenceID;
                                shipment.Shipment_Rate_Table_Reference_ID = Shipment_ReferenceID;

                                count++;
                            }

                            /************************Fill shipping information**************************/
                            string firstName = order.ShippedToCustomer.CustomerName.Split(' ')[0];
                            string lastName  = order.ShippedToCustomer.CustomerName.Substring((firstName.Length));

                            shipment.Shipment_Packages    = new Shipment_Package[1];
                            shipment.Shipment_Packages[0] = new Shipment_Package
                            {
                                Currency_Code         = redCurrencyCode.EUR,
                                Shipment_Items        = shipmentItems.ToArray(),
                                Shipment_Amount_Total = (decimal)totalPrice
                            };

                            shipment.Shipment_Address             = new Shipment_Address();
                            shipment.Shipment_Address.Address_One = order.ShippedToCustomer.CustomerAddressLine1;
                            //shipment.Shipment_Address.Address_Two = order.ShipToCustomer.CustomerAddressLine2;
                            //shipment.Shipment_Address.Address_Three = order.ShipToCustomer.CustomerAddressLine3;
                            shipment.Shipment_Address.City         = order.ShippedToCustomer.City;
                            shipment.Shipment_Address.Country_Code = order.ShippedToCustomer.Country;
                            //shipment.Shipment_Address.State_Code = "";
                            shipment.Shipment_Address.Zip_Code   = order.ShippedToCustomer.PostCode;
                            shipment.Shipment_Address.Phone      = order.ShippedToCustomer.CustomerTelephone;
                            shipment.Shipment_Address.First_Name = firstName;
                            shipment.Shipment_Address.Last_Name  = lastName;

                            orderShiptMentRequest.Shipment    = new Shipment[1];
                            orderShiptMentRequest.Shipment[0] = shipment;
                            /************************End Fill shipping information************************/

                            log.AuditInfo("Successfully added order items to order");

                            if (client.CompleteOrderReservationRequest(authHeader, order.OrderID.ToString(), "") == "OK")
                            {
                                log.AuditInfo("Order reservation successfully made");

                                string            requestXml    = string.Empty;
                                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(orderShiptMentRequest.GetType());
                                    XmlSerializerNamespaces nm         = new XmlSerializerNamespaces();
                                    nm.Add("xsi", "urn:Order_Shipment_Request");
                                    serializer.Serialize(xw, orderShiptMentRequest);

                                    XmlDocument document = new XmlDocument();
                                    document.LoadXml(requestString.ToString());
                                    document.DocumentElement.RemoveAttribute("xmlns:xsi");
                                    document.DocumentElement.RemoveAttribute("xmlns:xsd");
                                    requestXml = document.OuterXml;

                                    LogOrder(document, vendor.VendorID, string.Format("{0}.xml", order.OrderID), log);
                                }

                                ////***Order shipment request***//
                                if (shipmentItemsCount > 0)
                                {
                                    string response = client.OrderShipmentRequest(authHeader, requestXml.ToString());
                                    if (response == "OK")
                                    {
                                        log.InfoFormat("Order reservation successfully made");
                                    }
                                }
                                else
                                {
                                    log.InfoFormat("No items need shipping");
                                }

                                if (client.CommitToPurchaseOrderRequest(authHeader, order.OrderID.ToString(), order.OrderID.ToString()) == "OK")
                                {
                                    log.Info("Order succesfully purchased");

                                    log.Info("Processing product information");

                                    XDocument[] orderInformation = new XDocument[orderLineReserved.Count];

                                    int oc = 0;
                                    if (orderLineReserved.Count > 0)
                                    {
                                        OrderResponse orderResponse = null;

                                        foreach (var orderLine in orderLineReserved)
                                        {
                                            OrderResponseLine orderResponseLine = null;

                                            orderInformation[oc] =
                                                XDocument.Parse(client.PurchaseOrderItemFulfillmentRequest(authHeader, order.OrderID.ToString(),
                                                                                                           orderLine.OrderLineID.ToString(), ""));
                                            //#endif
                                            var OrderStatus = orderInformation[oc].Element("Order_Fulfillment").Element("Order_Status").Value;
                                            var OrderDate   = orderInformation[oc].Element("Order_Fulfillment").Element("Order_Date").Value;
                                            var Quantity    = orderInformation[oc].Element("Order_Fulfillment").Element("Quantity").Value;

                                            var getMaxShippingQuantity = orderLine.Product.ProductAttributeValues.Where(
                                                name => name.ProductAttributeMetaData.AttributeCode == "Max_Quantity_Per_Shipment_Charge").FirstOrDefault();

                                            var MaxShippingQuantity = getMaxShippingQuantity != null?Int32.Parse(getMaxShippingQuantity.Value) : 0;

                                            var _orderResponseRepo = unit.Scope.Repository <OrderResponse>();

                                            switch (OrderStatus)
                                            {
                                            case "Shipped":
                                                if (orderResponse == null)
                                                {
                                                    orderResponse = new OrderResponse
                                                    {
                                                        Orders = new List <Concentrator.Objects.Models.Orders.Order>()
                                                        {
                                                            Order
                                                        },
                                                        VendorDocument  = orderInformation[oc].Document.ToString(),
                                                        VendorID        = vendorID,
                                                        OrderDate       = DateTime.Parse(OrderDate),
                                                        ReceiveDate     = DateTime.Now,
                                                        PartialDelivery = MaxShippingQuantity != 0 ? Int32.Parse(Quantity) < MaxShippingQuantity
                                  ? false
                                  : true : false,
                                                        VendorDocumentNumber = Order.OrderID.ToString()
                                                    };
                                                    _orderResponseRepo.Add(orderResponse);
                                                }
                                                orderResponse.ResponseType = OrderResponseTypes.ShipmentNotification.ToString();

                                                break;

                                            case "ShipmentPending":
                                                if (orderResponse == null)
                                                {
                                                    orderResponse = new OrderResponse
                                                    {
                                                        Orders = new List <Concentrator.Objects.Models.Orders.Order>()
                                                        {
                                                            Order
                                                        },
                                                        VendorDocument  = orderInformation[oc].Document.ToString(),
                                                        VendorID        = vendorID,
                                                        OrderDate       = DateTime.Parse(OrderDate),
                                                        ReceiveDate     = DateTime.Now,
                                                        PartialDelivery =
                                                            Int32.Parse(Quantity) < MaxShippingQuantity
                                  ? false
                                  : true,
                                                        VendorDocumentNumber = Order.OrderID.ToString()
                                                    };
                                                    _orderResponseRepo.Add(orderResponse);
                                                }
                                                orderResponse.ResponseType = OrderResponseTypes.Acknowledgement.ToString();

                                                break;

                                            default:
                                                log.WarnFormat("Unknown order status");
                                                break;
                                            }

                                            var formattedBlocks =
                                                (from attribute in
                                                 orderInformation[oc].Element("Order_Fulfillment").Element("Fulfillment_Block").Elements()
                                                 where attribute.Name == "Preformatted_Block"
                                                 select new
                                            {
                                                Type = attribute.Attribute("Type").Value,
                                                Text = attribute.Value
                                            });

                                            var productName =
                                                (from attribute in
                                                 orderInformation[oc].Element("Order_Fulfillment").Element("Fulfillment_Block").Element(
                                                     "Fulfillment_Set").Elements()
                                                 where attribute.Name == "Header"
                                                 select attribute.Value).FirstOrDefault();

                                            var productInformation =
                                                (from attribute in
                                                 orderInformation[oc].Element("Order_Fulfillment").Element("Fulfillment_Block").Element(
                                                     "Fulfillment_Set").
                                                 Elements(
                                                     "Fulfillment_Item")
                                                 select new
                                            {
                                                FullfillmentAtoms =
                                                    (from attribute2 in
                                                     attribute.Elements("Fulfillment_Atom_Section").Elements("Fulfillment_Atom")
                                                     select new
                                                {
                                                    Header = attribute2.Parent.Element("Header") != null ? attribute2.Parent.Element("Header").Value : string.Empty,
                                                    Fulfillment_Atom = (from att in attribute2.Attributes()
                                                                        select new
                                                    {
                                                        Name = att.Name,
                                                        Value = att.Value
                                                    }).ToDictionary(x => x.Name, x => x.Value),
                                                    Value = attribute2.Value
                                                })
                                            });

                                            orderResponseLine = new OrderResponseLine
                                            {
                                                OrderResponse = orderResponse,
                                                OrderLineID   = orderLine.OrderLineID,
                                                Ordered       = OrderStatus != "Shipped" ? 0 : Int32.Parse(Quantity),
                                                Backordered   = OrderStatus != "Shipped" ? Int32.Parse(Quantity) : 0,
                                                Cancelled     = 0,
                                                Shipped       = OrderStatus != "Shipped" ? 0 : Int32.Parse(Quantity),
                                                //Invoiced
                                                Price       = (decimal)orderLine.Price.Value,
                                                Processed   = false,
                                                Delivered   = 0,
                                                ProductName = productName,
                                                html        = (from data in formattedBlocks
                                                               where data.Type == "Html"
                                                               select data.Text).FirstOrDefault(),
                                                Remark = (from data in formattedBlocks
                                                          where data.Type == "Text"
                                                          select data.Text).FirstOrDefault(),
                                            };
                                            unit.Scope.Repository <OrderResponseLine>().Add(orderResponseLine);

                                            foreach (var inf in productInformation)
                                            {
                                                foreach (var att in inf.FullfillmentAtoms)
                                                {
                                                    var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                                    {
                                                        OrderResponseLine = orderResponseLine
                                                    };

                                                    foreach (var atom in att.Fulfillment_Atom.Keys)
                                                    {
                                                        if (orderItemFullfilmentInformation.GetType().GetProperties().Any(x => x.Name == atom.LocalName))
                                                        {
                                                            Type type =
                                                                orderItemFullfilmentInformation.GetType().GetProperty(atom.LocalName).PropertyType;

                                                            string value = att.Fulfillment_Atom[atom];

                                                            orderItemFullfilmentInformation.GetType().GetProperty(atom.LocalName).SetValue(
                                                                orderItemFullfilmentInformation, Convert.ChangeType(value, type), null);
                                                        }
                                                    }

                                                    orderItemFullfilmentInformation.Value  = att.Value;
                                                    orderItemFullfilmentInformation.Header = att.Header;
                                                    unit.Scope.Repository <OrderItemFullfilmentInformation>().Add(orderItemFullfilmentInformation);
                                                }
                                            }
                                            oc++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.AuditError(ex);
                    }
                    unit.Save();
                }
                return(0);
            }
        }