public UsersListItemDto(User user) { Id = user.Id; //number = number; FullName = user.FullName; //user.LastName+" "+user.FirstName+" "+user.MiddleName; //branch = user.Branch; //department = user.Department; //position = user.Position; Login = user.Login; }
/// <summary> /// В строке показываем список руководителей для инициатора текущей заявки. /// </summary> /// <param name="curUser">Инициатор.</param> /// <param name="ManagerLevel">Урвоень руководителей, список которых нужно показать.</param> /// <returns></returns> protected string GetManagers(User curUser, int ManagerLevel) { string ManagersStr = string.Empty; if (curUser.Level > ManagerLevel) { IList<User> managers = DepartmentDao.GetDepartmentManagers(curUser.Department.Id, true) .Where<User>(x => x.Level == ManagerLevel && x.RoleId == (int)UserRole.Manager) .OrderBy(x => x.IsMainManager) .ThenBy(x => x.Name) .ToList<User>(); //список руководителей foreach (var item in managers) { ManagersStr += (string.IsNullOrEmpty(ManagersStr) ? "" : ", ") + item.Name + "(" + item.Position.Name + ")"; } } return ManagersStr; }
public Question(User user,string text) { _user = user; _date = DateTime.Now; _text = text; }
protected void SetManagerInfoModel(User user, ManagerInfoModel model,Appointment appointment, AppointmentReport appointmentReport) { if(appointmentReport != null) model.StaffName = appointmentReport.Creator.FullName; else if(appointment != null) { AppointmentReport rep = AppointmentReportDao.LoadForAppointmentId(appointment.Id).FirstOrDefault(); if(rep != null) model.StaffName = rep.Creator.FullName; } #region Заполнение списка вышестоящих руководителей IList<User> chiefs = GetChiefsForManager(user.Id) //.Where<User>(chief => chief.Level >= 4) .OrderByDescending<User, int?>(chief => chief.Level) .ToList<User>(); // + руководители по ручным привязкам IList<User> manualRoleManagers = ManualRoleRecordDao.GetManualRoleHoldersForUser(user.Id, UserManualRole.ApprovesEmployment); foreach (var manualRoleManager in manualRoleManagers) { if (!chiefs.Contains(manualRoleManager)) { chiefs.Add(manualRoleManager); } } StringBuilder chiefsBuilder = new StringBuilder(); foreach (var chief in chiefs) { chiefsBuilder.AppendFormat("{0} ({1}), ", chief.Name, chief.Position == null ? "<не указана>" : chief.Position.Name); } // Cut off trailing ", " if (chiefsBuilder.Length >= 2) { chiefsBuilder.Remove(chiefsBuilder.Length - 2, 2); } model.Chiefs = chiefsBuilder.ToString(); #endregion if(appointment!=null) model.DocumentNumber = appointment.Number.ToString(); model.Department = user.Department == null ? string.Empty : user.Department.Name; model.Organization = user.Organization != null ? user.Organization.Name : string.Empty; model.Position = user.Position != null ? user.Position.Name : string.Empty; model.UserName = user.FullName; model.ManagerId = user.Id; }
protected void SetFlagsState(int id, User current,UserRole currRole, Appointment entity, AppointmentEditModel model) { SetFlagsState(model, false); if (entity != null) { model.NonActual = entity.NonActual; var candidates = entity.Candidates!=null?entity.Candidates.Where(x => x.Status != Reports.Core.Enum.EmploymentStatus.REJECTED):null; if (candidates == null || !candidates.Any()) { model.IsNonActualButtonAvailable = true; } } model.StaffBossId = ConfigurationService.StaffBossId.HasValue?ConfigurationService.StaffBossId.Value:0; if(model.Id == 0) { if ((currRole & UserRole.Manager) != UserRole.Manager && currRole!= UserRole.StaffManager) throw new ArgumentException(string.Format(StrUserNotManager, current.Id)); model.IsEditable = true; model.IsSaveAvailable = true; model.IsManagerApproveAvailable = true; model.ApproveForAllAvailable = true; return; } model.IsManagerApproved = entity.ManagerDateAccept.HasValue; model.IsChiefApproved = entity.ChiefDateAccept.HasValue; //model.IsPersonnelApproved = entity.PersonnelDateAccept.HasValue; model.IsStaffApproved = entity.StaffDateAccept.HasValue; model.IsDeleted = entity.DeleteDate.HasValue; if (entity.AcceptManager != null && entity.ManagerDateAccept.HasValue) model.ManagerFio = entity.AcceptManager.FullName; if (entity.AcceptChief != null && entity.ChiefDateAccept.HasValue) model.ChiefFio = entity.AcceptChief.FullName; //if (entity.AcceptPersonnel != null && entity.PersonnelDateAccept.HasValue) // model.PersonnelFio = entity.AcceptPersonnel.FullName; if (entity.AcceptStaff != null && entity.StaffDateAccept.HasValue) model.StaffFio = entity.AcceptStaff.FullName; bool isApprovedReportExists = AppointmentReportDao.IsApprovedReportForAppointmentIdExists(entity.Id); if(entity.DeleteDate.HasValue) { model.DeleteUser = entity.DeleteUser.FullName; if (entity.AcceptStaff != null) model.IsStaffReceiveRejectMail = true; // todo Need flag on entity ? /*if (entity.AcceptStaff != null) model.StaffFio = entity.AcceptStaff.FullName;*/ } switch (currRole) { case UserRole.Manager: if(current.Id == entity.Creator.Id && !entity.DeleteDate.HasValue) { if(!isApprovedReportExists) model.IsManagerRejectAvailable = true; if (!entity.ManagerDateAccept.HasValue) { model.IsManagerApproveAvailable = true; model.IsEditable = true; } else { if (entity.BankAccountantAccept.HasValue) { model.IsChiefApproveAvailable = IsManagerChiefForCreator(current, entity.Creator) && entity.BankAccountantAccept.Value; } else { if (entity.Reason.Id == 3 || entity.Reason.Id == 6) model.IsChiefApproveAvailable = IsManagerChiefForCreator(current, entity.Creator); } } } else if (!entity.DeleteDate.HasValue && entity.ManagerDateAccept.HasValue && entity.Creator.Id != current.Id && IsManagerChiefForCreator(current, entity.Creator)) { if (!isApprovedReportExists) model.IsManagerRejectAvailable = true; if (!entity.ChiefDateAccept.HasValue && entity.BankAccountantAccept.HasValue && entity.IsVacationExists && entity.BankAccountantAcceptCount>0) model.IsChiefApproveAvailable = true; else if (!entity.ChiefDateAccept.HasValue) { if (entity.Reason.Id == 3 || entity.Reason.Id == 6) model.IsChiefApproveAvailable = IsManagerChiefForCreator(current, entity.Creator); } } break; case UserRole.StaffManager: if (!entity.DeleteDate.HasValue ) { if(entity.ChiefDateAccept.HasValue && !entity.StaffDateAccept.HasValue) model.IsStaffApproveAvailable = true; if (!entity.StaffDateAccept.HasValue && model.StaffCreatorId == current.Id) { model.ApproveForAllAvailable = true; if (!isApprovedReportExists) model.IsManagerRejectAvailable = true; if (!entity.ManagerDateAccept.HasValue) { model.IsEditable = true; model.IsManagerApproveAvailable = true; } } } break; case UserRole.Estimator: case UserRole.OutsourcingManager: break; case UserRole.ConsultantPersonnel: case UserRole.Security: case UserRole.PersonnelManager: break; default: throw new ArgumentException(string.Format("Недопустимая роль {0}",currRole)); } if ((entity.Creator.Id == current.Id || (entity.StaffCreator!=null && entity.StaffCreator.Id==current.Id)) && !entity.ManagerDateAccept.HasValue) { model.IsEditable = true; model.IsManagerApproveAvailable = true; } model.IsSaveAvailable = model.IsEditable || model.IsManagerApproveAvailable || ((CurrentUser.UserRole & UserRole.StaffManager)>0) || model.IsChiefApproveAvailable || model.IsStaffApproveAvailable || (currRole == UserRole.ConsultantPersonnel && (model.IsVacationExists != 1 || model.BankAccountantAccept != true || model.BankAccountantAcceptCount < int.Parse(model.VacationCount))); }
protected EmailDto SendEmailForBankAccountantReject(User user, Appointment entity) { string BankAccountantEmail = user.Email; if (string.IsNullOrEmpty(BankAccountantEmail)) throw new ValidationException("У пользователя нет почты"); string body = String.Format("Заявка №{0} от {1} на поиск кандидата не одобрена.", entity.Number, entity.CreateDate); string subject = "Заявка на поиск сотрудника не одобрена"; return SendEmail(BankAccountantEmail, subject, body); }
protected EmailDto SendEmailForAppointmentReject(User user, Appointment entity) { string to = string.Empty; if (entity.ManagerDateAccept.HasValue) { if (!string.IsNullOrEmpty(entity.AcceptManager.Email)) to += entity.AcceptManager.Email; else Log.ErrorFormat("No email for manager (id {0})",entity.AcceptManager.Id); } if (entity.ChiefDateAccept.HasValue) { if (!string.IsNullOrEmpty(entity.AcceptChief.Email)) { if (string.IsNullOrEmpty(to)) to = entity.AcceptChief.Email; else to += ";" + entity.AcceptChief.Email; } else Log.ErrorFormat("No email for chief (id {0})", entity.AcceptChief.Id); } /*if (entity.PersonnelDateAccept.HasValue) { if (!string.IsNullOrEmpty(entity.AcceptPersonnel.Email)) { if (string.IsNullOrEmpty(to)) to = entity.AcceptPersonnel.Email; else to += ";" + entity.AcceptPersonnel.Email; } else Log.ErrorFormat("No email for personnel (id {0})", entity.AcceptPersonnel.Id); }*/ if (entity.StaffDateAccept.HasValue) { if (!string.IsNullOrEmpty(entity.AcceptStaff.Email)) { if (string.IsNullOrEmpty(to)) to = entity.AcceptStaff.Email; else to += ";" + entity.AcceptStaff.Email; } else Log.ErrorFormat("No email for staff (id {0})", entity.AcceptStaff.Id); } string body; string subject = GetSubjectAndBodyForAppointmentRejectRequest(user, entity, out body); return SendEmail(to, subject, body); }
protected EmailDto SendEmailForAppointmentChiefAccept(User chief, Appointment entity) { string staffManagerEmail = ConfigurationService.AppointmentStaffManagerEmail; if (string.IsNullOrEmpty(staffManagerEmail)) throw new ValidationException(StrEmailForStaffManagerNotFound); string body; string subject = GetSubjectAndBodyForAppointmentManagerAcceptRequest(chief, entity, out body); return SendEmail(staffManagerEmail, subject, body); }
protected string GetSubjectAndBodyForManagerAcceptRequest(User user, DateTime acceptDate, out string body) { body = string.Format("Пользователь {0} подтвердил ввод заявок за неделю {1} - {2}", user.FullName, acceptDate.AddDays(-4).ToShortDateString(), acceptDate.ToShortDateString()); const string subject = "Подтверждение ввода заявок"; return subject; }
public IdNameReadonlyDto GetDepartmentDto(User user) { return (AuthenticationService.CurrentUser.UserRole & UserRole.Employee) == UserRole.Employee ? new IdNameReadonlyDto { Id = user.Department == null ? 0 : user.Department.Id, Name = user.Department == null ? string.Empty : user.Department.Name, IsReadOnly = true, } : new IdNameReadonlyDto { Id = 0, Name = string.Empty, IsReadOnly = false, }; }
/// <summary> /// Сохраняем изменения в справочнике штатных единиц. /// </summary> /// <param name="entity">Текущая заявка.</param> /// <param name="curUser">текущий пользователь.</param> /// <param name="error">Сообщение об ошибке.</param> /// <returns></returns> protected bool SaveStaffEstablishedPostReference(StaffEstablishedPostRequest entity, User curUser, out string error) { error = string.Empty; StaffEstablishedPost sep = entity.StaffEstablishedPost != null ? StaffEstablishedPostDao.Get(entity.StaffEstablishedPost.Id) : new StaffEstablishedPost(); //если заявка на создание, создаем новую запись и делаем в заявке на нее ссылку if (entity.RequestType.Id == 1 || entity.RequestType.Id == 4) { sep.Position = entity.Position; sep.Department = entity.Department; sep.Quantity = 0;// entity.Quantity; sep.Salary = entity.Salary; sep.IsUsed = true; sep.BeginAccountDate = entity.BeginAccountDate; sep.Creator = curUser; sep.CreateDate = DateTime.Now; } //изменилось количество изменяем количество связей if (!SaveStaffEstablishedPostChangeUserLinks(entity, sep, curUser, out error)) { return false; } else sep.Quantity = entity.Quantity; //если заявка на редактирование/удаление, редактируем текущую запись в справочнике if (entity.RequestType.Id != 1 && entity.RequestType.Id != 4) { if (entity.RequestType.Id == 2) { sep.Position = entity.Position; //пока решили не менять количество в заявках наизменение //sep.Quantity = entity.Quantity; sep.Salary = entity.Salary; } else if (entity.RequestType.Id == 3 && entity.StaffEstablishedPost.EstablishedPostUserLinks.Where(x => !x.IsDismissal).Count() == 0) { sep.IsUsed = false; //делаем неактивной текущую запись в справочнике, если больше нет в расстановке несокращенных записей } sep.BeginAccountDate = entity.BeginAccountDate; sep.Editor = curUser; sep.EditDate = DateTime.Now; } //для создания/изменения в надбавках делаем ссылку на штатную единицу if (entity.RequestType.Id != 3) { if (entity.PostChargeLinks.Count != 0) { foreach (var item in entity.PostChargeLinks) { item.EstablishedPost = sep; item.Editor = curUser; item.EditDate = DateTime.Now; } } } //архивируем изменения if (sep.EstablishedPostArchive == null) sep.EstablishedPostArchive = new List<StaffEstablishedPostArchive>(); sep.EstablishedPostArchive.Add(new StaffEstablishedPostArchive { StaffEstablishedPost = sep, Position = sep.Position, Department = sep.Department, Quantity = sep.Quantity, Salary = sep.Salary, IsUsed = sep.IsUsed, BeginAccountDate = sep.BeginAccountDate, Priority = sep.Priority, Creator = curUser, CreateDate = DateTime.Now }); try { StaffEstablishedPostDao.SaveAndFlush(sep); if (entity.StaffEstablishedPost == null) entity.StaffEstablishedPost = new StaffEstablishedPost(); entity.StaffEstablishedPost = sep; entity.DateSendToApprove = !entity.DateSendToApprove.HasValue ? DateTime.Now : entity.DateSendToApprove.Value;//отправлено на согласование entity.DateAccept = DateTime.Now;//согласовано //если создается новая штатная единица и в ней нет сотрудников, то надо указать признак выгрузки в 1С, чтобы пустые заявки не попали в выгрузку кадровых перемещений. //или сокращаются пустые места в расстановке if (entity.StaffEstablishedPost.EstablishedPostUserLinks.Where(x => x.User != null).Count() == 0 && entity.StaffEstablishedPost.EstablishedPostUserLinks.Where(x => x.User != null && x.IsDismissal && x.IsUsed).Count() == 0) { entity.SendTo1C = DateTime.Now; } //если заявка на сокращение или создание if (entity.RequestType.Id == 3 || entity.RequestType.Id == 1) entity.SendTo1C = DateTime.Now; } catch (Exception ex) { StaffEstablishedPostDao.RollbackTran(); error = string.Format("Произошла ошибка при сохранении данных! Исключение:{0}", ex.GetBaseException().Message); return false; } return true; }
/// <summary> /// Меняем количество связей штатной единицы с сотрудниками. /// </summary> /// <param name="entity">Заявка</param> /// <param name="sep">Штатная единица</param> /// <param name="curUser">Текущий пользователь</param> /// <param name="error">Для сообщений</param> /// <returns></returns> protected bool SaveStaffEstablishedPostChangeUserLinks(StaffEstablishedPostRequest entity, StaffEstablishedPost sep, User curUser, out string error) { error = string.Empty; int CountLinks = sep.EstablishedPostUserLinks != null ? sep.EstablishedPostUserLinks.Count() : 0; //если количество штатных единиц увеличилось, то нужно добавить необходимое количество записей для связей if (entity.Quantity > CountLinks) { CountLinks = entity.Quantity - CountLinks; if(sep.EstablishedPostUserLinks == null) sep.EstablishedPostUserLinks = new List<StaffEstablishedPostUserLinks>(); for (int i = 0; i < CountLinks; i++) { sep.EstablishedPostUserLinks.Add(new StaffEstablishedPostUserLinks() { StaffEstablishedPost = sep, User = null, IsUsed = true, Creator = curUser, CreateDate = DateTime.Now }); } } ////редактирование временных вакансий //if ((entity.RequestType.Id == 1 || entity.RequestType.Id == 2 || entity.RequestType.Id == 4) && sep.EstablishedPostUserLinks.Where(x => !x.IsDismissal && x.IsTemporary).Count() != 0) //{ // //на случай добавления временной вакансии // CountLinks = sep.EstablishedPostUserLinks != null ? sep.EstablishedPostUserLinks.Count() : 0; // if (entity.Quantity > CountLinks) // { // CountLinks = entity.Quantity - CountLinks; // for (int i = 0; i < CountLinks; i++) // { // sep.EstablishedPostUserLinks.Add(new StaffEstablishedPostUserLinks() // { // StaffEstablishedPost = sep, // User = null, // IsUsed = true, // Creator = curUser, // CreateDate = DateTime.Now // }); // } // } // foreach (var item in sep.EstablishedPostUserLinks // .Where(x => x.IsUsed && x.IsDismissal)) // { // item.IsUsed = false; // item.Editor = curUser; // item.EditDate = DateTime.Now; // } //} //сокращение if ((entity.RequestType.Id == 3 || entity.RequestType.Id == 4) && sep.EstablishedPostUserLinks.Where(x => x.IsUsed && x.IsDismissal).Count() != 0) { //если частичное сокращение в расстановке, то меняем количество единиц в заявке if (sep.EstablishedPostUserLinks.Where(x => x.IsUsed && x.IsDismissal).Count() != 0 && sep.EstablishedPostUserLinks.Where(x => x.IsUsed && !x.IsDismissal).Count() != 0) { entity.Quantity = sep.EstablishedPostUserLinks.Where(x => x.IsUsed && !x.IsDismissal).Count(); } foreach (var item in sep.EstablishedPostUserLinks .Where(x => x.IsUsed && x.IsDismissal)) { item.IsUsed = false; item.Editor = curUser; item.EditDate = DateTime.Now; } } return true; }
/// <summary> /// Сохраняем согласования. /// </summary> /// <param name="model">Модель</param> /// <param name="entity">Текущая заявка.</param> /// <param name="curUser">текущий пользователь.</param> /// <param name="error">Сообщение об ошибке.</param> /// <returns></returns> protected int SaveStaffEstablishedPostApprovals(StaffEstablishedPostRequestModel model, StaffEstablishedPostRequest entity, User curUser, out string error) { //возвращает значения от 1 до 4 - этап согласования прошел успешно, 0 - согласование завершено, заявка утверждена, -1 - ошибка при сохранении данных //только после утверждения заявки можно редактировать справочник подразделений. error = string.Empty; //в каждой ветке определяемся с участниками групповухи под кодовым названием согласование/утверждение заявки для подразделения //текущим пользователем может быть куратор ии кадровик, которые могут действовать за согласовантов User Assistant = AuthenticationService.CurrentUser.UserRole == UserRole.Inspector || AuthenticationService.CurrentUser.UserRole == UserRole.ConsultantPersonnel || AuthenticationService.CurrentUser.UserRole == UserRole.ConsultantOutsourcing ? curUser : null;//куратор/кадровик банка/консультант РК //выбираем из согласования не архивные записи. IList<DocumentApproval> DocApproval = DocumentApprovalDao.GetDocumentApproval(entity.Id, (int)ApprovalTypeEnum.StaffEstablishedPostRequest); DocumentApproval da = new DocumentApproval(); da.ApprovalType = (int)ApprovalTypeEnum.StaffEstablishedPostRequest; da.DocId = entity.Id; da.IsArchive = false; da.CreateDate = DateTime.Now; switch (DocApproval.Count) { case 0: //если иницатор не выбран, это значит, что инициатор действует сам User Initiator = model.InitiatorId != 0 ? UserDao.Get(model.InitiatorId) : curUser;//инициатор da.ApproveUser = Initiator; da.AssistantUser = Assistant; da.Number = 1; error = "Заявка создана!"; break; case 1: da.ApproveUser = curUser; da.AssistantUser = null; da.Number = 2; error = "Заявка проверена куратором!"; break; case 2: da.ApproveUser = curUser; da.AssistantUser = null; da.Number = 3; error = "Заявка проверена кадровиком банка!"; break; case 3: //если согласовант не выбран, это значит, что он действует сам User TopManager = model.TopManagerId != 0 ? UserDao.Get(model.TopManagerId) : curUser;//высший руководитель da.ApproveUser = TopManager; da.AssistantUser = Assistant; da.Number = 4; error = "Заявка согласована!"; break; case 4: //если утверждающий не выбран, это значит, что он действует сам User BoardMember = model.BoardMemberId != 0 ? UserDao.Get(model.BoardMemberId) : curUser;//член правления da.ApproveUser = BoardMember; da.AssistantUser = Assistant; da.Number = 5; error = "Заявка утверждена!"; break; } try { DocumentApprovalDao.SaveAndFlush(da); //сохраняем здачу пайруса if (!string.IsNullOrEmpty(model.PyrusNumber)) { entity.StaffRequestPyrusTasks.Add(new StaffRequestPyrusTasks() { EPRequest = entity, DocumentApproval = da, NumberTask = model.PyrusNumber, Creator = curUser, CreateDate = DateTime.Now }); } if (da.Number == 1) { entity.DateSendToApprove = DateTime.Now; return da.Number; } if (da.Number > 1 && da.Number < 5) return da.Number; if (da.Number == 5) { //entity.BeginAccountDate = DateTime.Now; entity.DateAccept = DateTime.Now; } } catch (Exception ex) { DocumentApprovalDao.RollbackTran(); error = string.Format("Произошла ошибка при сохранении данных! Исключение:{0}", ex.GetBaseException().Message); return -1; } return 0; }
/// <summary> /// Сохраняем изменения в справочнике подразделений. /// </summary> /// <param name="entity">Текущая заявка.</param> /// <param name="curUser">текущий пользователь.</param> /// <param name="error">Сообщение об ошибке.</param> /// <returns></returns> protected bool SaveDepartmentReference(StaffDepartmentRequest entity, User curUser, out string error) { error = string.Empty; //bool IsParentChange = false; //IList<Department> ChildDeps = null; Department dep = entity.Department != null ? DepartmentDao.Get(entity.Department.Id) : new Department(); //родительское подразделение Department ParentDep = entity.ParentDepartment != null ? DepartmentDao.Get(entity.ParentDepartment.Id) : new Department(); //если заявка на создание, создаем новую запись и делаем в заявке на нее ссылку if (entity.RequestType.Id == 1 || entity.RequestType.Id == 4) { dep.Code = null; dep.Name = entity.Name; dep.Code1C = null; dep.ParentId = ParentDep.Code1C; dep.Path = ParentDep.Path + "__new"; dep.ItemLevel = (ParentDep.ItemLevel + 1) != entity.ItemLevel ? ParentDep.ItemLevel + 1 : entity.ItemLevel; dep.CodeSKD = null; dep.Priority = 99;//искусственное значение dep.IsUsed = true; dep.DepartmentAccessory = entity.DepartmentAccessory; //dep.FingradCode = "";//формируем код ниже dep.Creator = curUser; dep.CreateDate = DateTime.Now; } //если заявка на редактирование/удаление, редактируем текущую запись в справочнике if (entity.RequestType.Id != 1 && entity.RequestType.Id != 4) { if (entity.RequestType.Id == 2) { ////если меняется родитель запоминаем, чтобы у подчиненых подразделений изменить путь //if (dep.ParentId.Value != ParentDep.Code1C) //{ // IsParentChange = true; // ChildDeps = DepartmentDao.GetChildDepartments(dep);//собираем подчиненные подразделения для подразделения у которого меняется родитель //} dep.Name = entity.Name; dep.ParentId = ParentDep.Code1C; dep.Path = ParentDep.ItemLevel != entity.ItemLevel ? ParentDep.Path + "__new" : dep.Path; dep.ItemLevel = (ParentDep.ItemLevel + 1) != entity.ItemLevel ? ParentDep.ItemLevel + 1 : entity.ItemLevel; dep.IsUsed = true; } else if (entity.RequestType.Id == 3) { dep.IsUsed = false; //делаем неактивной текущую запись в справочнике } dep.Editor = curUser; dep.EditDate = DateTime.Now; } try { DepartmentDao.SaveAndFlush(dep); if (entity.Department == null) entity.Department = new Department(); //если нет кода или изменился родитель, то надо подкорректировать путь dep.Path = ParentDep.Path + (dep.Code1C.HasValue ? dep.Code1C.Value.ToString() : dep.Id.ToString()) + "."; ////меняем пути у подчиненных подразделений ////РАБОТАЕТ НА ОДНОМ УРОВНЕ, ДОРАБОТАТЬ, ЧТОБЫ ИЗМЕНЯЛИСЬ ПУТИ У ВСЕЙ ВЕТКИ //if (IsParentChange) //{ // foreach (Department item in ChildDeps) // { // item.Path = dep.Path + item.Id.ToString() + "."; // DepartmentDao.SaveAndFlush(item); // } //} //только при добавлении надо заполнить эти поля, так как в структуре на поле Code1C ссылается поле ParentId, то есть значения в поле Code1C должны быть уникальными if (entity.RequestType.Id == 1 || entity.RequestType.Id == 4) { dep.Code = dep.Id.ToString(); dep.Code1C = dep.Id; } //у текущей заявки делаем ссылку на новое подразделение и ставим признак использования entity.Department = dep; //создаем код для подразделения if (entity.RequestType.Id != 3) { if (entity.DepartmentAccessory.Id == 2 || entity.DepartmentAccessory.Id == 6) { if (!CreateCodeForDepartment(entity, dep, curUser, out error)) { error = string.IsNullOrEmpty(error) || string.IsNullOrWhiteSpace(error) ? "Произошла ошибка при формировании кода подразделения!" : error; DepartmentDao.RollbackTran(); return false; } } } //архивируем изменения DepartmentArchive da = new DepartmentArchive() { Department = dep, Code = dep.Code, Name = dep.Name, Code1C = dep.Code1C, ParentId = dep.ParentId, Path = dep.Path, ItemLevel = dep.ItemLevel, Priority = dep.Priority, IsUsed = dep.IsUsed, Creator = curUser, CreateDate = DateTime.Now }; DepartmentArchiveDao.SaveAndFlush(da); } catch (Exception ex) { DepartmentDao.RollbackTran(); DepartmentArchiveDao.RollbackTran(); error = string.Format("Произошла ошибка при сохранении данных! Исключение:{0}", ex.GetBaseException().Message); return false; } return true; }
/// <summary> /// Сохраняем согласования. /// </summary> /// <param name="model">Модель</param> /// <param name="entity">Текущая заявка.</param> /// <param name="curUser">текущий пользователь.</param> /// <param name="error">Сообщение об ошибке.</param> /// <returns></returns> protected int SaveDepartmentApprovals(StaffDepartmentRequestModel model, StaffDepartmentRequest entity, User curUser, out string error) { //возвращает значения от 1 до 4 - этап согласования прошел успешно, 0 - согласование завершено, заявка утверждена, -1 - ошибка при сохранении данных //только после утверждения заявки можно редактировать справочник подразделений. error = string.Empty; //в каждой ветке определяемся с участниками групповухи под кодовым названием согласование/утверждение заявки для подразделения //текущим пользователем может быть куратор ии кадровик, которые могут действовать за согласовантов User Assistant = AuthenticationService.CurrentUser.UserRole == UserRole.Inspector || AuthenticationService.CurrentUser.UserRole == UserRole.ConsultantPersonnel || AuthenticationService.CurrentUser.UserRole == UserRole.ConsultantOutsourcing || AuthenticationService.CurrentUser.UserRole == UserRole.TaxCollector ? curUser : null;//куратор/кадровик банка/консультант РК //список руководителей по по ветке IList<User> Initiators = DepartmentDao.GetDepartmentManagers(entity.ParentDepartment.Id, true) .OrderByDescending<User, int?>(manager => manager.Level) .ToList<User>(); bool IsInitiator = Initiators.Where(x => x.Id == AuthenticationService.CurrentUser.Id).Count() != 0 ? true : false; bool IsTopManager = Initiators.Where(x => x.Id == AuthenticationService.CurrentUser.Id && x.Level <= 3).Count() != 0 ? true : false; bool IsBoardMember = AuthenticationService.CurrentUser.UserRole == UserRole.Director; bool IsCurator = (AuthenticationService.CurrentUser.UserRole == UserRole.Inspector); bool IsPersonnelBank = (AuthenticationService.CurrentUser.UserRole == UserRole.ConsultantPersonnel); bool IsConsultant = (AuthenticationService.CurrentUser.UserRole == UserRole.ConsultantOutsourcing); bool IsTaxCollector = (AuthenticationService.CurrentUser.UserRole == UserRole.TaxCollector); bool IsStaffListOrder = (AuthenticationService.CurrentUser.UserRole == UserRole.StaffListOrder); //вышестоящее руководство model.TopManagers = Initiators.Where(x => x.Level <= 3).ToList().ConvertAll(x => new IdNameDto { Id = x.Id, Name = x.Name + " - " + x.Position.Name }); //выбираем из согласования не архивные записи. IList<DocumentApproval> DocApproval = DocumentApprovalDao.GetDocumentApproval(entity.Id, (int)ApprovalTypeEnum.StaffDepartmentRequest); DocumentApproval da = new DocumentApproval(); da.ApprovalType = (int)ApprovalTypeEnum.StaffDepartmentRequest; da.DocId = entity.Id; da.IsArchive = false; da.CreateDate = DateTime.Now; if (model.IsImportance)//обязательное согласование { if (DocApproval.Where(x => x.Number == 1).Count() == 0 && (IsInitiator || IsCurator || IsPersonnelBank || IsConsultant))//инициатор, куратор, кадровик, консультант { //если иницатор не выбран, это значит, что инициатор действует сам User Initiator = model.InitiatorId != 0 ? UserDao.Get(model.InitiatorId) : curUser;//инициатор da.ApproveUser = Initiator; da.AssistantUser = Assistant; da.Number = 1; da.IsImportance = true; error = "Заявка создана!"; } if (DocApproval.Where(x => x.Number == 1).Count() == 1 && DocApproval.Where(x => x.Number == 2).Count() == 0 && (entity.DepartmentAccessory.Id == 2 || entity.DepartmentAccessory.Id == 6) && IsCurator)//только фронты и БэкФронты { da.ApproveUser = curUser; da.AssistantUser = null; da.Number = 2; da.IsImportance = true; error = "Заявка проверена куратором!"; } //if (DocApproval.Where(x => x.Number == 2).Count() == 1 && DocApproval.Where(x => x.Number == 3).Count() == 0) if (DocApproval.Where(x => x.Number == 1).Count() == 1 && DocApproval.Where(x => x.Number == 3).Count() == 0 && entity.DepartmentAccessory.Id == 1 && IsPersonnelBank)//только бэки { da.ApproveUser = curUser; da.AssistantUser = null; da.Number = 3; da.IsImportance = true; error = "Заявка проверена кадровиком банка!"; } if (DocApproval.Where(x => x.Number == 3 || x.Number == 2).Count() == 1 && DocApproval.Where(x => x.Number == 5).Count() == 0 && (IsTopManager || IsCurator || IsPersonnelBank || IsConsultant))//высший руководитель, куратор, кадровик, консультант { //если согласовант не выбран, это значит, что он действует сам User TopManager = model.TopManagerId != 0 ? UserDao.Get(model.TopManagerId) : curUser;//высший руководитель da.ApproveUser = TopManager; da.AssistantUser = Assistant; da.Number = 5; da.IsImportance = true; error = "Заявка согласована!"; } if (DocApproval.Where(x => x.Number == 5).Count() == 1 && DocApproval.Where(x => x.Number == 6).Count() == 0 && (IsBoardMember || IsCurator || IsPersonnelBank || IsConsultant))//член правления, куратор, кадровик, консультант { //если утверждающий не выбран, это значит, что он действует сам User BoardMember = model.BoardMemberId != 0 ? UserDao.Get(model.BoardMemberId) : curUser;//член правления da.ApproveUser = BoardMember; da.AssistantUser = Assistant; da.IsImportance = true; da.Number = 6; error = "Заявка утверждена!"; } } else //согласование специалистами { if (DocApproval.Where(x => x.Number == 7).Count() == 0 && (IsStaffListOrder || IsConsultant)) { da.ApproveUser = curUser; da.AssistantUser = null; da.Number = 7; error = "Приказ составлен!"; } if (DocApproval.Where(x => x.Number == 4).Count() == 0 && (IsTaxCollector || IsConsultant)) { da.ApproveUser = curUser; da.AssistantUser = null; da.Number = 4; error = "Заявка согласована налоговиком!"; } } try { DocumentApprovalDao.SaveAndFlush(da); //сохраняем здачу пайруса if (!string.IsNullOrEmpty(model.PyrusNumber)) { entity.StaffRequestPyrusTasks.Add(new StaffRequestPyrusTasks() { DepRequest = entity, DocumentApproval = da, NumberTask = model.PyrusNumber, Creator = curUser, CreateDate = DateTime.Now }); } if (da.Number == 1) { entity.DateSendToApprove = DateTime.Now; return da.Number; } if (da.Number > 1 && da.Number < 6) return da.Number; if (da.Number == 6) { entity.DateState = DateTime.Now; } } catch (Exception ex) { DocumentApprovalDao.RollbackTran(); error = string.Format("Произошла ошибка при сохранении данных! Исключение:{0}", ex.GetBaseException().Message); return -1; } return 0; }
/*protected bool IsDirectorChiefForCreator(User current, User creator) { if (!creator.Level.HasValue || creator.Level < MinManagerLevel || creator.Level > MaxManagerLevel) throw new ValidationException(string.Format(StrIncorrectManagerLevel, creator.Level.HasValue ? creator.Level.Value.ToString() : "<не указан>", creator.Id)); return (creator.Level.Value == 2); }*/ protected bool IsManagerChiefForCreator(User current, User creator) { var chiefs = GetChiefsForManager(creator.Id); //foreach(var el in manualchiefs) if (chiefs.Contains(current) ) return true; if (!current.Level.HasValue || current.Level < MinManagerLevel || current.Level > MaxManagerLevel) throw new ValidationException(string.Format(StrIncorrectManagerLevel, current.Level.HasValue ? current.Level.Value.ToString() : "<не указан>", current.Id)); if (!creator.Level.HasValue || creator.Level < MinManagerLevel || creator.Level > MaxManagerLevel) throw new ValidationException(string.Format(StrIncorrectManagerLevel, creator.Level.HasValue ? creator.Level.Value.ToString() : "<не указан>", creator.Id)); List<DepartmentDto> departments; switch (current.Level) { case 2: IList<int> managers2 = AppointmentDao.GetChildrenManager2ForManager2(current.Id); if (managers2.Any(x => x == creator.Id && creator.Level.Value == 2)) return true; IList<int> managers = AppointmentDao.GetManager3ForManager2(current.Id); if (managers.Any(x => x == creator.Id && creator.Level.Value == 3)) return true; departments = AppointmentDao.GetDepartmentsForManager23(current.Id, 2, true).ToList(); return departments.Any(x => creator.Department.Path.StartsWith(x.Path) && creator.Level == 4); /*case 3: if (creator.Level != 4) return false; departments = AppointmentDao.GetDepartmentsForManager23(current.Id, 3, false).ToList(); return departments.Any(x => creator.Department.Path.StartsWith(x.Path)); */ case 3: // Для руководителей 3 уровня получаем список ручных привязок к подразделениям return ManualRoleRecordDao.GetRoleRecords(user: current, roleCode: "000000037") .Any(roleRecord => (roleRecord.TargetDepartment != null && creator.Department.Path.StartsWith(roleRecord.TargetDepartment.Path))); case 4: case 5: return creator.Department.Path.StartsWith(current.Department.Path) && creator.Department.Path.Length > current.Department.Path.Length; default: if (creator.Department == null) throw new ValidationException(string.Format(StrNoDepartmentForManager, creator.Id)); if (current.Department == null) throw new ValidationException(string.Format(StrNoDepartmentForManager, current.Id)); return false; } }
protected void RejectReportsExceptId(int appointmentId,int exceptReportId,User user,string rejectReason) { List<AppointmentReport> list = AppointmentReportDao.LoadForAppointmentId(appointmentId); foreach (AppointmentReport report in list) { if(report.Id != exceptReportId && !report.DeleteDate.HasValue) { if (report.DateAccept.HasValue) { Log.ErrorFormat(StrOtherReportUserAccepted, report.Number); throw new ValidationException(string.Format(StrOtherReportUserAccepted, report.Number)); } report.DeleteUser = user; report.DeleteDate = DateTime.Now; report.RejectReason = rejectReason; AppointmentReportDao.SaveAndFlush(report); } } }
/// <summary> /// DEPRECATED. Отключено. /// </summary> /// <param name="user"></param> /// <param name="acceptDate"></param> /// <returns></returns> protected EmailDto SendEmailForManagerAcceptRequests(User user,DateTime acceptDate) { string to = null; switch (user.UserRole) { case UserRole.Manager: /*foreach (User u in user.Personnels) { if (string.IsNullOrEmpty(u.Email)) Log.ErrorFormat("Cannot send request accept e-mail from manager {0} to personnel manager {1} - empty email", user.Id, u.FullName); else { if (string.IsNullOrEmpty(to)) to = u.Email; else to += ";" + u.Email; } }*/ //Мыло отключено для кадровиков break; default: throw new ArgumentException(string.Format("SendEmailForManagerAcceptRequests - ivalid user {0} role",user.Id)); } string body; string subject = GetSubjectAndBodyForManagerAcceptRequest(user,acceptDate, out body); return SendEmail(to, subject, body); }
/*protected EmailDto SendEmailForAppointmentPersonnelAccept(User personnel, Appointment entity) { string staffManagerEmail = ConfigurationService.AppointmentStaffManagerEmail; if (string.IsNullOrEmpty(staffManagerEmail)) throw new ValidationException(StrEmailForStaffManagerNotFound); string body; string subject = GetSubjectAndBodyForAppointmentManagerAcceptRequest(personnel, entity, out body); return SendEmail(staffManagerEmail, subject, body); }*/ protected EmailDto SendEmailForAppointmentManagerAccept(User creator, Appointment entity) { string to = string.Empty; //IdNameDto user; List<IdNameDto> users; var chiefs = GetChiefsForManager(creator.Id).OrderByDescending(x=>x.Level); if (chiefs.Any()) foreach(var el in chiefs) { if (String.IsNullOrWhiteSpace(el.Email)) continue; string b; string s = GetSubjectAndBodyForAppointmentManagerAcceptRequest(creator, entity, out b); return SendEmail(el.Email, s, b); } #region Анахронизм switch (creator.UserRole) { case UserRole.Manager: switch (creator.Level) { case 2: users = AppointmentDao.GetParentForManager2(creator.Id); if (users.Count == 0) { Log.ErrorFormat(StrEmailForAppointmentManagerAcceptParent2NotFound, creator.Id); return new EmailDto { Error = string.Format(StrEmailForAppointmentManagerAcceptParent2NotFound, creator.Id) }; } foreach (IdNameDto usr in users) { if (string.IsNullOrEmpty(usr.Name)) Log.WarnFormat("No email for manager (id {0})", usr.Id); else { if (string.IsNullOrEmpty(to)) to = usr.Name; else to += ";" + usr.Name; } } /*if (user == null) { Log.ErrorFormat(StrEmailForAppointmentManagerAcceptParent2NotFound, creator.Id); return new EmailDto { Error = string.Format(StrEmailForAppointmentManagerAcceptParent2NotFound, creator.Id) }; } if (string.IsNullOrEmpty(user.Name)) { Log.ErrorFormat(StrEmailForAppointmentManagerAcceptNoEmail, user.Id); return new EmailDto { Error = string.Format(StrEmailForAppointmentManagerAcceptNoEmail, user.Id) }; } to = user.Name;*/ break; case 3: users = AppointmentDao.GetParentForManager3(creator.Id); if (users.Count == 0) { Log.ErrorFormat(StrEmailForAppointmentManagerAcceptParent3NotFound, creator.Id); return new EmailDto { Error = string.Format(StrEmailForAppointmentManagerAcceptParent3NotFound, creator.Id) }; } foreach (IdNameDto usr in users) { if (string.IsNullOrEmpty(usr.Name)) Log.WarnFormat("No email for manager (id {0})", usr.Id); else { if (string.IsNullOrEmpty(to)) to = usr.Name; else to += ";" + usr.Name; } } /*if(user == null) { Log.ErrorFormat(StrEmailForAppointmentManagerAcceptParent3NotFound, creator.Id); return new EmailDto { Error = string.Format(StrEmailForAppointmentManagerAcceptParent3NotFound, creator.Id) }; } if (string.IsNullOrEmpty(user.Name)) { Log.ErrorFormat(StrEmailForAppointmentManagerAcceptNoEmail, user.Id); return new EmailDto { Error = string.Format(StrEmailForAppointmentManagerAcceptNoEmail, user.Id) }; } to = user.Name;*/ break; case 4: users = AppointmentDao.GetParentForManager4Department(creator.Department.Id); if (users.Count == 0) { Log.ErrorFormat(StrEmailForAppointmentManagerAcceptParentNotFound, creator.Id); return new EmailDto { Error = string.Format(StrEmailForAppointmentManagerAcceptParentNotFound, creator.Id) }; } foreach (IdNameDto usr in users) { if (string.IsNullOrEmpty(usr.Name)) Log.WarnFormat("No email for manager (id {0})", usr.Id); else { if (string.IsNullOrEmpty(to)) to = usr.Name; else to += ";" + usr.Name; } } break; case 5: case 6: users = AppointmentDao.GetForManagersParentDepartment(creator.Department.Id); if (users.Count == 0) { Log.ErrorFormat(StrEmailForAppointmentManagerAcceptParentNotFound, creator.Id); return new EmailDto { Error = string.Format(StrEmailForAppointmentManagerAcceptParentNotFound, creator.Id) }; } foreach (IdNameDto usr in users) { if (string.IsNullOrEmpty(usr.Name)) Log.WarnFormat("No email for manager (id {0})", usr.Id); else { if (string.IsNullOrEmpty(to)) to = usr.Name; else to += ";"+ usr.Name; } } break; default: throw new ArgumentException(string.Format(StrEmailForAppointmentManagerAcceptIncorrectManagerLevel, creator.Id)); } break; default: throw new ArgumentException(string.Format(StrEmailForAppointmentManagerAcceptIncorrectRole, creator.Id)); } if (string.IsNullOrEmpty(to)) { Log.ErrorFormat(StrEmailForAppointmentManagerAcceptNoEmails, creator.Id); return new EmailDto { Error = string.Format(StrEmailForAppointmentManagerAcceptNoEmails, creator.Id) }; } string body; string subject = GetSubjectAndBodyForAppointmentManagerAcceptRequest(creator, entity, out body); return SendEmail(to, subject, body); #endregion }
protected EmailDto SendEmailForUserRequest(User user,IUser current, User creator,bool isDeleted, int requestId,int requestNumber, RequestTypeEnum requestType,bool isFromComment) { string to = null; switch(current.UserRole) { case UserRole.Employee: if(user.Manager == null || string.IsNullOrEmpty(user.Manager.Email)) { Log.ErrorFormat("Cannot send e-mail (request {0},requestType {1}) from user {2} to manager - no manager or empty email",requestId,requestType,user.Id); return null; } to = user.Manager.Email; break; case UserRole.DismissedEmployee: if (user.Manager == null || string.IsNullOrEmpty(user.Manager.Email)) { Log.ErrorFormat("Cannot send e-mail (request {0},requestType {1}) from user {2} to manager - no manager or empty email", requestId, requestType, user.Id); return null; } to = user.Manager.Email; break; case UserRole.Manager: //Мыло отключено для кадровиков, т.к. оно им не надо оказалось. /*foreach (User u in user.Personnels) { if (string.IsNullOrEmpty(u.Email)) Log.ErrorFormat("Cannot send e-mail (request {0},requestType {1}) from manager {2} to personnel manager {3} - empty email", requestId, requestType, current.Id, u.FullName); else { if (string.IsNullOrEmpty(to)) to = u.Email; else to += ";" + u.Email; } }*/ if ((creator.UserRole & UserRole.Manager) > 0) { if (string.IsNullOrEmpty(user.Email)) Log.ErrorFormat( "Cannot send e-mail (request {0},requestType {1}) from manager {2} to user - empty email", requestId, requestType, current.Id); else { if (string.IsNullOrEmpty(to)) to = user.Email; else to += ";" + user.Email; } } if (string.IsNullOrEmpty(to)) return null; break; case UserRole.PersonnelManager: if ((creator.UserRole & UserRole.PersonnelManager) > 0 || isDeleted) { if (user.Manager == null || string.IsNullOrEmpty(user.Manager.Email)) Log.ErrorFormat( "Cannot send e-mail (request {0},requestType {1}) from personnel manager {2} to manager - no manager or empty email", requestId, requestType, current.Id); else to = user.Manager.Email; if (string.IsNullOrEmpty(user.Email)) Log.ErrorFormat( "Cannot send e-mail (request {0},requestType {1}) from personnel manager {2} to user - empty email", requestId, requestType, current.Id); else { if (string.IsNullOrEmpty(to)) to = user.Email; else to += ";" + user.Email; } } if (string.IsNullOrEmpty(to)) return null; break; } string body; string subject = GetSubjectAndBody(current, requestId, requestNumber, requestType,isDeleted,out body); return SendEmail(to, subject, body); }
protected EmailDto SendEmailForBankAccountant(User user, Appointment entity) { string BankAccountantEmail = ConfigurationService.AppointmentPersonnelManagerEmail; if (string.IsNullOrEmpty(BankAccountantEmail)) throw new ValidationException(StrEmailForStaffManagerNotFound); string body=String.Format("Создана заявка №{0} от {1} на поиск кандидата в {2}",entity.Number,entity.CreateDate,entity.Department.Name); string subject = "Создана заявка на поиск сотрудника"; return SendEmail(BankAccountantEmail, subject, body); }
protected User SetUserModel(UserModel model, User user) { //User user = UserDao.Load(userId); model.UserId = user.Id; model.Code = user.Code; model.Comment = user.Comment; model.DateAccepted = user.DateAccept; model.DateRelease = user.DateRelease; model.FullName = user.FullName; return user; }
protected void SetCreatorDepartment(User creator,AppointmentEditModel model) { if ((creator.UserRole & UserRole.Manager) == UserRole.Manager) { List<DepartmentDto> departments; switch (creator.Level) { case 2: departments = AppointmentDao.GetDepartmentsForManager23(creator.Id, 2, false).ToList(); if(departments.Count > 0) { model.DepartmentId = departments[0].Id; model.DepartmentName = departments[0].Name; } break; case 3: departments = AppointmentDao.GetDepartmentsForManager23(creator.Id, 3, false).ToList(); if(departments.Count > 0) { model.DepartmentId = departments[0].Id; model.DepartmentName = departments[0].Name; } break; default: if (creator.Department == null) throw new ValidationException(string.Format(StrNoDepartmentForManager, creator.Id)); model.DepartmentId = creator.Department.Id; model.DepartmentName = creator.Department.Name; break; } } }
public void SetDocumentsToModel(AppointmentListModel model, User user) { UserRole role = AuthenticationService.CurrentUser.UserRole; //model.Documents = new List<AppointmentDto>(); model.Documents = AppointmentDao.GetDocuments( user.Id, role, model.DepartmentId, model.ReasonId, model.StatusId, model.Number, model.BeginDate, model.EndDate, model.UserName, model.RecruteFio, model.SortBy, model.SortDescending); }
protected void SetFlagsState(int id, User current, UserRole currRole, AppointmentReport entity, AppointmentReportEditModel model) { SetFlagsState(model, false); model.AppId = entity.Appointment.Id; if (entity.CandidateRejectDate.HasValue) { model.CandidateRejectDate = entity.CandidateRejectDate; model.CandidateRejectedBy = entity.CandidateRejectedBy != null ? entity.CandidateRejectedBy.Name : ""; } model.IsManagerApproved = entity.ManagerDateAccept.HasValue; model.IsBankAccountantAccept = entity.Appointment.BankAccountantAccept.HasValue && entity.Appointment.BankAccountantAccept.HasValue && entity.Appointment.BankAccountantAcceptCount > 0; model.IsStaffApproved = entity.StaffDateAccept.HasValue; model.IsDeleted = entity.DeleteDate.HasValue; if (entity.AcceptManager != null && entity.ManagerDateAccept.HasValue) model.ManagerFio = entity.AcceptManager.FullName; if (entity.AcceptStaff != null && entity.StaffDateAccept.HasValue) model.StaffFio = entity.AcceptStaff.FullName; if (entity.DeleteDate.HasValue) model.DeleteUser = entity.DeleteUser.FullName; model.ShowStaff = entity.Appointment.Recruter == 1; switch (currRole) { case UserRole.Manager: if (current.Id == entity.Appointment.Creator.Id && !entity.DeleteDate.HasValue) { if (!entity.StaffDateAccept.HasValue) { model.IsStaffApproveAvailable = true; } model.IsEditable = true; if (entity.AcceptManager != null && !string.IsNullOrEmpty(entity.TempLogin)) model.IsPrintLoginAvailable = true; if (!entity.DateAccept.HasValue) { if (entity.StaffDateAccept.HasValue) { model.IsManagerRejectAvailable = true; if (!entity.ManagerDateAccept.HasValue) { model.IsManagerApproveAvailable = true; model.IsColloquyDateEditable = true; } else { model.IsManagerEditable = true; if (!string.IsNullOrEmpty(entity.TempLogin)) model.IsPrintLoginAvailable = true; } } } } break; case UserRole.StaffManager: if (!entity.DeleteDate.HasValue /*&& (current.Id == entity.Appointment.AcceptStaff.Id || (entity.Appointment.Recruters!=null?entity.Appointment.Recruters.Any(x=>x.Id==current.Id):false))*/) { if (entity.AcceptManager != null && entity.AcceptManager.Id == current.Id && !string.IsNullOrEmpty(entity.TempLogin)) model.IsPrintLoginAvailable = true; if (!entity.DateAccept.HasValue) { if (!entity.StaffDateAccept.HasValue) { model.IsStaffApproveAvailable = true; model.IsEditable = true; if (model.AttachmentId > 0) { model.IsDeleteScanAvailable = true; model.IsManagerApproveAvailable = true; model.IsColloquyDateEditable = true; model.IsManagerEditable = false; } } else if (!entity.ManagerDateAccept.HasValue) { model.IsManagerRejectAvailable = true; model.IsManagerApproveAvailable = true; model.IsColloquyDateEditable = true; model.IsManagerEditable = false; } else if (entity.AcceptManager.Id == current.Id) { model.IsManagerRejectAvailable = true; model.IsManagerEditable = false; } /*if (!entity.StaffDateAccept.HasValue) { model.IsEditable = true; if (model.AttachmentId > 0) { model.IsStaffApproveAvailable = true; model.IsDeleteScanAvailable = true; model.IsManagerApproveAvailable = true; model.IsColloquyDateEditable = true; } } else { model.IsManagerRejectAvailable = true; if (!entity.ManagerDateAccept.HasValue) { model.IsManagerApproveAvailable = true; model.IsColloquyDateEditable = true; } else { model.IsManagerEditable = true; if (!string.IsNullOrEmpty(entity.TempLogin)) model.IsPrintLoginAvailable = true; } }*/ if (entity.ManagerDateAccept.HasValue && model.IsColloquyPassed == 1) model.IsStaffSetDateAcceptAvailable = true; model.IsAddAvailable = true; /*if (model.AttachmentId > 0) model.ApproveForAllAvailable = true;*/ } } break; case UserRole.Trainer: model.IsTrainerCanSave = model.IsColloquyPassed == 1; break; case UserRole.ConsultantPersonnel: case UserRole.PersonnelManager: case UserRole.Estimator: case UserRole.OutsourcingManager: case UserRole.Security: break; default: throw new ArgumentException(string.Format("Недопустимая роль {0}", currRole)); } model.IsSaveAvailable = model.IsEditable || model.IsManagerEditable || model.IsManagerApproveAvailable || model.IsStaffApproveAvailable || model.IsStaffSetDateAcceptAvailable | model.IsTrainerCanSave; }
protected void ChangeEntityProperties(IUser current, Appointment entity, AppointmentEditModel model, User user,out string error) { error = string.Empty; User currUser = UserDao.Load(current.Id); if (!model.IsDelete && (model.IsEditable || model.IsSaveAvailable)) { //entity.AdditionalRequirements = model.AdditionalRequirements; entity.FIO = model.FIO; entity.isNotifyNeeded=model.isNeedToNotify; entity.Bonus = Decimal.Parse(model.Bonus); entity.PyrusNumber = model.PyrusNumber; entity.City = model.City; entity.Compensation =(String.IsNullOrWhiteSpace(model.Compensation))?"-":model.Compensation; entity.Department = DepartmentDao.Load(model.DepartmentId); entity.EducationRequirements = (String.IsNullOrWhiteSpace(model.EducationRequirements))?"-":model.EducationRequirements; entity.ExperienceRequirements =(String.IsNullOrWhiteSpace( model.ExperienceRequirements))?"-":model.ExperienceRequirements; entity.OtherRequirements =(String.IsNullOrWhiteSpace( model.OtherRequirements))?"-":model.OtherRequirements; //entity.Period = model.Period; entity.PositionName = model.PositionName;//PositionDao.Load(model.PositionId); entity.Reason = AppointmentReasonDao.Load(model.ReasonId); entity.ReasonBeginDate = (model.ReasonId != 3 && !String.IsNullOrWhiteSpace(model.ReasonBeginDate)) ? DateTime.Parse(model.ReasonBeginDate) : new DateTime?(); entity.DesirableBeginDate = model.ShowStaff ? DateTime.Parse(model.DesirableBeginDate) : entity.ReasonBeginDate.HasValue ? entity.ReasonBeginDate.Value+TimeSpan.FromDays(14) : DateTime.Now; //entity.AppointmentEducationTypeId = model.AppointmentEducationType; entity.ReasonPosition = model.ReasonId != 1 && model.ReasonId != 2 ?model.ReasonPosition:null; if (model.ReasonId > 2 && model.ReasonId < 7 && model.ReasonPositionId>0) { entity.ReasonPositionUser = UserDao.Load(model.ReasonPositionId); } entity.Responsibility = (String.IsNullOrWhiteSpace(model.Responsibility))?"-":model.Responsibility; entity.Salary = Decimal.Parse(model.Salary); entity.Schedule = (String.IsNullOrWhiteSpace(model.Schedule))?"-":model.Schedule; entity.Type = model.TypeId == 1?true:false; if (current.UserRole == UserRole.ConsultantPersonnel) { entity.BankAccountant = UserDao.Load(current.Id); entity.IsVacationExists = model.IsVacationExists == 1 ? true : false; model.BankAccountantAccept = true; entity.BankAccountantAccept = model.BankAccountantAccept; entity.BankAccountantAcceptCount = model.BankAccountantAcceptCount; } entity.VacationCount = int.Parse(model.VacationCount); if (model.StaffCreatorId != 0) entity.StaffCreator = UserDao.Load(model.StaffCreatorId); } switch (current.UserRole) { case UserRole.ConsultantPersonnel: if (entity.BankAccountantAccept.HasValue && entity.IsVacationExists) { EmailDto dto = SendEmailForAppointmentManagerAccept(entity.Creator, entity); if (!string.IsNullOrEmpty(dto.Error)) error = string.Format("Заявка обработана успешно,но есть ошибка при отправке оповещений: {0}", dto.Error); } if (entity.BankAccountantAccept.HasValue && !entity.IsVacationExists) { EmailDto dto = SendEmailForBankAccountantReject(entity.Creator, entity); if (!string.IsNullOrEmpty(dto.Error)) error = string.Format("Заявка обработана успешно,но есть ошибка при отправке оповещений: {0}", dto.Error); } break; case UserRole.Manager: if(current.Id == entity.Creator.Id) { if (model.NonActual) { entity.NonActual = model.NonActual; EmploymentCandidateDao.CancelCandidatesByAppointmentId(model.Id); RejectReports(entity.Id, currUser, "Заявка отклонена"); } if(model.IsManagerRejectAvailable && !entity.DeleteDate.HasValue && model.IsDelete) { /*entity.DeleteDate = DateTime.Now; entity.DeleteUser = currUser;*/ RejectAppointment(entity); EmailDto dto = SendEmailForAppointmentReject(currUser, entity); if (!string.IsNullOrEmpty(dto.Error)) error = string.Format("Заявка обработана успешно,но есть ошибка при отправке оповещений: {0}",dto.Error); RejectReports(entity.Id, currUser, "Заявка отклонена"); //if(entity.AcceptStaff != null) // SendEmailForAppointmentReject(entity.AcceptStaff, entity); } if(!entity.DeleteDate.HasValue && model.IsManagerApproveAvailable && model.IsManagerApproved) { entity.ManagerDateAccept = DateTime.Now; entity.AppointmentEducationTypeId = model.AppointmentEducationType; entity.AcceptManager = currUser; //entity.AppointmentEducationTypeId = model.AppointmentEducationType; EmailDto dto = SendEmailForBankAccountant(entity.Creator, entity); //dto = SendEmailForAppointmentManagerAccept(entity.Creator, entity); if (!string.IsNullOrEmpty(dto.Error)) error = string.Format("Заявка обработана успешно,но есть ошибка при отправке оповещений: {0}", dto.Error); var dto2=SendEmailForStaffManager(entity); if (!string.IsNullOrEmpty(dto2.Error)) error = string.Format("Заявка обработана успешно,но есть ошибка при отправке оповещений: {0}", dto2.Error); } if(IsManagerChiefForCreator(currUser,entity.Creator)) if (!entity.DeleteDate.HasValue && model.IsChiefApproveAvailable && model.IsChiefApproved) { entity.ChiefDateAccept = DateTime.Now; entity.AcceptChief = currUser; EmailDto dto = SendEmailForAppointmentChiefAccept(currUser, entity); if (!string.IsNullOrEmpty(dto.Error)) error = string.Format("Заявка обработана успешно,но есть ошибка при отправке оповещений: {0}", dto.Error); if (entity.Recruter == 2) { entity.AcceptStaff = entity.Creator; CreateAppointmentReport(entity); } } } else if(IsManagerChiefForCreator(currUser,entity.Creator)) { if (model.NonActual) { entity.NonActual = model.NonActual; EmploymentCandidateDao.CancelCandidatesByAppointmentId(model.Id); RejectReports(entity.Id, currUser, "Заявка отклонена"); } if (model.IsManagerRejectAvailable && !entity.DeleteDate.HasValue && model.IsDelete) { /*entity.DeleteDate = DateTime.Now; entity.DeleteUser = currUser;*/ RejectAppointment(entity); EmailDto dto = SendEmailForAppointmentReject(currUser, entity); if (!string.IsNullOrEmpty(dto.Error)) error = string.Format("Заявка обработана успешно,но есть ошибка при отправке оповещений: {0}",dto.Error); RejectReports(entity.Id, currUser, "Заявка отклонена"); //if(entity.AcceptStaff != null) // SendEmailForAppointmentReject(entity.AcceptStaff, entity); } if (!entity.DeleteDate.HasValue && model.IsChiefApproveAvailable && model.IsChiefApproved) { entity.ChiefDateAccept = DateTime.Now; entity.AcceptChief = currUser; EmailDto dto = SendEmailForAppointmentChiefAccept(currUser, entity); if (!string.IsNullOrEmpty(dto.Error)) error = string.Format("Заявка обработана успешно,но есть ошибка при отправке оповещений: {0}", dto.Error); if (entity.Recruter == 2) { entity.AcceptStaff = entity.Creator; CreateAppointmentReport(entity); } } } break; case UserRole.StaffManager: if (model.AppointmentEducationType != entity.AppointmentEducationTypeId) { entity.AppointmentEducationTypeId = model.AppointmentEducationType; AppointmentReportDao.Update(x => x.Appointment.Id == entity.Id, y => y.Type = AppointmentEducationTypeDao.Load(entity.AppointmentEducationTypeId)); } if (model.NonActual) { entity.NonActual = model.NonActual; EmploymentCandidateDao.CancelCandidatesByAppointmentId(model.Id); RejectReports(entity.Id, currUser, "Заявка отклонена"); } if (!entity.DeleteDate.HasValue) { entity.NonActual = model.NonActual; if (model.StaffCreatorId == current.Id || entity.Creator.Id == current.Id) { if (model.ApproveForAll) { entity.ManagerDateAccept = DateTime.Now; entity.AcceptManager = currUser; entity.ChiefDateAccept = DateTime.Now; entity.AcceptChief = currUser; entity.StaffDateAccept = DateTime.Now; entity.AcceptStaff = currUser; if (entity.Id == 0) AppointmentDao.SaveAndFlush(entity); CreateAppointmentReport(entity); } else if (model.IsManagerRejectAvailable && model.IsDelete) { /*entity.DeleteDate = DateTime.Now; entity.DeleteUser = currUser;*/ RejectAppointment(entity); RejectReports(entity.Id, currUser, "Заявка отклонена"); } else if (model.IsChiefApproveAvailable && model.IsChiefApproved) { /*if (model.StaffCreatorId == current.Id) {*/ entity.ChiefDateAccept = DateTime.Now; entity.AcceptChief = currUser; //} } else if (model.IsManagerApproveAvailable && model.IsManagerApproved) { entity.ManagerDateAccept = DateTime.Now; entity.AcceptManager = currUser; EmailDto dto = SendEmailForAppointmentManagerAccept(entity.Creator, entity); if (!string.IsNullOrEmpty(dto.Error)) error = string.Format("Заявка обработана успешно,но есть ошибка при отправке оповещений: {0}", dto.Error); } else if (entity.ChiefDateAccept.HasValue && !entity.StaffDateAccept.HasValue && model.IsStaffApproveAvailable && model.IsStaffApproved) { entity.StaffDateAccept = DateTime.Now; var recruters = new List<User>(); if(model.Recruter1id>0) recruters.Add( UserDao.Load(model.Recruter1id)); if(model.Recruter2id>0) recruters.Add( UserDao.Load(model.Recruter2id)); if(model.Recruter3id>0) recruters.Add( UserDao.Load(model.Recruter3id)); entity.Recruters = recruters; //entity.AppointmentEducationTypeId = model.AppointmentEducationType; entity.AcceptStaff = currUser; entity.Priority = model.Priority; CreateAppointmentReport(entity); } } else if (entity.ChiefDateAccept.HasValue && !entity.StaffDateAccept.HasValue && model.IsStaffApproveAvailable && model.IsStaffApproved) { entity.StaffDateAccept = DateTime.Now; entity.AcceptStaff = currUser; //entity.AppointmentEducationTypeId = model.AppointmentEducationType; var recruters = new List<User>(); if (model.Recruter1id > 0) recruters.Add(UserDao.Load(model.Recruter1id)); if (model.Recruter2id > 0) recruters.Add(UserDao.Load(model.Recruter2id)); if (model.Recruter3id > 0) recruters.Add(UserDao.Load(model.Recruter3id)); entity.Recruters = recruters; entity.Priority = model.Priority; CreateAppointmentReport(entity); } } break; case UserRole.Estimator: case UserRole.OutsourcingManager: break; default: throw new ArgumentException(string.Format("Недопустимая роль {0}", current.UserRole)); } }
private void CreateCandidate(AppointmentReport entity) { User newUserEntity = new User(); newUserEntity.Login = entity.TempLogin; newUserEntity.Password = entity.TempPassword; newUserEntity.IsFirstTimeLogin = true; newUserEntity.IsActive = true; newUserEntity.IsNew = true; newUserEntity.Name = entity.Name; newUserEntity.RoleId = (int)UserRole.Candidate; newUserEntity.GivesCredit = false; newUserEntity.IsMainManager = false; //UserDao.SaveAndFlush(newUserEntity); EmploymentCommonDao.SaveAndFlush(new EmploymentCandidate { User = newUserEntity }); }
protected void ChangeEntityProperties(IUser current, AppointmentReport entity, AppointmentReportEditModel model, User user, out string error) { error = string.Empty; User currUser = UserDao.Get(current.Id); bool dateAcceptSet = false; if (model.CandidateRejectDate.HasValue) { entity.CandidateRejectDate = DateTime.Now; entity.CandidateRejectedBy = UserDao.Load(CurrentUser.Id); } if (!model.IsDelete) { if (model.IsEditable) { //model.IsEducationExists = !entity.IsEducationExists.HasValue ? 0 : (entity.IsEducationExists.Value ? 1 : 0); //model.UserId = entity.Creator.Id; //entity.Type = AppointmentEducationTypeDao.Get(model.TypeId); entity.Name = model.Name; entity.Phone = model.Phone; entity.Email = model.Email; //entity.ColloquyDate = DateTime.Parse(model.ColloquyDate); entity.EducationTime = model.EducationTime ; //entity.RejectReason = model.RejectReason; } if (!String.IsNullOrWhiteSpace(model.LessonDate)) { DateTime res; if (DateTime.TryParse(model.LessonDate, out res)) { entity.LessonDate = res; }; } if(model.IsColloquyDateEditable) { entity.ColloquyDate = string.IsNullOrEmpty(model.ColloquyDate) ? new DateTime?() : DateTime.Parse(model.ColloquyDate); } if (model.IsManagerEditable) { entity.ResumeComment = model.ResumeComment; if (model.IsColloquyPassed >= 0) entity.IsColloquyPassed = model.IsColloquyPassed == 1 ? true : false; else entity.IsColloquyPassed = new bool?(); if (!string.IsNullOrEmpty(model.DateAccept)) { entity.DateAccept = DateTime.Parse(model.DateAccept); dateAcceptSet = true; } } if (model.IsStaffSetDateAcceptAvailable) { /*if (model.IsEducationExists >= 0) entity.IsEducationExists = model.IsEducationExists == 1 ? true : false; else entity.IsEducationExists = new bool?();*/ if (!string.IsNullOrEmpty(model.DateAccept) && entity.IsEducationExists.HasValue) { entity.DateAccept = DateTime.Parse(model.DateAccept); dateAcceptSet = true; } } } switch (current.UserRole) { case UserRole.StaffManager: { if (!entity.DeleteDate.HasValue /*&& (entity.Appointment.AcceptStaff.Id == current.Id || entity.Appointment.Recruters.Any(x=>x.Id==current.Id))*/) { entity.TestingResult = model.TestingResult; entity.ResumeCommentByOPINP = model.ResumeCommentByOPINP; if (!entity.StaffDateAccept.HasValue && model.IsStaffApproved && model.AttachmentId > 0) { entity.StaffDateAccept = DateTime.Now; entity.AcceptStaff = currUser; } if (entity.StaffDateAccept.HasValue && !entity.ManagerDateAccept.HasValue && model.IsManagerApproved) { entity.ManagerDateAccept = DateTime.Now; entity.AcceptManager = currUser; entity.TempLogin = entity.Id.ToString(); entity.TempPassword = CreatePassword(PasswordLength); } /*if (entity.Appointment.Creator.Id == current.Id && dateAcceptSet) { RejectReportsExceptId(entity.Appointment.Id, entity.Id, entity.Appointment.Creator, string.Format("Другой кандидат принят на работу (отчет № {0})", entity.Number)); }*/ if (entity.AcceptStaff != null && dateAcceptSet) { RejectReportsExceptId(entity.Appointment.Id, entity.Id, entity.Creator, string.Format("Другой кандидат принят на работу (отчет № {0})", entity.Number)); } //} } } break; case UserRole.Manager: { if (!entity.StaffDateAccept.HasValue && model.IsStaffApproved && model.AttachmentId > 0) { entity.StaffDateAccept = DateTime.Now; entity.AcceptStaff = currUser; } if(!entity.DeleteDate.HasValue && entity.StaffDateAccept.HasValue && !entity.ManagerDateAccept.HasValue && entity.Appointment.Creator.Id == current.Id && model.IsManagerApproved) { entity.ManagerDateAccept = DateTime.Now; entity.AcceptManager = currUser; entity.TempLogin = entity.Id.ToString(); entity.TempPassword = CreatePassword(PasswordLength); entity.ResumeComment = model.ResumeComment; CreateCandidate(entity); } if (!entity.DeleteDate.HasValue && entity.Appointment.Creator.Id == current.Id && dateAcceptSet) { RejectReportsExceptId(entity.Appointment.Id, entity.Id, entity.Appointment.Creator, string.Format("Другой кандидат принят на работу (отчет № {0})", entity.Number)); } } break; case UserRole.Trainer: if (model.IsEducationExists >= 0) entity.IsEducationExists = model.IsEducationExists == 1 ? true : false; else entity.IsEducationExists = new bool?(); break; case UserRole.Estimator: case UserRole.OutsourcingManager: break; default: throw new ArgumentException(string.Format("Недопустимая роль {0}", current.UserRole)); } }
public IUser CreateUser(User user,UserRole roleId) { return UserDto.CreateUser(user,roleId); }
protected string GetSubjectAndBodyForAppointmentRejectRequest(User user, Appointment entity, out string body) { DepartmentDto dep3 = AppointmentDao.GetDepartmentForPathAndLevel(entity.Department.Path, 3); if (dep3 == null) Log.ErrorFormat(StrEmailForAppointmentManagerAcceptDepartment3NotFound, entity.Department.Id); body = string.Format(StrEmailForAppointmentManagerRejectText, entity.Number, entity.PositionName, dep3 == null ? "<не найдена в базе данных>" : dep3.Name, user.FullName); const string subject = StrEmailForAppointmentManagerRejectSubject; return subject; }