public List <ModelViewPrices> GetListPrices(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }

            List <int> lst = new List <int>();

            if (objCred.ProductID == 0)
            {
                lst = new BusinessOrder().GetListByProductID(dataUsuario.UserID, objCred.Date.Value);



                return(new RepositoryPrice().GetListPrice(lst, null));
            }
            else
            {
                lst.Add(objCred.ProductID);
                return(new RepositoryPrice().GetListPrice(lst, null));
            }
        }
        public List <ModelViewCountries> GetListCountries(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }

            var lt = new List <EntityCountries>();

            if (objCred.Date == null)
            {
                lt = GetAll();
            }
            else
            {
                lt = GetAll().Where(p => p.ModifyDate >= objCred.Date).ToList();
            }
            return(lt.Select(p => new ModelViewCountries()
            {
                CountryID = p.CountryID,
                CountryName = p.CountryName
            }).ToList());
        }
        public List <ModelViewNotification> GetByToken(EntitySecurity model)
        {
            if (model.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (model.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }

            var dataUser = new BusinessUsers().GetUserByToken(model.TokenUser);

            TimeZoneInfo estZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time (Mexico)");

            return(new RepositoryNotification().GetByUserID(dataUser.UserID).Select(p => new ModelViewNotification()
            {
                MessageID = p.MessageID,
                Message = p.Message,
                MessageRead = p.MessageRead,
                Title = p.Title,
                Url = p.Url,
                UserID = p.UserID,
                UserName = p.UserName,
                Status = p.Status,
                CreateDate = TimeZoneInfo.ConvertTimeFromUtc(p.CreateDate, estZone),
                ModifyDate = TimeZoneInfo.ConvertTimeFromUtc(p.ModifyDate, estZone),
                CreateDateString = TimeZoneInfo.ConvertTimeFromUtc(p.CreateDate, estZone).ToString("dd/MM/yyyy HH:mm:ss"),
                ModifyDateString = TimeZoneInfo.ConvertTimeFromUtc(p.ModifyDate, estZone).ToString("dd/MM/yyyy HH:mm:ss")
            }).ToList());
        }
Beispiel #4
0
        public List <ModelViewQuotation> GetListAllQuotation1(string StatusVisitID, string ModuleID, string PriorityID, string StatusOrderID, string ServiceID, string OrderID, string Employee, string StartDate, string EndDate, string User, string TypeQuotation)
        {
            int profileuser = new BusinessUsers().GetProfileByToken(User).ProfileID;

            if (profileuser == 7)
            {
                ModuleID = new BusinessUsers().GetProfileByToken(User).ModuleID.ToString();
            }

            DateTime fh1 = DateTime.Parse(StartDate);
            DateTime fh2 = DateTime.Parse(EndDate);

            User = "";
            return(new RepositoryQuotation().GetList(StatusVisitID, ModuleID, PriorityID, StatusOrderID, ServiceID, OrderID, Employee, fh1.ToString("yyyy-MM-dd"), fh2.ToString("yyyy-MM-dd"), User, TypeQuotation));
        }
        public string Insert(ModelViewLog model)
        {
            if (model.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (model.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            var           User  = new BusinessUsers().GetUserByToken(model.TokenUser);
            List <string> token = new List <string>();

            foreach (var item in model.Detail)
            {
                var             Ods  = new BusinessOrder().GetByOrderID(item.OrderID);
                EntityLogMobile data = new EntityLogMobile()
                {
                    PK_LogMobileID = 0,
                    FK_OrderID     = Ods == null ? 0 : Ods.PK_OrderID,
                    FK_UserID      = User.UserID,
                    UserName       = User.UserName,
                    Name           = User.Name,
                    OrderID        = item.OrderID,
                    Module         = item.Module,
                    Message        = item.Message,
                    InnerException = item.InnerException,
                    StackTrace     = item.StackTrace,
                    SignType       = item.SignType,
                    Battery        = item.Battery,
                    SignPercentage = item.SignPercentage,
                    ConnectionType = item.ConnectionType,
                    version        = item.version,
                    MobileModel    = item.MobileModel,
                    MobileStorage  = item.MobileStorage,
                    Type           = item.Type,
                    Date           = DateTime.Parse(item.Date),
                    Status         = true,
                    CreateDate     = DateTime.UtcNow,
                    ModifyDate     = DateTime.UtcNow
                };
                data = new RepositoryLogMobile().Insert(data);
                token.Add(item.TokenLog);
            }

            string TokenLog = string.Join(",", token);

            return(TokenLog);
        }
        public List <ModelViewGuarantys> GetListGuaranty(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }

            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }


            var NegocioTipoGarantia = new BusinessGuarantyType();
            var Guaranty            = new List <EntityGuaranty>();

            if (objCred.Date == null)
            {
                Guaranty = GetAll();
            }
            else
            {
                Guaranty = GetAll().Where(p => p.ModifyDate >= objCred.Date).ToList();
            }
            var GuarantyType = NegocioTipoGarantia.GetAll();
            var lt           = (from c in Guaranty
                                join p in GuarantyType on c.FK_GuarantyTypeID equals p.PK_GuarantyTypeID
                                select new ModelViewGuarantys()
            {
                GuarantyID = c.PK_GuarantyID,
                GuarantyCode = c.GuarantyID,
                Guaranty = c.Guaranty1,
                Status = c.Status,
                GuarantyTypeID = p.PK_GuarantyTypeID,
                GurantyType = p.GuarantyType1
            }).ToList();

            return(lt);
        }
        public List <ModelViewWorkforcePrices> GetListPricesWorkforce(ModelViewUserG objCred)
        {
            var dataUsuario = new BusinessUsers().GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }

            return(new BusinessWorkforce().GetAll(objCred.Date));
        }
Beispiel #8
0
        public List <ModelViewCauseOrder> GetListCauseOrder(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }

            var NegocioStatusCausaOrder = new BusinessStatusCauseOrder();
            var CauseOrder = new List <EntityCauseOrder>();

            //GetAll();
            if (objCred.Date == null)
            {
                CauseOrder = GetAll();
            }
            else
            {
                CauseOrder = GetAll().Where(p => p.ModifyDate >= objCred.Date).ToList();
            }
            var StatusCauseOrder = NegocioStatusCausaOrder.GetAll();
            var lt = (from c in CauseOrder
                      join p in StatusCauseOrder on c.FK_StatusOrderID equals p.PK_StatusOrderID
                      select new ModelViewCauseOrder()
            {
                CauseOrderID = c.PK_CauseOrderID,
                CauseOrder = c.CauseOrder1,
                Moment = c.Moment,
                Status = c.Status,
                StatusOrderID = p.PK_StatusOrderID,
                StatusOrder = p.StatusOrder1
            }).ToList();

            return(lt);
        }
        public List <ModelViewGuarantyProduct> GetLisValidationProduct(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }

            var lista = new List <EntityValidationGuarantyProduct>();
            var NegocioLugarCompra = new BusinessShopPlace();

            if (objCred.Date == null)
            {
                lista = GetAll();
            }
            else
            {
                lista = GetAll().Where(p => p.ModifyDate >= objCred.Date).ToList();
            }
            return((from a in lista
                    join b in NegocioLugarCompra.GetAll() on a.ClientID equals b.ClientID
                    select new ModelViewGuarantyProduct()
            {
                ValidationGuarantyProductID = a.PK_ValidationGuarantyProductID,
                ProducID = a.FK_ProducID.HasValue ? a.FK_ProducID.Value : 0,
                Country = a.Country,
                Model = a.Model,
                ClientID = a.ClientID,
                Months = a.Months,
                ValidFrom = a.ValidFrom.Value.ToString("yyyy-MM-dd"),
                ValidTo = a.ValidTo.Value.ToString("yyyy-MM-dd"),
                ShopPlaceID = b.PK_ShopPlaceID
            }).ToList());
        }
        public List <ModelViewNotification> GetByTokenActive(string TokenUser)
        {
            var dataUser = new BusinessUsers().GetUserByToken(TokenUser);

            return(new RepositoryNotification().GetAll().Where(p => p.UserID == dataUser.UserID && p.Status == true).Select(p => new ModelViewNotification()
            {
                MessageID = p.MessageID,
                Message = p.Message,
                MessageRead = p.MessageRead,
                Title = p.Title,
                Url = p.Url,
                UserID = p.UserID,
                UserName = p.UserName,
                Status = p.Status,
                CreateDate = p.CreateDate,
                ModifyDate = p.ModifyDate,
                CreateDateString = p.CreateDate.ToString("dd/MM/yyyy HH:mm:ss"),
                ModifyDateString = p.ModifyDate.ToString("dd/MM/yyyy HH:mm:ss")
            }).OrderByDescending(p => p.CreateDate).ToList());
        }
