Kaynağa Gözat

Merge branch 'master' into 红德堂APP调试

Long 1 gün önce
ebeveyn
işleme
77d08521e9
100 değiştirilmiş dosya ile 6557 ekleme ve 262 silme
  1. 12 0
      fs-admin/src/main/java/com/fs/company/controller/CompanyUserController.java
  2. 13 2
      fs-admin/src/main/java/com/fs/course/controller/FsUserCourseController.java
  3. 29 4
      fs-admin/src/main/java/com/fs/course/controller/FsUserCoursePeriodController.java
  4. 2 0
      fs-admin/src/main/java/com/fs/course/controller/FsUserCourseTrainingCampController.java
  5. 1 0
      fs-admin/src/main/java/com/fs/course/controller/FsUserVideoController.java
  6. 10 0
      fs-admin/src/main/java/com/fs/course/controller/qw/QwFsCourseWatchLogController.java
  7. 133 75
      fs-admin/src/main/java/com/fs/his/controller/FsPatientController.java
  8. 112 39
      fs-admin/src/main/java/com/fs/his/controller/FsStoreOrderController.java
  9. 46 0
      fs-admin/src/main/java/com/fs/his/controller/FsUserOperationLogController.java
  10. 19 0
      fs-admin/src/main/java/com/fs/his/controller/HzOMSErpApiController.java
  11. 53 20
      fs-admin/src/main/java/com/fs/his/task/Task.java
  12. 7 0
      fs-admin/src/main/java/com/fs/qw/controller/QwSopTempController.java
  13. 1 1
      fs-admin/src/main/resources/logback.xml
  14. 2 1
      fs-common/src/main/java/com/fs/common/enums/DataSourceType.java
  15. 5 0
      fs-common/src/main/java/com/fs/common/utils/date/DateUtil.java
  16. 24 0
      fs-company-app/src/main/java/com/fs/app/controller/CompanyTagController.java
  17. 1 1
      fs-company-app/src/main/java/com/fs/app/controller/FsUserController.java
  18. 15 1
      fs-company-app/src/main/java/com/fs/app/controller/FsUserCourseVideoController.java
  19. 60 0
      fs-company-app/src/main/java/com/fs/app/controller/FsUserOperationLogController.java
  20. 18 1
      fs-company-app/src/main/java/com/fs/app/controller/UserController.java
  21. 2 0
      fs-company-app/src/main/java/com/fs/app/param/LoginParam.java
  22. 2 1
      fs-company-app/src/main/resources/application.yml
  23. 17 0
      fs-company/src/main/java/com/fs/company/controller/company/CompanyConfigController.java
  24. 15 0
      fs-company/src/main/java/com/fs/company/controller/company/CompanyDeptController.java
  25. 29 0
      fs-company/src/main/java/com/fs/company/controller/company/CompanyLoginController.java
  26. 13 0
      fs-company/src/main/java/com/fs/company/controller/company/CompanyProfileController.java
  27. 56 3
      fs-company/src/main/java/com/fs/company/controller/company/CompanyUserController.java
  28. 3 1
      fs-company/src/main/java/com/fs/company/controller/course/FsCourseRedPacketLogController.java
  29. 4 1
      fs-company/src/main/java/com/fs/company/controller/course/FsCourseWatchLogController.java
  30. 15 0
      fs-company/src/main/java/com/fs/company/controller/course/FsUserCoursePeriodController.java
  31. 58 0
      fs-company/src/main/java/com/fs/company/controller/course/FsUserCourseTrainingCampController.java
  32. 43 0
      fs-company/src/main/java/com/fs/company/controller/course/FsUserOperationLogController.java
  33. 10 4
      fs-company/src/main/java/com/fs/company/controller/course/qw/FsQwCourseWatchLogController.java
  34. 57 2
      fs-company/src/main/java/com/fs/company/controller/qw/QwExternalContactController.java
  35. 3 1
      fs-company/src/main/java/com/fs/company/controller/qw/QwExternalContactInfoController.java
  36. 0 2
      fs-company/src/main/java/com/fs/company/controller/qw/QwGroupChatUserController.java
  37. 20 0
      fs-company/src/main/java/com/fs/company/controller/qw/QwSopController.java
  38. 7 0
      fs-company/src/main/java/com/fs/company/controller/qw/QwSopTempController.java
  39. 37 1
      fs-company/src/main/java/com/fs/company/controller/qw/QwUserController.java
  40. 212 0
      fs-company/src/main/java/com/fs/company/controller/qw/QwUserVoiceLogController.java
  41. 241 0
      fs-company/src/main/java/com/fs/company/controller/qw/QwWorkTaskNewController.java
  42. 158 27
      fs-company/src/main/java/com/fs/company/controller/qw/SopUserLogsInfoController.java
  43. 1 1
      fs-company/src/main/java/com/fs/company/controller/stats/SalesWatchStatisController.java
  44. 1 1
      fs-company/src/main/java/com/fs/company/controller/store/FsInquiryOrderController.java
  45. 100 64
      fs-company/src/main/java/com/fs/company/controller/store/FsPatientController.java
  46. 28 0
      fs-company/src/main/java/com/fs/company/utils/DomainUtil.java
  47. 28 4
      fs-company/src/main/java/com/fs/user/FsUserAdminController.java
  48. 2 1
      fs-company/src/main/resources/application.yml
  49. 40 0
      fs-framework/src/main/java/com/fs/framework/config/LogInterceptor.java
  50. 8 3
      fs-framework/src/main/java/com/fs/framework/config/ResourcesConfig.java
  51. 35 0
      fs-framework/src/main/java/com/fs/framework/config/ThreadPoolTaskWrapExecutor.java
  52. 60 0
      fs-framework/src/main/java/com/fs/framework/util/ThreadMdcUtil.java
  53. 141 0
      fs-ipad-task/pom.xml
  54. 14 0
      fs-ipad-task/src/main/java/com/fs/FSServletInitializer.java
  55. 24 0
      fs-ipad-task/src/main/java/com/fs/FsIpadTaskApplication.java
  56. 51 0
      fs-ipad-task/src/main/java/com/fs/app/exception/FSException.java
  57. 82 0
      fs-ipad-task/src/main/java/com/fs/app/exception/FSExceptionHandler.java
  58. 332 0
      fs-ipad-task/src/main/java/com/fs/app/service/IpadSendServer.java
  59. 234 0
      fs-ipad-task/src/main/java/com/fs/app/task/SendMsg.java
  60. 171 0
      fs-ipad-task/src/main/java/com/fs/framework/aspectj/DataScopeAspect.java
  61. 73 0
      fs-ipad-task/src/main/java/com/fs/framework/aspectj/DataSourceAspect.java
  62. 219 0
      fs-ipad-task/src/main/java/com/fs/framework/aspectj/LogAspect.java
  63. 117 0
      fs-ipad-task/src/main/java/com/fs/framework/aspectj/RateLimiterAspect.java
  64. 31 0
      fs-ipad-task/src/main/java/com/fs/framework/config/ApplicationConfig.java
  65. 58 0
      fs-ipad-task/src/main/java/com/fs/framework/config/ArrayStringTypeHandler.java
  66. 85 0
      fs-ipad-task/src/main/java/com/fs/framework/config/CaptchaConfig.java
  67. 118 0
      fs-ipad-task/src/main/java/com/fs/framework/config/DataSourceConfig.java
  68. 123 0
      fs-ipad-task/src/main/java/com/fs/framework/config/DruidConfig.java
  69. 72 0
      fs-ipad-task/src/main/java/com/fs/framework/config/FastJson2JsonRedisSerializer.java
  70. 59 0
      fs-ipad-task/src/main/java/com/fs/framework/config/FilterConfig.java
  71. 76 0
      fs-ipad-task/src/main/java/com/fs/framework/config/KaptchaTextCreator.java
  72. 150 0
      fs-ipad-task/src/main/java/com/fs/framework/config/MyBatisConfig.java
  73. 121 0
      fs-ipad-task/src/main/java/com/fs/framework/config/RedisConfig.java
  74. 76 0
      fs-ipad-task/src/main/java/com/fs/framework/config/ResourcesConfig.java
  75. 11 0
      fs-ipad-task/src/main/java/com/fs/framework/config/RetryConfig.java
  76. 158 0
      fs-ipad-task/src/main/java/com/fs/framework/config/SecurityConfig.java
  77. 33 0
      fs-ipad-task/src/main/java/com/fs/framework/config/ServerConfig.java
  78. 121 0
      fs-ipad-task/src/main/java/com/fs/framework/config/SwaggerConfig.java
  79. 102 0
      fs-ipad-task/src/main/java/com/fs/framework/config/ThreadPoolConfig.java
  80. 77 0
      fs-ipad-task/src/main/java/com/fs/framework/config/properties/DruidProperties.java
  81. 27 0
      fs-ipad-task/src/main/java/com/fs/framework/datasource/DynamicDataSource.java
  82. 45 0
      fs-ipad-task/src/main/java/com/fs/framework/datasource/DynamicDataSourceContextHolder.java
  83. 115 0
      fs-ipad-task/src/main/java/com/fs/framework/exception/GlobalExceptionHandler.java
  84. 56 0
      fs-ipad-task/src/main/java/com/fs/framework/interceptor/RepeatSubmitInterceptor.java
  85. 126 0
      fs-ipad-task/src/main/java/com/fs/framework/interceptor/impl/SameUrlDataInterceptor.java
  86. 56 0
      fs-ipad-task/src/main/java/com/fs/framework/manager/AsyncManager.java
  87. 40 0
      fs-ipad-task/src/main/java/com/fs/framework/manager/ShutdownManager.java
  88. 106 0
      fs-ipad-task/src/main/java/com/fs/framework/manager/factory/AsyncFactory.java
  89. 69 0
      fs-ipad-task/src/main/java/com/fs/framework/security/LoginBody.java
  90. 255 0
      fs-ipad-task/src/main/java/com/fs/framework/security/LoginUser.java
  91. 89 0
      fs-ipad-task/src/main/java/com/fs/framework/security/SecurityUtils.java
  92. 47 0
      fs-ipad-task/src/main/java/com/fs/framework/security/filter/JwtAuthenticationTokenFilter.java
  93. 35 0
      fs-ipad-task/src/main/java/com/fs/framework/security/handle/AuthenticationEntryPointImpl.java
  94. 54 0
      fs-ipad-task/src/main/java/com/fs/framework/security/handle/LogoutSuccessHandlerImpl.java
  95. 92 0
      fs-ipad-task/src/main/java/com/fs/framework/service/CompanyLoginService.java
  96. 66 0
      fs-ipad-task/src/main/java/com/fs/framework/service/CompanyPermissionService.java
  97. 170 0
      fs-ipad-task/src/main/java/com/fs/framework/service/PermissionService.java
  98. 236 0
      fs-ipad-task/src/main/java/com/fs/framework/service/TokenService.java
  99. 75 0
      fs-ipad-task/src/main/java/com/fs/framework/service/UserDetailsServiceImpl.java
  100. 1 0
      fs-ipad-task/src/main/resources/META-INF/spring-devtools.properties

+ 12 - 0
fs-admin/src/main/java/com/fs/company/controller/CompanyUserController.java

@@ -7,6 +7,7 @@ import com.fs.common.core.domain.AjaxResult;
 import com.fs.common.core.domain.R;
 import com.fs.common.core.page.TableDataInfo;
 import com.fs.common.enums.BusinessType;
+import com.fs.common.utils.ServletUtils;
 import com.fs.common.utils.poi.ExcelUtil;
 import com.fs.company.domain.CompanyUser;
 import com.fs.company.service.ICompanyUserService;
@@ -161,4 +162,15 @@ public class CompanyUserController extends BaseController
         return  R.ok().put("data",list);
     }
 
+    /**
+     * 获取用户列表
+     */
+    @GetMapping("/getCompanyUserListPage")
+    public TableDataInfo getCompanyUserListPage(CompanyUser user)
+    {
+        startPage();
+        List<CompanyUser> list = companyUserService.getCompanyUserList(user);
+        return getDataTable(list);
+    }
+
 }

+ 13 - 2
fs-admin/src/main/java/com/fs/course/controller/FsUserCourseController.java

@@ -164,14 +164,25 @@ public class FsUserCourseController extends BaseController
         return toAjax(1);
     }
 
+    /**
+     * 复制课程
+     */
+    @PreAuthorize("@ss.hasPermi('course:userCourse:copy')")
+    @Log(title = "课程", businessType = BusinessType.DELETE)
+    @GetMapping("/copy/{courseId}")
+    public AjaxResult copy(@PathVariable Long courseId)
+    {
+        int i = fsUserCourseService.copyFsUserCourse(courseId);
+        return toAjax(i);
+    }
+
     /**
      * 删除课程
      */
     @PreAuthorize("@ss.hasPermi('course:userCourse:remove')")
     @Log(title = "课程", businessType = BusinessType.DELETE)
 	@DeleteMapping("/{courseIds}")
