/// <summary>
        ///   Processes an order response
        /// </summary>
        public void GetAvailableDispatchAdvices(Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, string logPath, DataAccess.UnitOfWork.IUnitOfWork unit)
        {
            //Creates an instance of xdocument
            XDocument doc = new XDocument();

            // creates an instance of Xmlreader
            using (XmlReader reader = XmlReader.Create(new StringReader(_response)))
            {
                while (reader.Read())
                {
                    // Loads the soap response into the locally created Xdocument
                    doc = XDocument.Load(reader);
                }
                // Calls method ProcessXml
                ProcessXml(doc, vendor, unit);
            }
        }
        public int DispatchOrders(Dictionary <Models.Orders.Order, List <Models.Orders.OrderLine> > orderLines, Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, DataAccess.UnitOfWork.IUnitOfWork uni)
        {
            var Username = vendor.VendorSettings.GetValueByKey("Username", string.Empty);
            var Secret   = vendor.VendorSettings.GetValueByKey("Secret", string.Empty);

            var _orderResponseRepo        = uni.Scope.Repository <OrderResponse>();
            var _orderResponseLineRepo    = uni.Scope.Repository <OrderResponseLine>();
            var _orderItemFulfillmentRepo = uni.Scope.Repository <OrderItemFullfilmentInformation>();


            RetailServices10SoapClient client = new RetailServices10SoapClient();

            RetailAccount account = new RetailAccount();

            var inputString = Username + Secret;

            MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();

            byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(inputString);
            byte[] byteHash  = MD5.ComputeHash(byteValue);
            MD5.Clear();

            account.Client     = Username;
            account.SecureHash = Convert.ToBase64String(byteHash);

            var response = client.Ping(account);

            if (response != null)
            {
                log.AuditInfo("AtomBlock services are online");

                ShopOrder[] orders = new ShopOrder[orderLines.Count()];

                int orderCount = 0;
                foreach (var order in orderLines.Keys)
                {
                    int       count       = 0;
                    double    totalAmount = 0;
                    ShopOrder shopOrder   = new ShopOrder();
                    shopOrder.Identifier  = order.OrderID.ToString();
                    shopOrder.IsTestOrder = true;
                    shopOrder.Items       = new ShopOrderItemRequest[order.OrderLines.Count()];
                    //shopOrder.PaymentMethod = "????"; //SET PAYMENT

                    foreach (var item in order.OrderLines)
                    {
                        shopOrder.Items[count]                   = new ShopOrderItemRequest();
                        shopOrder.Items[count].Discount          = 0; // ?????
                        shopOrder.Items[count].ItemPrice         = (int)item.Price * 100;
                        shopOrder.Items[count].ProductIdentifier = item.Product.VendorAssortments.FirstOrDefault(x => x.VendorID == vendor.VendorID).CustomItemNumber;
                        shopOrder.Items[count].Quantity          = item.GetDispatchQuantity();
                        count++;
                        totalAmount += item.Price.Value;
                    }

                    shopOrder.TotalAmount          = (int)totalAmount;
                    shopOrder.TotalDiscount        = 0; // ?????
                    shopOrder.TotalTransactionCost = 0; // ?????
                    orders[orderCount]             = shopOrder;
                    orderCount++;
                }

                ShopProfile profile = new ShopProfile();
                //add info?
                // profile.Email =

                var result    = client.AddOrderBatched(account, profile, orders);
                var successes = new List <ShopOrderReceipt>();
                var failures  = new List <ShopOrderReceipt>();

                if (orders.Count() > 0)
                {
                    LogOrder(orders, vendor.VendorID, string.Format("{0}.xml", orders.FirstOrDefault().Identifier), log);
                }

                foreach (var callback in result)
                {
                    switch (callback.CommunicationStatus.Type)
                    {
                    case MessageType.ERROR:
                        failures.Add(callback);
                        break;

                    case MessageType.NO_ACCESS:
                        failures.Add(callback);
                        break;

                    case MessageType.OK:
                        successes.Add(callback);
                        break;

                    case MessageType.WRONG_REQUEST:
                        failures.Add(callback);
                        break;

                    default:
                        failures.Add(callback);
                        break;
                    }
                }
                //all orders correctly processed
                log.AuditInfo("Processing order details");

                foreach (var success in successes)
                {
                    var id    = Int32.Parse(success.Reference);
                    var Order = uni.Scope.Repository <Order>().GetSingle(x => x.OrderID == id);

                    if (Order != null)
                    {
                        var orderResponse = new OrderResponse
                        {
                            Order                = Order,
                            OrderDate            = DateTime.Now,
                            ReceiveDate          = DateTime.Now,
                            Vendor               = vendor,
                            VendorDocument       = "",
                            VendorDocumentNumber = Order.OrderID.ToString()
                        };
                        orderResponse.ResponseType = OrderResponseTypes.ShipmentNotification.ToString();
                        _orderResponseRepo.Add(orderResponse);

                        var TotalAmount = 0;

                        foreach (var orderline in success.OrderLines)
                        {
                            var name = orderline.Title;

                            var OrderLine = Order.OrderLines.FirstOrDefault(x => x.Product.ProductDescriptions.FirstOrDefault(p => p.ProductName == name).ProductName == name);

                            if (OrderLine != null)
                            {
                                var orderResponseLine = new OrderResponseLine
                                {
                                    OrderResponse = orderResponse,
                                    OrderLine     = OrderLine,
                                    Ordered       = orderline.Quantity,
                                    Backordered   = orderline.IsPreOrder ? orderline.Quantity : 0,
                                    Cancelled     = 0,
                                    Shipped       = orderline.IsPreOrder ? 0 : orderline.Quantity,
                                    Invoiced      = orderline.IsPreOrder ? 0 : orderline.Quantity,
                                    Price         = orderline.ItemPrice / 100,
                                    Processed     = false,
                                    Delivered     = 0,
                                    ProductName   = name,
                                    Remark        = orderline.IsPreOrder ? string.Format("PreOrder:{0}", orderline.PreOrderReleaseDate.ToString()) : null
                                };

                                _orderResponseLineRepo.Add(orderResponseLine);

                                TotalAmount += orderline.ItemPrice / 100;

                                if (!orderline.IsPreOrder)
                                {
                                    //DownloadFiles
                                    foreach (var file in orderline.DownloadFiles)
                                    {
                                        var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                        {
                                            OrderResponseLine = orderResponseLine
                                        };
                                        orderItemFullfilmentInformation.Type  = "Name";
                                        orderItemFullfilmentInformation.Label = "FileName";
                                        orderItemFullfilmentInformation.Value = file.File;
                                        _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                    }

                                    //Serials
                                    foreach (var serial in orderline.Serials)
                                    {
                                        var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                        {
                                            OrderResponseLine = orderResponseLine
                                        };
                                        orderItemFullfilmentInformation.Type  = "Key";
                                        orderItemFullfilmentInformation.Label = "Serial";
                                        orderItemFullfilmentInformation.Value = serial.Code;
                                        _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                    }

                                    //additional stuff
                                    foreach (var prop in orderline.GetType().GetProperties())
                                    {
                                        var propName = prop.Name;
                                        if (propName == "DownloadManagerUrl" || propName == "DownloadManagerReference" || propName == "SetupFileName")
                                        {
                                            var value = prop.GetValue(orderline, null);

                                            var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                            {
                                                OrderResponseLine = orderResponseLine
                                            };
                                            orderItemFullfilmentInformation.Type  = propName == "DownloadManagerUrl" ? "Binary" : "Name";
                                            orderItemFullfilmentInformation.Label = propName;
                                            orderItemFullfilmentInformation.Value = value.ToString();
                                            _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                        }
                                    }
                                }
                            }
                            else
                            {
                            }
                        }
                        orderResponse.TotalAmount = TotalAmount;
                    }
                }

                if (failures.Count != 0)
                {
                    log.AuditError("Some orders failed to process: ");
                    foreach (var failure in failures)
                    {
                        log.AuditError(string.Format("Failed ID: {0}", failure.OrderIdentifier));
                    }
                }
            }
            else
            {
                log.AuditError("AtomBlock services are offline, or incorrect credentials");
                return(-1);
            }
            uni.Save();
            return(0);
        }