Beispiel #11
0
        public List <ModelViewProducts> GetListProduct(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }

            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }
            var producto = new List <EntityProduct>();

            if (objCred.Date == null)
            {
                producto = GetAll();
            }
            else
            {
                producto = GetAll().Where(p => p.ModifyDate >= objCred.Date).ToList();
            }

            return(producto.Select(p => new ModelViewProducts()
            {
                ProductID = p.PK_ProductID,
                Model = p.Model,
                ProductName = p.ProductName,
                BarCode = p.BarCode,
                //ListPrice = p.li
                GroupMaterial1 = p.MaterialGroup1,
                GroupMaterial4 = p.MaterialGroup4,
                Status = p.Status
            }).ToList());
        }
Beispiel #12
0
        public List <ModelViewPriority> GetListPriority(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }


            var NegocioProgramacion = new BusinessSchedule();
            //var dataPriority = GetAll();
            var dataPriority = new List <EntityPriority>();

            if (objCred.Date == null)
            {
                dataPriority = GetAll();
            }
            else
            {
                dataPriority = GetAll().Where(p => p.ModifyDate >= objCred.Date).ToList();
            }
            var dataschedule = NegocioProgramacion.GetAll();
            var lt           = (from c in dataPriority
                                join p in dataschedule on c.FK_ScheduleID equals p.PK_ScheduleID
                                select new ModelViewPriority()
            {
                Priority = c.Priority1, ScheduleStart = p.ScheduleStart, ScheduleEnd = p.ScheduleEnd
            }).ToList();

            return(lt);
        }
        public List <ModelViewCauseVisit> GetListCauseOrder(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }
            var StatusVisit = new List <ModelViewCauseVisit>();

            if (objCred.Date == null)
            {
                StatusVisit = GetAll().Select(p => new
                                              ModelViewCauseVisit()
                {
                    StatusVisitID = p.PK_StatusVisitID,
                    StatusVisit   = p.StatusVisit1,
                    Status        = p.Status
                }).ToList();
            }
            else
            {
                StatusVisit = GetAll().Where(p => p.ModifyDate >= objCred.Date).Select(p => new
                                                                                       ModelViewCauseVisit()
                {
                    StatusVisitID = p.PK_StatusVisitID,
                    StatusVisit   = p.StatusVisit1,
                    Status        = p.Status
                }).ToList();
            }
            return(StatusVisit);
        }
        public List <ModelViewUserNotification> GetAllNotificationUsers(string ModuleID, string Name)
        {
            var NegocioUsuario     = new BusinessUsers();
            var NegocioEmpleado    = new BusinessEmployee();
            var NegocioModulosMabe = new BusinessModuleService();
            // var usuarios = NegocioUsuario.GetActives().Where(p=> p.ProfileID == 4);
            var empleados = NegocioEmpleado.GetAll();
            var modulos   = new List <EntityModuleService>();
            var usuarios  = new List <ModelViewUserList>();

            if (ModuleID != null)
            {
                int[] nums = ModuleID.Split(',').Select(int.Parse).ToArray();
                modulos = NegocioModulosMabe.GetAll().Where(p => nums.Contains(p.ModuleID)).ToList();
            }
            else
            {
                modulos = NegocioModulosMabe.GetAll();
            }

            if (Name != "")
            {
                usuarios = NegocioUsuario.GetActives().Where(p => p.ProfileID == 4 && (p.Name.ToLower().Contains(Name.ToLower()) || p.UserName.Contains(Name))).ToList();
            }
            else
            {
                usuarios = NegocioUsuario.GetActives();
            }

            return((from a in usuarios
                    join b in empleados on a.UserID equals b.FK_UserID
                    join c in modulos on b.FK_ModuleID equals c.ModuleID
                    select new ModelViewUserNotification()
            {
                UserID = a.UserID,
                Name = "(" + a.UserName + ")" + " " + b.FirstName + " " + b.LastName + " " + c.ID + " - " + c.Base
            }).ToList());
        }
        public List <ModelViewUserNotification> GetAllNotificationUsers(string Employee)
        {
            var NegocioUsuario     = new BusinessUsers();
            var NegocioEmpleado    = new BusinessEmployee();
            var NegocioModulosMabe = new BusinessModuleService();
            var empleados          = NegocioEmpleado.GetAll();
            var modulos            = new List <EntityModuleService>();
            var usuarios           = new List <ModelViewUserList>();

            modulos = NegocioModulosMabe.GetAll();

            int[] nums = Employee.Split(',').Select(int.Parse).ToArray();
            usuarios = NegocioUsuario.GetActives().Where(p => nums.Contains(p.UserID)).ToList();

            return((from a in usuarios
                    join b in empleados on a.UserID equals b.FK_UserID
                    join c in modulos on b.FK_ModuleID equals c.ModuleID
                    select new ModelViewUserNotification()
            {
                UserID = a.UserID,
                Name = "(" + a.UserName + ")" + " " + b.FirstName + " " + b.LastName + " " + c.ID + " - " + c.Base
            }).ToList());
        }
Beispiel #16
0
        public List <ModelViewInventory> GetInventory(ModelViewUserG Data)
        {
            var NegocioUsuario  = new BusinessUsers();
            var NegocioEmpleado = new BusinessEmployee();
            var NegocioModulo   = new BusinessModuleService();
            var NegocioRecf     = new BusinessREFACCIONES();
            var dataUsuario     = NegocioUsuario.GetUserByToken(Data.TokenUser);
            var empleado        = NegocioEmpleado.GetByUserID(dataUsuario.UserID);

            if (Data.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (Data.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }

            var modulo = NegocioModulo.GetAll().Where(a => empleado.Select(p => p.FK_ModuleID).ToList().Contains(a.ModuleID));

            var lt = NegocioRecf.GetAllRefc(DateTime.Now.Date, modulo.Select(p => p.ID).ToList(), empleado.Select(p => p.StoreProp).ToList()).Select(p => new ModelViewInventory()
            {
                RefManID = p.ID_REF,
                Quantity = p.TOTDISP.Value
            }).ToList();

            if (lt.Count == 0)
            {
                ModelViewInventory model = new ModelViewInventory();
                lt.Add(model);
            }
            return(lt);
        }
Beispiel #17
0
        public List <ModelViewShopPlace> GetListShopPlace(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }

            var lt = new List <EntityShopPlace>();

            if (objCred.Date == null)
            {
                lt = GetAll();
            }
            else
            {
                lt = GetAll().Where(p => p.ModifyDate >= objCred.Date).ToList();
            }
            return(lt.Select(p => new ModelViewShopPlace()
            {
                ShopPlaceID = p.PK_ShopPlaceID,
                StateID = p.FK_StateID.Value,
                ClientID = p.ClientID,
                ShopPlaceDescription = p.ShopPlaceID + " - " + p.ShopPlace1,
                ShopPlaceStatus = p.Status
            }).ToList());
        }