-    public AjaxResult remove(@PathVariable Long[] courseIds)
-    {
+    public AjaxResult remove(@PathVariable Long[] courseIds){
         fsUserCourseService.deleteFsUserCourseByCourseIds(courseIds);
         redisCacheUtil.delRedisKey("getCourseList");
         return toAjax(1);

+ 29 - 4
fs-admin/src/main/java/com/fs/course/controller/FsUserCoursePeriodController.java

@@ -13,13 +13,11 @@ import com.fs.course.domain.FsUserCourseVideoRedPackage;
 import com.fs.course.param.CompanyRedPacketParam;
 import com.fs.course.param.FsBatchPeriodRedPackageParam;
 import com.fs.course.param.PeriodCountParam;
+import com.fs.course.param.PeriodStatisticCountParam;
 import com.fs.course.service.IFsUserCoursePeriodDaysService;
 import com.fs.course.service.IFsUserCoursePeriodService;
 import com.fs.course.service.IFsUserCourseVideoRedPackageService;
-import com.fs.course.vo.FsPeriodCountVO;
-import com.fs.course.vo.FsUserCoursePeriodVO;
-import com.fs.course.vo.PeriodRedPacketVO;
-import com.fs.course.vo.UpdateCourseTimeVo;
+import com.fs.course.vo.*;
 import com.fs.his.vo.OptionsVO;
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.PageInfo;
@@ -29,9 +27,12 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.*;
 
+import java.math.BigDecimal;
+import java.time.LocalDateTime;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.TimeUnit;
 
 
 /**
@@ -45,6 +46,7 @@ import java.util.Map;
 @RequestMapping("/course/period")
 @Slf4j
 public class FsUserCoursePeriodController extends BaseController {
+
     private final IFsUserCoursePeriodService fsUserCoursePeriodService;
     private final IFsUserCoursePeriodDaysService fsUserCoursePeriodDaysService;
     private final IFsUserCourseVideoRedPackageService fsUserCourseVideoRedPackageService;
@@ -151,6 +153,14 @@ public class FsUserCoursePeriodController extends BaseController {
         return fsUserCoursePeriodDaysService.addCourse(entity);
     }
 
+    @PreAuthorize("@ss.hasPermi('course:period:dayRemove')")
+    @Log(title = "会员营期课程删除", businessType = BusinessType.DELETE)
+    @DeleteMapping("/day/{ids}")
+    public AjaxResult dayRemove(@PathVariable Long[] ids)
+    {
+        return toAjax(fsUserCoursePeriodDaysService.deleteFsUserCoursePeriodDaysByIds(ids));
+    }
+
     @PreAuthorize("@ss.hasPermi('course:period:updateCourseTime')")
     @PostMapping("/updateCourseTime")
     public R updateCourseTime(@RequestBody UpdateCourseTimeVo vo){
@@ -246,4 +256,19 @@ public class FsUserCoursePeriodController extends BaseController {
         return R.ok();
     }
 
+    @PostMapping("/periodCourseStatisticCount")
+    @ApiOperation("会员详情训练营数据总览")
+    public R periodCourseStatisticCount(@RequestBody PeriodStatisticCountParam param) {
+        if (param == null) {
+            return R.error("请求参数不能为空!");
+        }
+        return R.ok().put("data", fsUserCoursePeriodService.periodCourseStatisticCount(param));
+    }
+
+    @PostMapping("/periodlist")
+    public R periodList(@RequestBody PeriodStatisticCountParam param)
+    {
+        List<FsUserCoursePeriod> list = fsUserCoursePeriodService.selectFsPeriodlist(param);
+        return R.ok().put("data", list);
+    }
 }

+ 2 - 0
fs-admin/src/main/java/com/fs/course/controller/FsUserCourseTrainingCampController.java

@@ -36,6 +36,7 @@ public class FsUserCourseTrainingCampController {
     @PreAuthorize("@ss.hasPermi('course:trainingCamp:list')")
     @GetMapping("/list")
     public AjaxResult list(@RequestParam(required = false) String trainingCampName,
+                           @RequestParam(required = false) String userId,
                            @RequestParam String scs,
                            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                            @RequestParam(required = false, defaultValue = "10") Integer pageSize)
@@ -43,6 +44,7 @@ public class FsUserCourseTrainingCampController {
         Map<String, Object> params = new HashMap<>();
         params.put("trainingCampName", trainingCampName);
         params.put("scs", SortUtils.parseSort(scs));
+        params.put("userId", userId);
 
         PageHelper.startPage(pageNum, pageSize);
         List<FsUserCourseTrainingCampVO> list = fsUserCourseTrainingCampService.selectFsUserCourseTrainingCampVOListByMap(params);

+ 1 - 0
fs-admin/src/main/java/com/fs/course/controller/FsUserVideoController.java

@@ -207,6 +207,7 @@ public class FsUserVideoController extends BaseController
         try {
             extractFirstFrame(videoFile.getAbsolutePath(), frameFile.getAbsolutePath());
         } catch (Exception e) {
+            e.printStackTrace();
             // 记录错误日志
             return R.error("提取第一帧失败");
         }

+ 10 - 0
fs-admin/src/main/java/com/fs/course/controller/qw/QwFsCourseWatchLogController.java

@@ -10,6 +10,7 @@ import com.fs.common.utils.poi.ExcelUtil;
 import com.fs.course.domain.FsCourseWatchLog;
 import com.fs.course.param.FsCourseWatchLogListParam;
 import com.fs.course.param.FsCourseWatchLogStatisticsListParam;
+import com.fs.course.param.PeriodStatisticCountParam;
 import com.fs.course.service.IFsCourseWatchLogService;
 import com.fs.course.vo.FsCourseWatchLogListVO;
 import com.fs.course.vo.FsCourseWatchLogStatisticsListVO;
@@ -139,4 +140,13 @@ public class QwFsCourseWatchLogController extends BaseController
     {
         return toAjax(fsCourseWatchLogService.deleteFsCourseWatchLogByLogIds(logIds));
     }
+
+//    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:list')")
+    @GetMapping("/listBytrainingCampId")
+    public TableDataInfo listBytrainingCampId(PeriodStatisticCountParam param)
+    {
+        startPage();
+        List<FsCourseWatchLogListVO> list = fsCourseWatchLogService.selectListBytrainingCampId(param);
+        return getDataTable(list);
+    }
 }

+ 133 - 75
fs-admin/src/main/java/com/fs/his/controller/FsPatientController.java

@@ -11,6 +11,7 @@ import com.fs.common.core.domain.R;
 import com.fs.common.exception.CustomException;
 import com.fs.common.utils.SecurityUtils;
 import com.fs.his.vo.FsPatientVO;
+import com.hc.openapi.tool.util.StringUtils;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
@@ -132,48 +133,75 @@ public class FsPatientController extends BaseController
     public AjaxResult add(@RequestBody FsPatient fsPatient)
     {
         String idCardNumber = fsPatient.getIdCard(); // 替换为要验证的身份证号码
-        if (idCardNumber == null || idCardNumber.length() != 18) {
-           throw new CustomException("身份证号码不合法");
-        }
-        String regex = "\\d{17}[0-9Xx]";
-        if (!Pattern.matches(regex, idCardNumber)) {
-            throw new CustomException("身份证号码不合法");
+//        if (idCardNumber == null || idCardNumber.length() != 18) {
+//           throw new CustomException("身份证号码不合法");
+//        }
+//        String regex = "\\d{17}[0-9Xx]";
+//        if (!Pattern.matches(regex, idCardNumber)) {
+//            throw new CustomException("身份证号码不合法");
+//        }
+        if (StringUtils.isNotBlank(idCardNumber)){
+            if (idCardNumber.length() != 18) {
+                throw new CustomException("身份证号码不合法");
+            }
+            String regex = "\\d{17}[0-9Xx]";
+            if (!Pattern.matches(regex, idCardNumber)) {
+                throw new CustomException("身份证号码不合法");
+            }
+            String birthDateString = idCardNumber.substring(6, 14);
+            LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
+            LocalDate currentDate = LocalDate.now();
+            int age = currentDate.getYear() - birthDate.getYear();
+            if (currentDate.getMonthValue() < birthDate.getMonthValue()
+                    || (currentDate.getMonthValue() == birthDate.getMonthValue()
+                    && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
+                age--;
+            }
+            if (age < 18) {
+                throw new CustomException("年龄必须大于18岁");
+            }
+            if (age > 200) {
+                throw new CustomException("年龄超过200岁");
+            }
         }
         if (fsPatient.getPatientName().length()<2||fsPatient.getPatientName().length()>30||!fsPatient.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
             throw new CustomException("就诊人名称不合法");
         }
-        String birthDateString = idCardNumber.substring(6, 14);
-        LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
-        LocalDate currentDate = LocalDate.now();
-        int age = currentDate.getYear() - birthDate.getYear();
-        if (currentDate.getMonthValue() < birthDate.getMonthValue()
-                || (currentDate.getMonthValue() == birthDate.getMonthValue()
-                && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
-            age--;
-        }
-        if (age < 18) {
-            throw new CustomException("年龄必须大于18岁");
-        }
-        if (age > 200) {
-            throw new CustomException("年龄超过200岁");
-        }
+//        String birthDateString = idCardNumber.substring(6, 14);
+//        LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
+//        LocalDate currentDate = LocalDate.now();
+//        int age = currentDate.getYear() - birthDate.getYear();
+//        if (currentDate.getMonthValue() < birthDate.getMonthValue()
+//                || (currentDate.getMonthValue() == birthDate.getMonthValue()
+//                && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
+//            age--;
+//        }
+//        if (age < 18) {
+//            throw new CustomException("年龄必须大于18岁");
+//        }
+//        if (age > 200) {
+//            throw new CustomException("年龄超过200岁");
+//        }
         Date birthday = fsPatient.getBirthday();
-        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
-        String formattedBirthday = sdf.format(birthday);
-        LocalDate da = LocalDate.parse(formattedBirthday, DateTimeFormatter.ofPattern("yyyyMMdd"));
-        LocalDate currentDate2 = LocalDate.now();
-        int age2 = currentDate2.getYear() - da.getYear();
-        if (currentDate2.getMonthValue() < da.getMonthValue()
-                || (currentDate2.getMonthValue() == da.getMonthValue()
-                && currentDate2.getDayOfMonth() < da.getDayOfMonth())) {
-            age2--;
-        }
-        if (age2 < 18) {
-            throw new CustomException("年龄必须大于18岁");
-        }
-        if (age2 > 200) {
-            throw new CustomException("年龄超过200岁");
+        if (birthday!=null){
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
+            String formattedBirthday = sdf.format(birthday);
+            LocalDate da = LocalDate.parse(formattedBirthday, DateTimeFormatter.ofPattern("yyyyMMdd"));
+            LocalDate currentDate2 = LocalDate.now();
+            int age2 = currentDate2.getYear() - da.getYear();
+            if (currentDate2.getMonthValue() < da.getMonthValue()
+                    || (currentDate2.getMonthValue() == da.getMonthValue()
+                    && currentDate2.getDayOfMonth() < da.getDayOfMonth())) {
+                age2--;
+            }
+            if (age2 < 18) {
+                throw new CustomException("年龄必须大于18岁");
+            }
+            if (age2 > 200) {
+                throw new CustomException("年龄超过200岁");
+            }
         }
+
         return toAjax(fsPatientService.insertFsPatient(fsPatient));
     }
 
@@ -186,48 +214,78 @@ public class FsPatientController extends BaseController
     public AjaxResult edit(@RequestBody FsPatient fsPatient)
     {
         String idCardNumber = fsPatient.getIdCard();
-        if (idCardNumber == null || idCardNumber.length() != 18) {
-            throw new CustomException("身份证号码不合法");
-        }
-        String regex = "\\d{17}[0-9Xx]";
-        if (!Pattern.matches(regex, idCardNumber)) {
-            throw new CustomException("身份证号码不合法");
-        }
-        if (fsPatient.getPatientName().length()<2||fsPatient.getPatientName().length()>30||!fsPatient.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
-            throw new CustomException("就诊人名称不合法");
-        }
-        String birthDateString = idCardNumber.substring(6, 14);
-        LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
-        LocalDate currentDate = LocalDate.now();
-        int age = currentDate.getYear() - birthDate.getYear();
-        if (currentDate.getMonthValue() < birthDate.getMonthValue()
-                || (currentDate.getMonthValue() == birthDate.getMonthValue()
-                && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
-            age--;
-        }
-        if (age < 18) {
-            throw new CustomException("年龄必须大于18岁");
-        }
-        if (age > 200) {
-            throw new CustomException("年龄超过200岁");
+//        if (idCardNumber == null || idCardNumber.length() != 18) {
+//            throw new CustomException("身份证号码不合法");
+//        }
+//        String regex = "\\d{17}[0-9Xx]";
+//        if (!Pattern.matches(regex, idCardNumber)) {
+//            throw new CustomException("身份证号码不合法");
+//        }
+//        if (fsPatient.getPatientName().length()<2||fsPatient.getPatientName().length()>30||!fsPatient.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
+//            throw new CustomException("就诊人名称不合法");
+//        }
+//        String birthDateString = idCardNumber.substring(6, 14);
+//        LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
+//        LocalDate currentDate = LocalDate.now();
+//        int age = currentDate.getYear() - birthDate.getYear();
+//        if (currentDate.getMonthValue() < birthDate.getMonthValue()
+//                || (currentDate.getMonthValue() == birthDate.getMonthValue()
+//                && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
+//            age--;
+//        }
+//        if (age < 18) {
+//            throw new CustomException("年龄必须大于18岁");
+//        }
+//        if (age > 200) {
+//            throw new CustomException("年龄超过200岁");
+//        }
+        if (StringUtils.isNotBlank(idCardNumber)) {
+            if (idCardNumber.length() != 18) {
+                throw new CustomException("身份证号码不合法");
+            }
+            String regex = "\\d{17}[0-9Xx]";
+            if (!Pattern.matches(regex, idCardNumber)) {
+                throw new CustomException("身份证号码不合法");
+            }
+            if (fsPatient.getPatientName().length()<2||fsPatient.getPatientName().length()>30||!fsPatient.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
+                throw new CustomException("就诊人名称不合法");
+            }
+            String birthDateString = idCardNumber.substring(6, 14);
+            LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
+            LocalDate currentDate = LocalDate.now();
+            int age = currentDate.getYear() - birthDate.getYear();
+            if (currentDate.getMonthValue() < birthDate.getMonthValue()
+                    || (currentDate.getMonthValue() == birthDate.getMonthValue()
+                    && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
+                age--;
+            }
+            if (age < 18) {
+                throw new CustomException("年龄必须大于18岁");
+            }
+            if (age > 200) {
+                throw new CustomException("年龄超过200岁");
+            }
         }
         Date birthday = fsPatient.getBirthday();
-        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
-        String formattedBirthday = sdf.format(birthday);
-        LocalDate da = LocalDate.parse(formattedBirthday, DateTimeFormatter.ofPattern("yyyyMMdd"));
-        LocalDate currentDate2 = LocalDate.now();
-        int age2 = currentDate2.getYear() - da.getYear();
-        if (currentDate2.getMonthValue() < da.getMonthValue()
-                || (currentDate2.getMonthValue() == da.getMonthValue()
-                && currentDate2.getDayOfMonth() < da.getDayOfMonth())) {
-            age2--;
-        }
-        if (age2 < 18) {
-            throw new CustomException("年龄必须大于18岁");
-        }
-        if (age2 > 200) {
-            throw new CustomException("年龄超过200岁");
+        if (birthday!=null){
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
+            String formattedBirthday = sdf.format(birthday);
+            LocalDate da = LocalDate.parse(formattedBirthday, DateTimeFormatter.ofPattern("yyyyMMdd"));
+            LocalDate currentDate2 = LocalDate.now();
+            int age2 = currentDate2.getYear() - da.getYear();
+            if (currentDate2.getMonthValue() < da.getMonthValue()
+                    || (currentDate2.getMonthValue() == da.getMonthValue()
+                    && currentDate2.getDayOfMonth() < da.getDayOfMonth())) {
+                age2--;
+            }
+            if (age2 < 18) {
+                throw new CustomException("年龄必须大于18岁");
+            }
+            if (age2 > 200) {
+                throw new CustomException("年龄超过200岁");
+            }
         }
+
         return toAjax(fsPatientService.updateFsPatient(fsPatient));
     }
 

+ 112 - 39
fs-admin/src/main/java/com/fs/his/controller/FsStoreOrderController.java

@@ -19,22 +19,25 @@ import com.fs.company.service.ICompanyMoneyLogsService;
 import com.fs.company.vo.CompanyStoreOrderMoneyLogsVO;
 import com.fs.erp.domain.ErpDeliverys;
 import com.fs.erp.domain.ErpOrderQuery;
+import com.fs.erp.dto.ErpDeliverysRequest;
+import com.fs.erp.dto.ErpDeliverysResponse;
 import com.fs.erp.dto.ErpOrderQueryRequert;
 import com.fs.erp.dto.ErpOrderQueryResponse;
+import com.fs.erp.dto.df.BspOrderResponse;
+import com.fs.erp.dto.df.DFConfigVo;
 import com.fs.erp.service.IErpOrderService;
 import com.fs.framework.web.service.TokenService;
 import com.fs.his.config.FsSysConfig;
 import com.fs.his.domain.*;
 import com.fs.his.dto.ExpressInfoDTO;
 import com.fs.his.dto.StoreOrderExpressExportDTO;
+import com.fs.his.dto.TracesDTO;
 import com.fs.his.enums.ShipperCodeEnum;
 import com.fs.his.param.FsFollowMsgParam;
 import com.fs.his.param.FsStoreOrderParam;
 import com.fs.his.param.FsStoreOrderSalesParam;
 import com.fs.his.param.FsStoreOrderSetErpPhoneParam;
-import com.fs.his.service.IFsExportTaskService;
-import com.fs.his.service.IFsExpressService;
-import com.fs.his.service.IFsStoreService;
+import com.fs.his.service.*;
 import com.fs.his.utils.ConfigUtil;
 import com.fs.his.vo.*;
 import com.fs.system.domain.SysConfig;
@@ -49,7 +52,6 @@ import com.fs.common.annotation.Log;
 import com.fs.common.core.controller.BaseController;
 import com.fs.common.core.domain.AjaxResult;
 import com.fs.common.enums.BusinessType;
-import com.fs.his.service.IFsStoreOrderService;
 import com.fs.common.utils.poi.ExcelUtil;
 import com.fs.common.core.page.TableDataInfo;
 import org.springframework.web.multipart.MultipartFile;
@@ -90,8 +92,19 @@ public class FsStoreOrderController extends BaseController
     @Qualifier("wdtErpOrderServiceImpl")
     private IErpOrderService wdtOrderService;
 
+    @Autowired
+    @Qualifier("hzOMSErpOrderServiceImpl")
+    private IErpOrderService hzOMSErpOrderService;
+
+    @Autowired
+    @Qualifier("dfOrderServiceImpl")
+    private IErpOrderService dfOrderService;
+
     @Autowired
     SysConfigMapper sysConfigMapper;
+
+    @Autowired
+    private IFsStoreOrderDfService fsStoreOrderDfService;
     /**
      * 查询订单列表
      */
@@ -369,6 +382,12 @@ public class FsStoreOrderController extends BaseController
                 } else if (erpType == 2){
                     //旺店通
                     erpOrderService =  wdtOrderService;
+                }  else if (erpType == 3){
+                    //
+                    erpOrderService =  hzOMSErpOrderService;
+                } else if (erpType == 4){
+                    //代服
+                    erpOrderService =  dfOrderService;
                 }
                 return erpOrderService;
 
@@ -483,22 +502,58 @@ public class FsStoreOrderController extends BaseController
     @ApiOperation("批量创建ERP订单")
     @PreAuthorize("@ss.hasPermi('his:storeOrder:createErpOrder')")
     @PostMapping(value = "/batchCreateErpOrder")
-    public R batchCreateErpOrder(@RequestBody List<Long> orderIds)
+    public R batchCreateErpOrder(@RequestBody FsStoreOrderSetErpPhoneParam param)
     {
-        if (orderIds != null && !orderIds.isEmpty()) {
-            orderIds.forEach(orderId->{
-                try {
-                    fsStoreOrderService.createOmsOrder(orderId);
-                } catch (ParseException e) {
-                    throw new RuntimeException(e);
-                }
-
-            });
+        String loginAccount = param.getLoginAccount();
+        if (StringUtils.isBlank(loginAccount)){
+            return R.error("未选择推送erp账户");
+        }
+        FsStoreOrderDf df = getDFInfo(loginAccount);
+        if (df.getLoginAccount() == null){
+            return R.error("未查询到所选erp账户");
+        }
+        List<Long> orderIds = param.getOrderIds();
+        if (orderIds  == null || orderIds.isEmpty()) {
+            if (param.getUserPhoneMk() != null && !param.getUserPhoneMk().isEmpty()) {
+                param.setUserPhone(encryptPhone(param.getUserPhoneMk()));
+            }
+            List<FsStoreOrderListVO> list = fsStoreOrderService.selectFsStoreOrderListVO(param);
+            orderIds = list.stream().map(FsStoreOrderListVO::getOrderId).collect(Collectors.toList());
+        }
+        if (orderIds.isEmpty()){
+            return R.ok();
         }
+        orderIds.forEach(orderId->{
+            try {
+                df.setOrderId(orderId);
+                fsStoreOrderDfService.insertFsStoreOrderDf(df);
+                fsStoreOrderService.createOmsOrder(orderId);
+            } catch (ParseException e) {
+                throw new RuntimeException(e);
+            }
 
+        });
         return R.ok();
     }
 
+    private FsStoreOrderDf getDFInfo(String loginAccount) {
+        //查询订单账户 判断是否存在该订单账户
+        List<DFConfigVo> erpAccounts = fsStoreOrderService.getErpAccount();
+        FsStoreOrderDf df = new FsStoreOrderDf();
+        for (DFConfigVo erpAccount : erpAccounts) {
+            if (loginAccount.equals(erpAccount.getLoginAccount())){
+                //添加df记录
+                df.setAppKey(erpAccount.getDfAppKey());
+                df.setAppSecret(erpAccount.getDfAppsecret());
+                df.setLoginAccount(loginAccount);
+                df.setMonthlyCard(erpAccount.getMonthlyCard());
+                df.setStatus(0);
+                break;
+            }
+        }
+        return df;
+    }
+
     @Log(title = "冻结/解冻", businessType = BusinessType.UPDATE)
     @PreAuthorize("@ss.hasPermi('his:storeOrder:editTuiMoney')")
     @GetMapping(value = "/editTuiMoney/{id}")
@@ -535,7 +590,12 @@ public class FsStoreOrderController extends BaseController
     @PreAuthorize("@ss.hasPermi('his:storeOrder:syncExpress')")
     @GetMapping(value = "/syncExpress/{id}")
     public R syncExpress(@PathVariable("id") Long id) {
-        return fsStoreOrderService.syncExpress(id);
+        IErpOrderService erpService = getErpService();
+        if (erpService!=null && erpService == dfOrderService){
+            return fsStoreOrderService.syncDfExpress(id);
+        } else {
+            return fsStoreOrderService.syncExpress(id);
+        }
     }
 
     @PreAuthorize("@ss.hasPermi('his:storeOrder:sendMsg')")
@@ -556,34 +616,41 @@ public class FsStoreOrderController extends BaseController
     @GetMapping(value = "/getExpress/{id}")
     public R getExpress(@PathVariable("id") Long id)
     {
-        FsStoreOrder order=fsStoreOrderService.selectFsStoreOrderByOrderId(id);
         ExpressInfoDTO expressInfoDTO=null;
-        if(StringUtils.isNotEmpty(order.getDeliverySn())){
-            String lastFourNumber = "";
-            if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
-
-                lastFourNumber = order.getUserPhone();
-                if (lastFourNumber.length() == 11) {
-                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
-                }else if (lastFourNumber.length()>11){
-                    String jm = decryptPhone(lastFourNumber);
-                    lastFourNumber = StrUtil.sub(jm, jm.length(), -4);
-                }
-            }
-            expressInfoDTO=expressService.getExpressInfo(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);
-
-            if((expressInfoDTO.getStateEx()!=null&&expressInfoDTO.getStateEx().equals("0"))&&(expressInfoDTO.getState()!=null&&expressInfoDTO.getState().equals("0"))){
-                lastFourNumber = "19923690275";
+        FsStoreOrder order=fsStoreOrderService.selectFsStoreOrderByOrderId(id);
+        //代服管家 查询自己的物流
+        IErpOrderService erpService = getErpService();
+        if (erpService == dfOrderService){
+            expressInfoDTO = fsStoreOrderService.getDfExpressInfoDTO(order);
+        } else {
+            if(StringUtils.isNotEmpty(order.getDeliverySn())){
+                String lastFourNumber = "";
                 if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
+
+                    lastFourNumber = order.getUserPhone();
                     if (lastFourNumber.length() == 11) {
                         lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
+                    }else if (lastFourNumber.length()>11){
+                        String jm = decryptPhone(lastFourNumber);
+                        lastFourNumber = StrUtil.sub(jm, jm.length(), -4);
                     }
                 }
-
                 expressInfoDTO=expressService.getExpressInfo(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);
 
+                if((expressInfoDTO.getStateEx()!=null&&expressInfoDTO.getStateEx().equals("0"))&&(expressInfoDTO.getState()!=null&&expressInfoDTO.getState().equals("0"))){
+                    lastFourNumber = "19923690275";
+                    if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
+                        if (lastFourNumber.length() == 11) {
+                            lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
+                        }
+                    }
+
+                    expressInfoDTO=expressService.getExpressInfo(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);
+
+                }
             }
         }
+
         return R.ok().put("data",expressInfoDTO);
     }
     @PreAuthorize("@ss.hasPermi('his:storeOrder:msgList')")
@@ -646,15 +713,21 @@ public class FsStoreOrderController extends BaseController
     @PostMapping("/editErpPhone")
     public AjaxResult editErpPhone(@RequestBody FsStoreOrderSetErpPhoneParam param)
     {
-        String erpPhone = param.getErpPhone();
-        if (StringUtils.isBlank(erpPhone)) {
+        List<String> erpPhone = param.getErpPhone();
+        if (erpPhone == null || erpPhone.isEmpty()) {
             return AjaxResult.error("请选择手机号");
         }
-        List<Long> orderIds = param.getOrderIds();
-        if (orderIds  == null || orderIds.isEmpty()){
-            return AjaxResult.success();
-        }
         return toAjax(fsStoreOrderService.batchUpdateErpByOrderIds(param));
     }
 
+    /**
+     * 获取erp账户
+     */
+    @GetMapping("/getErpAccount")
+    public R getErpAccount()
+    {
+        List<DFConfigVo> erpAccounts = fsStoreOrderService.getErpAccount();
+        List<String> list = erpAccounts.stream().map(DFConfigVo::getLoginAccount).collect(Collectors.toList());
+        return R.ok().put("data", list);
+    }
 }

+ 46 - 0
fs-admin/src/main/java/com/fs/his/controller/FsUserOperationLogController.java

@@ -0,0 +1,46 @@
+package com.fs.his.controller;
+
+import com.fs.common.core.controller.BaseController;
+import com.fs.common.core.domain.R;
+import com.fs.common.core.page.TableDataInfo;
+import com.fs.his.domain.FsUserOperationLog;
+import com.fs.his.service.IFsUserOperationLogService;
+import com.fs.his.vo.FsUserOperationLogParamVo;
+import com.fs.his.vo.FsUserOperationLogVo;
+import com.hc.openapi.tool.fastjson.JSON;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * 用户操作日志对象
+ */
+@RestController
+@RequestMapping("/his/userOperationLog")
+public class FsUserOperationLogController extends BaseController {
+
+    @Autowired
+    private IFsUserOperationLogService fsUserOperationLogService;
+
+//    @PreAuthorize("@ss.hasPermi('his:userOperationLog:list')")
+    @GetMapping("/list")
+    public TableDataInfo list(FsUserOperationLog fsUserOperationLog)
+    {
+        startPage();
+        List<FsUserOperationLogVo> list = fsUserOperationLogService.selectFsUserOperationLogByList(fsUserOperationLog);
+
+        return getDataTable(list);
+    }
+
+    @GetMapping("/getOperationType")
+    public R getOperationType()
+    {
+        return R.ok().put("data",fsUserOperationLogService.getOperationType());
+    }
+}

+ 19 - 0
fs-admin/src/main/java/com/fs/his/controller/HzOMSErpApiController.java

@@ -1,17 +1,23 @@
 package com.fs.his.controller;
 
 
+import com.fs.common.core.domain.R;
 import com.fs.erp.domain.ErpOrder;
 import com.fs.erp.dto.ErpOrderResponse;
+import com.fs.erp.dto.df.BspOrderResponse;
 import com.fs.erp.dto.sdk.HzOMS.utils.HzOMSUtils;
 import com.fs.erp.service.IErpOrderService;
+import com.fs.his.domain.FsStoreOrder;
 import com.fs.his.domain.FsVessel;
 import com.fs.his.param.HzOMSErpApiParam;
 import com.fs.his.service.ErpApiService;
+import com.fs.his.service.IFsStoreOrderService;
+import com.fs.his.service.impl.FsStoreOrderServiceImpl;
 import com.fs.his.vo.HzOMSErpResponseVO;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
@@ -33,6 +39,9 @@ public class HzOMSErpApiController {
     @Qualifier("hzOMSErpOrderServiceImpl")
     IErpOrderService HzOMSErpOrderService;
 
+    @Autowired
+    private IFsStoreOrderService fsStoreOrderService;
+
     /**
      * 用于将瀚智商品库存同步到第三方
      *
@@ -117,4 +126,14 @@ public class HzOMSErpApiController {
 //        hzOMSErpResponseVO.setSuccess(true);
 //        return hzOMSErpResponseVO;
 //    }
+
+
+    /**
+     * 代服管家订单回调
+     */
+    @PostMapping("/dfNotifyUrl")
+    public R dfOrderResult(@RequestBody BspOrderResponse param)
+    {
+        return fsStoreOrderService.dfOrderResult(param);
+    }
 }

+ 53 - 20
fs-admin/src/main/java/com/fs/his/task/Task.java

@@ -16,9 +16,13 @@ import com.fs.course.mapper.FsCourseRedPacketLogMapper;
 import com.fs.course.service.IFsCourseWatchLogService;
 import com.fs.course.service.ITencentCloudCosService;
 import com.fs.erp.domain.ErpDeliverys;
+import com.fs.erp.domain.ErpOrder;
 import com.fs.erp.domain.ErpOrderQuery;
+import com.fs.erp.domain.FsErpFinishPush;
 import com.fs.erp.dto.ErpOrderQueryRequert;
 import com.fs.erp.dto.ErpOrderQueryResponse;
+import com.fs.erp.dto.ErpOrderResponse;
+import com.fs.erp.mapper.FsErpFinishPushMapper;
 import com.fs.erp.service.IErpOrderService;
 import com.fs.fastGpt.mapper.FastGptChatSessionMapper;
 import com.fs.his.config.FsSysConfig;
@@ -38,8 +42,8 @@ import com.fs.his.utils.ConfigUtil;
 import com.fs.his.vo.FsSubOrderResultVO;
 import com.fs.im.dto.*;
 import com.fs.im.service.IImService;
-import com.fs.qw.service.IQwAppContactWayService;
-import com.fs.qw.service.IQwExternalContactTransferLogService;
+import com.fs.qw.domain.QwCompany;
+import com.fs.qw.service.*;
 import com.fs.qwApi.service.QwApiService;
 import com.fs.system.domain.SysConfig;
 import com.fs.system.mapper.SysConfigMapper;
@@ -144,6 +148,19 @@ public class Task {
     ITencentCloudCosService tencentCloudCosService;
     @Autowired
     private ConfigUtil configUtil;
+    @Autowired
+    private IQwCompanyService qwCompanyService;
+    @Autowired
+    private IQwUserService qwUserService;
+
+    public void addQwUserName(){
+        QwCompany qwCompany = new QwCompany();
+        List<QwCompany> companyList = qwCompanyService.selectQwCompanyList(qwCompany);
+        for (QwCompany company : companyList) {
+            qwUserService.syncQwUserName(company.getCorpId());
+        }
+    }
+
     public void videoTranscode() throws Exception
     {
 
@@ -249,10 +266,11 @@ public class Task {
         List<FsStoreOrder> orders = null;
         if (erpOrderService == gyOrderService){
             orders = fsStoreOrderMapper.selectOmsOrderdeliveryOp();
-        } else if (erpOrderService == wdtOrderService){
+        } else if (erpOrderService == wdtOrderService || erpOrderService == dfOrderService){
             orders = fsStoreOrderMapper.selectWdtOmsOrderdeliveryOp();
         }
 
+
         for(FsStoreOrder order:orders){
 
             ErpOrderQueryRequert request=new ErpOrderQueryRequert();
@@ -260,17 +278,19 @@ public class Task {
             request.setCode(order.getExtendOrderId());
             if (erpOrderService != null){
                 ErpOrderQueryResponse response=erpOrderService.getOrder(request);
-                if(response.getOrders()!=null&&response.getOrders().size()>0){
-                    for(ErpOrderQuery orderQuery : response.getOrders()){
-                        if(orderQuery.getDeliverys()!=null&&orderQuery.getDeliverys().size()>0){
-                            for(ErpDeliverys delivery:orderQuery.getDeliverys()){
-                                if(delivery.getDelivery()&& StringUtils.isNotEmpty(delivery.getMail_no())){
-                                    //更新商订单状态 删除REDIS
-                                    fsStoreOrderService.deliveryOrder(order.getOrderCode(),delivery.getMail_no(),delivery.getExpress_code(),delivery.getExpress_name());
-                                    redisCache.deleteObject("delivery"+":"+order.getExtendOrderId());
+                if (erpOrderService != dfOrderService){
+                    if(response.getOrders()!=null&&response.getOrders().size()>0){
+                        for(ErpOrderQuery orderQuery : response.getOrders()){
+                            if(orderQuery.getDeliverys()!=null&&orderQuery.getDeliverys().size()>0){
+                                for(ErpDeliverys delivery:orderQuery.getDeliverys()){
+                                    if(delivery.getDelivery()&& StringUtils.isNotEmpty(delivery.getMail_no())){
+                                        //更新商订单状态 删除REDIS
+                                        fsStoreOrderService.deliveryOrder(order.getOrderCode(),delivery.getMail_no(),delivery.getExpress_code(),delivery.getExpress_name());
+                                        redisCache.deleteObject("delivery"+":"+order.getExtendOrderId());
+                                    }
                                 }
-                            }
 
+                            }
                         }
                     }
                 }
@@ -291,14 +311,14 @@ public class Task {
             } catch (Exception e) {
             }
         }
-        List<Long> tuiOrderList = fsStoreOrderMapper.selectFsStoreOrderNoTuiOrder();
-        for (Long l : tuiOrderList) {
-            try {
-                fsStoreOrderService.tuiOrder(l);
-            } catch (Exception e) {
-            }
-
-        }
+//        List<Long> tuiOrderList = fsStoreOrderMapper.selectFsStoreOrderNoTuiOrder();
+//        for (Long l : tuiOrderList) {
+//            try {
+//                fsStoreOrderService.tuiOrder(l);
+//            } catch (Exception e) {
+//            }
+//
+//        }
     }
 
     public void createFollow()
@@ -988,6 +1008,13 @@ public class Task {
     @Autowired
     @Qualifier("wdtErpOrderServiceImpl")
     private IErpOrderService wdtOrderService;
+    @Autowired
+    @Qualifier("hzOMSErpOrderServiceImpl")
+    private IErpOrderService hzOMSErpOrderService;
+    @Autowired
+    @Qualifier("dfOrderServiceImpl")
+    private IErpOrderService dfOrderService;
+
     private IErpOrderService getErpService() {
         FsSysConfig sysConfig = configUtil.getSysConfig();
         Integer erpOpen = sysConfig.getErpOpen();
@@ -1002,6 +1029,12 @@ public class Task {
                 } else if (erpType == 2){
                     //旺店通
                     erpOrderService =  wdtOrderService;
+                } else if (erpType == 3){
+                    //
+                    erpOrderService =  hzOMSErpOrderService;
+                } else if (erpType == 4){
+                    //代服
+                    erpOrderService =  dfOrderService;
                 }
                 return erpOrderService;
 

+ 7 - 0
fs-admin/src/main/java/com/fs/qw/controller/QwSopTempController.java

@@ -1,5 +1,6 @@
 package com.fs.qw.controller;
 
+import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
 import com.fs.common.annotation.Log;
 import com.fs.common.core.controller.BaseController;
 import com.fs.common.core.domain.AjaxResult;
@@ -21,8 +22,10 @@ import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.*;
 
 import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
+import java.util.stream.Collectors;
 
 /**
  * sop模板Controller
@@ -129,6 +132,10 @@ public class QwSopTempController extends BaseController
         qwSopTemp.setCreateBy(loginUser.getUser().getUserId().toString());
         int i = qwSopTempService.addNew(qwSopTemp);
         if(qwSopTemp.getSendType() == 11){
+            //筛选选课程数据
+            if(ObjectUtils.isNotNull(qwSopTemp.getTimeList()) && !qwSopTemp.getTimeList().isEmpty()){
+                qwSopTemp.setTimeList(new ArrayList<>(qwSopTemp.getTimeList().stream().filter(t->ObjectUtils.isNotNull(t) && !t.isEmpty()).collect(Collectors.toSet())));
+            }
             new Thread(() -> qwSopTempService.createSopTempRules(qwSopTemp)).start();
         }
         return toAjax(i);

+ 1 - 1
fs-admin/src/main/resources/logback.xml

@@ -3,7 +3,7 @@
     <!-- 日志存放路径 -->
 	<property name="log.path" value="/home/fs-admin/logs" />
     <!-- 日志输出格式 -->
-	<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
+    <property name="log.pattern" value="%replace([%X{traceId}] ){'\\[\\s*\\] ', ''}%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
 
 	<!-- 控制台输出 -->
 	<appender name="console" class="ch.qos.logback.core.ConsoleAppender">

+ 2 - 1
fs-common/src/main/java/com/fs/common/enums/DataSourceType.java

@@ -18,5 +18,6 @@ public enum DataSourceType
     /**
      * 从库
      */
-    SLAVE
+    SLAVE,
+    SopREAD
 }

+ 5 - 0
fs-common/src/main/java/com/fs/common/utils/date/DateUtil.java

@@ -5,6 +5,8 @@ import org.springframework.stereotype.Component;
 
 import java.text.SimpleDateFormat;
 import java.time.*;
+import java.time.chrono.ChronoLocalDate;
+import java.time.chrono.ChronoLocalDateTime;
 import java.time.format.DateTimeFormatter;
 import java.time.temporal.ChronoUnit;
 import java.util.Date;
@@ -505,4 +507,7 @@ public final class DateUtil {
 		return !targetDate.isBefore(actualStart) && !targetDate.isAfter(actualEnd);
 	}
 
+	public static long toInstant(ChronoLocalDateTime<? extends ChronoLocalDate> time) {
+		return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
+	}
 }

+ 24 - 0
fs-company-app/src/main/java/com/fs/app/controller/CompanyTagController.java

@@ -6,8 +6,11 @@ import com.fs.common.core.domain.R;
 import com.fs.common.exception.CustomException;
 import com.fs.common.utils.StringUtils;
 import com.fs.company.domain.CompanyTag;
+import com.fs.company.domain.CompanyTagUser;
 import com.fs.company.service.ICompanyTagService;
 import com.fs.company.service.ICompanyTagUserService;
+import com.fs.company.vo.CompanyTagUserVO;
+import com.fs.store.vo.h5.CompanyUserTagListVO;
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.PageInfo;
 import io.swagger.annotations.Api;
@@ -86,4 +89,25 @@ public class CompanyTagController extends AppBaseController {
         params.put("companyId", getCompanyId());
         return R.ok().put("data", companyTagUserService.selectUserListByMap(params));
     }
+
+    @Login
+    @GetMapping("/getTagByUser")
+    @ApiOperation("会员的标签")
+    public R getTagByUser(@RequestParam("userId") Long userId) {
+        CompanyTagUser map = new CompanyTagUser();
+        map.setUserId(userId);
+        map.setCompanyId(getCompanyId());
+        map.setCompanyUserId(Long.valueOf(getUserId()));
+        List<CompanyUserTagListVO> vos = companyTagUserService.getTagByUser(map);
+        StringBuilder tags = new StringBuilder();
+        if (vos != null && !vos.isEmpty()) {
+            for (CompanyUserTagListVO vo : vos) {
+                tags.append(vo.getTagName()).append(",");
+            }
+            if (tags.length() > 0) {
+                tags.deleteCharAt(tags.length() - 1);
+            }
+        }
+        return R.ok().put("data",tags.length()>0?tags.toString():null);
+    }
 }

+ 1 - 1
fs-company-app/src/main/java/com/fs/app/controller/FsUserController.java

@@ -326,7 +326,7 @@ public class FsUserController extends AppBaseController {
             String userPosterImage = jsonObject.getString("userPosterImage");
             String backgroundImagePath;
             if(StringUtils.isEmpty(userPosterImage)){
-                backgroundImagePath = "https://fbylive.obs.cn-southwest-2.myhuaweicloud.com/fs/20250430/1745980979886.png";
+                backgroundImagePath = "https://drk-1363981074.cos.ap-chongqing.myqcloud.com/fs/logo/30d7a0d1ec31e5ac16c6e96d5ca76ad.png";
             } else {
                 backgroundImagePath = userPosterImage;
             }

+ 15 - 1
fs-company-app/src/main/java/com/fs/app/controller/FsUserCourseVideoController.java

@@ -1,5 +1,6 @@
 package com.fs.app.controller;
 
+import cn.hutool.core.util.ObjectUtil;
 import cn.hutool.json.JSONUtil;
 import com.fs.app.annotation.Login;
 import com.fs.app.config.ImageStorageConfig;
@@ -168,7 +169,9 @@ public class FsUserCourseVideoController extends AppBaseController {
 //        String realLink = r.get("realLink").toString();
         String json = configService.selectConfigByKey("course.config");
         CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
-        String realLink = config.getRealLinkDomainName() + FsUserCourseServiceImpl.shortLink + link;
+        //验证是否有分配二级域名
+        CompanyUser companyUser=companyUserService.selectCompanyUserById(param.getCompanyUserId());
+        String realLink = (ObjectUtil.isNotNull(companyUser) && ObjectUtil.isNotNull(companyUser.getDomain())?companyUser.getDomain():config.getRealLinkDomainName()) + FsUserCourseServiceImpl.shortLink + link;
 
         log.info("二维码生成地址:{}", realLink);
         try {
@@ -246,5 +249,16 @@ public class FsUserCourseVideoController extends AppBaseController {
         return fsUserCourseVideoService.setWatchCourseTime(collect);
     }
 
+    /**
+     * 获取跳转微信小程序的链接地址
+     * @param linkStr
+     * @return
+     */
+    @Login
+    @GetMapping("/getGotoWxAppLink")
+    @ApiOperation("获取跳转微信小程序的链接地址")
+    public ResponseResult<String> getGotoWxAppLink(String linkStr,String appid) {
+        return ResponseResult.ok(courseLinkService.getGotoWxAppLink(linkStr,appid));
+    }
 
 }

+ 60 - 0
fs-company-app/src/main/java/com/fs/app/controller/FsUserOperationLogController.java

@@ -0,0 +1,60 @@
+package com.fs.app.controller;
+
+import java.util.List;
+
+import com.fs.app.annotation.Login;
+import com.fs.common.core.domain.R;
+import com.fs.common.core.domain.ResponseResult;
+import com.fs.course.vo.newfs.FsUserCourseVideoPageListVO;
+import com.fs.his.param.FsUserOperationLogQueryParam;
+import com.fs.his.vo.FsUserOperationLogPageVo;
+import com.github.pagehelper.PageHelper;
+import com.github.pagehelper.PageInfo;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import com.fs.common.annotation.Log;
+import com.fs.common.core.controller.BaseController;
+import com.fs.common.core.domain.AjaxResult;
+import com.fs.common.enums.BusinessType;
+import com.fs.his.domain.FsUserOperationLog;
+import com.fs.his.service.IFsUserOperationLogService;
+import com.fs.common.utils.poi.ExcelUtil;
+import com.fs.common.core.page.TableDataInfo;
+
+/**
+ * 用户操作日志Controller
+ *
+ * @author fs
+ * @date 2025-07-04
+ */
+@RestController
+@RequestMapping("/app/operationLog")
+public class FsUserOperationLogController extends AppBaseController
+{
+    @Autowired
+    private IFsUserOperationLogService fsUserOperationLogService;
+
+    /**
+     * 查询用户操作日志列表
+     */
+    @PostMapping("/page")
+    @Login
+    public ResponseResult<PageInfo<FsUserOperationLogPageVo>> list(@RequestBody FsUserOperationLogQueryParam param)
+    {
+        if (param.getUserId() == null){
+            return ResponseResult.fail(500,"未选择会员");
+        }
+        PageHelper.startPage(param.getPageNum(), param.getPageSize());
+        return ResponseResult.ok(fsUserOperationLogService.selectFsUserOperationLogList(param));
+    }
+
+
+}

+ 18 - 1
fs-company-app/src/main/java/com/fs/app/controller/UserController.java

@@ -1,6 +1,7 @@
 package com.fs.app.controller;
 
 import cn.hutool.core.lang.Validator;
+import cn.hutool.core.util.ObjectUtil;
 import cn.hutool.json.JSONUtil;
 import com.alibaba.fastjson.JSONObject;
 import com.fs.app.annotation.Login;
@@ -156,6 +157,7 @@ public class UserController extends AppBaseController {
         }
 
         try {
+
             //判断用户基本规则
             CompanyUser companyUser = userService.selectUserByUserName(param.getAccount());
             if (companyUser == null) {
@@ -176,6 +178,10 @@ public class UserController extends AppBaseController {
                 throw new BaseException("此用户所属公司不存在或已停用");
             }
 
+            if (StringUtils.isNotEmpty(company.getCourseMiniAppId()) && !company.getCourseMiniAppId().equals(param.getAppId())){
+                return R.error("登录用户不属于该小程序");
+            }
+
             // 公司名称
             companyUser.setCompanyName(company.getCompanyName());
             // 岗位
@@ -676,7 +682,18 @@ public class UserController extends AppBaseController {
     @PostMapping("/audit")
     public R auditUser(@RequestParam List<Long> userIds) {
         log.debug("批量审核用户 userIds :{}", userIds);
-        companyUserService.auditUsers(userIds);
+        if(ObjectUtil.isNotNull(userIds) && !userIds.isEmpty() && userIds.size() > 20){
+            return R.error("审核用户一次性不能大于20人!");
+        }
+
+        CompanyUser companyUser = companyUserService.selectCompanyUserByUserId(Long.parseLong(getUserId()));
+        if (ObjectUtil.isEmpty(companyUser)) {
+            return R.error("当前操作用户不存在!");
+        }else if (!companyUser.isAdmin()) {
+            return R.error("没有权限");
+        }
+
+        companyUserService.auditUsers(userIds,companyUser.getCompanyId());
         return R.ok();
     }
 

+ 2 - 0
fs-company-app/src/main/java/com/fs/app/param/LoginParam.java

@@ -14,4 +14,6 @@ public class LoginParam {
     private String password;
 
     private String jpushId;
+
+    private String appId;
 }

+ 2 - 1
fs-company-app/src/main/resources/application.yml

@@ -5,4 +5,5 @@ server:
 # Spring配置
 spring:
   profiles:
-    active: druid-fcky-test
+#    active: druid-fcky-test
+    active: dev

+ 17 - 0
fs-company/src/main/java/com/fs/company/controller/company/CompanyConfigController.java

@@ -1,12 +1,15 @@
 package com.fs.company.controller.company;
 
 import com.fs.common.core.controller.BaseController;
+import com.fs.common.core.domain.AjaxResult;
 import com.fs.common.core.domain.R;
 import com.fs.common.utils.ServletUtils;
 import com.fs.company.domain.CompanyConfig;
 import com.fs.company.service.ICompanyConfigService;
 import com.fs.framework.security.LoginUser;
 import com.fs.framework.service.TokenService;
+import com.fs.system.domain.SysConfig;
+import com.fs.system.service.ISysConfigService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.validation.annotation.Validated;
@@ -28,6 +31,9 @@ public class CompanyConfigController extends BaseController
     @Autowired
     private TokenService tokenService;
 
+    @Autowired
+    private ISysConfigService configService;
+
 
 
     @PreAuthorize("@ss.hasPermi('company:config:edit')")
@@ -40,6 +46,17 @@ public class CompanyConfigController extends BaseController
         return R.ok("操作成功");
     }
 
+    /**
+     * 根据参数键名查询总后台参数值
+     * @param configKey
+     * @return
+     */
+    @GetMapping(value = "/getConfigByKey/{configKey}")
+    public AjaxResult getConfigByKey(@PathVariable String configKey)
+    {
+        SysConfig config=configService.selectConfigByConfigKey(configKey);
+        return AjaxResult.success(config);
+    }
 
     /**
      * 根据参数键名查询参数值

+ 15 - 0
fs-company/src/main/java/com/fs/company/controller/company/CompanyDeptController.java

@@ -47,6 +47,21 @@ public class CompanyDeptController extends BaseController
         return AjaxResult.success(depts);
     }
 
+
+    /**
+     * 获取部门下拉树列表
+     */
+    @GetMapping("/myDeptTreeselect")
+    public AjaxResult myDeptTreeselect(CompanyDept dept)
+    {
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        dept.setCompanyId(loginUser.getCompany().getCompanyId());
+        dept.setStatus("0");
+        dept.setParentId(loginUser.getUser().getDeptId());
+        List<CompanyDept> depts = deptService.selectCompanyDeptListByDeptAndParent(dept);
+        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
+    }
+
     /**
      * 查询部门列表(排除节点)
      */

+ 29 - 0
fs-company/src/main/java/com/fs/company/controller/company/CompanyLoginController.java

@@ -1,5 +1,6 @@
 package com.fs.company.controller.company;
 
+import com.alibaba.fastjson.JSONObject;
 import com.fs.common.constant.Constants;
 import com.fs.common.core.domain.AjaxResult;
 import com.fs.common.core.redis.RedisCache;
@@ -13,6 +14,8 @@ import com.fs.framework.security.LoginUser;
 import com.fs.framework.service.CompanyLoginService;
 import com.fs.framework.service.CompanyPermissionService;
 import com.fs.framework.service.TokenService;
+import com.fs.system.domain.SysConfig;
+import com.fs.system.service.ISysConfigService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
@@ -43,6 +46,8 @@ public class CompanyLoginController
     private TokenService tokenService;
     @Autowired
     private RedisCache redisCache;
+    @Autowired
+    private ISysConfigService configService;
 
     /**
      * 登录方法
@@ -104,5 +109,29 @@ public class CompanyLoginController
         return AjaxResult.success(menuService.buildMenus(menus));
     }
 
+
+    /**
+     * 根据系统配置去查询是否需要首次登录,并开启校验
+     * @return
+     */
+    @GetMapping("getFirstLogin")
+    public AjaxResult getFirstLogin()
+    {
+        SysConfig config = configService.selectConfigByConfigKey("his.login");
+        if(config != null && config.getConfigValue() != null){
+            String configValue = config.getConfigValue();
+            JSONObject jsonObject = JSONObject.parseObject(configValue);
+            Boolean disabled = jsonObject.getBoolean("disabled");
+            if(disabled){
+                LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+                Long userId = redisCache.getCacheObject("newCompanyUser:" + loginUser.getUser().getCompanyId() + ":" + loginUser.getUser().getUserName());
+                if (loginUser.getUser().getUserId().equals(userId)) {
+                    return AjaxResult.success(true);
+                }
+            }
+        }
+        return AjaxResult.success(false);
+    }
+
 }
 

+ 13 - 0
fs-company/src/main/java/com/fs/company/controller/company/CompanyProfileController.java

@@ -4,6 +4,7 @@ import com.fs.common.annotation.Log;
 import com.fs.common.config.FSConfig;
 import com.fs.common.core.controller.BaseController;
 import com.fs.common.core.domain.AjaxResult;
+import com.fs.common.core.redis.RedisCache;
 import com.fs.common.enums.BusinessType;
 import com.fs.common.utils.PatternUtils;
 import com.fs.common.utils.ServletUtils;
@@ -14,6 +15,7 @@ import com.fs.company.service.ICompanyUserService;
 import com.fs.framework.security.LoginUser;
 import com.fs.framework.security.SecurityUtils;
 import com.fs.framework.service.TokenService;
+import com.fs.system.service.ISysConfigService;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
@@ -34,6 +36,8 @@ public class CompanyProfileController extends BaseController
 
     @Autowired
     private TokenService tokenService;
+    @Autowired
+    private RedisCache redisCache;
 
     /**
      * 个人信息
@@ -103,11 +107,20 @@ public class CompanyProfileController extends BaseController
             // 更新缓存用户密码
             loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
             tokenService.setLoginUser(loginUser);
+            cleanFirstLogin(loginUser);
             return AjaxResult.success();
         }
         return AjaxResult.error("修改密码异常,请联系管理员");
     }
 
+    /**
+     * 去除首次登录的标志
+     * @param loginUser
+     */
+    private void cleanFirstLogin(LoginUser loginUser) {
+        redisCache.deleteObject("newCompanyUser:" + loginUser.getUser().getCompanyId() + ":" + loginUser.getUser().getUserName());
+    }
+
     /**
      * 头像上传
      */

+ 56 - 3
fs-company/src/main/java/com/fs/company/controller/company/CompanyUserController.java

@@ -18,24 +18,27 @@ import com.fs.company.mapper.CompanyUserDelayTimeMapper;
 import com.fs.company.param.CompanyUserAreaParam;
 import com.fs.company.param.CompanyUserQwParam;
 import com.fs.company.service.*;
+import com.fs.company.utils.DomainUtil;
 import com.fs.company.vo.CompanyUserQwListVO;
 import com.fs.company.vo.CompanyUserVO;
 import com.fs.course.config.CourseConfig;
 import com.fs.framework.security.LoginUser;
 import com.fs.framework.security.SecurityUtils;
 import com.fs.framework.service.TokenService;
+import com.fs.his.vo.OptionsVO;
 import com.fs.qw.vo.CompanyUserQwVO;
 import com.fs.qw.vo.QwUserVO;
 import com.fs.system.service.ISysConfigService;
 import com.fs.voice.utils.StringUtil;
+import com.github.pagehelper.PageHelper;
+import com.github.pagehelper.PageInfo;
+import org.apache.ibatis.annotations.Param;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.validation.annotation.Validated;
 import org.springframework.web.bind.annotation.*;
 
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
+import java.util.*;
 import java.util.stream.Collectors;
 
 
@@ -362,5 +365,55 @@ public class CompanyUserController extends BaseController
         return companyUserService.updateCompanyUserAreaList(param);
     }
 
+    /**
+     * 根据销售名称模糊查询
+     * @param name  名称
+     * @return  list
+     */
+    @GetMapping("/getCompanyUserListLikeName")
+    public R getCompanyUserListLikeName(@RequestParam(required = false) String name,
+                                        @RequestParam(required = false, defaultValue = "1") Integer pageNum,
+                                        @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
+        Map<String,Object> params = new HashMap<>();
+        params.put("nickName", name);
+
+        PageHelper.startPage(pageNum, pageSize);
+        List<OptionsVO> companyUserList = companyUserService.selectCompanyUserListByMap(params);
+        return R.ok().put("data", new PageInfo<>(companyUserList));
+    }
+
+
+    /**
+     * 获取用户列表
+     */
+    @GetMapping("/getCompanyUserList")
+    public TableDataInfo getCompanyUserList(CompanyUser user)
+    {
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        user.setCompanyId(loginUser.getCompany().getCompanyId());
+        startPage();
+        List<CompanyUser> list = companyUserService.getCompanyUserList(user);
+        return getDataTable(list);
+    }
 
+    @GetMapping("/generateSubDomain")
+    public R generateSubDomain(CompanyUser user){
+        //获取后台配置
+        String json= configService.selectConfigByKey("course.config");
+        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
+        // 生成二级域名
+        String subDomain = "http://" + DomainUtil.generateSubDomain(config.getCourseDomainName(), 6, String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
+        return  R.ok().put("data",subDomain);
+    }
+
+    @Log(title = "设置是否需要单独注册会员", businessType = BusinessType.UPDATE)
+    @PutMapping("/setRegister")
+    public AjaxResult setIsRegisterMember(@RequestParam Boolean status, @RequestBody List<Long> userIds) {
+        Boolean r = companyUserService.setIsRegisterMember(status, userIds);
+        if (r) {
+            return AjaxResult.success();
+        } else {
+            return AjaxResult.error("操作失败");
+        }
+    }
 }

+ 3 - 1
fs-company/src/main/java/com/fs/company/controller/course/FsCourseRedPacketLogController.java

@@ -213,7 +213,9 @@ public class FsCourseRedPacketLogController extends BaseController
     @GetMapping("/courseList")
     public R courseList()
     {
-        List<OptionsVO> optionsVOS = fsUserCourseMapper.selectFsUserCourseAllList();
+
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        List<OptionsVO> optionsVOS = fsUserCourseMapper.selectFsUserCourseByCompany(loginUser.getCompany().getCompanyId());
         return R.ok().put("list", optionsVOS);
     }
 

+ 4 - 1
fs-company/src/main/java/com/fs/company/controller/course/FsCourseWatchLogController.java

@@ -61,6 +61,7 @@ public class FsCourseWatchLogController extends BaseController
     @GetMapping("/list")
     public TableDataInfo list(FsCourseWatchLogListParam param)
     {
+
         startPage();
         LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
         param.setCompanyId( loginUser.getCompany().getCompanyId());
@@ -225,6 +226,7 @@ public class FsCourseWatchLogController extends BaseController
     {
         LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
         param.setCompanyId( loginUser.getCompany().getCompanyId());
+        param.setCompanyUserId( loginUser.getUser().getUserId());
         List<FsCourseWatchLogListVO> list = fsCourseWatchLogService.selectFsCourseWatchLogListVO(param);
         ExcelUtil<FsCourseWatchLogListVO> util = new ExcelUtil<FsCourseWatchLogListVO>(FsCourseWatchLogListVO.class);
         return util.exportExcel(list, "短链课程看课记录数据");
@@ -239,7 +241,8 @@ public class FsCourseWatchLogController extends BaseController
     public AjaxResult myExport(FsCourseWatchLogListParam param)
     {
         LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
-        param.setCompanyId( loginUser.getCompany().getCompanyId());
+//        param.setCompanyId( loginUser.getCompany().getCompanyId());
+        param.setCompanyUserId( loginUser.getUser().getUserId());
         List<FsCourseWatchLogListVO> list = fsCourseWatchLogService.selectFsCourseWatchLogListVO(param);
         ExcelUtil<FsCourseWatchLogListVO> util = new ExcelUtil<FsCourseWatchLogListVO>(FsCourseWatchLogListVO.class);
         return util.exportExcel(list, "短链课程看课记录数据");

+ 15 - 0
fs-company/src/main/java/com/fs/company/controller/course/FsUserCoursePeriodController.java

@@ -14,6 +14,7 @@ import com.fs.course.domain.FsUserCourseVideoRedPackage;
 import com.fs.course.param.CompanyRedPacketParam;
 import com.fs.course.param.FsBatchPeriodRedPackageParam;
 import com.fs.course.param.PeriodCountParam;
+import com.fs.course.param.PeriodStatisticCountParam;
 import com.fs.course.service.IFsUserCoursePeriodDaysService;
 import com.fs.course.service.IFsUserCoursePeriodService;
 import com.fs.course.service.IFsUserCourseVideoRedPackageService;
@@ -252,5 +253,19 @@ public class FsUserCoursePeriodController extends BaseController {
         fsUserCoursePeriodService.closePeriod(id);
         return R.ok();
     }
+    @PostMapping("/periodCourseStatisticCount")
+    @ApiOperation("会员详情训练营数据总览")
+    public R periodCourseStatisticCount(@RequestBody PeriodStatisticCountParam param) {
+        if (param == null) {
+            return R.error("请求参数不能为空!");
+        }
+        return R.ok().put("data", fsUserCoursePeriodService.periodCourseStatisticCount(param));
+    }
 
+    @PostMapping("/periodlist")
+    public R periodList(@RequestBody PeriodStatisticCountParam param)
+    {
+        List<FsUserCoursePeriod> list = fsUserCoursePeriodService.selectFsPeriodlist(param);
+        return R.ok().put("data", list);
+    }
 }

+ 58 - 0
fs-company/src/main/java/com/fs/company/controller/course/FsUserCourseTrainingCampController.java

@@ -0,0 +1,58 @@
+package com.fs.company.controller.course;
+
+import com.fs.common.annotation.Log;
+import com.fs.common.core.domain.AjaxResult;
+import com.fs.common.core.domain.R;
+import com.fs.common.enums.BusinessType;
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.SortUtils;
+import com.fs.course.domain.FsUserCourseTrainingCamp;
+import com.fs.course.dto.FsUserCourseTrainingCampDTO;
+import com.fs.course.dto.FsUserCourseTrainingCampUpdateDTO;
+import com.fs.course.service.IFsUserCourseTrainingCampService;
+import com.fs.course.vo.FsUserCourseTrainingCampVO;
+import com.fs.framework.security.LoginUser;
+import com.fs.framework.service.TokenService;
+import com.fs.his.vo.OptionsVO;
+import com.github.pagehelper.PageHelper;
+import com.github.pagehelper.PageInfo;
+import lombok.AllArgsConstructor;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.*;
+
+import javax.validation.Valid;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+@RestController
+@RequestMapping("/course/trainingCamp")
+@AllArgsConstructor
+public class FsUserCourseTrainingCampController {
+
+    private final IFsUserCourseTrainingCampService fsUserCourseTrainingCampService;
+    private final TokenService tokenService;
+    /**
+     * 查询训练营列表
+     */
+    @PreAuthorize("@ss.hasPermi('course:trainingCamp:list')")
+    @GetMapping("/list")
+    public AjaxResult list(@RequestParam(required = false) String trainingCampName,
+                           @RequestParam(required = false) String userId,
+                           @RequestParam String scs,
+                           @RequestParam(required = false, defaultValue = "1") Integer pageNum,
+                           @RequestParam(required = false, defaultValue = "10") Integer pageSize)
+    {
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        Map<String, Object> params = new HashMap<>();
+        params.put("trainingCampName", trainingCampName);
+        params.put("scs", SortUtils.parseSort(scs));
+        params.put("companyId", loginUser.getCompany().getCompanyId());
+        params.put("userId", userId);
+        PageHelper.startPage(pageNum, pageSize);
+        List<FsUserCourseTrainingCampVO> list = fsUserCourseTrainingCampService.selectFsUserCourseTrainingCampVOListByMap(params);
+        return AjaxResult.success(new PageInfo<>(list));
+    }
+
+}

+ 43 - 0
fs-company/src/main/java/com/fs/company/controller/course/FsUserOperationLogController.java

@@ -0,0 +1,43 @@
+package com.fs.company.controller.course;
+
+import com.fs.common.core.controller.BaseController;
+import com.fs.common.core.domain.R;
+import com.fs.common.core.page.TableDataInfo;
+import com.fs.his.domain.FsUserOperationLog;
+import com.fs.his.service.IFsUserOperationLogService;
+import com.fs.his.vo.FsUserOperationLogVo;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.List;
+
+/**
+ * 用户操作日志对象
+ */
+@RestController
+@RequestMapping("/his/userOperationLog")
+public class FsUserOperationLogController extends BaseController {
+
+    @Autowired
+    private IFsUserOperationLogService fsUserOperationLogService;
+
+    @PreAuthorize("@ss.hasPermi('his:userOperationLog:list')")
+    @GetMapping("/list")
+    public TableDataInfo list(FsUserOperationLog fsUserOperationLog)
+    {
+        startPage();
+        List<FsUserOperationLogVo> list = fsUserOperationLogService.selectFsUserOperationLogByList(fsUserOperationLog);
+
+        return getDataTable(list);
+    }
+
+    @GetMapping("/getOperationType")
+    public R getOperationType()
+    {
+        return R.ok().put("data",fsUserOperationLogService.getOperationType());
+    }
+}

+ 10 - 4
fs-company/src/main/java/com/fs/company/controller/course/qw/FsQwCourseWatchLogController.java

@@ -8,10 +8,7 @@ import com.fs.common.enums.BusinessType;
 import com.fs.common.utils.ServletUtils;
 import com.fs.common.utils.poi.ExcelUtil;
 import com.fs.course.domain.FsCourseWatchLog;
-import com.fs.course.param.FsCourseOverParam;
-import com.fs.course.param.FsCourseUserStatisticsListParam;
-import com.fs.course.param.FsCourseWatchLogListParam;
-import com.fs.course.param.FsCourseWatchLogStatisticsListParam;
+import com.fs.course.param.*;
 import com.fs.course.service.IFsCourseWatchLogService;
 import com.fs.course.vo.FsCourseOverVO;
 import com.fs.course.vo.FsCourseUserStatisticsListVO;
@@ -259,4 +256,13 @@ public class FsQwCourseWatchLogController extends BaseController
     {
         return toAjax(fsCourseWatchLogService.deleteFsCourseWatchLogByLogIds(logIds));
     }
+
+    //    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:list')")
+    @GetMapping("/listBytrainingCampId")
+    public TableDataInfo listBytrainingCampId(PeriodStatisticCountParam param)
+    {
+        startPage();
+        List<FsCourseWatchLogListVO> list = fsCourseWatchLogService.selectListBytrainingCampId(param);
+        return getDataTable(list);
+    }
 }

+ 57 - 2
fs-company/src/main/java/com/fs/company/controller/qw/QwExternalContactController.java

@@ -207,12 +207,14 @@ public class QwExternalContactController extends BaseController
         return getDataTable(list);
     }
 
+
     @Log(title = "同步我的企业微信客户", businessType = BusinessType.INSERT)
     @GetMapping("/syncMyExternalContact/{id}")
     public R  syncMyExternalContact(@PathVariable("id") Long id ) throws IOException {
         return qwExternalContactService.syncMyQwExternalContact(id);
     }
 
+
     @Log(title = "新客同步", businessType = BusinessType.INSERT)
     @GetMapping("/syncAddMyExternalContact/{id}")
     public R  syncAddMyExternalContact(@PathVariable("id") Long id ) throws IOException {
@@ -226,11 +228,64 @@ public class QwExternalContactController extends BaseController
     @Log(title = "企业微信客户", businessType = BusinessType.EXPORT)
     @GetMapping("/export")
     public AjaxResult export(QwExternalContactParam qwExternalContact)
+    {
+        if (qwExternalContact.getCorpId()==null){
+            return AjaxResult.success();
+        }
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwExternalContact.setCompanyId(loginUser.getCompany().getCompanyId());
+        List<QwExternalContactVO> list = qwExternalContactService.selectQwExternalContactListVO(qwExternalContact);
+        list.forEach(item->{
+
+            if (!Objects.equals(item.getTagIds(), "[]") && item.getTagIds()!=null) {
+                QwTagSearchParam param = new QwTagSearchParam();
+                Gson gson = new Gson();
+                List<String> tagIds = gson.fromJson(
+                        item.getTagIds(),
+                        new TypeToken<List<String>>() {
+                        }.getType()
+                );
+
+                param.setTagIds(tagIds);
+
+                item.setTagIdsName(iQwTagService.selectQwTagListByTagIds(param));
+            }
+        });
+        ExcelUtil<QwExternalContactVO> util = new ExcelUtil<QwExternalContactVO>(QwExternalContactVO.class);
+        return util.exportExcel(list, "企业微信客户数据");
+    }
+
+
+    @PreAuthorize("@ss.hasPermi('qw:externalContact:myExport')")
+    @Log(title = "企业微信客户", businessType = BusinessType.EXPORT)
+    @GetMapping("/myExport")
+    public AjaxResult myExport(QwExternalContactParam qwExternalContact)
     {
         if (qwExternalContact.getQwUserId()==null){
             return AjaxResult.success();
         }
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwExternalContact.setCompanyId(loginUser.getCompany().getCompanyId());
+
         List<QwExternalContactVO> list = qwExternalContactService.selectQwExternalContactListVO(qwExternalContact);
+
+        list.forEach(item->{
+
+            if (!Objects.equals(item.getTagIds(), "[]") && item.getTagIds()!=null) {
+                QwTagSearchParam param = new QwTagSearchParam();
+                Gson gson = new Gson();
+                List<String> tagIds = gson.fromJson(
+                        item.getTagIds(),
+                        new TypeToken<List<String>>() {
+                        }.getType()
+                );
+
+                param.setTagIds(tagIds);
+
+                item.setTagIdsName(iQwTagService.selectQwTagListByTagIds(param));
+            }
+        });
+
         ExcelUtil<QwExternalContactVO> util = new ExcelUtil<QwExternalContactVO>(QwExternalContactVO.class);
         return util.exportExcel(list, "企业微信客户数据");
     }
@@ -269,7 +324,7 @@ public class QwExternalContactController extends BaseController
         return qwExternalContactService.syncQwExternalContactUnassigned(qwExternalContact.getCorpId());
     }
 
-    @PreAuthorize("@ss.hasPermi('qw:externalContact:addTag')")
+    @PreAuthorize("@ss.hasPermi('qw:externalContact:addTag') or @ss.hasPermi('qw:externalContact:myAddTag') or @ss.hasPermi('qw:externalContact:deptAddTag')")
     @Log(title = "添加标签", businessType = BusinessType.UPDATE)
     @PostMapping("/addTag")
     public R addTag(@RequestBody QwExternalContactAddTagParam Param) throws JSONException {
@@ -286,7 +341,7 @@ public class QwExternalContactController extends BaseController
 
     }
 
-    @PreAuthorize("@ss.hasPermi('qw:externalContact:delTag')")
+    @PreAuthorize("@ss.hasPermi('qw:externalContact:delTag') or @ss.hasPermi('qw:externalContact:myDelTag') or @ss.hasPermi('qw:externalContact:deptDelTag')")
     @Log(title = "移除标签", businessType = BusinessType.UPDATE)
     @PostMapping("/delTag")
     public R delTag(@RequestBody QwExternalContactAddTagParam Param)

+ 3 - 1
fs-company/src/main/java/com/fs/company/controller/qw/QwExternalContactInfoController.java

@@ -76,7 +76,7 @@ public class QwExternalContactInfoController extends BaseController
     /**
      * 修改外部联系人信息表
      */
-    @PreAuthorize("@ss.hasPermi('qw:externalContactInfo:edit')")
+    @PreAuthorize("@ss.hasPermi('qw:externalContactInfo:edit') or @ss.hasPermi('qw:externalContactInfo:myEdit') or @ss.hasPermi('qw:externalContactInfo:deptEdit')")
     @Log(title = "外部联系人信息表", businessType = BusinessType.UPDATE)
     @PutMapping
     public AjaxResult edit(@RequestBody QwExternalContactInfo qwExternalContactInfo)
@@ -98,6 +98,7 @@ public class QwExternalContactInfoController extends BaseController
 
 
 
+    @PreAuthorize("@ss.hasPermi('qw:externalContactInfo:updateTalk') or @ss.hasPermi('qw:externalContactInfo:myUpdateTalk') or @ss.hasPermi('qw:externalContactInfo:deptUpdateTalk')")
     @Log(title = "更改外部联系人信息表", businessType = BusinessType.UPDATE)
     @PutMapping("/editTalk/{ids}")
     public AjaxResult editTalk(@PathVariable Long[] ids)
@@ -105,6 +106,7 @@ public class QwExternalContactInfoController extends BaseController
         return toAjax(qwExternalContactInfoService.updateQwExternalContactInfoByIds(ids));
     }
 
+    @PreAuthorize("@ss.hasPermi('qw:externalContactInfo:updateAllTalk') or @ss.hasPermi('qw:externalContactInfo:myUpdateAllTalk') or @ss.hasPermi('qw:externalContactInfo:deptUpdateAllTalk')")
     @Log(title = "更改外部联系人信息表", businessType = BusinessType.UPDATE)
     @PutMapping("/editAllTalk/{id}")
     public AjaxResult editAllTalk(@PathVariable Long id)

+ 0 - 2
fs-company/src/main/java/com/fs/company/controller/qw/QwGroupChatUserController.java

@@ -35,7 +35,6 @@ public class QwGroupChatUserController extends BaseController
     /**
      * 查询客户群成员列列表
      */
-    @PreAuthorize("@ss.hasPermi('qw:group_chat_user:list')")
     @GetMapping("/list")
     public TableDataInfo list(QwGroupChatUser qwGroupChatUser)
     {
@@ -48,7 +47,6 @@ public class QwGroupChatUserController extends BaseController
     /**
      * 获取客户群成员列详细信息
      */
-    @PreAuthorize("@ss.hasPermi('qw:group_chat_user:query')")
     @GetMapping(value = "/{id}")
     public AjaxResult getInfo(@PathVariable("id") Long id)
     {

+ 20 - 0
fs-company/src/main/java/com/fs/company/controller/qw/QwSopController.java

@@ -184,6 +184,26 @@ public class QwSopController extends BaseController
         return util.exportExcel(list, "企微sop数据");
     }
 
+    /**
+     * 我的企微导出sop
+     * @param qwSop
+     * @return
+     */
+    @PreAuthorize("@ss.hasPermi('qw:sop:myExport')")
+    @Log(title = "我的企微sop", businessType = BusinessType.EXPORT)
+    @GetMapping("/myExport")
+    public AjaxResult myExport(QwSop qwSop)
+    {
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        Long companyId = loginUser.getCompany().getCompanyId();
+        Long userId = loginUser.getUser().getUserId();
+        qwSop.setCompanyId(companyId);
+        qwSop.setUserId(userId);
+        List<QwSop> list = qwSopService.selectQwSopList(qwSop);
+        ExcelUtil<QwSop> util = new ExcelUtil<QwSop>(QwSop.class);
+        return util.exportExcel(list, "企微sop数据");
+    }
+
     /**
      * 获取企微sop详细信息
      */

+ 7 - 0
fs-company/src/main/java/com/fs/company/controller/qw/QwSopTempController.java

@@ -1,5 +1,6 @@
 package com.fs.company.controller.qw;
 
+import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
 import com.fs.common.annotation.Log;
 import com.fs.common.core.controller.BaseController;
 import com.fs.common.core.domain.AjaxResult;
@@ -21,8 +22,10 @@ import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.*;
 
 import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
+import java.util.stream.Collectors;
 
 /**
  * sop模板Controller
@@ -136,6 +139,10 @@ public class QwSopTempController extends BaseController
         qwSopTemp.setCreateBy(loginUser.getUser().getUserId().toString());
         int i = qwSopTempService.addNew(qwSopTemp);
         if(qwSopTemp.getSendType() == 11){
+            //筛选选课程数据
+            if(ObjectUtils.isNotNull(qwSopTemp.getTimeList()) && !qwSopTemp.getTimeList().isEmpty()){
+                qwSopTemp.setTimeList(new ArrayList<>(qwSopTemp.getTimeList().stream().filter(t->ObjectUtils.isNotNull(t) && !t.isEmpty()).collect(Collectors.toSet())));
+            }
             new Thread(() -> qwSopTempService.createSopTempRules(qwSopTemp)).start();
         }
         return toAjax(i);

+ 37 - 1
fs-company/src/main/java/com/fs/company/controller/qw/QwUserController.java

@@ -35,6 +35,7 @@ import com.fs.qw.service.IQwExternalContactService;
 import com.fs.qw.service.IQwUserService;
 import com.fs.qw.vo.QwOptionsVO;
 import com.fs.qw.vo.QwUserVO;
+import com.fs.qw.vo.UpdateSendTypeVo;
 import com.fs.qwApi.domain.QwExternalContactAllListResult;
 import com.fs.qwApi.domain.inner.ExternalContact;
 import com.fs.qwApi.domain.inner.ExternalContactInfo;
@@ -42,6 +43,8 @@ import com.fs.qwApi.domain.inner.FollowInfo;
 import com.fs.qwApi.param.QwExternalListParam;
 import com.fs.qwApi.service.QwApiService;
 import com.fs.voice.utils.StringUtil;
+import com.github.pagehelper.PageHelper;
+import com.github.pagehelper.PageInfo;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;
@@ -274,6 +277,17 @@ public class QwUserController extends BaseController
         return toAjax(qwUserService.updateQwUser(qwUser));
     }
 
+    /**
+     * 自动发课启用禁用
+     * @param qwUser
+     * @return
+     */
+    @PostMapping("/updateIsAuto")
+    @PreAuthorize("@ss.hasPermi('qw:user:isauto')")
+    public AjaxResult updateIsAuto(@RequestBody QwUser qwUser){
+        return toAjax(qwUserService.updateQwUser(qwUser));
+    }
+
     /**
     * 企业微信员工账号 绑定 云主机
     */
@@ -346,6 +360,23 @@ public class QwUserController extends BaseController
         return qwUserService.qwUnbindCloudHost(appKey);
     }
 
+    /**
+     * 根据销售名称模糊查询
+     * @param qwUserName  名称
+     * @return  list
+     */
+    @GetMapping("/getQwUserListLikeName")
+    public R getQwUserListLikeName(@RequestParam(required = false) String qwUserName,
+                                        @RequestParam(required = false, defaultValue = "1") Integer pageNum,
+                                        @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
+        Map<String,Object> params = new HashMap<>();
+        params.put("qwUserName", qwUserName);
+
+        PageHelper.startPage(pageNum, pageSize);
+        List<QwOptionsVO> qwUserList = companyUserService.selectQwUserListLikeName(params);
+        return R.ok().put("data", new PageInfo<>(qwUserList));
+    }
+
     /**
      * 查询企微用户列表
      */
@@ -489,7 +520,7 @@ public class QwUserController extends BaseController
             if (string.equals(corpId)){
                 qwUserService.syncQwUser(string);
                 qwDeptService.insertOrUpdateQwDept(string);
-                System.out.println("同步完成");
+                logger.info("同步完成");
             }
         }
         return R.ok();
@@ -796,4 +827,9 @@ public class QwUserController extends BaseController
     public R restartCloudHost(@RequestParam String serverIp) {
         return qwUserService.restartCloudHost(serverIp);
     }
+    @PostMapping("/updateSendType")
+    public R updateSendType(@RequestBody UpdateSendTypeVo vo) {
+        return qwUserService.updateSendType(vo);
+    }
+
 }

+ 212 - 0
fs-company/src/main/java/com/fs/company/controller/qw/QwUserVoiceLogController.java

@@ -0,0 +1,212 @@
+package com.fs.company.controller.qw;
+
+import com.fs.common.annotation.Log;
+import com.fs.common.core.controller.BaseController;
+import com.fs.common.core.domain.AjaxResult;
+import com.fs.common.core.page.TableDataInfo;
+import com.fs.common.enums.BusinessType;
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.poi.ExcelUtil;
+import com.fs.framework.security.LoginUser;
+import com.fs.framework.service.TokenService;
+import com.fs.qw.domain.QwUserVoiceLog;
+import com.fs.qw.service.IQwUserVoiceLogService;
+import com.fs.qw.vo.QwUserVoiceLogTotalVo;
+import com.fs.qw.vo.QwUserVoiceLogVo;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+/**
+ * 企微用户通话记录Controller
+ *
+ * @author fs
+ * @date 2025-05-08
+ */
+@RestController
+@RequestMapping("/qw/qwUserVoiceLog")
+public class QwUserVoiceLogController extends BaseController
+{
+    @Autowired
+    private IQwUserVoiceLogService qwUserVoiceLogService;
+
+    @Autowired
+    private TokenService tokenService;
+
+    /**
+     * 查询企微用户通话记录列表
+     */
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:list')")
+    @GetMapping("/list")
+    public TableDataInfo list(QwUserVoiceLogVo qwUserVoiceLog)
+    {
+        startPage();
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwUserVoiceLog.setCompanyId(loginUser.getCompany().getCompanyId());
+        List<QwUserVoiceLogVo> list = qwUserVoiceLogService.selectQwUserVoiceLogList(qwUserVoiceLog);
+        return getDataTable(list);
+    }
+
+    /**
+     * 查询我的通话记录列表
+     * @param qwUserVoiceLog
+     * @return
+     */
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:myList')")
+    @GetMapping("/myList")
+    public TableDataInfo myList(QwUserVoiceLogVo qwUserVoiceLog)
+    {
+        startPage();
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwUserVoiceLog.setCompanyUserId(loginUser.getUser().getUserId());
+        qwUserVoiceLog.setCompanyId(loginUser.getCompany().getCompanyId());
+        List<QwUserVoiceLogVo> list = qwUserVoiceLogService.selectQwUserVoiceLogList(qwUserVoiceLog);
+        return getDataTable(list);
+    }
+
+    /**
+     * 导出我的通话记录
+     */
+
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:myExport')")
+    @Log(title = "我的通话记录", businessType = BusinessType.EXPORT)
+    @GetMapping("/myExport")
+    public AjaxResult myExport(QwUserVoiceLogVo qwUserVoiceLog)
+    {
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwUserVoiceLog.setCompanyUserId(loginUser.getUser().getUserId());
+        qwUserVoiceLog.setCompanyId(loginUser.getCompany().getCompanyId());
+        List<QwUserVoiceLogVo> list = qwUserVoiceLogService.selectQwUserVoiceLogList(qwUserVoiceLog);
+        list.forEach(m-> {
+            m.setCompanyUserName(m.getCompanyUser().getUserName());
+            m.setCompanyName(m.getCompany().getCompanyName());
+            m.setExtName(m.getQwExternalContact().getName());
+            m.setQwUserName(m.getQwUser().getQwUserName());
+        });
+        ExcelUtil<QwUserVoiceLogVo> util = new ExcelUtil<QwUserVoiceLogVo>(QwUserVoiceLogVo.class);
+        return util.exportExcel(list, "企微用户通话记录数据");
+    }
+
+
+    /**
+     * 统计查询企微用户通话记录
+     * @param qwUserVoiceLog
+     * @return
+     */
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:totalList')")
+    @GetMapping("/totalList")
+    public TableDataInfo totalList(QwUserVoiceLogTotalVo qwUserVoiceLog)
+    {
+        startPage();
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwUserVoiceLog.setCompanyId(loginUser.getCompany().getCompanyId());
+        qwUserVoiceLog.setQwUserId(1L);
+        List<QwUserVoiceLogTotalVo> list = qwUserVoiceLogService.selectQwUserVoiceLogTotalList(qwUserVoiceLog);
+        return getDataTable(list);
+    }
+
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:sellTotalList')")
+    @GetMapping("/sellTotalList")
+    public TableDataInfo sellTotalList(QwUserVoiceLogTotalVo qwUserVoiceLog)
+    {
+        startPage();
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwUserVoiceLog.setCompanyId(loginUser.getCompany().getCompanyId());
+        List<QwUserVoiceLogTotalVo> list = qwUserVoiceLogService.selectQwUserVoiceLogTotalList(qwUserVoiceLog);
+        return getDataTable(list);
+    }
+
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:sellTotalExport')")
+    @Log(title = "企微用户通话记录统计", businessType = BusinessType.EXPORT)
+    @GetMapping("/sellTotalExport")
+    public AjaxResult sellTotalExport(QwUserVoiceLogTotalVo qwUserVoiceLog)
+    {
+        List<QwUserVoiceLogTotalVo> list = qwUserVoiceLogService.selectQwUserVoiceLogTotalList(qwUserVoiceLog);
+        list.forEach(m-> {
+            m.setQwUserName(m.getQwUser().getQwUserName());
+        });
+        ExcelUtil<QwUserVoiceLogTotalVo> util = new ExcelUtil<QwUserVoiceLogTotalVo>(QwUserVoiceLogTotalVo.class);
+        return util.exportExcel(list, "企微用户通话记录数据");
+    }
+
+    /**
+     * 导出统计企微用户通话记录
+     */
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:totalExport')")
+    @Log(title = "企微用户通话记录统计", businessType = BusinessType.EXPORT)
+    @GetMapping("/totalExport")
+    public AjaxResult totalExport(QwUserVoiceLogTotalVo qwUserVoiceLog)
+    {
+        List<QwUserVoiceLogTotalVo> list = qwUserVoiceLogService.selectQwUserVoiceLogTotalList(qwUserVoiceLog);
+        list.forEach(m-> {
+            m.setQwUserName(m.getQwUser().getQwUserName());
+        });
+        ExcelUtil<QwUserVoiceLogTotalVo> util = new ExcelUtil<QwUserVoiceLogTotalVo>(QwUserVoiceLogTotalVo.class);
+        return util.exportExcel(list, "企微用户通话记录数据");
+    }
+
+
+    /**
+     * 导出企微用户通话记录列表
+     */
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:export')")
+    @Log(title = "企微用户通话记录", businessType = BusinessType.EXPORT)
+    @GetMapping("/export")
+    public AjaxResult export(QwUserVoiceLogVo qwUserVoiceLog)
+    {
+        List<QwUserVoiceLogVo> list = qwUserVoiceLogService.selectQwUserVoiceLogList(qwUserVoiceLog);
+        list.forEach(m-> {
+            m.setCompanyUserName(m.getCompanyUser().getUserName());
+            m.setCompanyName(m.getCompany().getCompanyName());
+            m.setExtName(m.getQwExternalContact().getName());
+            m.setQwUserName(m.getQwUser().getQwUserName());
+        });
+        ExcelUtil<QwUserVoiceLogVo> util = new ExcelUtil<QwUserVoiceLogVo>(QwUserVoiceLogVo.class);
+        return util.exportExcel(list, "企微用户通话记录数据");
+    }
+
+    /**
+     * 获取企微用户通话记录详细信息
+     */
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:query')")
+    @GetMapping(value = "/{id}")
+    public AjaxResult getInfo(@PathVariable("id") Long id)
+    {
+        return AjaxResult.success(qwUserVoiceLogService.selectQwUserVoiceLogById(id));
+    }
+
+    /**
+     * 新增企微用户通话记录
+     */
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:add')")
+    @Log(title = "企微用户通话记录", businessType = BusinessType.INSERT)
+    @PostMapping
+    public AjaxResult add(@RequestBody QwUserVoiceLog qwUserVoiceLog)
+    {
+        return toAjax(qwUserVoiceLogService.insertQwUserVoiceLog(qwUserVoiceLog));
+    }
+
+    /**
+     * 修改企微用户通话记录
+     */
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:edit')")
+    @Log(title = "企微用户通话记录", businessType = BusinessType.UPDATE)
+    @PutMapping
+    public AjaxResult edit(@RequestBody QwUserVoiceLog qwUserVoiceLog)
+    {
+        return toAjax(qwUserVoiceLogService.updateQwUserVoiceLog(qwUserVoiceLog));
+    }
+
+    /**
+     * 删除企微用户通话记录
+     */
+    @PreAuthorize("@ss.hasPermi('qw:qwUserVoiceLog:remove')")
+    @Log(title = "企微用户通话记录", businessType = BusinessType.DELETE)
+	@DeleteMapping("/{ids}")
+    public AjaxResult remove(@PathVariable Long[] ids)
+    {
+        return toAjax(qwUserVoiceLogService.deleteQwUserVoiceLogByIds(ids));
+    }
+}

+ 241 - 0
fs-company/src/main/java/com/fs/company/controller/qw/QwWorkTaskNewController.java

@@ -0,0 +1,241 @@
+package com.fs.company.controller.qw;
+
+import com.fs.common.annotation.Log;
+import com.fs.common.core.controller.BaseController;
+import com.fs.common.core.domain.AjaxResult;
+import com.fs.common.core.page.TableDataInfo;
+import com.fs.common.enums.BusinessType;
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.poi.ExcelUtil;
+import com.fs.company.service.impl.CompanyDeptServiceImpl;
+import com.fs.course.mapper.FsCourseWatchLogMapper;
+import com.fs.framework.security.LoginUser;
+import com.fs.framework.service.TokenService;
+import com.fs.qw.domain.QwExternalContact;
+import com.fs.qw.domain.QwWorkTask;
+import com.fs.qw.mapper.QwExternalContactMapper;
+import com.fs.qw.param.QwWorkTaskListParam;
+import com.fs.qw.service.IQwExternalContactService;
+import com.fs.qw.service.IQwWorkTaskService;
+import com.fs.qw.vo.QwWorkTaskAllListVO;
+import com.fs.qw.vo.QwWorkTaskListVO;
+import com.fs.qwApi.domain.QwExternalContactRemarkResult;
+import com.fs.qwApi.param.QwExternalContactRemarkParam;
+import com.fs.qwApi.service.QwApiService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * 企微任务看板Controller
+ *
+ * @author fs
+ * @date 2025-03-25
+ */
+@RestController
+@RequestMapping("/qw/QwWorkTaskNew")
+public class QwWorkTaskNewController extends BaseController
+{
+    @Autowired
+    private IQwWorkTaskService qwWorkTaskService;
+    @Autowired
+    private TokenService tokenService;
+    @Autowired
+    private FsCourseWatchLogMapper fsCourseWatchLogMapper;
+
+    @Autowired
+    private CompanyDeptServiceImpl companyDeptService;
+
+    /**
+     * 查询企微任务看板列表
+     */
+    @PreAuthorize("@ss.hasPermi('qw:QwWorkTaskNew:list')")
+    @GetMapping("/list")
+    public TableDataInfo list(QwWorkTaskListParam qwWorkTask)
+    {
+        startPage();
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwWorkTask.setCompanyId(loginUser.getCompany().getCompanyId());
+        qwWorkTask.setCompanyUserId(loginUser.getUser().getUserId());
+        List<QwWorkTaskListVO> list = qwWorkTaskService.selectQwWorkTaskListVO(qwWorkTask);
+
+        for (QwWorkTaskListVO qwWorkTaskListVO : list) {
+            qwWorkTaskListVO.setLogs(fsCourseWatchLogMapper.selectFsCourseWatchLog7DayByExtId(qwWorkTaskListVO.getExtId()));
+        }
+        return getDataTable(list);
+    }
+
+    /**
+     * 查询企微任务部门催课看板列表
+     */
+    @PreAuthorize("@ss.hasPermi('qw:QwWorkTaskNew:deptList')")
+    @GetMapping("/deptList")
+    public TableDataInfo deptList(QwWorkTaskListParam qwWorkTask)
+    {
+
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwWorkTask.setCompanyId(loginUser.getCompany().getCompanyId());
+
+        List<Long> combinedList = new ArrayList<>();
+        //本部门
+        Long deptId = loginUser.getUser().getDeptId();
+        if (deptId!=null){
+            combinedList.add(deptId);
+        }
+        //本部门的下级部门
+        List<Long> deptList = companyDeptService.selectCompanyDeptByParentId(deptId);
+        if (!deptList.isEmpty()){
+            combinedList.addAll(deptList);
+        }
+
+        qwWorkTask.setCuDeptIdList(combinedList);
+        qwWorkTask.setUserType(loginUser.getUser().getUserType());
+
+
+        startPage();
+        List<QwWorkTaskListVO> list = qwWorkTaskService.selectQwWorkTaskListVO(qwWorkTask);
+        for (QwWorkTaskListVO qwWorkTaskListVO : list) {
+            qwWorkTaskListVO.setLogs(fsCourseWatchLogMapper.selectFsCourseWatchLog7DayByExtId(qwWorkTaskListVO.getExtId()));
+        }
+        return getDataTable(list);
+    }
+
+    @GetMapping("/glList")
+    public TableDataInfo glList(QwWorkTaskListParam qwWorkTask)
+    {
+        startPage();
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwWorkTask.setCompanyId(loginUser.getCompany().getCompanyId());
+        List<QwWorkTaskListVO> list = qwWorkTaskService.selectQwWorkTaskListVO(qwWorkTask);
+        for (QwWorkTaskListVO qwWorkTaskListVO : list) {
+            qwWorkTaskListVO.setLogs(fsCourseWatchLogMapper.selectFsCourseWatchLog7DayByExtId(qwWorkTaskListVO.getExtId()));
+        }
+        return getDataTable(list);
+    }
+
+    @GetMapping("/allList")
+    public TableDataInfo allList(QwWorkTaskListParam qwWorkTask)
+    {
+        startPage();
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        qwWorkTask.setCompanyId(loginUser.getCompany().getCompanyId());
+        if (qwWorkTask.getSTime()==null||qwWorkTask.getETime()==null){
+            return new TableDataInfo();
+        }
+        List<QwWorkTaskAllListVO> list = qwWorkTaskService.selectQwWorkTaskAllListVO(qwWorkTask);
+
+        return getDataTable(list);
+    }
+    /**
+     * 导出企微任务看板列表
+     */
+    @PreAuthorize("@ss.hasPermi('qw:QwWorkTaskNew:export')")
+    @Log(title = "企微任务看板", businessType = BusinessType.EXPORT)
+    @GetMapping("/export")
+    public AjaxResult export(QwWorkTask qwWorkTask)
+    {
+        List<QwWorkTask> list = qwWorkTaskService.selectQwWorkTaskList(qwWorkTask);
+        ExcelUtil<QwWorkTask> util = new ExcelUtil<QwWorkTask>(QwWorkTask.class);
+        return util.exportExcel(list, "企微任务看板数据");
+    }
+
+    /**
+     * 获取企微任务看板详细信息
+     */
+    @PreAuthorize("@ss.hasPermi('qw:QwWorkTaskNew:query')")
+    @GetMapping(value = "/{id}")
+    public AjaxResult getInfo(@PathVariable("id") Long id)
+    {
+        return AjaxResult.success(qwWorkTaskService.selectQwWorkTaskById(id));
+    }
+
+    /**
+     * 新增企微任务看板
+     */
+    @PreAuthorize("@ss.hasPermi('qw:QwWorkTaskNew:add')")
+    @Log(title = "企微任务看板", businessType = BusinessType.INSERT)
+    @PostMapping
+    public AjaxResult add(@RequestBody QwWorkTask qwWorkTask)
+    {
+        return toAjax(qwWorkTaskService.insertQwWorkTask(qwWorkTask));
+    }
+    @Autowired
+    QwApiService qwApiService;
+    @Autowired
+    IQwExternalContactService qwExternalContactService;
+    @Autowired
+    QwExternalContactMapper qwExternalContactMapper;
+    /**
+     * 修改企微任务看板
+     */
+    @PreAuthorize("@ss.hasPermi('qw:QwWorkTaskNew:edit')")
+    @Log(title = "企微任务看板处理", businessType = BusinessType.UPDATE)
+    @PutMapping
+    public AjaxResult edit(@RequestBody QwWorkTask qwWorkTask)
+    {
+        QwWorkTask task = new QwWorkTask();
+        task.setId(qwWorkTask.getId());
+        task.setStatus(1);
+        task.setTrackType(qwWorkTask.getTrackType());
+        task.setDescription(qwWorkTask.getDescription());
+        task.setUpdateTime(new Date());
+        if (task.getDescription()!=null&& !task.getDescription().isEmpty()){
+
+            QwExternalContact qwExternalContact = qwExternalContactService.selectQwExternalContactById(qwWorkTask.getExtId());
+            if (qwExternalContact!=null){
+                QwExternalContactRemarkParam param = new QwExternalContactRemarkParam();
+                param.setUserid(qwExternalContact.getUserId());
+                param.setExternal_userid(qwExternalContact.getExternalUserId());
+                param.setDescription(task.getDescription());
+
+                QwExternalContactRemarkResult qwExternalContactRemarkResult = qwApiService.externalcontactRemark(param, qwExternalContact.getCorpId());
+                logger.info("QwExternalContactRemarkResult206:" + qwExternalContactRemarkResult);
+                if (qwExternalContactRemarkResult.getErrcode() == 0) {
+                    QwExternalContact ext = new QwExternalContact();
+                    ext.setId(qwExternalContact.getId());
+                    ext.setDescription(task.getDescription());
+                    qwExternalContactMapper.updateQwExternalContact(ext);
+                }
+            }
+        }
+        return toAjax(qwWorkTaskService.updateQwWorkTask(task));
+    }
+    @PreAuthorize("@ss.hasPermi('qw:QwWorkTaskNew:edit')")
+    @Log(title = "企微任务看板处理", businessType = BusinessType.UPDATE)
+    @PutMapping("/edit2")
+    public AjaxResult edit2(@RequestBody QwWorkTask qwWorkTask)
+    {
+        QwWorkTask task = new QwWorkTask();
+        task.setId(qwWorkTask.getId());
+        task.setStatus(1);
+        task.setUpdateTime(new Date());
+        task.setTrackType(2);
+        return toAjax(qwWorkTaskService.updateQwWorkTask(task));
+    }
+    @PreAuthorize("@ss.hasPermi('qw:QwWorkTaskNew:edit')")
+    @Log(title = "企微任务看板处理", businessType = BusinessType.UPDATE)
+    @PutMapping("/edit3")
+    public AjaxResult edit3(@RequestBody QwWorkTask qwWorkTask)
+    {
+        QwWorkTask task = new QwWorkTask();
+        task.setId(qwWorkTask.getId());
+        task.setStatus(1);
+        task.setUpdateTime(new Date());
+        task.setTrackType(3);
+        return toAjax(qwWorkTaskService.updateQwWorkTask(task));
+    }
+    /**
+     * 删除企微任务看板
+     */
+    @PreAuthorize("@ss.hasPermi('qw:QwWorkTaskNew:remove')")
+    @Log(title = "企微任务看板", businessType = BusinessType.DELETE)
+	@DeleteMapping("/{ids}")
+    public AjaxResult remove(@PathVariable Long[] ids)
+    {
+        return toAjax(qwWorkTaskService.deleteQwWorkTaskByIds(ids));
+    }
+}

+ 158 - 27
fs-company/src/main/java/com/fs/company/controller/qw/SopUserLogsInfoController.java

@@ -32,10 +32,10 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.*;
 
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
+import java.io.IOException;
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.*;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
 
@@ -89,7 +89,7 @@ public class SopUserLogsInfoController extends BaseController
                 Map<Long, SopExternalContactInfo> externalContactInfoMap = qwExternalContactVOTimes.stream()
                         .collect(Collectors.toMap(
                                 QwExternalContactVOTime::getId,
-                                item -> new SopExternalContactInfo(item.getCreateTime(), item.getTagIds(), item.getRemark())
+                                item -> new SopExternalContactInfo(item.getCreateTime(), item.getTagIds(), item.getRemark(),item.getLevel())
                         ));
                 List<String> tagIds = qwExternalContactVOTimes.stream().map(QwExternalContactVOTime::getTagIds).filter(StringUtils::isNotEmpty).flatMap(e -> JSON.parseArray(e, String.class).stream()).collect(Collectors.toList());
                 if(!tagIds.isEmpty()){
@@ -105,27 +105,70 @@ public class SopUserLogsInfoController extends BaseController
                 list.forEach(item -> {
                     SopExternalContactInfo info = externalContactInfoMap.getOrDefault(
                             item.getExternalId(),
-                            new SopExternalContactInfo("无进线时间", "无标签", "无备注"));
+                            new SopExternalContactInfo("无进线时间", "无标签", "无备注",0));
                     item.setInComTime(info.getCreateTime());
                     item.setTagIds(info.getTagIds());
                     item.setRemark(info.getRemark());
+                    item.setLevel(info.getLevel());
+
                 });
             }
 
+
+//            Predicate<SopUserLogsInfo> tagFilter = item ->
+//                    sopUserLogsInfo.getTagIds() == null ||
+//                            sopUserLogsInfo.getTagIds().isEmpty() ||
+//                            item.getTagIds().contains(sopUserLogsInfo.getTagIds());
+
+            Predicate<SopUserLogsInfo> tagFilter = item -> {
+                String queryTagIds = sopUserLogsInfo.getTagIds();
+                String itemTagIds = item.getTagIds();
+
+                if (queryTagIds == null || queryTagIds.trim().equals("[]")) {
+                    return true;
+                }
+                List<String> queryTags = parseTagIds(queryTagIds);
+                List<String> itemTags = parseTagIds(itemTagIds);
+
+                // 检查 itemTags 是否包含所有 queryTags(AND 关系)
+                return itemTags.containsAll(queryTags);
+            };
+
             // 优化过滤条件
             boolean isRemarkEmpty = StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getRemark());
-            Predicate<SopUserLogsInfo> tagFilter = item ->
-                    sopUserLogsInfo.getTagIds() == null ||
-                            sopUserLogsInfo.getTagIds().isEmpty() ||
-                            item.getTagIds().contains(sopUserLogsInfo.getTagIds());
-
             Predicate<SopUserLogsInfo> remarkFilter = item ->
                     isRemarkEmpty ||
                             item.getRemark().contains(sopUserLogsInfo.getRemark());
 
-            if (sopUserLogsInfo.getTagIds() != null || !isRemarkEmpty) {
+
+            boolean isLevelEmpty = sopUserLogsInfo.getLevel() == null;
+            Predicate<SopUserLogsInfo> levelFilter = item ->
+                    isLevelEmpty ||
+                            (item.getLevel() != null && Objects.equals(item.getLevel(), sopUserLogsInfo.getLevel()) );
+
+
+            Predicate<SopUserLogsInfo> timeFilter = item -> {
+                if (StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getEntryTime())) {
+                    return true;
+                }
+                try {
+                    LocalDate entryDate = LocalDate.parse(
+                            sopUserLogsInfo.getEntryTime(),
+                            DateTimeFormatter.ofPattern("yyyy-MM-dd")
+                    );
+                    LocalDate createDate = LocalDate.parse(
+                            item.getInComTime().substring(0, 10),
+                            DateTimeFormatter.ofPattern("yyyy-MM-dd")
+                    );
+                    return entryDate.equals(createDate);
+                } catch (Exception e) {
+                    return false;
+                }
+            };
+
+            if (sopUserLogsInfo.getTagIds() != null || !isRemarkEmpty || !StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getEntryTime()) ||!isLevelEmpty) {
                 list = list.stream()
-                        .filter(tagFilter.and(remarkFilter))
+                        .filter(tagFilter.and(remarkFilter).and(timeFilter).and(levelFilter))
                         .collect(Collectors.toList());
             }
 
@@ -137,9 +180,15 @@ public class SopUserLogsInfoController extends BaseController
                     param.setTagIds(tagIds);
                     item.setTagIdsName(iQwTagService.selectQwTagListByTagIds(param));
                 }
+
+                // 处理 level
+                item.setLevelName(getLevel(item.getLevel()));
             });
+
             return getDataTable(list);
-        } else {
+        }
+        else {
+
             List<QwGroupChatUser> list = qwGroupChatUserService.selectByChatId(sopUserLogsInfo);
 
 
@@ -158,15 +207,14 @@ public class SopUserLogsInfoController extends BaseController
                 Map<String, SopExternalContactInfo> externalContactInfoMap = qwExternalContactVOTimes.stream()
                         .collect(Collectors.toMap(
                                 QwExternalContactVOTime::getExternalUserId,
-                                item -> new SopExternalContactInfo(item.getCreateTime(), item.getTagIdsName(), item.getTagIds(), item.getRemark())
+                                item -> new SopExternalContactInfo(item.getCreateTime(), item.getTagIds(), item.getRemark(),item.getLevel())
                         ));
 
                 // 遍历 list,赋值 inComTime 和 tagIds
                 list.forEach(item -> {
-                    SopExternalContactInfo info = externalContactInfoMap.getOrDefault(item.getUserId(), new SopExternalContactInfo("无进线时间", "无标签", "无备注"));
+                    SopExternalContactInfo info = externalContactInfoMap.getOrDefault(item.getUserId(), new SopExternalContactInfo("无进线时间", "无标签", "无备注",0));
                     item.setInComTime(info.getCreateTime());
                     item.setTagIds(info.getTagIds());
-                    item.setTagNames(info.getTagNames());
                     item.setRemark(info.getRemark());
                 });
 
@@ -181,22 +229,105 @@ public class SopUserLogsInfoController extends BaseController
                         )
                         .collect(Collectors.toList());
             }
