示例#1
0
 protected int? SaveAttachment(int entityId, int id, UploadFileDto dto, RequestAttachmentTypeEnum type, out string attachment)
 {
     attachment = string.Empty;
     if (dto == null)
         return new int?();
     RequestAttachment attach = id != 0 ?
        RequestAttachmentDao.Get(id) :
        new RequestAttachment
        {
            RequestId = entityId,
            RequestType = (int)type,
            CreatorRole = RoleDao.Load((int)CurrentUser.UserRole),
        };
     if (id == 0)
     {
         RequestAttachment existingAttach = RequestAttachmentDao.FindByRequestIdAndTypeId(entityId, type);
         if (existingAttach != null)
         {
             Log.InfoFormat("Файл уже существует", entityId, type, existingAttach.Id);
             attach = existingAttach;
         }
     }
     attach.DateCreated = DateTime.Now;
     attach.UncompressContext = dto.Context;
     attach.ContextType = dto.ContextType;
     attach.FileName = dto.FileName;
     attach.CreatorRole = RoleDao.Load((int)CurrentUser.UserRole);
     RequestAttachmentDao.SaveAndFlush(attach);
     attachment = attach.FileName;
     if (type == RequestAttachmentTypeEnum.StaffMovements)
     {
         var doc=StaffMovementsDocsDao.Load(entityId);
         doc.Attachment = attach;
         StaffMovementsDocsDao.SaveAndFlush(doc);
     }
     return attach.Id;
 }
示例#2
0
        protected bool ValidateServiceRequestEditModel(HelpServiceRequestEditModel model, UploadFileDto fileDto)
        {
            /*if (model.Id > 0 && fileDto == null && model.AttachmentId == 0)
            {
                if (model.Operation == 1)
                    ModelState.AddModelError(string.Empty,StrCannotSendRequestWithoutTemplate);
            }*/

            //if (model.TypeId == 15)
            //{
            //    ModelState.AddModelError("TypeId", "Данный вид услуги не доступен для создания заявки!");
            //}

            if(model.IsForFiredUser)
            {
                if (String.IsNullOrWhiteSpace(model.UserBirthDate)) ModelState.AddModelError("UserBirthDate", "Не заполнена дата рождения");
                if (String.IsNullOrWhiteSpace(model.FiredUserName)) ModelState.AddModelError("FiredUserName", "Не заполнено имя");
                if (String.IsNullOrWhiteSpace(model.FiredUserSurname)) ModelState.AddModelError("FiredUserSurname", "Не заполнено фамилия");
                if (String.IsNullOrWhiteSpace(model.FiredUserPatronymic)) ModelState.AddModelError("FiredUserPatronymic", "Не заполнено отчество");
            }
            return ModelState.IsValid;
        }
示例#3
0
        public bool SaveAppointmentReportEditModel(AppointmentReportEditModel model, UploadFileDto fileDto,out string error)
        {
            error = string.Empty;
            User creator = null;
            AppointmentReport entity = null;
            try
            {
                IUser current = AuthenticationService.CurrentUser;
                entity = AppointmentReportDao.Get(model.Id);
                if (entity == null)
                    throw new ValidationException(string.Format(StrAppointmentReportNotFound, model.Id));
                creator = UserDao.Load(entity.Appointment.Creator.Id);

                if (entity.Version != model.Version)
                {
                    error = StrMultipleAccessError;
                    model.ReloadPage = true;
                    return false;
                }
                if (entity.DeleteDate.HasValue)
                {
                    error = StrReportWasRejected;
                    model.ReloadPage = true;
                    return false;
                }
                if (entity.Appointment.DeleteDate.HasValue)
                {
                    error = StrAppointmentWasRejected;
                    model.ReloadPage = true;
                    return false;
                }
                string fileName;
                int? attachmentId = SaveAttachment(entity.Id, model.AttachmentId, fileDto, RequestAttachmentTypeEnum.AppointmentReport, out fileName);
                if (attachmentId.HasValue)
                {
                    model.AttachmentId = attachmentId.Value;
                    model.Attachment = fileName;
                }
                if (model.IsDelete)
                {
                    switch (current.UserRole)
                    {
                        case UserRole.StaffManager:
                            if (!entity.DeleteDate.HasValue && !entity.ManagerDateAccept.HasValue
                                 && entity.Appointment.AcceptStaff.Id == current.Id)
                            {
                                entity.DeleteDate = DateTime.Now;
                                entity.DeleteUser = entity.Appointment.AcceptStaff;
                            }
                            break;
                        case UserRole.Manager:
                            if (!entity.DeleteDate.HasValue && entity.StaffDateAccept.HasValue
                                && entity.Appointment.Creator.Id == current.Id
                                && !entity.DateAccept.HasValue)
                            {
                                entity.DeleteDate = DateTime.Now;
                                entity.DeleteUser = entity.Appointment.Creator;
                                entity.RejectReason = model.RejectReason;
                            }
                            break;
                        case UserRole.Trainer:

                            break;
                        default:
                            throw new ArgumentException(string.Format("Недопустимая роль {0}", current.UserRole));
                    }
                }
                else
                {
                    ChangeEntityProperties(current, entity, model, creator, out error);
                    AppointmentReportDao.SaveAndFlush(entity);
                    if (entity.Version != model.Version)
                    {
                        entity.EditDate = DateTime.Now;
                        AppointmentReportDao.SaveAndFlush(entity);
                    }
                }
                if (entity.DeleteDate.HasValue)
                    model.IsDeleted = true;
                model.DocumentNumber = entity.Number.ToString();
                model.Version = entity.Version;
                model.DateCreated = entity.CreateDate.ToShortDateString();
                model.IsEducationExists = entity.IsEducationExists.HasValue ? (entity.IsEducationExists.Value ? 1 : 0) : -1;
                model.IsColloquyPassed = entity.IsColloquyPassed.HasValue?(entity.IsColloquyPassed.Value?1:0):-1;
                SetFlagsState(entity.Id, UserDao.Load(current.Id), current.UserRole, entity, model);
                //Задолбала Улькина
                model.ReloadPage = true;
                return true;
            }
            catch (Exception ex)
            {
                AppointmentDao.RollbackTran();
                Log.Error("Error on SaveAppointmentReportEditModel:", ex);
                error = StrException + ex.GetBaseException().Message;
                return false;
            }
            finally
            {
                SetManagerInfoModel(creator, model,null,entity);
                LoadDictionaries(model);
                SetHiddenFields(model,entity);
            }
        }
