Пример #1
0
        /// <summary>
        /// 删除文档
        /// </summary>
        /// <param name="applicationDocId">文档ID</param>
        /// <returns></returns>
        public static void Delete(int applicationDocId, Func <Application, CurrentUser, bool> privilege)
        {
            using (var ctx = new AspodesDB())
            {
                var doc = ctx.ApplicationDocs.FirstOrDefault(ad => ad.ApplicationDocId == applicationDocId);
                if (null == doc)
                {
                    throw new NotFoundException("未找到文档");
                }

                var application = ctx.Applications.FirstOrDefault(a => a.ApplicationId == doc.ApplicationId);
                if (!privilege(application, UserHelper.GetCurrentUser()))
                {
                    throw new UnauthorizationException();
                }

                ctx.ApplicationDocs.Remove(doc);
                ctx.SaveChanges();
            }
        }
        /// <summary>
        /// 添加或者修改申请书领域
        /// </summary>
        /// <param name="fieldDTO">申请书领域信息</param>
        /// <returns></returns>
        public List <ApplicationField> AddOrUpdateApplicationField(List <AddApplicationFieldDTO> fieldDTOs, Func <Application, CurrentUser, bool> privilege)
        {
            var userInfo = UserHelper.GetCurrentUser();
            List <ApplicationField> fields = new List <ApplicationField>();

            using (var ctx = new AspodesDB())
            {
                foreach (var fieldDTO in fieldDTOs)
                {
                    var application = ctx.Applications.FirstOrDefault(a => a.ApplicationId == fieldDTO.ApplicationId);
                    if (null == application)
                    {
                        throw new NotFoundException("未找到申请书");
                    }

                    if (!privilege(application, userInfo) /**/ && false /**/)
                    {
                        throw new UnauthorizationException();                                                    //2018-03-15 取消填申请书草稿的年限验证
                    }
                    ApplicationField newField = Mapper.Map <ApplicationField>(fieldDTO);
                    var oldField = ctx.ApplicationFields.FirstOrDefault(ef => ef.ApplicationFieldId == newField.ApplicationFieldId);
                    if (null == oldField)
                    {
                        if (ctx.ApplicationFields.Where(af => af.ApplicationId == newField.ApplicationId).Count() >= SystemConfig.ApplicationFieldAmount)
                        {
                            throw new OtherException("申请书领域数目超过限制");
                        }
                        newField = ctx.ApplicationFields.Add(newField);
                    }
                    else
                    {
                        //不允许修改的属性
                        newField.ApplicationId = oldField.ApplicationId;
                        ctx.Entry(oldField).CurrentValues.SetValues(newField);
                    }
                    fields.Add(newField);
                }
                ctx.SaveChanges();
                return(fields);
            }
        }
Пример #3
0
        /// <summary>
        /// 修改用户工作经历
        /// </summary>
        /// <param name="working">工作经历</param>
        public List <WorkingDTO> EditWorking(WorkingDTO working)
        {
            var userid = HttpContext.Current.User.Identity.Name;

            using (var db = new AspodesDB())
            {
                var userInfo = db.Users.FirstOrDefault(c => c.UserId == userid);
                if (userInfo != null)
                {
                    ;
                    if (!string.IsNullOrEmpty(userInfo.Person.WorkingHistory))
                    {
                        List <WorkingDTO> workingList = JsonConvert.DeserializeObject <List <WorkingDTO> >(userInfo.Person.WorkingHistory);
                        var workingdata =
                            workingList.FirstOrDefault(c => c.WorkingId == working.WorkingId);
                        if (workingdata != null)
                        {
                            workingList.Remove(workingdata);
                            workingList.Add(working);

                            userInfo.Person.WorkingHistory = JsonConvert.SerializeObject(workingList);

                            db.SaveChanges();
                            return(workingList);
                        }
                        else
                        {
                            throw new NotFoundException("该工作经历不存在!");
                        }
                    }
                    else
                    {
                        throw new NotFoundException("无工作经历!");
                    }
                }
                else
                {
                    throw new NotFoundException("找不到用户!");
                }
            }
        }
Пример #4
0
        /// <summary>
        /// 修改用户教育经历
        /// </summary>
        /// <param name="education">教育经历</param>
        public List <EducationDTO> EditEducation(EducationDTO education)
        {
            var userid = HttpContext.Current.User.Identity.Name;

            using (var db = new AspodesDB())
            {
                var userInfo = db.Users.FirstOrDefault(c => c.UserId == userid);
                if (userInfo != null)
                {
                    ;
                    if (!string.IsNullOrEmpty(userInfo.Person.EducationHistor))
                    {
                        List <EducationDTO> educationList = JsonConvert.DeserializeObject <List <EducationDTO> >(userInfo.Person.EducationHistor);
                        var educationdata =
                            educationList.FirstOrDefault(c => c.EducationId == education.EducationId);
                        if (educationdata != null)
                        {
                            educationList.Remove(educationdata);
                            educationList.Add(education);

                            userInfo.Person.EducationHistor = JsonConvert.SerializeObject(educationList);

                            db.SaveChanges();
                            return(educationList);
                        }
                        else
                        {
                            throw new NotFoundException("该教育经历不存在!");
                        }
                    }
                    else
                    {
                        throw new NotFoundException("无教育经历!");
                    }
                }
                else
                {
                    throw new NotFoundException("找不到用户!");
                }
            }
        }