+
+            // 处理标签名称
+            list.parallelStream().forEach(item -> {
+                if (item.getTagIds() != null && !item.getTagIds().equals("[]") && !item.getTagIds().equals("无标签")) {
+                    List<String> tagIds = GSON.fromJson(item.getTagIds(), new TypeToken<List<String>>() {}.getType());
+                    QwTagSearchParam param = new QwTagSearchParam();
+                    param.setTagIds(tagIds);
+                    item.setTagIdsName(iQwTagService.selectQwTagListByTagIds(param));
+                }
+            });
             return getDataTable(list);
+//            List<QwGroupChatUser> list = qwGroupChatUserService.selectByChatId(sopUserLogsInfo);
+//
+//
+//            if (!list.isEmpty()) {
+//
+//                List<String> externalIdList = list.stream()
+//                        .map(QwGroupChatUser::getUserId) // 提取 externalId
+//                        .filter(StringUtils::isNotEmpty) // 过滤掉 null 值,防止 NullPointerException
+//                        .distinct()
+//                        .collect(Collectors.toList()); // 收集到 List
+//
+//                List<QwExternalContactVOTime> qwExternalContactVOTimes = iQwExternalContactService.selectQwExternalContactListVOByUserIds(externalIdList);
+//
+//
+//                // 先将 qwExternalContactVOTimes 转换为 Map,key 为 id,value 为 ExternalContactInfo(包含 createTime 和 tagIds)
+//                Map<String, SopExternalContactInfo> externalContactInfoMap = qwExternalContactVOTimes.stream()
+//                        .collect(Collectors.toMap(
+//                                QwExternalContactVOTime::getExternalUserId,
+//                                item -> new SopExternalContactInfo(item.getCreateTime(), item.getTagIdsName(), item.getTagIds(), item.getRemark())
+//                        ));
+//
+//                // 遍历 list,赋值 inComTime 和 tagIds
+//                list.forEach(item -> {
+//                    SopExternalContactInfo info = externalContactInfoMap.getOrDefault(item.getUserId(), new SopExternalContactInfo("无进线时间", "无标签", "无备注"));
+//                    item.setInComTime(info.getCreateTime());
+//                    item.setTagIds(info.getTagIds());
+//                    item.setTagNames(info.getTagNames());
+//                    item.setRemark(info.getRemark());
+//                });
+//
+//            }
+//
+//            if ((sopUserLogsInfo.getTagIds() != null && !sopUserLogsInfo.getTagIds().isEmpty())
+//                    || !StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getRemark())) {
+//                list = list.stream()
+//                        .filter(item ->
+//                                (sopUserLogsInfo.getTagIds() == null || sopUserLogsInfo.getTagIds().isEmpty() || item.getTagIds().contains(sopUserLogsInfo.getTagIds()))
+//                                        && (StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getRemark()) || item.getRemark().contains(sopUserLogsInfo.getRemark()))
+//                        )
+//                        .collect(Collectors.toList());
+//            }
+//            return getDataTable(list);
         }
 