示例#4
0
 protected bool ValidateAppointmentReportEditModel(AppointmentReportEditModel model,UploadFileDto fileDto)
 {
     if (model.IsDelete)
         return true;
     if (!string.IsNullOrEmpty(model.ColloquyDate))
     {
         DateTime colloquyDate;
         if (!DateTime.TryParse(model.ColloquyDate, out colloquyDate))
             ModelState.AddModelError("ColloquyDate", StrInvalidColloquyDate);
     }
     if (!string.IsNullOrEmpty(model.DateAccept))
     {
         DateTime dateAccept;
         if (!DateTime.TryParse(model.DateAccept, out dateAccept))
             ModelState.AddModelError("DateAccept", StrInvalidDateAccept);
     }
     return ModelState.IsValid;
 }
示例#5
0
文件: HelpBl.cs 项目: andreyu/Reports
        public bool SaveServiceRequestEditModel(HelpServiceRequestEditModel model, UploadFileDto fileDto, out string error)
        {
            error = string.Empty;
            User currUser = null;
            User user = null;
            HelpServiceRequest entity = null;
            try
            {

                IUser current = AuthenticationService.CurrentUser;
                currUser = UserDao.Load(current.Id);
                user = UserDao.Load(model.UserId);

                if (model.Id == 0)
                {
                    entity = new HelpServiceRequest
                    {
                        CreateDate = DateTime.Now,
                        Creator = currUser,//UserDao.Load(current.Id),
                        Number = RequestNextNumberDao.GetNextNumberForType((int)RequestTypeEnum.HelpServiceRequest),
                        EditDate = DateTime.Now,
                        User = user,
                        FiredUserName=model.FiredUserName,
                        FiredUserSurname=model.FiredUserSurname,
                        FiredUserPatronymic=model.FiredUserPatronymic,
                        Note=noteTypeDao.Load(model.Note),
                        IsForGEMoney=model.IsForGEMoney
                    };
                    if (model.UserBirthDate != null) entity.UserBirthDate = DateTime.Parse(model.UserBirthDate);

                    ChangeEntityProperties(entity, model,fileDto,currUser,out error);
                    HelpServiceRequestDao.SaveAndFlush(entity);
                    model.Id = entity.Id;
                    model.DocumentNumber = entity.Number.ToString();
                    model.DateCreated = entity.CreateDate.ToShortDateString();
                    model.Creator = entity.Creator.FullName;
                    if (fileDto != null && entity.Type.IsAttachmentAvailable)
                        ChangeEntityProperties(entity, model, fileDto, currUser, out error);//если создается черновик, то цепляем файл образца
                }
                else
                {
                    entity = HelpServiceRequestDao.Get(model.Id);
                    if (entity == null)
                        throw new ValidationException(string.Format(StrServiceRequestNotFound, model.Id));
                    if (entity.Version != model.Version)
                    {
                        error = StrServiceRequestWasChanged;
                        model.ReloadPage = true;
                        return false;
                    }
                    ChangeEntityProperties(entity, model, fileDto, currUser, out error);
                    HelpServiceRequestDao.SaveAndFlush(entity);
                    if (entity.Version != model.Version)
                    {
                        if((entity.Creator !=null && entity.Creator.Id == CurrentUser.Id) || (entity.User!=null && entity.User.Id==CurrentUser.Id))
                            entity.EditDate = DateTime.Now;
                        HelpServiceRequestDao.SaveAndFlush(entity);
                    }
                }
                    //if (entity.DeleteDate.HasValue)
                    //    model.IsDeleted = true;
                //}
                model.Version = entity.Version;
                model.Worker = entity.Consultant != null ? entity.Consultant.FullName : string.Empty;
                model.WorkerEndDate = entity.EndWorkDate.HasValue ?
                                      entity.EndWorkDate.Value.ToShortDateString() : string.Empty;
                model.ConfirmDate = entity.ConfirmWorkDate.HasValue ?
                                     entity.ConfirmWorkDate.Value.ToShortDateString() : string.Empty;

                SetFlagsState(entity.Id, currUser,entity, model);
                return true;
            }
            catch (Exception ex)
            {
                HelpServiceRequestDao.RollbackTran();
                Log.Error("Error on SaveServiceRequestEditModel:", ex);
                error = StrException + ex.GetBaseException().Message;
                return false;
            }
            finally
            {
                //SetUserInfoModel(user, model);
                LoadDictionaries(model);
                SetHiddenFields(model);
            }
        }