Beispiel #18
0
        public async Task <IActionResult> AddEmployee([FromBody] BusinessEmployeeViewModel employee)
        {
            var id = "";

            var errorMessage = new ErrorMessageViewModel();
            var error        = new { Error = errorMessage };

            try
            {
                id = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").SingleOrDefault().Value;
            }
            catch (Exception exception)
            {
                errorMessage.Message = "Id was not found";
                return(BadRequest(error));
            }

            // Get the employer info
            BusinessUsers business = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault();

            if (business == null)
            {
                errorMessage.Message = "Could not get the employer info";
                return(Json(error));
            }

            // Check if the user exists
            ApplicationUser user = _userManager.Users.SingleOrDefault(e => e.Email.Equals(employee.Email, StringComparison.InvariantCultureIgnoreCase));

            // If not, create the user identity profile
            if (user == null)
            {
                if (employee.Email != null)
                {
                    ApplicationUser applicationUser = new ApplicationUser
                    {
                        UserName = employee.Email,
                        Email    = employee.Email
                    };

                    // Set temporary password
                    string password = String.Format("{0}{1}#{2}",
                                                    employee.Email.First().ToString().ToUpper(), employee.Email.Substring(1), DateTime.Now.Year);


                    IdentityResult result = await _userManager.CreateAsync(applicationUser, password);

                    if (result.Succeeded)
                    {
                        await _userManager.AddToRoleAsync(applicationUser, "Employee");

                        await _signInManager.SignInAsync(applicationUser, false);

                        // Add the new user to the database
                        BusinessEmployees businessEmployee = new BusinessEmployees
                        {
                            FirstName      = employee.FirstName,
                            LastName       = employee.LastName,
                            Position       = employee.Position,
                            CanEditLibrary = employee.CanEditLibrary,
                            PhoneNumber    = employee.PhoneNumber,
                            UserId         = applicationUser.Id,
                            BusinessUserId = business.BusinessUserId
                        };

                        if (!String.IsNullOrWhiteSpace(employee.ProfilePicture))
                        {
                            var fileName = await fileController.UploadImage(employee.ProfilePicture, Request);

                            if (String.IsNullOrWhiteSpace(fileName))
                            {
                                errorMessage.Message = "Image upload encountered an error";
                                return(Json(error));
                            }

                            businessEmployee.ProfilePicture = fileName;
                        }

                        db.BusinessEmployees.Add(businessEmployee);

                        try
                        {
                            db.SaveChanges();
                        }
                        catch (Exception exception)
                        {
                            errorMessage.Message = "Could not create the business employee";
                            return(Json(error));
                        }

                        // model data
                        var modelData = new BusinessEmployeeViewModel
                        {
                            Id             = businessEmployee.UserId,
                            FirstName      = businessEmployee.FirstName,
                            LastName       = businessEmployee.LastName,
                            Position       = businessEmployee.Position,
                            ProfilePicture = businessEmployee.ProfilePicture,
                            PhoneNumber    = businessEmployee.PhoneNumber,
                            CanEditLibrary = businessEmployee.CanEditLibrary,
                            Email          = applicationUser.Email
                        };

                        return(CreatedAtAction("AddEmployee", new { id = modelData.Id }, modelData));
                    }

                    // Send an email with this link ( SET UP SENDGRID TOWARDS END OF PROJECT )

                    //string code = await _userManager.GeneratePasswordResetTokenAsync(applicationUser);
                    //var callbackUrl = Url.Action("ResetPassword", "Accounts", new { userId = applicationUser.Id, code }, protocol: Request.Scheme);

                    //// Send the email
                    //var emailNotification = new EmailNotificationViewModel
                    //{
                    //    Email = applicationUser.Email,
                    //    Subject = "SPINE - Password Reset",
                    //    Content = "",
                    //    Html = "Please reset your password by clicking <a href =\"" + callbackUrl + "\">here</a>"
                    //};

                    //await notificationsController.SendEmailNotification(emailNotification);
                }
                else
                {
                    errorMessage.Message = "Data is missing the Email field";
                    return(Json(error));
                }
            }

            errorMessage.Message = "An error has occurred";
            return(Json(error));
        }
        //public List<ModelViewSpareParts> GetListSparePartsComplete(ModelViewUserG objCred)
        //{
        //    return new RepositoryBuildOfMaterial().GetList(objCred);
        //}


        public List <ModelViewSpareParts> GetListSpareParts(ModelViewUserG objCred)
        {
            var NegocioBase     = new BusinessInstalledBase();
            var NegocioUsuario  = new BusinessUsers();
            var NegocioOrdenes  = new BusinessOrder();
            var NegocioEmpleado = new BusinessEmployee();
            var NegocioManoObra = new BusinessWorkforce();
            var user            = NegocioUsuario.GetUserByToken(objCred.TokenUser);
            var empleado        = NegocioEmpleado.GetByUserID(user.UserID);


            var lista = new List <ModelViewSpareParts>();

            if (objCred.ProductID == 0)
            {
                //var ordenes1 = NegocioOrdenes.GetAll().Where(p => empleado.Select(q => q.PK_EmployeeID).ToArray<int>().Contains(p.FK_EmployeeID.Value) && p.OrderExecuteDate >= objCred.Date);
                var        ordenes       = NegocioOrdenes.GetAll(empleado.Select(q => q.PK_EmployeeID).ToList(), objCred.Date.Value, false);
                List <int> baseInstalada = ordenes.Select(p => p.FK_InstalledBaseID).ToList();
                //var prod = NegocioBase.GetAll();
                //var modelos = (from c in ordenes
                //               join p in prod on c.FK_InstalledBaseID equals p.PK_InstalledBaseID
                //               select p.FK_ProductID).Distinct();
                var modelos = NegocioBase.GetAllByBI(baseInstalada).Select(p => p.FK_ProductID).Distinct();
                modelos = modelos.Where(x => x != null).ToList();
                List <int> modelo = modelos.Where(x => x != null).Cast <int>().ToList();
                lista = GetListSparePartsByModel(modelo);
                //lista = (from c in modelos
                //         join p in GetAll() on c equals p.FK_ProductID
                //         select new ModelViewSpareParts()
                //         {
                //             BuildOfMaterialsID = p.PK_BuildOfMaterialsID,
                //             ProductID = p.FK_ProductID,
                //             Model = p.Model,
                //             SparePartsID = p.SparePartsID,
                //             Quantity = p.Quantity,
                //             SpartePartDescription = p.SparePartDescription,
                //             StatusBOM = p.StatusBOM,
                //             Status = p.Status
                //         }).ToList<ModelViewSpareParts>();
            }
            else
            {
                lista = GetAll().Where(p => p.FK_ProductID == objCred.ProductID).Select(p => new ModelViewSpareParts()
                {
                    BuildOfMaterialsID = p.PK_BuildOfMaterialsID,
                    ProductID          = p.FK_ProductID,
                    Model                 = p.Model,
                    SparePartsID          = p.SparePartsID,
                    Quantity              = p.Quantity,
                    SpartePartDescription = p.SparePartDescription,
                    StatusBOM             = p.StatusBOM,
                    Status                = p.Status
                }).ToList <ModelViewSpareParts>();
            }
            var demo2 = NegocioManoObra.GetAll().Where(p => p.WorkforceID == "8011161600000031").Select(p => new ModelViewSpareParts
            {
                BuildOfMaterialsID = 0,
                ProductID          = 0,
                Model                 = "",
                SparePartsID          = p.WorkforceID,
                Quantity              = 1,
                SpartePartDescription = p.Description,
                StatusBOM             = "",
                Status                = p.Status,
            }).First();

            var demo3 = NegocioManoObra.GetAll().Where(p => p.WorkforceID == "8011161600000032").Select(p => new ModelViewSpareParts
            {
                BuildOfMaterialsID = 0,
                ProductID          = 0,
                Model                 = "",
                SparePartsID          = p.WorkforceID,
                Quantity              = 1,
                SpartePartDescription = p.Description,
                StatusBOM             = "",
                Status                = p.Status,
            }).First();

            lista.Add(demo2);
            lista.Add(demo3);

            return(lista);
        }
