public ActionResult UpdateDevice(Guid key, string ip) { _logger.LogDebug("Device attempts to update its address {0} for device key {1}.", ip, key); try { if (string.IsNullOrEmpty(ip)) { throw new ArgumentNullException("You must provide a valid IP address to this update routine."); } var deviceCriteria = UnitOfWorkSession.CreateCriteria <RemoteDevice>(); deviceCriteria.Add(Expression.Eq("DeviceKey", key)); var devices = deviceCriteria.List <RemoteDevice>(); if (devices.Count() == 1) { devices[0].LastOnline = DateTime.Now; devices[0].Address = ip; GTSDataRepository.Update <RemoteDevice>(devices[0]); _logger.LogInfo("Device address update for {0} is succesful: address {1}", devices[0].Name, devices[0].Address); } else { throw new InvalidOperationException("Device not found or devices found with duplicate keys."); } return(new HttpStatusCodeResult(200)); } catch (Exception) { _logger.LogError("Device adress update for key: {0} and address {1} failed."); throw; } }
public ActionResult SerialExists(string serial, string modelNameSearchString) { _logger.LogInfo("A remote device attempts to check if a serial {0} exist for a model with {1} in its name.", serial, modelNameSearchString); try { // try to retrieve an assembly for the serial parameter var assemblySearchCriteria = UnitOfWorkSession.CreateCriteria <ProductAssembly>(); assemblySearchCriteria = assemblySearchCriteria.Add(Expression.Eq("ProductSerial", serial)); var hits = assemblySearchCriteria.List(); foreach (ProductAssembly hit in hits) { // check for search string in model name if (hit.GetType().ToString().ToLower().Contains(modelNameSearchString.ToLower())) { if (hit.RemarkSymptoms.Where(symptom => symptom.Resolved == false && symptom.IsArchived == false).Count() > 0) { return(new HttpStatusCodeResult(500, "Wing is in remark")); } return(new HttpStatusCodeResult(200, "Serial found")); } } return(new HttpStatusCodeResult(500, "Serial not found")); } catch (Exception ex) { _logger.LogError(ex); throw; } }
/// <summary> /// Initializes the reporting filter data. /// </summary> /// <returns></returns> public ActionResult InitReportingFilterData() { _logger.LogInfo("User {0} attempts to initialize needed filter data to generate reports.", User.Identity.Name); try { var searchCriteria = UnitOfWorkSession.CreateCriteria <ProductModel>() .Add(Expression.Eq("IsArchived", false)) .Add(Expression.Eq("IsReleased", true)); var models = searchCriteria.List <ProductModel>().ToList <ProductModel>().DistinctBy(model => model.BaseModelId).Select(model => new { Id = model.Id, Name = model.Name, BaseModelId = model.BaseModelId }).ToList(); var result = new { StartDate = DateTime.Now.AddDays(-7), EndDate = DateTime.Now, Models = models, }; return(SerializeForWeb(result)); //return new HttpStatusCodeResult(200, "Operation completed succesfully"); } catch (Exception ex) { _logger.LogError(ex); throw; } }
public ActionResult InitShippingManagement() { _logger.LogInfo("User {0} attempts to initialize data for the shipping management interface", User.Identity.Name); try { // 1. RETRIEVE SHIPPING PREPARATIONS var bomListFromSageDB = new List <string>(); // do an old-school Sql Cmd approach var connection = new SqlConnection(SAGE_CONN_STR); using (connection) { var SqlCmd = new SqlCommand(SAGE_SQL_STR, connection); connection.Open(); using (SqlDataReader oReader = SqlCmd.ExecuteReader()) { while (oReader.Read()) { var currentPickingBom = oReader["PickingBOM"].ToString(); bomListFromSageDB.Add(currentPickingBom); } } connection.Close(); } throw new InvalidOperationException("Rule below this always closes shipments => not good"); bomListFromSageDB.ForEach(bom => PersistAndStartStopShippingPreparation(false, bom)); // get all shipping preps found in our database var orderCriteria = UnitOfWorkSession.CreateCriteria <ShippingPreparation>(); var savedPreparations = orderCriteria.List <ShippingPreparation>().ToList(); // 2. RETRIEVE SHIPPING BOXES var boxCriteria = UnitOfWorkSession.CreateCriteria <ShippingBoxTemplate>(); var savedBoxes = boxCriteria.List <ShippingBoxTemplate>().ToList(); // 3. RETRIEVE A LIST OF PARTNRS AND ASSOCIATED MODEL NAMES var partNrCritera = UnitOfWorkSession.CreateCriteria <PartNumber>(); var partNrs = partNrCritera.List <PartNumber>().ToList().Select(partNr => new { Number = partNr.Number, ProductModelId = partNr.ProductModel.Id }).ToList(); var result = new { ShippingPreparations = savedPreparations, ShippingBoxes = savedBoxes, PartNumbers = partNrs }; return(SerializeForWeb(result)); } catch (Exception ex) { _logger.LogError(ex); throw; } }
/// <summary> /// Updates an order line. /// </summary> /// <param name="orderLineJSON">The order line json.</param> /// <returns></returns> public ActionResult UpdateOrderLine(string orderLineJSON) { _logger.LogInfo("User {0} attempts to update an order line in the shipping management interface.", User.Identity.Name); try { var orderLine = new JavaScriptSerializer().Deserialize <OrderLine>(orderLineJSON); var existingOrderLine = UnitOfWorkSession.CreateCriteria <OrderLine>() .Add(Expression.Eq("PickingBOM", orderLine.PickingBOM)) .Add(Expression.Eq("OrderLineNr", orderLine.OrderLineNr)).List <OrderLine>().ToList().Single(); // check if input was required but not given //if (string.IsNullOrEmpty(orderLine.FieldInput) && orderLine.InputRequirement == "SERIE") // throw new InvalidOperationException(string.Format("The orderline {0} for BOM {1} expects input which wasn't provided.", orderLine.OrderLineNr, orderLine.PickingBOM)); // check if part nr is associated with a product model var productModelBaseId = GetProductModelBaseIdByPartNumber(orderLine.PartNr); // check if an actual physical product exists var assembly = GTSDataRepository.GetByProductSerial <ProductAssembly>(orderLine.FieldInput, productModelBaseId); if (assembly == null) { throw new InvalidOperationException("Could not find assembly with serial: " + orderLine.FieldInput); } // check if associated assembly has any remarks if (assembly.RemarkSymptoms.Where(remark => remark.Resolved == false).Count() > 0) { throw new InvalidOperationException(string.Format("Assembly with serial {0} has open remarks and cannot be shipped", assembly.ProductSerial)); } // check if associated assembly is "Delivered" if (assembly.ProductModelState.Name.ToLower() != "delivered") { throw new InvalidOperationException(string.Format("Assembly with serial {0} does not have the state 'Delivered'", assembly.ProductSerial)); } // update id and EditedBy existingOrderLine.FieldInput = orderLine.FieldInput; existingOrderLine.EditedBy = User.Identity.Name; // update existing order line in the database GTSDataRepository.Update <OrderLine>(existingOrderLine); return(SerializeForWeb(orderLine)); } catch (Exception ex) { _logger.LogError(ex); throw; } }
public UnitOfWorkSessionTest() { var dbInMemory = DbInMemory.getDbInMemoryOptions(dbName); var personRepo = new PersonRepo(dbInMemory); var sessionRepo = new SessionRepo(dbInMemory); var reasonRepo = new ReasonRepo(dbInMemory); var classRepo = new ClassRepo(dbInMemory); var semesterRepo = new SemesterRepo(dbInMemory); db = new TCSContext(dbInMemory); unitSession = new UnitOfWorkSession(personRepo, reasonRepo, sessionRepo, classRepo, semesterRepo); }
/// <summary> /// Retrieves part number data. /// </summary> /// <param name="partNumbersForShipping">The part numbers for shipping.</param> /// <returns></returns> private Dictionary <string, string> getPartNumberData(List <string> partNumbersForShipping) { var searchCriteria = UnitOfWorkSession.CreateCriteria <PartNumber>() .Add(Expression.In("Number", partNumbersForShipping)) .CreateCriteria("ProductModel") .Add(Expression.Like("IsReleased", true)) .Add(Expression.Like("IsArchived", false)); ///var hits = searchCriteria.List<PartNumber>().Select(item => new { Number = item.Number, IdMask = item.ProductModel.IdMask }).ToList().ToDictionary<dynamic, string>(item => item.Number); var result = new Dictionary <string, string>(); searchCriteria.List <PartNumber>().ToList().ForEach(partNumber => { result.Add(partNumber.Number, partNumber.ProductModel.IdMask); }); return(result); }
/// <summary> /// Retrieves a product model by its part number. /// </summary> /// <param name="partNr">The part nr.</param> /// <returns></returns> private Guid GetProductModelBaseIdByPartNumber(string partNr) { var searchCriteria = UnitOfWorkSession.CreateCriteria <PartNumber>() .Add(Expression.Eq("Number", partNr)); var results = searchCriteria.List <PartNumber>(); if (results == null || results.Count == 0) { throw new InvalidOperationException("Could not find product model for part number :" + partNr); } if (results.ToList <PartNumber>().DistinctBy(currentPartNumber => currentPartNumber.ProductModel.BaseModelId).Count() > 1) { throw new InvalidOperationException("Found multiple distinct models for part number :" + partNr); } return(results[0].ProductModel.BaseModelId); }
public SessionsControllerTest() { var dbOptions = DbInMemory.getDbInMemoryOptions(dbName); db = new TCSContext(dbOptions); sessionRepo = new SessionRepo(dbOptions); var personRepo = new PersonRepo(dbOptions); var semesterRepo = new SemesterRepo(dbOptions); var sessionClassRepo = new SessionClassRepo(dbOptions); var sessionReasonRepo = new SessionReasonRepo(dbOptions); var reasonRepo = new ReasonRepo(dbOptions); var classRepo = new ClassRepo(dbOptions); csvParser = new CSVSessionUploadParser(); var mapper = Utils.GetProjectMapper(); var unitSession = new UnitOfWorkSession(personRepo, reasonRepo, sessionRepo, classRepo, semesterRepo); sessionController = new SessionsController(sessionRepo, semesterRepo, personRepo, sessionReasonRepo, sessionClassRepo, mapper, csvParser, unitSession); }
/// <summary> /// Gets the usage of a serial in another assembly. /// </summary> /// <param name="serial">The serial.</param> /// <returns></returns> public ActionResult GetSerialUsage(string serial) { _logger.LogInfo("User {0} attempts to determine if serial {1} is used in any assemblies", User.Identity.Name, serial); try { serial = serial.Replace('*', '%'); var serialUsageCriteria = UnitOfWorkSession.CreateCriteria <ComponentAssembly>() .Add(Expression.Like("Serial", serial)) .Add(Expression.Eq("IsArchived", false)); var serialCriteria = UnitOfWorkSession.CreateCriteria <ProductAssembly>() .Add(Expression.Like("ProductSerial", serial)); var assembliesWithThisSerial = serialCriteria.List <ProductAssembly>(); var assembliesContainingThisSerial = serialUsageCriteria.List <ComponentAssembly>(); var dtoResult = assembliesContainingThisSerial.Select(componentAssembly => new { Id = componentAssembly.Id, Name = componentAssembly.ProductAssembly.ProductModel.Name, Serial = componentAssembly.ProductAssembly.ProductSerial, PublicSerial = componentAssembly.ProductAssembly.PublicProductSerial, Version = "v" + componentAssembly.ProductAssembly.ProductModel.Version, State = componentAssembly.ProductAssembly.ProductModelState.Name, ComponentName = componentAssembly.ProductComponent.ComponentName, ComponentSerial = componentAssembly.Serial, ComponentVersion = "v" + assembliesWithThisSerial.Where(assembly => assembly.ProductSerial == componentAssembly.Serial && assembly.ProductModel.BaseModelId == componentAssembly.ProductComponent.UnderlyingProductModel.BaseModelId).Single().ProductModel.Version }); return(SerializeForWeb(dtoResult)); } catch (Exception ex) { _logger.LogError(ex); throw; } }
/// <summary> /// Starts the stop shipping preparation. /// </summary> /// <param name="doStart">if set to <c>true</c> [do start].</param> /// <param name="bomNr">The bom nr.</param> /// <returns></returns> public ActionResult PersistAndStartStopShippingPreparation(bool doStart, string bomNr) { _logger.LogDebug("User {0} attempts to set the Shipping Preparation with Bom Nr {2}'s IsActive property to {1}.", User.Identity.Name, doStart, bomNr); try { var newGuid = Guid.NewGuid(); var shippingPreparation = UnitOfWorkSession.CreateCriteria <ShippingPreparation>() .Add(Expression.Eq("BOMNr", bomNr)).UniqueResult <ShippingPreparation>() ?? new ShippingPreparation // if retrieval fails, create a new shippingPreparation { Id = newGuid, BOMNr = bomNr, EditedBy = User.Identity.Name, StartDateTime = DateTime.Now, }; shippingPreparation.IsActive = doStart; if (newGuid == shippingPreparation.Id) { _logger.LogInfo("Shipping preparation did not exist yet, creating new ShippingPreparation entity with id {0}", newGuid); GTSDataRepository.Create <ShippingPreparation>(shippingPreparation); } else { GTSDataRepository.Update <ShippingPreparation>(shippingPreparation); } _logger.LogInfo("User {0} has successfully set the Shipping Preparation with Bom Nr {2}'s IsActive property to {1}.", User.Identity.Name, doStart, bomNr); return(new HttpStatusCodeResult(200)); } catch (Exception ex) { _logger.LogError(ex); throw; } }
/// <summary> /// Initializes the list of model component names which is requested when the user makes selection in the list of model versions. /// </summary> /// <param name="versionNr">The version nr.</param> /// <param name="modelId">The model identifier.</param> /// <returns></returns> public ActionResult InitModelComponentNamesData(int versionNr, Guid modelId) { _logger.LogInfo("User {0} attempts to request a list of component names for a particular model with id {1}", User.Identity.Name, modelId); try { var searchCriteria = UnitOfWorkSession.CreateCriteria <ProductModel>() .Add(Expression.Eq("Id", modelId)) .Add(Expression.Eq("Version", versionNr)); var modelComponents = searchCriteria.List <ProductModel>() .Single() .ProductComponents .Select(component => new { Id = component.Id, Name = component.ComponentName, SequenceOrder = component.SequenceOrder }).ToList(); return(SerializeForWeb(modelComponents)); } catch (Exception ex) { _logger.LogError(ex); throw; } }
/// <summary> /// Initializes the model version nr collection which is requested after the user makes a selection in the model select list. /// </summary> /// <param name="baseModelId">The base model identifier.</param> /// <returns></returns> public ActionResult InitModelVersionData(Guid baseModelId) { _logger.LogInfo("User {0} attempts to generate a list of versions for a model with base model id {1}", User.Identity.Name, baseModelId); try { var searchCriteria = UnitOfWorkSession.CreateCriteria <ProductModel>() //.Add(Expression.Eq("IsArchived", false)) .Add(Expression.Eq("BaseModelId", baseModelId)); var versions = searchCriteria.List <ProductModel>().Select(model => new { Id = model.Id, VersionNr = model.Version }).ToList(); return(SerializeForWeb(versions)); } catch (Exception ex) { _logger.LogError(ex); throw; } }
/// <summary> /// Retrieves the active shipping preparations. /// </summary> /// <returns></returns> private List <ShippingPreparation> getActiveShippingPreparations() { return(UnitOfWorkSession.CreateCriteria <ShippingPreparation>() .Add(Expression.Eq("IsActive", true)) .List <ShippingPreparation>().ToList()); }
public ActionResult GetRemarksBetweenDates(DateTime?start, DateTime?end, bool onlyOpenRemarks) { _logger.LogInfo("User {0} requests report of Remarks between dates {1} and {2}.", User.Identity.Name, start != null ? start.ToString() : "Not-entered", end != null ? end.ToString() : "Not-entered"); try { var finalEndDate = new DateTime(9999, 12, 31, 23, 59, 59, 0); // create a criteria set to list RemarkSymptoms var remarks = UnitOfWorkSession.CreateCriteria <RemarkSymptom>(); // if requested, create criteria to only show open remarks if (onlyOpenRemarks) { remarks = remarks.Add(Expression.Eq("Resolved", false)); } // add start date to criteria, if available if (start != null) { remarks = remarks.Add(Expression.Gt("CreationDate", ((DateTime)start).Date)); } // add end date to criteria, if available and take enddate near max date into account if (end != null) { remarks = remarks.Add(Expression.Le("ResolutionDate", ((DateTime)end).Date) || Expression.Eq("ResolutionDate", finalEndDate) || Expression.IsNull("ResolutionDate")); } var data = remarks.List <RemarkSymptom>(); var simplifiedData = data.Select(x => new { Id = x.Id, Name = x.ProductAssembly.ProductModel.Name, ProductSerial = x.ProductAssembly.ProductSerial, PublicProductSerial = x.ProductAssembly.PublicProductSerial, TypeOfProduct = x.ProductAssembly.ProductModel.ModelType.ToString(), Configurations = CreateModelConfigurationString(x.ProductAssembly.ProductModelConfigurations), CreationDate = x.CreationDate, EditedBy = x.EditedBy, Description = TrimLinebreaks(x.Description), IsArchived = x.IsArchived ? "yes" : "no", Cause = x.RemarkSymptomCauses.Count > 0 ? x.RemarkSymptomCauses[0].CauseType.Name + (x.RemarkSymptomCauses.Count > 1 ? " (+" + (x.RemarkSymptomCauses.Count - 1) + ")" : "") : "None", CauseDescription = x.RemarkSymptomCauses.Count > 0 ? TrimLinebreaks(x.RemarkSymptomCauses[0].Description) : "", CauseDate = x.RemarkSymptomCauses.Count > 0 ? x.RemarkSymptomCauses[0].CauseDate.ToString() : "", Solution = x.RemarkSymptomCauses.Count > 0 && x.RemarkSymptomCauses[0].RemarkSymptomSolution != null ? x.RemarkSymptomCauses[0].RemarkSymptomSolution.RemarkSymptomSolutionType.Name : "None", Costs = x.RemarkSymptomCauses.Count > 0 ? x.RemarkSymptomCauses[0].MaterialCost.ToString() : "0", Resolved = x.Resolved, ResolvedBy = x.Resolved ? x.RemarkSymptomCauses.Count > 0 && x.RemarkSymptomCauses[0].RemarkSymptomSolution != null ? x.RemarkSymptomCauses[0].RemarkSymptomSolution.EditedBy : "None" : "", ResolutionDate = x.Resolved ? x.RemarkSymptomCauses.Count > 0 && x.RemarkSymptomCauses[0].RemarkSymptomSolution != null ? x.RemarkSymptomCauses[0].RemarkSymptomSolution.SolutionDate.ToString() : "None" : "", }); simplifiedData = simplifiedData.OrderByDescending(x => x.CreationDate).ToList(); return(SerializeForWeb(simplifiedData)); } catch (Exception ex) { _logger.LogError(ex); throw; } }
/// <summary> /// Updates an assembly. /// </summary> /// <param name="objectAsString">The object as a json string.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException"> /// No product serial was found in incoming device data. /// or /// Could not find product with serial: " + postData["productSerial"] /// or /// Data is corrupted: the system found more than one product with serial " + postData["productSerial"] /// or /// Could not find component assemblies for product with serial: " + postData["productSerial"] /// </exception> private ActionResult UpdateAssemblyParsed(string objectAsString) { _logger.LogInfo("Incoming data from a remote device: {0}", objectAsString); try { var postData = (Dictionary <string, object>) new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(objectAsString); if (postData["productSerial"] == null || string.IsNullOrEmpty(postData["productSerial"].ToString())) { throw new InvalidOperationException("No product serial was found in incoming device data."); } var keyWords = postData.Keys.ToList().Where(x => x.ToString() != "productSerial" && x.ToString() != "baseModelId" && x.ToString() != "deviceKey").ToArray <string>(); var doCreateRemark = false; if (postData["createRemark"].ToString().ToLower() == "true") { doCreateRemark = true; } // check if product exists var productAssemblyCriteria = UnitOfWorkSession.CreateCriteria <ProductAssembly>(); productAssemblyCriteria = productAssemblyCriteria.Add(Expression.Eq("ProductSerial", postData["productSerial"])); var productAssembly = productAssemblyCriteria.List <ProductAssembly>(); if (productAssembly.Count() == 0) { throw new InvalidOperationException("Could not find product with serial: " + postData["productSerial"]); } if (productAssembly.Count() > 1) { throw new InvalidOperationException("Data is corrupted: the system found more than one product with serial " + postData["productSerial"]); } var componentAssemblyCriteria = UnitOfWorkSession.CreateCriteria <ComponentAssembly>(); componentAssemblyCriteria = componentAssemblyCriteria.CreateAlias("ProductAssembly", "pa"); componentAssemblyCriteria = componentAssemblyCriteria.Add(Expression.Eq("pa.ProductSerial", postData["productSerial"])); componentAssemblyCriteria = componentAssemblyCriteria.CreateAlias("ProductComponent", "pc"); componentAssemblyCriteria = componentAssemblyCriteria.Add(Expression.In("pc.DeviceKeyword", keyWords)); componentAssemblyCriteria = componentAssemblyCriteria.CreateAlias("pc.ProductModel", "pm"); componentAssemblyCriteria = componentAssemblyCriteria.Add(Expression.Eq("pm.IsReleased", true)); //componentAssemblyCriteria = componentAssemblyCriteria.Add(Expression.Eq("pm.IsArchived", false)); if (postData.Keys.Contains <string>("baseModelId")) { componentAssemblyCriteria = componentAssemblyCriteria.Add(Expression.Eq("pm.BaseModelId", Guid.Parse(postData["baseModelId"].ToString()))); } var filteredComponentAssemblies = componentAssemblyCriteria.List <ComponentAssembly>(); if (filteredComponentAssemblies.Count() == 0) { throw new InvalidOperationException("Could not find component assemblies for product with serial: " + postData["productSerial"]); } // find matching component assemblies for any device keywords in the post data keyWords.ToList().ForEach(x => { filteredComponentAssemblies.Where(y => y.ProductComponent.DeviceKeyword == x).ToList().ForEach(z => { // update component assembly if (postData[x] != null) { z.Revision = postData[x].ToString(); GTSDataRepository.Update <ComponentAssembly>(z); } }); }); // create remark when needed if (doCreateRemark) { var remarkMessage = string.Format("Product with serial {0} failed its automated tests. Reasons given: ", postData["productSerial"].ToString()); if (productAssembly[0].ProductModel.Name.ToLower().Contains("wing")) { if (postData["deviceApproval"] != null && postData["deviceApproval"].ToString() == "no") { remarkMessage += "Product found to be invalid by wing checker tool, "; if (postData["errorMessage"] != null) { remarkMessage += postData["errorMessage"].ToString(); } } if (postData["minmax"] != null && postData["minmax"].ToString() == "no") { remarkMessage += "User did not approve min and / or max, "; } } else if (productAssembly[0].ProductModel.Name.ToLower().Contains("ux11 motor")) { if (!(bool)postData["userApproval"]) { remarkMessage += "User disapproves (" + postData["disapprovalReason"].ToString() + "), "; } if (!(bool)postData["systemApprovalVoltage"]) { remarkMessage += "Measured voltage does not conform to expectations, "; } if (!(bool)postData["systemApprovalCurrent"]) { remarkMessage += "Measured current does not conform to expectations, "; } if (!(bool)postData["systemApprovalRPM"]) { remarkMessage += "Measured rpm does not conform to expectations, "; } if (!(bool)postData["systemApprovalDirection"]) { remarkMessage += "Measured direction of spin does not conform to expectations, "; } } var newRemark = new RemarkSymptom { Id = Guid.NewGuid(), CreationDate = DateTime.Now, ResolutionDate = DateTime.MaxValue, Description = remarkMessage, ProductAssembly = productAssembly[0], EditedBy = postData["user"].ToString(), RemarkSymptomType = GTSDataRepository.GetListByQuery <RemarkSymptomType>("FROM RemarkSymptomType WHERE Name = '" + postData["remarkSymptomType"].ToString() + "'").FirstOrDefault(), }; GTSDataRepository.Create <RemarkSymptom>(newRemark); } return(new HttpStatusCodeResult(200, "Data received")); } catch (Exception ex) { _logger.LogError(ex); return(new HttpStatusCodeResult(500, ex.Message)); } }
/// <summary> /// Prepares the shipping json. /// </summary> /// <returns></returns> public ActionResult PrepareShippingJSON() { _logger.LogDebug("User {0} chose to display the Shipping Preparation Interface.", User.Identity.Name); try { // create lists for picking, packaging and validations var packagingList = new List <OrderLine>(); var pickingList = new List <Picking>(); var bomList = new List <dynamic>(); var validationMessages = new List <ShippingPreparationValidationMessage>(); // retrieve shipping GTS meta data from the database var activeShippingPreparations = getActiveShippingPreparations(); // do an old-school Sql Cmd approach var connection = new SqlConnection(SAGE_CONN_STR); using (connection) { var SqlCmd = new SqlCommand(SAGE_SQL_STR, connection); connection.Open(); using (SqlDataReader oReader = SqlCmd.ExecuteReader()) { while (oReader.Read()) { Console.WriteLine(oReader.ToString()); // create a list of BOM nrs bomList.Add( new { BomNr = oReader["PickingBOM"].ToString(), IsActive = activeShippingPreparations.Where(x => x.BOMNr == oReader["PickingBOM"].ToString()).Count() > 0 }); // filter out data for non-activated Shippings (activation starts / stops are done in this page as well) if (activeShippingPreparations.Where(x => x.BOMNr == oReader["PickingBOM"].ToString()).Count() == 0) { continue; } // Use query result row to cast to internal DTO classes var packagingDTO = new OrderLine(oReader, User.Identity.Name); packagingList.Add(packagingDTO); } connection.Close(); } } if (packagingList.Count > 0) { // ensure ClientRef and SalesOrder are found on every line var clientRef = packagingList.Where(order => !string.IsNullOrEmpty(order.SalesOrder)).First().ClientRef; var salesOrder = packagingList.Where(order => !string.IsNullOrEmpty(order.SalesOrder)).First().SalesOrder; var colorTagIndex = 0; var isCommercialBom = false; packagingList.ForEach(order => { if (order.CommercialBOM == "O") { isCommercialBom = true; } if (string.IsNullOrEmpty(order.CommercialBOM)) { isCommercialBom = false; } if (!isCommercialBom) { colorTagIndex = (colorTagIndex + 1) % 6; } else if (order.CommercialBOM != "O") { order.DoIndent = true; } if (!string.IsNullOrEmpty(order.PartNr)) { order.ColorTag = _colorTable[colorTagIndex]; } order.ClientRef = clientRef; order.SalesOrder = salesOrder; }); } // when we're done creating an picking list, regroup the orderlist according to BOM nr var tempOrderList = new List <OrderLine>(); packagingList.OrderBy(x => x.PickingBOM).ToList().ForEach(order => { var currentorderQuantity = order.Quantity; if (currentorderQuantity > 1 && order.UoM == "PCE") { for (var c = 0; c < currentorderQuantity; c++) { //order.Quantity = 1; tempOrderList.Add(order); } } else { tempOrderList.Add(order); } }); var groupedOrderList = tempOrderList.GroupBy(order => order.PickingBOM); // create a picking list from the list of orders made in the previous step packagingList.ToList().ForEach(packagingDTO => { var existingItemInPickingList = pickingList.Where(item => item.PartNr == packagingDTO.PartNr).SingleOrDefault(); if (existingItemInPickingList == null) { existingItemInPickingList = new Picking(packagingDTO); existingItemInPickingList.Quantity = 0; // set quantity to null, we will recalculate this below // create a fake stock location if needed if (string.IsNullOrEmpty(packagingDTO.StockLocation) && packagingDTO.StockLevel > 0 && !string.IsNullOrEmpty(packagingDTO.UoM)) { existingItemInPickingList.StockLocation = ""; } pickingList.Add(existingItemInPickingList); } if (/*packagingDTO.UoM == "PCE" && */ packagingDTO.Quantity > 0) { existingItemInPickingList.Quantity += packagingDTO.Quantity; } }); // check stock levels to create a picking issue summary ShippingPreparationValidationMessage shippingPrepValidationMessage = null; pickingList.ForEach(shippingDTO => { if (ShippingPreparationValidationMessage.GetShippingPreparationValidationMessage(shippingDTO.Quantity, shippingDTO.StockLevel, shippingDTO.PartNr, out shippingPrepValidationMessage) == false) { validationMessages.Add(shippingPrepValidationMessage); } }); _logger.LogInfo("User {0} successfully requested Shipping Preparation data.", User.Identity.Name); assignIdMasks(tempOrderList); // try to retrieve existing orderLines with the BOM from the database var searchCriteria = UnitOfWorkSession.CreateCriteria <OrderLine>() .Add(Expression.Eq("PickingBOM", packagingList.Count > 0 ? packagingList[0]?.PickingBOM : "")); // put the results in a list var existingPackagingEntities = searchCriteria.List <OrderLine>().ToList(); // for every collection of order lines with the same BOM foreach (var item in packagingList) { // iterate over all current oderlines and use the previously created list to check if the current line // is already in the database and create it, if not var potentiallyExistingOrderLines = existingPackagingEntities.Where(entity => entity.OrderLineNr == item.OrderLineNr); if (potentiallyExistingOrderLines.Count() > 1) { throw new InvalidOperationException(string.Format("More then 1 row was found in the database for the current Picking BOM {0} and Order Line Nr {1}", item.PickingBOM, item.OrderLineNr)); } if (potentiallyExistingOrderLines.Count() == 0) { item.Id = Guid.NewGuid(); item.EditedBy = User.Identity.Name; GTSDataRepository.Create <OrderLine>(item); } else // at this point we can assume there's only orderline found in the database, retrieve any input value if possible { item.FieldInput = potentiallyExistingOrderLines.First().FieldInput; } } return(SerializeForWeb(new { Picking = pickingList, Packing = groupedOrderList, BomList = bomList.Distinct().ToList(), ValidationMessages = validationMessages, TotalToPick = pickingList.Where(picking => !string.IsNullOrEmpty(picking.StockLocation)).DistinctBy(picking => picking.PartNr).Count() })); } catch (Exception ex) { _logger.LogError(ex); throw; } }
/// <summary> /// Reports the on assemblies. /// </summary> /// <param name="baseModelId">The base model identifier.</param> /// <param name="modelId">The model identifier.</param> /// <param name="componentName">Name of the component.</param> /// <param name="componentNameFreeInput">The component name free input.</param> /// <param name="componentValue">The component value.</param> /// <param name="productSerial">The product serial.</param> /// <param name="startDate">The start date.</param> /// <param name="endDate">The end date.</param> /// <returns></returns> public ActionResult ReportOnAssemblies(Guid?baseModelId, Guid?modelId, Guid?componentId, string componentNameFreeInput, string componentValue, string productSerial, DateTime?startDate, DateTime endDate) { _logger.LogInfo("User {0} attempts to generate a report on assemblies. User filter params: baseModelId = '{1}', modelId = '{2}', componentId = '{3}', componentNameFreeInput = '{4}', componentValue = '{5}', productSerial = '{6}', start date = '{7}', end data = '{8}'", User.Identity.Name, // 0 baseModelId, // 1 modelId, // 2 componentId, // 3 componentNameFreeInput, // 4 componentValue, // 5 productSerial, // 6 startDate, // 7 endDate); // 8 try { var searchCriteria = UnitOfWorkSession.CreateCriteria <ProductAssembly>(); // check for product serial user input if (!string.IsNullOrEmpty(productSerial)) { productSerial = productSerial.Replace('*', '%'); searchCriteria = searchCriteria.Add(Expression.Like("ProductSerial", productSerial)); } // start date if (startDate != null && startDate != DateTime.MinValue && startDate != DateTime.MaxValue) { searchCriteria = searchCriteria.Add(Expression.Gt("StartDate", startDate)); } else { searchCriteria = searchCriteria.Add(Expression.Gt("StartDate", _minDate)); } // end date if (endDate != null && endDate != DateTime.MinValue && endDate != DateTime.MaxValue) { searchCriteria = searchCriteria.Add(Expression.Lt("EndDate", endDate) || Expression.Eq("EndDate", _finalEndDate)); //searchCriteria = searchCriteria.Add(Expression.Lt("EndDate", endDate) || Expression.Lt("EndDate", _finalEndDate)); } else { searchCriteria = searchCriteria.Add(Expression.Lt("EndDate", _finalEndDate)); } // check for component user input if (!string.IsNullOrEmpty(componentValue)) { componentValue = componentValue.Replace('*', '%'); componentNameFreeInput = componentNameFreeInput?.Replace('*', '%'); // filter on ComponentAssemblies searchCriteria = searchCriteria.CreateCriteria("ComponentAssemblies"); // use component value to filter, if needed searchCriteria = searchCriteria.Add(Expression.Like("Revision", componentValue) || Expression.Like("Serial", componentValue)); // check component id vs component name entries searchCriteria = searchCriteria.CreateCriteria("ProductComponent"); if (componentId != null && componentId != Guid.Empty) { searchCriteria = searchCriteria.Add(Expression.Eq("Id", componentId)); } else if (!string.IsNullOrEmpty(componentNameFreeInput)) { searchCriteria = searchCriteria.Add(Expression.Like("ComponentName", componentNameFreeInput)); } } // check model selection if (modelId != null && modelId != Guid.Empty) { searchCriteria = searchCriteria.CreateCriteria("ProductModel").Add(Expression.Eq("Id", modelId)); } else if (baseModelId != null && baseModelId != Guid.Empty) { searchCriteria = searchCriteria.CreateCriteria("ProductModel").Add(Expression.Eq("BaseModelId", baseModelId)); } // retrieve results var results = searchCriteria.List <ProductAssembly>(); IEnumerable <dynamic> assemblies = null; // check if we need to include a component value (= if a component value is entered by the user) if (!string.IsNullOrEmpty(componentValue)) { var tmpAssemblyList = new List <dynamic>(); results.ToList <ProductAssembly>().ForEach(x => { string componentName, ComponentDataRevision, ComponentDataSerial = null; ComponentAssembly componentAssembly = null; // use either the component id input parameter or the free text entry component namee if (componentId != null && componentId != Guid.Empty) { componentAssembly = x.ComponentAssemblies.Where(componentAssy => componentAssy.ProductComponent.Id == componentId).Single(); } else { componentAssembly = x.ComponentAssemblies.Where(componentAssy => componentAssy.ProductComponent.ComponentName.Contains(componentNameFreeInput.Remove(componentNameFreeInput.IndexOf('%'), 1))).Single(); } // use the retrieved component assembly componentName = componentAssembly?.ProductComponent.ComponentName; ComponentDataRevision = componentAssembly?.Revision; ComponentDataSerial = componentAssembly?.Serial; var ComponentChangeDate = componentAssembly?.AssemblyDateTime; var assy = new { Id = x.Id, StartDate = x.StartDate, LastUpdate = x.ComponentAssemblies.ToList().OrderByDescending(ca => ca.AssemblyDateTime).FirstOrDefault()?.AssemblyDateTime, Name = x.ProductModel.Name, ProductSerial = x.ProductSerial, PublicProductSerial = x.PublicProductSerial, Configurations = CreateModelConfigurationString(x.ProductModelConfigurations), ModelType = x.ProductModel.ModelType.ToString(), State = x.ProductModelState.Name, Progress = x.Progress, FinalState = x.Evaluation, ModelVersion = x.ProductModel.Version, ComponentName = componentName, ComponentDataRevision = ComponentDataRevision, ComponentDataSerial = ComponentDataSerial, ComponentChangeDate = ComponentChangeDate }; tmpAssemblyList.Add(assy); assemblies = tmpAssemblyList.OrderBy(y => y.StartDate); }); } else { assemblies = results.Select(x => new { Id = x.Id, StartDate = x.StartDate, LastUpdate = x.ComponentAssemblies.ToList().OrderByDescending(ca => ca.AssemblyDateTime).FirstOrDefault()?.AssemblyDateTime, Name = x.ProductModel.Name, ProductSerial = x.ProductSerial, PublicProductSerial = x.PublicProductSerial, Configurations = CreateModelConfigurationString(x.ProductModelConfigurations), ModelType = x.ProductModel.ModelType.ToString(), State = x.ProductModelState.Name, Progress = x.Progress, FinalState = x.Evaluation, ModelVersion = x.ProductModel.Version }).OrderBy(x => x.StartDate); } return(SerializeForWeb(assemblies)); } catch (Exception ex) { _logger.LogError(ex); throw; } }