Ejemplo n.º 1
0
        public ActionResult Edit(int Id)
        {
            Subdistributor model = controller.RetrieveSubdistributor(Id);

            if (controller.ResultManager.IsCorrect)
            {
                //copy the info from TempData into an aux object (cause we cannot use the same object from TempData, it would cause to have two UnitOfWork objects (one from the TempDate and one from the controller object), causing an error on the controller
                ICollection <SubdistributorCropsXMunicipality> auxCropsXMunicipality = new List <SubdistributorCropsXMunicipality>();
                foreach (SubdistributorCropsXMunicipality item in model.CropsXMunicipality)
                {
                    auxCropsXMunicipality.Add(new SubdistributorCropsXMunicipality()
                    {
                        Id = item.Id,
                        AddressMunicipalityAddressStateId = item.AddressMunicipalityAddressStateId,
                        Crop = item.Crop,
                        AddressMunicipalityId = item.AddressMunicipalityId,
                        Municipality          = item.Municipality,
                        Cat_CropId            = item.Cat_CropId,
                        SubdistributorId      = model.Id
                    });
                }

                TempData["CropsXMunicipality"] = auxCropsXMunicipality;
                ViewBag.AddressStates          = AddressStates();
                return(View(model));
            }

            NotifyUser(resultManager: controller.ResultManager);
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 2
0
        public ActionResult ContactIndex(int id)
        {
            Subdistributor subdistributor = controller.RetrieveSubdistributor(id);

            ViewBag.Id = subdistributor.Id;
            ViewBag.SubdistributorName = subdistributor.BusinessName;

            List <SubdistributorContact> contacts = controller.ContactsRetrieveAll(id);

            if (controller.ResultManager.IsCorrect)
            {
                return(View(contacts));
            }

            NotifyUser(resultManager: controller.ResultManager);
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 3
0
        public ActionResult Detail(int Id)
        {
            if (Id == -1)
            {
                NotifyUser(message: "Seleccione primero al subdistribuidor a consultar haciendo click en su Id", messageDebug: controllerTraceId + "Detail.111: no Id was received");
                return(RedirectToAction("Index"));
            }

            Subdistributor auxModel = controller.RetrieveSubdistributor(Id);

            if (!controller.ResultManager.IsCorrect)
            {
                NotifyUser(resultManager: controller.ResultManager);
                RedirectToAction("Index");
            }
            else
            {
                return(View(auxModel));
            }
            return(RedirectToError(errorDefault));
        }
        public bool CreateSubdistributor(Subdistributor model)
        {
            ResultManager.Clear();

            //sys validations
            if (model == null)
            {
                ResultManager.Add(ErrorDefault, Trace + "UpdateSubdistributor.111 No se recibió el modelo");
                return(false);
            }
            if (model.BNAddress == null)
            {
                ResultManager.Add(ErrorDefault, Trace + "UpdateSubdistributor.151 El modelo recibido no contiene el campo BNAddress");
                return(false);
            }
            if (model.SubdistributorEmployees == null || model.SubdistributorEmployees.FirstOrDefault() == null)
            {
                ResultManager.Add(ErrorDefault, Trace + "UpdateSubdistributor.171 El modelo recibido no contiene el campo SubdistributorEmployee[0]");
                return(false);
            }

            //business validations
            if (model.SubdistributorEmployees == null || model.SubdistributorEmployees.FirstOrDefault() == null || string.IsNullOrWhiteSpace(model.SubdistributorEmployees.FirstOrDefault().EMail))
            {
                ResultManager.Add("El correo electrónico del dueño no puede estar vacio", Trace + "UpdateSubdistributor.211 El campo 'SubdistributorEmployees[0].EMail' esta vacio");
                return(false);
            }
            if (model.BNAddress.AddressColonyId == null || model.BNAddress.AddressColonyId < 1)
            {
                ResultManager.Add("Se debe seleccionar la dirección del representante legal", Trace + "UpdateSubdistributor.211 El campo 'BNAddress.AddressColonyId' esta vacio");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.BNAddress.Street))
            {
                ResultManager.Add("Se debe seleccionar la calle, en la dirección del representante legal", Trace + "UpdateSubdistributor.211 El campo 'BNAddress.Street' esta vacio");
                return(false);
            }
            if (model.RTV_BayerEmployeeId < 1)
            {
                ResultManager.Add("Se debe tener asignado un RTV", Trace + "UpdateSubdistributor.211 El campo 'RTV_BayerEmployeeId' esta vacio");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.Type) || model.Type == "-1")
            {
                ResultManager.Add("Se debe seleccionar el tipo Subdistribuidor ó Agricultor", Trace + "UpdateSubdistributor.211 El campo 'Type' esta vacio");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.BusinessName))
            {
                ResultManager.Add("Se debe indicar la razón social", Trace + "UpdateSubdistributor.211 El campo 'BusinessName' esta vacio");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.BNLegalRepresentative))
            {
                ResultManager.Add("Se debe indicar el nombre del representante legal", Trace + "UpdateSubdistributor.211 El campo 'BNLegalRepresentative' esta vacio");
                return(false);
            }
            if (model.CommercialNames.Count <= 0 || model.CommercialNames.FirstOrDefault().Name.Length == 0)
            {
                ResultManager.Add("Se debe indicar al menos un nombre comercial", Trace + "UpdateSubdistributor.211 El campo 'CommercialNames' esta vacio");
                return(false);
            }
            string emailToCheck = model.SubdistributorEmployees.Count > 0 ? model.SubdistributorEmployees.FirstOrDefault().EMail : string.Empty;

            if (IsMailAddressCurrentlyUsed(emailToCheck))
            {
                ResultManager.Add(ErrorDefault, Trace + "La direccion de email '" + emailToCheck + "' actualmente esta asignada a otro usuario, por favor ingresa una diferente.");
                return(false);
            }

            string token = PSD.Common.Random.Token(20);

            Model.SubdistributorEmployee subdistributorEmployee = null;

            try
            {
                //user principal
                User user = User.NewEmpty();
                user.Person                  = null;
                user.Cat_UserStatusId        = 4;                              //created
                user.Cat_UserStatus          = Repository.UserStatuses.Get(4); ///TODO: why do I need this if i already set statusId (doesn't update automatically unless i restart app)
                user.NickName                = model.SubdistributorEmployees.FirstOrDefault().EMail;
                user.FailedLoginAttempts     = 0;
                user.LoginToken              = token;
                user.LoginTokenGeneratedDate = PSD.Common.Dates.Today;

                Model.RolesXUser rolesXUser = new RolesXUser();
                rolesXUser.UserId         = user.Id;
                rolesXUser.Cat_UserRoleId = 9;//9:subdistributor (principal)
                user.RolesXUser           = new List <RolesXUser>()
                {
                    rolesXUser
                };

                subdistributorEmployee = new SubdistributorEmployee();
                subdistributorEmployee.Subdistributor = null;
                subdistributorEmployee.EMail          = model.SubdistributorEmployees.FirstOrDefault().EMail;
                subdistributorEmployee.Name           = model.CommercialNames.FirstOrDefault().Name;
                subdistributorEmployee.User           = user;

                /*
                 * //user view
                 * User userView = User.NewEmpty();
                 * userView.Person = null;
                 * userView.Cat_UserStatusId = 4;//created
                 * userView.Cat_UserStatus = Repository.UserStatuses.Get(4);///TODO: why do I need this if i already set statusId (doesn't update automatically unless i restart app)
                 * userView.NickName = "";//no email at first
                 * userView.FailedLoginAttempts = 0;
                 * userView.LoginToken = "";
                 * userView.LoginTokenGeneratedDate = null;
                 *
                 * Model.RolesXUser rolesXUserView = new RolesXUser();
                 * rolesXUserView.UserId = userView.Id;
                 * rolesXUserView.Cat_UserRoleId = 8;//8:distributor(view)
                 * userView.RolesXUser = new List<RolesXUser>() { rolesXUserView };
                 *
                 * Model.SubdistributorEmployee distributorEmployeeView = SubdistributorEmployee();
                 * distributorEmployeeView.Distributor = null;
                 * distributorEmployeeView.EMail = model.EMail;
                 * distributorEmployeeView.Name = model.Distributor.CommercialName + "(consulta)";
                 * distributorEmployeeView.User = userView;
                 * //employee.Cat_ZoneId = model.Cat_ZoneId == -1? null : model.Cat_ZoneId;
                 */

                //TODO:create from model info
                Address       bnAddress = new Address();
                AddressColony auxColony = Repository.AddressColonies.Get((int)model.BNAddress.AddressColonyId);
                bnAddress.AddressStateId        = auxColony.AddressStateId;
                bnAddress.AddressMunicipalityId = auxColony.AddressMunicipalityId;
                bnAddress.AddressPostalCodeId   = auxColony.AddressPostalCodeId;
                bnAddress.AddressColonyId       = auxColony.Id;
                bnAddress.Street    = model.BNAddress.Street;
                bnAddress.NumberExt = model.BNAddress.NumberExt;
                bnAddress.NumberInt = model.BNAddress.NumberInt;


                //subdistributor
                Model.Subdistributor subddistributor = new Subdistributor();

                //TODO:set address
                subddistributor.BNAddress = bnAddress;

                // add set of additional address
                Address address1 = new Address();
                address1.AddressStateId        = null;
                address1.AddressMunicipalityId = null;
                address1.AddressPostalCodeId   = null;
                address1.AddressColonyId       = null;
                address1.Street    = string.Empty;
                address1.NumberExt = string.Empty;
                address1.NumberInt = string.Empty;

                Address address2 = new Address();
                address2.AddressStateId        = null;
                address2.AddressMunicipalityId = null;
                address2.AddressPostalCodeId   = null;
                address2.AddressColonyId       = null;
                address2.Street    = string.Empty;
                address2.NumberExt = string.Empty;
                address2.NumberInt = string.Empty;

                Address address3 = new Address();
                address3.AddressStateId        = null;
                address3.AddressMunicipalityId = null;
                address3.AddressPostalCodeId   = null;
                address3.AddressColonyId       = null;
                address3.Street    = string.Empty;
                address3.NumberExt = string.Empty;
                address3.NumberInt = string.Empty;

                AddressesXSubdistributor addressPerSubdistributor1 = new AddressesXSubdistributor();
                addressPerSubdistributor1.Address        = address1;
                addressPerSubdistributor1.Subdistributor = subddistributor;

                AddressesXSubdistributor addressPerSubdistributor2 = new AddressesXSubdistributor();
                addressPerSubdistributor2.Address        = address2;
                addressPerSubdistributor2.Subdistributor = subddistributor;

                AddressesXSubdistributor addressPerSubdistributor3 = new AddressesXSubdistributor();
                addressPerSubdistributor3.Address        = address3;
                addressPerSubdistributor3.Subdistributor = subddistributor;

                subddistributor.Addresses.Add(addressPerSubdistributor1);
                subddistributor.Addresses.Add(addressPerSubdistributor2);
                subddistributor.Addresses.Add(addressPerSubdistributor3);

                subddistributor.IdB  = Repository.AppConfigurations.IdBCounterGetNextSubdistributor();
                subddistributor.Type = model.Type;
                subddistributor.BNLegalRepresentative      = model.BNLegalRepresentative;
                subddistributor.RTV_BayerEmployeeId        = model.RTV_BayerEmployeeId;
                subddistributor.RTVCreator_BayerEmployeeId = (int)model.RTV_BayerEmployeeId;
                subddistributor.BusinessName    = model.BusinessName;
                subddistributor.CommercialNames = model.CommercialNames;
                subddistributor.WebSite         = model.WebSite;
                subddistributor.SubdistributorEmployees.Add(subdistributorEmployee);
                //subddistributor.DistributorUsers.Add(distributorEmployeeView);
                subddistributor.CropsXMunicipality = model.CropsXMunicipality;

                Repository.Subdistributors.Add(subddistributor);

                Repository.Complete();
                ResultManager.IsCorrect = true;
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, "exception while creating subddistributor", ex);
                return(false);
            }

            if (SendUserInvitationEmail(subdistributorEmployee.User))
            {
                ResultManager.Add("El subdistribuidor se ha creado correctamente", "");
            }
            else
            {
                ResultManager.Add("El subdistribuidor se ha creado correctamente, sin embargo hubo un problema al enviar la invitación de correo", "Puede reenviar la invitación desde la página de detalle de usuario");
            }
            return(ResultManager.IsCorrect);
        }
        public bool DeleteSubdistributor(int subdistributorId)
        {
            ResultManager.IsCorrect = false;

            // validate bayer contract associated
            bool hasBayerContract = Repository.ContractsSubdistributor.GetAll().Any(x => x.SubdistributorId == subdistributorId);

            if (hasBayerContract)
            {
                ResultManager.Add(ErrorDefault, Trace + "DeleteSubdistributor.### El Subdistribuidor seleccionado no se puede eliminar ya que existe un contracto con Bayer existente.");
                return(false);
            }

            // now proceed with the delete operation
            try
            {
                #region Subdistributor Contact Delete

                IEnumerable <int> subdistributorContactIds = Repository.SubdistributorContacts.GetAll().Where(x => x.SubdistributorId == subdistributorId).Select(y => y.Id);
                foreach (int contactId in subdistributorContactIds)
                {
                    Repository.SubdistributorContacts.Remove(contactId);
                }

                #endregion

                #region Subdistributor Crops x Municipality Delete

                IEnumerable <int> subdistributorCropsxMunicipalityIds = Repository.SubdistributorCropsXMunicipality.GetAll().Where(x => x.SubdistributorId == subdistributorId).Select(y => y.Id);
                foreach (int cropxMunicipalityId in subdistributorCropsxMunicipalityIds)
                {
                    Repository.SubdistributorCropsXMunicipality.Remove(cropxMunicipalityId);
                }

                #endregion

                #region Subdistributor Comercial Names Delete

                IEnumerable <int> subdistributorComercialNameIds = Repository.SubdistributorCommercialNames.GetAll().Where(x => x.SubdistributorId == subdistributorId).Select(y => y.Id);
                foreach (int comercialNameId in subdistributorComercialNameIds)
                {
                    Repository.SubdistributorCommercialNames.Remove(comercialNameId);
                }

                #endregion

                #region Distributor entity delete

                // rmeove address directly associated to distributor
                IEnumerable <AddressesXSubdistributor> adressesXSubdistributorList = Repository.AddressesXSubdistributor.GetAll().Where(x => x.SubdistributorId == subdistributorId);

                // address associated via AddressXSubdistributor entity delete
                IEnumerable <int> addressIds = adressesXSubdistributorList.Select(x => x.AddressId);
                foreach (int addressId in addressIds)
                {
                    Repository.Addresses.Remove(addressId);
                }

                IEnumerable <int> addressSubdistibutorIds = adressesXSubdistributorList.Select(x => x.Id);
                foreach (int addressSubdistributorId in addressSubdistibutorIds)
                {
                    Repository.AddressesXSubdistributor.Remove(addressSubdistributorId);
                }
                // address BN associated detete
                Subdistributor item = Repository.Subdistributors.Get(subdistributorId);
                Repository.Addresses.Remove(item.BNAddressId);

                // remove distributor entity itself
                Repository.Subdistributors.Remove(subdistributorId);

                // remove data from Person_DistributorEmployee entity
                IEnumerable <int> personIds = Repository.SubdistributorEmployees.GetAll().Where(x => x.SubdistributorId == subdistributorId).Select(y => y.Id);
                foreach (int personId in personIds)
                {
                    // delete from DistributorEmployees
                    Repository.SubdistributorEmployees.Remove(personId);
                    // delete from Person
                    Repository.Persons.Remove(personId);
                    // delete from User
                    Repository.Users.Remove(personId);
                    // delete from RolesXUser
                    Repository.RolesXUser.Remove(personId);
                }

                #endregion

                Repository.Complete();
                ResultManager.IsCorrect = true;
            }
            catch (Exception ex)
            {
                ErrorManager.Add(Trace + "", ErrorDefault, "Exception while deleting subdistributor", ex);
                ResultManager.IsCorrect = false;
            }

            return(ResultManager.IsCorrect);
        }
        public bool UpdateSubdistributor(Subdistributor model)
        {
            ResultManager.Clear();

            //sys validations
            if (model == null)
            {
                ResultManager.Add(ErrorDefault, Trace + "UpdateSubdistributor.111 No se recibió el modelo");
                return(false);
            }
            if (model.Id < 1)
            {
                ResultManager.Add(ErrorDefault, Trace + "UpdateSubdistributor.311 El modelo recibido no contiene el id a actualizar");
                return(false);
            }
            if (model.BNAddress == null)
            {
                ResultManager.Add(ErrorDefault, Trace + "UpdateSubdistributor.211 El modelo recibido no contiene el campo BNAddress");
                return(false);
            }

            //business validations
            if (string.IsNullOrWhiteSpace(model.SubdistributorEmployees.FirstOrDefault().EMail))
            {
                ResultManager.Add("El correo electrónico del dueño no puede estar vacio", Trace + "UpdateSubdistributor.211 El campo 'SubdistributorEmployees[0].EMail' esta vacio");
                return(false);
            }
            if (model.BNAddress.AddressColonyId <= 0)
            {
                ResultManager.Add("Se debe seleccionar la dirección del representante legal", Trace + "UpdateSubdistributor.211 El campo 'BNAddress.AddressColonyId' esta vacio");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.BNAddress.Street))
            {
                ResultManager.Add("Se debe seleccionar la calle, en la dirección del representante legal", Trace + "UpdateSubdistributor.211 El campo 'BNAddress.Street' esta vacio");
                return(false);
            }
            if (model.RTV_BayerEmployeeId <= 0)
            {
                ResultManager.Add("Se debe tener asignado un RTV", Trace + "UpdateSubdistributor.211 El campo 'RTV_BayerEmployeeId' esta vacio");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.Type))
            {
                ResultManager.Add("Se debe seleccionar el tipo Subdistribuidor ó Agricultor", Trace + "UpdateSubdistributor.211 El campo 'Type' esta vacio");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.BusinessName))
            {
                ResultManager.Add("Se debe indicar la razón social", Trace + "UpdateSubdistributor.211 El campo 'BusinessName' esta vacio");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.BNLegalRepresentative))
            {
                ResultManager.Add("Se debe indicar el nombre del representante legal", Trace + "UpdateSubdistributor.211 El campo 'BNLegalRepresentative' esta vacio");
                return(false);
            }
            if (model.CommercialNames.Count <= 0)
            {
                ResultManager.Add("Se debe indicar al menos un nombre comercial", Trace + "UpdateSubdistributor.211 El campo 'CommercialNames' esta vacio");
                return(false);
            }
            string emailToCheck           = model.SubdistributorEmployees.Count > 0 ? model.SubdistributorEmployees.FirstOrDefault().EMail : string.Empty;
            int    subdistributorPersonId = model.SubdistributorEmployees.Count > 0 ? model.SubdistributorEmployees.FirstOrDefault().Id : 0;

            if (IsMailAddressCurrentlyUsed(emailToCheck, subdistributorPersonId))
            {
                ResultManager.Add(ErrorDefault, Trace + "La direccion de email '" + emailToCheck + "' actualmente esta asignada a otro usuario, por favor ingresa una diferente.");
                return(false);
            }

            Subdistributor auxSubdistributor   = null;
            int            auxSubdistributorId = -1;
            bool           auxFoundItem        = false;

            try
            {
                //retrieve subdistributor from db
                auxSubdistributor = Repository.Subdistributors.Get(model.Id);

                //sys validations (continue)
                //-subdistributor id exists in db
                if (auxSubdistributor == null)
                {
                    ResultManager.Add(ErrorDefault, Trace + "UpdateSubdistributor.311 No se encontró un subdistribuidor con id '" + model.Id + "' en la base de datos");
                }
                //business validations
                //TODO: business validations (empty fields, etc.)

                //update subdistributor details
                //auxSubdistributor.IdB = model.IdB;
                auxSubdistributor.Type = model.Type;
                auxSubdistributor.BNLegalRepresentative = model.BNLegalRepresentative;
                auxSubdistributor.RTV_BayerEmployeeId   = model.RTV_BayerEmployeeId;
                auxSubdistributor.BusinessName          = model.BusinessName;
                auxSubdistributor.WebSite = model.WebSite;

                //update commercial names
                if (auxSubdistributor.CommercialNames.Count == model.CommercialNames.Count)
                {//same number of commercial names
                    //update names
                    List <SubdistributorCommercialName> auxNewCommercialNames = model.CommercialNames.ToList();
                    int counter = 0;
                    foreach (SubdistributorCommercialName item in auxSubdistributor.CommercialNames)
                    {
                        item.Name = auxNewCommercialNames[counter++].Name;
                    }
                }
                else
                {//different number of commercial names
                    //remove old commercial names
                    while (auxSubdistributor.CommercialNames.Count > 0)
                    {
                        Repository.SubdistributorCommercialNames.Remove(auxSubdistributor.CommercialNames.FirstOrDefault());
                    }
                    //assign current list
                    auxSubdistributor.CommercialNames = model.CommercialNames;
                }


                //update cropsxmunicipality
                if (model.CropsXMunicipality.Count == 0)
                {
                    auxSubdistributor.CropsXMunicipality.Clear();
                }
                else
                {
                    //add new items
                    foreach (SubdistributorCropsXMunicipality itemNow in model.CropsXMunicipality)
                    {
                        if (itemNow.Id > 0)
                        {//preexistent item, do nothing
                        }
                        else
                        {//new item, add
                            auxSubdistributor.CropsXMunicipality.Add(new SubdistributorCropsXMunicipality()
                            {
                                AddressMunicipalityAddressStateId = itemNow.AddressMunicipalityAddressStateId,
                                AddressMunicipalityId             = itemNow.AddressMunicipalityId,
                                Cat_CropId       = itemNow.Cat_CropId,
                                SubdistributorId = model.Id
                            });
                        }
                    }

                    //delete removed items
                    List <SubdistributorCropsXMunicipality> auxCropsXMunicipalityToRemove = new List <SubdistributorCropsXMunicipality>();
                    foreach (SubdistributorCropsXMunicipality itemOld in auxSubdistributor.CropsXMunicipality)
                    {
                        foreach (SubdistributorCropsXMunicipality itemNow in model.CropsXMunicipality)
                        {
                            if (itemNow.Id == itemOld.Id)
                            {
                                auxFoundItem = true;
                                break;
                            }
                        }
                        if (!auxFoundItem)
                        {
                            auxCropsXMunicipalityToRemove.Add(itemOld);
                        }
                    }
                    foreach (SubdistributorCropsXMunicipality item in auxCropsXMunicipalityToRemove)
                    {
                        auxSubdistributor.CropsXMunicipality.Remove(item);
                    }
                }

                //-BNAddress
                AddressColony auxColony = Repository.AddressColonies.Get((int)model.BNAddress.AddressColonyId);
                auxSubdistributor.BNAddress.AddressStateId        = auxColony.AddressStateId;
                auxSubdistributor.BNAddress.AddressMunicipalityId = auxColony.AddressMunicipalityId;
                auxSubdistributor.BNAddress.AddressPostalCodeId   = auxColony.AddressPostalCodeId;
                auxSubdistributor.BNAddress.AddressColonyId       = auxColony.Id;
                auxSubdistributor.BNAddress.Street    = model.BNAddress.Street;
                auxSubdistributor.BNAddress.NumberExt = model.BNAddress.NumberExt;
                auxSubdistributor.BNAddress.NumberInt = model.BNAddress.NumberInt;

                // Update Addresses related via AddressesXSubdistributor entity
                foreach (AddressesXSubdistributor address in model.Addresses)
                {
                    Address relatedAddress = Repository.Addresses.Get(address.Address.Id);
                    relatedAddress.AddressColonyId       = address.Address.AddressColonyId;
                    relatedAddress.AddressMunicipalityId = address.Address.AddressMunicipalityId;
                    relatedAddress.AddressPostalCodeId   = address.Address.AddressPostalCodeId;
                    relatedAddress.AddressStateId        = address.Address.AddressStateId;
                    relatedAddress.NumberExt             = address.Address.NumberExt ?? string.Empty;
                    relatedAddress.NumberInt             = address.Address.NumberInt ?? string.Empty;
                    relatedAddress.Street = address.Address.Street ?? string.Empty;
                }

                //TODO: update employees
                //Model.SubdistributorEmployee subdistributorEmployee = null;


                //update subdistributor users info
                SubdistributorEmployee auxSubdistributorEmployeeOwner = auxSubdistributor.SubdistributorEmployees.FirstOrDefault();
                if (auxSubdistributorEmployeeOwner.EMail != model.SubdistributorEmployees.FirstOrDefault().EMail)
                {
                    auxSubdistributorEmployeeOwner.EMail         = model.SubdistributorEmployees.FirstOrDefault().EMail;
                    auxSubdistributorEmployeeOwner.User.NickName = auxSubdistributorEmployeeOwner.EMail;
                    auxSubdistributorId = auxSubdistributorEmployeeOwner.Id;
                }
                model = null;
                Repository.Complete();
                ResultManager.IsCorrect = true;
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, "exception while creating subddistributor", ex);
                return(false);
            }

            if (true)//TODO:send email to subdistributor about update (it could be the user email changed, what to do then, send another token?) SendNotificationUpdatedEmail(auxSubdistributorId))
            {
                ResultManager.Add("El subdistribuidor se ha actualizado correctamente", "");
            }
            else
            {
                ResultManager.Add("El subdistribuidor se ha actualizado correctamente, sin embargo hubo un problema al enviar la notificación de correo");
            }
            return(ResultManager.IsCorrect);
        }
