示例#1
0
        public ActionResult EditSubdistributorEmployee()
        {
            ViewBag.AddressStates = AddressStates();
            SubdistributorEmployee employee = controller.GetSubdistributorEmployee(CurrentUser.Id);

            if (employee.Subdistributor.CropsXMunicipality != null)
            {
                TempData["CropsXMunicipality"] = employee.Subdistributor.CropsXMunicipality;
            }
            return(View(employee));
        }
示例#2
0
        public ActionResult EditSubdistributorEmployee(SubdistributorEmployee model)
        {
            if (model == null)
            {
                NotifyUser(messageError: errorDefault, messageDebug: controllerTraceId + "Edit.511 User object was not received");
                return(RedirectToError());
            }

            if (controller.UpdateSubdistributorEmployee(model) && controller.ResultManager.IsCorrect)
            {
                NotifyUser(messageOk: "Perfil actualizado");
                return(RedirectToAction("Index"));
            }

            NotifyUser(resultManager: controller.ResultManager);
            return(RedirectToHome());
        }
        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 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);
        }
示例#5
0
        /// <summary>
        /// Retrieve DistributorId data
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int GetSubdistributorId(int userId)
        {
            SubdistributorEmployee employeeData = Repository.SubdistributorEmployees.Get(userId);

            return(employeeData.SubdistributorId);
        }
示例#6
0
        public bool UpdateSubdistributorEmployee(SubdistributorEmployee model)
        {
            ResultManager.Clear();

            //sys validations
            if (model == null)
            {
                ResultManager.Add(ErrorDefault, Trace + "UpdateSubdistributorEmployee.111 No se recibió el modelo");
                return(false);
            }
            if (model.Id == 0 || model.Id == -1)
            {
                ResultManager.Add(ErrorDefault, Trace + "UpdateSubdistributorEmployee.121 El modelo recibido no contiene el id a actualizar");
                return(false);
            }
            if (model.Subdistributor.BNAddress == null)
            {
                ResultManager.Add(ErrorDefault, Trace + "UpdateSubdistributorEmployee.211 El modelo recibido no contiene el campo BNAddress");
                return(false);
            }
            //business validation
            if (string.IsNullOrWhiteSpace(model.EMail))
            {
                ResultManager.Add("El correo electrónico no puede estar vacio", Trace + "UpdateSubdistributorEmployee.211 El campo EMail esta vacio");
                return(false);
            }
            if (model.Subdistributor.BNAddress.AddressColonyId <= 0)
            {
                ResultManager.Add("Se debe seleccionar la dirección del representante legal", Trace + "UpdateSubdistributorEmployee.211 El campo BNAddress esta vacio");
                return(false);
            }
            if (IsMailAddressCurrentlyUsed(model.EMail, CurrentUser.Id))
            {
                ResultManager.Add(ErrorDefault, Trace + "La direccion de email '" + model.EMail + "' actualmente esta asignada a otro usuario, por favor ingresa una diferente.");
                return(false);
            }

            SubdistributorEmployee auxEmployee = null;

            try
            {
                auxEmployee = Repository.SubdistributorEmployees.Get(model.Id);
                auxEmployee.User.NickName = model.EMail;
                auxEmployee.EMail         = model.EMail;
                //auxEmployee.Name = model.Name;
                //auxEmployee.LastNameF = model.LastNameF;
                //auxEmployee.LastNameM = model.LastNameM;
                //auxEmployee.PhoneNumber = model.PhoneNumber;

                //auxEmployee.Subdistributor.BusinessName = model.Subdistributor.BusinessName;
                //auxEmployee.Subdistributor.CommercialNames = model.Distributor.CommercialName;
                auxEmployee.Subdistributor.WebSite = model.Subdistributor.WebSite;

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

                //if profile was not completed, complete
                if (auxEmployee.User.Cat_UserStatusId == 5)
                {
                    auxEmployee.User.Cat_UserStatusId = 1;
                }

                Repository.Complete();
                ResultManager.IsCorrect = true;
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, Trace + "911. Excepción al actualizar la información Mi Cuenta del subdistribuidor", ex);
            }

            return(ResultManager.IsCorrect);
        }
