Esempio n. 1
0
        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;
            }
        }
Esempio n. 2
0
        public ActionResult ResetPasswordFromEmail(Guid id)
        {
            _logger.LogInfo("A password reset request was made for token: " + id);

            ViewBag.AllowChange = false;

            try
            {
                var existingToken = GTSDataRepository.GetListByQuery <PasswordHelper>("FROM PasswordHelper ph WHERE ph.IsArchived = false AND ph.Token = :token", new Dictionary <string, object> {
                    { "token", id }
                }).FirstOrDefault();

                if (existingToken != null && DateTime.Now.Subtract(existingToken.RequestDate) < new TimeSpan(24, 0, 0))
                {
                    ViewBag.AllowChange = true;
                }

                return(View());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                throw;
            }
        }
Esempio n. 3
0
 /// <summary>
 /// Gets the open remarks (not archived, not resolved) for a particular assembly.
 /// </summary>
 /// <param name="assembly">The assembly.</param>
 /// <returns></returns>
 internal List <RemarkSymptom> GetOpenRemarksForAssembly(Guid assemblyId)
 {
     return(GTSDataRepository.GetListByQuery <RemarkSymptom>("FROM RemarkSymptom rs WHERE rs.IsArchived = false AND rs.Resolved = false AND rs.ProductAssembly.Id = :id",
                                                             new Dictionary <string, object> {
         { "id", assemblyId }
     }).ToList());
 }
Esempio n. 4
0
        /// <summary>
        /// Attempts to tracks changes to an entity.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="newEntity">The new entity.</param>
        public void TrackChanges <T>(T newEntity) where T : DomainObject
        {
            var type   = newEntity.GetType();
            var entity = GTSDataRepository.GetById <T>(newEntity.Id);

            TrackChanges <T>(entity, newEntity);
        }
Esempio n. 5
0
        /// <summary>
        /// Tracks the property changes.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">The entity.</param>
        /// <param name="propName">Name of the property.</param>
        /// <param name="oldValue">The old value.</param>
        /// <param name="newValue">The new value.</param>
        public void TrackProperty <T>(T entity, string propName, string oldValue, string newValue) where T : DomainObject
        {
            var name = typeof(T).Name;

            switch (typeof(T).Name)
            {
            case "ProductModel":
                name = (entity as ProductModel).Name;
                break;

            case "ProductComponent":
                name = (entity as ProductComponent).ComponentName;
                break;

            case "WorkInstruction":
                name = (entity as GTSWorkInstruction).Title;
                break;
            }

            var change = new EntityChange
            {
                Id = Guid.NewGuid(),
                ChangedEntityId   = entity.Id,
                ChangedEntityType = typeof(T),
                ChangeDate        = DateTime.Now,
                ChangeDescription = string.Format("{3} '{4}'s property '{0}' was changed from '{1}' to '{2}'.", propName, oldValue, newValue, typeof(T).Name, name),
                ChangeMadeBy      = entity.EditedBy,
                OldValue          = oldValue,
                NewValue          = newValue
            };

            // save change to system
            GTSDataRepository.Create <EntityChange>(change);
        }
Esempio n. 6
0
        /// <summary>
        /// Attempts to tracks changes to an entity.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oldEntity">The old entity.</param>
        /// <param name="newEntity">The new entity.</param>
        public void TrackChanges <T>(T oldEntity, T newEntity) where T : DomainObject
        {
            // get a list of properties of the entity
            var props = typeof(T).GetProperties().ToList();

            var name = string.Empty;

            switch (typeof(T).Name)
            {
            case "ProductModel":
                name = (newEntity as ProductModel).Name;
                break;

            case "ProductComponent":
                name = (newEntity as ProductComponent).ComponentName;
                break;

            case "GTSWorkInstruction":
                name = (newEntity as GTSWorkInstruction).Title;
                break;
            }

            // iterate over all properties and track changes
            props.ForEach(prop =>
            {
                // get values
                var oldValue = prop.GetValue(oldEntity);
                var newValue = prop.GetValue(newEntity);

                // check for differences
                if ((oldValue != null && newValue != null) &&
                    !oldValue.Equals(newValue) &&
                    !(oldValue is IList) && !oldValue.GetType().IsGenericType &&
                    prop.Name != "ModificationDate")
                {
                    // create and save new EntityChange object
                    var change = new EntityChange
                    {
                        Id = Guid.NewGuid(),
                        ChangedEntityId   = oldEntity.Id,
                        ChangedEntityType = typeof(T),
                        ChangeDate        = DateTime.Now,
                        ChangeDescription = string.Format("{3} '{4}'s property '{0}' is changed from '{1}' to '{2}'", prop.Name, oldValue, newValue, typeof(T).Name, name),
                        ChangeMadeBy      = User.Identity.Name, //oldEntity.EditedBy,
                        OldValue          = oldValue.ToString(),
                        NewValue          = newValue.ToString()
                    };

                    // save change to system
                    GTSDataRepository.Create <EntityChange>(change);
                }
            });
        }