Пример #5
0
        /// <summary>
        /// 修改用户成果
        /// </summary>
        /// <param name="achievement">成果</param>
        public List <AchievementDTO> EditAchievement(AchievementDTO achievement)
        {
            var userid = HttpContext.Current.User.Identity.Name;

            using (var db = new AspodesDB())
            {
                var userInfo = db.Users.FirstOrDefault(c => c.UserId == userid);
                if (userInfo != null)
                {
                    ;
                    if (!string.IsNullOrEmpty(userInfo.Person.Achievements))
                    {
                        List <AchievementDTO> achievementList = JsonConvert.DeserializeObject <List <AchievementDTO> >(userInfo.Person.Achievements);
                        var achievementdata =
                            achievementList.FirstOrDefault(c => c.AchievementId == achievement.AchievementId);
                        if (achievementdata != null)
                        {
                            achievementList.Remove(achievementdata);
                            achievementList.Add(achievement);

                            userInfo.Person.Achievements = JsonConvert.SerializeObject(achievementList);

                            db.SaveChanges();
                            return(achievementList);
                        }
                        else
                        {
                            throw new NotFoundException("该项目成果不存在!");
                        }
                    }
                    else
                    {
                        throw new NotFoundException("无项目成果!");
                    }
                }
                else
                {
                    throw new NotFoundException("找不到用户!");
                }
            }
        }
Пример #6
0
        /// <summary>
        /// 添加公告、修改公告
        /// </summary>
        /// <param name="announceDTO">公告信息</param>
        /// <returns>
        /// 添加成功,返回ResponseStatus.success
        /// 失败,返回ResponseStatus.unknown_error和错误信息
        /// </returns>
        public GetAnnouncementDTO AddAnnouncement(AddAnnouncementDTO announceDTO)
        {
            Announcement saveValue = null;

            using (var ctx = new AspodesDB())
            {
                var oldValue = ctx.Announcements.FirstOrDefault(a => a.AnnouncementId == announceDTO.AnnouncementId);

                if (oldValue == null)
                {
                    Announcement announce = Mapper.Map <Announcement>(announceDTO);
                    var          user     = UserHelper.GetCurrentUser();
                    announce.InstituteId = user.InstId;
                    announce.PublisherId = user.UserId;
                    saveValue            = ctx.Announcements.Add(announce);
                    ctx.SaveChanges();
                    foreach (int attachmentId in announceDTO.Attachments)
                    {
                        ctx.AnnouncementAttachments.Find(attachmentId).AnnouncementId = saveValue.AnnouncementId;
                    }
                }
                else
                {
                    saveValue = Mapper.Map <Announcement>(announceDTO);
                    //不允许在Update时更改的值
                    saveValue.Status         = oldValue.Status;
                    saveValue.AnnouncementId = oldValue.AnnouncementId;
                    saveValue.InstituteId    = oldValue.InstituteId;
                    saveValue.PublisherId    = oldValue.PublisherId;
                    saveValue.PublishDate    = oldValue.PublishDate;
                    ctx.Entry(oldValue).CurrentValues.SetValues(saveValue);
                    ctx.SaveChanges();
                    foreach (int attachmentId in announceDTO.Attachments)
                    {
                        ctx.AnnouncementAttachments.Find(attachmentId).AnnouncementId = saveValue.AnnouncementId;
                    }
                }
                ctx.SaveChanges();
                return(Mapper.Map <GetAnnouncementDTO>(saveValue));
            }
        }
Пример #7
0
        private Institute AddInst(AspodesDB ctx, AddInstDTO dto)
        {
            var inst   = Mapper.Map <Institute>(dto);
            var person = Mapper.Map <Person>(dto);
            //添加单位
            var newInst = ctx.Institutes.Add(inst);

            ctx.SaveChanges();

            //添加联系人
            person.InstituteId = newInst.InstituteId;
            var newPerson = ctx.Persons.Add(person);

            ctx.SaveChanges();

            //给联系人添加账户
            User user = ctx.Users.Add(Mapper.Map <User>(newPerson));

            ctx.SaveChanges();

            //设置单位联系人
            newInst.ContactId = user.UserId;

            //给联系人添加用户角色
            Model.Authorize commen = new Model.Authorize
            {
                UserId = user.UserId,
                RoleId = 1
            };
            ctx.Authorizes.Add(commen);

            //给联系人添加单位管理员角色
            Model.Authorize instAdmin = new Model.Authorize
            {
                UserId = user.UserId,
                RoleId = 2
            };
            ctx.Authorizes.Add(instAdmin);
            ctx.SaveChanges();
            return(newInst);
        }
Пример #8
0
 /// <summary>
 /// 删除专家推荐
 /// </summary>
 /// <param name="recommendationId">专家推荐的ID</param>
 /// <returns></returns>
 public void DeleteRecommendation(int recommendationId, Func <Recommendation, bool> privilege)
 {
     using (var ctx = new AspodesDB())
     {
         var recommendation = ctx.Recommendations.FirstOrDefault(r => r.RecommendationId == recommendationId);
         if (null == recommendation)
         {
             throw new NotFoundException("未找到该用户");
         }
         if (!privilege(recommendation))
         {
             throw new UnauthorizationException();
         }
         if (recommendation.Adopt != null)
         {
             throw new OtherException("院管理员已处理,不可撤销");
         }
         ctx.Recommendations.Remove(recommendation);
         ctx.SaveChanges();
     }
 }
Пример #9
0
 /// <summary>
 /// 删除申请书草稿
 /// </summary>
 /// <param name="applicationId">申请书ID</param>
 /// <returns></returns>
 public void Delete(string applicationId, Func <Application, bool> privilege)
 {
     using (var ctx = new AspodesDB())
     {
         var application = ctx.Applications.FirstOrDefault(a => a.ApplicationId == applicationId);
         if (null == application)
         {
             throw new NotFoundException("未找到申请书");
         }
         if (!privilege(application))
         {
             throw new UnauthorizedAccessException("您没有权限删除该申请书");
         }
         if (application.Status >= ApplicationStatus.CHECK)
         {
             throw new OtherException("该申请书不允许删除");
         }
         ctx.Applications.Remove(application);
         ctx.SaveChanges();
     }
 }