Ejemplo n.º 7
0
        public bool Login(string nickName, string password)
        {
            //business validations
            //-has nickname
            if (string.IsNullOrWhiteSpace(nickName))
            {
                ResultManager.Add("Credenciales inválidas, no se indicó el correo del usuario", Trace + "Login.111 No nickname was provided. ");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                ResultManager.Add("Credenciales inválidas, no se indicó la contraseña", Trace + "Login.121 No password was provided (empty passwords are not allowed on any case)");
                return(false);
            }

            nickName = nickName.Trim();
            password = password.Trim();


            PSD.Model.User userLogin = null;
            IEnumerable <PSD.Model.RolesXUser> userRoles;

            try
            {
                userLogin = Repository.Users.GetByNickName(nickName);
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, Trace + "Login.311 Error while trying to retrieve user '" + nickName + "' from database. ", ex);
                return(false);
            }

            if (userLogin == null)
            {
                ResultManager.Add("Credenciales inválidas", Trace + "Login.411 User with nickname '" + nickName + "'not found in DB");
                return(false);
            }

            //validate user able to perform login
            switch (userLogin.Cat_UserStatus.IdB)
            {
            case "active":
            case "toconfirm":
            case "tocomplete":
                break;

            case "disabled":
                ResultManager.Add("Credenciales inválidas, el usuario '" + nickName + "' esta deshabilitado. Contacte a su administrador para rehabilitarlo", Trace + "Login.511 user '" + nickName + "' was disabled");
                return(false);

            case "deleted":
                ResultManager.Add("Credenciales inválidas, usuario no encontrado.", Trace + "Login.511 user '" + nickName + "' was deleted");
                return(false);

            default:     //unknown status
                ResultManager.Add(ErrorDefault, Trace + "Login.531 User nickname '" + nickName + "' is on an unknown status '" + userLogin.Cat_UserStatus.IdB + "'");
                return(false);
            }
            if (userLogin.FailedLoginAttempts >= 5)
            {
                try
                {
                    userLogin.Cat_UserStatusId = Repository.UserStatuses.Get(3).Id;//disabled ///TODO: change to dynamic status id set by IdB
                }
                catch (Exception ex)
                {
                    ResultManager.Add("El usuario esta inhabilitado", Trace + "Login.551 Exception while trying to inactivate user (due max failed login attempts reached)", ex);
                    return(false);
                }
                ResultManager.Add("Credenciales inválidas. Por seguridad, el usuario ha sido deshabilitado. Contacte a su administrador para rehabilitarlo", Trace + "Login.631 User has been disabled");
                return(false);
            }

            //validate user password
            bool resultPasswordValid = false;

            if (string.IsNullOrWhiteSpace(userLogin.Salt) || string.IsNullOrWhiteSpace(userLogin.Hash))
            {
                ResultManager.Add("El usuario no tiene un login asociado", Trace + "Login.561 User nickname '" + nickName + "' has not yet defined a login password (hash/salt)");
                return(false);
            }
            else
            {
                try
                {
                    if (Identity.ValidatePassword(password, userLogin.Salt, userLogin.Hash))
                    {
                        resultPasswordValid = true;
                    }
                }
                catch (Exception ex)
                {
                    ResultManager.Add(ErrorDefault, Trace + "Login.571 Exception while trying to validate password for user nickname '" + nickName + "'", ex);
                    return(false);
                }
            }
            if (!resultPasswordValid)
            {
                ResultManager.Add("Credenciales inválidas", Trace + "581. Invalid password for user with nickname '" + nickName + "'");

                //increase fail login attempts counter
                try
                {
                    userLogin.FailedLoginAttempts++;
                }
                catch (Exception ex)
                {
                    ResultManager.Add(ErrorDefault, Trace + "Login.611 Exception while trying to inactivate user due max failed login attempts reached", ex);
                    return(false);
                }

                //verify if max login attempts reached so it needs to be disabled
                if (userLogin.FailedLoginAttempts >= 5)
                {
                    try
                    {
                        userLogin.Cat_UserStatusId = Repository.UserStatuses.Get(3).Id;//disabled ///TODO: change to dynamic status id set by IdB
                        ResultManager.Add("El usuario ha sido deshabilitado debido a que ha alcanzado el número máximo de intentos de logueo fallidos permitido, contacte a su administrador para reactivar su usuario", Trace + "Login.631 User is disabled so can't login");
                    }
                    catch (Exception ex)
                    {
                        ResultManager.Add(ErrorDefault, Trace + "Login.651 Exception while trying to inactivate user due max failed login attempts reached", ex);
                        return(false);
                    }
                }
                Repository.Complete();
                return(false);
            }

            //at this point credentials are valid, perform login

            // validate password expiracy, false or true either way we need to login
            HasPasswordExpired = userLogin.LastPasswordChangeDate.HasValue
                                ? (DateTime.Today - userLogin.LastPasswordChangeDate.Value).Days > Configurations.PasswordExpireDays
                                : true;

            //-update db info about login
            try
            {
                userLogin.FailedLoginAttempts = 0;
                userLogin.LastLoginDate       = Common.Dates.Today;
                //Repository.Complete();
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, Trace + "Login.711 Error while trying to update user info about login on DB", ex);
                return(false);
            }

            //-create user session object (recover db user details)
            try
            {
                userRoles = userLogin.RolesXUser;//repository.RolesXUser.GetUserRoles(userLogin.Id);
                if (userRoles == null)
                {
                    throw new Exception("Error while trying to get user roles, userId '" + userLogin.Id + "'");
                }

                string[] userRolesArray    = new string[userRoles.Count()];
                string[] userRoleIdBsArray = new string[userRoles.Count()];
                int      i = 0;
                foreach (PSD.Model.RolesXUser item in userRoles)
                {
                    userRolesArray[i]      = item.Cat_UserRole.IdB;
                    userRoleIdBsArray[i++] = item.Cat_UserRole.Name;
                }

                string employeeId = "";
                string userType   = "";
                string parentId   = "";
                switch (userRolesArray[0])
                {
                case "sysadmin":
                case "appadmin":
                case "employee-manager_operation":
                case "employee-manager_view":
                case "employee-rtv_operation":
                case "employee-rtv_view":
                    employeeId = Repository.BayerEmployees.Get(userLogin.Person.Id).IdB; break;

                case "customer-distributor_operation":
                case "customer-distributor_view":
                    Distributor auxDistributor = Repository.DistributorEmployees.Get(userLogin.Person.Id).Distributor;
                    employeeId = auxDistributor.IdB;
                    parentId   = auxDistributor.Id.ToString();
                    break;

                case "customer-subdistributor_operation":
                case "customer-subdistributor_view":
                    Subdistributor auxSubdistributor = Repository.SubdistributorEmployees.Get(userLogin.Person.Id).Subdistributor;
                    employeeId = auxSubdistributor.IdB;
                    userType   = auxSubdistributor.Type;
                    parentId   = auxSubdistributor.Id.ToString();
                    break;

                default: employeeId = ""; break;
                }

                Security.Entity.User auxUser = new Security.Entity.User(
                    userLogin.Id.ToString()
                    , employeeId
                    , userLogin.NickName
                    , userLogin.Person.Name + " " + userLogin.Person.LastNameF ///TODO:implement displayname on partial model class
                    , userLogin.Person.EMail
                    , userRolesArray
                    , userRoleIdBsArray
                    , userLogin.Cat_UserStatus.IdB
                    , userLogin.Cat_UserStatus.Name
                    , userType
                    , parentId
                    );

                if (!Identity.InitSession(auxUser))
                {
                    throw new Exception("Error while performing 'InitSession' for user.");
                }

                Repository.Complete();
                ResultManager.IsCorrect = true;
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, Trace + "Login.811 Error while creating user session object", ex);
                return(false);
            }

            if (!ResultManager.IsCorrect)
            {
                return(false);
            }

            return(ResultManager.IsCorrect);
        }