Exemplo n.º 3
0
 public void OrderChange(Concentrator.Web.Objects.EDI.ChangeOrder.ChangeOrderRequest changeOrderRequest, Models.Vendors.Vendor administrativeVendor, List <Models.Orders.OrderLine> orderLines)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 4
0
 public void InvoiceMessage(Concentrator.Web.Objects.EDI.InvoiceMessage invoiceMessage, Models.Vendors.Vendor administrativeVendor, List <Models.Orders.OrderLine> orderLines)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 5
0
 public void PurchaseConfirmation(Concentrator.Web.Objects.EDI.Purchase.PurchaseConfirmation purchaseConfirmation, Models.Vendors.Vendor administrativeVendor, List <Models.Orders.OrderLine> orderLines)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 6
0
 public int DispatchOrders(Dictionary <Models.Orders.Order, List <Models.Orders.OrderLine> > orderLines, Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, DataAccess.UnitOfWork.IUnitOfWork uni)
 {
     foreach (var ord in orderLines)
     {
         Console.WriteLine(string.Format("{0} : {1}", ord.Key, string.Join(", ", ord.Value.Select(c => c.CustomerItemNumber).ToArray())));
     }
     return(1);
 }
Exemplo n.º 7
0
 public void PurchaseConfirmation(Concentrator.Web.Objects.EDI.Purchase.PurchaseConfirmation purchaseConfirmation, Models.Vendors.Vendor administrativeVendor, List <Models.Orders.OrderLine> orderLines)
 {
     return;
 }