-//        if (sopUserLogsInfo.getTagIds() != null && !sopUserLogsInfo.getTagIds().isEmpty()) {
-//            list = list.stream()
-//                    .filter(item -> item.getTagIds().contains(sopUserLogsInfo.getTagIds()))
-//                    .collect(Collectors.toList());
-//        }
-//        if (!StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getRemark())) {
-//            list = list.stream()
-//                    .filter(item -> item.getRemark().contains(sopUserLogsInfo.getRemark()))
-//                    .collect(Collectors.toList());
-//        }
     }
 
 
+    private String getLevel(Integer level){
+
+        String levelName = "无";
+
+        if (level != null) {
+
+            switch (level) {
+                case 0:
+                    levelName = "无";
+                    break;
+                case 1:
+                    levelName = "A";
+                    break;
+                case 2:
+                    levelName = "B";
+                    break;
+                case 3:
+                    levelName = "C";
+                    break;
+                case 4:
+                    levelName = "D";
+                    break;
+                case 5:
+                    levelName = "E";
+                    break;
+                default:
+                    levelName = "无";
+            }
+        }
+        return  levelName;
+    }
+    private List<String> parseTagIds(String jsonTagIds) {
+        if (jsonTagIds == null || jsonTagIds.trim().isEmpty() || jsonTagIds.equals("[]")) {
+            return Collections.emptyList();
+        }
+        // 去掉开头和结尾的 [ ],然后按 "," 分割
+        return Arrays.stream(jsonTagIds.replaceAll("[\\[\\]\"]", "").split(","))
+                .map(String::trim)
+                .filter(s -> !s.isEmpty())
+                .collect(Collectors.toList());
+    }
 //    /**
 //     * 导出sopUserLogsInfo列表
 //     */

+ 1 - 1
fs-company/src/main/java/com/fs/company/controller/stats/SalesWatchStatisController.java

@@ -100,7 +100,7 @@ public class SalesWatchStatisController {
         param.setPageSize(null);
         List<FsStatisQwWatch> list = fsStatisQwWatchService.exportQueryList(param);
         ExcelUtil<FsStatisQwWatch> util = new ExcelUtil<>(FsStatisQwWatch.class);
-        return util.exportExcel(list, "销售完播统计");
+        return util.exportExcel(list, "进线转化统计");
     }
 
 

+ 1 - 1
fs-company/src/main/java/com/fs/company/controller/store/FsInquiryOrderController.java

@@ -59,7 +59,7 @@ public class FsInquiryOrderController extends BaseController
     /**
      * 查询问诊订单列表
      */