Пример #10
0
        //还不能用依赖注入
        //private AspodesDB _context;
        //public ApplicationRepository(AspodesDB context)
        //{
        //    this._context = context;
        //}
        /// <summary>
        /// 获取一份申请书的基本信息
        /// </summary>
        /// <param name="id">申请书ID</param>
        /// <returns>
        /// 成功,返回ResponseStatus.success和申请书基本信息
        /// 没有找到数据,返回ResponseStatus.parameter_error,
        /// 出错,返回ResponseStatus.unknown_error和错误信息
        /// 没有权限访问,返回ResponseStatus.unauthorize
        /// </returns>
        public GetApplicationDTO GetOneApplication(string id)
        {
            GetApplicationDTO appDTO = null;

            using (var ctx = new AspodesDB())
            {
                var app = ctx.Applications.FirstOrDefault(a => a.ApplicationId == id);
                if (app == null)
                {
                    throw new NotFoundException("未找到申请书");
                }
                appDTO = Mapper.Map <GetApplicationDTO>(app);
                var pdf = ctx.ApplicationDocs.FirstOrDefault(ad => ad.ApplicationId == appDTO.ApplicationId && ad.Type == ApplicationDocType.PDF);
                if (pdf != null)
                {
                    appDTO.PDF = pdf.RelativeURL.Replace("~", "");
                }
            }

            return(appDTO);
        }
Пример #11
0
        /// <summary>
        /// 删除单位
        /// </summary>
        /// <param name="id">单位ID</param>
        /// <returns></returns>
        public void DeleteInst(int id)
        {
            using (var ctx = new AspodesDB())
            {
                var inst = ctx.Institutes.FirstOrDefault(i => i.InstituteId == id);
                if (null == inst)
                {
                    throw new NotFoundException();
                }
                if (ctx.Persons.Where(p => p.InstituteId == inst.InstituteId).Count() > 0)
                {
                    throw new OtherException("单位有人员记录");
                }
                if (ctx.Applications.Where(a => a.InstituteId == inst.InstituteId).Count() > 0)
                {
                    throw new OtherException("单位有申请书记录");
                }

                ctx.Institutes.Remove(inst);
                ctx.SaveChanges();
            }
        }
Пример #12
0
        /// <summary>
        /// 添加或者更新专家领域
        /// </summary>
        /// <param name="fieldDTOs"></param>
        /// <param name="privilege"></param>
        /// <returns></returns>
        public List <GetExpertFieldDTO> AddOrUpdateExpertField(List <AddExpertFieldDTO> fieldDTOs, Func <User, bool> privilege)
        {
            List <ExpertField> fields = new List <ExpertField>();

            using (var ctx = new AspodesDB())
            {
                foreach (var fieldDTO in fieldDTOs)
                {
                    var field = ctx.ExpertFields.FirstOrDefault(ef => ef.ExpertFieldId == fieldDTO.ExpertFieldId);
                    var user  = ctx.Users.FirstOrDefault(u => u.PersonId == fieldDTO.PersonId);

                    var newField = Mapper.Map <ExpertField>(fieldDTO);
                    newField.UserId = user.UserId;

                    if (!privilege(user))
                    {
                        throw new UnauthorizationException();
                    }

                    if (field == null)
                    {
                        if (ctx.ExpertFields.Where(ef => ef.UserId == user.UserId).Count() >= SystemConfig.ExpertFieldAmount)
                        {
                            break;
                        }
                        fields.Add(ctx.ExpertFields.Add(newField));
                    }
                    else
                    {
                        ctx.Entry(field).CurrentValues.SetValues(newField);
                        fields.Add(newField);
                    }
                }

                ctx.SaveChanges();

                return(fields.Select(Mapper.Map <GetExpertFieldDTO>).ToList());
            }
        }
Пример #13
0
 public void ResendAllEmail()
 {
     using (var ctx = new AspodesDB())
     {
         var emails = ctx.Emails.Where(e => e.Status < EmailStatus.FAIL);
         var client = CreateSmtpClient();
         foreach (var email in emails)
         {
             var mailMsg = CreateMailMessage(email);
             try
             {
                 client.Send(mailMsg);
                 email.Status = EmailStatus.SUCCESS;
             }
             catch (Exception e)
             {
                 email.Status++;
             }
             ctx.SaveChanges();
         }
     }
 }
Пример #14
0
 /// <summary>
 /// 院管理员和院管理员下载打包后的申请书的PDF文档
 /// </summary>
 /// <param name="instId"></param>
 /// <param name="projectTypeId"></param>
 /// <param name="ProjectTypeIds"></param>
 /// <param name="status"></param>
 /// <param name="packageName"></param>
 /// <returns></returns>
 public HttpResponseMessage DeptDownloadApplicationPackage(int instId, int projectTypeId, int?[] ProjectTypeIds, ApplicationStatus status, string packageName)
 {
     string[] applicationDocs = null;
     using (var ctx = new AspodesDB())
     {
         applicationDocs = (from ad in ctx.ApplicationDocs
                            from a in ctx.Applications
                            where a.CurrentYear == SystemConfig.ApplicationStartYear && //本年度的
                            (instId == 0 || a.InstituteId == instId) && //单位的
                            a.Status == status &&
                            ((projectTypeId == 0 && ProjectTypeIds.Contains(a.ProjectTypeId)) || (ProjectTypeIds.Contains(a.ProjectTypeId) && (projectTypeId == a.ProjectTypeId))) &&
                            ad.ApplicationId == a.ApplicationId &&
                            ad.Type == ApplicationDocType.PDF     //格式为pdf
                            select ad.RelativeURL).ToArray();
     }
     if (applicationDocs == null || applicationDocs.Length == 0)
     {
         return(ResponseWrapper.SuccessResponse("没有要导出的数据"));
     }
     UserHelper.ZipFiles(applicationDocs, SystemConfig.ZipFileAddress, packageName);
     return(FileHelper.Download(HttpContext.Current, SystemConfig.ZipFileAddress + packageName, packageName));
 }
