Ejemplo n.º 1
0
        public static void SendToAxapta(Order order, OrderResponseTypes orderResponseType, List <OrderResponseLine> orderResponseLines)
        {
            bool useAxapta = order.Connector.ConnectorSettings.GetValueByKey("UseAxapta", false);

            if (useAxapta)
            {
                switch (orderResponseType)
                {
                case OrderResponseTypes.ReceivedNotification:
                    using (var received = new ProcessPurchaseOrderReceivedConfirmation())
                    {
                        received.Process(orderResponseLines);
                    }
                    break;

                case OrderResponseTypes.ShipmentNotification:
                    //using (var pickticket = new ProcessPickTicketShipmentConfirmation())
                    //{
                    //  pickticket.Process(orderResponseLines);
                    //}
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
        }
Ejemplo n.º 2
0
        public LazyCsvParser GetCSVFile(Stream fileStream, OrderResponseTypes type)
        {
            Array         enumValArray = null;
            List <string> enumValList  = null;

            switch (type)
            {
            case OrderResponseTypes.Acknowledgement:
                enumValArray = Enum.GetValues(typeof(VSNAcknowledgement));

                enumValList = new List <string>(enumValArray.Length);

                foreach (int val in enumValArray)
                {
                    enumValList.Add(Enum.Parse(typeof(VSNAcknowledgement), val.ToString()).ToString());
                }
                break;

            case OrderResponseTypes.ShipmentNotification:
                enumValArray = Enum.GetValues(typeof(VSNShipment));

                enumValList = new List <string>(enumValArray.Length);

                foreach (int val in enumValArray)
                {
                    enumValList.Add(Enum.Parse(typeof(VSNShipment), val.ToString()).ToString());
                }
                break;

            case OrderResponseTypes.CancelNotification:
                enumValArray = Enum.GetValues(typeof(VSNCancel));

                enumValList = new List <string>(enumValArray.Length);

                foreach (int val in enumValArray)
                {
                    enumValList.Add(Enum.Parse(typeof(VSNCancel), val.ToString()).ToString());
                }
                break;
            }

            return(new LazyCsvParser(fileStream, enumValList, true, '\t'));

            //return new LazyCsvParser(enumValList, true, '\t');
        }
 private OrderResponse ConstructOrderResponse(List <OrderResponseLine> responseLines, Order order, XDocument document, OrderResponseTypes type)
 {
     return(new OrderResponse()
     {
         Order = order,
         OrderResponseLines = responseLines,
         ReceiveDate = DateTime.Now.ToUniversalTime(),
         ResponseType = type.ToString(),
         Vendor = Vendor,
         VendorDocument = document.ToString(),
         VendorDocumentDate = DateTime.Now.ToUniversalTime(),
         VendorDocumentReference = order.WebSiteOrderNumber,
         VendorDocumentNumber = order.WebSiteOrderNumber,
     });
 }
Ejemplo n.º 4
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);
                }
            }
        }
Ejemplo n.º 5
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);
                }
            }
        }