Esempio n. 7
0
        /// <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;
            }
        }
Esempio n. 8
0
        public ActionResult ForgotPasswordJson(string emailAddress)
        {
            try
            {
                //var user = UserManager.FindByNameAsync(emailAddress);
                var user = UserManager.FindByEmail(emailAddress);
                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(new HttpStatusCodeResult(200));
                }

                //var existingHelperForEmailIds = GTSDataRepository.GetListByQuery<PasswordHelper>("FROM PasswordHelper ph WHERE ph.EmailAddress = :email", new Dictionary<string, object> { { "email", emailAddress } })

                var passwordHelper = new PasswordHelper {
                    Id = Guid.NewGuid(), EmailAddress = emailAddress, RequestDate = DateTime.Now, Token = Guid.NewGuid()
                };

                GTSDataRepository.Create(passwordHelper);

                var callBackUrl = HttpContext.Request.Url.Authority;

                var resetUrl = string.Format("http://{0}/Account/ResetPasswordFromEmail/{1}", callBackUrl, passwordHelper.Token);

                var body = string.Format(
                    "Hello," +
                    "<br />" +
                    "<br />" +
                    "This mail was sent to enable you to reset your password and will expire after 24 hours. Click <a href='{0}'>here</a> to reset your password.<br />" +
                    "If you did not request this mail you can simply ignore it." +
                    "<br />" +
                    "<br />" +
                    "Kind regards,<br />" +
                    "GTS", resetUrl);

                var subject = "GTS Password Change Request";

                var from = "*****@*****.**";

                var to = emailAddress;

                MailHandler.Send(to, from, subject, body, _logger, true, true);

                return(new HttpStatusCodeResult(200));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                throw;
            }
        }