Пример #15
0
        /// <summary>
        /// 获取分页的申请书列表
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public PagingListDTO <GetApplicationDTO> GetPagingApplicationList(Func <Application, bool> predicate, int page)
        {
            PagingListDTO <GetApplicationDTO> pagingList = new PagingListDTO <GetApplicationDTO>();

            using (var ctx = new AspodesDB())
            {
                pagingList.TotalNum     = ctx.Applications.Where(predicate).Count();
                pagingList.TotalPageNum = (pagingList.TotalNum + SystemConfig.ApplicationPageCount - 1) / SystemConfig.ApplicationPageCount;
                if (pagingList.TotalNum <= 0)
                {
                    pagingList.TotalPageNum = 1;
                }

                pagingList.NowPage = page <= 0 ? 1 : page;

                var applications = ctx.Applications
                                   .Where(predicate)
                                   .OrderByDescending(a => a.EditTime)
                                   .Skip((pagingList.NowPage - 1) * SystemConfig.ApplicationPageCount)
                                   .Take(SystemConfig.ApplicationPageCount);

                //如果不需要PDF预览功能,删除下面的循环
                foreach (var application in applications)
                {
                    var applicationDTO = Mapper.Map <GetApplicationDTO>(application);
                    var pdf            = ctx.ApplicationDocs.FirstOrDefault(ad => ad.ApplicationId == application.ApplicationId && ad.Type == ApplicationDocType.PDF);
                    if (pdf != null)
                    {
                        applicationDTO.PDF = pdf.RelativeURL.Replace("~", "");
                    }
                    pagingList.ItemDTOs.Add(applicationDTO);
                }

                pagingList.NowNum = pagingList.ItemDTOs.Count();
            }

            return(pagingList);
        }
Пример #16
0
        public void CreateApplicationPDF(string applicationId)
        {
            using (var ctx = new AspodesDB())
            {
                //取出申请书信息
                Application application = ctx.Applications.FirstOrDefault(a => a.ApplicationId == applicationId);
                if (null == application)
                {
                    throw new NotFoundException("未找到申请书");
                }

                //生成申请书PDF文档
                var body   = ctx.ApplicationDocs.FirstOrDefault(ad => ad.ApplicationId == application.ApplicationId && ad.Type == ApplicationDocType.BODY);
                var oldPdf = ctx.ApplicationDocs.FirstOrDefault(ad => ad.ApplicationId == application.ApplicationId && ad.Type == ApplicationDocType.PDF);
                if (null != oldPdf)
                {
                    ApplicationDocRepository.Delete(oldPdf.ApplicationDocId.Value, (a, u) => true);
                }

                var  pdfName   = body.Name.Replace(".docx", "") + "PDF";
                bool createPDF = PdfHelper.CreatePdf(application.ApplicationId, body.Name, pdfName, SystemConfig.ApplicationStartYear);
                if (!createPDF)
                {
                    throw new OtherException("PDF生成失败");
                }
                //添加PDF文档记录
                ApplicationDoc pdf = new ApplicationDoc()
                {
                    Name          = pdfName + ".pdf",
                    RelativeURL   = body.RelativeURL.Replace(body.Name, pdfName + ".pdf"),
                    Type          = ApplicationDocType.PDF,
                    ApplicationId = applicationId
                };
                ctx.ApplicationDocs.Add(pdf);

                ctx.SaveChanges();
            }
        }
Пример #17
0
        /// <summary>
        /// 系统管理员获取申请书分类
        /// </summary>
        /// <returns></returns>
        public List <SysSupportCategoryGetDTO> GetSupportCategorys()
        {
            List <SysSupportCategoryGetDTO> supportCategoryList = new List <SysSupportCategoryGetDTO>();
            SysSupportCategoryGetDTO        supportCategory;

            using (var db = new AspodesDB())
            {
                var pjdata = db.ProjectTypes.OrderBy(c => c.Name);
                var scdata = db.SupportCategorys;

                foreach (var temp in pjdata)
                {
                    supportCategory      = new SysSupportCategoryGetDTO();
                    supportCategory.Name = temp.Name;
                    supportCategory.SupportCategoryId = temp.ProjectTypeId.Value;
                    supportCategory.Categorys         = scdata.Where(c => c.ProjectTypeId == temp.ProjectTypeId)
                                                        .OrderBy(c => c.Name)
                                                        .ToList();
                    supportCategoryList.Add(supportCategory);
                }
            }
            return(supportCategoryList);
        }
Пример #18
0
 /// <summary>
 /// 添加申请书成员
 /// </summary>
 /// <param name="memberDTO">成员信息</param>
 /// <returns></returns>
 public GetMemberDTO AddMember(AddMemberDTO memberDTO, Func <Application, CurrentUser, bool> privilege)
 {
     using (var ctx = new AspodesDB())
     {
         var application = ctx.Applications.FirstOrDefault(a => a.ApplicationId == memberDTO.ApplicationId);
         if (null == application)
         {
             throw new NotFoundException();
         }
         if (!privilege(application, UserHelper.GetCurrentUser()))
         {
             throw new UnauthorizationException();
         }
         var old = ctx.Members.FirstOrDefault(m => m.ApplicationId == memberDTO.ApplicationId && m.PersonId == memberDTO.PersonId);
         if (old != null)
         {
             throw new OtherException("人员已添加");
         }
         var member = ctx.Members.Add(Mapper.Map <Member>(memberDTO));
         ctx.SaveChanges();
         return(Mapper.Map <GetMemberDTO>(member));
     }
 }