-    @PreAuthorize("@ss.hasPermi('store:inquiryOrder:list')")
+//    @PreAuthorize("@ss.hasPermi('store:inquiryOrder:list')")
     @GetMapping("/list")
    public TableDataInfo list(FsInquiryOrderParam fsInquiryOrder)
     {

+ 100 - 64
fs-company/src/main/java/com/fs/company/controller/store/FsPatientController.java

@@ -6,6 +6,7 @@ import com.fs.common.core.domain.AjaxResult;
 import com.fs.common.core.page.TableDataInfo;
 import com.fs.common.enums.BusinessType;
 import com.fs.common.exception.CustomException;
+import com.fs.common.utils.StringUtils;
 import com.fs.common.utils.poi.ExcelUtil;
 import com.fs.framework.security.LoginUser;
 import com.fs.framework.security.SecurityUtils;
@@ -123,68 +124,33 @@ public class FsPatientController extends BaseController
     public AjaxResult add(@RequestBody FsPatient fsPatient)
     {
         String idCardNumber = fsPatient.getIdCard(); // 替换为要验证的身份证号码
-        if (idCardNumber == null || idCardNumber.length() != 18) {
-            throw new CustomException("身份证号码不合法");
-        }
-        String regex = "\\d{17}[0-9Xx]";
-        if (!Pattern.matches(regex, idCardNumber)) {
-            throw new CustomException("身份证号码不合法");
-        }
-        if (fsPatient.getPatientName().length()<2||fsPatient.getPatientName().length()>30||!fsPatient.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
-            throw new CustomException("就诊人名称不合法");
-        }
-        String birthDateString = idCardNumber.substring(6, 14);
-        LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
-        LocalDate currentDate = LocalDate.now();
-        int age = currentDate.getYear() - birthDate.getYear();
-        if (currentDate.getMonthValue() < birthDate.getMonthValue()
-                || (currentDate.getMonthValue() == birthDate.getMonthValue()
-                && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
-            age--;
-        }
-        if (age < 18) {
-            throw new CustomException("年龄必须大于18岁");
-        }
-        if (age > 200) {
-            throw new CustomException("年龄超过200岁");
-        }
-        Date birthday = fsPatient.getBirthday();
-        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
-        String formattedBirthday = sdf.format(birthday);
-        LocalDate da = LocalDate.parse(formattedBirthday, DateTimeFormatter.ofPattern("yyyyMMdd"));
-        LocalDate currentDate2 = LocalDate.now();
-        int age2 = currentDate2.getYear() - da.getYear();
-        if (currentDate2.getMonthValue() < da.getMonthValue()
-                || (currentDate2.getMonthValue() == da.getMonthValue()
-                && currentDate2.getDayOfMonth() < da.getDayOfMonth())) {
-            age2--;
-        }
-        if (age2 < 18) {
-            throw new CustomException("年龄必须大于18岁");
-        }
-        if (age2 > 200) {
-            throw new CustomException("年龄超过200岁");
-        }
-        return toAjax(fsPatientService.insertFsPatient(fsPatient));
-    }
-
-    /**
-     * 修改病人
-     */
-    @PreAuthorize("@ss.hasPermi('his:patient:edit')")
-    @Log(title = "病人", businessType = BusinessType.UPDATE)
-    @PutMapping
-    public AjaxResult edit(@RequestBody FsPatient fsPatient)
-    {
-
-        if (fsPatient.getMobile().contains("*")){
-            fsPatient.setMobile(null);
-        }
-        if (fsPatient.getIdCard().contains("*")){
-            fsPatient.setIdCard(null);
-        }else {
-            String idCardNumber = fsPatient.getIdCard();
-            if (idCardNumber == null || idCardNumber.length() != 18) {
+//        if (idCardNumber == null || idCardNumber.length() != 18) {
+//            throw new CustomException("身份证号码不合法");
+//        }
+//        String regex = "\\d{17}[0-9Xx]";
+//        if (!Pattern.matches(regex, idCardNumber)) {
+//            throw new CustomException("身份证号码不合法");
+//        }
+//        if (fsPatient.getPatientName().length()<2||fsPatient.getPatientName().length()>30||!fsPatient.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
+//            throw new CustomException("就诊人名称不合法");
+//        }
+//        String birthDateString = idCardNumber.substring(6, 14);
+//        LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
+//        LocalDate currentDate = LocalDate.now();
+//        int age = currentDate.getYear() - birthDate.getYear();
+//        if (currentDate.getMonthValue() < birthDate.getMonthValue()
+//                || (currentDate.getMonthValue() == birthDate.getMonthValue()
+//                && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
+//            age--;
+//        }
+//        if (age < 18) {
+//            throw new CustomException("年龄必须大于18岁");
+//        }
+//        if (age > 200) {
+//            throw new CustomException("年龄超过200岁");
+//        }
+        if (StringUtils.isNotBlank(idCardNumber)){
+            if ( idCardNumber.length() != 18) {
                 throw new CustomException("身份证号码不合法");
             }
             String regex = "\\d{17}[0-9Xx]";
@@ -209,8 +175,9 @@ public class FsPatientController extends BaseController
             if (age > 200) {
                 throw new CustomException("年龄超过200岁");
             }
-
-            Date birthday = fsPatient.getBirthday();
+        }
+        Date birthday = fsPatient.getBirthday();
+        if (birthday!=null){
             SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
             String formattedBirthday = sdf.format(birthday);
             LocalDate da = LocalDate.parse(formattedBirthday, DateTimeFormatter.ofPattern("yyyyMMdd"));
@@ -227,6 +194,75 @@ public class FsPatientController extends BaseController
             if (age2 > 200) {
                 throw new CustomException("年龄超过200岁");
             }
+        }
+
+        return toAjax(fsPatientService.insertFsPatient(fsPatient));
+    }
+
+    /**
+     * 修改病人
+     */
+    @PreAuthorize("@ss.hasPermi('his:patient:edit')")
+    @Log(title = "病人", businessType = BusinessType.UPDATE)
+    @PutMapping
+    public AjaxResult edit(@RequestBody FsPatient fsPatient)
+    {
+
+        if (fsPatient.getMobile()!=null && fsPatient.getMobile().contains("*")){
+            fsPatient.setMobile(null);
+        }
+        if (fsPatient.getIdCard()!=null && fsPatient.getIdCard().contains("*")){
+            fsPatient.setIdCard(null);
+        }else {
+            String idCardNumber = fsPatient.getIdCard();
+            if (StringUtils.isNotBlank(idCardNumber)){
+                if (idCardNumber.length() != 18) {
+                    throw new CustomException("身份证号码不合法");
+                }
+                String regex = "\\d{17}[0-9Xx]";
+                if (!Pattern.matches(regex, idCardNumber)) {
+                    throw new CustomException("身份证号码不合法");
+                }
+                if (fsPatient.getPatientName().length()<2||fsPatient.getPatientName().length()>30||!fsPatient.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
+                    throw new CustomException("就诊人名称不合法");
+                }
+                String birthDateString = idCardNumber.substring(6, 14);
+                LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
+                LocalDate currentDate = LocalDate.now();
+                int age = currentDate.getYear() - birthDate.getYear();
+                if (currentDate.getMonthValue() < birthDate.getMonthValue()
+                        || (currentDate.getMonthValue() == birthDate.getMonthValue()
+                        && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
+                    age--;
+                }
+                if (age < 18) {
+                    throw new CustomException("年龄必须大于18岁");
+                }
+                if (age > 200) {
+                    throw new CustomException("年龄超过200岁");
+                }
+            }
+
+            Date birthday = fsPatient.getBirthday();
+            if (birthday!=null){
+                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
+                String formattedBirthday = sdf.format(birthday);
+                LocalDate da = LocalDate.parse(formattedBirthday, DateTimeFormatter.ofPattern("yyyyMMdd"));
+                LocalDate currentDate2 = LocalDate.now();
+                int age2 = currentDate2.getYear() - da.getYear();
+                if (currentDate2.getMonthValue() < da.getMonthValue()
+                        || (currentDate2.getMonthValue() == da.getMonthValue()
+                        && currentDate2.getDayOfMonth() < da.getDayOfMonth())) {
+                    age2--;
+                }
+                if (age2 < 18) {
+                    throw new CustomException("年龄必须大于18岁");
+                }
+                if (age2 > 200) {
+                    throw new CustomException("年龄超过200岁");
+                }
+            }
+
 
 
         }

+ 28 - 0
fs-company/src/main/java/com/fs/company/utils/DomainUtil.java

@@ -0,0 +1,28 @@
+package com.fs.company.utils;
+
+
+import java.util.Random;
+
+public class DomainUtil {
+
+    private static final String LETTER = "abcdefghijklmnopqrstuvwxyz";
+    private static final Random RANDOM = new Random();
+
+    /**
+     * 生成二级域名
+     * @param domain 主域名
+     * @param length 名称长度
+     * @param suffix 后缀
+     * @return  二级域名
+     */
+    public static String generateSubDomain(String domain, int length, String suffix) {
+        if (length < 6) {
+            length = 6;
+        }
+        StringBuilder sub = new StringBuilder(length);
+        for (int i = 0; i < length; i++) {
+            sub.append(LETTER.charAt(RANDOM.nextInt(LETTER.length())));
+        }
+        return sub + "-" + suffix + "." + domain;
+    }
+}

+ 28 - 4
fs-company/src/main/java/com/fs/user/FsUserAdminController.java

@@ -1,32 +1,36 @@
 package com.fs.user;
 
 import com.alibaba.fastjson.JSON;
+import com.fs.common.annotation.Log;
 import com.fs.common.core.controller.BaseController;
+import com.fs.common.core.domain.AjaxResult;
 import com.fs.common.core.domain.R;
 import com.fs.common.core.page.TableDataInfo;
+import com.fs.common.enums.BusinessType;
 import com.fs.common.utils.ServletUtils;
 import com.fs.company.cache.ICompanyUserCacheService;
 import com.fs.framework.security.LoginUser;
 import com.fs.framework.service.TokenService;
 
+import com.fs.his.domain.FsUser;
 import com.fs.his.service.IFsUserService;
 import com.fs.qw.domain.CustomerTransferApproval;
 import com.fs.qw.dto.FsUserTransferParamDTO;
 import com.fs.qw.service.ICustomerTransferApprovalService;
 import com.fs.store.param.h5.FsUserPageListParam;
+import com.fs.store.vo.h5.FsUserPageListVO;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.AllArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 
 import java.util.Date;
 
+import static com.fs.his.utils.PhoneUtil.decryptAutoPhoneMk;
+
 @Api(tags = "会员管理接口")
 @RestController
 @Slf4j
@@ -99,5 +103,25 @@ public class FsUserAdminController extends BaseController {
         return R.ok("转移申请已经提交,等待转移成功!");
     }
 
+    /**
+     * 获取用户详细信息
+     */
+    @GetMapping(value = "/{userId}")
+    public AjaxResult getInfo(@PathVariable("userId") Long userId)
+    {
+        return AjaxResult.success(fsUserService.selectFsUserPageListVOByUserId(userId));
+    }
+
+    /**
+     * 修改用户
+     */
+    @PreAuthorize("@ss.hasPermi('user:fsUser:edit')")
+    @Log(title = "用户", businessType = BusinessType.UPDATE)
+    @PutMapping
+    public AjaxResult edit(@RequestBody FsUser fsUser)
+    {
+        return toAjax(fsUserService.updateFsUser(fsUser));
+    }
+
 
 }

+ 2 - 1
fs-company/src/main/resources/application.yml

@@ -3,7 +3,8 @@ server:
 # Spring配置
 spring:
   profiles:
-    active: druid-fcky-test
+#    active: druid-fcky-test
+    active: dev
 #    active: druid-jzzx
 #    active: druid-hdt
 #    active: druid-sxjz

+ 40 - 0
fs-framework/src/main/java/com/fs/framework/config/LogInterceptor.java

@@ -0,0 +1,40 @@
+package com.fs.framework.config;
+
+
+
+import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+import org.springframework.web.servlet.HandlerInterceptor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.UUID;
+
+
+/**
+ * @description: 日志拦截器
+ * @author: xdd
+ * @date: 2025/3/13
+ */
+@Component
+public class LogInterceptor implements HandlerInterceptor {
+
+    private static final String traceId = "traceId";
+
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
+        String tid = UUID.randomUUID().toString().replace("-", "");
+        if (!StringUtils.isEmpty(request.getHeader("traceId"))) {
+            tid = request.getHeader("traceId");
+        }
+        MDC.put(traceId, tid);
+        return true;
+    }
+
+    @Override
+    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
+                                Exception ex) {
+        MDC.remove(traceId);
+    }
+}

+ 8 - 3
fs-framework/src/main/java/com/fs/framework/config/ResourcesConfig.java

@@ -19,8 +19,7 @@ import java.time.format.DateTimeFormatter;
 
 /**
  * 通用配置
- * 
-
+ *
  */
 @Configuration
 public class ResourcesConfig implements WebMvcConfigurer
@@ -28,6 +27,9 @@ public class ResourcesConfig implements WebMvcConfigurer
     @Autowired
     private RepeatSubmitInterceptor repeatSubmitInterceptor;
 
+    @Autowired
+    private LogInterceptor logInterceptor;
+
     @Override
     public void addResourceHandlers(ResourceHandlerRegistry registry)
     {
@@ -45,6 +47,9 @@ public class ResourcesConfig implements WebMvcConfigurer
     public void addInterceptors(InterceptorRegistry registry)
     {
         registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
+
+        registry.addInterceptor(logInterceptor)
+                .addPathPatterns("/**");
     }
 
     /**
@@ -73,4 +78,4 @@ public class ResourcesConfig implements WebMvcConfigurer
         registrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd")); // 统一日期格式
         registrar.registerFormatters(registry);
     }
-}
+}

+ 35 - 0
fs-framework/src/main/java/com/fs/framework/config/ThreadPoolTaskWrapExecutor.java

@@ -0,0 +1,35 @@
+package com.fs.framework.config;
+
+import com.fs.framework.util.ThreadMdcUtil;
+import org.slf4j.MDC;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
+
+/**
+ * @description:
+ * @author: xdd
+ * @date: 2025/3/13
+ */
+public final class ThreadPoolTaskWrapExecutor extends ThreadPoolTaskExecutor {
+    public ThreadPoolTaskWrapExecutor() {
+        super();
+    }
+
+    @Override
+    public void execute(Runnable task) {
+        super.execute(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
+    }
+
+
+    @Override
+    public <T> Future<T> submit(Callable<T> task) {
+        return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
+    }
+
+    @Override
+    public Future<?> submit(Runnable task) {
+        return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
+    }
+}

+ 60 - 0
fs-framework/src/main/java/com/fs/framework/util/ThreadMdcUtil.java

@@ -0,0 +1,60 @@
+package com.fs.framework.util;
+
+
+import org.slf4j.MDC;
+
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.Callable;
+/**
+ * @description:
+ * @author: xdd
+ * @date: 2025/3/13
+ * @Description:
+ */
+public final class ThreadMdcUtil {
+    private static final String traceId = "traceId";
+
+    public static String generateTraceId() {
+        return UUID.randomUUID().toString().replace("-", "");
+    }
+
+    public static void setTraceIdIfAbsent() {
+        if (MDC.get(traceId) == null) {
+            MDC.put(traceId, generateTraceId());
+        }
+    }
+
+    public static<T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
+        return () -> {
+            if (context == null) {
+                MDC.clear();
+            } else {
+                MDC.setContextMap(context);
+            }
+            setTraceIdIfAbsent();
+            try {
+                return callable.call();
+            } finally {
+                MDC.clear();
+            }
+        };
+    }
+
+
+    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
+        return () -> {
+            if (context == null) {
+                MDC.clear();
+            } else {
+                MDC.setContextMap(context);
+            }
+            setTraceIdIfAbsent();
+            try {
+                runnable.run();
+            } finally {
+                MDC.clear();
+            }
+        };
+    }
+}

+ 141 - 0
fs-ipad-task/pom.xml

@@ -0,0 +1,141 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>fs</artifactId>
+        <groupId>com.fs</groupId>
+        <version>1.1.0</version>
+    </parent>
+    <version>1.1.0</version>
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>com.fs</groupId>
+    <artifactId>fs-ipad-task</artifactId>
+    <description>
+        企微定时任务
+    </description>
+
+    <dependencies>
+        <!-- spring-boot-devtools -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-devtools</artifactId>
+            <optional>true</optional> <!-- 表示依赖不会传递 -->
+        </dependency>
+        <!-- swagger2-->
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger2</artifactId>
+        </dependency>
+
+        <!-- swagger2-UI-->
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger-ui</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.github.xiaoymin</groupId>
+            <artifactId>swagger-bootstrap-ui</artifactId>
+            <version>1.9.3</version>
+        </dependency>
+
+
+        <!-- Mysql驱动包 -->
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+        </dependency>
+
+        <!-- SpringBoot Web容器 -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
+        <!-- SpringBoot 拦截器 -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-aop</artifactId>
+        </dependency>
+
+        <!-- 阿里数据库连接池 -->
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>druid-spring-boot-starter</artifactId>
+        </dependency>
+
+        <!--clickhouse-->
+        <dependency>
+            <groupId>com.clickhouse</groupId>
+            <artifactId>clickhouse-jdbc</artifactId>
+            <version>0.4.6</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.retry</groupId>
+            <artifactId>spring-retry</artifactId>
+            <version>1.3.1</version>
+        </dependency>
+
+        <!--        <dependency>-->
+<!--            <groupId>ru.yandex.clickhouse</groupId>-->
+<!--            <artifactId>clickhouse-jdbc</artifactId>-->
+<!--            <version>0.3.2</version>-->
+<!--        </dependency>-->
+
+        <!-- 验证码 -->
+        <dependency>
+            <groupId>com.github.penggle</groupId>
+            <artifactId>kaptcha</artifactId>
+            <exclusions>
+                <exclusion>
+                    <artifactId>javax.servlet-api</artifactId>
+                    <groupId>javax.servlet</groupId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+
+        <!-- 获取系统信息 -->
+        <dependency>
+            <groupId>com.github.oshi</groupId>
+            <artifactId>oshi-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.fs</groupId>
+            <artifactId>fs-service</artifactId>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <version>2.1.1.RELEASE</version>
+                <configuration>
+                    <fork>true</fork> <!-- 如果没有该配置,devtools不会生效 -->
+                </configuration>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>repackage</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-war-plugin</artifactId>
+                <version>3.1.0</version>
+                <configuration>
+                    <failOnMissingWebXml>false</failOnMissingWebXml>
+                    <warName>${project.artifactId}</warName>
+                </configuration>
+            </plugin>
+        </plugins>
+        <finalName>${project.artifactId}</finalName>
+    </build>
+
+
+</project>

+ 14 - 0
fs-ipad-task/src/main/java/com/fs/FSServletInitializer.java

@@ -0,0 +1,14 @@
+package com.fs;
+
+import org.springframework.boot.builder.SpringApplicationBuilder;
+import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
+
+
+public class FSServletInitializer extends SpringBootServletInitializer
+{
+    @Override
+    protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
+    {
+        return application.sources(FsIpadTaskApplication.class);
+    }
+}

+ 24 - 0
fs-ipad-task/src/main/java/com/fs/FsIpadTaskApplication.java

@@ -0,0 +1,24 @@
+package com.fs;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
+import org.springframework.scheduling.annotation.EnableAsync;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+/**
+ * 启动程序
+ */
+@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
+@EnableTransactionManagement
+@EnableAsync
+@EnableScheduling
+public class FsIpadTaskApplication
+{
+    public static void main(String[] args){
+        // System.setProperty("spring.devtools.restart.enabled", "false");
+        SpringApplication.run(FsIpadTaskApplication.class, args);
+        System.out.println("IpadTask启动成功");
+    }
+}

+ 51 - 0
fs-ipad-task/src/main/java/com/fs/app/exception/FSException.java

@@ -0,0 +1,51 @@
+package com.fs.app.exception;
+
+/**
+ * 自定义异常
+ */
+public class FSException extends RuntimeException {
+	private static final long serialVersionUID = 1L;
+	
+    private String msg;
+    private int code = 500;
+    
+    public FSException(String msg) {
+		super(msg);
+		this.msg = msg;
+	}
+	
+	public FSException(String msg, Throwable e) {
+		super(msg, e);
+		this.msg = msg;
+	}
+	
+	public FSException(String msg, int code) {
+		super(msg);
+		this.msg = msg;
+		this.code = code;
+	}
+	
+	public FSException(String msg, int code, Throwable e) {
+		super(msg, e);
+		this.msg = msg;
+		this.code = code;
+	}
+
+	public String getMsg() {
+		return msg;
+	}
+
+	public void setMsg(String msg) {
+		this.msg = msg;
+	}
+
+	public int getCode() {
+		return code;
+	}
+
+	public void setCode(int code) {
+		this.code = code;
+	}
+	
+	
+}

+ 82 - 0
fs-ipad-task/src/main/java/com/fs/app/exception/FSExceptionHandler.java

@@ -0,0 +1,82 @@
+package com.fs.app.exception;
+
+
+
+
+import com.fs.common.core.domain.R;
+import com.fs.common.exception.CustomException;
+import lombok.extern.slf4j.Slf4j;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.dao.DuplicateKeyException;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.validation.BindException;
+import org.springframework.validation.FieldError;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+import org.springframework.web.servlet.NoHandlerFoundException;
+
+
+/**
+ * 异常处理器
+ */
+@Slf4j
+@RestControllerAdvice
+public class FSExceptionHandler {
+
+	/**
+	 * 处理自定义异常
+	 */
+	@ExceptionHandler(FSException.class)
+	public R handleRRException(FSException e){
+		R r = new R();
+		r.put("code", e.getCode());
+		r.put("msg", e.getMessage());
+
+		return r;
+	}
+
+	@ExceptionHandler(NoHandlerFoundException.class)
+	public R handlerNoFoundException(Exception e) {
+		log.error(e.getMessage(), e);
+		return R.error(404, "路径不存在,请检查路径是否正确");
+	}
+
+	@ExceptionHandler(DuplicateKeyException.class)
+	public R handleDuplicateKeyException(DuplicateKeyException e){
+		log.error(e.getMessage(), e);
+		return R.error("数据库中已存在该记录");
+	}
+
+
+	@ExceptionHandler(Exception.class)
+	public R handleException(Exception e){
+		log.error(e.getMessage(), e);
+		return R.error();
+	}
+	@ExceptionHandler(AccessDeniedException.class)
+	public R handleAccessDeniedException(AccessDeniedException e){
+		log.error(e.getMessage(), e);
+		return R.error("没有权限");
+	}
+
+	@ExceptionHandler(BindException.class)
+	public R bindExceptionHandler(BindException e) {
+		FieldError error = e.getFieldError();
+		String message = String.format("%s",  error.getDefaultMessage());
+		return R.error(message);
+	}
+
+	@ExceptionHandler(MethodArgumentNotValidException.class)
+	public R exceptionHandler(MethodArgumentNotValidException e) {
+		FieldError error = e.getBindingResult().getFieldError();
+		String message = String.format("%s",  error.getDefaultMessage());
+		return R.error(message);
+	}
+	@ExceptionHandler(CustomException.class)
+	public R handleException(CustomException e){
+
+		return R.error(e.getMessage());
+	}
+}

+ 332 - 0
fs-ipad-task/src/main/java/com/fs/app/service/IpadSendServer.java

@@ -0,0 +1,332 @@
+package com.fs.app.service;
+
+import com.fs.common.core.redis.RedisCache;
+import com.fs.common.utils.StringUtils;
+import com.fs.common.utils.date.DateUtil;
+import com.fs.course.config.CourseMaConfig;
+import com.fs.course.domain.FsCourseWatchLog;
+import com.fs.course.service.IFsCourseWatchLogService;
+import com.fs.ipad.IpadSendUtils;
+import com.fs.ipad.vo.*;
+import com.fs.qw.domain.QwUser;
+import com.fs.qw.mapper.QwExternalContactMapper;
+import com.fs.qw.mapper.QwUserMapper;
+import com.fs.qw.vo.QwSopCourseFinishTempSetting;
+import com.fs.qwApi.param.QwExternalContactHParam;
+import com.fs.sop.domain.QwSopLogs;
+import com.fs.sop.service.IQwSopLogsService;
+import com.fs.sop.service.impl.QwSopLogsServiceImpl;
+import com.fs.wxwork.dto.*;
+import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDateTime;
+import java.util.Map;
+
+@Slf4j
+@Service
+@AllArgsConstructor
+public class IpadSendServer {
+
+    private final QwUserMapper qwUserMapper;
+    private final IpadSendUtils ipadSendUtils;
+    private final IQwSopLogsService qwSopLogsService;
+    private final QwExternalContactMapper qwExternalContactMapper;
+    private final IFsCourseWatchLogService watchLogService;
+    private final RedisCache redisCache;
+
+    private void sendMiniProgram(BaseVo vo, QwSopCourseFinishTempSetting.Setting content, Map<String, CourseMaConfig> miniMap) {
+        CourseMaConfig courseMaConfig = miniMap.get(content.getMiniprogramAppid());
+        // 小程序
+        MiniProgramVo miniProgramVo = MiniProgramVo.builder()
+                .desc(content.getMiniprogramTitle())
+                .title(courseMaConfig.getName())
+                .weappIconUrl(courseMaConfig.getLog())
+                .imgUrl(content.getMiniprogramPicUrl())
+                .username(courseMaConfig.getUsername() + "@app")
+                .pagepath(content.getMiniprogramPage())
+                .appid(content.getMiniprogramAppid())
+                .build();
+        miniProgramVo.setBase(vo);
+        WxWorkResponseDTO<WxWorkSendAppMsgRespDTO> resp = ipadSendUtils.sendMiniProgram(miniProgramVo);
+        if (resp.getErrcode() != 0) {
+            log.debug("ID:{}-ipad接口请求返回异常:{}", vo.getId(), resp.getErrmsg());
+            content.setSendStatus(2);
+            content.setSendRemarks("发送失败:" + resp.getErrmsg());
+        }
+    }
+
+    private void sendFile(BaseVo vo, QwSopCourseFinishTempSetting.Setting content) {
+        FileVo fileVo = FileVo.builder()
+                .url(content.getFileUrl())
+                .build();
+        fileVo.setBase(vo);
+        WxWorkResponseDTO<WxwSendCDNFileMsgRespDTO> resp = ipadSendUtils.sendFile(fileVo);
+        if (resp.getErrcode() != 0) {
+            log.debug("ID:{}-ipad接口请求返回异常:{}", vo.getId(), resp.getErrmsg());
+            content.setSendStatus(2);
+            content.setSendRemarks("发送失败:" + resp.getErrmsg());
+        }
+    }
+
+    public void sendTxt(BaseVo vo, QwSopCourseFinishTempSetting.Setting content) {
+        TxtVo txtVo = TxtVo.builder().content(content.getValue()).build();
+        txtVo.setBase(vo);
+        WxWorkResponseDTO<WxWorkSendTextMsgRespDTO> resp = ipadSendUtils.sendTxt(txtVo);
+        if (resp.getErrcode() != 0) {
+            log.debug("ID:{}-ipad接口请求返回异常:{}", vo.getId(), resp.getErrmsg());
+            content.setSendStatus(2);
+            content.setSendRemarks("发送失败:" + resp.getErrmsg());
+        }
+    }
+
+    public void sendImg(BaseVo vo, QwSopCourseFinishTempSetting.Setting content) {
+        FileVo imgVo = FileVo.builder().url(content.getImgUrl()).build();
+        imgVo.setBase(vo);
+        WxWorkResponseDTO<WxwSendCDNImgMsgRespDTO> resp = ipadSendUtils.sendImg(imgVo);
+        if (resp.getErrcode() != 0) {
+            log.debug("ID:{}-ipad接口请求返回异常:{}", vo.getId(), resp.getErrmsg());
+            content.setSendStatus(2);
+            content.setSendRemarks("发送失败:" + resp.getErrmsg());
+        }
+    }
+
+    public void sendLink(BaseVo vo, QwSopCourseFinishTempSetting.Setting content) {
+        // 文本
+        LinkVo linkVo = LinkVo.builder()
+                .title(content.getLinkTitle())
+                .content(content.getLinkDescribe())
+                .url(content.getLinkUrl())
+                .imgUrl(content.getLinkImageUrl())
+                .build();
+        linkVo.setBase(vo);
+        WxWorkResponseDTO<WxwSendLinkMsgRespDTO> resp = ipadSendUtils.sendLink(linkVo);
+        if (resp.getErrcode() != 0) {
+            log.debug("ID:{}-ipad接口请求返回异常:{}", vo.getId(), resp.getErrmsg());
+            content.setSendStatus(2);
+            content.setSendRemarks("发送失败:" + resp.getErrmsg());
+        }
+    }
+
+    public void sendVideo(BaseVo vo, QwSopCourseFinishTempSetting.Setting content) {
+        FileVo videoVo = FileVo.builder()
+                .url(content.getVideoUrl())
+                .build();
+        videoVo.setBase(vo);
+        WxWorkResponseDTO<WxwSendCDNVideoMsgRespDTO> resp = ipadSendUtils.sendVideo(videoVo);
+        if (resp.getErrcode() != 0) {
+            log.debug("ID:{}-ipad接口请求返回异常:{}", vo.getId(), resp.getErrmsg());
+            content.setSendStatus(2);
+            content.setSendRemarks("发送失败:" + resp.getErrmsg());
+        }
+    }
+
+    public void sendVoice(BaseVo vo, QwSopCourseFinishTempSetting.Setting content) {
+        if (StringUtils.isEmpty(content.getVoiceUrl()) || StringUtils.isEmpty(content.getVoiceDuration())) {
+            log.debug("语音未生成无法发送,转文字发送:{}", vo);
+            sendTxt(vo, content);
+            return;
+        }
+        FileVo voiceVo = FileVo.builder()
+                .url(content.getVoiceUrl())
+                .voiceTime(Integer.parseInt(content.getVoiceDuration()))
+                .build();
+        voiceVo.setBase(vo);
+        WxWorkResponseDTO<WxwSendCDNVoiceMsgRespDTO> resp = ipadSendUtils.sendVoice(voiceVo);
+        if (resp.getErrcode() != 0) {
+            log.debug("ID:{}-ipad接口请求返回异常:{}", vo.getId(), resp.getErrmsg());
+            content.setSendStatus(2);
+            content.setSendRemarks("发送失败:" + resp.getErrmsg());
+        }
+    }
+
+    public boolean isSend(QwUser qwUser) {
+        // 判断企微发送方式是否是ipad
+        if (qwUser.getSendMsgType() == 0) {
+            log.debug("企微用户:ID:{} 名称:{} 发送方式:{}", qwUser.getId(), qwUser.getQwUserName(), qwUser.getSendMsgType().toString());
+            return false;
+        }
+        // 判断是否信息准确
+        if (org.springframework.util.StringUtils.isEmpty(qwUser.getUid())) {
+            log.debug("企微用户:ID:{} 名称:{}", qwUser.getId(), qwUser.getQwUserName());
+            return false;
+        }
+        // 是否已经授权服务器地址
+        if (qwUser.getServerId() == null) {
+            log.debug("企微用户:ID:{} 名称:{} 未绑定AI主机", qwUser.getId(), qwUser.getQwUserName());
+            return false;
+        }
+        // ipad状态是否是登录状态
+        if (qwUser.getIpadStatus() == 0) {
+            log.debug("企微用户:ID:{} 名称:{} 未登录uid:{},serveID:{}", qwUser.getId(), qwUser.getQwUserName(), qwUser.getUid(), qwUser.getServerId());
+            return false;
+        }
+        // 更新信息使用的类
+        QwUser updateQwUser = new QwUser();
+        try {
+            // 调用ipad接口判断是否真实登录
+            WxLoginResp login = ipadSendUtils.isLogin(qwUser.getUid(), qwUser.getServerId());
+            if (login.getLoginType() == 0) {
+                updateQwUser.setId(qwUser.getId());
+                updateQwUser.setRemark("AI未初始化");
+                updateQwUser.setIpadStatus(0);
+                qwUserMapper.updateById(updateQwUser);
+                return false;
+            }
+            if (login.getLoginType() == 1) {
+                updateQwUser.setId(qwUser.getId());
+                updateQwUser.setRemark("未登录");
+                updateQwUser.setIpadStatus(0);
+                qwUserMapper.updateById(updateQwUser);
+                return false;
+            }
+            if (!login.getUser_info().isLogin()) {
+                updateQwUser.setId(qwUser.getId());
+                updateQwUser.setRemark("登录状态异常");
+                updateQwUser.setIpadStatus(0);
+                qwUserMapper.updateById(updateQwUser);
+                return false;
+            }
+            log.debug("QwUserID:{}, AI主机信息:{}", qwUser.getId(), login);
+        } catch (Exception e) {
+            updateQwUser.setId(qwUser.getId());
+            updateQwUser.setRemark("登录状态异常");
+            updateQwUser.setIpadStatus(0);
+            qwUserMapper.updateById(updateQwUser);
+            return false;
+        }
+        return true;
+    }
+
+    public boolean isSendLogs(QwSopLogs qwSopLogs, QwSopCourseFinishTempSetting setting, QwUser qwUser) {
+        if(qwSopLogs.getSendStatus() != 3){
+            log.info("状态异常不发送:{}, LOGID: {}", qwUser.getQwUserName(), qwSopLogs.getId());
+            return false;
+        }
+        if(redisCache.getCacheObject("qw:user:id:" + qwUser.getId()) != null){
+            log.info("频率异常不发送:{}", qwUser.getQwUserName());
+            return false;
+        }
+
+        boolean noSop = qwSopLogs.getSendType() != 3 && qwSopLogs.getSendType() != 7;
+
+        if (qwSopLogs.getExpiryTime() == null && noSop) {
+            // 作废消息
+            log.warn("SOP_LOG_ID:{}, SOP任务被删除", qwSopLogs.getId());
+            qwSopLogsService.updateQwSopLogsByWatchLogType(qwSopLogs.getId(), "SOP任务被删除");
+            return false;
+        }
+
+        LocalDateTime sendTime = DateUtil.stringToLocalDateTime(qwSopLogs.getSendTime());
+        LocalDateTime expiryDateTime;
+
+        // 判断是否过期
+        if(qwSopLogs.getSendType() == 3 || qwSopLogs.getSendType() == 7){
+            expiryDateTime = sendTime.plusHours(12);
+        }else{
+            expiryDateTime = sendTime.plusHours(qwSopLogs.getExpiryTime());
+        }
+
+        if (LocalDateTime.now().isAfter(expiryDateTime)  ) {
+            // 作废消息
+            log.warn("SOP_LOG_ID:{}, 已过期,不发送", qwSopLogs.getId());
+            qwSopLogsService.updateQwSopLogsByWatchLogType(qwSopLogs.getId(), "已过期,不发送");
+            return false;
+        }
+
+        if (setting.getCourseType() == null && noSop && setting.getType() == 2) {
+            log.warn("SOP_LOG_ID:{}, 模板未选消息类型,不发送", qwSopLogs.getId());
+            qwSopLogsService.updateQwSopLogsByWatchLogType(qwSopLogs.getId(), "模板未选消息类型,不发送");
+            return false;
+        }
+
+        if (qwSopLogs.getSendType() != 12 && noSop) {
+            // 客户的信息
+            QwExternalContactHParam contactHParam = new QwExternalContactHParam();
+            contactHParam.setUserId(qwUser.getQwUserId().trim());
+            contactHParam.setExternalUserId(qwSopLogs.getExternalUserId().trim());
+            contactHParam.setCorpId(qwUser.getCorpId().trim());
+            Integer courseType = setting.getCourseType();
+            if (setting.getType() == 2 && courseType != 0) {// 课程消息,进行复杂的条件判断
+                log.debug("企微查询:{}", contactHParam);
+                Long qwExternalContactId = qwExternalContactMapper.getQwExternalContactId(contactHParam);
+                FsCourseWatchLog watchLog = watchLogService.getWatchCourseLogVideoBySop(
+                        setting.getVideoId().longValue(),
+                        String.valueOf(qwUser.getId()),
+                        qwExternalContactId
+                );
+                log.debug("ID:{}-看课记录参数:videoID:{}, qwUserID:{}, extID:{}", qwSopLogs.getId(), setting.getVideoId().longValue(), qwUser.getId(), qwExternalContactId);
+                log.debug("ID:{}-看课记录:{}", qwSopLogs.getId(), watchLog);
+                String logId = qwSopLogs.getId();
+                if (watchLog != null) {
+                    //新逻辑
+                    if (!QwSopLogsServiceImpl.isCourseTypeValid(courseType, watchLog.getLogType())) {
+                        // 作废消息
+                        log.warn("SOP_LOG_ID:{}, 看课状态未满足,不发送", qwSopLogs.getId());
+                        qwSopLogsService.updateQwSopLogsByWatchLogType(logId, "看课状态未满足,不发送");
+                        return false;
+                    }
+                } else {
+                    log.warn("SOP_LOG_ID:{}, 无观看记录,不发送", qwSopLogs.getId());
+                    qwSopLogsService.updateQwSopLogsByWatchLogType(logId, "无观看记录,不发送");
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    public void send(QwSopCourseFinishTempSetting.Setting content, QwUser qwUser, QwSopLogs qwSopLogs, Map<String, CourseMaConfig> miniMap) {
+        BaseVo vo = new BaseVo();
+        vo.setId(Long.parseLong(qwSopLogs.getId()));
+        vo.setRoom(qwSopLogs.getSendType() == 12);
+        vo.setUuid(qwUser.getUid());
+        vo.setExId(qwSopLogs.getExternalUserId());
+        vo.setServerId(qwUser.getServerId());
+        try {
+            content.setSendStatus(1);
+            switch (content.getContentType()) {
+                case "1":
+                    // 文本
+                    sendTxt(vo, content);
+                    break;
+                case "2":
+                    // 图片
+                    sendImg(vo, content);
+                    break;
+                case "3":
+                    // 链接
+                    sendLink(vo, content);
+                    break;
+                case "4":
+                    sendMiniProgram(vo, content, miniMap);
+                    break;
+                case "5":
+                    // 文件
+                    sendFile(vo, content);
+                    break;
+                case "6":
+                    // 视频
+                    sendVideo(vo, content);
+                    break;
+                case "7":
+                    // 语音
+                    sendVoice(vo, content);
+                    break;
+                default:
+                    // 未知类型,记录警告
+                    log.error("SOP_LOG_ID:{}错误的发送类型: {}", qwSopLogs.getId(), content.getContentType());
+                    break;
+            }
+        } catch (Exception e) {
+            log.error("ID:" + qwSopLogs.getId() + "-发送失败QW_SOP_ID:" + qwSopLogs.getId(), e);
+            content.setSendStatus(2);
+            content.setSendRemarks("发送失败:" + e.getMessage());
+        }
+    }
+
+    public void loginOut(QwUser user) {
+        ipadSendUtils.loginOut(user.getUid(), user.getServerId());
+    }
+}

+ 234 - 0
fs-ipad-task/src/main/java/com/fs/app/task/SendMsg.java

@@ -0,0 +1,234 @@
+package com.fs.app.task;
+
+
+import com.alibaba.fastjson.JSON;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.fs.app.service.IpadSendServer;
+import com.fs.common.core.redis.RedisCacheT;
+import com.fs.common.utils.PubFun;
+import com.fs.course.config.CourseConfig;
+import com.fs.course.config.CourseMaConfig;
+import com.fs.ipad.vo.BaseVo;
+import com.fs.qw.domain.QwIpadServer;
+import com.fs.qw.domain.QwUser;
+import com.fs.qw.mapper.QwIpadServerMapper;
+import com.fs.qw.mapper.QwUserMapper;
+import com.fs.qw.service.impl.AsyncSopTestService;
+import com.fs.qw.vo.QwSopCourseFinishTempSetting;
+import com.fs.qw.vo.QwSopTempSetting;
+import com.fs.sop.domain.QwSopLogs;
+import com.fs.sop.mapper.QwSopLogsMapper;
+import com.fs.sop.service.IQwSopLogsService;
+import com.fs.system.domain.SysConfig;
+import com.fs.system.mapper.SysConfigMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+
+import java.text.SimpleDateFormat;
+import java.time.LocalDateTime;
+import java.util.*;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+@Component
+@Slf4j
+public class SendMsg {
+
+    private final QwUserMapper qwUserMapper;
+    private final QwSopLogsMapper qwSopLogsMapper;
+    private final IpadSendServer sendServer;
+    private final SysConfigMapper sysConfigMapper;
+    private final IQwSopLogsService qwSopLogsService;
+    private final AsyncSopTestService asyncSopTestService;
+    private final QwIpadServerMapper qwIpadServerMapper;
+    private final RedisCacheT<Long> redisCache;
+
+    @Value("${group-no}")
+    private String groupNo;
+    private final List<QwUser> qwUserList = Collections.synchronizedList(new ArrayList<>());
+    private final Map<Long, Long> qwMap = new ConcurrentHashMap<>();
+    private final Map<Long, Long> removeQwMap = new ConcurrentHashMap<>();
+
+    @Autowired
+    @Qualifier("customThreadPool")
+    private ThreadPoolTaskExecutor customThreadPool;
+
+    public SendMsg(QwUserMapper qwUserMapper, QwSopLogsMapper qwSopLogsMapper, IpadSendServer sendServer, SysConfigMapper sysConfigMapper, IQwSopLogsService qwSopLogsService, AsyncSopTestService asyncSopTestService, QwIpadServerMapper qwIpadServerMapper, RedisCacheT<Long> redisCache) {
+        this.qwUserMapper = qwUserMapper;
+        this.qwSopLogsMapper = qwSopLogsMapper;
+        this.sendServer = sendServer;
+        this.sysConfigMapper = sysConfigMapper;
+        this.qwSopLogsService = qwSopLogsService;
+        this.asyncSopTestService = asyncSopTestService;
+        this.qwIpadServerMapper = qwIpadServerMapper;
+        this.redisCache = redisCache;
+    }
+    private List<QwUser> getQwUserList() {
+        if (qwUserList.isEmpty()) {
+            List<QwIpadServer> serverList = qwIpadServerMapper.selectList(new QueryWrapper<QwIpadServer>().eq("group_no", groupNo));
+            if(serverList.isEmpty()){
+                return new ArrayList<>();
+            }
+            List<Long> serverIds = PubFun.listToNewList(serverList, QwIpadServer::getId);
+            List<QwUser> qwUsers = qwUserMapper.selectList(new QueryWrapper<QwUser>().eq("send_msg_type", 1).eq("server_status", 1).eq("ipad_status", 1).in("server_id", serverIds));
+            qwUserList.addAll(qwUsers);
+        }
+        return qwUserList;
+    }
+
+    private Map<String, CourseMaConfig> getMiniMap() {
+        SysConfig maConfig = sysConfigMapper.selectConfigByConfigKey("courseMa.config");
+        List<CourseMaConfig> courseMaConfigs = JSON.parseArray(maConfig.getConfigValue(), CourseMaConfig.class);
+        return PubFun.listToMapByGroupObject(courseMaConfigs, CourseMaConfig::getAppid);
+    }
+
+
+    @Scheduled(fixedRate = 50000) // 每50秒执行一次
+    public void refulsQwUserList() {
+        qwUserList.clear();
+    }
+    @Scheduled(fixedDelay = 20000) // 每20秒执行一次
+    public void sendMsg2() {
+        log.info("执行日志:{}", LocalDateTime.now());
+        if (StringUtils.isEmpty(groupNo)) {
+            log.error("corpId为空不执行");
+            return;
+        }
+        SysConfig courseConfig = sysConfigMapper.selectConfigByConfigKey("course.config");
+        CourseConfig config = JSON.parseObject(courseConfig.getConfigValue(), CourseConfig.class);
+        // 消息发送延迟
+        int delayStart;
+        int delayEnd;
+        if (config.getDelayStart() == null || config.getDelayEnd() == null) {
+            log.debug("消息发送延迟为空手动设置1000ms - 2000ms");
+            delayStart = 1000;
+            delayEnd = 2000;
+        } else {
+            delayStart = config.getDelayStart();
+            delayEnd = config.getDelayEnd();
+        }
+        Map<String, CourseMaConfig> miniMap = getMiniMap();
+        // 清空需要删除的
+        List<Long> keyList = new ArrayList<>(removeQwMap.keySet());
+        keyList.forEach(key -> {
+            removeQwMap.remove(key);
+            qwMap.remove(key);
+        });
+        log.info("删除id:{}", JSON.toJSONString(keyList));
+        getQwUserList().forEach(e -> {
+            synchronized (e.getId()){
+                if (qwMap.containsKey(e.getId())) {
+                    log.error("用户:{}已在处理中,跳过重复执行", e.getQwUserName());
+                    return;
+                }
+                qwMap.computeIfAbsent(e.getId(), k -> {
+                    CompletableFuture.runAsync(() -> {
+                        try {
+                            processUser(e, delayStart, delayEnd, miniMap);
+                        } catch (Exception exception){
+                            log.error("发送错误:", exception);
+                        }finally {
+                            removeQwMap.putIfAbsent(e.getId(), System.currentTimeMillis());
+                        }
+                    }, customThreadPool);
+                    return System.currentTimeMillis(); // 占位值
+                });
+            }
+        });
+    }
+
+    private void processUser(QwUser qwUser, int delayStart, int delayEnd, Map<String, CourseMaConfig> miniMap) {
+        long start1 = System.currentTimeMillis();
+        List<QwSopLogs> qwSopLogList = qwSopLogsMapper.selectByQwUserId(qwUser.getId());
+        if(qwSopLogList.isEmpty()){
+            return;
+        }
+        QwUser user = qwUserMapper.selectById(qwUser.getId());
+        BaseVo parentVo = new BaseVo();
+        long end1 = System.currentTimeMillis();
+        if (!sendServer.isSend(user)) {
+            return;
+        }
+        log.info("销售:{}, 消息:{}, 耗时: {}, 时间:{}", user.getQwUserName(), qwSopLogList.size(), end1 - start1, qwMap.get(qwUser.getId()));
+        long start3 = System.currentTimeMillis();
+        for (QwSopLogs qwSopLogs : qwSopLogList) {
+            long start2 = System.currentTimeMillis();
+            QwSopCourseFinishTempSetting setting = JSON.parseObject(qwSopLogs.getContentJson(), QwSopCourseFinishTempSetting.class);
+            // 判断消息状态是否满足发送条件
+            if (!sendServer.isSendLogs(qwSopLogs, setting, user)) {
+                log.info("销售:{}, 消息发送条件未满足:{}", user.getQwUserName(), qwSopLogs.getId());
+                continue;
+            }
+            log.info("进入发送消息状态:{}", qwSopLogs.getId());
+            String key = "qw:logs:pad:send:id:" + qwSopLogs.getId();
+            Long time = redisCache.getCacheObject(key);
+            if(redisCache.getCacheObject(key) != null){
+                log.error("{}已有发送:{}, :{}", qwUser.getQwUserName(), qwSopLogs.getId(), time);
+                return;
+            }
+            redisCache.setCacheObject(key, System.currentTimeMillis(), 10, TimeUnit.MINUTES);
+            for (QwSopCourseFinishTempSetting.Setting content : setting.getSetting()) {
+                sendServer.send(content, user, qwSopLogs, miniMap);
+//                if(content.getSendStatus() == 2 && "请求失败:消息发送过于频繁,请稍后再试".equals(content.getSendRemarks())){
+//                    QwUser update = new QwUser();
+//                    update.setRemark("请求频率异常,暂停发送,三小时后恢复继续发送");
+//                    update.setUpdateTime(new Date());
+//                    qwUserMapper.update(update, new QueryWrapper<QwUser>().eq("id", user.getId()));
+//                    redisCache.setCacheObject("qw:user:id:" + user.getId(), user.getId(), 3, TimeUnit.HOURS);
+//                    return;
+//                }
+                try {
+                    int delay = ThreadLocalRandom.current().nextInt(300, 1000);
+                    log.debug("等待:{}ms", delay);
+                    Thread.sleep(delay);
+                } catch (InterruptedException e) {
+                    log.error("线程等待错误!");
+                }
+            }
+            qwSopLogs.setSend(true);
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+            QwSopLogs updateQwSop = new QwSopLogs();
+            updateQwSop.setId(qwSopLogs.getId());
+            // 是否全部发送失败
+            if (setting.getSetting().stream().allMatch(e -> e.getSendStatus() == 2)) {
+                updateQwSop.setReceivingStatus(0L);
+                updateQwSop.setSendStatus(0L);
+                updateQwSop.setRemark("全部发送失败");
+            } else if (setting.getSetting().stream().anyMatch(e -> e.getSendStatus() == 2)) {
+                updateQwSop.setReceivingStatus(1L);
+                updateQwSop.setSendStatus(1L);
+                updateQwSop.setRemark("部分发送失败");
+                updateQwSop.setRealSendTime(sdf.format(new Date()));
+            } else {
+                updateQwSop.setReceivingStatus(1L);
+                updateQwSop.setSendStatus(1L);
+                updateQwSop.setRemark("全部发送成功");
+                updateQwSop.setRealSendTime(sdf.format(new Date()));
+            }
+//            updateQwSop.setReceivingStatus(1L);
+//            updateQwSop.setSendStatus(1L);
+//            updateQwSop.setRealSendTime(sdf.format(new Date()));
+            long end2 = System.currentTimeMillis();
+            int i = qwSopLogsService.updateQwSopLogsSendType(updateQwSop);
+            log.info("销售:{}, 修改条数{}, 发送方消息完成:{}, 耗时: {}", user.getQwUserName(), i, qwSopLogs.getId(),end2 - start2);
+            try {
+                int delay = ThreadLocalRandom.current().nextInt(delayStart, delayEnd);
+                log.debug("等待:{}ms", delay);
+                Thread.sleep(delay);
+            } catch (InterruptedException e) {
+                log.error("线程等待错误!");
+            }
+        }
+        long end3 = System.currentTimeMillis();
+        log.info("销售执行完成:{}, 耗时:{}", user.getQwUserName(), end3 - start3);
+    }
+}

+ 171 - 0
fs-ipad-task/src/main/java/com/fs/framework/aspectj/DataScopeAspect.java

@@ -0,0 +1,171 @@
+package com.fs.framework.aspectj;
+
+import com.fs.common.annotation.DataScope;
+import com.fs.common.core.domain.BaseEntity;
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.StringUtils;
+import com.fs.common.utils.spring.SpringUtils;
+import com.fs.company.domain.CompanyRole;
+import com.fs.company.domain.CompanyUser;
+import com.fs.framework.security.LoginUser;
+import com.fs.framework.service.TokenService;
+import org.aspectj.lang.JoinPoint;
+import org.aspectj.lang.Signature;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Before;
+import org.aspectj.lang.annotation.Pointcut;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Method;
+
+/**
+ * 数据过滤处理
+ *
+
+ */
+@Aspect
+@Component
+public class DataScopeAspect
+{
+    /**
+     * 全部数据权限
+     */
+    public static final String DATA_SCOPE_ALL = "1";
+
+    /**
+     * 自定数据权限
+     */
+    public static final String DATA_SCOPE_CUSTOM = "2";
+
+    /**
+     * 部门数据权限
+     */
+    public static final String DATA_SCOPE_DEPT = "3";
+
+    /**
+     * 部门及以下数据权限
+     */
+    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";
+
+    /**
+     * 仅本人数据权限
+     */
+    public static final String DATA_SCOPE_SELF = "5";
+
+    /**
+     * 数据权限过滤关键字
+     */
+    public static final String DATA_SCOPE = "dataScope";
+
+    // 配置织入点
+    @Pointcut("@annotation(com.fs.common.annotation.DataScope)")
+    public void dataScopePointCut()
+    {
+    }
+
+    @Before("dataScopePointCut()")
+    public void doBefore(JoinPoint point) throws Throwable
+    {
+        handleDataScope(point);
+    }
+
+    protected void handleDataScope(final JoinPoint joinPoint)
+    {
+        // 获得注解
+        DataScope controllerDataScope = getAnnotationLog(joinPoint);
+        if (controllerDataScope == null)
+        {
+            return;
+        }
+        // 获取当前的用户
+        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
+        if (StringUtils.isNotNull(loginUser))
+        {
+            CompanyUser currentUser = loginUser.getUser();
+            // 如果是超级管理员,则不过滤数据
+            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())
+            {
+                dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
+                        controllerDataScope.userAlias());
+            }
+        }
+    }
+
+    /**
+     * 数据范围过滤
+     *
+     * @param joinPoint 切点
+     * @param user 用户
+     * @param userAlias 别名
+     */
+    public static void dataScopeFilter(JoinPoint joinPoint, CompanyUser user, String deptAlias, String userAlias)
+    {
+        StringBuilder sqlString = new StringBuilder();
+
+        for (CompanyRole role : user.getRoles())
+        {
+            String dataScope = role.getDataScope();
+            if (DATA_SCOPE_ALL.equals(dataScope))
+            {
+                sqlString = new StringBuilder();
+                break;
+            }
+            else if (DATA_SCOPE_CUSTOM.equals(dataScope))
+            {
+                sqlString.append(StringUtils.format(
+                        " OR {}.dept_id IN ( SELECT dept_id FROM company_role_dept WHERE role_id = {} ) ", deptAlias,
+                        role.getRoleId()));
+            }
+            else if (DATA_SCOPE_DEPT.equals(dataScope))
+            {
+                sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
+            }
+            else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope))
+            {
+                sqlString.append(StringUtils.format(
+                        " OR {}.dept_id IN ( SELECT dept_id FROM company_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
+                        deptAlias, user.getDeptId(), user.getDeptId()));
+            }
+            else if (DATA_SCOPE_SELF.equals(dataScope))
+            {
+                if (StringUtils.isNotBlank(userAlias))
+                {
+                    sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
+                }
+                else
+                {
+                    // 数据权限为仅本人且没有userAlias别名不查询任何数据
+                    //sqlString.append(" OR 1=0 ");
+                        sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
+                }
+            }
+        }
+
+        if (StringUtils.isNotBlank(sqlString.toString()))
+        {
+            Object params = joinPoint.getArgs()[0];
+            if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
+            {
+                BaseEntity baseEntity = (BaseEntity) params;
+                baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
+            }
+        }
+    }
+
+    /**
+     * 是否存在注解,如果存在就获取
+     */
+    private DataScope getAnnotationLog(JoinPoint joinPoint)
+    {
+        Signature signature = joinPoint.getSignature();
+        MethodSignature methodSignature = (MethodSignature) signature;
+        Method method = methodSignature.getMethod();
+
+        if (method != null)
+        {
+            return method.getAnnotation(DataScope.class);
+        }
+        return null;
+    }
+}

+ 73 - 0
fs-ipad-task/src/main/java/com/fs/framework/aspectj/DataSourceAspect.java

@@ -0,0 +1,73 @@
+package com.fs.framework.aspectj;
+
+import com.fs.common.annotation.DataSource;
+import com.fs.common.utils.StringUtils;
+import com.fs.framework.datasource.DynamicDataSourceContextHolder;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.core.annotation.AnnotationUtils;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+
+import java.util.Objects;
+
+/**
+ * 多数据源处理
+ * 
+ 
+ */
+@Aspect
+@Order(1)
+@Component
+public class DataSourceAspect
+{
+    protected Logger logger = LoggerFactory.getLogger(getClass());
+
+    @Pointcut("@annotation(com.fs.common.annotation.DataSource)"
+            + "|| @within(com.fs.common.annotation.DataSource)")
+    public void dsPointCut()
+    {
+
+    }
+
+    @Around("dsPointCut()")
+    public Object around(ProceedingJoinPoint point) throws Throwable
+    {
+        DataSource dataSource = getDataSource(point);
+
+        if (StringUtils.isNotNull(dataSource))
+        {
+            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
+        }
+
+        try
+        {
+            return point.proceed();
+        }
+        finally
+        {
+            // 销毁数据源 在执行方法之后
+            DynamicDataSourceContextHolder.clearDataSourceType();
+        }
+    }
+
+    /**
+     * 获取需要切换的数据源
+     */
+    public DataSource getDataSource(ProceedingJoinPoint point)
+    {
+        MethodSignature signature = (MethodSignature) point.getSignature();
+        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
+        if (Objects.nonNull(dataSource))
+        {
+            return dataSource;
+        }
+
+        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
+    }
+}

+ 219 - 0
fs-ipad-task/src/main/java/com/fs/framework/aspectj/LogAspect.java

@@ -0,0 +1,219 @@
+package com.fs.framework.aspectj;
+
+import com.alibaba.fastjson.JSON;
+import com.fs.common.annotation.Log;
+import com.fs.common.enums.BusinessStatus;
+import com.fs.common.enums.HttpMethod;
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.StringUtils;
+import com.fs.common.utils.ip.IpUtils;
+import com.fs.common.utils.spring.SpringUtils;
+import com.fs.company.domain.CompanyOperLog;
+import com.fs.framework.manager.AsyncManager;
+import com.fs.framework.manager.factory.AsyncFactory;
+import com.fs.framework.security.LoginUser;
+import com.fs.framework.service.TokenService;
+import org.aspectj.lang.JoinPoint;
+import org.aspectj.lang.Signature;
+import org.aspectj.lang.annotation.AfterReturning;
+import org.aspectj.lang.annotation.AfterThrowing;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.servlet.HandlerMapping;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+/**
+ * 操作日志记录处理
+ * 
+
+ */
+@Aspect
+@Component
+public class LogAspect
+{
+    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
+
+    // 配置织入点
+    @Pointcut("@annotation(com.fs.common.annotation.Log)")
+    public void logPointCut()
+    {
+    }
+
+    /**
+     * 处理完请求后执行
+     *
+     * @param joinPoint 切点
+     */
+    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
+    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
+    {
+        handleLog(joinPoint, null, jsonResult);
+    }
+
+    /**
+     * 拦截异常操作
+     * 
+     * @param joinPoint 切点
+     * @param e 异常
+     */
+    @AfterThrowing(value = "logPointCut()", throwing = "e")
+    public void doAfterThrowing(JoinPoint joinPoint, Exception e)
+    {
+        handleLog(joinPoint, e, null);
+    }
+
+    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult)
+    {
+        try
+        {
+            // 获得注解
+            Log controllerLog = getAnnotationLog(joinPoint);
+            if (controllerLog == null)
+            {
+                return;
+            }
+
+            // 获取当前的用户
+            LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
+
+            // *========数据库日志=========*//
+            CompanyOperLog operLog = new CompanyOperLog();
+            operLog.setCompanyId(loginUser.getCompany().getCompanyId());
+            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
+            // 请求的地址
+            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
+            operLog.setOperIp(ip);
+            // 返回参数
+            operLog.setJsonResult(JSON.toJSONString(jsonResult));
+
+            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
+            if (loginUser != null)
+            {
+                operLog.setOperName(loginUser.getUsername());
+            }
+
+            if (e != null)
+            {
+                operLog.setStatus(BusinessStatus.FAIL.ordinal());
+                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
+            }
+            // 设置方法名称
+            String className = joinPoint.getTarget().getClass().getName();
+            String methodName = joinPoint.getSignature().getName();
+            operLog.setMethod(className + "." + methodName + "()");
+            // 设置请求方式
+            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
+            // 处理设置注解上的参数
+            getControllerMethodDescription(joinPoint, controllerLog, operLog);
+            // 保存数据库
+            AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
+        }
+        catch (Exception exp)
+        {
+            // 记录本地异常日志
+            log.error("==前置通知异常==");
+            log.error("异常信息:{}", exp.getMessage());
+            exp.printStackTrace();
+        }
+    }
+
+    /**
+     * 获取注解中对方法的描述信息 用于Controller层注解
+     * 
+     * @param log 日志
+     * @param operLog 操作日志
+     * @throws Exception
+     */
+    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, CompanyOperLog operLog) throws Exception
+    {
+        // 设置action动作
+        operLog.setBusinessType(log.businessType().ordinal());
+        // 设置标题
+        operLog.setTitle(log.title());
+        // 设置操作人类别
+        operLog.setOperatorType(log.operatorType().ordinal());
+        // 是否需要保存request,参数和值
+        if (log.isSaveRequestData())
+        {
+            // 获取参数的信息,传入到数据库中。
+            setRequestValue(joinPoint, operLog);
+        }
+    }
+
+    /**
+     * 获取请求的参数,放到log中
+     * 
+     * @param operLog 操作日志
+     * @throws Exception 异常
+     */
+    private void setRequestValue(JoinPoint joinPoint, CompanyOperLog operLog) throws Exception
+    {
+        String requestMethod = operLog.getRequestMethod();
+        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))
+        {
+            String params = argsArrayToString(joinPoint.getArgs());
+            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
+        }
+        else
+        {
+            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
+            operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
+        }
+    }
+
+    /**
+     * 是否存在注解,如果存在就获取
+     */
+    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
+    {
+        Signature signature = joinPoint.getSignature();
+        MethodSignature methodSignature = (MethodSignature) signature;
+        Method method = methodSignature.getMethod();
+
+        if (method != null)
+        {
+            return method.getAnnotation(Log.class);
+        }
+        return null;
+    }
+
+    /**
+     * 参数拼装
+     */
+    private String argsArrayToString(Object[] paramsArray)
+    {
+        String params = "";
+        if (paramsArray != null && paramsArray.length > 0)
+        {
+            for (int i = 0; i < paramsArray.length; i++)
+            {
+                if (!isFilterObject(paramsArray[i]))
+                {
+                    Object jsonObj = JSON.toJSON(paramsArray[i]);
+                    params += jsonObj.toString() + " ";
+                }
+            }
+        }
+        return params.trim();
+    }
+
+    /**
+     * 判断是否需要过滤的对象。
+     * 
+     * @param o 对象信息。
+     * @return 如果是需要过滤的对象,则返回true;否则返回false。
+     */
+    public boolean isFilterObject(final Object o)
+    {
+        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
+    }
+}