Esempio n. 9
0
        public ActionResult GetDevices()
        {
            _logger.LogDebug("User attempts to request a list of remote devices");

            try
            {
                var devices = GTSDataRepository.GetAll <RemoteDevice>();

                return(SerializeForWeb(devices));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                throw;
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Gets GTS stats.
        /// </summary>
        /// <returns></returns>
        public ActionResult GetGtsStats()
        {
            try
            {
                //var userList = new List<ViewUser>();

                var tmmm = this;

                //var tmo = GTSDataRepository;

                // count users
                var userCount = new ApplicationDbContext().Users.Count();

                // count released models
                var releaseModelCount = GTSDataRepository.ExecuteQuery("SELECT Count(Id) FROM ProductModel pm WHERE pm.IsArchived = 0 AND pm.IsReleased = 1", null, true);

                // count assemblies
                var assemblyCount = GTSDataRepository.ExecuteQuery("SELECT Count(pa.Id) FROM ProductAssembly pa INNER JOIN ProductModelState pms on pa.ProductModelState_id = pms.Id WHERE pms.Name = 'Delivered'", null, true);

                // count remarks
                var unresolvedRemarkCount = GTSDataRepository.ExecuteQuery("SELECT Count(Id) FROM RemarkSymptom rs WHERE rs.IsArchived = 0 AND rs.Resolved = 0", null, true);

                // count items in the list and aggegrate them
                var result = new
                {
                    modelCount    = releaseModelCount,
                    assemblyCount = assemblyCount,
                    remarkCount   = unresolvedRemarkCount,
                    userCount     = userCount
                };

                return(SerializeForWeb(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                throw;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Tracks the addition of an object to a collection.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="U"></typeparam>
        /// <param name="addedObject">The added object.</param>
        /// <param name="parentObject">The parent object.</param>
        /// <param name="propName">Name of the property.</param>
        public void TrackAddition <T, U>(T addedObject, U parentObject, string propName) where T : DomainObject where U : DomainObject
        {
            var change = new EntityChange
            {
                Id = Guid.NewGuid(),
                ChangedEntityId   = parentObject.Id,
                ChangedEntityType = typeof(U),
                ChangeDate        = DateTime.Now,
                //ChangeDescription = string.Format("Property '{0}' is changed from '{1}' to '{2}'", prop.Name, oldValue, newValue),
                ChangeMadeBy = addedObject.EditedBy,
                OldValue     = "Parent Id: " + parentObject.Id.ToString(),
                NewValue     = "Added object Id: " + addedObject.Id.ToString(),
            };

            switch (typeof(T).Name)
            {
            case "ProductComponent":
                var model     = parentObject as ProductModel;
                var component = addedObject as ProductComponent;
                change.ChangeDescription = string.Format("Model '{0}' with has added Component '{1}' to its collection of ProductComponents", model.Name, component.ComponentName);
                break;

            case "AssemblyTool":
                model = parentObject as ProductModel;
                var tool = addedObject as AssemblyTool;
                change.ChangeDescription = string.Format("Model '{0}' with has added Tool '{1}' to its collection of Tools", model.Name, tool.Name + " " + tool.ToolCode);
                break;

            case "GTSWorkInstruction":
                var parentComponent = parentObject as ProductComponent;
                var instruction     = addedObject as GTSWorkInstruction;
                change.ChangeDescription = string.Format("Product Component '{0}' with has added Work Instruction '{1}' to its collection of WorkInstructions", parentComponent.ComponentName, instruction.Title);
                break;
            }

            // save change to system
            GTSDataRepository.Create <EntityChange>(change);
        }
Esempio n. 12
0
        /// <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;
            }
        }
Esempio n. 13
0
        public async Task <ActionResult> ResetPasswordJson(string newPassword, Guid token)
        {
            try
            {
                var helper = GTSDataRepository.GetListByQuery <PasswordHelper>("FROM PasswordHelper ph WHERE ph.IsArchived = false AND ph.Token = :token", new Dictionary <string, object> {
                    { "token", token }
                }).FirstOrDefault();

                if (helper == null && token != Guid.Empty)
                {
                    throw new InvalidOperationException("Could not find password reset token");
                }

                var users = UserManager.Users;

                var emailAddress = string.Empty;
                if (helper == null)
                {
                    emailAddress = User.Identity.Name;
                }
                else
                {
                    emailAddress = helper.EmailAddress;
                }

                var usr = users.Where(x => x.Email == emailAddress).FirstOrDefault();

                var validPass = await UserManager.PasswordValidator.ValidateAsync(newPassword);

                if (validPass.Succeeded)
                {
                    var user = UserManager.FindByName(usr.Email);
                    user.PasswordHash = UserManager.PasswordHasher.HashPassword(newPassword);
                    var res = UserManager.Update(user);
                    if (res.Succeeded)
                    {
                        GTSDataRepository.ExecuteUpdateQuery("Update PasswordHelper SET IsArchived = true, ArchivedBy = :name, ArchivalDate = :dateNow where EmailAddress = :email", new Dictionary <string, object> {
                            { "name", usr.Email }, { "dateNow", DateTime.Now }, { "email", usr.Email }
                        });

                        AuthenticationManager.SignOut();

                        return(new HttpStatusCodeResult(200, "Password change successful."));
                    }
                    else
                    {
                        var errorMsg = "One or more errors occured during the password change attempt: ";
                        res.Errors.ForEach(x => errorMsg += (x + ". "));
                        throw new InvalidOperationException(errorMsg);
                    }
                }
                else
                {
                    throw new InvalidOperationException("The password you've provided is not considered strong enough, please choose another.");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                throw;
            }
        }
Esempio n. 14
0
        /// <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));
            }
        }
Esempio n. 15
0
        public void DoCheck(object entityAsObject)
        {
            var domainObject = (DomainObject)entityAsObject;

            var _logger = new Logger("BusinessRules");

            try
            {
                var _gtsRepository = new GTSDataRepository(new UnitOfWork(), _logger); //.Instance(true);
                // var currentSerial = string.Empty;
                // check if a referenced product in a component isn't used anywhere else

                //if (domainObject.GetType() == typeof(ComponentAssembly))
                //{
                //    var entity = (ComponentAssembly)domainObject;
                //    if (entity.ProductComponent.UnderlyingProductModel != null)
                //    {
                //        if (!string.IsNullOrEmpty(entity.Serial))
                //        {
                //            // get all ComponentAssemblies that use the current serial
                //            var usedSerialInComponents = _gtsRepository.GetListByQuery<ComponentAssembly>("from ComponentAssembly ca WHERE ca.Serial = :serial AND ca.Id <> :id AND ca.ProductComponent.UnderlyingProductModel.BaseModelId = :baseModelId",
                //                new Dictionary<string, object>() {
                //                { "serial", entity.Serial },
                //                { "id", entity.Id },
                //                { "baseModelId", entity.ProductComponent.UnderlyingProductModel.BaseModelId}
                //                });

                //            // serial is found in other components / models => throw error
                //            if (usedSerialInComponents.Count() > 0 && currentSerial != entity.Serial)
                //            {
                //                currentSerial = entity.Serial;
                //                //entity.Serial = string.Empty;
                //                //_gtsRepository.Update<ComponentAssembly>(entity);
                //                throw new InvalidOperationException("The component (" + entity.ProductComponent.ComponentName + ") that references a product with serial (" + currentSerial + ") is already used in another product assembly.");
                //            }

                //            // new serial entered, check if we need to auto create referenced model
                //            if (usedSerialInComponents.Count() == 0 && entity.Serial != null && entity.ProductAssembly.ProductSerial != entity.Serial)
                //            {
                //                if (entity.ProductComponent.UnderlyingProductModel.AutoCreate)
                //                {/*
                //                    var existingAssemblies = _gtsRepository.GetListByQuery<ProductAssembly>("FROM ProductAssembly Where ProductSerial = :serial AND Id != :id",
                //                        new Dictionary<string, object> { { "serial", entity.Serial }, { "id", entity.ProductAssembly.Id } }).ToList();

                //                    var createNew = true;
                //                    if (existingAssemblies.Count() > 0)
                //                    {
                //                        existingAssemblies.ForEach(currentAssembly =>
                //                        {
                //                            if (currentAssembly.ProductSerial != entity.Serial)
                //                                throw new InvalidOperationException("This serial is already taken for this " + entity.ProductComponent.UnderlyingProductModel.Name);
                //                            else
                //                                createNew = false;
                //                        });
                //                    }

                //                    if (createNew)
                //                    {
                //                        var datetimeNow = DateTime.Now;
                //                        var assembly = new ProductAssembly();
                //                        assembly.Id = Guid.NewGuid();
                //                        assembly.StartDate = datetimeNow;
                //                        assembly.StartedBy = ((ProductAssembly)assembly).EditedBy = entity.EditedBy;
                //                        assembly.EndDate = datetimeNow.AddMinutes(1);
                //                        assembly.ProductModel = entity.ProductComponent.UnderlyingProductModel;
                //                        assembly.ProductModelState = _gtsRepository.GetListByQuery<ProductModelState>("FROM ProductModelState Where Name = 'Delivered'", null).FirstOrDefault();
                //                        assembly.ProductSerial = entity.Serial;
                //                        assembly.NHVersion = 1;

                //                        var tmp = new UnitOfWork();
                //                        tmp.Session.Save(assembly);

                //                        //_gtsRepository.Create<ProductAssembly>(assembly);
                //                    }*/
                //                }
                //                else
                //                {
                //                    var existingAssembly = _gtsRepository.GetListByQuery<ProductAssembly>("FROM ProductAssembly Where ProductSerial = :serial AND Id != :id",
                //                        new Dictionary<string, object> { { "serial", entity.Serial }, { "id", entity.ProductAssembly.Id } }).FirstOrDefault();

                //                    if (existingAssembly == null)
                //                    {
                //                        var serial = entity.Serial;
                //                        //entity.Serial = string.Empty;
                //                        //_gtsRepository.Save<Compon>(assembly);
                //                        throw new InvalidOperationException("You are trying to reference a product with serial (" + serial + ") that doesn't exist.");
                //                    }
                //                }
                //            }
                //        }
                //    }
                //}

                // check if a user attempts to resolve a remark of type empty
                if (domainObject.GetType() == typeof(RemarkSymptom))
                {
                    var entity = (RemarkSymptom)domainObject;
                    if (entity.Resolved && entity.RemarkSymptomType.Name == "Empty")
                    {
                        //entity.Resolved = false;
                        throw new InvalidOperationException("You cannot resolve a remark of type 'Empty'.");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                throw;
            }
        }
Esempio n. 16
0
        /// <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;
            }
        }