Пример #19
0
 /// <summary>
 /// 根据单位ID获取单位信息
 /// </summary>
 /// <param name="instId">单位ID</param>
 /// <returns>
 /// 成功,返回ResponseStatus.success和单位信息
 /// 未找到数据,返回ResponseStatus.parameter_error
 /// 失败,返回ResponseStatus.unknown_error和错误信息
 /// </returns>
 public GetInstituteDTO GetOneInst(int instId)
 {
     using (var ctx = new AspodesDB())
     {
         var inst = ctx.Institutes.FirstOrDefault(i => i.InstituteId == instId);
         if (inst == null)
         {
             throw new NotFoundException();
         }
         var instDTO = Mapper.Map <GetInstituteDTO>(inst);
         if (inst.ContactId != null)
         {
             var contact = ctx.Users.FirstOrDefault(u => u.UserId == inst.ContactId);
             if (null != contact)
             {
                 instDTO.ContactEmail = contact.UserId;
                 instDTO.ContactName  = contact.Name;
                 instDTO.ContactPhone = contact.Person.Phone;
             }
         }
         return(instDTO);
     }
 }
Пример #20
0
 /// <summary>
 /// 计算所有申请书的初审总分
 /// </summary>
 public static void ReviewCommentTotalScore()
 {
     try
     {
         using (var ctx = new AspodesDB())
         {
             var applications = ctx.Applications.Where(
                 a => a.CurrentYear == SystemConfig.ApplicationStartYear //本年度的
                 //&& a.Status == ApplicationStatus.FINISH_REVIEW//评审完结的申请书
                 );
             foreach (var a in applications)
             {
                 var comments = ctx.ReviwerComments.Where(rc => rc.ApplicationId == a.ApplicationId && rc.Year == SystemConfig.ApplicationStartYear);
                 a.TotalScore = CalculationReviewCommentTotalScore(comments.ToList());
             }
             ctx.SaveChanges();
         }
     }
     catch (Exception e)
     {
         //写日志
     }
 }
Пример #21
0
        /// <summary>
        /// 添加或修改驳回、未受理原因
        /// </summary>
        /// <param name="type">1为未受理、0为驳回</param>
        /// <param name="templateReason">原因</param>
        /// <returns></returns>
        public GetTemplateReasonDTO AddOrUpdateTemplateReason(int type, TemplateReasonDTO templateReason)
        {
            using (var db = new AspodesDB())
            {
                TemplateReason tempReason;
                if (templateReason.ReasonId == -1)
                {
                    //新增
                    tempReason = new TemplateReason();
                }
                else
                {
                    //修改
                    tempReason = db.TemplateReasons
                                 .Where(c => c.Type == type && c.ReasonId == templateReason.ReasonId)
                                 .FirstOrDefault();
                }

                if (null == tempReason)
                {
                    throw new ModelValidException("参数错误,找不到对应的ID");
                }

                tempReason.Type     = type;
                tempReason.Content  = templateReason.ReasonContent;
                tempReason.EditTime = DateTime.Now;
                tempReason.EditorId = HttpContext.Current.User.Identity.Name;

                if (templateReason.ReasonId == -1)
                {
                    db.TemplateReasons.Add(tempReason);
                }

                db.SaveChanges();
                return(Mapper.Map <GetTemplateReasonDTO>(tempReason));
            }
        }
        /// <summary>
        /// 发送专家指派
        /// </summary>
        /// <returns></returns>
        public void SendReviewAssignment()
        {
            using (var ctx = new AspodesDB())
            {
                var userInfo     = UserHelper.GetCurrentUser();
                var applications = ctx.Applications
                                   .Where(a => a.CurrentYear == SystemConfig.ApplicationStartYear &&
                                          a.Status == ApplicationStatus.SEND_ASSIGNMENT &&
                                          userInfo.ProjectTypeIds.Contains(a.ProjectTypeId));

                foreach (var application in applications)
                {
                    //获取今年的指派
                    var assignments = ctx.ReviewAssignments
                                      .Where(ra => ra.ApplicationId == application.ApplicationId && !ra.Overdue.Value && ra.Status != ReviewAssignmentStatus.CHANGE)
                                      .ToList();
                    //删除多余的专家指派
                    if (assignments.Count() > SystemConfig.ApplicationExpertAmount)
                    {
                        var extra = assignments.Skip(SystemConfig.ApplicationExpertAmount).Take(assignments.Count());
                        assignments.RemoveRange(SystemConfig.ApplicationExpertAmount, extra.Count());
                        ctx.ReviewAssignments.RemoveRange(extra);
                    }
                    //修改指派状态
                    foreach (var assignment in assignments)
                    {
                        if (assignment.Status == ReviewAssignmentStatus.NEW)
                        {
                            assignment.Status = ReviewAssignmentStatus.WAITE_REVIEW;
                        }
                    }
                    //修改申请书状态
                    application.Status = ApplicationStatus.REVIEW;
                }
                ctx.SaveChanges();
            }
        }