Beispiel #20
0
        public static ModelViewResultREST SetPayment(ModelViewPayment model)
        {
            try
            {
                var dataUsuario = new BusinessUsers().GetUserByToken(model.TokenUser);
                if (model.TokenApp != GlobalConfiguration.TokenWEB)
                {
                    if (model.TokenApp != GlobalConfiguration.TokenMobile)
                    {
                        throw new Exception("TokenInvalid");
                    }
                }
                if (dataUsuario == null)
                {
                    throw new Exception("UserPasswordInvalid");
                }
                var orden   = new BusinessOrder().GetByOrderID(model.OrderID);
                var payment = new BusinessPayment().GetPolicyPayment(orden.PK_OrderID, model.Folio);

                if (payment.OrderID == null)
                {
                    new BusinessPayment().Insert(new entities.Entity.Operation.EntityPayment()
                    {
                        PK_PaymentID         = 0,
                        FK_OrderID           = new BusinessOrder().GetByOrderID(model.OrderID).PK_OrderID,
                        AuthorizationPayment = model.AuthorizationPayment,
                        DatePayment          = Convert.ToDateTime(model.DatePayment),
                        MountPayment         = model.MountPayment,
                        TypePaymentID        = model.TypePaymentID,
                        Status           = true,
                        CreateDate       = DateTime.UtcNow,
                        ModifyDate       = DateTime.UtcNow,
                        Folio            = model.Folio,
                        Fk_TypeQuotation = model.EstimatedType
                    });
                }
                else
                {
                    new BusinessPayment().Update(new entities.Entity.Operation.EntityPayment()
                    {
                        PK_PaymentID         = payment.PK_PaymentID,
                        FK_OrderID           = new BusinessOrder().GetByOrderID(model.OrderID).PK_OrderID,
                        AuthorizationPayment = model.AuthorizationPayment,
                        DatePayment          = Convert.ToDateTime(model.DatePayment),
                        MountPayment         = model.MountPayment,
                        TypePaymentID        = model.TypePaymentID,
                        Status           = true,
                        CreateDate       = DateTime.UtcNow,
                        ModifyDate       = DateTime.UtcNow,
                        Folio            = model.Folio,
                        Fk_TypeQuotation = model.EstimatedType
                    });
                }
                return(new ModelViewResultREST()
                {
                    Result = "Success"
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #21
0
        public async Task <IActionResult> GetMyBooks()
        {
            var id   = "";
            var role = "";

            var errorMessage = new ErrorMessageViewModel();
            var error        = new { Error = errorMessage };

            if (User == null)
            {
                errorMessage.Message = "Could not find user for claims";
                return(Json(error));
            }

            try
            {
                id   = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").SingleOrDefault().Value;
                role = User.Claims.Where(c => c.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").SingleOrDefault().Value;
            }
            catch (Exception exception)
            {
                errorMessage.Message = "Id or role was not found";
                return(Json(error));
            }

            if (role == "Personal")
            {
                PersonalUsers personalUser = db.PersonalUsers.Where(e => e.UserId == id).SingleOrDefault();

                if (personalUser == null)
                {
                    errorMessage.Message = "Could not find user profile";
                    return(Json(error));
                }

                // Get books for the user
                List <BookDetailsViewModel> books    = new List <BookDetailsViewModel>();
                List <Documents>            bookList = db.Documents.Where(e => e.UserId == id).ToList();

                foreach (Documents item in bookList)
                {
                    // Get the genres for the book
                    List <DocumentGenres>     genreList = db.DocumentGenres.Where(e => e.DocumentId == item.DocumentId).ToList();
                    List <BookGenreViewModel> genres    = new List <BookGenreViewModel>();

                    foreach (var dbGenre in genreList)
                    {
                        Genres genre = db.Genres.Where(e => e.GenreId == dbGenre.GenreId).SingleOrDefault();

                        if (genre == null)
                        {
                            errorMessage.Message = "Could not find the genre for the book";
                            return(Json(error));
                        }

                        var bookGenre = new BookGenreViewModel
                        {
                            GenreId = genre.GenreId,
                            Name    = genre.Title
                        };

                        genres.Add(bookGenre);
                    }

                    // Get the authors for the book
                    List <DocumentAuthors>     authorList = db.DocumentAuthors.Where(e => e.DocumentId == item.DocumentId).ToList();
                    List <BookAuthorViewModel> authors    = new List <BookAuthorViewModel>();

                    foreach (var documentAuthor in authorList)
                    {
                        Authors author = db.Authors.Where(e => e.AuthorId == documentAuthor.AuthorId).SingleOrDefault();

                        if (author == null)
                        {
                            errorMessage.Message = "Could not find the author for the book";
                            return(Json(error));
                        }

                        var bookAuthor = new BookAuthorViewModel
                        {
                            AuthorId = author.AuthorId,
                            Name     = author.Name
                        };

                        authors.Add(bookAuthor);
                    }

                    // Get the insurance information for the book
                    InsuranceInformation          bookInsurance        = db.InsuranceInformation.Where(e => e.InsuranceInformationId == item.InsuranceInformationId).SingleOrDefault();
                    InsuranceInformationViewModel insuranceInformation = new InsuranceInformationViewModel();

                    if (bookInsurance != null)
                    {
                        insuranceInformation.Cost          = bookInsurance.Cost;
                        insuranceInformation.DatePurchased = bookInsurance.DatePurchased.ToString("yyyy-MM-dd");
                        insuranceInformation.ReceiptImage  = bookInsurance.ReceiptImage;
                        insuranceInformation.IssueDate     = bookInsurance.IssueDate.ToString("yyyy-MM-dd");
                    }

                    BookDetailsViewModel book = new BookDetailsViewModel
                    {
                        Id                   = item.DocumentId,
                        Title                = item.Title,
                        Authors              = authors.ToArray(),
                        Genres               = genres.ToArray(),
                        ISBN                 = item.ISBN,
                        CheckedOut           = item.CheckedOut,
                        Picture              = item.CoverImage,
                        Pages                = Convert.ToInt32(item.Pages),
                        Publisher            = item.Publisher,
                        PublishedDate        = item.PublishedDate.ToString("yyyy-MM-dd"),
                        Edition              = item.Edition,
                        Description          = item.Description,
                        InsuranceInformation = insuranceInformation
                    };

                    books.Add(book);
                }

                return(Ok(books));
            }

            else if (role == "Business")
            {
                BusinessUsers businessUser = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault();

                if (businessUser == null)
                {
                    errorMessage.Message = "Could not find user profile";
                    return(Json(error));
                }

                // Get books for the user
                List <BookDetailsViewModel> books    = new List <BookDetailsViewModel>();
                List <Documents>            bookList = db.Documents.Where(e => e.UserId == id).ToList();

                foreach (Documents item in bookList)
                {
                    // Get the genres for the book
                    List <DocumentGenres>     genreList = db.DocumentGenres.Where(e => e.DocumentId == item.DocumentId).ToList();
                    List <BookGenreViewModel> genres    = new List <BookGenreViewModel>();

                    foreach (var dbGenre in genreList)
                    {
                        Genres genre = db.Genres.Where(e => e.GenreId == dbGenre.GenreId).SingleOrDefault();

                        if (genre == null)
                        {
                            errorMessage.Message = "Could not find the genre for the book";
                            return(Json(error));
                        }

                        var bookGenre = new BookGenreViewModel
                        {
                            GenreId = genre.GenreId,
                            Name    = genre.Title
                        };

                        genres.Add(bookGenre);
                    }

                    // Get the authors for the book
                    List <DocumentAuthors>     authorList = db.DocumentAuthors.Where(e => e.DocumentId == item.DocumentId).ToList();
                    List <BookAuthorViewModel> authors    = new List <BookAuthorViewModel>();

                    foreach (var documentAuthor in authorList)
                    {
                        Authors author = db.Authors.Where(e => e.AuthorId == documentAuthor.AuthorId).SingleOrDefault();

                        if (author == null)
                        {
                            errorMessage.Message = "Could not find the author for the book";
                            return(Json(error));
                        }

                        var bookAuthor = new BookAuthorViewModel
                        {
                            AuthorId = author.AuthorId,
                            Name     = author.Name
                        };

                        authors.Add(bookAuthor);
                    }

                    // Get the insurance information for the book
                    InsuranceInformation          bookInsurance        = db.InsuranceInformation.Where(e => e.InsuranceInformationId == item.InsuranceInformationId).SingleOrDefault();
                    InsuranceInformationViewModel insuranceInformation = new InsuranceInformationViewModel();

                    if (bookInsurance != null)
                    {
                        insuranceInformation.Cost          = bookInsurance.Cost;
                        insuranceInformation.DatePurchased = bookInsurance.DatePurchased.ToString("yyyy-MM-dd");
                        insuranceInformation.ReceiptImage  = bookInsurance.ReceiptImage;
                        insuranceInformation.IssueDate     = bookInsurance.IssueDate.ToString("yyyy-MM-dd");
                    }

                    BookDetailsViewModel book = new BookDetailsViewModel
                    {
                        Id                   = item.DocumentId,
                        Title                = item.Title,
                        Authors              = authors.ToArray(),
                        Genres               = genres.ToArray(),
                        ISBN                 = item.ISBN,
                        CheckedOut           = item.CheckedOut,
                        Picture              = item.CoverImage,
                        Pages                = Convert.ToInt32(item.Pages),
                        Publisher            = item.Publisher,
                        PublishedDate        = item.PublishedDate.ToString("yyyy-MM-dd"),
                        Edition              = item.Edition,
                        Description          = item.Description,
                        InsuranceInformation = insuranceInformation
                    };

                    books.Add(book);
                }

                return(Ok(books));
            }

            else if (role == "Employee")
            {
                BusinessEmployees employee = db.BusinessEmployees.Where(e => e.UserId == id).SingleOrDefault();

                if (employee == null)
                {
                    errorMessage.Message = "Could not find user profile";
                    return(Json(error));
                }

                // Get the employer
                BusinessUsers businessUser = db.BusinessUsers.Where(e => e.BusinessUserId == employee.BusinessUserId).SingleOrDefault();

                // Get books for the user
                List <BookDetailsViewModel> books    = new List <BookDetailsViewModel>();
                List <Documents>            bookList = db.Documents.Where(e => e.UserId == businessUser.UserId).ToList();

                foreach (Documents item in bookList)
                {
                    // Get the genres for the book
                    List <DocumentGenres>     genreList = db.DocumentGenres.Where(e => e.DocumentId == item.DocumentId).ToList();
                    List <BookGenreViewModel> genres    = new List <BookGenreViewModel>();

                    foreach (var dbGenre in genreList)
                    {
                        Genres genre = db.Genres.Where(e => e.GenreId == dbGenre.GenreId).SingleOrDefault();

                        if (genre == null)
                        {
                            errorMessage.Message = "Could not find the genre for the book";
                            return(Json(error));
                        }

                        var bookGenre = new BookGenreViewModel
                        {
                            GenreId = genre.GenreId,
                            Name    = genre.Title
                        };

                        genres.Add(bookGenre);
                    }

                    // Get the authors for the book
                    List <DocumentAuthors>     authorList = db.DocumentAuthors.Where(e => e.DocumentId == item.DocumentId).ToList();
                    List <BookAuthorViewModel> authors    = new List <BookAuthorViewModel>();

                    foreach (var documentAuthor in authorList)
                    {
                        Authors author = db.Authors.Where(e => e.AuthorId == documentAuthor.AuthorId).SingleOrDefault();

                        if (author == null)
                        {
                            errorMessage.Message = "Could not find the author for the book";
                            return(Json(error));
                        }

                        var bookAuthor = new BookAuthorViewModel
                        {
                            AuthorId = author.AuthorId,
                            Name     = author.Name
                        };

                        authors.Add(bookAuthor);
                    }

                    // Get the insurance information for the book
                    InsuranceInformation          bookInsurance        = db.InsuranceInformation.Where(e => e.InsuranceInformationId == item.InsuranceInformationId).SingleOrDefault();
                    InsuranceInformationViewModel insuranceInformation = new InsuranceInformationViewModel();

                    if (bookInsurance != null)
                    {
                        insuranceInformation.Cost          = bookInsurance.Cost;
                        insuranceInformation.DatePurchased = bookInsurance.DatePurchased.ToString("yyyy-MM-dd");
                        insuranceInformation.ReceiptImage  = bookInsurance.ReceiptImage;
                        insuranceInformation.IssueDate     = bookInsurance.IssueDate.ToString("yyyy-MM-dd");
                    }

                    BookDetailsViewModel book = new BookDetailsViewModel
                    {
                        Id                   = item.DocumentId,
                        Title                = item.Title,
                        Authors              = authors.ToArray(),
                        Genres               = genres.ToArray(),
                        ISBN                 = item.ISBN,
                        CheckedOut           = item.CheckedOut,
                        Picture              = item.CoverImage,
                        Pages                = Convert.ToInt32(item.Pages),
                        Publisher            = item.Publisher,
                        PublishedDate        = item.PublishedDate.ToString("yyyy-MM-dd"),
                        Edition              = item.Edition,
                        Description          = item.Description,
                        InsuranceInformation = insuranceInformation
                    };

                    books.Add(book);
                }

                return(Ok(books));
            }

            errorMessage.Message = "An error has occurred";
            return(Ok(error));
        }
Beispiel #22
0
        public async Task <IActionResult> GetUserProfile([FromRoute] string id)
        {
            var errorMessage = new ErrorMessageViewModel();
            var error        = new { Error = errorMessage };

            // Get the user profile
            ApplicationUser user = db.ApplicationUser.Where(e => e.Id == id).SingleOrDefault();

            if (user == null)
            {
                errorMessage.Message = "Could not find the user profile";
                return(Json(error));
            }

            // Find the user type based on the id
            BusinessUsers businessUser = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault();

            if (businessUser == null)
            {
                BusinessEmployees employee = db.BusinessEmployees.Where(e => e.UserId == id).SingleOrDefault();

                if (employee == null)
                {
                    PersonalUsers personalUser = db.PersonalUsers.Where(e => e.UserId == id).SingleOrDefault();

                    if (personalUser == null)
                    {
                        errorMessage.Message = "Could not find the profile for the user";
                        return(Json(error));
                    }

                    // Get the personal user details
                    ProfileDetailsViewModel personalProfile = new ProfileDetailsViewModel
                    {
                        Id             = personalUser.UserId,
                        FirstName      = personalUser.FirstName,
                        LastName       = personalUser.LastName,
                        Email          = user.Email,
                        AccountType    = "Personal",
                        ProfilePicture = personalUser.ProfilePicture
                    };

                    return(Ok(personalProfile));
                }

                // Get the employer info
                BusinessUsers employer = db.BusinessUsers.Where(e => e.BusinessUserId == employee.BusinessUserId).SingleOrDefault();

                if (employer == null)
                {
                    errorMessage.Message = "Could not find the employer profile for the employee";
                    return(Json(error));
                }

                // Get the employee user details
                EmployeeDetailsViewModel employeeProfile = new EmployeeDetailsViewModel
                {
                    Id             = employee.UserId,
                    FirstName      = employee.FirstName,
                    LastName       = employee.LastName,
                    Email          = user.Email,
                    AccountType    = "Employee",
                    ProfilePicture = employee.ProfilePicture,
                    Organization   = employer.Organization,
                    CanEditLibrary = employee.CanEditLibrary
                };

                return(Ok(employeeProfile));
            }

            // Get the business user details
            ProfileDetailsViewModel businessProfile = new ProfileDetailsViewModel
            {
                Id             = businessUser.UserId,
                FirstName      = businessUser.FirstName,
                LastName       = businessUser.LastName,
                Email          = user.Email,
                AccountType    = "Business",
                ProfilePicture = businessUser.ProfilePicture,
                Organization   = businessUser.Organization
            };

            return(Ok(businessProfile));
        }
Beispiel #23
0
        public async Task <IActionResult> UpdateProfile([FromRoute] string id, [FromBody] ProfileDetailsViewModel profile)
        {
            var errorMessage = new ErrorMessageViewModel();
            var error        = new { Error = errorMessage };

            var role = "";

            if (User != null)
            {
                try
                {
                    role = User.Claims.Where(c => c.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").SingleOrDefault().Value;

                    if (role == null)
                    {
                        errorMessage.Message = "Could not find role for user";
                        return(Json(error));
                    }
                }
                catch (Exception exception)
                {
                    errorMessage.Message = "Could not get role for user";
                    return(Json(error));
                }
            }

            if (profile == null)
            {
                errorMessage.Message = "Model is missing data";
                return(Json(error));
            }

            // Find the type of user based on the role
            if (role == "Personal")
            {
                // Get the personal user in the database
                PersonalUsers personalUser = db.PersonalUsers.Where(e => e.UserId == id).SingleOrDefault();

                // Update the details for the profile
                if (personalUser != null)
                {
                    personalUser.FirstName = profile.FirstName;
                    personalUser.LastName  = profile.LastName;

                    if (!String.IsNullOrWhiteSpace(profile.ProfilePicture))
                    {
                        var fileName = await fileController.UploadImage(profile.ProfilePicture, Request);

                        if (String.IsNullOrWhiteSpace(fileName))
                        {
                            errorMessage.Message = "Image upload encountered an error";
                            return(Json(error));
                        }

                        personalUser.ProfilePicture = fileName;
                    }

                    // Update record in the database
                    db.Entry(personalUser).State = EntityState.Modified;

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception exception)
                    {
                        errorMessage.Message = "Could update the account information";
                        return(Json(error));
                    }

                    return(Ok(personalUser));
                }
                else
                {
                    errorMessage.Message = "Could not find the user profile";
                    return(Json(error));
                }
            }
            else if (role == "Business")
            {
                // Get the business user in the database
                BusinessUsers businessUser = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault();

                // Update the details for the profile
                if (businessUser != null)
                {
                    businessUser.FirstName    = profile.FirstName;
                    businessUser.LastName     = profile.LastName;
                    businessUser.Organization = profile.Organization;
                    businessUser.PhoneNumber  = profile.PhoneNumber;

                    if (!String.IsNullOrWhiteSpace(profile.ProfilePicture))
                    {
                        var fileName = await fileController.UploadImage(profile.ProfilePicture, Request);

                        if (String.IsNullOrWhiteSpace(fileName))
                        {
                            errorMessage.Message = "Image upload encountered an error";
                            return(Json(error));
                        }

                        businessUser.ProfilePicture = fileName;
                    }

                    // Update record in the database
                    db.Entry(businessUser).State = EntityState.Modified;

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception exception)
                    {
                        errorMessage.Message = "Could update the account information";
                        return(Json(error));
                    }

                    return(Ok(businessUser));
                }
                else
                {
                    errorMessage.Message = "Could not find the user profile";
                    return(Json(error));
                }
            }
            else if (role == "Employee")
            {
                // Get the employee in the database
                BusinessEmployees employee = db.BusinessEmployees.Where(e => e.UserId == id).SingleOrDefault();

                // Update the details for the profile
                if (employee != null)
                {
                    employee.FirstName   = profile.FirstName;
                    employee.LastName    = profile.LastName;
                    employee.PhoneNumber = profile.PhoneNumber;

                    if (!String.IsNullOrWhiteSpace(profile.ProfilePicture))
                    {
                        var fileName = await fileController.UploadImage(profile.ProfilePicture, Request);

                        if (String.IsNullOrWhiteSpace(fileName))
                        {
                            errorMessage.Message = "Image upload encountered an error";
                            return(Json(error));
                        }

                        employee.ProfilePicture = fileName;
                    }

                    // Update record in the database
                    db.Entry(employee).State = EntityState.Modified;

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception exception)
                    {
                        errorMessage.Message = "Could update the account information";
                        return(Json(error));
                    }

                    return(Ok(employee));
                }
                else
                {
                    errorMessage.Message = "Could not find the user profile";
                    return(Json(error));
                }
            }

            errorMessage.Message = "An error has occurred";
            return(Json(error));
        }
Beispiel #24
0
        public List <ModelViewGuarantyBOM> GetLisValidationBOM(ModelViewUserG objCred)
        {
            var NegocioUsuario  = new BusinessUsers();
            var NegocioEmpleado = new BusinessEmployee();
            var dataUsuario     = NegocioUsuario.GetUserByToken(objCred.TokenUser);
            var empleado        = NegocioEmpleado.GetByUserID(dataUsuario.UserID);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }

            //var lista = new List<EntityValidationGuarantyBOM>();

            var lt = new List <EntityValidationGuarantyBOM>();

            if (objCred.Date == null)
            {
                lt = GetAll();
            }
            else
            {
                lt = GetAll().Where(p => p.ModifyDate >= objCred.Date).ToList();
            }
            return(lt.Select(p => new ModelViewGuarantyBOM()
            {
                ValidationGuarantySparePartID = p.PK_ValidationGuarantySparePartID,
                ProductID = p.FK_ProducID.HasValue ? p.FK_ProducID.Value : 0,
                BuildOfMaterialsID = p.FK_BuildOfMaterialsID.HasValue ? p.FK_BuildOfMaterialsID.Value : 0,
                SalesOrganization = p.SalesOrganization,
                SparePartsID = p.SparePartsID,
                Model = p.Model,
                ClientID = p.ClientID,
                Months = p.Months,
                ValidFrom = p.ValidFrom.Value.ToString("yyyy-MM-dd"),
                ValidTo = p.ValidTo.Value.ToString("yyyy-MM-dd"),
            }).ToList <ModelViewGuarantyBOM>());


            //var NegocioOrdenes = new BusinessOrder();
            //var NegocioBase = new BusinessInstalledBase();
            //var ordenes = NegocioOrdenes.GetAll().Where(p => empleado.Select(q => q.PK_EmployeeID).ToArray<int>().Contains(p.FK_EmployeeID.Value) && p.OrderExecuteDate >= objCred.Date.Value.Date);
            //var prod = NegocioBase.GetAll();
            //var modelos = (from c in ordenes
            //               join p in prod on c.FK_InstalledBaseID equals p.PK_InstalledBaseID
            //               select p.FK_ProductID).Distinct();
            //var lista = GetAll();
            //return (from d in lista
            //        join e in modelos on d.FK_ProducID equals e
            //        select new ModelViewGuarantyBOM()
            //        {
            //            ValidationGuarantySparePartID = d.PK_ValidationGuarantySparePartID,
            //            ProductID = d.FK_ProducID.HasValue ? d.FK_ProducID.Value : 0,
            //            BuildOfMaterialsID = d.FK_BuildOfMaterialsID.HasValue ? d.FK_BuildOfMaterialsID.Value : 0,
            //            SalesOrganization = d.SalesOrganization,
            //            SparePartsID = d.SparePartsID,
            //            Model = d.Model,
            //            ClientID = d.ClientID,
            //            Months = d.Months,
            //            ValidFrom = d.ValidFrom.Value.ToString("yyyy-MM-dd"),
            //            ValidTo = d.ValidTo.Value.ToString("yyyy-MM-dd"),
            //        }).ToList<ModelViewGuarantyBOM>();
        }
Beispiel #25
0
        public List <ModelViewFolios> GetLastFolio(ModelViewUserG objCred)
        {
            var NegocioPoliza   = new BusinessPolicy();
            var NegocioRef      = new BusinessRefsell();
            var NegocioOrden    = new BusinessOrder();
            var NegocioUsuario  = new BusinessUsers();
            var NegocioEmpleado = new BusinessEmployee();
            var dataUsuario     = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }
            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }


            DateTime date = objCred.Date.Value;


            List <ModelViewFolios> x = new List <ModelViewFolios>();

            var Empleado2 = NegocioEmpleado.GetEmployeUser(dataUsuario.UserID);
            var Empleado  = Empleado2[0];

            int Conteo;
            List <EntityQuotation> Cotizaciones;
            List <EntityPolicy>    Polizas;
            List <EntityRefSell>   Refacciones;

            string Tipo;
            int    count = 1;

            while (count < 4)
            {
                switch (count)
                {
                case 1:

                    Tipo         = "Cotizacion";
                    Conteo       = GetByEmpoyeeDate(Empleado.PK_EmployeeID, date).Count;
                    Cotizaciones = GetByEmpoyeeDate(Empleado.PK_EmployeeID, date);

                    var LastFolio = Cotizaciones.Count is 0 ? "": Cotizaciones[0].Folio;

                    x.Add(new ModelViewFolios(Tipo, Conteo, LastFolio));
                    count++;

                    break;

                case 2:
                    Tipo    = "Polizas";
                    Conteo  = NegocioPoliza.GetByEmpoyeeDate(Empleado.PK_EmployeeID, date).Count;
                    Polizas = NegocioPoliza.GetByEmpoyeeDate(Empleado.PK_EmployeeID, date);

                    LastFolio = Polizas.Count is 0 ? "" : Polizas[0].IDPolicy;

                    x.Add(new ModelViewFolios(Tipo, Conteo, LastFolio));
                    count++;
                    break;

                case 3:
                    Tipo        = "Refacciones";
                    Conteo      = NegocioRef.GetByEmpoyeeDate(Empleado.PK_EmployeeID, date).Count;
                    Refacciones = NegocioRef.GetByEmpoyeeDate(Empleado.PK_EmployeeID, date);
                    LastFolio   = Refacciones.Count is 0 ? "" : Refacciones[0].IDRefSell;

                    x.Add(new ModelViewFolios(Tipo, Conteo, LastFolio));
                    count++;
                    break;

                default:

                    count++;
                    break;
                }
            }



            return(x);
        }