示例#6
0
文件: HelpBl.cs 项目: andreyu/Reports
        protected void ChangeEntityProperties(HelpServiceRequest entity,HelpServiceRequestEditModel model,
            UploadFileDto fileDto, User currUser,out string error)
        {
            error = string.Empty;
            UserRole currRole = AuthenticationService.CurrentUser.UserRole;
            if (model.IsEditable)
            {
                HelpServiceType type = HelpServiceTypeDao.Load(model.TypeId);
                if (model.Id != 0)
                {
                    if (fileDto != null && entity.Type.IsAttachmentAvailable && model.AttachmentId != 0)
                        RequestAttachmentDao.DeleteAndFlush(model.AttachmentId);
                }
                entity.Type = type;
                entity.IsForGEMoney = model.IsForGEMoney;
                entity.Note = noteTypeDao.Load(model.Note);
                entity.FiredUserName = model.FiredUserName;
                entity.FiredUserSurname = model.FiredUserSurname;
                entity.FiredUserPatronymic = model.FiredUserPatronymic;
                if (model.DepartmentId > 0)
                {
                    var dep = DepartmentDao.Load(model.DepartmentId);
                    entity.FiredUserDepartment = dep;
                }
                if(model.UserBirthDate!=null) entity.UserBirthDate = DateTime.Parse(model.UserBirthDate);
                entity.ProductionTime = HelpServiceProductionTimeDao.Load(model.ProductionTimeTypeId);
                entity.TransferMethod = helpServiceTransferMethodDao.Load(model.TransferMethodTypeId);
                entity.Requirements = type.IsRequirementsAvailable ? model.Requirements : null;
                entity.Period = type.IsPeriodAvailable
                                    ? model.PeriodId.HasValue ? helpServicePeriodDao.Load(model.PeriodId.Value) : null
                                    : null;
                entity.Address = model.Address;
                if(fileDto != null && entity.Type.IsAttachmentAvailable && entity.Id != 0)
                {
                    RequestAttachment attachment = new RequestAttachment
                                                       {
                                                           UncompressContext = fileDto.Context,
                                                           ContextType = fileDto.ContextType,
                                                           CreatorRole = RoleDao.Load((int)currRole),
                                                           DateCreated = DateTime.Now,
                                                           FileName = fileDto.FileName,
                                                           RequestId = entity.Id,
                                                           RequestType = (int)RequestAttachmentTypeEnum.HelpServiceRequestTemplate,
                                                       };
                    RequestAttachmentDao.SaveAndFlush(attachment);
                    model.AttachmentId = attachment.Id;
                    model.Attachment = attachment.FileName;
                }
                if (!entity.Type.IsAttachmentAvailable && model.AttachmentId != 0)
                    RequestAttachmentDao.DeleteAndFlush(model.AttachmentId);
            }
            if (model.IsConsultantOutsourcingEditable)
            {
                if (fileDto != null && model.ServiceAttachmentId != 0)
                    RequestAttachmentDao.DeleteAndFlush(model.ServiceAttachmentId);
                if (fileDto != null)
                {
                    RequestAttachment attachment = new RequestAttachment
                    {
                        UncompressContext = fileDto.Context,
                        ContextType = fileDto.ContextType,
                        CreatorRole = RoleDao.Load((int)currRole),
                        DateCreated = DateTime.Now,
                        FileName = fileDto.FileName,
                        RequestId = entity.Id,
                        RequestType = (int)RequestAttachmentTypeEnum.HelpServiceRequest,
                        DocumentsCount =  model.DocumentsCount>0?model.DocumentsCount:1
                    };
                    RequestAttachmentDao.SaveAndFlush(attachment);
                    model.ServiceAttachmentId = attachment.Id;
                    model.ServiceAttachment = attachment.FileName;
                }
            }
            switch (currRole)
            {
                case UserRole.ConsultantPersonnel:
                case UserRole.Employee:
                    if (entity.Creator.Id == currUser.Id)
                    {
                        if (model.Operation == 1 && !entity.SendDate.HasValue)
                            entity.SendDate = DateTime.Now;
                        if(entity.EndWorkDate.HasValue)
                        {
                            if(model.Operation == 4)
                                entity.ConfirmWorkDate = DateTime.Now;
                            else if(model.Operation == 5)
                            {
                                entity.SendDate = null;
                                entity.BeginWorkDate = null;
                                entity.EndWorkDate = null;
                            }
                        }
                    }
                    break;
                case UserRole.DismissedEmployee:
                    if (entity.Creator.Id == currUser.Id)
                    {
                        if (model.Operation == 1 && !entity.SendDate.HasValue)
                            entity.SendDate = DateTime.Now;
                        if (entity.EndWorkDate.HasValue)
                        {
                            if (model.Operation == 4)
                                entity.ConfirmWorkDate = DateTime.Now;
                            else if (model.Operation == 5)
                            {
                                entity.SendDate = null;
                                entity.BeginWorkDate = null;
                                entity.EndWorkDate = null;
                            }
                        }
                    }
                    break;
                case UserRole.Manager:
                    if (entity.Creator.Id == currUser.Id)
                    {
                        if (model.Operation == 1 && !entity.SendDate.HasValue)
                            entity.SendDate = DateTime.Now;
                        if (entity.EndWorkDate.HasValue)
                        {
                            if (model.Operation == 4)
                                entity.ConfirmWorkDate = DateTime.Now;
                            else if (model.Operation == 5)
                            {
                                entity.SendDate = null;
                                entity.BeginWorkDate = null;
                                entity.EndWorkDate = null;
                            }
                        }
                    }
                    break;
                case UserRole.ConsultantOutsourcing:
                    if (entity.Consultant == null || (entity.Consultant.Id == currUser.Id))
                    {
                        if (model.Operation == 2 && entity.SendDate.HasValue)
                        {
                            entity.BeginWorkDate = DateTime.Now;
                            entity.Consultant = currUser;
                        }
                        if (entity.Consultant != null && entity.Consultant.Id == currUser.Id
                            && model.Operation == 3 && entity.BeginWorkDate.HasValue)
                        {
                            entity.EndWorkDate = DateTime.Now;
                            entity.ConfirmWorkDate = DateTime.Now;
                        }
                        if (entity.Consultant != null && entity.Consultant.Id == currUser.Id
                            && model.Operation == 6 && entity.BeginWorkDate.HasValue)
                        {
                            entity.EndWorkDate = DateTime.Now;
                            entity.NotEndWorkDate = DateTime.Now;
                        }
                    }
                    //кнопка принятия в работу доступна пока не сформируется услуга не зависимо от того, кто ее принял в работу
                    if (model.Operation == 2 && entity.SendDate.HasValue && !entity.NotEndWorkDate.HasValue)
                    {
                        entity.BeginWorkDate = DateTime.Now;
                        entity.Consultant = currUser;
                    }
                    break;
                case UserRole.PersonnelManager:
                    if (entity.Consultant == null || (entity.Consultant.Id == currUser.Id))
                    {
                        if (model.Operation == 2 && entity.SendDate.HasValue)
                        {
                            entity.BeginWorkDate = DateTime.Now;
                            entity.Consultant = currUser;
                        }
                        if (entity.Consultant != null && entity.Consultant.Id == currUser.Id
                            && model.Operation == 3 && entity.BeginWorkDate.HasValue)
                        {
                            entity.EndWorkDate = DateTime.Now;
                            entity.ConfirmWorkDate = DateTime.Now;
                        }
                        if (entity.Consultant != null && entity.Consultant.Id == currUser.Id
                            && model.Operation == 6 && entity.BeginWorkDate.HasValue)
                        {
                            entity.EndWorkDate = DateTime.Now;
                            entity.NotEndWorkDate = DateTime.Now;
                        }
                    }
                    //кнопка принятия в работу доступна пока не сформируется услуга не зависимо от того, кто ее принял в работу
                    if (model.Operation == 2 && entity.SendDate.HasValue && !entity.NotEndWorkDate.HasValue)
                    {
                        entity.BeginWorkDate = DateTime.Now;
                        entity.Consultant = currUser;
                    }

                    //если консультант создает заявку за сотрудника
                    if (entity.Creator.Id == currUser.Id && model.Operation == 1 && !entity.SendDate.HasValue)
                        entity.SendDate = DateTime.Now;
                    break;
                /*case UserRole.PersonnelManager: //DEPRECATED MAY BE PROBLEM
                    if (entity.Consultant == null || (entity.Consultant.Id == currUser.Id))
                    {
                        if (model.Operation == 2 && entity.SendDate.HasValue)
                        {
                            entity.BeginWorkDate = DateTime.Now;
                            entity.Consultant = currUser;
                        }
                        if (entity.Consultant != null && entity.Consultant.Id == currUser.Id
                            && model.Operation == 3 && entity.BeginWorkDate.HasValue)
                        {
                            entity.EndWorkDate = DateTime.Now;
                            entity.ConfirmWorkDate = DateTime.Now;
                        }
                        if (entity.Consultant != null && entity.Consultant.Id == currUser.Id
                            && model.Operation == 6 && entity.BeginWorkDate.HasValue && currUser.Id == 10)
                        {
                            entity.EndWorkDate = DateTime.Now;
                            entity.NotEndWorkDate = DateTime.Now;
                        }
                    }
                    //кнопка принятия в работу доступна пока не сформируется услуга не зависимо от того, кто ее принял в работу
                    if (model.Operation == 2 && entity.SendDate.HasValue && !entity.NotEndWorkDate.HasValue)
                    {
                        entity.BeginWorkDate = DateTime.Now;
                        entity.Consultant = currUser;
                    }
                    break;*/
            }
        }