Пример #23
0
        public List <GetReviewAssignmentDTO> AcceptApplication(string applicationId, Func <Application, bool> privilege)
        {
            var deleagetype = DelegateType.DIRECTIONAL;

            using (var ctx = new AspodesDB())
            {
                var application = ctx.Applications.FirstOrDefault(a => a.ApplicationId == applicationId && a.Status == ApplicationStatus.ACCEPT);
                if (null == application)
                {
                    throw new NotFoundException("未找到申请书或者申请书状态不符合条件");
                }
                if (!privilege(application))
                {
                    throw new UnauthorizationException("当前用没有受理该申请书的权限");
                }
                //定向委托项目直接跳过评审
                if (application.DeleageType == DelegateType.DIRECTIONAL)
                {
                    application.Status = ApplicationStatus.FINISH_REVIEW;
                }
                else
                {
                    deleagetype        = DelegateType.NORMAL;
                    application.Status = SystemConfig.AutoAssignmentExpert ? ApplicationStatus.ASSIGNMENT : ApplicationStatus.MANUAL_ASSIGNMENT;
                }


                ctx.SaveChanges();
            }

            if (SystemConfig.AutoAssignmentExpert && deleagetype != DelegateType.DIRECTIONAL)
            {
                return(new ReviewAssignmentRepository().ApplicationExpertAssignment(applicationId, a => true));
            }

            return(new List <GetReviewAssignmentDTO>());
        }
        /// <summary>
        /// 删除公告附件
        /// </summary>
        /// <param name="announcementAttachmentId">公告附件ID</param>
        /// <returns></returns>
        public void Delete(int announcementAttachmentId)
        {
            AnnouncementAttachment aa = null;
            string path = "";

            using (var ctx = new AspodesDB())
            {
                aa = ctx.AnnouncementAttachments.FirstOrDefault(an => an.AnnouncementAttachmentId == announcementAttachmentId);
                if (null == aa)
                {
                    throw new NotFoundException("未找到公告");
                }

                //获取绝对路径
                string relative = aa.RelativeURL.Replace("~", "").Replace("/", @"\");
                if (relative.StartsWith(@"\"))
                {
                    relative = relative.Substring(1);
                }
                path = Path.Combine(HttpRuntime.AppDomainAppPath, relative);
                ctx.AnnouncementAttachments.Remove(aa);
                ctx.SaveChanges();
            }
        }
Пример #25
0
        /// <summary>
        /// 单位管理员更改单位信息
        /// </summary>
        /// <param name="instDTO">更新的单位信息</param>
        /// <returns></returns>
        public GetInstituteDTO UpdateInstitute(AddInstituteDTO instDTO, Func <Institute, bool> privilege)
        {
            var newValue = Mapper.Map <Institute>(instDTO);

            using (var ctx = new AspodesDB())
            {
                var inst = ctx.Institutes.FirstOrDefault(i => i.InstituteId == instDTO.InstituteId);
                if (null == inst)
                {
                    throw new NotFoundException();
                }
                if (!privilege(inst))
                {
                    throw new UnauthorizationException();
                }
                //不允许在Update时更改的值
                newValue.Status   = inst.Status;
                newValue.ParentId = inst.ParentId;

                ctx.Entry(inst).CurrentValues.SetValues(newValue);
                ctx.SaveChanges();
                return(Mapper.Map <GetInstituteDTO>(inst));
            }
        }
Пример #26
0
        private Person AddPerson(AspodesDB ctx, Person person)
        {
            ctx.Persons.Add(person);
            ctx.SaveChanges();
            Person    newPerson  = ctx.Persons.Where(c => c.IDCard == person.IDCard && c.Email == person.Email).First();
            Institute personInst = ctx.Institutes.Where(c => c.InstituteId == newPerson.InstituteId).First();

            if (personInst.Type != InstituteType.PARTNER)   //添加外单位人员,不需要建立用户
            {
                //添加用户
                User user    = Mapper.Map <User>(newPerson);
                User newUser = ctx.Users.Add(user);
                //添加用户角色
                Model.Authorize authorize = new Model.Authorize()
                {
                    UserId = newUser.UserId,
                    RoleId = 1
                };
                ctx.Authorizes.Add(authorize);
                ctx.SaveChanges();
            }

            return(newPerson);
        }
Пример #27
0
        /// <summary>
        /// 开启第year年度的申请
        /// </summary>
        /// <param name="year">申请年度</param>
        public void StartApplication(int year)
        {
            if (year <= 0 || SystemConfig.ApplicationStartYear >= year)
            {
                throw new OtherException("请年度不合法或者已经使用");
            }

            using (var db = new AspodesDB())
            {
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        //添加修改记录
                        SysSettingHistory setings = new SysSettingHistory();
                        setings.ApplicationStartYear = SystemConfig.ApplicationStartYear;
                        setings.UpdateTime           = DateTime.Now;
                        setings.UpdateId             = HttpContext.Current.User.Identity.Name;
                        setings.UpdateIp             = HttpContext.Current.Request.UserHostAddress;
                        db.SysSettingHistorys.Add(setings);

                        //重置一些字段
                        string resetProjectTypeLimit     = "update ProjectTypes set Limit=0;";
                        string resetExpertReviewAmount   = "update [User] set ReviewAmount=0;";
                        string setRevewAssignmentOverdue = "update ReviewAssignment set Overdue=1 where Overdue = 0;";

                        db.Database.ExecuteSqlCommand(resetProjectTypeLimit);
                        db.Database.ExecuteSqlCommand(resetExpertReviewAmount);
                        db.Database.ExecuteSqlCommand(setRevewAssignmentOverdue);

                        //修改配置文件
                        Configuration      config     = WebConfigurationManager.OpenWebConfiguration("~/");
                        AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
                        appSection.Settings["ApplicationStartYear"].Value = year.ToString();
                        config.Save();

                        //删除临时文件
                        //删除压缩的临时文件
                        DirectoryInfo subdir = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemConfig.DeleteZipFileAddress));
                        if (subdir.Exists)
                        {
                            subdir.Delete(true);
                            subdir.Create();
                        }
                        subdir = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemConfig.ExportExcel));
                        if (subdir.Exists)
                        {
                            subdir.Delete(true);
                            subdir.Create();
                        }

                        transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        transaction.Rollback();
                        throw e;
                    }
                }
            }
        }
