public FtpService(ILogger <FtpService> logger, IFapConfigService configService) { _logger = logger; _configService = configService; host = _configService.GetSysParamValue("ftp.path"); username = _configService.GetSysParamValue("ftp.username"); password = _configService.GetSysParamValue("ftp.password"); ftpRootPath = _configService.GetSysParamValue("ftp.directory.root"); }
/// <summary> /// 获取文件存放路径 /// </summary> /// <returns></returns> private string GetFilePath() { string path = _configService.GetSysParamValue("file.directory.path"); if (path.IsPresent()) { if (path.Contains("\\") || path.Contains("/")) { path = path.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar); } } return(path); }
///// <summary> ///// 获取当前文件服务的类型, 默认是数据库 ///// </summary> ///// <returns></returns> //public string GetCurrentFileServiceType() //{ // string type = FILESERVICE_DATABASE; // object obj = FapPlatformConfig.PlatformProperties["system.fileservice.type"]; // if (obj != null) // { // type = obj.ToString(); // } // return type; //} /// <summary> /// 获取文件服务对象 /// </summary> /// <param name="fileServiceType"></param> /// <returns></returns> IFileService GetFileService() { if (_fileService == null) { if (_fileServiceType.IsMissing()) { _fileServiceType = _configService.GetSysParamValue("system.fileservice.type"); } if (_fileServiceType.Equals(FapFileService.FILESERVICE_FILE, StringComparison.CurrentCultureIgnoreCase)) { ILogger <FileDirectoryService> log = _logger.CreateLogger <FileDirectoryService>(); _fileService = new FileDirectoryService(_dataAccessor, log, _configService); } else if (_fileServiceType.Equals(FapFileService.FILESERVICE_FTP, StringComparison.CurrentCultureIgnoreCase)) { ILogger <FtpService> log = _logger.CreateLogger <FtpService>(); _fileService = new FtpService(log, _configService); } else if (_fileServiceType.Equals(FapFileService.FILESERVICE_DATABASE, StringComparison.CurrentCultureIgnoreCase)) { _fileService = new DatabaseService(_dataAccessor); } if (_fileService == null) //默认是数据库 { _fileService = new DatabaseService(_dataAccessor); _fileServiceType = FILESERVICE_DATABASE; } } return(_fileService); }
/// <summary> /// 获取管辖的部门 /// </summary> /// <returns></returns> public IEnumerable <OrgDept> GetDominationDepartment() { var param = new Dapper.DynamicParameters(new { _applicationContext.EmpUid }); var deptList = _dbContext.QueryWhere <OrgDept>("DeptManager=@EmpUid", param); string director = _configService.GetSysParamValue("org.permissions.director"); if (director.ToBool()) { deptList = deptList.Concat(_dbContext.QueryWhere <OrgDept>("Director=@EmpUid", param)); } IEnumerable <OrgDept> dominations = Enumerable.Empty <OrgDept>(); foreach (var dept in deptList) { dominations = dominations.Concat(_platformDomain.OrgDeptSet.Where(d => d.DeptCode.StartsWith(dept.DeptCode, StringComparison.OrdinalIgnoreCase))); } return(dominations.Distinct(new FapModelEqualityComparer <OrgDept>())); }
public bool ResetPasswor(IList <string> Uids) { string password = _configService.GetSysParamValue("employee.user.password"); if (password.IsMissing()) { password = "******"; } PasswordHasher pwdHasher = new PasswordHasher(); password = pwdHasher.HashPassword(password); int r = _dbContext.Execute("update FapUser set UserPassword=@Pwd where Fid in @Fids", new DynamicParameters(new { Pwd = password, Fids = Uids })); return(r > 0 ? true : false); }
public bool Upload(Stream stream, FapFileInfo fileInfo, FileUploadEventHandler updateEvent) { if (fileInfo == null || stream == null) { return(false); } FtpStrategy strategy = new FtpStrategy(); string lv = _configService.GetSysParamValue("ftp.directory.level"); if (lv.IsPresent()) { strategy.Level = lv.ToInt(); } else { strategy.Level = 3; } string fileName = ""; string directoryPath = strategy.GetFullPath("" + fileInfo.FileId, out fileName); string destPath_to_save = Path.Combine(ftpRootPath, directoryPath); string filePath_to_save = Path.Combine(destPath_to_save, fileName + fileInfo.FileSuffix); try { using (FtpClient conn = new FtpClient()) { conn.Host = host; conn.Credentials = new NetworkCredential(username, password); conn.Connect(); if (!conn.DirectoryExists(destPath_to_save)) { conn.CreateDirectory(destPath_to_save); } using (Stream outStream = conn.OpenWrite(filePath_to_save)) { using (var inStream = stream) { stream.CopyTo(outStream); if (updateEvent != null) { updateEvent(fileInfo, new FileUploadEventArgs() { Total = inStream.Length, Uploaded = inStream.Length, FileFullName = Path.Combine(directoryPath, fileName + fileInfo.FileSuffix), FileName = fileName + fileInfo.FileSuffix, FileDirectory = directoryPath }); } } } } return(true); } catch (Exception ex) { _logger.LogError(ex.Message); } return(false); }
public void AutoSendMail() { string account = _configService.GetSysParamValue(FapPlatformConstants.MailAccount); string password = _configService.GetSysParamValue(FapPlatformConstants.MailPassword); string server = _configService.GetSysParamValue(FapPlatformConstants.MailServer); int? port = _configService.GetSysParamValue(FapPlatformConstants.MailPort).ToInt(); string accountName = _configService.GetSysParamValue(FapPlatformConstants.MailAccountName); MailKitOptions mailOption = new MailKitOptions() { Account = account, Password = password, Port = (int)port, Server = server, SenderEmail = account, SenderName = accountName }; IEmailService service = new EmailService(new MailKitProvider(mailOption)); try { SendEmail(); } catch (Exception ex) { _logger.LogError($"任务调度 邮件发送异常信息:{ex.Message}"); } void SendEmail() { //未发送或发送次数小于5,注:可能发送失败,每次发送次数会增加 IEnumerable <FapMail> listMails = _dataAccessor.Query <FapMail>($"select * from FapMail where SendStatus=0 and SendCount<5"); if (listMails == null || listMails.Count() < 1) { _logger.LogInformation("无邮件可发"); return; } //招聘相关的特殊处理 var rcrtMails = listMails.Where <FapMail>(m => m.MailCategory == "招聘相关"); IEnumerable <dynamic> rcrtEmailAddress = new List <dynamic>(); if (rcrtMails != null && rcrtMails.Count() > 0) { rcrtEmailAddress = _dataAccessor.Query("select * from RcrtMail where Enabled=1"); } foreach (FapMail mail in listMails) { if (mail.RecipientEmailAddress.IsMissing()) { mail.SendCount = 5; mail.Failures = "收件人为空"; _dataAccessor.Update <FapMail>(mail); continue; } //预计发送时间 if (mail.PreSendTime.IsPresent()) { DateTime pre = Convert.ToDateTime(mail.PreSendTime); //不到预计时间不发送 if (pre > DateTime.Now) { continue; } } List <AttachmentInfo> listAtts = new List <AttachmentInfo>(); var attachemts = _fileService.FileList(mail.Attachment); if (attachemts != null && attachemts.Any()) { foreach (var att in attachemts) { listAtts.Add(new AttachmentInfo { ContentType = att.FileType, UniqueId = att.Id.ToString(), FileName = att.FileName, Stream = _fileService.GetFileStream(att) }); } } string[] arryRec = mail.RecipientEmailAddress.Split(';'); string failMsg = string.Empty; //是否分别发送,分别发送的情况下 就没有抄送和密送 if (mail.IsSeparate == 1) { if (arryRec != null && arryRec.Length > 0) { foreach (string rec in arryRec) { string emailAddr = rec.Trim(); if (emailAddr.IsPresent()) { try { //招聘的特殊处理 if (mail.MailCategory == "招聘相关" && mail.SenderEmailAddress.IsPresent()) { var rcrtMail = rcrtEmailAddress.FirstOrDefault(m => m.Account == mail.SenderEmailAddress); if (rcrtMail != null) { try { MailKitOptions rcrtMailOption = new MailKitOptions() { Account = rcrtMail.Account, Password = rcrtMail.Password, Port = Convert.ToInt32(rcrtMail.SmtpPort), Server = rcrtMail.Smtp, SenderEmail = rcrtMail.Account, SenderName = "招聘负责人" }; IEmailService mailService = new EmailService(new MailKitProvider(rcrtMailOption)); mailService.Send(emailAddr, mail.Subject, mail.MailContent, MimeKit.Text.TextFormat.Html, listAtts); } catch (Exception ex) { failMsg += $"{ex.Message}"; _logger.LogError($"招聘相关 邮件发送失败:{ex.Message}"); } _logger.LogInformation("招聘相关 任务调度,定时执行 发送邮件 成功=====>" + mail.Fid); } } else { try { service.Send(emailAddr, mail.Subject, mail.MailContent, MimeKit.Text.TextFormat.Html, listAtts); } catch (Exception ex) { failMsg += $"{ex.Message}"; _logger.LogError($"邮件发送失败:{ex.Message}"); } _logger.LogInformation("任务调度,定时执行 发送邮件 成功=====>" + mail.Fid); } } catch (Exception ex) { _logger.LogError($"分割发送邮件异常,邮件地址:{rec + ex.Message}"); continue; } } } } } else { if (mail.MailCategory == "招聘相关" && mail.SenderEmailAddress.IsPresent()) { var rcrtMail = rcrtEmailAddress.FirstOrDefault(m => m.Account == mail.SenderEmailAddress); if (rcrtMail != null) { try { MailKitOptions rcrtMailOption = new MailKitOptions() { Account = rcrtMail.Account, Password = rcrtMail.Password, Port = Convert.ToInt32(rcrtMail.SmtpPort), Server = rcrtMail.Smtp, SenderEmail = rcrtMail.Account, SenderName = "招聘负责人" }; IEmailService mailService = new EmailService(new MailKitProvider(rcrtMailOption)); mailService.Send(mail.RecipientEmailAddress, mail.CCEmailAddress, mail.BCCEmailAddress, mail.Subject, mail.MailContent, TextFormat.Html, listAtts); } catch (Exception ex) { failMsg += $"{ex.Message}"; _logger.LogError($"招聘相关 合并发送邮件发送失败:{ex.Message}"); } _logger.LogInformation("招聘相关 任务调度,定时执行 发送邮件 成功=====>" + mail.Fid); } else { try { service.Send(mail.RecipientEmailAddress, mail.CCEmailAddress, mail.BCCEmailAddress, mail.Subject, mail.MailContent, TextFormat.Html, listAtts); } catch (Exception ex) { failMsg += $"{ex.Message}"; _logger.LogError($"招聘相关 合并发送邮件发送失败:{ex.Message}"); } _logger.LogInformation("招聘相关 任务调度,定时执行 发送邮件 成功=====>" + mail.Fid); } } else { try { service.Send(mail.RecipientEmailAddress, mail.CCEmailAddress, mail.BCCEmailAddress, mail.Subject, mail.MailContent, TextFormat.Html, listAtts); } catch (Exception ex) { failMsg += $"{ex.Message}"; _logger.LogError($" 合并发送邮件发送失败:{ex.Message}"); } _logger.LogInformation(" 任务调度,定时执行 发送邮件 成功=====>" + mail.Fid); } } if (failMsg.IsPresent()) { mail.SendCount += 1; mail.SendStatus = 1; mail.Failures = failMsg; _dataAccessor.Update <FapMail>(mail); } else { mail.SendStatus = 1; mail.SendCount += 1; _dataAccessor.Update <FapMail>(mail); } } } }
public void DayResultCalculate() { //获取当前月考勤周期的排班 var currPeriod = GetCurrentPeriod(); string startDate = currPeriod.StartDate; string endDate = currPeriod.EndDate; //初始化当月日结果数据通过排班 InitDayResultBySchedule(); //此时间段日结果 string sWhere = $"{nameof(TmDayResult.CurrDate)}>=@StartDate and {nameof(TmDayResult.CurrDate)}<=@EndDate"; var param = new DynamicParameters(new { StartDate = startDate, EndDate = DateTimeUtils.CurrentDateStr }); var dayResults = _dbContext.QueryWhere <TmDayResult>(sWhere, param); //更新打卡数据到日结果 UpdateCardRecordToDayResult(); UpdateTravelAndLeaveToDayResult(); //计算日结果 foreach (var dayResult in dayResults) { //无请假出差 if (dayResult.TravelType.IsMissing() && dayResult.LeavelType.IsMissing()) { //计算打卡 CalculateCardRecord(dayResult); } else { //计算出差和请假 CalculateTravelAndLeavel(dayResult); } } _dbContext.UpdateBatchSql(dayResults); //日结果计算后事件 string afterSql = _configService.GetSysParamValue("AfterDayResultCalculate"); if (afterSql.IsPresent()) { List <string> sqls = afterSql.SplitSemicolon(); foreach (var sql in sqls) { if (sql.IsPresent()) { _dbContext.Execute(sql + " and " + sWhere, param); } } } void CalculateTravelAndLeavel(TmDayResult dayResult) { string calResult = string.Empty; if (dayResult.TravelType.IsPresent()) { calResult = DayResultEnum.Travel.Description(); if (dayResult.TravelHours != dayResult.WorkHoursLength) { calResult += $"{dayResult.TravelHours}小时"; } } if (dayResult.LeavelType.IsPresent()) { calResult = DayResultEnum.TakeLeave.Description(); if (dayResult.LeavelHours != dayResult.WorkHoursLength) { calResult += $"{dayResult.LeavelHours}小时"; } } double abs = dayResult.WorkHoursLength - dayResult.LeavelHours - dayResult.TravelHours - dayResult.StWorkHourLength; if (abs > 0) { calResult += (DayResultEnum.Absence.Description() + $"{Math.Round(abs, 2)}小时"); } } void CalculateCardRecord(TmDayResult dayResult) { //存在实际工作时长 if (dayResult.StWorkHourLength > 0) { if (DateTimeUtils.ToDateTime(dayResult.CardStartTime) > DateTimeUtils.ToDateTime(dayResult.LateTime) && DateTimeUtils.ToDateTime(dayResult.CardEndTime) > DateTimeUtils.ToDateTime(dayResult.EndTime)) { //早打卡迟到且晚打卡大于下班时间 dayResult.CalResult = DayResultEnum.ComeLate.Description(); } if (DateTimeUtils.ToDateTime(dayResult.CardEndTime) < DateTimeUtils.ToDateTime(dayResult.LeaveTime) && DateTimeUtils.ToDateTime(dayResult.CardStartTime) < DateTimeUtils.ToDateTime(dayResult.StartTime)) { //早打卡正常,晚打卡早于早退时间 dayResult.CalResult = DayResultEnum.LeaveEarly.Description(); } if (DateTimeUtils.ToDateTime(dayResult.CardStartTime) > DateTimeUtils.ToDateTime(dayResult.LateTime) && DateTimeUtils.ToDateTime(dayResult.CardEndTime) < DateTimeUtils.ToDateTime(dayResult.LeaveTime)) { //迟到早退 dayResult.CalResult = DayResultEnum.ComeLate.Description() + DayResultEnum.LeaveEarly.Description(); } //实际工作时长>工作时长,且无迟到早退 if (dayResult.StWorkHourLength >= dayResult.WorkHoursLength) { if (dayResult.CalResult.IsMissing()) { dayResult.CalResult = DayResultEnum.Normal.Description(); } } else if (dayResult.StWorkHourLength < dayResult.WorkHoursLength) { dayResult.CalResult = DayResultEnum.Absence.Description() + $"{Math.Round(dayResult.WorkHoursLength - dayResult.StWorkHourLength, 2)}小时"; } } else { dayResult.CalResult = DayResultEnum.Absence.Description(); } } void UpdateCardRecordToDayResult() { //此时间段(+-1天)所有打卡记录,存在跨天情况 var cardRecords = _dbContext.QueryWhere <TmCardRecord>($"{nameof(TmCardRecord.CardTime)}>=@StartDate and {nameof(TmCardRecord.CardTime)}<=@EndDate" , new DynamicParameters(new { StartDate = DateTimeUtils.DateTimeFormat(DateTimeUtils.ToDateTime(startDate).AddDays(-1)), EndDate = DateTimeUtils.DateTimeFormat(DateTimeUtils.ToDateTime(endDate).AddDays(1)) })); if (!cardRecords.Any()) { return; } foreach (var dayResult in dayResults) { //当前日结果中考勤打卡集合 var cardTimes = cardRecords.Where(c => c.EmpUid == dayResult.EmpUid && DateTimeUtils.ToDateTime(c.CardTime) >= DateTimeUtils.ToDateTime(dayResult.StartCardTime) && DateTimeUtils.ToDateTime(c.CardTime) <= DateTimeUtils.ToDateTime(dayResult.EndCardTime)); if (cardTimes.Any()) { dayResult.CardStartTime = cardTimes.Min(c => c.CardTime); dayResult.CardEndTime = cardTimes.Max(c => c.CardTime); if (dayResult.CardStartTime == dayResult.CardEndTime) { dayResult.StWorkHourLength = 0; } else { dayResult.StWorkHourLength = Math.Round(DateTimeUtils.ToDateTime(dayResult.CardEndTime).Subtract(DateTimeUtils.ToDateTime(dayResult.CardStartTime)).TotalHours - Math.Round(dayResult.RestMinutesLength / 60.0, 2), 2); } } } } void UpdateTravelAndLeaveToDayResult() { var travelStatList = _dbContext.QueryWhere <TmTravelStat>($"{nameof(TmTravelStat.WorkDate)}>=@StartDate and {nameof(TmTravelStat.WorkDate)}<=@EndDate" , new DynamicParameters(new { StartDate = DateTimeUtils.DateTimeFormat(DateTimeUtils.ToDateTime(startDate).AddDays(-1)), EndDate = DateTimeUtils.DateTimeFormat(DateTimeUtils.ToDateTime(endDate).AddDays(1)) })); var leaveStatList = _dbContext.QueryWhere <TmLeaveStat>($"{nameof(TmLeaveStat.WorkDate)}>=@StartDate and {nameof(TmLeaveStat.WorkDate)}<=@EndDate" , new DynamicParameters(new { StartDate = DateTimeUtils.DateTimeFormat(DateTimeUtils.ToDateTime(startDate).AddDays(-1)), EndDate = DateTimeUtils.DateTimeFormat(DateTimeUtils.ToDateTime(endDate).AddDays(1)) })); if (!travelStatList.Any() && !leaveStatList.Any()) { return; } foreach (var dayResult in dayResults) { if (travelStatList.Any()) { var travel = travelStatList.FirstOrDefault(t => t.WorkDate == dayResult.CurrDate && t.EmpUid == dayResult.EmpUid); if (travel != null) { dayResult.TravelType = travel.TravelTypeUid; dayResult.TravelDays = travel.TravelDays; dayResult.TravelHours = travel.TravelHours; } } if (leaveStatList.Any()) { var leave = leaveStatList.FirstOrDefault(t => t.WorkDate == dayResult.CurrDate && t.EmpUid == dayResult.EmpUid); if (leave != null) { dayResult.LeavelType = leave.LeaveTypeUid; dayResult.LeaveDays = leave.LeaveDays; dayResult.LeavelHours = leave.LeaveHours; } } } } void InitDayResultBySchedule() { int isExist = _dbContext.Count(nameof(TmDayResult), $"{nameof(TmDayResult.CurrDate)}>='{currPeriod.StartDate}' and {nameof(TmDayResult.CurrDate)}<='{currPeriod.EndDate}'"); if (isExist > 0) { return; } var schedules = _dbContext.QueryWhere <TmSchedule>($"{nameof(TmSchedule.WorkDay)}>= '{currPeriod.StartDate}' and {nameof(TmSchedule.WorkDay)}<='{currPeriod.EndDate}'"); if (!schedules.Any()) { Guard.Against.FapBusiness("未找到当月排班,请设置排班"); } //排班员工 var scheduleEmployees = _dbContext.QueryWhere <TmScheduleEmployee>($"{nameof(TmScheduleEmployee.ScheduleUid)} in @ScheduleUids", new DynamicParameters(new { ScheduleUids = schedules.Select(s => s.ScheduleUid) })); if (!scheduleEmployees.Any()) { Guard.Against.FapBusiness("未找到次考勤周期的排班员工"); } _dbContext.InsertBatchSql(InitDayResult()); IEnumerable <TmDayResult> InitDayResult() { foreach (var schedule in schedules) { foreach (var scheduleEmployee in scheduleEmployees) { TmDayResult dayResult = new TmDayResult(); dayResult.EmpUid = scheduleEmployee.EmpUid; dayResult.DeptUid = scheduleEmployee.DeptUid; dayResult.ShiftUid = schedule.ShiftUid; dayResult.WorkHoursLength = schedule.WorkHoursLength; dayResult.RestMinutesLength = schedule.RestMinutesLength; dayResult.CurrDate = schedule.WorkDay; dayResult.StartTime = schedule.StartTime; dayResult.EndTime = schedule.EndTime; dayResult.LateTime = schedule.LateTime; dayResult.LeaveTime = schedule.LeaveTime; dayResult.StartCardTime = schedule.StartCardTime; dayResult.EndCardTime = schedule.EndCardTime; dayResult.RestStartTime = schedule.RestStartTime; dayResult.RestEndTime = schedule.RestEndTime; yield return(dayResult); } } } } }