+ 117 - 0
fs-ipad-task/src/main/java/com/fs/framework/aspectj/RateLimiterAspect.java

@@ -0,0 +1,117 @@
+package com.fs.framework.aspectj;
+
+import com.fs.common.annotation.RateLimiter;
+import com.fs.common.enums.LimitType;
+import com.fs.common.exception.ServiceException;
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.StringUtils;
+import com.fs.common.utils.ip.IpUtils;
+import org.aspectj.lang.JoinPoint;
+import org.aspectj.lang.Signature;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Before;
+import org.aspectj.lang.annotation.Pointcut;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.script.RedisScript;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * 限流处理
+ *
+
+ */
+@Aspect
+@Component
+public class RateLimiterAspect
+{
+    private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class);
+
+    private RedisTemplate<Object, Object> redisTemplate;
+
+    private RedisScript<Long> limitScript;
+
+    @Autowired
+    public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate)
+    {
+        this.redisTemplate = redisTemplate;
+    }
+
+    @Autowired
+    public void setLimitScript(RedisScript<Long> limitScript)
+    {
+        this.limitScript = limitScript;
+    }
+
+    // 配置织入点
+    @Pointcut("@annotation(com.fs.common.annotation.RateLimiter)")
+    public void rateLimiterPointCut()
+    {
+    }
+
+    @Before("rateLimiterPointCut()")
+    public void doBefore(JoinPoint point) throws Throwable
+    {
+        RateLimiter rateLimiter = getAnnotationRateLimiter(point);
+        String key = rateLimiter.key();
+        int time = rateLimiter.time();
+        int count = rateLimiter.count();
+
+        String combineKey = getCombineKey(rateLimiter, point);
+        List<Object> keys = Collections.singletonList(combineKey);
+        try
+        {
+            Long number = redisTemplate.execute(limitScript, keys, count, time);
+            if (StringUtils.isNull(number) || number.intValue() > count)
+            {
+                throw new ServiceException("访问过于频繁,请稍后再试");
+            }
+            log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), key);
+        }
+        catch (ServiceException e)
+        {
+            throw e;
+        }
+        catch (Exception e)
+        {
+            throw new RuntimeException("服务器限流异常,请稍后再试");
+        }
+    }
+
+    /**
+     * 是否存在注解,如果存在就获取
+     */
+    private RateLimiter getAnnotationRateLimiter(JoinPoint joinPoint)
+    {
+        Signature signature = joinPoint.getSignature();
+        MethodSignature methodSignature = (MethodSignature) signature;
+        Method method = methodSignature.getMethod();
+
+        if (method != null)
+        {
+            return method.getAnnotation(RateLimiter.class);
+        }
+        return null;
+    }
+
+    public String getCombineKey(RateLimiter rateLimiter, JoinPoint point)
+    {
+        StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());
+        if (rateLimiter.limitType() == LimitType.IP)
+        {
+            stringBuffer.append(IpUtils.getIpAddr(ServletUtils.getRequest()));
+        }
+        MethodSignature signature = (MethodSignature) point.getSignature();
+        Method method = signature.getMethod();
+        Class<?> targetClass = method.getDeclaringClass();
+        stringBuffer.append("-").append(targetClass.getName()).append("- ").append(method.getName());
+        return stringBuffer.toString();
+    }
+}

+ 31 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/ApplicationConfig.java

@@ -0,0 +1,31 @@
+package com.fs.framework.config;
+
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+
+import java.util.TimeZone;
+
+/**
+ * 程序注解配置
+ *
+
+ */
+@Configuration
+// 表示通过aop框架暴露该代理对象,AopContext能够访问
+@EnableAspectJAutoProxy(exposeProxy = true)
+// 指定要扫描的Mapper类的包的路径
+@MapperScan("com.fs.**.mapper")
+public class ApplicationConfig
+{
+    /**
+     * 时区配置
+     */
+    @Bean
+    public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization()
+    {
+        return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault());
+    }
+}

+ 58 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/ArrayStringTypeHandler.java

@@ -0,0 +1,58 @@
+package com.fs.framework.config;
+
+import org.apache.ibatis.type.BaseTypeHandler;
+import org.apache.ibatis.type.JdbcType;
+import org.springframework.context.annotation.Configuration;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+
+@Configuration
+public class ArrayStringTypeHandler extends BaseTypeHandler<List<String>> {
+
+    @Override
+    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
+        // 将 List<String> 转换为字符串,ClickHouse 支持的格式为 "['item1', 'item2']"
+        StringBuilder sb = new StringBuilder();
+        sb.append("[");
+        for (int j = 0; j < parameter.size(); j++) {
+            sb.append("'").append(parameter.get(j)).append("'");
+            if (j < parameter.size() - 1) {
+                sb.append(",");
+            }
+        }
+        sb.append("]");
+        ps.setString(i, sb.toString());
+    }
+
+    @Override
+    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
+        // 处理查询结果,将其转换为 List<String>
+        String result = rs.getString(columnName);
+        return parseArray(result);
+    }
+
+    @Override
+    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
+        String result = rs.getString(columnIndex);
+        return parseArray(result);
+    }
+
+    @Override
+    public List<String> getNullableResult(java.sql.CallableStatement cs, int columnIndex) throws SQLException {
+        String result = cs.getString(columnIndex);
+        return parseArray(result);
+    }
+
+    private List<String> parseArray(String arrayStr) {
+        // 将 ClickHouse 的 Array 字符串转换为 List<String>
+        if (arrayStr == null || arrayStr.isEmpty()) {
+            return null;
+        }
+        arrayStr = arrayStr.substring(1, arrayStr.length() - 1);  // 去掉 "[" 和 "]"
+        String[] elements = arrayStr.split(",");
+        return java.util.Arrays.asList(elements);
+    }
+}

+ 85 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/CaptchaConfig.java

@@ -0,0 +1,85 @@
+package com.fs.framework.config;
+
+import com.google.code.kaptcha.impl.DefaultKaptcha;
+import com.google.code.kaptcha.util.Config;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.util.Properties;
+
+import static com.google.code.kaptcha.Constants.*;
+
+/**
+ * 验证码配置
+ * 
+
+ */
+@Configuration
+public class CaptchaConfig
+{
+    @Bean(name = "captchaProducer")
+    public DefaultKaptcha getKaptchaBean()
+    {
+        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
+        Properties properties = new Properties();
+        // 是否有边框 默认为true 我们可以自己设置yes,no
+        properties.setProperty(KAPTCHA_BORDER, "yes");
+        // 验证码文本字符颜色 默认为Color.BLACK
+        properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");
+        // 验证码图片宽度 默认为200
+        properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
+        // 验证码图片高度 默认为50
+        properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
+        // 验证码文本字符大小 默认为40
+        properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38");
+        // KAPTCHA_SESSION_KEY
+        properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode");
+        // 验证码文本字符长度 默认为5
+        properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
+        // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
+        properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
+        // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
+        properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
+        Config config = new Config(properties);
+        defaultKaptcha.setConfig(config);
+        return defaultKaptcha;
+    }
+
+    @Bean(name = "captchaProducerMath")
+    public DefaultKaptcha getKaptchaBeanMath()
+    {
+        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
+        Properties properties = new Properties();
+        // 是否有边框 默认为true 我们可以自己设置yes,no
+        properties.setProperty(KAPTCHA_BORDER, "yes");
+        // 边框颜色 默认为Color.BLACK
+        properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90");
+        // 验证码文本字符颜色 默认为Color.BLACK
+        properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
+        // 验证码图片宽度 默认为200
+        properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
+        // 验证码图片高度 默认为50
+        properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
+        // 验证码文本字符大小 默认为40
+        properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35");
+        // KAPTCHA_SESSION_KEY
+        properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath");
+        // 验证码文本生成器
+        properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "com.fs.framework.config.KaptchaTextCreator");
+        // 验证码文本字符间距 默认为2
+        properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3");
+        // 验证码文本字符长度 默认为5
+        properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6");
+        // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
+        properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
+        // 验证码噪点颜色 默认为Color.BLACK
+        properties.setProperty(KAPTCHA_NOISE_COLOR, "white");
+        // 干扰实现类
+        properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
+        // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
+        properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
+        Config config = new Config(properties);
+        defaultKaptcha.setConfig(config);
+        return defaultKaptcha;
+    }
+}

+ 118 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/DataSourceConfig.java

@@ -0,0 +1,118 @@
+package com.fs.framework.config;
+
+import com.alibaba.druid.pool.DruidDataSource;
+import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
+import com.alibaba.druid.util.Utils;
+import com.fs.common.enums.DataSourceType;
+import com.fs.framework.datasource.DynamicDataSource;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.boot.web.servlet.FilterRegistrationBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+
+import javax.servlet.*;
+import javax.sql.DataSource;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+@Configuration
+public class DataSourceConfig {
+    @Bean
+    @ConfigurationProperties(prefix = "spring.datasource.sop.druid.master")
+    public DataSource sopDataSource() {
+        return new DruidDataSource();
+    }
+
+    @Bean
+    @ConfigurationProperties(prefix = "spring.datasource.sop.druid.read")
+    public DataSource sopReadDataSource() {
+        return new DruidDataSource();
+    }
+
+    @Bean
+    @ConfigurationProperties(prefix = "spring.datasource.clickhouse")
+    public DataSource clickhouseDataSource() {
+        return new DruidDataSource();
+    }
+
+    @Bean
+    @ConfigurationProperties(prefix = "spring.datasource.mysql.druid.master")
+    public DataSource masterDataSource() {
+        return new DruidDataSource();
+    }
+
+    @Bean
+    @ConfigurationProperties(prefix = "spring.datasource.mysql.druid.slave")
+    public DataSource slaveDataSource() {
+        return new DruidDataSource();
+    }
+
+
+
+    @Bean
+    @Primary
+    public DynamicDataSource dataSource(@Qualifier("clickhouseDataSource") DataSource clickhouseDataSource,
+                                        @Qualifier("masterDataSource") DataSource masterDataSource,
+                                        @Qualifier("sopDataSource") DataSource sopDataSource,
+                                        @Qualifier("slaveDataSource") DataSource slaveDataSource,
+                                        @Qualifier("sopReadDataSource") DataSource sopReadDataSource
+                                        ) {
+        Map<Object, Object> targetDataSources = new HashMap<>();
+        targetDataSources.put(DataSourceType.MASTER, masterDataSource);
+
+        targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource);
+        targetDataSources.put(DataSourceType.SOP.name(), sopDataSource);
+        targetDataSources.put(DataSourceType.CLICKHOUSE.name(), clickhouseDataSource); // Ensure matching key
+        return new DynamicDataSource(masterDataSource, targetDataSources);
+    }
+
+    /**
+     * 去除监控页面底部的广告
+     */
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @Bean
+    @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
+    public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties)
+    {
+        // 获取web监控页面的参数
+        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
+        // 提取common.js的配置路径
+        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
+        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
+        final String filePath = "support/http/resources/js/common.js";
+        // 创建filter进行过滤
+        Filter filter = new Filter()
+        {
+            @Override
+            public void init(javax.servlet.FilterConfig filterConfig) throws ServletException
+            {
+            }
+            @Override
+            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+                    throws IOException, ServletException
+            {
+                chain.doFilter(request, response);
+                // 重置缓冲区,响应头不会被重置
+                response.resetBuffer();
+                // 获取common.js
+                String text = Utils.readFromResource(filePath);
+                // 正则替换banner, 除去底部的广告信息
+                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
+                text = text.replaceAll("powered.*?shrek.wang</a>", "");
+                response.getWriter().write(text);
+            }
+            @Override
+            public void destroy()
+            {
+            }
+        };
+        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
+        registrationBean.setFilter(filter);
+        registrationBean.addUrlPatterns(commonJsPattern);
+        return registrationBean;
+    }
+}

+ 123 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/DruidConfig.java

@@ -0,0 +1,123 @@
+package com.fs.framework.config;//package com.fs.framework.config;
+//
+//import com.alibaba.druid.pool.DruidDataSource;
+//import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
+//import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
+//import com.alibaba.druid.util.Utils;
+//import com.fs.framework.datasource.DynamicDataSource;
+//import com.fs.common.enums.DataSourceType;
+//import com.fs.common.utils.spring.SpringUtils;
+//import com.fs.framework.config.properties.DruidProperties;
+//import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+//import org.springframework.boot.context.properties.ConfigurationProperties;
+//import org.springframework.boot.web.servlet.FilterRegistrationBean;
+//import org.springframework.context.annotation.Bean;
+//import org.springframework.context.annotation.Configuration;
+//import org.springframework.context.annotation.Primary;
+//
+//import javax.servlet.*;
+//import javax.sql.DataSource;
+//import java.io.IOException;
+//import java.util.HashMap;
+//import java.util.Map;
+//
+///**
+// * druid 配置多数据源
+// *
+//
+// */
+//@Configuration
+//public class DruidConfig
+//{
+//    @Bean
+//    @ConfigurationProperties("spring.datasource.druid.master")
+//    public DataSource masterDataSource(DruidProperties druidProperties)
+//    {
+//        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
+//        return druidProperties.dataSource(dataSource);
+//    }
+//
+//    @Bean
+//    @ConfigurationProperties("spring.datasource.druid.slave")
+//    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
+//    public DataSource slaveDataSource(DruidProperties druidProperties)
+//    {
+//        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
+//        return druidProperties.dataSource(dataSource);
+//    }
+//
+//    @Bean(name = "dynamicDataSource")
+//    @Primary
+//    public DynamicDataSource dataSource(DataSource masterDataSource)
+//    {
+//        Map<Object, Object> targetDataSources = new HashMap<>();
+//        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
+//        setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource");
+//        return new DynamicDataSource(masterDataSource, targetDataSources);
+//    }
+//
+//    /**
+//     * 设置数据源
+//     *
+//     * @param targetDataSources 备选数据源集合
+//     * @param sourceName 数据源名称
+//     * @param beanName bean名称
+//     */
+//    public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName)
+//    {
+//        try
+//        {
+//            DataSource dataSource = SpringUtils.getBean(beanName);
+//            targetDataSources.put(sourceName, dataSource);
+//        }
+//        catch (Exception e)
+//        {
+//        }
+//    }
+//
+//    /**
+//     * 去除监控页面底部的广告
+//     */
+//    @SuppressWarnings({ "rawtypes", "unchecked" })
+//    @Bean
+//    @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
+//    public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties)
+//    {
+//        // 获取web监控页面的参数
+//        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
+//        // 提取common.js的配置路径
+//        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
+//        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
+//        final String filePath = "support/http/resources/js/common.js";
+//        // 创建filter进行过滤
+//        Filter filter = new Filter()
+//        {
+//            @Override
+//            public void init(javax.servlet.FilterConfig filterConfig) throws ServletException
+//            {
+//            }
+//            @Override
+//            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+//                    throws IOException, ServletException
+//            {
+//                chain.doFilter(request, response);
+//                // 重置缓冲区,响应头不会被重置
+//                response.resetBuffer();
+//                // 获取common.js
+//                String text = Utils.readFromResource(filePath);
+//                // 正则替换banner, 除去底部的广告信息
+//                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
+//                text = text.replaceAll("powered.*?shrek.wang</a>", "");
+//                response.getWriter().write(text);
+//            }
+//            @Override
+//            public void destroy()
+//            {
+//            }
+//        };
+//        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
+//        registrationBean.setFilter(filter);
+//        registrationBean.addUrlPatterns(commonJsPattern);
+//        return registrationBean;
+//    }
+//}

+ 72 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/FastJson2JsonRedisSerializer.java

@@ -0,0 +1,72 @@
+package com.fs.framework.config;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.parser.ParserConfig;
+import com.alibaba.fastjson.serializer.SerializerFeature;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+import org.springframework.data.redis.serializer.RedisSerializer;
+import org.springframework.data.redis.serializer.SerializationException;
+import org.springframework.util.Assert;
+
+import java.nio.charset.Charset;
+
+/**
+ * Redis使用FastJson序列化
+ * 
+
+ */
+public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
+{
+    @SuppressWarnings("unused")
+    private ObjectMapper objectMapper = new ObjectMapper();
+
+    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
+
+    private Class<T> clazz;
+
+    static
+    {
+        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
+    }
+
+    public FastJson2JsonRedisSerializer(Class<T> clazz)
+    {
+        super();
+        this.clazz = clazz;
+    }
+
+    @Override
+    public byte[] serialize(T t) throws SerializationException
+    {
+        if (t == null)
+        {
+            return new byte[0];
+        }
+        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
+    }
+
+    @Override
+    public T deserialize(byte[] bytes) throws SerializationException
+    {
+        if (bytes == null || bytes.length <= 0)
+        {
+            return null;
+        }
+        String str = new String(bytes, DEFAULT_CHARSET);
+
+        return JSON.parseObject(str, clazz);
+    }
+
+    public void setObjectMapper(ObjectMapper objectMapper)
+    {
+        Assert.notNull(objectMapper, "'objectMapper' must not be null");
+        this.objectMapper = objectMapper;
+    }
+
+    protected JavaType getJavaType(Class<?> clazz)
+    {
+        return TypeFactory.defaultInstance().constructType(clazz);
+    }
+}

+ 59 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/FilterConfig.java