Exemplo n.º 8
0
 public void CancelOrder(Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, string logPath)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 9
0
        public int DispatchOrders(Dictionary <Models.Orders.Order, List <Models.Orders.OrderLine> > orderLines, Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, DataAccess.UnitOfWork.IUnitOfWork uni)
        {
            var CustNo          = vendor.VendorSettings.GetValueByKey("CopacoCustomerNo", string.Empty);
            var SenderID        = vendor.VendorSettings.GetValueByKey("CopacoSenderID", string.Empty);
            var FtpUrl          = vendor.VendorSettings.GetValueByKey("FtpUrl", string.Empty);
            var FtpUserName     = vendor.VendorSettings.GetValueByKey("Username", string.Empty);
            var FtpPassword     = vendor.VendorSettings.GetValueByKey("Password", string.Empty);
            var UploadDirectory = vendor.VendorSettings.GetValueByKey("UploadDirectory", string.Empty);

            Concentrator.Objects.Ordering.XmlClasses.Customer customer = new Concentrator.Objects.Ordering.XmlClasses.Customer();
            customer.customerid = CustNo;

            foreach (var order in orderLines.Keys)
            {
                int count = 0;

                //new order
                XML_order orderxml = new XML_order();
                orderxml.documentsource       = "order_in";
                orderxml.external_document_id = order.OrderID.ToString();
                orderxml.supplier             = "COPACO";

                //order header with customer and shipping info
                orderheader header = new orderheader();
                header.Customer               = customer; // set customer
                header.completedelivery       = "N";
                header.requested_deliverydate = "";
                header.customer_ordernumber   = order.OrderID.ToString();
                header.sender_id              = SenderID;
                header.testflag               = "Y";
                header.recipientsreference    = order.CustomerOrderReference;


                // shipping info
                ShipTo ship   = new ShipTo();
                adress adress = new adress();
                adress.name1 = order.ShippedToCustomer.CustomerName;


                //overige ook toevoegen?
                adress.street            = order.ShippedToCustomer.CustomerAddressLine1 + " " + order.ShippedToCustomer.HouseNumber;
                adress.postalcode        = order.ShippedToCustomer.PostCode.Substring(0, 4) + " " + order.ShippedToCustomer.PostCode.Substring(4);
                adress.city              = order.ShippedToCustomer.City;
                adress.country           = order.ShippedToCustomer.Country;
                ship.Items               = new adress[1];
                ship.ItemsElementName    = new ItemsChoiceType[1];
                ship.ItemsElementName[0] = ItemsChoiceType.adress;
                ship.Items[0]            = adress;

                #region future use

                //notification notification = new notification();
                //ordertext ordertext = new ordertext();
                //License_data license_data = new License_data();
                //end_user_contact end_user_contact = new end_user_contact();

                //header.notification = notification;
                //header.ordertext = new ordertext[1];
                //header.ordertext[0] = ordertext;
                //header.License_data = license_data;
                //header.License_data.end_user_contact = end_user_contact;
                #endregion

                //orderline array
                orderxml.orderline = new orderline[order.OrderLines.Count];

                //add basic info to xml
                orderxml.orderheader        = header;
                orderxml.orderheader.ShipTo = ship;


                foreach (var itemOrder in order.OrderLines)
                {
                    //add orderline
                    orderline orderline = new orderline();
                    orderline.linenumber       = itemOrder.OrderLineID.ToString();
                    orderline.item_id          = new item_id[1];
                    orderline.item_id[0]       = new item_id();
                    orderline.item_id[0].tag   = "PN";
                    orderline.item_id[0].Value = itemOrder.Product.VendorAssortments.FirstOrDefault(x => x.VendorID == vendor.VendorID).CustomItemNumber;
                    orderline.quantity         = new quantity();
                    orderline.quantity.unit    = "ST";
                    orderline.quantity.Value   = itemOrder.GetDispatchQuantity().ToString();
                    //orderline.deliverydate = "";//DateTime.Today.AddDays(1).ToString("DD-MM-YYYY");
                    orderline.price           = new price();
                    orderline.price.currency  = "EUR";
                    orderline.price.Value     = itemOrder.Price.Value.ToString().Replace(',', '.');
                    orderxml.orderline[count] = orderline;

                    count++;
                }

                string            fileName      = string.Format("Order_{0}.xml", order.OrderID.ToString());
                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(orderxml.GetType());
                    XmlSerializerNamespaces nm         = new XmlSerializerNamespaces();
                    nm.Add("", "");
                    serializer.Serialize(xw, orderxml, nm);

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

                    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

                    byte[] file = encoding.GetBytes(xml.InnerXml.ToString());

                    SimpleFtp ftp = new SimpleFtp(FtpUrl, FtpUserName, FtpPassword, log, true);
                    ftp.UploadFile(file, fileName, UploadDirectory);

                    LogOrder(xml, vendor.VendorID, fileName, log);
                }
            }

            return(0);
        }