示例#7
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);
        }
        /*
         * public bool UpdateAndApprove(ContractSubdistributor model)
         * {
         *  ResultManager.IsCorrect = false;
         *  //initial validations
         *  //-sys validations
         *  if (model == null)
         *  {
         *      ResultManager.Add(ErrorDefault, Trace + "UpdateAndApprove.111 No se recibio el modelo");
         *      return false;
         *  }
         *  //-business validations
         *
         *  //approve
         *  ContractSubdistributor auxContract = null;
         *  BayerEmployee auxRTV = new BayerEmployee();
         *  try
         *  {
         *      auxContract = Repository.ContractsSubdistributor.Get(model.Id);
         *
         *      auxContract.AmountGoalS1 = model.AmountGoalS1;
         *      auxContract.AmountGoalS2 = model.AmountGoalS2;
         *      auxContract.AmountGoalTotal = model.AmountGoalTotal;
         *
         *      auxContract.ContractSubdistributorStatusId = 3;
         *
         *      //set rtv info for email send (will be lost from auxContract after Repository.Complete())
         *      auxRTV.EMail = auxContract.RTVBayerEmployee.EMail;
         *      auxRTV.Name = auxContract.RTVBayerEmployee.NameDisplay;
         *
         *      Repository.Complete();
         *      ResultManager.IsCorrect = true;
         *  }
         *  catch (Exception ex)
         *  {
         *      ResultManager.Add(ErrorDefault, Trace + "UpdateAndApprove.511 Excepción al crear el nuevo elemento" + ex.Message);
         *  }
         *
         *  if (ResultManager.IsCorrect)
         *  {
         *      ResultManager.Add("El convenio ha sido actualizado", "");
         *
         *      if (SendEmailContractApproved(auxRTV.Name, auxRTV.EMail, auxContract.Id, auxContract.IdB))
         *      {
         *          ResultManager.Add("Se ha enviado un correo al RTV para la aprobación final", "");
         *      }
         *      else
         *      {
         *          ResultManager.Add("No se pudo enviar actualización por correo al RTV");
         *      }
         *  }
         *
         *  return ResultManager.IsCorrect;
         * }
         */

        /*
         * public bool Approve(int contractId)
         * {
         *  ResultManager.IsCorrect = false;
         *  //initial validations
         *  //-sys validations
         *  if (contractId == -1)
         *  {
         *      ResultManager.Add(ErrorDefault, Trace + "Approve.111 No se recibio el parámetro id");
         *      return false;
         *  }
         *  //-business validations
         *
         *  //approve
         *  int auxSubdistributorId = -1;
         *  ContractSubdistributor auxContract = null;
         *  try
         *  {
         *      auxContract = Repository.ContractsSubdistributor.Get(contractId);
         *      auxContract.ContractSubdistributorStatusId = 3;
         *
         *      auxSubdistributorId = auxContract.SubdistributorId;
         *
         *      Repository.Complete();
         *      ResultManager.IsCorrect = true;
         *  }
         *  catch (Exception ex)
         *  {
         *      ResultManager.Add(ErrorDefault, Trace + "Approve.511 Excepción al crear el nuevo elemento" + ex.Message);
         *  }
         *
         *  if (ResultManager.IsCorrect)
         *  {
         *      ResultManager.Add("El convenio ha sido actualizado", "");
         *      DistributorEmployee auxDistributorEmployee = Repository.Distributors.Get(auxSubdistributorId).DistributorUsers.FirstOrDefault();
         *      if (SendEmailContractApproved(auxDistributorEmployee.NameDisplay, auxDistributorEmployee.EMail, contractId, auxContract.IdB))
         *      {
         *          ResultManager.Add("Se ha enviado un correo al distribuidor", "");
         *      }
         *      else
         *      {
         *          ResultManager.Add("No se pudo enviar actualización por correo al distribuidor");
         *      }
         *  }
         *
         *  return ResultManager.IsCorrect;
         * }
         */

        public bool Approve(int id)
        {
            ResultManager.IsCorrect = false;
            //initial validations
            //-sys validations
            if (id == -1)
            {
                ResultManager.Add(ErrorDefault, Trace + "Approve.111 No se recibio el parámetro id");
                return(false);
            }
            //-business validations

            ContractSubdistributor auxContract  = null;
            string auxSubdistributorDisplayName = string.Empty;
            string auxSubdistributorEmail       = string.Empty;
            string auxRtvDisplayName            = string.Empty;
            string auxRtvEmail    = string.Empty;
            string auxContractIdB = string.Empty;

            try
            {
                //retrieve contract to update
                auxContract = Repository.ContractsSubdistributor.Get(id);

                //set new values
                auxContract.ContractSubdistributorStatusId = 1;//1:active

                //save aux informationto send emails
                SubdistributorEmployee auxSubdistributorEmployee = auxContract.Subdistributor.SubdistributorEmployees.FirstOrDefault();
                auxSubdistributorDisplayName = auxSubdistributorEmployee.NameDisplay;
                auxSubdistributorEmail       = auxSubdistributorEmployee.EMail;
                auxRtvDisplayName            = auxContract.RTVBayerEmployee.NameDisplay;
                auxRtvEmail    = auxContract.RTVBayerEmployee.EMail;
                auxContractIdB = auxContract.IdB;

                //save changes
                Repository.Complete();
                ResultManager.IsCorrect = true;
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, Trace + "Approve.311 Excepción al actualizar la información del contrato id '" + id + "'" + ex.Message);
                return(false);
            }

            if (ResultManager.IsCorrect)
            {
                ResultManager.Add("El convenio ha sido actualizado", "");
                try
                {
                    //send email to subdistributor
                    if (SendEmailToSubdistributorContractApproved(auxSubdistributorDisplayName, auxSubdistributorEmail, id, auxContract.IdB))
                    {
                        ResultManager.Add("Se ha enviado un correo al distribuidor", "");
                    }
                    else
                    {
                        ResultManager.Add("No se pudo enviar actualización por correo al distribuidor");
                    }

                    //send email to rtv
                    if (SendEmailToBayerEmployeeContractApproved(auxRtvDisplayName, auxRtvEmail, id, auxContract.IdB))
                    {
                        ResultManager.Add("Se ha enviado un correo al rtv", "");
                    }
                    else
                    {
                        ResultManager.Add("No se pudo enviar actualización por correo al rtv");
                    }
                }
                catch (Exception ex)
                {
                    ResultManager.Add("Error al enviar notificaciones de correo", Trace + "Create.711 Excepción al enviar notificación de correo del convenio: " + ex.Message);
                }
            }

            return(ResultManager.IsCorrect);
        }