@@ -0,0 +1,59 @@
+package com.fs.framework.config;
+
+import com.fs.common.filter.RepeatableFilter;
+import com.fs.common.filter.XssFilter;
+import com.fs.common.utils.StringUtils;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.boot.web.servlet.FilterRegistrationBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import javax.servlet.DispatcherType;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Filter配置
+ *
+
+ */
+@Configuration
+@ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
+public class FilterConfig
+{
+    @Value("${xss.excludes}")
+    private String excludes;
+
+    @Value("${xss.urlPatterns}")
+    private String urlPatterns;
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @Bean
+    public FilterRegistrationBean xssFilterRegistration()
+    {
+        FilterRegistrationBean registration = new FilterRegistrationBean();
+        registration.setDispatcherTypes(DispatcherType.REQUEST);
+        registration.setFilter(new XssFilter());
+        registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
+        registration.setName("xssFilter");
+        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
+        Map<String, String> initParameters = new HashMap<String, String>();
+        initParameters.put("excludes", excludes);
+        registration.setInitParameters(initParameters);
+        return registration;
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @Bean
+    public FilterRegistrationBean someFilterRegistration()
+    {
+        FilterRegistrationBean registration = new FilterRegistrationBean();
+        registration.setFilter(new RepeatableFilter());
+        registration.addUrlPatterns("/*");
+        registration.setName("repeatableFilter");
+        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
+        return registration;
+    }
+
+}

+ 76 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/KaptchaTextCreator.java

@@ -0,0 +1,76 @@
+package com.fs.framework.config;
+
+import com.google.code.kaptcha.text.impl.DefaultTextCreator;
+
+import java.util.Random;
+
+/**
+ * 验证码文本生成器
+ * 
+
+ */
+public class KaptchaTextCreator extends DefaultTextCreator
+{
+    private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");
+
+    @Override
+    public String getText()
+    {
+        Integer result = 0;
+        Random random = new Random();
+        int x = random.nextInt(10);
+        int y = random.nextInt(10);
+        StringBuilder suChinese = new StringBuilder();
+        int randomoperands = (int) Math.round(Math.random() * 2);
+        if (randomoperands == 0)
+        {
+            result = x * y;
+            suChinese.append(CNUMBERS[x]);
+            suChinese.append("*");
+            suChinese.append(CNUMBERS[y]);
+        }
+        else if (randomoperands == 1)
+        {
+            if (!(x == 0) && y % x == 0)
+            {
+                result = y / x;
+                suChinese.append(CNUMBERS[y]);
+                suChinese.append("/");
+                suChinese.append(CNUMBERS[x]);
+            }
+            else
+            {
+                result = x + y;
+                suChinese.append(CNUMBERS[x]);
+                suChinese.append("+");
+                suChinese.append(CNUMBERS[y]);
+            }
+        }
+        else if (randomoperands == 2)
+        {
+            if (x >= y)
+            {
+                result = x - y;
+                suChinese.append(CNUMBERS[x]);
+                suChinese.append("-");
+                suChinese.append(CNUMBERS[y]);
+            }
+            else
+            {
+                result = y - x;
+                suChinese.append(CNUMBERS[y]);
+                suChinese.append("-");
+                suChinese.append(CNUMBERS[x]);
+            }
+        }
+        else
+        {
+            result = x + y;
+            suChinese.append(CNUMBERS[x]);
+            suChinese.append("+");
+            suChinese.append(CNUMBERS[y]);
+        }
+        suChinese.append("=?@" + result);
+        return suChinese.toString();
+    }
+}

+ 150 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/MyBatisConfig.java

@@ -0,0 +1,150 @@
+package com.fs.framework.config;
+
+import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
+import com.fs.common.utils.StringUtils;
+import org.apache.ibatis.io.VFS;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.mybatis.spring.SqlSessionFactoryBean;
+import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.env.Environment;
+import org.springframework.core.io.DefaultResourceLoader;
+import org.springframework.core.io.Resource;
+import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
+import org.springframework.core.io.support.ResourcePatternResolver;
+import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
+import org.springframework.core.type.classreading.MetadataReader;
+import org.springframework.core.type.classreading.MetadataReaderFactory;
+import org.springframework.util.ClassUtils;
+
+import javax.sql.DataSource;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+
+/**
+ * Mybatis支持*匹配扫描包
+ * 
+
+ */
+@Configuration
+public class MyBatisConfig
+{
+    @Autowired
+    private Environment env;
+
+    static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
+
+    public static String setTypeAliasesPackage(String typeAliasesPackage)
+    {
+        ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver();
+        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
+        List<String> allResult = new ArrayList<String>();
+        try
+        {
+            for (String aliasesPackage : typeAliasesPackage.split(","))
+            {
+                List<String> result = new ArrayList<String>();
+                aliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+                        + ClassUtils.convertClassNameToResourcePath(aliasesPackage.trim()) + "/" + DEFAULT_RESOURCE_PATTERN;
+                Resource[] resources = resolver.getResources(aliasesPackage);
+                if (resources != null && resources.length > 0)
+                {
+                    MetadataReader metadataReader = null;
+                    for (Resource resource : resources)
+                    {
+                        if (resource.isReadable())
+                        {
+                            metadataReader = metadataReaderFactory.getMetadataReader(resource);
+                            try
+                            {
+                                result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
+                            }
+                            catch (ClassNotFoundException e)
+                            {
+                                e.printStackTrace();
+                            }
+                        }
+                    }
+                }
+                if (result.size() > 0)
+                {
+                    HashSet<String> hashResult = new HashSet<String>(result);
+                    allResult.addAll(hashResult);
+                }
+            }
+            if (allResult.size() > 0)
+            {
+                typeAliasesPackage = String.join(",", (String[]) allResult.toArray(new String[0]));
+            }
+            else
+            {
+                throw new RuntimeException("mybatis typeAliasesPackage 路径扫描错误,参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包");
+            }
+        }
+        catch (IOException e)
+        {
+            e.printStackTrace();
+        }
+        return typeAliasesPackage;
+    }
+
+    public Resource[] resolveMapperLocations(String[] mapperLocations)
+    {
+        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
+        List<Resource> resources = new ArrayList<Resource>();
+        if (mapperLocations != null)
+        {
+            for (String mapperLocation : mapperLocations)
+            {
+                try
+                {
+                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
+                    resources.addAll(Arrays.asList(mappers));
+                }
+                catch (IOException e)
+                {
+                    // ignore
+                }
+            }
+        }
+        return resources.toArray(new Resource[resources.size()]);
+    }
+
+//    @Bean
+//    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception
+//    {
+//        String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage");
+//        String mapperLocations = env.getProperty("mybatis.mapperLocations");
+//        String configLocation = env.getProperty("mybatis.configLocation");
+//        typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage);
+//        VFS.addImplClass(SpringBootVFS.class);
+//
+//        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
+//        sessionFactory.setDataSource(dataSource);
+//        sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
+//        sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ",")));
+//        sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
+//        return sessionFactory.getObject();
+//    }
+    @Bean
+    public SqlSessionFactory sqlSessionFactorys(DataSource dataSource) throws Exception
+    {
+        String typeAliasesPackage = env.getProperty("mybatis-plus.typeAliasesPackage");
+        String mapperLocations = env.getProperty("mybatis-plus.mapperLocations");
+        String configLocation = env.getProperty("mybatis-plus.configLocation");
+        typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage);
+        VFS.addImplClass(SpringBootVFS.class);
+
+        final MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
+        sessionFactory.setDataSource(dataSource);
+        sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
+        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
+        sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
+        return sessionFactory.getObject();
+    }
+}

+ 121 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/RedisConfig.java

@@ -0,0 +1,121 @@
+package com.fs.framework.config;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
+import org.springframework.cache.annotation.CachingConfigurerSupport;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.script.DefaultRedisScript;
+import org.springframework.data.redis.serializer.GenericToStringSerializer;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+/**
+ * redis配置
+ *
+
+ */
+@Configuration
+@EnableCaching
+public class RedisConfig extends CachingConfigurerSupport
+{
+    @Bean
+    @SuppressWarnings(value = { "unchecked", "rawtypes" })
+    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
+    {
+        RedisTemplate<Object, Object> template = new RedisTemplate<>();
+        template.setConnectionFactory(connectionFactory);
+
+        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
+
+        ObjectMapper mapper = new ObjectMapper();
+        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
+        serializer.setObjectMapper(mapper);
+
+        // 使用StringRedisSerializer来序列化和反序列化redis的key值
+        template.setKeySerializer(new StringRedisSerializer());
+        template.setValueSerializer(serializer);
+
+        // Hash的key也采用StringRedisSerializer的序列化方式
+        template.setHashKeySerializer(new StringRedisSerializer());
+        template.setHashValueSerializer(serializer);
+
+        template.afterPropertiesSet();
+        return template;
+    }
+    @Bean
+    public RedisTemplate<String, Boolean> redisTemplateForBoolean(RedisConnectionFactory connectionFactory) {
+        RedisTemplate<String, Boolean> template = new RedisTemplate<>();
+        template.setConnectionFactory(connectionFactory);
+
+        // 使用StringRedisSerializer来序列化和反序列化redis的key值
+        template.setKeySerializer(new StringRedisSerializer());
+        template.setValueSerializer(new GenericToStringSerializer<>(Boolean.class));
+
+        // Hash的key也采用StringRedisSerializer的序列化方式
+        template.setHashKeySerializer(new StringRedisSerializer());
+        template.setHashValueSerializer(new GenericToStringSerializer<>(Boolean.class));
+
+        template.afterPropertiesSet();
+        return template;
+    }
+
+    @Bean
+    @SuppressWarnings(value = { "unchecked", "rawtypes" })
+    public RedisTemplate<String, Object> redisTemplateForObject(RedisConnectionFactory connectionFactory) {
+        RedisTemplate<String, Object> template = new RedisTemplate<>();
+        template.setConnectionFactory(connectionFactory);
+
+        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
+
+        ObjectMapper mapper = new ObjectMapper();
+        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
+        serializer.setObjectMapper(mapper);
+
+        // 使用StringRedisSerializer来序列化和反序列化redis的key值
+        template.setKeySerializer(new StringRedisSerializer());
+        template.setValueSerializer(serializer);
+
+        // Hash的key也采用StringRedisSerializer的序列化方式
+        template.setHashKeySerializer(new StringRedisSerializer());
+        template.setHashValueSerializer(serializer);
+
+        template.afterPropertiesSet();
+        return template;
+    }
+
+    @Bean
+    public DefaultRedisScript<Long> limitScript()
+    {
+        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
+        redisScript.setScriptText(limitScriptText());
+        redisScript.setResultType(Long.class);
+        return redisScript;
+    }
+
+    /**
+     * 限流脚本
+     */
+    private String limitScriptText()
+    {
+        return "local key = KEYS[1]\n" +
+                "local count = tonumber(ARGV[1])\n" +
+                "local time = tonumber(ARGV[2])\n" +
+                "local current = redis.call('get', key);\n" +
+                "if current and tonumber(current) > count then\n" +
+                "    return current;\n" +
+                "end\n" +
+                "current = redis.call('incr', key)\n" +
+                "if tonumber(current) == 1 then\n" +
+                "    redis.call('expire', key, time)\n" +
+                "end\n" +
+                "return current;";
+    }
+}

+ 76 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/ResourcesConfig.java

@@ -0,0 +1,76 @@
+package com.fs.framework.config;
+
+import com.fs.common.config.FSConfig;
+import com.fs.common.constant.Constants;
+import com.fs.framework.interceptor.RepeatSubmitInterceptor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.format.FormatterRegistry;
+import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CorsFilter;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+import java.time.format.DateTimeFormatter;
+
+/**
+ * 通用配置
+ *
+
+ */
+@Configuration
+public class ResourcesConfig implements WebMvcConfigurer
+{
+    @Autowired
+    private RepeatSubmitInterceptor repeatSubmitInterceptor;
+
+    @Override
+    public void addResourceHandlers(ResourceHandlerRegistry registry)
+    {
+        /** 本地文件上传路径 */
+        registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + FSConfig.getProfile() + "/");
+
+        /** swagger配置 */
+        registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
+    }
+
+    /**
+     * 自定义拦截规则
+     */
+    @Override
+    public void addInterceptors(InterceptorRegistry registry)
+    {
+        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
+    }
+
+    /**
+     * 跨域配置
+     */
+    @Bean
+    public CorsFilter corsFilter()
+    {
+        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+        CorsConfiguration config = new CorsConfiguration();
+        config.setAllowCredentials(true);
+        // 设置访问源地址
+        config.addAllowedOrigin("*");
+        // 设置访问源请求头
+        config.addAllowedHeader("*");
+        // 设置访问源请求方法
+        config.addAllowedMethod("*");
+        // 对接口配置跨域设置
+        source.registerCorsConfiguration("/**", config);
+        return new CorsFilter(source);
+    }
+
+    @Override
+    public void addFormatters(FormatterRegistry registry) {
+        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
+        registrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd")); // 统一日期格式
+        registrar.registerFormatters(registry);
+    }
+}

+ 11 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/RetryConfig.java

@@ -0,0 +1,11 @@
+package com.fs.framework.config;
+
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.retry.annotation.EnableRetry;
+
+@Configuration
+@EnableRetry
+public class RetryConfig {
+
+}

+ 158 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/SecurityConfig.java

@@ -0,0 +1,158 @@
+package com.fs.framework.config;
+
+
+import com.fs.framework.security.filter.JwtAuthenticationTokenFilter;
+import com.fs.framework.security.handle.AuthenticationEntryPointImpl;
+import com.fs.framework.security.handle.LogoutSuccessHandlerImpl;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+import org.springframework.security.web.authentication.logout.LogoutFilter;
+import org.springframework.web.filter.CorsFilter;
+
+/**
+ * spring security配置
+ *
+
+ */
+@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
+public class SecurityConfig extends WebSecurityConfigurerAdapter
+{
+    /**
+     * 自定义用户认证逻辑
+     */
+    @Autowired
+    private UserDetailsService userDetailsService;
+
+    /**
+     * 认证失败处理类
+     */
+    @Autowired
+    private AuthenticationEntryPointImpl unauthorizedHandler;
+
+    /**
+     * 退出处理类
+     */
+    @Autowired
+    private LogoutSuccessHandlerImpl logoutSuccessHandler;
+
+    /**
+     * token认证过滤器
+     */
+    @Autowired
+    private JwtAuthenticationTokenFilter authenticationTokenFilter;
+
+    /**
+     * 跨域过滤器
+     */
+    @Autowired
+    private CorsFilter corsFilter;
+
+    /**
+     * 解决 无法直接注入 AuthenticationManager
+     *
+     * @return
+     * @throws Exception
+     */
+    @Bean
+    @Override
+    public AuthenticationManager authenticationManagerBean() throws Exception
+    {
+        return super.authenticationManagerBean();
+    }
+
+    /**
+     * anyRequest          |   匹配所有请求路径
+     * access              |   SpringEl表达式结果为true时可以访问
+     * anonymous           |   匿名可以访问
+     * denyAll             |   用户不能访问
+     * fullyAuthenticated  |   用户完全认证可以访问(非remember-me下自动登录)
+     * hasAnyAuthority     |   如果有参数,参数表示权限,则其中任何一个权限可以访问
+     * hasAnyRole          |   如果有参数,参数表示角色,则其中任何一个角色可以访问
+     * hasAuthority        |   如果有参数,参数表示权限,则其权限可以访问
+     * hasIpAddress        |   如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
+     * hasRole             |   如果有参数,参数表示角色,则其角色可以访问
+     * permitAll           |   用户可以任意访问
+     * rememberMe          |   允许通过remember-me登录的用户访问
+     * authenticated       |   用户登录后可访问
+     */
+    @Override
+    protected void configure(HttpSecurity httpSecurity) throws Exception
+    {
+        httpSecurity
+                // CSRF禁用,因为不使用session
+                .csrf().disable()
+                // 认证失败处理类
+                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
+                // 基于token,所以不需要session
+                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
+                // 过滤请求
+                .authorizeRequests()
+                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
+                .antMatchers("/chat/upload/**","/login", "/register", "/captchaImage").anonymous()
+                .antMatchers(
+                        HttpMethod.GET,
+                        "/",
+                        "/*.html",
+                        "/**/*.html",
+                        "/**/*.css",
+                        "/**/*.js",
+                        "/profile/**"
+                ).permitAll()
+                .antMatchers("**/errorLogUpload").anonymous()
+                .antMatchers("**").anonymous()
+                .antMatchers("/qw/getJsapiTicket/**").anonymous()
+                .antMatchers("/msg/**").anonymous()
+                .antMatchers("/msg/**/**").anonymous()
+                .antMatchers("/msg").anonymous()
+                .antMatchers("/app/common/**").anonymous()
+                .antMatchers("/common/getId**").anonymous()
+                .antMatchers("/common/uploadOSS**").anonymous()
+                .antMatchers("/common/uploadWang**").anonymous()
+                .antMatchers("/common/download**").anonymous()
+                .antMatchers("/common/download/resource**").anonymous()
+                .antMatchers("/swagger-ui.html").anonymous()
+                .antMatchers("/swagger-resources/**").anonymous()
+                .antMatchers("/webjars/**").anonymous()
+                .antMatchers("/*/api-docs").anonymous()
+                .antMatchers("/druid/**").anonymous()
+                .antMatchers("/qw/data/**").anonymous()
+                // 除上面外的所有请求全部需要鉴权认证
+                .anyRequest().authenticated()
+                .and()
+                .headers().frameOptions().disable();
+        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
+        // 添加JWT filter
+        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
+        // 添加CORS filter
+        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
+        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
+    }
+
+    /**
+     * 强散列哈希加密实现
+     */
+    @Bean
+    public BCryptPasswordEncoder bCryptPasswordEncoder()
+    {
+        return new BCryptPasswordEncoder();
+    }
+
+    /**
+     * 身份认证接口
+     */
+    @Override
+    protected void configure(AuthenticationManagerBuilder auth) throws Exception
+    {
+        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
+    }
+}

+ 33 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/ServerConfig.java

@@ -0,0 +1,33 @@
+package com.fs.framework.config;
+
+import com.fs.common.utils.ServletUtils;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * 服务相关配置
+ *
+
+ */
+@Component
+public class ServerConfig
+{
+    /**
+     * 获取完整的请求路径,包括:域名,端口,上下文访问路径
+     *
+     * @return 服务地址
+     */
+    public String getUrl()
+    {
+        HttpServletRequest request = ServletUtils.getRequest();
+        return getDomain(request);
+    }
+
+    public static String getDomain(HttpServletRequest request)
+    {
+        StringBuffer url = request.getRequestURL();
+        String contextPath = request.getServletContext().getContextPath();
+        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
+    }
+}

+ 121 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/SwaggerConfig.java

@@ -0,0 +1,121 @@
+package com.fs.framework.config;
+
+import com.fs.common.config.FSConfig;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.models.auth.In;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import springfox.documentation.builders.ApiInfoBuilder;
+import springfox.documentation.builders.PathSelectors;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.service.*;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spi.service.contexts.SecurityContext;
+import springfox.documentation.spring.web.plugins.Docket;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Swagger2的接口配置
+ * 
+
+ */
+@Configuration
+public class SwaggerConfig
+{
+    /** 系统基础配置 */
+    @Autowired
+    private FSConfig fsConfig;
+
+    /** 是否开启swagger */
+    @Value("${swagger.enabled}")
+    private boolean enabled;
+
+    /** 设置请求的统一前缀 */
+    @Value("${swagger.pathMapping}")
+    private String pathMapping;
+
+    /**
+     * 创建API
+     */
+    @Bean
+    public Docket createRestApi()
+    {
+        return new Docket(DocumentationType.SWAGGER_2)
+                // 是否启用Swagger
+                .enable(enabled)
+                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
+                .apiInfo(apiInfo())
+                // 设置哪些接口暴露给Swagger展示
+                .select()
+                // 扫描所有有注解的api,用这种方式更灵活
+                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
+                // 扫描指定包中的swagger注解
+                // .apis(RequestHandlerSelectors.basePackage("com.fs.project.tool.swagger"))
+                // 扫描所有 .apis(RequestHandlerSelectors.any())
+                .paths(PathSelectors.any())
+                .build()
+                /* 设置安全模式,swagger可以设置访问token */
+                .securitySchemes(securitySchemes())
+                .securityContexts(securityContexts())
+                .pathMapping(pathMapping);
+    }
+
+    /**
+     * 安全模式,这里指定token通过Authorization头请求头传递
+     */
+    private List<ApiKey> securitySchemes()
+    {
+        List<ApiKey> apiKeyList = new ArrayList<ApiKey>();
+        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
+        return apiKeyList;
+    }
+
+    /**
+     * 安全上下文
+     */
+    private List<SecurityContext> securityContexts()
+    {
+        List<SecurityContext> securityContexts = new ArrayList<>();
+        securityContexts.add(
+                SecurityContext.builder()
+                        .securityReferences(defaultAuth())
+                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
+                        .build());
+        return securityContexts;
+    }
+
+    /**
+     * 默认的安全上引用
+     */
+    private List<SecurityReference> defaultAuth()
+    {
+        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
+        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
+        authorizationScopes[0] = authorizationScope;
+        List<SecurityReference> securityReferences = new ArrayList<>();
+        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
+        return securityReferences;
+    }
+
+    /**
+     * 添加摘要信息
+     */
+    private ApiInfo apiInfo()
+    {
+        // 用ApiInfoBuilder进行定制
+        return new ApiInfoBuilder()
+                // 设置标题
+                .title("标题:FS管理系统_接口文档")
+                // 描述
+                .description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...")
+                // 作者信息
+                .contact(new Contact(fsConfig.getName(), null, null))
+                // 版本
+                .version("版本号:" + fsConfig.getVersion())
+                .build();
+    }
+}

+ 102 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/ThreadPoolConfig.java

@@ -0,0 +1,102 @@
+package com.fs.framework.config;
+
+import com.fs.common.utils.Threads;
+import org.apache.commons.lang3.concurrent.BasicThreadFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.scheduling.annotation.EnableAsync;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadPoolExecutor;
+
+/**
+ * 线程池配置
+ *
+
+ **/
+@Configuration
+@EnableAsync
+public class ThreadPoolConfig
+{
+    // 核心线程池大小
+    private int corePoolSize = 50;
+
+    // 最大可创建的线程数
+    private int maxPoolSize = 300;
+
+    // 队列最大长度
+    private int queueCapacity = 1000;
+
+    // 线程池维护线程所允许的空闲时间
+    private int keepAliveSeconds = 300;
+
+    @Bean(name = "threadPoolTaskExecutor")
+    public ThreadPoolTaskExecutor threadPoolTaskExecutor()
+    {
+        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+        executor.setMaxPoolSize(maxPoolSize);
+        executor.setCorePoolSize(corePoolSize);
+        executor.setQueueCapacity(queueCapacity);
+        executor.setKeepAliveSeconds(keepAliveSeconds);
+        // 线程池对拒绝任务(无线程可用)的处理策略
+        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
+        return executor;
+    }
+
+    /**
+     * 执行周期性或定时任务
+     */
+    @Bean(name = "scheduledExecutorService")
+    protected ScheduledExecutorService scheduledExecutorService()
+    {
+        return new ScheduledThreadPoolExecutor(corePoolSize,
+                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build())
+        {
+            @Override
+            protected void afterExecute(Runnable r, Throwable t)
+            {
+                super.afterExecute(r, t);
+                Threads.printException(r, t);
+            }
+        };
+    }
+
+    @Bean(name = "sopTaskExecutor")
+    public Executor sopTaskExecutor() {
+        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+        executor.setCorePoolSize(16); // 根据需求调整
+        executor.setMaxPoolSize(32);  // 根据需求调整
+        executor.setQueueCapacity(800); // 根据需求调整
+        executor.setThreadNamePrefix("SopTask-");
+        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
+        executor.initialize();
+        return executor;
+    }
+
+    @Bean(name = "sopChatTaskExecutor")
+    public Executor batchInsertExecutor() {
+        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+        executor.setCorePoolSize(16);
+        executor.setMaxPoolSize(32);
+        executor.setQueueCapacity(800);
+        executor.setThreadNamePrefix("BatchInsert-");
+        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
+        executor.initialize();
+        return executor;
+    }
+
+    @Bean(name = "sopRatingExecutor")
+    public Executor sopRatingExecutor() {
+        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+        executor.setCorePoolSize(16); // 根据需求调整
+        executor.setMaxPoolSize(32);  // 根据需求调整
+        executor.setQueueCapacity(800); // 根据需求调整
+        executor.setThreadNamePrefix("SopRating-");
+        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
+        executor.initialize();
+        return executor;
+    }
+}

+ 77 - 0
fs-ipad-task/src/main/java/com/fs/framework/config/properties/DruidProperties.java

@@ -0,0 +1,77 @@
+package com.fs.framework.config.properties;
+
+import com.alibaba.druid.pool.DruidDataSource;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * druid 配置属性
+ *
+
+ */
+@Configuration
+public class DruidProperties
+{
+    @Value("${spring.datasource.mysql.druid.initialSize}")
+    private int initialSize;
+
+    @Value("${spring.datasource.mysql.druid.minIdle}")
+    private int minIdle;
+
+    @Value("${spring.datasource.mysql.druid.maxActive}")
+    private int maxActive;
+
+    @Value("${spring.datasource.mysql.druid.maxWait}")
+    private int maxWait;
+
+    @Value("${spring.datasource.mysql.druid.timeBetweenEvictionRunsMillis}")
+    private int timeBetweenEvictionRunsMillis;
+
+    @Value("${spring.datasource.mysql.druid.minEvictableIdleTimeMillis}")
+    private int minEvictableIdleTimeMillis;
+
+    @Value("${spring.datasource.mysql.druid.maxEvictableIdleTimeMillis}")
+    private int maxEvictableIdleTimeMillis;
+
+    @Value("${spring.datasource.mysql.druid.validationQuery}")
+    private String validationQuery;
+
+    @Value("${spring.datasource.mysql.druid.testWhileIdle}")
+    private boolean testWhileIdle;
+
+    @Value("${spring.datasource.mysql.druid.testOnBorrow}")
+    private boolean testOnBorrow;
+
+    @Value("${spring.datasource.mysql.druid.testOnReturn}")
+    private boolean testOnReturn;
+
+    public DruidDataSource dataSource(DruidDataSource datasource)
+    {
+        /** 配置初始化大小、最小、最大 */
+        datasource.setInitialSize(initialSize);
+        datasource.setMaxActive(maxActive);
+        datasource.setMinIdle(minIdle);
+
+        /** 配置获取连接等待超时的时间 */
+        datasource.setMaxWait(maxWait);
+
+        /** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */
+        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
+
+        /** 配置一个连接在池中最小、最大生存的时间,单位是毫秒 */
+        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
+        datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);
+
+        /**
+         * 用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
+         */
+        datasource.setValidationQuery(validationQuery);
+        /** 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 */
+        datasource.setTestWhileIdle(testWhileIdle);
+        /** 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */
+        datasource.setTestOnBorrow(testOnBorrow);
+        /** 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */
+        datasource.setTestOnReturn(testOnReturn);
+        return datasource;
+    }
+}

+ 27 - 0
fs-ipad-task/src/main/java/com/fs/framework/datasource/DynamicDataSource.java

@@ -0,0 +1,27 @@
+package com.fs.framework.datasource;
+
+import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
+
+import javax.sql.DataSource;
+import java.util.Map;
+
+/**
+ * 动态数据源
+ *
+
+ */
+public class DynamicDataSource extends AbstractRoutingDataSource
+{
+    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources)
+    {
+        super.setDefaultTargetDataSource(defaultTargetDataSource);
+        super.setTargetDataSources(targetDataSources);
+        super.afterPropertiesSet();
+    }
+
+    @Override
+    protected Object determineCurrentLookupKey()
+    {
+        return DynamicDataSourceContextHolder.getDataSourceType();
+    }
+}

+ 45 - 0
fs-ipad-task/src/main/java/com/fs/framework/datasource/DynamicDataSourceContextHolder.java

@@ -0,0 +1,45 @@
+package com.fs.framework.datasource;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * 数据源切换处理
+ *
+
+ */
+public class DynamicDataSourceContextHolder
+{
+    public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);
+
+    /**
+     * 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
+     *  所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
+     */
+    private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
+
+    /**
+     * 设置数据源的变量
+     */
+    public static void setDataSourceType(String dsType)
+    {
+//        log.info("切换到{}数据源", dsType);
+        CONTEXT_HOLDER.set(dsType);
+    }
+
+    /**
+     * 获得数据源的变量
+     */
+    public static String getDataSourceType()
+    {
+        return CONTEXT_HOLDER.get();
+    }
+
+    /**
+     * 清空数据源变量
+     */
+    public static void clearDataSourceType()
+    {
+        CONTEXT_HOLDER.remove();
+    }
+}

+ 115 - 0
fs-ipad-task/src/main/java/com/fs/framework/exception/GlobalExceptionHandler.java

@@ -0,0 +1,115 @@
+package com.fs.framework.exception;
+
+import com.fs.common.constant.HttpStatus;
+import com.fs.common.core.domain.AjaxResult;
+import com.fs.common.exception.DemoModeException;
+import com.fs.common.exception.ServiceException;
+import com.fs.common.utils.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.validation.BindException;
+import org.springframework.web.HttpRequestMethodNotSupportedException;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * 全局异常处理器
+ *
+
+ */
+@RestControllerAdvice
+public class GlobalExceptionHandler
+{
+    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
+
+    /**
+     * 权限校验异常
+     */
+    @ExceptionHandler(AccessDeniedException.class)
+    public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request)
+    {
+        String requestURI = request.getRequestURI();
+        log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
+        return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权");
+    }
+
+    /**
+     * 请求方式不支持
+     */
+    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
+    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
+            HttpServletRequest request)
+    {
+        String requestURI = request.getRequestURI();
+        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
+        return AjaxResult.error(e.getMessage());
+    }
+
+    /**
+     * 业务异常
+     */
+    @ExceptionHandler(ServiceException.class)
+    public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request)
+    {
+        log.error(e.getMessage(), e);
+        Integer code = e.getCode();
+        return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
+    }
+
+    /**
+     * 拦截未知的运行时异常
+     */
+    @ExceptionHandler(RuntimeException.class)
+    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request)
+    {
+        String requestURI = request.getRequestURI();
+        log.error("请求地址'{}',发生未知异常.", requestURI, e);
+        return AjaxResult.error(e.getMessage());
+    }
+
+    /**
+     * 系统异常
+     */
+    @ExceptionHandler(Exception.class)
+    public AjaxResult handleException(Exception e, HttpServletRequest request)
+    {
+        String requestURI = request.getRequestURI();
+        log.error("请求地址'{}',发生系统异常.", requestURI, e);
+        return AjaxResult.error(e.getMessage());
+    }
+
+    /**
+     * 自定义验证异常
+     */
+    @ExceptionHandler(BindException.class)
+    public AjaxResult handleBindException(BindException e)
+    {
+        log.error(e.getMessage(), e);
+        String message = e.getAllErrors().get(0).getDefaultMessage();
+        return AjaxResult.error(message);
+    }
+
+    /**
+     * 自定义验证异常
+     */
+    @ExceptionHandler(MethodArgumentNotValidException.class)
+    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
+    {
+        log.error(e.getMessage(), e);
+        String message = e.getBindingResult().getFieldError().getDefaultMessage();
+        return AjaxResult.error(message);
+    }
+
+    /**
+     * 演示模式异常
+     */
+    @ExceptionHandler(DemoModeException.class)
+    public AjaxResult handleDemoModeException(DemoModeException e)
+    {
+        return AjaxResult.error("演示模式,不允许操作");
+    }
+}

+ 56 - 0
fs-ipad-task/src/main/java/com/fs/framework/interceptor/RepeatSubmitInterceptor.java

@@ -0,0 +1,56 @@
+package com.fs.framework.interceptor;
+
+import com.alibaba.fastjson.JSONObject;
+import com.fs.common.annotation.RepeatSubmit;
+import com.fs.common.core.domain.AjaxResult;
+import com.fs.common.utils.ServletUtils;
+import org.springframework.stereotype.Component;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.lang.reflect.Method;
+
+/**
+ * 防止重复提交拦截器
+ *
+
+ */
+@Component
+public abstract class RepeatSubmitInterceptor extends HandlerInterceptorAdapter
+{
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
+    {
+        if (handler instanceof HandlerMethod)
+        {
+            HandlerMethod handlerMethod = (HandlerMethod) handler;
+            Method method = handlerMethod.getMethod();
+            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
+            if (annotation != null)
+            {
+                if (this.isRepeatSubmit(request))
+                {
+                    AjaxResult ajaxResult = AjaxResult.error("不允许重复提交,请稍后再试");
+                    ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
+                    return false;
+                }
+            }
+            return true;
+        }
+        else
+        {
+            return super.preHandle(request, response, handler);
+        }
+    }
+
+    /**
+     * 验证是否重复提交由子类实现具体的防重复提交的规则
+     *
+     * @param request
+     * @return
+     * @throws Exception
+     */
+    public abstract boolean isRepeatSubmit(HttpServletRequest request);
+}

+ 126 - 0
fs-ipad-task/src/main/java/com/fs/framework/interceptor/impl/SameUrlDataInterceptor.java