示例#7
0
        public bool SaveEditDocumentInternal(EmployeeDocumentEditModel model, UploadFileDto fileDto,
            User owner, out string Error)
        {
            try
            {
                bool isNewDocument = false;
                Error = null;
                List<EmployeeDocumentType> types = GetEmployeeDocumentTypes();
                model.DocumentTypes = types.ConvertAll(x => new IdNameDto(x.Id, x.Name));
                EmployeeDocumentType type = types.Where(x => x.Id == model.DocumentTypeId).First();
                IList<EmployeeDocumentSubType> subTypes = type.SubTypes.OrderBy(x => x.Name).ToList();
                model.DocumentSubTypes = subTypes.ToList().ConvertAll(x => new IdNameDto(x.Id, x.Name));
                Document doc = null;
                if (model.DocumentId != 0)
                {
                    doc = DocumentDao.Load(model.DocumentId);
                    if (model.Version != doc.Version)
                    {
                        model.ReloadPage = true;
                        Error = "Документ был изменен.";
                        return false;
                    }
                    //throw new ModifyDocumentException("Документ был изменен.");
                }
                IUser user = AuthenticationService.CurrentUser;
                if (((user.UserRole & UserRole.Employee) != UserRole.Employee) && (model.DocumentId == 0))
                    throw new ArgumentException("Новый документ может быть создан только сотрудником");
                if ((user.UserRole & UserRole.Employee) == UserRole.Employee)
                {

                    if (user.Id != owner.Id)
                        throw new ArgumentException("Доступ к документу запрещен.");
                    if (doc == null)
                    {
                        doc = new Document {Type = type, User = owner};
                        isNewDocument = true;
                    }
                    if (doc.ManagerDateAccept.HasValue)
                    {
                        model.ReloadPage = true;
                        Error = "Документ уже был одобрен руководителем, его изменение невозможно";
                        return false;
                    }
                    //throw new ModifyDocumentException("Документ уже был одобрен руководителем, его изменение невозможно");
                    Attachment attach;
                    doc = SetDocumentFromModel(model, fileDto, doc, type, subTypes, out attach);
                    model.Date = doc.LastModifiedDate;
                    model.DocumentId = doc.Id;
                    if (attach != null)
                    {
                        model.AttachmentId = attach.Id;
                        model.Attachment = attach.FileName;
                    }
                }
                else if ((user.UserRole & UserRole.Manager) == UserRole.Manager)
                {
                    if (user.Id != owner.Manager.Id)
                        throw new ArgumentException("Доступ к документу запрещен.");
                    if (doc.ManagerDateAccept.HasValue)
                    {
                        Error = "Документ уже был одобрен.";
                        return false;
                    }
                    if (model.IsApprovedByManager)
                    {
                        doc.ManagerDateAccept = DateTime.Now;
                        doc = DocumentDao.MergeAndFlush(doc);
                    }
                }
                else if ((user.UserRole & UserRole.PersonnelManager) == UserRole.PersonnelManager)
                {
                    if (owner.Personnels.Where(x => x.Id == user.Id).FirstOrDefault() == null)
                        throw new ArgumentException("Доступ к документу запрещен.");
                    if (doc.PersonnelManagerDateAccept.HasValue)
                    {
                        Error = "Документ уже был одобрен.";
                        return false;
                    }
                    if (model.IsApprovedByPersonnelManager)
                    {
                        doc.PersonnelManagerDateAccept = DateTime.Now;
                        doc = DocumentDao.MergeAndFlush(doc);
                    }
                }
                else if ((user.UserRole & UserRole.BudgetManager) == UserRole.BudgetManager)
                {
                    //if (user.Id != owner.BudgetManager.Id)
                    //    throw new ArgumentException("Доступ к документу запрещен.");
                    if (doc.BudgetManagerDateAccept.HasValue)
                    {
                        Error = "Документ уже был одобрен.";
                        return false;
                    }
                    if (model.IsApprovedByBudgetManager)
                    {
                        doc.BudgetManagerDateAccept = DateTime.Now;
                        doc = DocumentDao.MergeAndFlush(doc);
                    }
                }
                else if ((user.UserRole & UserRole.OutsourcingManager) == UserRole.OutsourcingManager || (user.UserRole & UserRole.Estimator) == UserRole.Estimator)
                {
                    //if (user.Id != owner.OutsourcingManager.Id)
                    //    throw new ArgumentException("Доступ к документу запрещен.");
                    if (doc.OutsourcingManagerDateAccept.HasValue)
                    {
                        Error = "Документ уже был обработан.";
                        return false;
                    }
                    if (model.IsApprovedByOutsorsingManager)
                    {
                        doc.OutsourcingManagerDateAccept = DateTime.Now;
                        doc = DocumentDao.MergeAndFlush(doc);
                    }
                }
                model.Version = doc.Version;
                if(isNewDocument)
                {
                    Settings settings = SettingsDao.LoadFirst();
                    if(settings == null)
                        Log.Error("Отсутствуют настройки в базе данных.");
                    else if (settings.SendEmailToManagerAboutNew)
                    {
                        if (doc.User.Manager == null || string.IsNullOrEmpty(doc.User.Manager.Email))
                            Log.WarnFormat("У пользователя {0} (Id {1}) отсутствует руководитель или e-mail руководителя не указан.", doc.User.FullName, doc.User.Id);
                        else
                        {
                            SendEmail(settings, model, doc.User.Manager.Email,
                                        "Новая заявка",
                                        string.Format("Пользователем {0} создана новая заявка.", doc.User.FullName));
                            if (!string.IsNullOrEmpty(model.EmailDto.Error))
                                Log.WarnFormat(
                                    "Письмо о новой заявке пользователя {0}(Id {1}) не было отправлено руководителю {2}.Ошибка: {3}",
                                    doc.User.FullName, doc.User.Id, doc.User.Manager.FullName, model.EmailDto.Error);
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Log.Error("Error on DocumentEdit:", ex);
                Error = string.Format("Исключение:{0}", ex.GetBaseException().Message);
                return false;
            }
        }
示例#8
0
 protected Document SetDocumentFromModel(EmployeeDocumentEditModel model, UploadFileDto fileDto,
     Document doc, EmployeeDocumentType type,
     IList<EmployeeDocumentSubType> subTypes, out Attachment attach)
 {
     doc.Comment = model.EditComment;
     doc.LastModifiedDate = DateTime.Now;
     doc.Type = type;
     doc.SubType = subTypes.Where(x => x.Id == model.DocumentSubTypeId).FirstOrDefault();
     doc = DocumentDao.MergeAndFlush(doc);
     attach = null;
     if (model.DocumentId != 0)
         attach = AttachmentDao.FindByDocumentId(doc.Id);
     if (fileDto != null)
     {
         if (attach == null)
             attach = new Attachment();
         attach.Context = fileDto.Context;
         attach.ContextType = fileDto.ContextType;
         attach.FileName = fileDto.FileName;
         attach.Document = doc;
         AttachmentDao.SaveAndFlush(attach);
     }
     return doc;
 }
示例#9
0
 public bool SaveEditDocument(EmployeeDocumentEditModel model, UploadFileDto fileDto,
     out string Error)
 {
     User owner = SetUserModel(model, model.UserId.Value);
     bool result = SaveEditDocumentInternal(model, fileDto, owner, out Error);
     model.CommentsModel = SetCommentsModel(model.DocumentId);
     //SetCommentsModel(model, model.DocumentId);
     SetControlsState(model, owner);
     return result;
 }
示例#10
0
        protected bool ValidateVacationEditModel(VacationEditModel model, UploadFileDto fileDto)
        {
            ModelState.Clear();
             UserRole role = AuthenticationService.CurrentUser.UserRole;
             if (model.Id > 0 && fileDto == null)
             {
                 int attachmentCount = RequestBl.GetAttachmentsCount(model.Id, RequestAttachmentTypeEnum.Vacation);
                 if (attachmentCount <= 0)
                 {
                     if ((role == UserRole.Employee && model.IsApprovedByUser) ||
                         (role == UserRole.Manager && model.IsApprovedByManager) ||
                         (role == UserRole.PersonnelManager && model.IsApprovedByPersonnelManager))
                     {

                         ModelState.AddModelError(string.Empty,
                                                  "Заявка не может быть согласована без прикрепленого документа.");
                         if (role == UserRole.Employee && model.IsApprovedByUser)
                         {
                             ModelState.Remove("IsApprovedByUser");
                             model.IsApprovedByUser = false;
                         }
                         if (role == UserRole.Manager && model.IsApprovedByManager)
                         {
                             ModelState.Remove("IsApprovedByManager");
                             model.IsApprovedByManager = false;
                         }
                         if (role == UserRole.PersonnelManager && model.IsApprovedByPersonnelManager)
                         {
                             ModelState.Remove("IsApprovedByPersonnelManager");
                             model.IsApprovedByPersonnelManager = false;
                         }
                     }
                 }
             }

             if(model.BeginDate.HasValue && model.EndDate.HasValue)
             {
                 if(model.BeginDate > model.EndDate)
                    ModelState.AddModelError("BeginDate", "Дата начала отпуска не может превышать дату окончания отпуска.");
                 else if(!model.IsDelete)
                 {
                     int requestCount = RequestBl.GetOtherRequestCountsForUserAndDates
                         (model.BeginDate.Value, model.EndDate.Value,
                         model.UserId, model.Id, false);
                     if(requestCount > 0)
                         ModelState.AddModelError("BeginDate",
                      "Для данного пользователя существуют другие заявки в указанном интервале дат.");
                 }
             }
             CheckBeginDate(model);
             return ModelState.IsValid;
        }
示例#11
0
        protected bool ValidateSicklistEditModel(SicklistEditModel model, UploadFileDto fileDto
             /*out bool needToReload,out string error*/)
        {
            //needToReload = false;
             //error = string.Empty;
             if (model.Id > 0 && fileDto == null)
             {
                 int attachmentCount = RequestBl.GetAttachmentsCount(model.Id,RequestAttachmentTypeEnum.Sicklist);
                 if (attachmentCount <= 0)
                 {
                     UserRole role = AuthenticationService.CurrentUser.UserRole;
                     if ((role == UserRole.Employee && model.IsApprovedByUser) ||
                         (role == UserRole.Manager && model.IsApprovedByManager) ||
                         ((role == UserRole.PersonnelManager || role == UserRole.OutsourcingManager || role == UserRole.Estimator) && model.IsApprovedByPersonnelManager))
                     {

                         ModelState.AddModelError(string.Empty,
                                                  "Заявка не может быть согласована без прикрепленого скана больничного.");
                         if (role == UserRole.Employee && model.IsApprovedByUser)
                         {
                             ModelState.Remove("IsApprovedByUser");
                             model.IsApprovedByUser = false;
                         }
                         if (role == UserRole.Manager && model.IsApprovedByManager)
                         {
                             ModelState.Remove("IsApprovedByManager");
                             model.IsApprovedByManager = false;
                         }
                         if (role == UserRole.PersonnelManager && model.IsApprovedByPersonnelManager)
                         {
                             ModelState.Remove("IsApprovedByPersonnelManager");
                             model.IsApprovedByPersonnelManager = false;
                         }
                         //error = "Заявка не может быть согласована без прикрепленого скана больничного.";
                         //needToReload = true;
                         //return false;

                     }
                 }
             }
             if (model.BeginDate.HasValue && model.EndDate.HasValue)
             {
                 UserRole role = AuthenticationService.CurrentUser.UserRole;

                 // Проверка на дубликаты
                 int requestCount = RequestBl.GetOtherRequestCountsForUserAndDates(model.BeginDate.Value, model.EndDate.Value, model.UserId, model.Id, RequestTypeEnum.Sicklist);
                 if (requestCount > 0)
                     ModelState.AddModelError("BeginDate", "Для данного пользователя существуют другие заявки в указанном интервале дат.");

                 if(model.BeginDate > model.EndDate)
                    ModelState.AddModelError("BeginDate", "Дата начала отпуска не может превышать дату окончания отпуска.");
                 else if (!model.IsDelete && model.IsApproved)
                 {
                     DateTime beginDate = model.BeginDate.Value;
                     DateTime current = DateTime.Today;
                     DateTime monthBegin = new DateTime(current.Year, current.Month, 1);
                     bool isValid = true;
                     if ((current.Day != 1) && monthBegin > beginDate)
                     {
                         isValid = RequestBl.HaveAbsencesForPeriod(model.BeginDate.Value,
                             model.EndDate.Value, model.UserId, AuthenticationService.CurrentUser.Id,role);
                         //ModelState.AddModelError(string.Empty, "Создание/изменение заявки в прошлом запрещено .");
                         //return;
                     }
                     if ((current.Day == 1) && monthBegin.AddMonths(-1) > beginDate)
                     {
                         isValid = RequestBl.HaveAbsencesForPeriod(model.BeginDate.Value,
                             model.EndDate.Value, model.UserId, AuthenticationService.CurrentUser.Id,role);
                         //ModelState.AddModelError(string.Empty, "Создание/изменение заявки в прошлом запрещено .");
                         //return;
                     }
                     if(!isValid)
                     {
                         Log.InfoFormat("Absence not found for sicklist {0}",model.Id);
                         ModelState.AddModelError(string.Empty,
              "Период, указанный в заявке,не соответствует данным по неявкам в табеле.Вы не можете согласовать эту заявку.");
                     }
                 }
             }

             if (!string.IsNullOrEmpty(model.SicklistNumber))
             {
                 Regex r = new Regex(@"^\d{12}$");
                 if(!r.IsMatch(model.SicklistNumber))
                    ModelState.AddModelError("SicklistNumber", "Номер больничного листа должен содержать 12 цифр");
             }

             if (model.IsPersonnelFieldsEditable && AuthenticationService.CurrentUser.UserRole != UserRole.OutsourcingManager && AuthenticationService.CurrentUser.UserRole != UserRole.Estimator)
             {
                 if (string.IsNullOrEmpty(model.ExperienceYears) && string.IsNullOrEmpty(model.ExperienceYears) && !(model.ExperienceIn1C == true))
                    ModelState.AddModelError("ExperienceYears", "Необходимо заполнить хотя бы одно из полей стажа.");

                 if (!string.IsNullOrEmpty(model.ExperienceYears))
                 {
                     int experienceYears;
                     if (!Int32.TryParse(model.ExperienceYears, out experienceYears))
                         ModelState.AddModelError("ExperienceYears", "Неправильно указано число лет стажа.");
                     else if (experienceYears < 0)
                         ModelState.AddModelError("ExperienceYears",
                                                  "Число лет стажа должно быть неотрицательным числом.");
                 }
                 if (!string.IsNullOrEmpty(model.ExperienceMonthes))
                 {
                     int experienceMonth;
                     if (!Int32.TryParse(model.ExperienceMonthes, out experienceMonth))
                         ModelState.AddModelError("ExperienceMonthes", "Неправильно указано число месяцев стажа.");
                     else if (experienceMonth < 0 || experienceMonth > 11)
                         ModelState.AddModelError("ExperienceMonthes",
                                                  "Число месяцев стажа должно быть неотрицательным числом меньшим 12.");
                 }
             }

             if (model.IsPersonnelFieldsEditable)
             {
                 if (!model.PaymentBeginDate.HasValue)
                     ModelState.AddModelError("PaymentBeginDate","'Назначить с даты' - обязательное поле.");

                 if(model.PaymentBeginDate.HasValue && model.BeginDate.HasValue && model.BeginDate.Value > model.PaymentBeginDate.Value)
                     ModelState.AddModelError("PaymentBeginDate",
                                                  "Поле 'Назначить с даты' не должно быть меньше поля 'Дата начала'.");
                 if (model.PaymentBeginDate.HasValue && model.EndDate.HasValue && model.EndDate.Value < model.PaymentBeginDate.Value)
                     ModelState.AddModelError("PaymentBeginDate",
                                                  "Поле 'Назначить с даты' не должно быть больше поля 'Дата окончания'.");
                 if (model.PaymentDecreaseDate.HasValue && model.BeginDate.HasValue && model.BeginDate.Value > model.PaymentDecreaseDate.Value)
                     ModelState.AddModelError("PaymentDecreaseDate",
                                                  "Поле 'Снизить пособие за нарушение режима с' не должно быть меньше поля 'Дата начала'.");
                 if (model.PaymentDecreaseDate.HasValue && model.EndDate.HasValue && model.EndDate.Value < model.PaymentDecreaseDate.Value)
                     ModelState.AddModelError("PaymentBeginDate",
                                                  "Поле 'Снизить пособие за нарушение режима с' не должно быть больше поля 'Дата окончания'.");
             }
             return ModelState.IsValid;
        }
示例#12
0
        protected bool ValidateDismissalEditModel(DismissalEditModel model, UploadFileDto fileDto)
        {
            //if (model.BeginDate.HasValue && model.EndDate.HasValue &&
             //    model.BeginDate > model.EndDate)
             //    ModelState.AddModelError("BeginDate", "Дата начала не может превышать дату окончания.");
             UserRole role = AuthenticationService.CurrentUser.UserRole;
             if (model.Id > 0 && fileDto == null)
             {
                 int attachmentCount = RequestBl.GetAttachmentsCount(model.Id, RequestAttachmentTypeEnum.Dismissal);
                 if (attachmentCount <= 0)
                 {
                     if ((role == UserRole.Employee && model.IsApprovedByUser) ||
                         (role == UserRole.Manager && model.IsApprovedByManager) ||
                         (role == UserRole.PersonnelManager && model.IsApprovedByPersonnelManager))
                     {

                         ModelState.AddModelError(string.Empty,
                                                  "Заявка не может быть согласована без прикрепленого заявления.");
                         if (role == UserRole.Employee && model.IsApprovedByUser)
                         {
                             ModelState.Remove("IsApprovedByUser");
                             model.IsApprovedByUser = false;
                         }
                         if (role == UserRole.Manager && model.IsApprovedByManager)
                         {
                             ModelState.Remove("IsApprovedByManager");
                             model.IsApprovedByManager = false;
                         }
                         if (role == UserRole.PersonnelManager && model.IsApprovedByPersonnelManager)
                         {
                             ModelState.Remove("IsApprovedByPersonnelManager");
                             model.IsApprovedByPersonnelManager = false;
                         }
                         //error = "Заявка не может быть согласована без прикрепленого скана больничного.";
                         //needToReload = true;
                         //return false;

                     }
                 }
             }
             if (role == UserRole.PersonnelManager && string.IsNullOrEmpty(model.Reason))
                 ModelState.AddModelError("Reason", "Основание документ - обязательное поле.");
             if(!string.IsNullOrEmpty(model.Compensation))
             {
                 decimal compensation;
                 if(!Decimal.TryParse(model.Compensation,out compensation) ||
                     compensation < 0)
                     ModelState.AddModelError("Compensation", "Кол-во дней компенсации должно быть неотрицательным десятичным числом.");
             }
             if (!string.IsNullOrEmpty(model.Reduction))
             {
                 decimal reduction;
                 if (!Decimal.TryParse(model.Reduction, out reduction) ||
                     reduction < 0)
                     ModelState.AddModelError("Reduction", "Кол-во дней удержания должно быть неотрицательным десятичным числом.");
             }
             if (role == UserRole.PersonnelManager && string.IsNullOrEmpty(model.Compensation) && string.IsNullOrEmpty(model.Reduction))
                 ModelState.AddModelError("Compensation", "Укажите \"Кол-во дней компенсации\" и/или \"Кол-во дней удержания\"");

             CheckEndDate(model);
             return ModelState.IsValid;
        }
示例#13
0
        protected bool ValidateChildVacationEditModel(ChildVacationEditModel model, UploadFileDto fileDto)
        {
            UserRole role = AuthenticationService.CurrentUser.UserRole;
             if (model.Id > 0 && fileDto == null)
             {
                 int attachmentCount = RequestBl.GetAttachmentsCount(model.Id, RequestAttachmentTypeEnum.ChildVacation);
                 if (attachmentCount <= 0)
                 {
                     if ((role == UserRole.Employee && model.IsApprovedByUser) ||
                         (role == UserRole.Manager && model.IsApprovedByManager) ||
                         (role == UserRole.PersonnelManager && model.IsApprovedByPersonnelManager))
                     {

                         ModelState.AddModelError(string.Empty,
                                                  "Заявка не может быть согласована без прикрепленого документа.");
                         if (role == UserRole.Employee && model.IsApprovedByUser)
                         {
                             ModelState.Remove("IsApprovedByUser");
                             model.IsApprovedByUser = false;
                         }
                         if (role == UserRole.Manager && model.IsApprovedByManager)
                         {
                             ModelState.Remove("IsApprovedByManager");
                             model.IsApprovedByManager = false;
                         }
                         if (role == UserRole.PersonnelManager && model.IsApprovedByPersonnelManager)
                         {
                             ModelState.Remove("IsApprovedByPersonnelManager");
                             model.IsApprovedByPersonnelManager = false;
                         }
                     }
                 }
             }
             if (model.BeginDate.HasValue && model.EndDate.HasValue)
             {
                 if (model.BeginDate > model.EndDate)
                     ModelState.AddModelError("BeginDate", "Дата начала отпуска не может превышать дату окончания отпуска.");
                 else if (!model.IsDelete)
                 {
                     /*int requestCount = RequestBl.GetOtherRequestCountsForUserAndDates
                         (model.BeginDate.Value, model.EndDate.Value,
                         model.UserId, model.Id,true);
                     if (requestCount > 0)
                         ModelState.AddModelError("BeginDate","Для данного пользователя существуют другие заявки в указанном интервале дат.");*/
                     if (model.IsApproved)
                     {
                         DateTime beginDate = model.BeginDate.Value;
                         DateTime current = DateTime.Today;
                         DateTime monthBegin = new DateTime(current.Year, current.Month, 1);
                         bool isValid = true;
                         if ((current.Day != 1) && monthBegin > beginDate)
                         {
                             isValid = RequestBl.HaveAbsencesForPeriod(model.BeginDate.Value,
                                                                       model.EndDate.Value, model.UserId,
                                                                       AuthenticationService.CurrentUser.Id, role);
                         }
                         if ((current.Day == 1) && monthBegin.AddMonths(-1) > beginDate)
                         {
                             isValid = RequestBl.HaveAbsencesForPeriod(model.BeginDate.Value,
                                                                       model.EndDate.Value, model.UserId,
                                                                       AuthenticationService.CurrentUser.Id, role);
                         }
                         if (!isValid)
                         {
                             Log.InfoFormat("Absence not found for child vacation {0}", model.Id);
                             ModelState.AddModelError(string.Empty,
                         "Период, указанный в заявке,не соответствует данным по неявкам в табеле.Вы не можете согласовать эту заявку.");
                         }
                     }
                 }
             }
             if (model.PaidToDate.HasValue && model.EndDate.HasValue && model.EndDate.Value < model.PaidToDate.Value)
                 ModelState.AddModelError("PaidToDate","Поле 'Выплачивать по' не должно быть больше поля 'Дата окончания'.");
             if (model.PaidToDate1.HasValue && model.EndDate.HasValue && model.EndDate.Value < model.PaidToDate1.Value)
                 ModelState.AddModelError("PaidToDate1", "Поле 'Выплачивать по' не должно быть больше поля 'Дата окончания'.");

             if (model.IsPersonnelFieldsEditable)
             {
                 if (!string.IsNullOrEmpty(model.ChildrenCount))
                 {
                     int childrenCount;
                     if (!Int32.TryParse(model.ChildrenCount, out childrenCount))
                         ModelState.AddModelError("ChildrenCount", "Неправильно указано количество детей.");
                     else if (childrenCount <= 0)
                         ModelState.AddModelError("ChildrenCount", "Количество детей должно быть целым положительным числом.");
                 }
             }
             //CheckBeginDate(model);
             return ModelState.IsValid;
        }