Beispiel #26
0
        public List <ModelViewSerialNumber> GetListModel(ModelViewUserG objCred)
        {
            var NegocioBase         = new BusinessInstalledBase();
            var NegocioUsuario      = new BusinessUsers();
            var NegocioOrdenes      = new BusinessOrder();
            var NegocioValidacionSN = new BusinessValidationsSerialNumber();
            var NegocioEmpleado     = new BusinessEmployee();
            var user         = NegocioUsuario.GetUserByToken(objCred.TokenUser);
            var empleado     = NegocioEmpleado.GetByUserID(user.UserID);
            var ordenes      = NegocioOrdenes.GetAll().Where(p => empleado.Select(q => q.PK_EmployeeID).ToList <int>().Contains(p.FK_EmployeeID.Value) && p.OrderExecuteDate >= objCred.Date);
            var prod         = NegocioBase.GetAll();
            var SerialNumber = GetAll();
            var Validation   = NegocioValidacionSN.GetAll();

            if (objCred.ProductID == 0)
            {
                var modelos = (from c in ordenes
                               join p in prod on c.FK_InstalledBaseID equals p.PK_InstalledBaseID
                               select p.FK_ProductID).Distinct().ToList();
                modelos = modelos.Where(x => x != null).ToList();
                var lt = (from c in SerialNumber
                          join p in Validation on c.PK_ModelSerialNumberID equals p.FK_ModelSerialNumberID
                          select new ModelViewSerialNumber()
                {
                    ModelSerialNumberID = c.PK_ModelSerialNumberID,
                    ProductID = c.FK_ProducID,
                    Model = c.Model,
                    ValidationFormatID = c.ValidationFormatID,
                    ValidDate = c.ValidDate,
                    InitialDate = c.InitialDate != null ? c.InitialDate.Value.ToString("yyyy-MM-dd") : "",
                    EndDate = c.EndDate != null ? c.EndDate.Value.ToString("yyyy-MM-dd") : "",
                    ValidationsSerialNumberID = p.PK_ValidationsSerialNumberID,
                    ValidationName = p.ValidationName,
                    InitialPosition = p.InitialPosition,
                    FinalPosition = p.FinalPosition,
                    Allowed = p.Allowed,
                    RankID = p.RankID
                }).ToList();


                return((from c in modelos
                        join p in lt on c equals p.ProductID
                        select p).ToList());
            }
            else
            {
                return((from c in SerialNumber.Where(p => p.FK_ProducID == objCred.ProductID)
                        join p in Validation on c.PK_ModelSerialNumberID equals p.FK_ModelSerialNumberID
                        select new ModelViewSerialNumber()
                {
                    ModelSerialNumberID = c.PK_ModelSerialNumberID,
                    ProductID = c.FK_ProducID,
                    Model = c.Model,
                    ValidationFormatID = c.ValidationFormatID,
                    ValidDate = c.ValidDate,
                    InitialDate = c.InitialDate != null ? c.InitialDate.Value.ToString("yyyy-MM-dd") : "",
                    EndDate = c.EndDate != null ? c.EndDate.Value.ToString("yyyy-MM-dd") : "",
                    ValidationsSerialNumberID = p.PK_ValidationsSerialNumberID,
                    ValidationName = p.ValidationName,
                    InitialPosition = p.InitialPosition,
                    FinalPosition = p.FinalPosition,
                    Allowed = p.Allowed,
                    RankID = p.RankID
                }).ToList());
            }



            //return lt;
        }
        public EntityGoogleMapsDistanceMatrixResponse GetDistanceMatrix(ModelViewGoogleMapsDistanceMatrixRequest model)
        {
            var dataUsuario = new BusinessUsers().GetUserByToken(model.TokenUser);

            if (model.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (model.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }

            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }


            EntityGoogleMapsDistanceMatrixRequest request = new EntityGoogleMapsDistanceMatrixRequest();

            request.origins        = model.origins;
            request.destinations   = model.destinations;
            request.units          = "metric";
            request.departure_time = "now";
            request.key            = GlobalConfiguration.GoogleMapsDistanceMatrixTOKEN;

            EntityGoogleMapsDistanceMatrixResponse objResponse = null;

            try
            {
                string Url = GlobalConfiguration.GoogleMapsDistanceMatrixURL;

                Url += "?units=" + request.units;
                Url += "&origins=" + request.origins;
                Url += "&destinations=" + request.destinations;
                Url += "&departure_time=" + request.departure_time;
                Url += "&key=" + request.key;

                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(Url);
                webrequest.Method        = "POST";
                webrequest.ContentType   = "application/json";
                webrequest.ContentLength = 0;
                Stream stream = webrequest.GetRequestStream();
                stream.Close();
                string result;
                using (WebResponse response = webrequest.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        result      = reader.ReadToEnd();
                        objResponse = JsonConvert.DeserializeObject <EntityGoogleMapsDistanceMatrixResponse>(result);
                    }
                }

                if (objResponse == null)
                {
                    throw new Exception("Error parser " + result + " | Url " + Url);
                }
            }
            catch (Exception ex)
            {
                throw new Generic_Exception(ex, Generic_Exception.ErrorCodes.ErrorGoogleMaps);
            }
            return(objResponse);
        }
        public List <ModelViewFailures> GetListCodeFailure(ModelViewUserG objCred)
        {
            var NegocioUsuario = new BusinessUsers();
            var dataUsuario    = NegocioUsuario.GetUserByToken(objCred.TokenUser);

            if (objCred.TokenApp != GlobalConfiguration.TokenWEB)
            {
                if (objCred.TokenApp != GlobalConfiguration.TokenMobile)
                {
                    throw new Exception("TokenInvalid");
                }
            }

            if (dataUsuario == null)
            {
                throw new Exception("UserPasswordInvalid");
            }
            var NegocioOrdenes     = new BusinessOrder();
            var NegocioEmpleado    = new BusinessEmployee();
            var NegocioCodigoFalla = new BusinessCodeFailure();
            var NegocioBase        = new BusinessInstalledBase();
            var codefailure        = NegocioCodigoFalla.GetAll();
            var empleado           = NegocioEmpleado.GetByUserID(dataUsuario.UserID);

            if (objCred.ProductID == 0)
            {
                //var ordenes = NegocioOrdenes.GetAll().Where(p => empleado.Select(q => q.PK_EmployeeID).ToArray<int>().Contains(p.FK_EmployeeID.Value) && p.OrderExecuteDate >= objCred.Date.Value.Date);
                //var prod = NegocioBase.GetAll();
                //var modelos = (from c in ordenes
                //               join p in prod on c.FK_InstalledBaseID equals p.PK_InstalledBaseID
                //               select p.FK_ProductID).Distinct().ToList();
                //modelos = modelos.Where(x => x != null).ToList();
                var        ordenes       = NegocioOrdenes.GetAll(empleado.Select(q => q.PK_EmployeeID).ToList(), objCred.Date.Value, false);
                List <int> baseInstalada = ordenes.Select(p => p.FK_InstalledBaseID).ToList();
                var        modelos       = NegocioBase.GetAllByBI(baseInstalada).Select(p => p.FK_ProductID).Distinct();
                modelos = modelos.Where(x => x != null).ToList();
                List <int> modelo    = modelos.Where(x => x != null).Cast <int>().ToList();
                var        codfallas = new List <ModelViewFailures>();
                foreach (var item in modelos)
                {
                    var x = (from c in GetByProductID(item.Value)
                             join p in codefailure on c.FK_CodeFailureID equals p.PK_CodeFailureID
                             select new ModelViewFailures()
                    {
                        CodeFailureID = p.PK_CodeFailureID,
                        ProductID = c.FK_ProductID,
                        CodeFailure = p.CodeFailure1,
                        Failure = p.Failure,
                        Complexity = c.Complexity.GetValueOrDefault(),
                        Status = c.Status
                    }).ToList();

                    codfallas.AddRange(x);
                }
                return(codfallas);
                //return (from c in modelos
                //        join p in GetAll() on c equals p.FK_ProductID
                //        join d in  codefailure on p.FK_CodeFailureID equals d.PK_CodeFailureID
                //        select new ModelViewFailures()
                //        {
                //            CodeFailureID = p.FK_CodeFailureID,
                //            ProductID = p.FK_ProductID,
                //            CodeFailure = d.CodeFailure1,
                //            Failure = d.Failure,
                //            Complexity = p.Complexity.GetValueOrDefault(),
                //            Status = p.Status
                //        }).ToList();
            }
            else
            {
                return((from c in GetByProductID(objCred.ProductID)
                        join p in codefailure on c.FK_CodeFailureID equals p.PK_CodeFailureID
                        select new ModelViewFailures()
                {
                    CodeFailureID = p.PK_CodeFailureID,
                    ProductID = c.FK_ProductID,
                    CodeFailure = p.CodeFailure1,
                    Failure = p.Failure,
                    Complexity = c.Complexity.GetValueOrDefault(),
                    Status = c.Status
                }).ToList());
            }
        }