Ejemplo n.º 8
0
        public ActionResult Create(Subdistributor model, string selectedType = "", string selectedCommercialNames = "", string postAction = "", int selectedAddressState = -1, List <int> selectedMunicipalities = null, List <int> selectedCrops = null)
        {
            if (model == null)
            {
                return(RedirectToError(messageDebug: controllerTraceId + "DistributorCreate[Post].111 No model was received"));
            }

            if (TempData["CropsXMunicipality"] != null)
            {
                //copy the info from TempData into an aux object (cause we cannot use the same object from TempData, it would cause to have two UnitOfWork objects (one from the TempDate and one from the controller object), causing an error on the controller ('An entity object cannot be referenced by multiple instances of IEntityChangeTracker')
                ICollection <SubdistributorCropsXMunicipality> auxCropsXMunicipality = (ICollection <SubdistributorCropsXMunicipality>)TempData["CropsXMunicipality"];
                foreach (SubdistributorCropsXMunicipality item in auxCropsXMunicipality)
                {
                    model.CropsXMunicipality.Add(new SubdistributorCropsXMunicipality()
                    {
                        AddressMunicipalityAddressStateId = item.AddressMunicipalityAddressStateId,
                        AddressMunicipalityId             = item.AddressMunicipalityId,
                        Cat_CropId = item.Cat_CropId,
                        //Crop = item.Crop,
                        //Municipality = item.Municipality
                    });
                }
                auxCropsXMunicipality = null;

                TempData["CropsXMunicipality"] = model.CropsXMunicipality;
            }

            List <AddressMunicipality> auxMunicipalities;

            PSD.Controller.DistributorController distributorController = null;
            switch (postAction)
            {
            case "getMunicipalities":     //get municipalities for the selected addressState
                distributorController = new PSD.Controller.DistributorController(Configurations);
                auxMunicipalities     = distributorController.GetMunicipalitiesByState(selectedAddressState);
                //ViewBag.SelectedPostalCode = auxPostalCode;
                ViewBag.AvailableMunicipalities = auxMunicipalities;
                ViewBag.AddressStates           = AddressStates(selectedAddressState);
                return(View(model));

            case "addInfluence":     //add "area de influencia" to the list
                distributorController = new PSD.Controller.DistributorController(Configurations);
                auxMunicipalities     = distributorController.GetMunicipalitiesByState(selectedAddressState);
                foreach (int itemMunicipalityId in selectedMunicipalities)
                {
                    foreach (int itemCropId in selectedCrops)
                    {
                        AddressMunicipality municipalityName = new AddressMunicipality();
                        foreach (AddressMunicipality aMName in auxMunicipalities)
                        {
                            if (aMName.Id == itemMunicipalityId)
                            {
                                municipalityName = aMName;
                                break;
                            }
                        }

                        model.CropsXMunicipality.Add(new SubdistributorCropsXMunicipality()
                        {
                            AddressMunicipalityAddressStateId = selectedAddressState
                            ,
                            Crop = distributorController.GetCropById(itemCropId)
                            ,
                            AddressMunicipalityId = itemMunicipalityId
                            ,
                            Municipality = municipalityName
                            ,
                            Cat_CropId = itemCropId
                            ,
                            SubdistributorId = model.Id
                        });
                    }
                }
                TempData["CropsXMunicipality"] = model.CropsXMunicipality;
                ViewBag.AddressStates          = AddressStates();
                return(View(model));

            case "createDistributor":
                model.Type = selectedType;

                List <Model.SubdistributorCommercialName> businesses = new List <SubdistributorCommercialName>();
                bool isFirstCommercialName = true;
                foreach (string item in selectedCommercialNames.Split('/'))
                {
                    businesses.Add(new SubdistributorCommercialName()
                    {
                        Name = item, SubdistributorId = model.Id, IsMain = isFirstCommercialName
                    });
                    isFirstCommercialName = false;
                }
                model.CommercialNames = businesses;


                if (controller.CreateSubdistributor(model) && controller.ResultManager.IsCorrect)
                {
                    NotifyUser(resultManager: controller.ResultManager);
                    return(RedirectToAction("Index"));
                }
                else
                {
                    NotifyUser(resultManager: controller.ResultManager);
                }
                break;

            default:
                break;
            }
            ViewBag.AddressStates = AddressStates();
            return(View(model));
        }