Пример #28
0
        /// <summary>
        /// 添加评审结果
        /// </summary>
        /// <param name="ReviewCommentDTO">评审结果信息</param>
        /// <returns>
        /// 添加成功,返回ResponseStatus.success
        /// 失败,返回ResponseStatus.unknown_error和错误信息
        /// </returns>
        public GetReviewCommentDTO AddOrUpdateReviewComment(AddReviewCommentDTO dto, Func <ReviewAssignment, bool> privilege)
        {
            using (var ctx = new AspodesDB())
            {
                //权限验证
                var assignment = ctx.ReviewAssignments.FirstOrDefault(ra => ra.ReviewAssignmentId == dto.ReviewAssignmentId);
                if (null == assignment)
                {
                    throw new NotFoundException();
                }
                if (assignment.Overdue.Value)
                {
                    throw new OtherException("不允许执行操作");
                }
                if (!privilege(assignment))
                {
                    throw new UnauthorizationException();
                }


                //补全信息
                var newComment = Mapper.Map <ReviewComment>(dto);
                newComment.ExpertId        = assignment.ExpertId;
                newComment.ApplicationId   = assignment.ApplicationId;
                newComment.Status          = ReviwerCommentStatus.SAVE;
                newComment.Year            = SystemConfig.ApplicationStartYear;
                newComment.ReviewCommentId = null;
                //添加或者更改
                var oldComment  = ctx.ReviwerComments.FirstOrDefault(rc => rc.ReviewAssignmentId == dto.ReviewAssignmentId);
                var transaction = ctx.Database.BeginTransaction();
                try
                {
                    if (null == oldComment)
                    {
                        newComment.Status = ReviwerCommentStatus.SAVE;
                        ctx.ReviwerComments.Add(newComment);
                        assignment.Status = ReviewAssignmentStatus.ALREADY_REVIEW;
                        ctx.SaveChanges();

                        bool reviewFinish = ctx.ReviewAssignments
                                            .Where(ra => ra.ApplicationId == assignment.ApplicationId && !ra.Overdue.Value && ra.Status != ReviewAssignmentStatus.CHANGE && ra.Status != ReviewAssignmentStatus.REFUSE)
                                            .All(ra => ra.Status == Model.ReviewAssignmentStatus.ALREADY_REVIEW);
                        if (reviewFinish)
                        {
                            assignment.Application.Status = Model.ApplicationStatus.FINISH_REVIEW;
                        }
                    }
                    else
                    {
                        //检查是否允许更改

                        //不允许更改的字段
                        newComment.ReviewCommentId = oldComment.ReviewCommentId;
                        newComment.Status          = oldComment.Status;
                        newComment.ExpertId        = oldComment.ExpertId;
                        newComment.ApplicationId   = oldComment.ApplicationId;
                        //更新
                        ctx.Entry(oldComment).CurrentValues.SetValues(newComment);
                    }

                    ctx.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    throw e;
                }

                return(Mapper.Map <GetReviewCommentDTO>(newComment));
            }
        }
Пример #29
0
        public HttpResponseMessage Post(LoginDTO dto)
        {
            try
            {
                using (AspodesDB _context = new AspodesDB())
                {
                    string pwd = HashHelper.IntoMd5(dto.Password);
                    //User user = _context.Users.FirstOrDefault(u => u.UserId == dto.Username && u.Password == pwd && u.Person.Status != "D");

                    //20170114 为演示方便,更改登录验证为 EnglishName 登录(英文名默认为汉字转拼音)
                    string username = dto.Username.ToLower().Replace("@qq.com", "").ToUpper();
                    User   user     = _context.Users.FirstOrDefault(u => (u.Person.EnglishName == username || u.UserId == dto.Username) && u.Password == pwd && u.Person.Status != "D");

                    if (null == user)
                    {
                        return(ResponseWrapper.ExceptionResponse(new OtherException("用户名或密码错误!")));
                    }
                    var roles = (from r in _context.Roles
                                 join a in _context.Authorizes
                                 on r.RoleId equals a.RoleId
                                 join u in _context.Users
                                 on a.UserId equals u.UserId
                                 where u.UserId == user.UserId
                                 select r.Name).ToArray();

                    LoginData ld = new LoginData();
                    ld.UserId        = user.UserId;
                    ld.UserName      = user.Name;
                    ld.UserTimeStamp = HashHelper.GetTimestamp();
                    ld.Roles         = roles;

                    if (user.Person.PersonId.HasValue)
                    {
                        ld.PersonId = user.Person.PersonId.Value;
                    }
                    else
                    {
                        ld.PersonId = 0;
                    }

                    LoginLog log = new LoginLog();
                    log.LoginLogId     = Guid.NewGuid().ToString();
                    log.UserId         = user.UserId;
                    log.Roles          = string.Join(",", roles);;
                    log.LoginIP        = Helper.GetClientIpAddress(Request);
                    log.LoginTime      = DateTime.Now;
                    log.LastActiveTime = DateTime.Now;
                    log.IsLogout       = false;
                    log.LoginTimeStamp = HashHelper.GetTimestamp(DateTime.Now.AddMinutes(HashHelper.LoginDuration));
                    log.Token          = HashHelper.Encrypt(JsonConvert.SerializeObject(ld));
                    ld.Token           = log.Token;

                    _context.LoginLogs.Add(log);

                    _context.SaveChanges();

                    CurrentUser current = new CurrentUser
                    {
                        UserId   = user.UserId,
                        PersonId = user.PersonId.Value,
                        InstId   = user.Person.InstituteId.Value,
                        Name     = user.Name,
                        Roles    = roles
                    };
                    if (roles.Contains("院管理员"))
                    {
                        var projectTypes = from aa in _context.ApplicationAssignments where aa.UserId == user.UserId select aa.ProjectTypeId;
                        current.ProjectTypeIds = projectTypes.ToArray();
                    }

                    var cookie = new HttpCookie("user", UserHelper.SerializeUserInfo(current));
                    HttpContext.Current.Response.AppendCookie(cookie);

                    return(ResponseWrapper.SuccessResponse(ld));
                }
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                }
                return(ResponseWrapper.ExceptionResponse(new OtherException("数据库连接错误")));
            }
            catch (Exception e)
            {
                var a = e.Message;
                return(ResponseWrapper.ExceptionResponse(e));
            }
        }