Beispiel #29
0
        public async Task <object> Register([FromBody] RegistrationViewModel model)
        {
            var errorMessage = new ErrorMessageViewModel();
            var error        = new { Error = errorMessage };

            // Check for the role type upon registration
            string[] availableRoles = { "Personal", "Business" };
            if (!availableRoles.Contains(model.Role))
            {
                errorMessage.Message = "Invalid Role";
                return(Json(error));
            }

            // Create variable for Application User
            var user = new ApplicationUser
            {
                Email    = model.Email,
                UserName = model.Email
            };

            ApplicationUser appUser = db.ApplicationUser.Where(e => e.Email.Equals(user.Email, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();

            if (appUser != null)
            {
                errorMessage.Message = "Username is already taken.";
                return(Json(error));
            }

            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                await _userManager.AddToRoleAsync(user, model.Role);

                await _signInManager.SignInAsync(user, false);

                // Profile Types
                BusinessUsers businessUser = new BusinessUsers();
                PersonalUsers personalUser = new PersonalUsers();

                // Create the user profile
                if (model == null)
                {
                    errorMessage.Message = "No data was found";
                    return(Json(error));
                }

                if (model.Role == availableRoles[0])
                {
                    // If the user role is a business user
                    var profile = new PersonalUsers
                    {
                        FirstName = model.FirstName,
                        LastName  = model.LastName,
                        UserId    = user.Id
                    };

                    // Add the user to the database
                    db.PersonalUsers.Add(profile);

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception exception)
                    {
                        errorMessage.Message = "Could not add personal user to the database";
                        return(Json(error));
                    }

                    personalUser = profile;
                }
                else if (model.Role == availableRoles[1])
                {
                    // If the user role is a personal user
                    var profile = new BusinessUsers
                    {
                        FirstName    = model.FirstName,
                        LastName     = model.LastName,
                        Organization = model.Organization,
                        UserId       = user.Id,
                        PhoneNumber  = model.PhoneNumber
                    };

                    // Add the user to the database
                    db.BusinessUsers.Add(profile);

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception exception)
                    {
                        errorMessage.Message = "Could not add business user to the database";
                        return(Json(error));
                    }

                    businessUser = profile;
                }

                // Create role list to create jwt token
                List <string> roleList = new List <string>()
                {
                    model.Role
                };

                var jwtToken = await GenerateJwtToken(model.Email, user, roleList);

                var userRoles = await _userManager.GetRolesAsync(user);

                // Send the user role along with the JWT Token
                if (model.Role == availableRoles[0])
                {
                    var response = new PersonalLoginResponse
                    {
                        Token        = jwtToken.ToString(),
                        Roles        = userRoles.ToArray(),
                        PersonalUser = personalUser
                    };

                    return(Json(response));
                }
                else if (model.Role == availableRoles[1])
                {
                    var response = new BusinessLoginResponse
                    {
                        Token        = jwtToken.ToString(),
                        Roles        = userRoles.ToArray(),
                        BusinessUser = businessUser
                    };

                    return(Json(response));
                }
            }
            else if (!result.Succeeded)
            {
                errorMessage.Message = "Password must have 6+ characters, at least 1 uppercase character, 1 lowercase character, 1 number, and 1 non-alphanumeric character";
                return(Json(error));
            }

            errorMessage.Message = "An error has occurred";
            return(Json(error));
        }