Ejemplo n.º 9
0
 public ActionResult Create()
 {
     ViewBag.AddressStates          = AddressStates();
     TempData["CropsXMunicipality"] = null;
     return(View(Subdistributor.NewEmpty()));
 }
Ejemplo n.º 10
0
        public bool Create(ContractSubdistributor model, bool sendToDistributorReview = true)
        {
            ResultManager.IsCorrect = false;
            //initial validations
            //-sys validations
            if (model == null)
            {
                ResultManager.Add(ErrorDefault, Trace + "Create.111 No se recibio el modelo");
                return(false);
            }
            //-business validations
            if (model.SubdistributorId == 0 || model.SubdistributorId == -1)
            {
                ResultManager.Add("Se debe seleccionar un subdistribuidor");
                return(false);
            }
            if (model.DistributorPurchases == null || model.DistributorPurchases.Count == 0)
            {
                ResultManager.Add("Se debe seleccionar al menos un distribuidor");
                return(false);
            }

            /*
             * if (model.GRVBayerEmployeeId == 0 || model.GRVBayerEmployeeId == -1)
             * {
             *  ResultManager.Add("Se debe tener asignado un GRV");
             *  return false;
             * }
             * if (model.RTVBayerEmployeeId == 0 || model.RTVBayerEmployeeId == -1)
             * {
             *  ResultManager.Add("Se debe tener asignado un RTV");
             *  return false;
             * }
             */
            if (model.Year == 0 || model.Year == -1)
            {
                ResultManager.Add("Se debe indicar el año del convenio");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(model.RegisteredZoneName))
            {
                ResultManager.Add("Debe haber una zona asignada");
                return(false);
            }
            if (model.AmountGoalS1Pre == 0 || model.AmountGoalS1Pre == -1)
            {
                ResultManager.Add("El monto S1 no puede estar vacio");
                return(false);
            }
            if (model.AmountGoalS2Pre == 0 || model.AmountGoalS2Pre == -1)
            {
                ResultManager.Add("El monto S2 no puede estar vacio");
                return(false);
            }
            if (model.AmountGoalTotalPre == 0 || model.AmountGoalTotalPre == -1)
            {
                ResultManager.Add("El total de monto meta no puede estar vacio");
                return(false);
            }
            if (model.Subdistributor.Type == "Subdistribuidor" && model.AmountGoalTotalPre < 75000)
            {
                ResultManager.Add("El total de monto meta no puede ser menor a $75,000 MXN para un subdistribuidor");
                return(false);
            }
            if (model.Subdistributor.Type == "Agricultor" && model.AmountGoalTotalPre < 50000)
            {
                ResultManager.Add("El total de monto meta no puede ser menor a $50,000 MXN para un agricultor");
                return(false);
            }

            //insert new item
            try
            {
                ContractSubdistributor newContract = new ContractSubdistributor();

                newContract.IdB = Repository.AppConfigurations.IdBCounterGetNextContractSubdistributor();
                newContract.SubdistributorId     = model.SubdistributorId;
                newContract.GRVBayerEmployeeId   = CurrentUser.Id; //model.GRVBayerEmployeeId;
                newContract.RTVBayerEmployeeId   = CurrentUser.Id; //model.RTVBayerEmployeeId;
                newContract.RegisteredRegionName = model.RegisteredRegionName;
                newContract.RegisteredZoneName   = model.RegisteredZoneName;
                newContract.Year               = model.Year;
                newContract.AmountGoalS1       = newContract.AmountGoalS1Pre = model.AmountGoalS1Pre;
                newContract.AmountGoalS2       = newContract.AmountGoalS2Pre = model.AmountGoalS2Pre;
                newContract.AmountGoalTotalPre = newContract.AmountGoalTotal = model.AmountGoalTotalPre;

                foreach (DistributorPurchasesXContractSubdistributor item in model.DistributorPurchases)
                {
                    newContract.DistributorPurchases.Add(
                        new DistributorPurchasesXContractSubdistributor()
                    {
                        ContractSubdistributorId = newContract.Id,
                        DistributorId            = item.DistributorId
                    }
                        );
                }

                //set initial contract status
                if (sendToDistributorReview)
                {
                    newContract.ContractSubdistributorStatusId = 4;//4:revision subdistribuidor
                }
                else
                {
                    newContract.ContractSubdistributorStatusId = 3;//3:revision bayer
                }

                //update current contract at subdistributor
                Subdistributor auxSubdistributor = Repository.Subdistributors.Get(newContract.SubdistributorId);
                if (auxSubdistributor == null)
                {
                    throw new Exception("No se encontro el subdistribuidor con id '" + newContract.SubdistributorId + "' para actualizar el convenio actual");
                }
                auxSubdistributor.CurrentContract = newContract;

                //create discount coupon entry
                SubdistributorDiscountCoupon newDiscountCoupon = new SubdistributorDiscountCoupon();
                newDiscountCoupon.HasCoupon                          =
                    newDiscountCoupon.HasCouponS1                    =
                        newDiscountCoupon.HasCouponS2                =
                            newDiscountCoupon.IsCalculated           =
                                newDiscountCoupon.IsCalculatedS1     =
                                    newDiscountCoupon.IsCalculatedS2 =
                                        false;
                newContract.SubdistributorDiscountCoupon = newDiscountCoupon;

                //create promotion coupon entry
                SubdistributorPromotionCoupon newPromotionCoupon = new SubdistributorPromotionCoupon();
                newPromotionCoupon.HasCoupon                          =
                    newPromotionCoupon.HasCouponS1                    =
                        newPromotionCoupon.HasCouponS2                =
                            newPromotionCoupon.IsCalculated           =
                                newPromotionCoupon.IsCalculatedS1     =
                                    newPromotionCoupon.IsCalculatedS2 =
                                        false;
                newContract.SubdistributorPromotionCoupon = newPromotionCoupon;

                //set default values
                newContract.ContractDate     = Common.Dates.Today;
                newContract.ContractFilePath = string.Empty;

                Repository.ContractsSubdistributor.Add(newContract);
                Repository.Complete();
                ResultManager.IsCorrect = true;
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, Trace + "Create.511 Excepción al crear el nuevo elemento" + ex.Message);
            }

            if (ResultManager.IsCorrect)
            {
                ResultManager.Add("El convenio ha sido creado", "");
                try
                {
                    //send email to subdistributor
                    SubdistributorEmployee auxSubdistributorEmployee = Repository.Subdistributors.Get(model.SubdistributorId).SubdistributorEmployees.FirstOrDefault();
                    if (SendEmailToSubdistributorContractCreated(auxSubdistributorEmployee.NameDisplay, auxSubdistributorEmployee.EMail, auxSubdistributorEmployee.Subdistributor.CurrentContract.Id, auxSubdistributorEmployee.Subdistributor.CurrentContract.IdB))
                    {
                        ResultManager.Add("Se ha enviado una notificación por correo electrónico al subdistribuidor", "");
                    }
                    else
                    {
                        ResultManager.Add("No se pudo notificar por correo electrónico al subdistribuidor");
                    }
                }
                catch (Exception ex)
                {
                    ResultManager.Add(ErrorDefault, Trace + "Create.511 Excepción al crear el convenio: " + ex.Message);
                }
            }

            return(ResultManager.IsCorrect);
        }