Exemplo n.º 10
0
        public bool PurchaseOrders(Models.Orders.Order order, List <Models.Orders.OrderLine> orderLines, Models.Vendors.Vendor administrativeVendor, Models.Vendors.Vendor vendor, bool directShipment, DataAccess.UnitOfWork.IUnitOfWork unit, log4net.ILog logger)
        {
            try
            {
                var webShopStockType = unit.Scope.Repository <VendorStockType>().GetSingle(x => x.StockType == "Webshop");

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



                orderLines.Where(c => (!c.Product.IsNonAssortmentItem.HasValue || (c.Product.IsNonAssortmentItem.HasValue && !c.Product.IsNonAssortmentItem.Value))).ToList().ForEach(line =>
                {
                    var webshopStock = line.Product.VendorStocks.FirstOrDefault(x => x.VendorStockTypeID == webShopStockType.VendorStockTypeID && x.VendorID == int.Parse(ConfigurationManager.AppSettings["ATVendorID"]));
                    if (webshopStock == null)
                    {
                        throw new Exception(string.Format("Stocklocation Webshop does not exists for product {0}, skip order process", line.ProductID));
                    }



                    if (line.Quantity > webshopStock.QuantityOnHand)
                    {
                        //CANCEL LINE
                        int qtyCancelled = Math.Abs(line.Quantity - Math.Abs(webshopStock.QuantityOnHand));
                        line.SetStatus(OrderLineStatus.Cancelled, unit.Scope.Repository <OrderLedger>(), qtyCancelled);
                        CancelLine(line, unit, qtyCancelled, "Out of stock");
                    }
                    else
                    {
                        webshopStock.QuantityOnHand -= line.GetDispatchQuantity();
                        line.SetStatus(OrderLineStatus.ReadyToOrder, unit.Scope.Repository <OrderLedger>());
                    }
                });
            }
            catch (Exception e)
            {
                logger.Debug(e);
            }

            unit.Save();

            return(false);
        }
Exemplo n.º 11
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();
        }