Beispiel #30
0
        public async Task <IActionResult> GetAllEmployees()
        {
            var id = "";

            var errorMessage = new ErrorMessageViewModel();
            var error        = new { Error = errorMessage };

            try
            {
                id = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").SingleOrDefault().Value;
            }
            catch (Exception exception)
            {
                errorMessage.Message = "Id was not found";
                return(BadRequest(error));
            }

            // Get the user
            BusinessUsers user = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault();

            if (user == null)
            {
                errorMessage.Message = "Could not find the business user profile";
                return(Json(error));
            }

            List <BusinessEmployees> employees = new List <BusinessEmployees>();

            employees = db.BusinessEmployees.Where(e => e.BusinessUserId == user.BusinessUserId).ToList();

            List <BusinessEmployeeViewModel> employeeList = new List <BusinessEmployeeViewModel>();

            // Format list with required data
            foreach (BusinessEmployees employee in employees)
            {
                // Get the application user profile
                var profile = db.ApplicationUser.Where(e => e.Id == employee.UserId).SingleOrDefault();

                if (profile == null)
                {
                    errorMessage.Message = "Could not find the employee profile";
                    return(Json(error));
                }

                // Create view model to return
                var businessEmployee = new BusinessEmployeeViewModel
                {
                    Id             = profile.Id,
                    FirstName      = employee.FirstName,
                    LastName       = employee.LastName,
                    Email          = profile.Email,
                    Position       = employee.Position,
                    ProfilePicture = employee.ProfilePicture,
                    PhoneNumber    = employee.PhoneNumber
                };

                employeeList.Add(businessEmployee);
            }

            return(Ok(employeeList.ToArray()));
        }