Пример #30
0
        /// <summary>
        /// 导出初审结果
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="count"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public HttpResponseMessage ExportReviewComment(Func <Application, bool> predicate, int count, string userName)
        {
            string relativePath = "";
            //string userName = UserHepler.GetCurrentUser().Name;
            FileStream writeStream = null;
            IWorkbook  workbook    = null;

            try
            {
                List <string> projectTypes = null;
                List <GetApplicationReviewCommentDTO> applications = new List <GetApplicationReviewCommentDTO>();
                using (var ctx = new AspodesDB())
                {
                    if (count <= 0)
                    {
                        count = ctx.Applications.Count(predicate);
                    }
                    //筛选出需要导出的数据
                    applications = ctx.Applications.Include("ReviewComments")
                                   .Where(predicate)
                                   .Select(Mapper.Map <GetApplicationReviewCommentDTO>)
                                   .Take(count)
                                   .OrderByDescending(a => a.TotalScore)
                                   .ToList();

                    projectTypes = ctx.ProjectTypes.Select(pt => pt.Name).ToList();
                }

                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemConfig.ExportReviewCommentExcelTemplate);
                workbook = WorkbookFactory.Create(path);

                //设置单元格样式
                ICellStyle style = workbook.CreateCellStyle();
                style.Alignment         = HorizontalAlignment.General;
                style.VerticalAlignment = VerticalAlignment.Center;

                //取出标题行
                ISheet titleSheet = workbook.GetSheetAt(0);
                IRow   titleRow   = titleSheet.GetRow(0);
                int    columns    = titleRow.Cells.Count;

                foreach (var type in projectTypes)
                {
                    //按项目类型取出数据
                    var typeApplications = applications
                                           .Where(a => type.Equals(a.ProjectTypeName))
                                           .OrderByDescending(a => a.TotalScore);

                    if (typeApplications.Count() == 0)
                    {
                        continue;
                    }


                    //应用单元格样式
                    ISheet sheet = workbook.CreateSheet(type);
                    for (int i = 0; i < columns; i++)
                    {
                        sheet.SetDefaultColumnStyle(i, style);
                    }

                    //复制标题行
                    IRow firstRow = sheet.CreateRow(0);
                    CopyRow(titleRow, firstRow);

                    //插入数据
                    int insertRowIndex = 1;
                    for (int i = 0; i < typeApplications.Count(); i++)
                    {
                        var  applicationComments = typeApplications.ElementAt(i);
                        IRow row      = sheet.CreateRow(insertRowIndex);
                        int  areaRows = applicationComments.ReviewComments.Count();
                        if (areaRows <= 0)
                        {
                            continue;
                        }
                        if (!applicationComments.TotalScore.HasValue)
                        {
                            return(ResponseWrapper.ExceptionResponse(new OtherException("请先手动计算总分后再导出数据")));
                        }
                        SetMergedRegion(row, applicationComments.ProjectName, new CellRangeAddress(insertRowIndex, insertRowIndex + areaRows - 1, 0, 0));
                        SetMergedRegion(row, applicationComments.ApplicationId, new CellRangeAddress(insertRowIndex, insertRowIndex + areaRows - 1, 1, 1));
                        SetMergedRegion(row, applicationComments.ProjectTypeName, new CellRangeAddress(insertRowIndex, insertRowIndex + areaRows - 1, 2, 2));
                        SetMergedRegion(row, applicationComments.InstituteName, new CellRangeAddress(insertRowIndex, insertRowIndex + areaRows - 1, 3, 3));
                        SetMergedRegion(row, applicationComments.LeaderName, new CellRangeAddress(insertRowIndex, insertRowIndex + areaRows - 1, 4, 4));
                        SetMergedRegion(row, applicationComments.TotalBudget.Value, new CellRangeAddress(insertRowIndex, insertRowIndex + areaRows - 1, 5, 5));
                        SetMergedRegion(row, applicationComments.FirstYearBudget.Value, new CellRangeAddress(insertRowIndex, insertRowIndex + areaRows - 1, 6, 6));
                        SetMergedRegion(row, applicationComments.Period.Value, new CellRangeAddress(insertRowIndex, insertRowIndex + areaRows - 1, 7, 7));
                        SetMergedRegion(row, applicationComments.TotalScore.Value, new CellRangeAddress(insertRowIndex, insertRowIndex + areaRows - 1, 8, 8));
                        SetMergedRegion(row, (i + 1), new CellRangeAddress(insertRowIndex, insertRowIndex + areaRows - 1, 9, 9));

                        for (int j = 0; j < areaRows; j++)
                        {
                            var  comment    = applicationComments.ReviewComments.ElementAt(j);
                            IRow commentRow = sheet.GetRow(insertRowIndex + j);
                            if (commentRow == null)
                            {
                                commentRow = sheet.CreateRow(insertRowIndex + j);
                            }
                            SetCell(commentRow, "第" + (j + 1) + "位专家", 10);
                            SetCell(commentRow, comment.Level, 11);
                            SetCell(commentRow, comment.Imburse, 12);
                            SetCell(commentRow, comment.Comment, 13);
                        }

                        insertRowIndex += areaRows;
                    }
                    //sheet.SetColumnHidden(2, false);
                }

                //删除标题Sheet页
                if (workbook.NumberOfSheets > 1)
                {
                    workbook.RemoveSheetAt(0);
                }

                //保存数据
                string filename = userName + DateTime.Now.ToFileTime() + ".xls";
                relativePath = Path.Combine(SystemConfig.ExportReviewCommentPath, filename);
                string savePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemConfig.ExportReviewCommentPath, filename);
                writeStream = File.Create(savePath);
                workbook.Write(writeStream);
                writeStream.Flush();
            }
            catch (Exception e)
            {
                return(ResponseWrapper.ExceptionResponse(e));
            }
            finally
            {
                if (null != writeStream)
                {
                    writeStream.Close();
                    writeStream.Dispose();
                }
                if (null != workbook)
                {
                    workbook.Close();
                }
            }

            return(FileHelper.Download(HttpContext.Current, "\\" + relativePath, SystemConfig.ApplicationStartYear + ".xls"));
        }