Exemplo n.º 12
0
        public int DispatchOrders(Dictionary <Models.Orders.Order, List <Models.Orders.OrderLine> > orderLines, Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, DataAccess.UnitOfWork.IUnitOfWork uni)
        {
            var AmacomUrl   = vendor.VendorSettings.GetValueByKey("AmacomUrl", string.Empty);
            var OrderPath   = vendor.VendorSettings.GetValueByKey("OrderPath", string.Empty);
            var Username    = vendor.VendorSettings.GetValueByKey("Username", string.Empty);
            var Password    = vendor.VendorSettings.GetValueByKey("Password", string.Empty);
            var Organistion = vendor.VendorSettings.GetValueByKey("Organisation", string.Empty);
            var Fact        = vendor.VendorSettings.GetValueByKey("FactDeb", string.Empty);

            FtpManager orderUploader = new FtpManager(
                AmacomUrl,
                OrderPath,
                Username,
                Password,
                false, true, log);

            //Generate CSV

            DataTable table = new DataTable();

            table.Columns.Add("vkorg");
            table.Columns.Add("bstkd_besteldatumt");
            table.Columns.Add("betaler_kunre");
            table.Columns.Add("vastklantnummer_kunnr");
            table.Columns.Add("bstnk");
            table.Columns.Add("posnr");
            table.Columns.Add("kunnr");
            table.Columns.Add("matnr");
            table.Columns.Add("kwmeng");
            table.Columns.Add("vrkme");
            table.Columns.Add("leeg");
            table.Columns.Add("kunwe");
            table.Columns.Add("name1");
            table.Columns.Add("stras");
            table.Columns.Add("pstlz");
            table.Columns.Add("ort01");
            table.Columns.Add("land1");
            table.Columns.Add("kunre");
            table.Columns.Add("email");
            table.Columns.Add("tel");

            foreach (var order in orderLines.Keys)
            {
                DataRow row = table.NewRow();
                row["vkorg"] = Organistion;
                row["bstkd_besteldatumt"]    = DateTime.Now.ToString("ddMMyyyy");
                row["betaler_kunre"]         = Fact;
                row["vastklantnummer_kunnr"] = "";
                table.Rows.Add(row);

                DataRow line = table.NewRow();
                line[0] = order.OrderID.ToString();
                foreach (var orderline in order.OrderLines)
                {
                    var customItemNr = orderline.Product.VendorAssortments.FirstOrDefault().CustomItemNumber;

                    if (customItemNr.Length < 18)
                    {
                        customItemNr = "";
                        for (int i = orderline.Product.VendorAssortments.FirstOrDefault().CustomItemNumber.Length; i < 18; i++)
                        {
                            customItemNr += "0";
                        }
                        customItemNr += orderline.Product.VendorAssortments.FirstOrDefault().CustomItemNumber;
                    }

                    line[1]  = orderline.OrderLineID.ToString();
                    line[2]  = "";
                    line[3]  = customItemNr;
                    line[4]  = orderline.GetDispatchQuantity().ToString();
                    line[5]  = "";
                    line[6]  = "";
                    line[7]  = "";
                    line[8]  = order.ShippedToCustomer.CustomerName;
                    line[9]  = order.ShippedToCustomer.CustomerAddressLine1;
                    line[10] = order.ShippedToCustomer.PostCode;
                    line[11] = order.ShippedToCustomer.City;
                    line[12] = order.ShippedToCustomer.Country;
                    line[14] = "";
                    line[14] = order.ShippedToCustomer.CustomerEmail;
                    line[15] = order.ShippedToCustomer.CustomerTelephone;

                    table.Rows.Add(line);
                    line = table.NewRow();
                }

                CsvWriter csvWriter = new CsvWriter(table, '\t');
                var       csv       = csvWriter.AsString();
                //edit new line

                csv = csv.Substring(0, 60) + Environment.NewLine + csv.Substring(61);

                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

                var          fileName = string.Format("BasOrder_{0}.csv", order.OrderID.ToString());
                byte[]       file     = encoding.GetBytes(csv);
                MemoryStream stream   = new MemoryStream(file);
                //Place order on FTP
                orderUploader.Upload(stream, fileName);

                LogOrder(csv, vendor.VendorID, fileName, log);
            }

            throw new NotImplementedException();
        }
        private bool ProcessXml(XDocument doc, Models.Vendors.Vendor vendor, DataAccess.UnitOfWork.IUnitOfWork unit)
        {
            // Name space needed
            XNamespace xName = "http://www.cbonline.nl/xsd";
            // The soap hierarchy
            IEnumerable <XElement> hierarchy = doc.Root.Descendants().Elements("return").Elements(xName + "CbOrderProduct").Descendants();
            //use this to check if its a bundle
            IEnumerable <XElement> eBookBundle = hierarchy.Elements(xName + "Item");

            // Checks for errors
            var errorList = (from e in hierarchy.Elements("Error")
                             select new
            {
                ErrorCode = e.Element("ErrorCode").Value,
                Msg = e.Element("ErrorMsg").Value
            }).FirstOrDefault();

            // If theres an error, return!
            if (errorList != null)
            {
                return(false);
            }

            // Retrieves the order references
            var orderList = (from i in hierarchy
                             select new
            {
                CbOrderReference = i.Element(xName + "CbOrderReference").Value,
                OrderReference = i.Element(xName + "OrderReference").Value,
            }).FirstOrDefault();

            // Creates a new object of type OrderResponse
            var orderResponse = new OrderResponse()
            {
                OrderID              = Int32.Parse(orderList.OrderReference.Remove(0, 1)),
                ResponseType         = Enum.GetName(typeof(OrderResponseTypes), 100),
                VendorDocument       = doc.ToString(),
                VendorID             = vendor.VendorID,
                VendorDocumentNumber = orderList.CbOrderReference,
                ReceiveDate          = DateTime.Today
            };

            // Add the new object to the OrderResponse repository
            unit.Scope.Repository <OrderResponse>().Add(orderResponse);

            // Retrieves the orderline from the order
            var _orderLineRepo = unit.Scope.Repository <OrderLine>().GetSingle(x => x.OrderID == orderResponse.OrderID);
            // Instanciates a new OrderResponseLine
            var orderResponseLine = new OrderResponseLine();

            // if its a bundle book
            if (eBookBundle.Count() > 0)
            {
                // The response contains multiple items, so for each item..
                eBookBundle.ForEach((item, idx) =>
                {
                    // creates a new OrderResponseLine
                    orderResponseLine = new OrderResponseLine()
                    {
                        OrderResponseID  = orderResponse.OrderResponseID,
                        OrderLineID      = _orderLineRepo.OrderLineID,
                        Ordered          = 1,
                        Backordered      = 0,
                        Cancelled        = 0,
                        Shipped          = 0,
                        Invoiced         = 0,
                        Price            = Decimal.Parse(_orderLineRepo.Price.ToString()),
                        Processed        = false,
                        Delivered        = 0,
                        VendorItemNumber = item.Element(xName + "EAN").Value
                    };
                    // Adds it to the repository
                    unit.Scope.Repository <OrderResponseLine>().Add(orderResponseLine);

                    // creates a new orderitemfullfillment object
                    var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation()
                    {
                        OrderResponseLine = orderResponseLine,
                        Value             = item.Element(xName + "DownloadURL").Value
                    };
                    // adds it to the repository
                    unit.Scope.Repository <OrderItemFullfilmentInformation>().Add(orderItemFullfilmentInformation);
                });
            }

            // A single book
            else
            {
                // retries the download links
                var downloadlinks = (from i in hierarchy
                                     select new
                {
                    DownloadPage = i.Element(xName + "DownloadPage").Value,
                    DownloadURL = i.Element(xName + "DownloadURL").Value
                }).FirstOrDefault();

                //Creates a new OrderResponseLine object
                orderResponseLine = new OrderResponseLine()
                {
                    OrderResponseID = orderResponse.OrderResponseID,
                    OrderLineID     = _orderLineRepo.OrderLineID,
                    Ordered         = 1,
                    Backordered     = 0,
                    Cancelled       = 0,
                    Shipped         = 0,
                    Invoiced        = 0,
                    Price           = Decimal.Parse(_orderLineRepo.Price.ToString()),
                    Processed       = false,
                    Delivered       = 0
                };
                // Adds it to the repository
                unit.Scope.Repository <OrderResponseLine>().Add(orderResponseLine);

                // Creates a new OrderItemFullfilmentInformation object
                var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation()
                {
                    OrderResponseLine = orderResponseLine,
                    Value             = downloadlinks.DownloadURL
                };
                // Adds it to the repository
                unit.Scope.Repository <OrderItemFullfilmentInformation>().Add(orderItemFullfilmentInformation);
            }

            // Saves the objects
            unit.Save();

            // returns true
            return(true);
        }
        public void GetAvailableDispatchAdvices(Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, string logPath, DataAccess.UnitOfWork.IUnitOfWork unit)
        {
            var Username = vendor.VendorSettings.GetValueByKey("Username", string.Empty);
            var Secret   = vendor.VendorSettings.GetValueByKey("Secret", string.Empty);

            var _orderResponseRepo        = unit.Scope.Repository <OrderResponse>();
            var _orderResponseLineRepo    = unit.Scope.Repository <OrderResponseLine>();
            var _orderItemFulfillmentRepo = unit.Scope.Repository <OrderItemFullfilmentInformation>();

            RetailServices10SoapClient client = new RetailServices10SoapClient();

            RetailAccount account = new RetailAccount();

            var inputString = Username + Secret;

            MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();

            byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(inputString);
            byte[] byteHash  = MD5.ComputeHash(byteValue);
            MD5.Clear();

            account.Client     = Username;
            account.SecureHash = Convert.ToBase64String(byteHash);

            var response = client.Ping(account);

            if (response != null)
            {
                log.AuditInfo("AtomBlock services are online");

                //get orderresponses for items pre ordered
                var items = unit.Scope.Repository <OrderResponse>().GetAll(x => x.ResponseType == OrderResponseTypes.ShipmentNotification.ToString() && x.Vendor == vendor);

                foreach (var item in items)
                {
                    var preOrders = item.OrderResponseLines.Where(x => x.Backordered > 0);

                    var OrdersToProcess = new List <string>();

                    foreach (var order in preOrders)
                    {
                        var TotalAmount = 0;
                        var releaseDate = DateTime.Parse(order.Remark.Substring(9).Trim());
                        if (releaseDate < DateTime.Now)
                        {
                            ////item is available so get order details
                            //var productIdentifier = unit.Scope.Repository<ProductDescription>().GetSingle(x => x.ProductName == order.ProductName).Product.VendorItemNumber;//nasty

                            if (order.OrderLineID.HasValue)
                            {
                                var success = client.GetOrderDetails(account, order.OrderLine.OrderID.ToString());
                                if (success.CommunicationStatus.Type == MessageType.OK)
                                {
                                    var Order = order.OrderLine.Order;
                                    //var Order = uni.Scope.Repository<Order>().GetSingle(x => x.OrderID == Int32.Parse(success.OrderIdentifier));
                                    var orderResponse = new OrderResponse
                                    {
                                        Order = Order,
                                        // OrderDate = Order.,
                                        ReceiveDate          = DateTime.Now,
                                        VendorDocument       = "",
                                        Vendor               = vendor,
                                        VendorDocumentNumber = Order.OrderID.ToString()
                                    };
                                    orderResponse.ResponseType = OrderResponseTypes.ShipmentNotification.ToString();
                                    _orderResponseRepo.Add(orderResponse);


                                    foreach (var orderline in success.OrderLines)
                                    {
                                        var name = orderline.Title;

                                        var OrderLine = Order.OrderLines.FirstOrDefault(x => x.Product.ProductDescriptions.FirstOrDefault().ProductName == name);

                                        if (OrderLine != null)
                                        {
                                            var orderResponseLine = new OrderResponseLine
                                            {
                                                OrderResponse = orderResponse,
                                                OrderLine     = OrderLine,
                                                Ordered       = orderline.Quantity,
                                                Backordered   = orderline.IsPreOrder ? orderline.Quantity : 0, //should always be false
                                                Cancelled     = 0,
                                                Shipped       = orderline.IsPreOrder ? 0 : orderline.Quantity,
                                                Invoiced      = orderline.IsPreOrder ? 0 : orderline.Quantity,
                                                Price         = orderline.ItemPrice,
                                                Processed     = false,
                                                Delivered     = 0,
                                                ProductName   = name,
                                                Remark        = orderline.IsPreOrder ? string.Format("PreOrder:{0}", orderline.PreOrderReleaseDate.ToString()) : null
                                            };

                                            _orderResponseLineRepo.Add(orderResponseLine);

                                            TotalAmount += orderline.ItemPrice / 100;

                                            if (!orderline.IsPreOrder)
                                            {
                                                //DownloadFiles
                                                foreach (var file in orderline.DownloadFiles)
                                                {
                                                    var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                                    {
                                                        OrderResponseLine = orderResponseLine
                                                    };
                                                    orderItemFullfilmentInformation.Type  = "Name";
                                                    orderItemFullfilmentInformation.Label = "FileName";
                                                    orderItemFullfilmentInformation.Value = file.File;
                                                    _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                                }

                                                //Serials
                                                foreach (var serial in orderline.Serials)
                                                {
                                                    var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                                    {
                                                        OrderResponseLine = orderResponseLine
                                                    };
                                                    orderItemFullfilmentInformation.Type  = "Key";
                                                    orderItemFullfilmentInformation.Label = "Serial";
                                                    orderItemFullfilmentInformation.Value = serial.Code;
                                                    _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                                }

                                                //additional stuff
                                                foreach (var prop in orderline.GetType().GetProperties())
                                                {
                                                    var propName = prop.Name;
                                                    if (propName == "DownloadManagerUrl" || propName == "DownloadManagerReference" || propName == "SetupFileName")
                                                    {
                                                        var value = prop.GetValue(orderline, null);

                                                        var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                                        {
                                                            OrderResponseLine = orderResponseLine
                                                        };
                                                        orderItemFullfilmentInformation.Type  = propName == "DownloadManagerUrl" ? "Binary" : "Name";
                                                        orderItemFullfilmentInformation.Label = propName;
                                                        orderItemFullfilmentInformation.Value = value.ToString();
                                                        _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //hmmzz very strange indeed
                                        }
                                    }
                                    orderResponse.TotalAmount = TotalAmount;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                log.AuditError("AtomBlock services are offline, or incorrect credentials");
            }
        }
Exemplo n.º 15
0
 public void InvoiceMessage(Concentrator.Web.Objects.EDI.InvoiceMessage invoiceMessage, Models.Vendors.Vendor administrativeVendor, List <Models.Orders.OrderLine> orderLines)
 {
     return;
 }
Exemplo n.º 16
0
 public void GetAvailableDispatchAdvices(Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, string logPath, DataAccess.UnitOfWork.IUnitOfWork unit)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 17
0
 public void OrderChange(Concentrator.Web.Objects.EDI.ChangeOrder.ChangeOrderRequest changeOrderRequest, Models.Vendors.Vendor administrativeVendor, List <Models.Orders.OrderLine> orderLines)
 {
     return;
 }
Exemplo n.º 18
0
        public int DispatchOrders(Dictionary <Models.Orders.Order, List <Models.Orders.OrderLine> > orderLines, Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, DataAccess.UnitOfWork.IUnitOfWork uni)
        {
            try
            {
                if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["ConcentratorMailerUrl"]))
                {
                    throw new Exception("ConcentratorMailerUrl setting empty or not in Config");
                }

                var mailerUrl = new Uri(new Uri(ConfigurationManager.AppSettings["ConcentratorMailerUrl"]), "SendIngramOrder");

                List <IngramMailProduct> productList = new List <IngramMailProduct>();

                foreach (var order in orderLines.Keys)
                {
                    foreach (var orderline in orderLines[order])
                    {
                        IngramMailProduct product = new IngramMailProduct();

                        product.CustomItemNumber   = orderline.Product.VendorAssortments.FirstOrDefault().CustomItemNumber;
                        product.ProductDescription = orderline.Product.VendorAssortments.FirstOrDefault().ShortDescription;
                        product.Price            = orderline.Price.ToString();
                        product.NumberOfProducts = orderline.Quantity.ToString();

                        productList.Add(product);
                    }


                    var data = new IngramMailData
                    {
                        CustomerName = order.ShippedToCustomer.CustomerName,
                        Address      = order.ShippedToCustomer.CustomerAddressLine1,
                        Email        = order.ShippedToCustomer.CustomerEmail,
                        PhoneNumber  = order.ShippedToCustomer.CustomerTelephone,
                        ProductList  = productList
                    };

                    StringBuilder     requestString = new StringBuilder();
                    XmlWriterSettings settings      = new XmlWriterSettings();
                    settings.Encoding = Encoding.UTF8;
                    using (XmlWriter xw = XmlWriter.Create(requestString, settings))
                    {
                        XmlSerializer           serializer = new XmlSerializer(typeof(IngramMailData));
                        XmlSerializerNamespaces nm         = new XmlSerializerNamespaces();
                        nm.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                        serializer.Serialize(xw, data);

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

                        byte[] byteData = UTF8Encoding.UTF8.GetBytes(document.OuterXml);

                        using (Stream s = request.GetRequestStream())
                        {
                            s.Write(byteData, 0, byteData.Length);
                        }

                        var result = request.GetResponse();

                        log.AuditSuccess("The order has been successfully mailed to the customer");

                        LogOrder(document, vendor.VendorID, string.Format("{0}.xml", order.OrderID), log);
                    }
                }
                return(1);
            }
            catch (Exception e)
            {
                log.Error(e.Message, e.InnerException);

                return(0);
            }
        }
        /// <summary>
        ///   Dispatches passed in order lines
        /// </summary>
        public int DispatchOrders(Dictionary <Models.Orders.Order, List <Models.Orders.OrderLine> > orderLines, Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, DataAccess.UnitOfWork.IUnitOfWork uni)
        {
            foreach (var order in orderLines)
            {
                //Retrieves the values
                String EAN            = uni.Scope.Repository <VendorAssortment>().GetSingle(c => c.VendorID == vendor.VendorID).CustomItemNumber;
                String orderReference = String.Concat("C", order.Key.OrderID.ToString());
                String clientID       = ConfigurationManager.AppSettings.Get("CbClientID"); //We will get this from centraal boekhuis

                //Checks if the book is available //DON'T REMOVE UNLESS YOURE SURE! this checks if the book is available
                //SendSoapRequest(EAN, orderReference, clientID, false, true);

                // Order Product request
                SendSoapRequest(EAN, orderReference, clientID, true, false);

                //TEST
                //string orderReference = DateTime.Now.TimeOfDay.ToString();

                //Test
                //GetAvailableDispatchAdvices(vendor, log, String.Empty, uni);
            }

            // Whatever floats your boat!
            return(orderLines.Count());
        }