Ejemplo n.º 6
0
        public void GetAvailableDispatchAdvices(Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, string logPath, DataAccess.UnitOfWork.IUnitOfWork unit)
        {
            var FtpUrl            = vendor.VendorSettings.GetValueByKey("FtpUrl", string.Empty);
            var FtpUserName       = vendor.VendorSettings.GetValueByKey("DispUsername", string.Empty);
            var FtpPassword       = vendor.VendorSettings.GetValueByKey("DispPassword", string.Empty);
            var DownloadDirectory = vendor.VendorSettings.GetValueByKey("DownloadDirectory", string.Empty);
            var vendorID          = vendor.VendorID;

            OrderResponseTypes responseType = new OrderResponseTypes();

            FtpManager ftp = new FtpManager(
                FtpUrl,
                DownloadDirectory,
                FtpUserName,
                FtpPassword,
                false, true, log);

            //SimpleFtp ftp = new SimpleFtp(FtpUrl, FtpUserName, FtpPassword, log, true);

            //var files = ftp.AsEnumerable().ToList();

            foreach (var file in ftp)
            {
                if (file.FileName.Contains("CNOBV") || file.FileName.Contains("CNFAC") || file.FileName.Contains("CNPAK"))
                {
                    OrderResponse orderresponse = null;

                    switch (file.FileName.Substring(0, 5))
                    {
                    case "CNPAK":
                        responseType = OrderResponseTypes.ShipmentNotification;
                        break;

                    case "CNFAC":
                        responseType = OrderResponseTypes.InvoiceNotification;
                        break;

                    case "CNOBV":
                        responseType = OrderResponseTypes.Acknowledgement;
                        break;
                    }

                    using (var stream = ftp.OpenFile(file.FileName))
                    {
                        XDocument           xml     = XDocument.Load(stream.Data);
                        List <OrderProcess> details = null;


                        //parse
                        if (responseType == OrderResponseTypes.Acknowledgement)
                        {
                            details = (from d in xml.Element("orderresponses").Elements("orderconfirmation")
                                       select new OrderProcess
                            {
                                OrderID = d.Attribute("external_document_id").Value,
                                VendorDocNr = d.Element("orderheader").Attribute("order_number").Value,
                                Currency = d.Element("orderheader").Attribute("currency").Value,
                                ShipToName = d.Element("ShipTo").Element("name1").Value,
                                ShipToStreet = d.Element("ShipTo").Element("street").Value,
                                ShipToPostalCode = d.Element("ShipTo").Element("postalcode").Value,
                                ShipToCity = d.Element("ShipTo").Element("city").Value,
                                ShipToCountry = d.Element("ShipTo").Element("country").Value,
                                Tax = d.Element("VAT").Element("amount").Value,
                                Date = d.Element("orderheader").Attribute("orderdate").Value,
                                Costs = (from c in d.Elements("costs")
                                         select new OrderCost
                                {
                                    Description = c.Element("description").Value,
                                    Amount = c.Element("amount").Value
                                }).ToList(),
                                OrderLines = (from o in d.Elements("orderline")
                                              select new OrderProcessLine
                                {
                                    VendorLineNr = o.Attribute("linenumber").Value,
                                    OrderlineID = o.Attribute("customer_linenumber").Value,        //remove 0000's
                                    VendorItemNr = o.Attribute("item_id").Value,
                                    Description = o.Attribute("item_description").Value,
                                    Price = o.Attribute("price").Value,
                                    OEM = o.Attribute("manufacturer_item_id").Value,
                                    Ordered = o.Attribute("quantity_ordered").Value,
                                    StatusCode = o.Element("schedulelines").Element("atp_code").Value,
                                    StatusDate = o.Element("schedulelines").Element("atp_date").Value,
                                    StatusQuantity = o.Element("schedulelines").Element("quantity").Value
                                }).ToList(),
                                TotalPrice = d.Element("ordertrailer").Element("order_amount_incl_VAT").Value
                            }).ToList();
                        }

                        if (responseType == OrderResponseTypes.InvoiceNotification)
                        {
                            try
                            {
                                details = (from d in xml.Element("orderresponses").Elements("invoice")
                                           select new OrderProcess
                                {
                                    OrderID = d.Element("invoiceline").Element("customerorder").Element("customer_ordernumber").Value,
                                    InvoiceNumber = d.Element("invoiceheader").Element("invoice_number").Value,
                                    InvoiceDate = d.Element("invoiceheader").Element("invoice_date").Value,
                                    ShipToName = d.Element("invoiceline").Element("invoiceorder").Element("ShipTo").Element("name1").Value,
                                    ShipToStreet = d.Element("invoiceline").Element("invoiceorder").Element("ShipTo").Element("street").Value,
                                    ShipToPostalCode = d.Element("invoiceline").Element("invoiceorder").Element("ShipTo").Element("postalcode").Value,
                                    ShipToCity = d.Element("invoiceline").Element("invoiceorder").Element("ShipTo").Element("city").Value,
                                    ShipToCountry = d.Element("invoiceline").Element("invoiceorder").Element("ShipTo").Element("country").Value,
                                    VendorDocNr = d.Element("invoiceline").Element("invoiceorder").Element("ordernumber").Value,
                                    Currency = d.Element("invoiceheader").Element("invoice_currency").Value,
                                    TrackingNumber = d.Element("invoiceheader").Element("TrackingNumber").Value,
                                    TotalExVat = d.Element("invoicetrailer").Element("invoice_amount_ex_VAT").Value,
                                    VatAmount = d.Element("invoicetrailer").Element("invoice_VAT_amount").Value,
                                    //PaymentDays = d.Element("invoiceheader").Element("invoice_terms_of_payment_text").Value.Substring(16, 2), //get number: ex Betaling binnen 30 dagen netto
                                    OrderDate = d.Element("invoiceline").Element("invoiceorder").Element("orderdate").Value,
                                    Costs = (from c in d.Element("invoicetrailer").Elements("costs")
                                             select new OrderCost
                                    {
                                        Description = c.Element("description").Value,
                                        Amount = c.Element("amount").Value
                                    }).ToList(),
                                    OrderLines = (from o in d.Elements("invoiceline")
                                                  select new OrderProcessLine
                                    {
                                        VendorLineNr = o.Element("invoiceorder").Element("linenumber").Value,
                                        OrderlineID = o.Element("customerorder").Element("customer_ordernumber").Value,      //remove 0000's
                                        VendorItemNr = o.Element("invoice_item").Element("item_id").Value,
                                        Description = o.Element("invoice_item").Element("item_description").Value,
                                        Price = o.Element("invoice_item").Element("price").Value,
                                        OEM = o.Element("invoice_item").Element("manufacturer_item_id").Value,
                                        Ordered = o.Element("invoice_item").Element("quantity_ordered").Value,
                                        Invoiced = o.Element("invoice_item").Element("quantity_invoiced").Value,
                                        OrderDate = o.Element("invoiceorder").Element("orderdate").Value,
                                        VATPercentage = o.Element("invoice_item").Element("item_vat").Element("percentage").Value,
                                        VATAmount = o.Element("invoice_item").Element("item_vat").Element("amount").Value
                                    }).ToList(),
                                    TotalPrice = d.Element("invoicetrailer").Element("invoice_amount_incl_VAT").Value
                                }).ToList();
                            }
                            catch (Exception)
                            {
                            }
                        }

                        else if (responseType == OrderResponseTypes.ShipmentNotification)
                        {
                            details = (from d in xml.Element("orderresponses").Elements("dispatchadvice")
                                       select new OrderProcess
                            {
                                OrderID = d.Element("dispatchline").Element("customerorder").Element("customer_ordernumber").Value,
                                ReceiveDate = d.Element("dispatchheader").Element("dispatchdate").Value,
                                ShipmentNumber = d.Element("dispatchheader").Element("dispatchnumber").Value,
                                ShipmentDate = d.Element("dispatchheader").Element("dispatchdate").Value,
                                ShipToName = d.Element("ShipTo").Element("name1").Value,
                                ShipToStreet = d.Element("ShipTo").Element("street").Value,
                                ShipToPostalCode = d.Element("ShipTo").Element("postalcode").Value,
                                ShipToCity = d.Element("ShipTo").Element("city").Value,
                                ShipToCountry = d.Element("ShipTo").Element("country").Value,
                                VendorDocNr = d.Element("dispatchline").Element("order").Element("ordernumber").Value,
                                TrackingNumbers = (from nr in d.Element("dispatchline").Element("tracking_numbers").Elements("trackingnumber")
                                                   select nr.Value).ToList(),
                                OrderLines = (from o in d.Elements("dispatchline")
                                              select new OrderProcessLine
                                {
                                    VendorLineNr = o.Element("order").Element("linenumber").Value,
                                    OrderDate = o.Element("order").Element("orderdate").Value,
                                    OrderlineID = o.Element("customerorder").Element("customer_ordernumber").Value,        //remove 0000's
                                    VendorItemNr = o.Element("item").Element("item_id").Value,
                                    Description = o.Element("item").Element("item_description").Value,
                                    OEM = o.Element("item").Element("manufacturer_item_id").Value,
                                    Shipped = o.Element("item").Element("quantity").Value,
                                }).ToList(),
                                TotalShipped = d.Element("dispatchtrailer").Element("total_number_of_units").Value
                            }).ToList();
                        }

                        var Order   = details.FirstOrDefault();
                        int OrderID = 0;

                        Int32.TryParse(Order.OrderID, out OrderID);

                        var orderInDb = unit.Scope.Repository <Order>().GetSingle(x => x.OrderID == OrderID);

                        var orderResponseLines = new List <OrderResponseLine>();

                        if (orderInDb != null)
                        {
                            string VendorDocument = "";

                            StringBuilder builder = new StringBuilder();
                            using (TextWriter writer = new StringWriter(builder))
                            {
                                xml.Save(writer);
                            }

                            VendorDocument = builder.ToString();

                            if (responseType == OrderResponseTypes.Acknowledgement)
                            {
                                orderresponse = new OrderResponse()
                                {
                                    VendorID             = vendorID,
                                    OrderID              = Int32.Parse(Order.OrderID),
                                    ResponseType         = responseType.ToString(),
                                    AdministrationCost   = decimal.Parse(Order.Costs.FirstOrDefault(x => x.Description == "Handlingkosten" || x.Description == "Handlingskosten").Amount, CultureInfo.InvariantCulture),
                                    DropShipmentCost     = decimal.Parse(Order.Costs.FirstOrDefault(x => x.Description == "Dropshipmentkosten").Amount, CultureInfo.InvariantCulture),
                                    OrderDate            = DateTime.Parse(Order.Date),
                                    VendorDocumentNumber = Order.VendorDocNr,
                                    VendorDocument       = VendorDocument,
                                    ReceiveDate          = DateTime.Now
                                };

                                decimal TotalAmount;

                                decimal.TryParse(Order.TotalPrice, NumberStyles.Any, CultureInfo.InvariantCulture, out TotalAmount);


                                orderresponse.TotalAmount       = TotalAmount;
                                orderresponse.ShippedToCustomer = new Models.Orders.Customer();

                                orderresponse.ShippedToCustomer.City = Order.Try(x => x.ShipToCity, null);
                                orderresponse.ShippedToCustomer.CustomerAddressLine1 = Order.Try(x => x.ShipToStreet, null);
                                orderresponse.ShippedToCustomer.PostCode             = Order.Try(x => x.ShipToPostalCode, null);
                                orderresponse.ShippedToCustomer.Country      = Order.Try(x => x.ShipToCountry, null);
                                orderresponse.ShippedToCustomer.CustomerName = Order.Try(x => x.ShipToName, null);


                                foreach (var orderline in Order.OrderLines)
                                {
                                    var orderLine = orderInDb.OrderLines.FirstOrDefault(x => x.OrderLineID == Int32.Parse(orderline.OrderlineID));
                                    if (orderLine != null)
                                    {
                                        var OrderResponseLine = new OrderResponseLine
                                        {
                                            OrderResponse    = orderresponse,
                                            VendorLineNumber = orderline.VendorLineNr,
                                            VendorItemNumber = orderline.VendorItemNr,
                                            Description      = orderline.Description,
                                            Ordered          = 0,
                                            Backordered      = 0,
                                            Invoiced         = 0,
                                            Shipped          = 0,
                                            Cancelled        = 0,
                                            Processed        = false,
                                            RequestDate      = DateTime.Now //aanpassen indien word meegeven in orderplacement
                                        };

                                        decimal Price;
                                        int     OrderlineID;
                                        int     Ordered;

                                        int.TryParse(orderline.OrderlineID, out OrderlineID);
                                        decimal.TryParse(orderline.Price, NumberStyles.Any, CultureInfo.InvariantCulture, out Price);
                                        int.TryParse(orderline.Ordered, NumberStyles.Any, CultureInfo.InvariantCulture, out Ordered);

                                        OrderResponseLine.Price       = Price;
                                        OrderResponseLine.OrderLineID = OrderlineID;
                                        OrderResponseLine.Ordered     = Ordered;

                                        //check if backordered
                                        if (Int32.Parse(orderline.StatusCode) == (int)CopacoStatusCodes.ExpectedbyXXXXX ||
                                            Int32.Parse(orderline.StatusCode) == (int)CopacoStatusCodes.Expectedsupplier ||
                                            Int32.Parse(orderline.StatusCode) == (int)CopacoStatusCodes.ExpectedbyXXXXX ||
                                            Int32.Parse(orderline.StatusCode) == (int)CopacoStatusCodes.Unknowndelivery500 ||
                                            Int32.Parse(orderline.StatusCode) == (int)CopacoStatusCodes.IndicationXXXXX ||
                                            Int32.Parse(orderline.StatusCode) == (int)CopacoStatusCodes.Outofstock ||
                                            Int32.Parse(orderline.StatusCode) == (int)CopacoStatusCodes.Notavailableyet)
                                        {
                                            int StatusQuantity;

                                            int.TryParse(orderline.StatusQuantity, NumberStyles.Any, CultureInfo.InvariantCulture, out StatusQuantity);
                                            OrderResponseLine.Backordered = StatusQuantity;
                                        }
                                        orderResponseLines.Add(OrderResponseLine);
                                    }
                                }
                            }
                            else
                            if (responseType == OrderResponseTypes.ShipmentNotification)
                            {
                                orderresponse = new OrderResponse
                                {
                                    OrderID      = Int32.Parse(Order.OrderID),
                                    ResponseType = responseType.ToString(),
                                    //ReceiveDate = DateTime.Parse(Order.ReceiveDate),
                                    VendorDocumentNumber = Order.VendorDocNr,
                                    TrackAndTrace        = Order.TrackingNumbers.FirstOrDefault(),
                                    VendorDocument       = VendorDocument
                                };

                                DateTime ReceiveDate;

                                DateTime.TryParseExact(Order.ReceiveDate, "yyyyMMdd", null, DateTimeStyles.None, out ReceiveDate);

                                decimal TotalShipped;

                                decimal.TryParse(Order.TotalShipped, NumberStyles.Any, CultureInfo.InvariantCulture, out TotalShipped);

                                orderresponse.ReceiveDate       = ReceiveDate;
                                orderresponse.TotalGoods        = TotalShipped;
                                orderresponse.ShippedToCustomer = new Models.Orders.Customer();

                                orderresponse.ShippedToCustomer.City = Order.Try(x => x.ShipToCity, null);
                                orderresponse.ShippedToCustomer.CustomerAddressLine1 = Order.Try(x => x.ShipToStreet, null);
                                orderresponse.ShippedToCustomer.PostCode             = Order.Try(x => x.ShipToPostalCode, null);
                                orderresponse.ShippedToCustomer.Country      = Order.Try(x => x.ShipToCountry, null);
                                orderresponse.ShippedToCustomer.CustomerName = Order.Try(x => x.ShipToName, null);

                                foreach (var orderline in Order.OrderLines)
                                {
                                    var orderLine = orderInDb.OrderLines.FirstOrDefault(x => x.OrderLineID == Int32.Parse(orderline.OrderlineID));
                                    if (orderLine != null)
                                    {
                                        var OrderResponseLine = new OrderResponseLine
                                        {
                                            OrderResponse    = orderresponse,
                                            VendorLineNumber = orderline.VendorLineNr,           //
                                            OrderLineID      = int.Parse(orderline.OrderlineID), //
                                            VendorItemNumber = orderline.VendorItemNr,           //
                                            Description      = orderline.Description,            //
                                            OEMNumber        = orderline.OEM,                    //
                                            Ordered          = 0,
                                            Backordered      = 0,
                                            Invoiced         = 0,
                                            Shipped          = 0,
                                            Cancelled        = 0,
                                            Processed        = false,
                                        };

                                        DateTime RequestDate;


                                        DateTime.TryParseExact(orderline.OrderDate, "yyyyMMdd", null, DateTimeStyles.None, out RequestDate);

                                        int Shipped;
                                        int.TryParse(orderline.Shipped, NumberStyles.Any, CultureInfo.InvariantCulture, out Shipped);

                                        OrderResponseLine.RequestDate = RequestDate;
                                        OrderResponseLine.Shipped     = Shipped;

                                        orderResponseLines.Add(OrderResponseLine);
                                    }
                                }
                            }

                            else if (responseType == OrderResponseTypes.InvoiceNotification)
                            {
                                orderresponse = new OrderResponse
                                {
                                    VendorID = vendorID,
                                    InvoiceDocumentNumber = Order.InvoiceNumber,
                                    AdministrationCost    = decimal.Parse(Order.Costs.FirstOrDefault(x => x.Description == "Handlingkosten" || x.Description == "Handlingskosten").Amount),
                                    DropShipmentCost      = decimal.Parse(Order.Costs.FirstOrDefault(x => x.Description == "Dropshipmentkosten").Amount),
                                    InvoiceDate           = DateTime.Parse(Order.InvoiceDate),
                                    PaymentConditionDays  = int.Parse(Order.PaymentDays),
                                    TotalExVat            = decimal.Parse(Order.TotalExVat),
                                    VatAmount             = decimal.Parse(Order.VatAmount),
                                    VendorDocumentNumber  = Order.VendorDocNr,
                                    OrderID        = int.Parse(Order.OrderID),
                                    TrackAndTrace  = Order.TrackingNumber,
                                    OrderDate      = DateTime.Parse(Order.OrderDate),
                                    ResponseType   = responseType.ToString(),
                                    VendorDocument = VendorDocument,
                                    ReceiveDate    = DateTime.Now
                                };


                                foreach (var orderline in Order.OrderLines)
                                {
                                    var orderLine = orderInDb.OrderLines.FirstOrDefault(x => x.OrderLineID == Int32.Parse(orderline.OrderlineID));
                                    if (orderLine != null)
                                    {
                                        var OrderResponseLine = new OrderResponseLine
                                        {
                                            OrderResponse    = orderresponse,
                                            VendorLineNumber = orderline.VendorLineNr,
                                            OrderLineID      = int.Parse(orderline.OrderlineID),
                                            VendorItemNumber = orderline.VendorItemNr,
                                            Description      = orderline.Description,
                                            OEMNumber        = orderline.OEM,
                                            Ordered          = 0,
                                            Backordered      = 0,
                                            Invoiced         = 0,
                                            Shipped          = 0,
                                            Cancelled        = 0,
                                            Processed        = false
                                        };

                                        decimal Price;
                                        int     OrderlineID;
                                        int     Ordered;
                                        int     Invoiced;

                                        DateTime RequestDate;

                                        DateTime.TryParseExact(Order.OrderDate, "yyyyMMdd", null, DateTimeStyles.None, out RequestDate);

                                        int.TryParse(orderline.Invoiced, NumberStyles.Any, CultureInfo.InvariantCulture, out Invoiced);
                                        decimal.TryParse(orderline.Price, NumberStyles.Any, CultureInfo.InvariantCulture, out Price);
                                        int.TryParse(orderline.Ordered, NumberStyles.Any, CultureInfo.InvariantCulture, out Ordered);

                                        int.TryParse(orderline.OrderlineID, out OrderlineID);


                                        OrderResponseLine.Price       = Price;
                                        OrderResponseLine.OrderLineID = OrderlineID;
                                        OrderResponseLine.Ordered     = Ordered;
                                        OrderResponseLine.Invoiced    = Invoiced;
                                        OrderResponseLine.RequestDate = RequestDate;

                                        orderResponseLines.Add(OrderResponseLine);
                                    }
                                }
                            }

                            unit.Scope.Repository <OrderResponse>().Add(orderresponse);
                            unit.Scope.Repository <OrderResponseLine>().Add(orderResponseLines);
                        }
                    }
                }
            }


            unit.Save();
        }