@@ -0,0 +1,126 @@
+package com.fs.framework.interceptor.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.fs.common.constant.Constants;
+import com.fs.common.core.redis.RedisCache;
+import com.fs.common.filter.RepeatedlyRequestWrapper;
+import com.fs.common.utils.StringUtils;
+import com.fs.common.utils.http.HttpHelper;
+import com.fs.framework.interceptor.RepeatSubmitInterceptor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * 判断请求url和数据是否和上一次相同,
+ * 如果和上次相同,则是重复提交表单。 有效时间为10秒内。
+ *
+
+ */
+@Component
+public class SameUrlDataInterceptor extends RepeatSubmitInterceptor
+{
+    public final String REPEAT_PARAMS = "repeatParams";
+
+    public final String REPEAT_TIME = "repeatTime";
+
+    // 令牌自定义标识
+    @Value("${token.header}")
+    private String header;
+
+    @Autowired
+    private RedisCache redisCache;
+
+    /**
+     * 间隔时间,单位:秒 默认10秒
+     *
+     * 两次相同参数的请求,如果间隔时间大于该参数,系统不会认定为重复提交的数据
+     */
+    private int intervalTime = 10;
+
+    public void setIntervalTime(int intervalTime)
+    {
+        this.intervalTime = intervalTime;
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public boolean isRepeatSubmit(HttpServletRequest request)
+    {
+        String nowParams = "";
+        if (request instanceof RepeatedlyRequestWrapper)
+        {
+            RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
+            nowParams = HttpHelper.getBodyString(repeatedlyRequest);
+        }
+
+        // body参数为空,获取Parameter的数据
+        if (StringUtils.isEmpty(nowParams))
+        {
+            nowParams = JSONObject.toJSONString(request.getParameterMap());
+        }
+        Map<String, Object> nowDataMap = new HashMap<String, Object>();
+        nowDataMap.put(REPEAT_PARAMS, nowParams);
+        nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());
+
+        // 请求地址(作为存放cache的key值)
+        String url = request.getRequestURI();
+
+        // 唯一值(没有消息头则使用请求地址)
+        String submitKey = request.getHeader(header);
+        if (StringUtils.isEmpty(submitKey))
+        {
+            submitKey = url;
+        }
+
+        // 唯一标识(指定key + 消息头)
+        String cacheRepeatKey = Constants.REPEAT_SUBMIT_KEY + submitKey;
+
+        Object sessionObj = redisCache.getCacheObject(cacheRepeatKey);
+        if (sessionObj != null)
+        {
+            Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
+            if (sessionMap.containsKey(url))
+            {
+                Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
+                if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap))
+                {
+                    return true;
+                }
+            }
+        }
+        Map<String, Object> cacheMap = new HashMap<String, Object>();
+        cacheMap.put(url, nowDataMap);
+        redisCache.setCacheObject(cacheRepeatKey, cacheMap, intervalTime, TimeUnit.SECONDS);
+        return false;
+    }
+
+    /**
+     * 判断参数是否相同
+     */
+    private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap)
+    {
+        String nowParams = (String) nowMap.get(REPEAT_PARAMS);
+        String preParams = (String) preMap.get(REPEAT_PARAMS);
+        return nowParams.equals(preParams);
+    }
+
+    /**
+     * 判断两次间隔时间
+     */
+    private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap)
+    {
+        long time1 = (Long) nowMap.get(REPEAT_TIME);
+        long time2 = (Long) preMap.get(REPEAT_TIME);
+        if ((time1 - time2) < (this.intervalTime * 1000))
+        {
+            return true;
+        }
+        return false;
+    }
+}

+ 56 - 0
fs-ipad-task/src/main/java/com/fs/framework/manager/AsyncManager.java

@@ -0,0 +1,56 @@
+package com.fs.framework.manager;
+
+import com.fs.common.utils.Threads;
+import com.fs.common.utils.spring.SpringUtils;
+
+import java.util.TimerTask;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * 异步任务管理器
+ * 
+ 
+ */
+public class AsyncManager
+{
+    /**
+     * 操作延迟10毫秒
+     */
+    private final int OPERATE_DELAY_TIME = 10;
+
+    /**
+     * 异步操作任务调度线程池
+     */
+    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
+
+    /**
+     * 单例模式
+     */
+    private AsyncManager(){}
+
+    private static AsyncManager me = new AsyncManager();
+
+    public static AsyncManager me()
+    {
+        return me;
+    }
+
+    /**
+     * 执行任务
+     * 
+     * @param task 任务
+     */
+    public void execute(TimerTask task)
+    {
+        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
+    }
+
+    /**
+     * 停止任务线程池
+     */
+    public void shutdown()
+    {
+        Threads.shutdownAndAwaitTermination(executor);
+    }
+}

+ 40 - 0
fs-ipad-task/src/main/java/com/fs/framework/manager/ShutdownManager.java

@@ -0,0 +1,40 @@
+package com.fs.framework.manager;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PreDestroy;
+
+/**
+ * 确保应用退出时能关闭后台线程
+ *
+ 
+ */
+@Component
+public class ShutdownManager
+{
+    private static final Logger logger = LoggerFactory.getLogger("sys-user");
+
+    @PreDestroy
+    public void destroy()
+    {
+        shutdownAsyncManager();
+    }
+
+    /**
+     * 停止异步执行任务
+     */
+    private void shutdownAsyncManager()
+    {
+        try
+        {
+            logger.info("====关闭后台任务任务线程池====");
+            AsyncManager.me().shutdown();
+        }
+        catch (Exception e)
+        {
+            logger.error(e.getMessage(), e);
+        }
+    }
+}

+ 106 - 0
fs-ipad-task/src/main/java/com/fs/framework/manager/factory/AsyncFactory.java

@@ -0,0 +1,106 @@
+package com.fs.framework.manager.factory;
+
+import com.fs.common.constant.Constants;
+import com.fs.common.utils.LogUtils;
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.ip.AddressUtils;
+import com.fs.common.utils.ip.IpUtils;
+import com.fs.common.utils.spring.SpringUtils;
+import com.fs.company.domain.CompanyLogininfor;
+import com.fs.company.domain.CompanyOperLog;
+import com.fs.company.service.ICompanyLogininforService;
+import com.fs.company.service.ICompanyOperLogService;
+import eu.bitwalker.useragentutils.UserAgent;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Date;
+import java.util.TimerTask;
+
+/**
+ * 异步工厂(产生任务用)
+ * 
+
+ */
+public class AsyncFactory
+{
+    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");
+
+    /**
+     * 记录登录信息
+     * 
+     * @param username 用户名
+     * @param status 状态
+     * @param message 消息
+     * @param args 列表
+     * @return 任务task
+     */
+    public static TimerTask recordLogininfor(final Long companyId,final String username, final String status, final String message,
+            final Object... args)
+    {
+        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
+        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
+        return new TimerTask()
+        {
+            @Override
+            public void run()
+            {
+                String address = AddressUtils.getRealAddressByIP(ip);
+                StringBuilder s = new StringBuilder();
+                s.append(LogUtils.getBlock(ip));
+                s.append(address);
+                s.append(LogUtils.getBlock(username));
+                s.append(LogUtils.getBlock(status));
+                s.append(LogUtils.getBlock(message));
+                // 打印信息到日志
+                sys_user_logger.info(s.toString(), args);
+                // 获取客户端操作系统
+                String os = userAgent.getOperatingSystem().getName();
+                // 获取客户端浏览器
+                String browser = userAgent.getBrowser().getName();
+                // 封装对象
+                CompanyLogininfor logininfor = new CompanyLogininfor();
+                logininfor.setCompanyId(companyId);
+                logininfor.setUserName(username);
+                logininfor.setIpaddr(ip);
+                logininfor.setLoginLocation(address);
+                logininfor.setBrowser(browser);
+                logininfor.setOs(os);
+                logininfor.setMsg(message);
+                // 日志状态
+                if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status))
+                {
+                    logininfor.setStatus(Constants.SUCCESS);
+                }
+                else if (Constants.LOGIN_FAIL.equals(status))
+                {
+                    logininfor.setStatus(Constants.FAIL);
+                }
+                logininfor.setLoginTime(new Date());
+                // 插入数据
+                SpringUtils.getBean(ICompanyLogininforService.class).insertCompanyLogininfor(logininfor);
+            }
+        };
+    }
+
+    /**
+     * 操作日志记录
+     * 
+     * @param operLog 操作日志信息
+     * @return 任务task
+     */
+    public static TimerTask recordOper(final CompanyOperLog operLog)
+    {
+        return new TimerTask()
+        {
+            @Override
+            public void run()
+            {
+                // 远程查询操作地点
+                operLog.setOperTime(new Date());
+                operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
+                SpringUtils.getBean(ICompanyOperLogService.class).insertCompanyOperLog(operLog);
+            }
+        };
+    }
+}

+ 69 - 0
fs-ipad-task/src/main/java/com/fs/framework/security/LoginBody.java

@@ -0,0 +1,69 @@
+package com.fs.framework.security;
+
+/**
+ * 用户登录对象
+ * 
+
+ */
+public class LoginBody
+{
+    /**
+     * 用户名
+     */
+    private String username;
+
+    /**
+     * 用户密码
+     */
+    private String password;
+
+    /**
+     * 验证码
+     */
+    private String code;
+
+    /**
+     * 唯一标识
+     */
+    private String uuid = "";
+
+    public String getUsername()
+    {
+        return username;
+    }
+
+    public void setUsername(String username)
+    {
+        this.username = username;
+    }
+
+    public String getPassword()
+    {
+        return password;
+    }
+
+    public void setPassword(String password)
+    {
+        this.password = password;
+    }
+
+    public String getCode()
+    {
+        return code;
+    }
+
+    public void setCode(String code)
+    {
+        this.code = code;
+    }
+
+    public String getUuid()
+    {
+        return uuid;
+    }
+
+    public void setUuid(String uuid)
+    {
+        this.uuid = uuid;
+    }
+}

+ 255 - 0
fs-ipad-task/src/main/java/com/fs/framework/security/LoginUser.java

@@ -0,0 +1,255 @@
+package com.fs.framework.security;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fs.company.domain.Company;
+import com.fs.company.domain.CompanyUser;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+
+import java.util.Collection;
+import java.util.Set;
+
+/**
+ * 登录用户身份权限
+ * 
+
+ */
+public class LoginUser implements UserDetails
+{
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 用户唯一标识
+     */
+    private String token;
+
+    /**
+     * 登录时间
+     */
+    private Long loginTime;
+
+    /**
+     * 过期时间
+     */
+    private Long expireTime;
+
+    /**
+     * 登录IP地址
+     */
+    private String ipaddr;
+
+    /**
+     * 登录地点
+     */
+    private String loginLocation;
+
+    /**
+     * 浏览器类型
+     */
+    private String browser;
+
+    /**
+     * 操作系统
+     */
+    private String os;
+
+
+
+    /**
+     * 权限列表
+     */
+    private Set<String> permissions;
+
+    /**
+     * 用户信息
+     */
+    private CompanyUser user;
+
+    private Company company;
+
+
+
+    public static long getSerialVersionUID() {
+        return serialVersionUID;
+    }
+
+
+
+    public Company getCompany() {
+        return company;
+    }
+
+    public void setCompany(Company company) {
+        this.company = company;
+    }
+
+    public String getToken()
+    {
+        return token;
+    }
+
+    public void setToken(String token)
+    {
+        this.token = token;
+    }
+
+    public LoginUser()
+    {
+    }
+    public LoginUser(CompanyUser user, Set<String> permissions, Company company)
+    {
+        this.user = user;
+        this.permissions = permissions;
+        this.company=company;
+    }
+    public LoginUser(CompanyUser user, Set<String> permissions)
+    {
+        this.user = user;
+        this.permissions = permissions;
+    }
+
+    @JsonIgnore
+    @Override
+    public String getPassword()
+    {
+        return user.getPassword();
+    }
+
+    @Override
+    public String getUsername()
+    {
+        return user.getUserName();
+    }
+
+    /**
+     * 账户是否未过期,过期无法验证
+     */
+    @JsonIgnore
+    @Override
+    public boolean isAccountNonExpired()
+    {
+        return true;
+    }
+
+    /**
+     * 指定用户是否解锁,锁定的用户无法进行身份验证
+     * 
+     * @return
+     */
+    @JsonIgnore
+    @Override
+    public boolean isAccountNonLocked()
+    {
+        return true;
+    }
+
+    /**
+     * 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
+     * 
+     * @return
+     */
+    @JsonIgnore
+    @Override
+    public boolean isCredentialsNonExpired()
+    {
+        return true;
+    }
+
+    /**
+     * 是否可用 ,禁用的用户不能身份验证
+     * 
+     * @return
+     */
+    @JsonIgnore
+    @Override
+    public boolean isEnabled()
+    {
+        return true;
+    }
+
+    public Long getLoginTime()
+    {
+        return loginTime;
+    }
+
+    public void setLoginTime(Long loginTime)
+    {
+        this.loginTime = loginTime;
+    }
+
+    public String getIpaddr()
+    {
+        return ipaddr;
+    }
+
+    public void setIpaddr(String ipaddr)
+    {
+        this.ipaddr = ipaddr;
+    }
+
+    public String getLoginLocation()
+    {
+        return loginLocation;
+    }
+
+    public void setLoginLocation(String loginLocation)
+    {
+        this.loginLocation = loginLocation;
+    }
+
+    public String getBrowser()
+    {
+        return browser;
+    }
+
+    public void setBrowser(String browser)
+    {
+        this.browser = browser;
+    }
+
+    public String getOs()
+    {
+        return os;
+    }
+
+    public void setOs(String os)
+    {
+        this.os = os;
+    }
+
+    public Long getExpireTime()
+    {
+        return expireTime;
+    }
+
+    public void setExpireTime(Long expireTime)
+    {
+        this.expireTime = expireTime;
+    }
+
+    public Set<String> getPermissions()
+    {
+        return permissions;
+    }
+
+    public void setPermissions(Set<String> permissions)
+    {
+        this.permissions = permissions;
+    }
+
+    public CompanyUser getUser()
+    {
+        return user;
+    }
+
+    public void setUser(CompanyUser user)
+    {
+        this.user = user;
+    }
+
+    @Override
+    public Collection<? extends GrantedAuthority> getAuthorities()
+    {
+        return null;
+    }
+}

+ 89 - 0
fs-ipad-task/src/main/java/com/fs/framework/security/SecurityUtils.java

@@ -0,0 +1,89 @@
+package com.fs.framework.security;
+
+import com.fs.common.constant.HttpStatus;
+import com.fs.common.exception.CustomException;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+
+/**
+ * 安全服务工具类
+ * 
+
+ */
+public class SecurityUtils
+{
+    /**
+     * 获取用户账户
+     **/
+    public static String getUsername()
+    {
+        try
+        {
+            return getLoginUser().getUsername();
+        }
+        catch (Exception e)
+        {
+            throw new CustomException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
+        }
+    }
+
+    /**
+     * 获取用户
+     **/
+    public static LoginUser getLoginUser()
+    {
+        try
+        {
+            return (LoginUser) getAuthentication().getPrincipal();
+        }
+        catch (Exception e)
+        {
+            throw new CustomException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
+        }
+    }
+
+    /**
+     * 获取Authentication
+     */
+    public static Authentication getAuthentication()
+    {
+        return SecurityContextHolder.getContext().getAuthentication();
+    }
+
+    /**
+     * 生成BCryptPasswordEncoder密码
+     *
+     * @param password 密码
+     * @return 加密字符串
+     */
+    public static String encryptPassword(String password)
+    {
+        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
+        return passwordEncoder.encode(password);
+    }
+
+    /**
+     * 判断密码是否相同
+     *
+     * @param rawPassword 真实密码
+     * @param encodedPassword 加密后字符
+     * @return 结果
+     */
+    public static boolean matchesPassword(String rawPassword, String encodedPassword)
+    {
+        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
+        return passwordEncoder.matches(rawPassword, encodedPassword);
+    }
+
+    /**
+     * 是否为管理员
+     * 
+     * @param userId 用户ID
+     * @return 结果
+     */
+    public static boolean isAdmin(Long userId)
+    {
+        return userId != null && 1L == userId;
+    }
+}

+ 47 - 0
fs-ipad-task/src/main/java/com/fs/framework/security/filter/JwtAuthenticationTokenFilter.java

@@ -0,0 +1,47 @@
+package com.fs.framework.security.filter;
+
+import com.fs.common.core.redis.RedisCache;
+import com.fs.common.utils.StringUtils;
+import com.fs.framework.security.LoginUser;
+import com.fs.framework.security.SecurityUtils;
+import com.fs.framework.service.TokenService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * token过滤器 验证token有效性
+ *
+
+ */
+@Component
+public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
+{
+    @Autowired
+    private TokenService tokenService;
+    @Autowired
+    private RedisCache redisCache;
+    @Override
+    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
+            throws ServletException, IOException
+    {
+        LoginUser loginUser = tokenService.getLoginUser(request);
+        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
+        {
+            tokenService.verifyToken(loginUser);
+            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
+            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
+            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
+        }
+        chain.doFilter(request, response);
+    }
+}

+ 35 - 0
fs-ipad-task/src/main/java/com/fs/framework/security/handle/AuthenticationEntryPointImpl.java

@@ -0,0 +1,35 @@
+package com.fs.framework.security.handle;
+
+import com.alibaba.fastjson.JSON;
+import com.fs.common.constant.HttpStatus;
+import com.fs.common.core.domain.AjaxResult;
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.StringUtils;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.AuthenticationEntryPoint;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.Serializable;
+
+/**
+ * 认证失败处理类 返回未授权
+ * 
+ 
+ */
+@Component
+public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
+{
+    private static final long serialVersionUID = -8970718410437077606L;
+
+    @Override
+    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
+            throws IOException
+    {
+        int code = HttpStatus.UNAUTHORIZED;
+        String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI());
+        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
+    }
+}

+ 54 - 0
fs-ipad-task/src/main/java/com/fs/framework/security/handle/LogoutSuccessHandlerImpl.java

@@ -0,0 +1,54 @@
+package com.fs.framework.security.handle;
+
+import com.alibaba.fastjson.JSON;
+import com.fs.common.constant.Constants;
+import com.fs.common.constant.HttpStatus;
+import com.fs.common.core.domain.AjaxResult;
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.StringUtils;
+import com.fs.framework.manager.AsyncManager;
+import com.fs.framework.manager.factory.AsyncFactory;
+import com.fs.framework.security.LoginUser;
+import com.fs.framework.service.TokenService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * 自定义退出处理类 返回成功
+ *
+
+ */
+@Configuration
+public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
+{
+    @Autowired
+    private TokenService tokenService;
+
+    /**
+     * 退出处理
+     *
+     * @return
+     */
+    @Override
+    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
+            throws IOException, ServletException
+    {
+        LoginUser loginUser = tokenService.getLoginUser(request);
+        if (StringUtils.isNotNull(loginUser))
+        {
+            String userName = loginUser.getUsername();
+            // 删除用户缓存记录
+            tokenService.delLoginUser(loginUser.getToken());
+            // 记录用户退出日志
+            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginUser.getCompany().getCompanyId(),userName, Constants.LOGOUT, "退出成功"));
+        }
+        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")));
+    }
+}

+ 92 - 0
fs-ipad-task/src/main/java/com/fs/framework/service/CompanyLoginService.java

@@ -0,0 +1,92 @@
+package com.fs.framework.service;
+
+import com.fs.common.constant.Constants;
+import com.fs.common.core.redis.RedisCache;
+import com.fs.common.exception.ServiceException;
+import com.fs.common.exception.user.CaptchaException;
+import com.fs.common.exception.user.CaptchaExpireException;
+import com.fs.common.exception.user.UserPasswordNotMatchException;
+import com.fs.common.utils.MessageUtils;
+import com.fs.framework.manager.AsyncManager;
+import com.fs.framework.manager.factory.AsyncFactory;
+import com.fs.framework.security.LoginUser;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * 登录校验方法
+ *
+
+ */
+@Component
+public class CompanyLoginService
+{
+    @Autowired
+    private TokenService tokenService;
+
+    @Resource
+    private AuthenticationManager authenticationManager;
+
+    @Autowired
+    private RedisCache redisCache;
+
+    /**
+     * 登录验证
+     *
+     * @param username 用户名
+     * @param password 密码
+     * @param code 验证码
+     * @param uuid 唯一标识
+     * @return 结果
+     */
+    public String login(String username, String password, String code, String uuid)
+    {
+        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
+        String captcha = redisCache.getCacheObject(verifyKey);
+        redisCache.deleteObject(verifyKey);
+        if (captcha == null)
+        {
+            AsyncManager.me().execute(AsyncFactory.recordLogininfor(0l,username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
+            throw new CaptchaExpireException();
+        }
+        if (!code.equalsIgnoreCase(captcha))
+        {
+            AsyncManager.me().execute(AsyncFactory.recordLogininfor(0l,username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
+            throw new CaptchaException();
+        }
+        // 用户验证
+        Authentication authentication = null;
+        try
+        {
+            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
+            authentication = authenticationManager
+                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
+        }
+        catch (Exception e)
+        {
+            if (e instanceof BadCredentialsException)
+            {
+                AsyncManager.me().execute(AsyncFactory.recordLogininfor(0l,username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
+                throw new UserPasswordNotMatchException();
+            }
+            else
+            {
+                AsyncManager.me().execute(AsyncFactory.recordLogininfor(0l,username, Constants.LOGIN_FAIL, e.getMessage()));
+                throw new ServiceException(e.getMessage());
+            }
+        }
+        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
+        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginUser.getUser().getCompanyId(),username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
+        redisCache.setCacheObject("companyId:"+loginUser.getUser().getUserId(),loginUser.getUser().getCompanyId(),604800, TimeUnit.SECONDS);
+        // 生成token
+        return tokenService.createToken(loginUser);
+    }
+
+}

+ 66 - 0
fs-ipad-task/src/main/java/com/fs/framework/service/CompanyPermissionService.java

@@ -0,0 +1,66 @@
+package com.fs.framework.service;
+
+import com.fs.company.domain.CompanyUser;
+import com.fs.company.service.ICompanyMenuService;
+import com.fs.company.service.ICompanyRoleService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * 用户权限处理
+ * 
+ 
+ */
+@Component
+public class CompanyPermissionService
+{
+    @Autowired
+    private ICompanyRoleService roleService;
+    @Autowired
+    private ICompanyMenuService menuService;
+
+    /**
+     * 获取角色数据权限
+     * 
+     * @param user 用户信息
+     * @return 角色权限信息
+     */
+    public Set<String> getRolePermission(CompanyUser user)
+    {
+        Set<String> roles = new HashSet<String>();
+        // 管理员拥有所有权限
+        if (user.isAdmin())
+        {
+            roles.add("admin");
+        }
+        else
+        {
+            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
+        }
+        return roles;
+    }
+
+    /**
+     * 获取菜单数据权限
+     * 
+     * @param user 用户信息
+     * @return 菜单权限信息
+     */
+    public Set<String> getMenuPermission(CompanyUser user)
+    {
+        Set<String> perms = new HashSet<String>();
+        // 管理员拥有所有权限
+        if (user.isAdmin())
+        {
+            perms.add("*:*:*");
+        }
+        else
+        {
+            perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
+        }
+        return perms;
+    }
+}

+ 170 - 0
fs-ipad-task/src/main/java/com/fs/framework/service/PermissionService.java

@@ -0,0 +1,170 @@
+package com.fs.framework.service;
+
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.StringUtils;
+import com.fs.company.domain.CompanyRole;
+import com.fs.framework.security.LoginUser;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+
+import java.util.Set;
+
+/**
+ * 自定义权限实现,ss取自SpringSecurity首字母
+ */
+@Service("ss")
+public class PermissionService
+{
+    /** 所有权限标识 */
+    private static final String ALL_PERMISSION = "*:*:*";
+
+    /** 管理员角色权限标识 */
+    private static final String SUPER_ADMIN = "admin";
+
+    private static final String ROLE_DELIMETER = ",";
+
+    private static final String PERMISSION_DELIMETER = ",";
+
+    @Autowired
+    private TokenService tokenService;
+
+    /**
+     * 验证用户是否具备某权限
+     * 
+     * @param permission 权限字符串
+     * @return 用户是否具备某权限
+     */
+    public boolean hasPermi(String permission)
+    {
+        if (StringUtils.isEmpty(permission))
+        {
+            return false;
+        }
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions()))
+        {
+            return false;
+        }
+        return hasPermissions(loginUser.getPermissions(), permission);
+    }
+
+    /**
+     * 验证用户是否不具备某权限,与 hasPermi逻辑相反
+     *
+     * @param permission 权限字符串
+     * @return 用户是否不具备某权限
+     */
+    public boolean lacksPermi(String permission)
+    {
+        return hasPermi(permission) != true;
+    }
+
+    /**
+     * 验证用户是否具有以下任意一个权限
+     *
+     * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表
+     * @return 用户是否具有以下任意一个权限
+     */
+    public boolean hasAnyPermi(String permissions)
+    {
+        if (StringUtils.isEmpty(permissions))
+        {
+            return false;
+        }
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions()))
+        {
+            return false;
+        }
+        Set<String> authorities = loginUser.getPermissions();
+        for (String permission : permissions.split(PERMISSION_DELIMETER))
+        {
+            if (permission != null && hasPermissions(authorities, permission))
+            {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 判断用户是否拥有某个角色
+     * 
+     * @param role 角色字符串
+     * @return 用户是否具备某角色
+     */
+    public boolean hasRole(String role)
+    {
+        if (StringUtils.isEmpty(role))
+        {
+            return false;
+        }
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles()))
+        {
+            return false;
+        }
+        for (CompanyRole sysRole : loginUser.getUser().getRoles())
+        {
+            String roleKey = sysRole.getRoleKey();
+            if (SUPER_ADMIN.contains(roleKey) || roleKey.contains(StringUtils.trim(role)))
+            {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 验证用户是否不具备某角色,与 isRole逻辑相反。
+     *
+     * @param role 角色名称
+     * @return 用户是否不具备某角色
+     */
+    public boolean lacksRole(String role)
+    {
+        return hasRole(role) != true;
+    }
+
+    /**
+     * 验证用户是否具有以下任意一个角色
+     *
+     * @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表
+     * @return 用户是否具有以下任意一个角色
+     */
+    public boolean hasAnyRoles(String roles)
+    {
+        if (StringUtils.isEmpty(roles))
+        {
+            return false;
+        }
+        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
+        if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles()))
+        {
+            return false;
+        }
+        for (String role : roles.split(ROLE_DELIMETER))
+        {
+            if (hasRole(role))
+            {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 判断是否包含权限
+     * 
+     * @param permissions 权限列表
+     * @param permission 权限字符串
+     * @return 用户是否具备某权限
+     */
+    private boolean hasPermissions(Set<String> permissions, String permission)
+    {
+        return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
+    }
+
+
+}

+ 236 - 0
fs-ipad-task/src/main/java/com/fs/framework/service/TokenService.java

@@ -0,0 +1,236 @@
+package com.fs.framework.service;
+
+import com.fs.common.constant.Constants;
+import com.fs.common.core.redis.RedisCache;
+import com.fs.common.utils.ServletUtils;
+import com.fs.common.utils.StringUtils;
+import com.fs.common.utils.ip.AddressUtils;
+import com.fs.common.utils.ip.IpUtils;
+import com.fs.common.utils.uuid.IdUtils;
+import com.fs.framework.security.LoginUser;
+import eu.bitwalker.useragentutils.UserAgent;
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * token验证处理
+ *
+ 
+ */
+@Component
+public class TokenService
+{
+    // 令牌自定义标识
+    @Value("${token.header}")
+    private String header;
+
+    // 令牌秘钥
+    @Value("${token.secret}")
+    private String secret;
+
+    // 令牌有效期(默认30分钟)
+    @Value("${token.expireTime}")
+    private int expireTime;
+
+    protected static final long MILLIS_SECOND = 1000;
+
+    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
+
+    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 100000000000L;
+
+    @Autowired
+    private RedisCache redisCache;
+
+    /**
+     * 获取用户身份信息
+     *
+     * @return 用户信息
+     */
+    public LoginUser getLoginUser(HttpServletRequest request)
+    {
+        // 获取请求携带的令牌
+        String token = getToken(request);
+        if (StringUtils.isNotEmpty(token))
+        {
+            Claims claims = parseToken(token);
+            // 解析对应的权限以及用户信息
+            String uuid = (String) claims.get(Constants.COMPANY_LOGIN_USER_KEY);
+            String userKey = getTokenKey(uuid);
+            LoginUser user = redisCache.getCacheObject(userKey);
+            return user;
+        }
+        token=getUrlToken(request);
+        if (StringUtils.isNotEmpty(token))
+        {
+            Claims claims = parseToken(token);
+            // 解析对应的权限以及用户信息
+            String uuid = (String) claims.get(Constants.COMPANY_LOGIN_USER_KEY);
+            String userKey = getTokenKey(uuid);
+            LoginUser user = redisCache.getCacheObject(userKey);
+            return user;
+        }
+
+        return null;
+    }
+
+    /**
+     * 设置用户身份信息
+     */
+    public void setLoginUser(LoginUser loginUser)
+    {
+        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
+        {
+            refreshToken(loginUser);
+        }
+    }
+
+    /**
+     * 删除用户身份信息
+     */
+    public void delLoginUser(String token)
+    {
+        if (StringUtils.isNotEmpty(token))
+        {
+            String userKey = getTokenKey(token);
+            redisCache.deleteObject(userKey);
+        }
+    }
+
+    /**
+     * 创建令牌
+     *
+     * @param loginUser 用户信息
+     * @return 令牌
+     */
+    public String createToken(LoginUser loginUser)
+    {
+        String token = IdUtils.fastUUID();
+        loginUser.setToken(token);
+        setUserAgent(loginUser);
+        refreshToken(loginUser);
+
+        Map<String, Object> claims = new HashMap<>();
+        claims.put(Constants.COMPANY_LOGIN_USER_KEY, token);
+        return createToken(claims);
+    }
+
+    /**
+     * 验证令牌有效期,相差不足20分钟,自动刷新缓存
+     *
+     * @param loginUser
+     * @return 令牌
+     */
+    public void verifyToken(LoginUser loginUser)
+    {
+        long expireTime = loginUser.getExpireTime();
+        long currentTime = System.currentTimeMillis();
+        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
+        {
+            refreshToken(loginUser);
+        }
+    }
+
+    /**
+     * 刷新令牌有效期
+     *
+     * @param loginUser 登录信息
+     */
+    public void refreshToken(LoginUser loginUser)
+    {
+        loginUser.setLoginTime(System.currentTimeMillis());
+        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
+        // 根据uuid将loginUser缓存
+        String userKey = getTokenKey(loginUser.getToken());
+        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
+    }
+
+    /**
+     * 设置用户代理信息
+     *
+     * @param loginUser 登录信息
+     */
+    public void setUserAgent(LoginUser loginUser)
+    {
+        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
+        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
+        loginUser.setIpaddr(ip);
+        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
+        loginUser.setBrowser(userAgent.getBrowser().getName());
+        loginUser.setOs(userAgent.getOperatingSystem().getName());
+    }
+
+    /**
+     * 从数据声明生成令牌
+     *
+     * @param claims 数据声明
+     * @return 令牌
+     */
+    private String createToken(Map<String, Object> claims)
+    {
+        String token = Jwts.builder()
+                .setClaims(claims)
+                .signWith(SignatureAlgorithm.HS512, secret).compact();
+        return token;
+    }
+
+    /**
+     * 从令牌中获取数据声明
+     *
+     * @param token 令牌
+     * @return 数据声明
+     */
+    private Claims parseToken(String token)
+    {
+        return Jwts.parser()
+                .setSigningKey(secret)
+                .parseClaimsJws(token)
+                .getBody();
+    }
+
+    /**
+     * 从令牌中获取用户名
+     *
+     * @param token 令牌
+     * @return 用户名
+     */
+    public String getUsernameFromToken(String token)
+    {
+        Claims claims = parseToken(token);
+        return claims.getSubject();
+    }
+
+    /**
+     * 获取请求token
+     *
+     * @param request
+     * @return token
+     */
+    private String getToken(HttpServletRequest request)
+    {
+        String token = request.getHeader(header);
+        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
+        {
+            token = token.replace(Constants.TOKEN_PREFIX, "");
+        }
+        return token;
+    }
+    private String getUrlToken(HttpServletRequest request)
+    {
+        String token = request.getParameter("token");
+        return token;
+    }
+
+    private String getTokenKey(String uuid)
+    {
+        return Constants.COMPANY_LOGIN_TOKEN_KEY + uuid;
+    }
+}

+ 75 - 0
fs-ipad-task/src/main/java/com/fs/framework/service/UserDetailsServiceImpl.java

@@ -0,0 +1,75 @@
+package com.fs.framework.service;
+
+
+import com.fs.common.enums.UserStatus;
+import com.fs.common.exception.CustomException;
+import com.fs.common.utils.StringUtils;
+import com.fs.company.domain.Company;
+import com.fs.company.domain.CompanyUser;
+import com.fs.company.service.ICompanyService;
+import com.fs.company.service.ICompanyUserService;
+import com.fs.framework.security.LoginUser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.stereotype.Service;
+
+/**
+ * 用户验证处理
+ *
+ 
+ */
+@Service
+public class UserDetailsServiceImpl implements UserDetailsService
+{
+    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
+
+    @Autowired
+    private ICompanyUserService userService;
+
+    @Autowired
+    private CompanyPermissionService permissionService;
+
+    @Autowired
+    private ICompanyService companyService;
+
+
+
+
+    @Override
+    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
+    {
+
+
+        CompanyUser user = userService.selectUserByUserName(username);
+        if (StringUtils.isNull(user))
+        {
+            log.info("登录用户:{} 不存在.", username);
+            throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
+        }
+        Company company=companyService.selectCompanyById(user.getCompanyId()) ;
+        if(company==null||company.getStatus()==0||company.getIsDel()==1){
+            throw new CustomException("此用户所属公司不存在或已停用");
+        }
+        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
+        {
+            log.info("登录用户:{} 已被删除.", username);
+            throw new CustomException("对不起,您的账号:" + username + " 已被删除");
+        }
+        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
+        {
+            log.info("登录用户:{} 已被停用.", username);
+            throw new CustomException("对不起,您的账号:" + username + " 已停用");
+        }
+
+        return createLoginUser(user);
+    }
+
+    public UserDetails createLoginUser(CompanyUser user)
+    {
+        return new LoginUser(user, permissionService.getMenuPermission(user),companyService.selectCompanyById(user.getCompanyId()));
+    }
+}

+ 1 - 0
fs-ipad-task/src/main/resources/META-INF/spring-devtools.properties

@@ -0,0 +1 @@
+restart.include.json=/com.alibaba.fastjson.*.jar

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor