private void ProcessSalesOrderNotifications(IEnumerable <OrderNotification> listOfNotifications) { var listOfOrders = listOfNotifications .Where(x => x.OrderType == (int)OrderTypes.PickTicketOrder && x.WebSiteOrderNumber.StartsWith("SDO")) .GroupBy(x => x.OrderID); foreach (var salesOrder in listOfOrders) { var orderNumber = salesOrder.First().WebSiteOrderNumber; _log.AuditInfo(string.Format("Start processing ShipmentNotification for OrderNumber '{0}'", orderNumber)); ProcessSalesOrderNotification(salesOrder, orderNumber); } }
public void Execute(JobExecutionContext context) { string pluginName = context.JobDetail.FullName; try { using (var unit = GetUnitOfWork()) { DataMap = context.JobDetail.JobDataMap; DateTime start = DateTime.Now; Plugin plugin = null; if (DataMap.Contains("Plugin")) { int pluginID = ((Plugin)DataMap.Get("Plugin")).PluginID; plugin = unit.Scope.Repository <Plugin>().GetSingle(x => x.PluginID == pluginID); plugin.NextRun = null; plugin.Duration = null; } ConnectorSchedule schedule = null; if (DataMap.Contains("ConnectorSchedule")) { int connectorScheduleID = ((ConnectorSchedule)DataMap.Get("ConnectorSchedule")).ConnectorScheduleID; schedule = unit.Scope.Repository <ConnectorSchedule>().GetSingle(x => x.ConnectorScheduleID == connectorScheduleID); schedule.LastRun = start; schedule.Duration = null; schedule.ScheduledNextRun = null; schedule.ConnectorScheduleStatus = (int)ConnectorScheduleStatus.Running; } unit.Save(); Running = true; log.InfoFormat("Starting plugin: {0}", pluginName); Concentrator.Objects.Web.Client.Login(Concentrator.Objects.Web.ConcentratorPrincipal.SystemPrincipal); var _repoConnectors = unit.Scope.Repository <Connector>(); // filter connectors based on the optional attribute on Plugin level var att = GetType().GetCustomAttributes(typeof(ConnectorSystemAttribute), true); if (att.Length > 0) { var attributevalue = ((ConnectorSystemAttribute)att[0]).ConnectorSystem; _connectors = _repoConnectors.GetAll(c => c.ConnectorSystemID.HasValue && c.ConnectorSystem.Name == attributevalue).ToList(); #if !DEBUG _connectors = _connectors.Where(c => c.IsActive).ToList(); #endif } else { try { _connectors = _repoConnectors.GetAll().ToList(); #if !DEBUG _connectors = _connectors.Where(c => c.IsActive).ToList(); #endif } catch (Exception e) { log.Debug(e.InnerException); } } if (schedule == null) { var allConnectorSchedules = unit.Scope.Repository <ConnectorSchedule>().GetAll(x => x.PluginID == plugin.PluginID).ToList(); _connectors = _connectors.Except(allConnectorSchedules.Select(x => x.Connector)); } else { _connectors = _connectors.Where(x => x.ConnectorID == schedule.ConnectorID); } _vendors = unit.Scope.Repository <Vendor>().GetAll().ToList(); Stopwatch watch = Stopwatch.StartNew(); log.AuditInfo(string.Format("Starting {0} at {1}", Name, DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss")), Name); Process(); watch.Stop(); log.AuditComplete(string.Format("Finished {0} at {1}. The plugin took {2} to finish", Name, DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss"), watch.Elapsed.TotalMinutes.ToString()), Name); //_connectorSchedules.Where(x => x.ConnectorScheduleStatus != (int)ConnectorScheduleStatus.WaitForNextRun).ToList().ForEach(x => x.ConnectorScheduleStatus = (int)ConnectorScheduleStatus.Disabled); TimeSpan ts = DateTime.Now.Subtract(start); string time = ts.ToString().Substring(0, 8); if (plugin != null && schedule == null) { plugin.LastRun = start; plugin.Duration = time; if (context.NextFireTimeUtc.HasValue) { plugin.NextRun = context.NextFireTimeUtc.Value.ToLocalTime(); } } if (schedule != null) { if (context.NextFireTimeUtc.HasValue) { schedule.ScheduledNextRun = context.NextFireTimeUtc.Value.ToLocalTime(); } schedule.ConnectorScheduleStatus = (int)ConnectorScheduleStatus.WaitForNextRun; schedule.Duration = time; } log.InfoFormat("Finished plugin: {0}, duration : {1}, next run : {2}", pluginName, time, context.NextFireTimeUtc.HasValue ? context.NextFireTimeUtc.Value.ToLocalTime() : DateTime.MinValue); unit.Save(); } } catch (Exception ex) { //log.FatalFormat("Error executing {0} plugin : {1}\n{2}", pluginName, ex.InnerException != null ? ex.InnerException.Message : ex.Message, ex.StackTrace); log.AuditFatal(string.Format("Error executing {0} plugin : {1}\n{2}", pluginName, ex.InnerException != null ? ex.InnerException.Message : ex.Message, ex.StackTrace), ex, pluginName); } }
private void DispatchOrders(bool directShipment) { FailedOrders = 0; DispatchedOrders = 0; foreach (var vendorOrderLine in VendorOrderLines) { var vendor = this.unit.Scope.Repository <Vendor>().GetSingle(vs => vs.VendorID == vendorOrderLine.Key); try { var vendorDispatcherType = vendor.OrderDispatcherType; var typeDispatcher = AppDomain.CurrentDomain .GetAssemblies() .SelectMany(assembly => assembly.GetTypes()) .Single(type => type.FullName == vendorDispatcherType && type.GetInterfaces().Contains(typeof(IDispatchable))); var dispatcher = (IDispatchable) Activator.CreateInstance(typeDispatcher); if (dispatcher != null) { var ord = GetGroupedOrders(vendorOrderLine.Value, OrderLineStatus.New); var OrderAdditionalOrderLines = new List <OrderLine>(); foreach (var order in ord.Keys) { var additionalOrderLines = unit.Scope.Repository <OrderLine>().GetAllAsQueryable(x => x.OrderID == order.OrderID && (x.Product == null || (x.Product.IsNonAssortmentItem.HasValue && x.Product.IsNonAssortmentItem.Value)) && !x.isDispatched); int parentVendorID = vendor.ParentVendorID.HasValue ? vendor.ParentVendorID.Value : 0; if (order.Connector.Vendor != null && (((VendorType)order.Connector.Vendor.VendorType).Has(VendorType.HasFinancialProcess) || (order.Connector.Vendor != vendor && order.Connector.AdministrativeVendorID != parentVendorID)) && !string.IsNullOrEmpty(order.Connector.Vendor.PurchaseOrderType)) { foreach (var additionalOrderLine in additionalOrderLines) { var additionalOrderProduct = (from aop in unit.Scope.Repository <AdditionalOrderProduct>().GetAllAsQueryable() where aop.ConnectorID == additionalOrderLine.Order.ConnectorID && aop.ConnectorProductID == additionalOrderLine.CustomerItemNumber && aop.VendorID == order.Connector.AdministrativeVendorID.Value select aop).FirstOrDefault(); if (additionalOrderProduct != null) { if (additionalOrderLine.ProductID.HasValue) { additionalOrderLine.SetStatus(OrderLineStatus.ReadyToOrder, unit.Scope.Repository <OrderLedger>()); } OrderAdditionalOrderLines.Add(additionalOrderLine); ord[order].Add(additionalOrderLine); } else { log.AuditInfo(string.Format("Skip orderline item {0}, cannot find settings for connectorID {1} and customItemNumber {2}", additionalOrderLine.OrderLineID, additionalOrderLine.Order.ConnectorID, additionalOrderLine.CustomerItemNumber)); } } var purchaseOrderVendor = (IPurchase)Activator.CreateInstance(Assembly.GetAssembly(typeof(IPurchase)).GetType(order.Connector.Vendor.PurchaseOrderType)); bool waitForConfirmation = false; waitForConfirmation = purchaseOrderVendor.PurchaseOrders(order, ord[order], order.Connector.Vendor, vendor, directShipment, unit, log); foreach (var line in ord[order]) { if (waitForConfirmation) { line.SetStatus(OrderLineStatus.WaitingForPurchaseConfirmation, unit.Scope.Repository <OrderLedger>()); } line.DispatchedToVendorID = vendorOrderLine.Key; if (!line.ProductID.HasValue) { line.SetStatus(OrderLineStatus.Processed, unit.Scope.Repository <OrderLedger>()); line.isDispatched = true; line.DispatchedToVendorID = order.Connector.AdministrativeVendorID; } } } else { foreach (var additionalOrderLine in additionalOrderLines) { int addVendorID = 0; if (vendor.ParentVendorID.HasValue) { addVendorID = vendor.ParentVendorID.Value; } var additionalOrderProduct = (from aop in unit.Scope.Repository <AdditionalOrderProduct>().GetAllAsQueryable() where aop.ConnectorID == additionalOrderLine.Order.ConnectorID && aop.ConnectorProductID == additionalOrderLine.CustomerItemNumber && (aop.VendorID == vendor.VendorID || aop.VendorID == addVendorID) select aop).FirstOrDefault(); if (additionalOrderProduct != null) { additionalOrderLine.SetStatus(OrderLineStatus.ReadyToOrder, unit.Scope.Repository <OrderLedger>()); OrderAdditionalOrderLines.Add(additionalOrderLine); } else { log.AuditInfo(string.Format("Skip orderline item {0}, cannot find settings for connectorID {1} and customItemNumber {2}", additionalOrderLine.OrderLineID, additionalOrderLine.Order.ConnectorID, additionalOrderLine.CustomerItemNumber)); } } foreach (var line in ord[order]) { line.SetStatus(OrderLineStatus.ReadyToOrder, unit.Scope.Repository <OrderLedger>()); } } } vendorOrderLine.Value.AddRange(OrderAdditionalOrderLines); ord = GetGroupedOrders(vendorOrderLine.Value, OrderLineStatus.ReadyToOrder); if (ord.Count > 0) { int vendorOrderID = dispatcher.DispatchOrders(ord, vendor, log, unit); DispatchedOrders += (from v in ord select v.Value.Count).ToList().Sum(); log.AuditInfo(string.Format("Dispatched {0} orders to {1}", ord.Count, vendor.Name)); } foreach (var lines in ord.Values) { lines.ForEach(c => { c.SetStatus(OrderLineStatus.WaitingForAcknowledgement, unit.Scope.Repository <OrderLedger>()); c.isDispatched = true; c.DispatchedToVendorID = vendorOrderLine.Key; }); } } } catch (Exception e) { FailedOrders++; Exceptions.Add(new Exception("Failed: Order #" + vendorOrderLine.Key + " , OrderLines: " + string.Join(", ", vendorOrderLine.Value.Select(c => c.OrderLineID.ToString()).ToArray()) + " to " + vendor.Name, e)); } finally { unit.Save(); } } }
public static void doResponse(RetailerSoapClient client, AuthenticationHeader authHeader, IUnitOfWork unit, IAuditLogAdapter log, string id, string feed) { log.AuditInfo("Start catalog response"); var Feed = GetXML(feed); if (Feed != null) { var ConcentratorProducts = (from product in Feed.Element("Producten").Elements("Product") select new { ConnectorID = product.Element("ConnectorID").Value, ProductID = product.Element("ProductID").Value, MycomProductID = product.Element("MycomProductID").Value, URL = product.Element("URL").Value }).ToList(); var Offers = unit.Scope.Repository <VendorAssortment>().GetAll(c => c.VendorID == 50).ToList(); //Create Responce XML Catalog_Response response = new Catalog_Response(); response.Version = byte.Parse("2"); response.Reference_ID = id; Offer[] offers = new Offer[Offers.Count]; Trial_Purchase_URL trial_url = new Trial_Purchase_URL(); int counter = 0; foreach (var Offer in Offers) { Offer offer = new Offer(); var prod = (from product in ConcentratorProducts where product.ProductID == Offer.ProductID.ToString() select product).FirstOrDefault(); if (prod != null) { Catalog_URL url = new Catalog_URL(); url.Value = prod.URL; offer.Catalog_URL = new Catalog_URL[1]; offer.Catalog_URL[0] = url; offer.Offer_ID = Offer.ActivationKey; offer.Retailer_Item_Number = prod.ProductID; offer.Status = redState.Active; trial_url.Value = ""; offer.Trial_Purchase_URL = new Trial_Purchase_URL[1]; offer.Trial_Purchase_URL[0] = trial_url; offers[counter] = offer; counter++; } } response.Offer = offers; 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(response.GetType()); XmlSerializerNamespaces nm = new XmlSerializerNamespaces(); nm.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); serializer.Serialize(xw, response, nm); //XmlDocument document = new XmlDocument(); //document.LoadXml(requestString.ToString()); } if (client.CatalogResponseRequest(authHeader, requestString.ToString()) == "OK") { log.AuditInfo("Catalog response successfully"); } else { log.AuditInfo("Catalog response failed"); } } }
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); } } }
public DataTable[] Process() { try { string path = xlsPath; OleDbConnection con = null; System.Data.DataTable exceldt = null; try { if (path.Contains(".xlsx")) { con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=YES;\""); } else if (path.Contains(".xls")) { con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0"); } else { log.Error("Foutief bestand"); return(null); } con.Open(); using (exceldt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null)) { if (exceldt == null) { log.AuditError("Fout verwerken file: Ongeldig tablad"); } String[] excelSheets = new String[exceldt.Rows.Count]; log.AuditInfo(string.Format("Found {0} worksheets in excel", exceldt.Rows.Count)); int i = 0; DataTable[] tables = new DataTable[exceldt.Rows.Count]; // Add the sheet name to the string array. foreach (DataRow row in exceldt.Rows) { excelSheets[i] = row["TABLE_NAME"].ToString(); string sheet = row["TABLE_NAME"].ToString(); OleDbDataAdapter da = null; DataTable dt = null; da = new OleDbDataAdapter(string.Format("select * from [{0}]", sheet), con); dt = new DataTable(); da.Fill(dt); // exceldt. tables[i] = dt; i++; } return(tables); } if (con != null) { con.Close(); con.Dispose(); } //File.(path, Path.Combine(ConfigurationManager.AppSettings["ExcelProcessedDirectory"], e.Name + "-" + Guid.NewGuid())); } catch (IOException ex) { log.AuditFatal("Fout verwerken file: " + ex.Message); //File.Move(e.FullPath, Path.Combine(ConfigurationManager.AppSettings["ExcelErrorDirectory"], e.Name + "-" + Guid.NewGuid())); } catch (Exception ex) { log.AuditFatal("Fout verwerken file: " + ex.Message); //if (File.Exists(e.FullPath)) // File.Move(e.FullPath, Path.Combine(ConfigurationManager.AppSettings["ExcelErrorDirectory"], e.Name + "-" + Guid.NewGuid())); //Logging.UserMail("Fout bij het verwerken van de excel order, de naam van het tabblad dient 'EDI_Order_V2' te zijn. Of u maakt gebruik van een verouderde versie, vraag uw accountmanager naar de nieuwe EDI Excel template", mailLog.Mailaddress, DocumentType.Excel); } finally { if (con != null) { con.Close(); con.Dispose(); } } } catch (Exception ex) { log.AuditFatal(ex.InnerException); } return(null); }
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; } } }
public int DispatchOrders(Dictionary <Concentrator.Objects.Models.Orders.Order, List <OrderLine> > orderLines, Vendor vendor, IAuditLogAdapter log, IUnitOfWork unit) { var vendorID = vendor.VendorID; List <string> orders = new List <string>(); //List<Offer> offers = new List<Offer>(); using (RetailerSoapClient client = new RetailerSoapClient()) { AuthenticationHeader authHeader = new AuthenticationHeader(); authHeader.Username = vendor.VendorSettings.GetValueByKey("ArvatoUserName", string.Empty); authHeader.Password = vendor.VendorSettings.GetValueByKey("ArvatoPassword", string.Empty); foreach (var order in orderLines.Keys) { var Order = unit.Scope.Repository <Concentrator.Objects.Models.Orders.Order>().GetSingle(o => o.OrderID == order.OrderID); try { //***Begin order reserveration request***/// if (client.BeginOrderReservationRequest(authHeader, order.OrderID.ToString()) == "OK") { log.Info("Successfully begun order reservation"); Order_Shipment_Request orderShiptMentRequest = new Order_Shipment_Request(); orderShiptMentRequest.Order_ID = order.OrderID.ToString(); Shipment shipment = new Shipment(); List <Shipment_Item> shipmentItems = new List <Shipment_Item>(); //Track shipmentitem amount int shipmentItemsCount = 0; //Counter for loop int count = 0; //Total ESD product price decimal totalPrice = 0; //Total price for items who need shipping decimal totalShipmentPrice = 0; //List of items that need to be shipped List <OrderLine> orderLineReserved = new List <OrderLine>(); foreach (var detail in orderLines[order]) { var orderLine = (from line in Order.OrderLines where line.OrderLineID == detail.OrderLineID select line).FirstOrDefault(); var relatedProducts = (from prod in orderLine.Product.RelatedProductsRelated select prod).ToList(); //var productType = orderLine.Product.ProductAttributeValues.Where(value => value.Value) var vendorAssortment = unit.Scope.Repository <VendorAssortment>().GetAll(assortment => assortment.VendorID == vendor.VendorID && assortment.ProductID == orderLine.ProductID).FirstOrDefault(); var Offer_ID = vendorAssortment.ActivationKey.ToString(); var Shipment_ReferenceID = vendorAssortment.ShipmentRateTableReferenceID; var Zone_ReferenceID = vendorAssortment.ZoneReferenceID; var Price = (vendorAssortment.VendorPrices.FirstOrDefault() != null ? vendorAssortment.VendorPrices.FirstOrDefault().Price.Value : (decimal)orderLine.Price) * 100; totalPrice += Price; var Quantity = orderLine.GetDispatchQuantity(); //check if product is primary var productType = orderLine.Product.ProductAttributeValues.Where( name => name.ProductAttributeMetaData.AttributeCode == "Product_Type").FirstOrDefault().Value; if (productType == "Supplementary") { shipmentItems.Add(new Shipment_Item { Line_Item_ID = orderLine.OrderLineID.ToString(), Quantity = Quantity.ToString() }); shipmentItemsCount++; } ////***Add order item***// XDocument addOrderItemResponse = XDocument.Parse(client.AddOrderItemRequest(authHeader, order.OrderID.ToString(), orderLine.OrderLineID.ToString(), Offer_ID, (decimal)Price, "EUR", Quantity, "", "")); int relCount = 1; foreach (var relatedProduct in relatedProducts) { //check if product is supplementary var relProductType = relatedProduct.SourceProduct.ProductAttributeValues.Where( name => name.ProductAttributeMetaData.AttributeCode == "Product_Type").FirstOrDefault().Value; var relatedProductPrice = relatedProduct.SourceProduct.VendorAssortments.FirstOrDefault().VendorPrices.FirstOrDefault().Price; var relVendorAssortment = unit.Scope.Repository <VendorAssortment>().GetAllAsQueryable(assortment => assortment.VendorID == vendor.VendorID && assortment.ProductID == relatedProduct.ProductID); var relOffer_ID = relVendorAssortment.FirstOrDefault().ActivationKey.ToString(); XDocument addRelatedOrderItemResponse = XDocument.Parse(client.AddOrderItemRequest(authHeader, order.OrderID.ToString(), (orderLine.OrderLineID.ToString() + "_" + relCount.ToString()), relOffer_ID, relatedProductPrice.Value, "EUR", Quantity, "", "")); if (relProductType == "Supplementary") { totalShipmentPrice += relatedProductPrice.Value; shipmentItems.Add(new Shipment_Item { Line_Item_ID = (orderLine.OrderLineID.ToString() + "_" + relCount.ToString()), Quantity = Quantity.ToString() }); shipmentItemsCount++; } relCount++; } var status = (from orderResponseStatus in addOrderItemResponse.Element("Order_Fulfillment_Reservation").Elements() where orderResponseStatus.Name == "Order_Status" select orderResponseStatus).FirstOrDefault(); log.InfoFormat("Order item {0} status {1}", orderLine.OrderLineID.ToString(), status.Value); //set item status if (status.Value.Equals("Reserved")) { orderLineReserved.Add(orderLine); var item = unit.Scope.Repository <OrderLine>().GetSingle(prod => prod.OrderLineID == orderLine.OrderLineID); item.SetStatus(OrderLineStatus.Processed, unit.Scope.Repository <OrderLedger>()); } shipment.Zone_Reference_ID = Zone_ReferenceID; shipment.Shipment_Rate_Table_Reference_ID = Shipment_ReferenceID; count++; } /************************Fill shipping information**************************/ string firstName = order.ShippedToCustomer.CustomerName.Split(' ')[0]; string lastName = order.ShippedToCustomer.CustomerName.Substring((firstName.Length)); shipment.Shipment_Packages = new Shipment_Package[1]; shipment.Shipment_Packages[0] = new Shipment_Package { Currency_Code = redCurrencyCode.EUR, Shipment_Items = shipmentItems.ToArray(), Shipment_Amount_Total = (decimal)totalPrice }; shipment.Shipment_Address = new Shipment_Address(); shipment.Shipment_Address.Address_One = order.ShippedToCustomer.CustomerAddressLine1; //shipment.Shipment_Address.Address_Two = order.ShipToCustomer.CustomerAddressLine2; //shipment.Shipment_Address.Address_Three = order.ShipToCustomer.CustomerAddressLine3; shipment.Shipment_Address.City = order.ShippedToCustomer.City; shipment.Shipment_Address.Country_Code = order.ShippedToCustomer.Country; //shipment.Shipment_Address.State_Code = ""; shipment.Shipment_Address.Zip_Code = order.ShippedToCustomer.PostCode; shipment.Shipment_Address.Phone = order.ShippedToCustomer.CustomerTelephone; shipment.Shipment_Address.First_Name = firstName; shipment.Shipment_Address.Last_Name = lastName; orderShiptMentRequest.Shipment = new Shipment[1]; orderShiptMentRequest.Shipment[0] = shipment; /************************End Fill shipping information************************/ log.AuditInfo("Successfully added order items to order"); if (client.CompleteOrderReservationRequest(authHeader, order.OrderID.ToString(), "") == "OK") { log.AuditInfo("Order reservation successfully made"); string requestXml = string.Empty; StringBuilder requestString = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter xw = XmlWriter.Create(requestString, settings)) { xw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\""); XmlSerializer serializer = new XmlSerializer(orderShiptMentRequest.GetType()); XmlSerializerNamespaces nm = new XmlSerializerNamespaces(); nm.Add("xsi", "urn:Order_Shipment_Request"); serializer.Serialize(xw, orderShiptMentRequest); XmlDocument document = new XmlDocument(); document.LoadXml(requestString.ToString()); document.DocumentElement.RemoveAttribute("xmlns:xsi"); document.DocumentElement.RemoveAttribute("xmlns:xsd"); requestXml = document.OuterXml; LogOrder(document, vendor.VendorID, string.Format("{0}.xml", order.OrderID), log); } ////***Order shipment request***// if (shipmentItemsCount > 0) { string response = client.OrderShipmentRequest(authHeader, requestXml.ToString()); if (response == "OK") { log.InfoFormat("Order reservation successfully made"); } } else { log.InfoFormat("No items need shipping"); } if (client.CommitToPurchaseOrderRequest(authHeader, order.OrderID.ToString(), order.OrderID.ToString()) == "OK") { log.Info("Order succesfully purchased"); log.Info("Processing product information"); XDocument[] orderInformation = new XDocument[orderLineReserved.Count]; int oc = 0; if (orderLineReserved.Count > 0) { OrderResponse orderResponse = null; foreach (var orderLine in orderLineReserved) { OrderResponseLine orderResponseLine = null; orderInformation[oc] = XDocument.Parse(client.PurchaseOrderItemFulfillmentRequest(authHeader, order.OrderID.ToString(), orderLine.OrderLineID.ToString(), "")); //#endif var OrderStatus = orderInformation[oc].Element("Order_Fulfillment").Element("Order_Status").Value; var OrderDate = orderInformation[oc].Element("Order_Fulfillment").Element("Order_Date").Value; var Quantity = orderInformation[oc].Element("Order_Fulfillment").Element("Quantity").Value; var getMaxShippingQuantity = orderLine.Product.ProductAttributeValues.Where( name => name.ProductAttributeMetaData.AttributeCode == "Max_Quantity_Per_Shipment_Charge").FirstOrDefault(); var MaxShippingQuantity = getMaxShippingQuantity != null?Int32.Parse(getMaxShippingQuantity.Value) : 0; var _orderResponseRepo = unit.Scope.Repository <OrderResponse>(); switch (OrderStatus) { case "Shipped": if (orderResponse == null) { orderResponse = new OrderResponse { Orders = new List <Concentrator.Objects.Models.Orders.Order>() { Order }, VendorDocument = orderInformation[oc].Document.ToString(), VendorID = vendorID, OrderDate = DateTime.Parse(OrderDate), ReceiveDate = DateTime.Now, PartialDelivery = MaxShippingQuantity != 0 ? Int32.Parse(Quantity) < MaxShippingQuantity ? false : true : false, VendorDocumentNumber = Order.OrderID.ToString() }; _orderResponseRepo.Add(orderResponse); } orderResponse.ResponseType = OrderResponseTypes.ShipmentNotification.ToString(); break; case "ShipmentPending": if (orderResponse == null) { orderResponse = new OrderResponse { Orders = new List <Concentrator.Objects.Models.Orders.Order>() { Order }, VendorDocument = orderInformation[oc].Document.ToString(), VendorID = vendorID, OrderDate = DateTime.Parse(OrderDate), ReceiveDate = DateTime.Now, PartialDelivery = Int32.Parse(Quantity) < MaxShippingQuantity ? false : true, VendorDocumentNumber = Order.OrderID.ToString() }; _orderResponseRepo.Add(orderResponse); } orderResponse.ResponseType = OrderResponseTypes.Acknowledgement.ToString(); break; default: log.WarnFormat("Unknown order status"); break; } var formattedBlocks = (from attribute in orderInformation[oc].Element("Order_Fulfillment").Element("Fulfillment_Block").Elements() where attribute.Name == "Preformatted_Block" select new { Type = attribute.Attribute("Type").Value, Text = attribute.Value }); var productName = (from attribute in orderInformation[oc].Element("Order_Fulfillment").Element("Fulfillment_Block").Element( "Fulfillment_Set").Elements() where attribute.Name == "Header" select attribute.Value).FirstOrDefault(); var productInformation = (from attribute in orderInformation[oc].Element("Order_Fulfillment").Element("Fulfillment_Block").Element( "Fulfillment_Set"). Elements( "Fulfillment_Item") select new { FullfillmentAtoms = (from attribute2 in attribute.Elements("Fulfillment_Atom_Section").Elements("Fulfillment_Atom") select new { Header = attribute2.Parent.Element("Header") != null ? attribute2.Parent.Element("Header").Value : string.Empty, Fulfillment_Atom = (from att in attribute2.Attributes() select new { Name = att.Name, Value = att.Value }).ToDictionary(x => x.Name, x => x.Value), Value = attribute2.Value }) }); orderResponseLine = new OrderResponseLine { OrderResponse = orderResponse, OrderLineID = orderLine.OrderLineID, Ordered = OrderStatus != "Shipped" ? 0 : Int32.Parse(Quantity), Backordered = OrderStatus != "Shipped" ? Int32.Parse(Quantity) : 0, Cancelled = 0, Shipped = OrderStatus != "Shipped" ? 0 : Int32.Parse(Quantity), //Invoiced Price = (decimal)orderLine.Price.Value, Processed = false, Delivered = 0, ProductName = productName, html = (from data in formattedBlocks where data.Type == "Html" select data.Text).FirstOrDefault(), Remark = (from data in formattedBlocks where data.Type == "Text" select data.Text).FirstOrDefault(), }; unit.Scope.Repository <OrderResponseLine>().Add(orderResponseLine); foreach (var inf in productInformation) { foreach (var att in inf.FullfillmentAtoms) { var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation { OrderResponseLine = orderResponseLine }; foreach (var atom in att.Fulfillment_Atom.Keys) { if (orderItemFullfilmentInformation.GetType().GetProperties().Any(x => x.Name == atom.LocalName)) { Type type = orderItemFullfilmentInformation.GetType().GetProperty(atom.LocalName).PropertyType; string value = att.Fulfillment_Atom[atom]; orderItemFullfilmentInformation.GetType().GetProperty(atom.LocalName).SetValue( orderItemFullfilmentInformation, Convert.ChangeType(value, type), null); } } orderItemFullfilmentInformation.Value = att.Value; orderItemFullfilmentInformation.Header = att.Header; unit.Scope.Repository <OrderItemFullfilmentInformation>().Add(orderItemFullfilmentInformation); } } oc++; } } } } } } catch (Exception ex) { log.AuditError(ex); } unit.Save(); } return(0); } }