Ejemplo n.º 7
0
 public void GenerateOrderResponse(OrderResponseTypes type, Objects.Models.EDI.Response.EdiOrderResponse orderResponse)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 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);
                }
            }
        }
Ejemplo n.º 9
0
        private void ProcessNotifications(FtpManager manager, OrderResponseTypes responseType, IAuditLogAdapter log, Vendor vendor, string logPath, IUnitOfWork unit)
        {
            //DataLoadOptions options = new DataLoadOptions();
            //options.LoadWith<Concentrator.Objects.Orders.Order>(x => x.OrderLines);

            foreach (var file in manager)
            {
                bool error = false;

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

                        Guid vendorDocumentReference = Guid.NewGuid();

                        string fileName = "Lenmar_" + responseType.ToString() + "_" + vendorDocumentReference + ".xml";

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

                        XNamespace xName = "http://logictec.com/schemas/internaldocuments";

                        OrderResponse            orderResponse      = null;
                        List <OrderResponseLine> orderResponseLines = null;

                        IEnumerable <XElement> orderDocuments = null;

                        if (responseType == OrderResponseTypes.InvoiceNotification)
                        {
                            orderDocuments = xdoc.Elements(xName + "Envelope").Elements("Messages").Elements(xName + "Invoice");
                        }
                        else if (responseType == OrderResponseTypes.ShipmentNotification)
                        {
                            orderDocuments = xdoc.Elements(xName + "Envelope").Elements("Messages").Elements(xName + "AdvancedShipNotice");
                        }
                        else if (responseType == OrderResponseTypes.Acknowledgement)
                        {
                            orderDocuments = xdoc.Elements(xName + "Envelope").Elements("Messages").Elements(xName + "POAck");
                        }

                        foreach (var orderDocument in orderDocuments)
                        {
                            if (responseType == OrderResponseTypes.ShipmentNotification)
                            {
                                orderResponse = new OrderResponse
                                {
                                    InvoiceDocumentNumber = orderDocument.Element("ASNHeader").Element("InvoiceNumber").Value,
                                    VendorDocumentNumber  = orderDocument.Element("ASNHeader").Element("OrderID").Value,
                                    OrderID            = int.Parse(orderDocument.Element("ASNHeader").Element("PartnerPO").Value),
                                    AdministrationCost = Decimal.Parse(orderDocument.Element("ASNHeader").Element("HandlingAmt").Value),
                                    TrackAndTrace      = orderDocument.Element("ASNTrackingNumbers").Element("ASNTrackingNumberItem").Element("TrackingNumber").Value,
                                    OrderDate          = DateTime.Parse(orderDocument.Element("ASNHeader").Element("PODateTime").Value),
                                    ResponseType       = responseType.ToString()
                                };

                                orderResponseLines = (from d in orderDocument.Elements("ASNItems").Elements("ASNItem")
                                                      select new OrderResponseLine
                                {
                                    OrderResponse = orderResponse,
                                    VendorLineNumber = d.Element("LineID").Value,
                                    OrderLineID = int.Parse(d.Element("PartnerLineID").Value),
                                    Ordered = int.Parse(d.Element("Qty").Value),
                                    Shipped = int.Parse(d.Element("QtyShipped").Value),
                                    VendorItemNumber = d.Element("SupplierSKU").Value,
                                    Price = decimal.Parse(d.Element("ItemPrice").Value) / 100,
                                    Barcode = d.Element("UPCCode").Value,
                                    Description = d.Element("Description").Value,
                                    OEMNumber = d.Element("MfgSKU").Value,
                                    DeliveryDate = DateTime.Parse(d.Element("ExpectedDeliveryDate").Value),
                                    TrackAndTrace = orderDocument.Element("ASNTrackingNumbers").Element("ASNTrackingNumberItem").Element("TrackingNumber").Value,
                                    RequestDate = DateTime.Parse(d.Element("RequestedShipDate").Value)
                                }).ToList();
                            }
                            else if (responseType == OrderResponseTypes.InvoiceNotification)
                            {
                                orderResponse = new OrderResponse
                                {
                                    InvoiceDocumentNumber               = orderDocument.Element("InvoiceHeader").Element("InvoiceNumber").Value,
                                    InvoiceDate                         = DateTime.Parse(orderDocument.Element("InvoiceHeader").Element("InvoiceDateTime").Value),
                                    PaymentConditionDays                = int.Parse(orderDocument.Element("InvoiceHeader").Element("InvoiceDaysDue").Value),
                                    PaymentConditionDiscount            = orderDocument.Element("InvoiceHeader").Element("DiscountDaysDue").Value,
                                    PaymentConditionDiscountDescription = orderDocument.Element("InvoiceHeader").Element("DiscountPercent").Value,
                                    TotalExVat           = decimal.Parse(orderDocument.Element("InvoiceHeader").Element("InvoiceTotal").Value),
                                    VatAmount            = decimal.Parse(orderDocument.Element("InvoiceHeader").Element("InvoiceTaxAmt").Value),
                                    VendorDocumentNumber = orderDocument.Element("InvoiceHeader").Element("OrderID").Value,
                                    OrderID            = int.Parse(orderDocument.Element("InvoiceHeader").Element("PartnerPO").Value),
                                    AdministrationCost = Decimal.Parse(orderDocument.Element("InvoiceHeader").Element("HandlingAmt").Value),
                                    TrackAndTrace      = orderDocument.Element("InvoiceTrackingNumbers").Element("InvoiceTrackingNumberItem").Element("TrackingNumber").Value,
                                    OrderDate          = DateTime.Parse(orderDocument.Element("InvoiceHeader").Element("PODateTime").Value),
                                    ResponseType       = responseType.ToString()
                                };

                                orderResponseLines = (from d in orderDocument.Elements("InvoiceItems").Elements("InvoiceItem")
                                                      select new OrderResponseLine
                                {
                                    OrderResponse = orderResponse,
                                    VendorLineNumber = d.Element("LineID").Value,
                                    OrderLineID = int.Parse(d.Element("PartnerLineID").Value),
                                    Ordered = int.Parse(d.Element("Qty").Value),
                                    Invoiced = int.Parse(d.Element("QtyShipped").Value),
                                    VendorItemNumber = d.Element("SupplierSKU").Value,
                                    Price = decimal.Parse(d.Element("ItemPrice").Value) / 100,
                                    Barcode = d.Element("UPCCode").Value,
                                    Description = d.Element("Description").Value,
                                    OEMNumber = d.Element("MfgSKU").Value,
                                    DeliveryDate = DateTime.Parse(d.Element("ActualShipDate").Value),
                                    RequestDate = DateTime.Parse(d.Element("RequestedShipDate").Value)
                                }).ToList();
                            }
                            else if (responseType == OrderResponseTypes.Acknowledgement)
                            {
                                orderResponse = new OrderResponse
                                {
                                    VendorDocumentNumber = orderDocument.Element("POAckHeader").Element("OrderID").Value,
                                    OrderID            = int.Parse(orderDocument.Element("POAckHeader").Element("PartnerPO").Value),
                                    AdministrationCost = Decimal.Parse(orderDocument.Element("POAckHeader").Element("HandlingAmt").Value),
                                    OrderDate          = DateTime.Parse(orderDocument.Element("POAckHeader").Element("PODateTime").Value),
                                    ResponseType       = responseType.ToString()
                                };

                                orderResponseLines = (from d in orderDocument.Elements("POAckItems").Elements("POAckItem")
                                                      select new OrderResponseLine
                                {
                                    OrderResponse = orderResponse,
                                    VendorLineNumber = d.Element("LineID").Value,
                                    OrderLineID = int.Parse(d.Element("PartnerLineID").Value),
                                    Ordered = int.Parse(d.Element("Qty").Value),
                                    Backordered = int.Parse(d.Element("QtyBackOrdered").Value),
                                    VendorItemNumber = d.Element("SupplierSKU").Value,
                                    Price = decimal.Parse(d.Element("ItemPrice").Value) / 100,
                                    Barcode = d.Element("UPCCode").Value,
                                    Description = d.Element("Description").Value,
                                    RequestDate = DateTime.Parse(d.Element("RequestedShipDate").Value)
                                }).ToList();
                            }

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


                            if (order != null)
                            {
                                orderResponse.VendorID           = vendor.VendorID;
                                orderResponse.ReceiveDate        = DateTime.Now;
                                orderResponse.VendorDocument     = xdoc.ToString();
                                orderResponse.VendorDocumentDate = DateTime.Now;
                                orderResponse.DocumentName       = fileName;
                                unit.Scope.Repository <OrderResponse>().Add(orderResponse);
                                unit.Scope.Repository <OrderResponseLine>().Add(orderResponseLines);
                            }
                            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)
                {
                    throw e;
                }
            }
        }
Ejemplo n.º 10
0
        public List <OrderResponse> GetOrderResponses(OrderResponseTypes type, IRepository <OrderResponse> repo)
        {
            string responseType = type.ToString();

            return(repo.GetAll(x => x.OrderResponseLines.Any(y => y.OrderLineID.HasValue && y.OrderLine.OrderID == OrderID) && x.ResponseType == responseType).ToList());
        }