From d8803113a2a7824d24a9949a7561e9b67fd4bf16 Mon Sep 17 00:00:00 2001
From: liujie <1793218484@qq.com>
Date: 星期四, 11 十二月 2025 09:03:40 +0800
Subject: [PATCH] Merge branch 'master' of http://120.76.84.145:10101/gitblit/r/java/jiashida
---
ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/IndexController.java | 41 ---
/dev/null | 286 --------------------------
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java | 44 +++
ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/TAppUserResp.java | 2
ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/UserIndexController.java | 118 +---------
ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/WxPayController.java | 53 ----
ruoyi-applet/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java | 62 ++++
ruoyi-applet/src/main/resources/application-test.yml | 2
ruoyi-common/src/main/java/com/ruoyi/common/core/domain/model/LoginUserApplet.java | 8
9 files changed, 124 insertions(+), 492 deletions(-)
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/ChildcareController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/ChildcareController.java
deleted file mode 100644
index 2e77394..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/ChildcareController.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package com.ruoyi.web.controller.api;
-
-import com.ruoyi.common.core.domain.R;
-import com.ruoyi.framework.web.service.TokenService;
-import com.ruoyi.system.model.TChildcareServices;
-import com.ruoyi.system.service.TChildcareServicesService;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import lombok.extern.slf4j.Slf4j;
-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;
-
-@Slf4j
-@RestController
-@RequestMapping("/childcare")
-@Api(tags = "托育模块")
-public class ChildcareController {
-
- private final TChildcareServicesService childcareServicesService;
- private final TokenService tokenService;
-
-
- public ChildcareController(TChildcareServicesService childcareServicesService, TokenService tokenService) {
- this.childcareServicesService = childcareServicesService;
- this.tokenService = tokenService;
- }
-
-
-
- // 添加托育模块
- @PostMapping("/addChildcare")
- @ApiOperation(value = "添加托育服务")
- public R<String> addChildcare(@RequestBody TChildcareServices tChildcareServices) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- tChildcareServices.setAppUserId(userId);
- boolean save = childcareServicesService.save(tChildcareServices);
- if (save) {
- return R.ok("添加成功");
- }
- return R.fail("添加失败");
- }
-
-}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/ConvenienceController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/ConvenienceController.java
deleted file mode 100644
index 7550c40..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/ConvenienceController.java
+++ /dev/null
@@ -1,316 +0,0 @@
-package com.ruoyi.web.controller.api;
-
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ruoyi.common.core.domain.BaseModel;
-import com.ruoyi.common.core.domain.BasePage;
-import com.ruoyi.common.core.domain.R;
-import com.ruoyi.framework.web.service.TokenService;
-import com.ruoyi.system.model.*;
-import com.ruoyi.system.query.CommunityActivityListQuery;
-import com.ruoyi.system.query.ConvenientInformationListQuery;
-import com.ruoyi.system.query.DeliberationVoteListQuery;
-import com.ruoyi.system.query.MicroWishListQuery;
-import com.ruoyi.system.service.*;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.web.bind.annotation.*;
-
-import java.time.LocalDateTime;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-import java.util.Objects;
-import java.util.stream.Collectors;
-
-@Slf4j
-@RestController
-@RequestMapping("/convenience")
-@Api(tags = "普惠便民模块")
-public class ConvenienceController {
-
- private final THtmlConfigService tHtmlConfigService;
- private final TServiceGuideFileService tServiceGuideFileService;
- private final TConvenientInformationService tConvenientInformationService;
- private final TMicroWishService tMicroWishService;
- private final TokenService tokenService;
- private final TCommunityActivityService tCommunityActivityService;
- private final TCommunityActivityRegistrationService tCommunityActivityRegistrationService;
- private final TDeliberationVoteService tDeliberationVoteService;
- private final TDeliberationVoteOptionService tDeliberationVoteOptionService;
- private final TAppealServicesService tAppealServicesService;
-
- public ConvenienceController(THtmlConfigService tHtmlConfigService, TServiceGuideFileService tServiceGuideFileService, TConvenientInformationService tConvenientInformationService, TMicroWishService tMicroWishService, TokenService tokenService, TCommunityActivityService tCommunityActivityService, TCommunityActivityRegistrationService tCommunityActivityRegistrationService, TDeliberationVoteService tDeliberationVoteService, TDeliberationVoteOptionService tDeliberationVoteOptionService, TAppealServicesService tAppealServicesService) {
- this.tHtmlConfigService = tHtmlConfigService;
- this.tServiceGuideFileService = tServiceGuideFileService;
- this.tConvenientInformationService = tConvenientInformationService;
- this.tMicroWishService = tMicroWishService;
- this.tokenService = tokenService;
- this.tCommunityActivityService = tCommunityActivityService;
- this.tCommunityActivityRegistrationService = tCommunityActivityRegistrationService;
- this.tDeliberationVoteService = tDeliberationVoteService;
- this.tDeliberationVoteOptionService = tDeliberationVoteOptionService;
- this.tAppealServicesService = tAppealServicesService;
- }
-
-
- @ApiOperation(value = "说明--1=托育服务 2=阅芽计划 3=办事指南图文指引 4=暖心服务图片 5=注册协议 6=隐私政策 7=学习申请书 8=安全告知书 9=购买支付说明 10=微心愿风险提示 11=群众诉求服务说明 12=随手拍说明 13=康年年图文介绍 ", response = THtmlConfig.class)
- @GetMapping("/getServiceGuide")
- public R<THtmlConfig> getServiceGuide(int type) {
- return R.ok(tHtmlConfigService.getOne(
- Wrappers.<THtmlConfig>lambdaQuery().eq(THtmlConfig::getConfigType, type)
- ));
- }
-
-
- @ApiOperation(value = "办事指南--流程指引文件", response = TServiceGuideFile.class)
- @PostMapping("/getServiceGuideFile")
- public R<Page<TServiceGuideFile>> getServiceGuideFile(@RequestBody BasePage basePage) {
- return R.ok(tServiceGuideFileService.page(new Page<TServiceGuideFile>(basePage.getPageNum(), basePage.getPageSize()),
- Wrappers.<TServiceGuideFile>lambdaQuery().orderByDesc(TServiceGuideFile::getCreateTime)
- ));
- }
-
-
- @ApiOperation(value = "便民信息--便民信息列表", response = TConvenientInformation.class)
- @PostMapping("/getConvenientInformationList")
- public R<Page<TConvenientInformation>> getConvenientInformationList(@RequestBody ConvenientInformationListQuery query) {
- Page<TConvenientInformation> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TConvenientInformation> tConvenientInformationPage = tConvenientInformationService.page(page, new LambdaQueryWrapper<TConvenientInformation>().like(Objects.nonNull(query.getName()), TConvenientInformation::getConvenientName, query.getName()).orderByDesc(BaseModel::getCreateTime));
- return R.ok(tConvenientInformationPage);
- }
-
-
- @ApiOperation(value = "便民信息--便民信息详情", response = TConvenientInformation.class)
- @GetMapping("/getConvenientInformationDetail/{id}")
- public R<TConvenientInformation> getConvenientInformationDetail(@PathVariable String id) {
- return R.ok(tConvenientInformationService.getById(id));
- }
-
-
- @ApiOperation(value = "微心愿--微心愿列表", response = TMicroWish.class)
- @PostMapping("/getMicroWishList")
- public R<Page<TMicroWish>> getMicroWishList(@RequestBody MicroWishListQuery query) {
- Page<TMicroWish> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TMicroWish> tMicroWishPage = tMicroWishService.page(page, new LambdaQueryWrapper<TMicroWish>().eq(TMicroWish::getWishType, 1).eq(TMicroWish::getStatus, 2).like(Objects.nonNull(query.getWishDescription()), TMicroWish::getWishDescription, query.getWishDescription()).orderByDesc(BaseModel::getCreateTime));
- return R.ok(tMicroWishPage);
- }
-
-
- @ApiOperation(value = "微心愿--发布心愿", response = TMicroWish.class)
- @PostMapping("/addMicroWish")
- public R<?> addMicroWish(@RequestBody TMicroWish dto) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- dto.setAppUserId(userId);
- if(dto.getWishType() == 1){
- dto.setStatus(1);
- }else {
- dto.setStatus(4);
- }
- tMicroWishService.save(dto);
- return R.ok();
- }
-
-
- @ApiOperation(value = "社区活动--列表", response = TCommunityActivity.class)
- @PostMapping("/getCommunityActivityList")
- public R<Page<TCommunityActivity>> getCommunityActivityList(@RequestBody CommunityActivityListQuery query) {
- String userId = null;
- try {
- userId = tokenService.getLoginUserApplet().getUserId();
- } catch (Exception e) {
- }
- Page<TCommunityActivity> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TCommunityActivity> tCommunityActivityPage = tCommunityActivityService.page(page, new LambdaQueryWrapper<TCommunityActivity>().eq(TCommunityActivity::getStatus, 2).like(Objects.nonNull(query.getName()), TCommunityActivity::getActivityTitle, query.getName()).orderByDesc(BaseModel::getCreateTime));
- List<TCommunityActivity> activityList = tCommunityActivityPage.getRecords();
- // 判断是否已经报名
- if (!activityList.isEmpty() && userId != null) {
- List<String> activityIds = activityList.stream().map(TCommunityActivity::getId).collect(Collectors.toList());
- List<TCommunityActivityRegistration> activityRegistrationList = tCommunityActivityRegistrationService.list(new LambdaQueryWrapper<TCommunityActivityRegistration>().in(TCommunityActivityRegistration::getActivityId, activityIds).eq(TCommunityActivityRegistration::getAppUserId, userId));
- for (TCommunityActivity tCommunityActivity : activityList) {
- List<TCommunityActivityRegistration> tCommunityActivityRegistrations = activityRegistrationList.stream().filter(e -> e.getActivityId().equals(tCommunityActivity.getId())).collect(Collectors.toList());
- tCommunityActivity.setUserNum(tCommunityActivityRegistrations.size());
- String finalUserId = userId;
- TCommunityActivityRegistration tCommunityActivityRegistration = tCommunityActivityRegistrations.stream().filter(e -> e.getAppUserId().equals(finalUserId)).findFirst().orElse(null);
- if (tCommunityActivityRegistration != null) {
- tCommunityActivity.setState(2);
- }
- }
-
- }
- tCommunityActivityPage.setRecords(activityList);
- return R.ok(tCommunityActivityPage);
- }
-
-
- @ApiOperation(value = "社区活动--详情", response = TCommunityActivity.class)
- @GetMapping("/getCommunityActivityDetail/{id}")
- public R<TCommunityActivity> getCommunityActivityDetail(@PathVariable String id) {
- TCommunityActivity tCommunityActivity = tCommunityActivityService.getById(id);
- if (tCommunityActivity == null) {
- return R.fail("活动不存在");
- }
- String userId = null;
- try {
- userId = tokenService.getLoginUserApplet().getUserId();
- } catch (Exception e) {
- }
- if (userId != null) {
- long count = tCommunityActivityRegistrationService.count(new LambdaQueryWrapper<TCommunityActivityRegistration>().eq(TCommunityActivityRegistration::getActivityId, id).eq(TCommunityActivityRegistration::getAppUserId, userId));
- if (count > 0) {
- tCommunityActivity.setState(2);
- }
- }
- return R.ok(tCommunityActivity);
- }
-
-
- @ApiOperation(value = "社区活动--报名", response = TCommunityActivity.class)
- @PostMapping("/addCommunityActivityRegistration")
- public R<?> addCommunityActivityRegistration(@RequestBody TCommunityActivityRegistration dto) {
-
- String userId = tokenService.getLoginUserApplet().getUserId();
- TCommunityActivity activity = tCommunityActivityService.getById(dto.getActivityId());
- if (activity == null) {
- return R.fail("活动不存在");
- }
- if (activity.getEndTime().isBefore(LocalDateTime.now())) {
- return R.fail("报名已结束");
- }
- if (activity.getStartTime().isAfter(LocalDateTime.now())) {
- return R.fail("报名未开始");
- }
- if (activity.getStatus() == 3) {
- return R.fail("活动已结束");
- }
- if (activity.getStatus() == 1) {
- return R.fail("活动未发布");
- }
- if (tCommunityActivityRegistrationService.count(new LambdaQueryWrapper<TCommunityActivityRegistration>().eq(TCommunityActivityRegistration::getActivityId, dto.getActivityId()).eq(TCommunityActivityRegistration::getAppUserId, userId)) > 0) {
- return R.fail("你已报名");
- }
-
- dto.setAppUserId(userId);
- tCommunityActivityRegistrationService.save(dto);
- return R.ok();
- }
-
-
- @ApiOperation(value = "议事投票--列表", response = TDeliberationVote.class)
- @PostMapping("/getDeliberationVoteList")
- public R<Page<TDeliberationVote>> getDeliberationVoteList(@RequestBody DeliberationVoteListQuery query) {
- String userId = null;
- try {
- userId = tokenService.getLoginUserApplet().getUserId();
- } catch (Exception e) {
- }
- Page<TDeliberationVote> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TDeliberationVote> tDeliberationVotePage = tDeliberationVoteService.page(page, new LambdaQueryWrapper<TDeliberationVote>().eq(TDeliberationVote::getStatus, query.getStatus()).orderByDesc(BaseModel::getCreateTime));
- List<TDeliberationVote> tDeliberationVoteList = tDeliberationVotePage.getRecords();
- if (!tDeliberationVoteList.isEmpty()) {
- List<String> voteIds = tDeliberationVoteList.stream().map(TDeliberationVote::getId).collect(Collectors.toList());
- List<TDeliberationVoteOption> tDeliberationVoteOptionList = tDeliberationVoteOptionService.list(new LambdaQueryWrapper<TDeliberationVoteOption>().in(TDeliberationVoteOption::getVoteId, voteIds));
- for (TDeliberationVote tDeliberationVote : tDeliberationVoteList) {
- List<TDeliberationVoteOption> options = tDeliberationVoteOptionList.stream().filter(e -> e.getVoteId().equals(tDeliberationVote.getId())).collect(Collectors.toList());
- for (TDeliberationVoteOption option : options) {
-
- if (option.getVoteCount() != null) {
-
-
- String[] split = option.getVoteCount().split(",");
- // split转为数组
- List<String> list = Arrays.asList(split);
- option.setVoteCountNum(list.size());
- if (tDeliberationVote.getVoteState() == 1 && userId != null && list.contains(userId)) {
- tDeliberationVote.setVoteState(2);
- }
- }
-
- }
- tDeliberationVote.setOptions(options);
- }
- }
- tDeliberationVotePage.setRecords(tDeliberationVoteList);
- return R.ok(tDeliberationVotePage);
- }
-
- @ApiOperation(value = "议事投票--详情", response = TDeliberationVote.class)
- @GetMapping("/getDeliberationVoteDetail/{id}")
- public R<TDeliberationVote> getDeliberationVoteDetail(@PathVariable String id) {
- String userId = null;
- try {
- userId = tokenService.getLoginUserApplet().getUserId();
- } catch (Exception e) {
- }
- TDeliberationVote tDeliberationVote = tDeliberationVoteService.getById(id);
- if (tDeliberationVote != null) {
- List<TDeliberationVoteOption> tDeliberationVoteOptionList = tDeliberationVoteOptionService.list(new LambdaQueryWrapper<TDeliberationVoteOption>().eq(TDeliberationVoteOption::getVoteId, id));
- List<TDeliberationVoteOption> options = tDeliberationVoteOptionList.stream().filter(e -> e.getVoteId().equals(tDeliberationVote.getId())).collect(Collectors.toList());
- for (TDeliberationVoteOption option : options) {
- if (option.getVoteCount() != null) {
- String[] split = option.getVoteCount().split(",");
- // split转为数组
- List<String> list = Arrays.asList(split);
- option.setVoteCountNum(list.size());
- if (tDeliberationVote.getVoteState() == 1 && userId != null && list.contains(userId)) {
- tDeliberationVote.setVoteState(2);
- }
- }
-
- }
- tDeliberationVote.setOptions(options);
- }
- return R.ok(tDeliberationVote);
- }
-
-
- @ApiOperation(value = "议事投票--投票")
- @PostMapping("/addDeliberationVoteOption")
- public R<?> addDeliberationVoteOption(@RequestBody TDeliberationVoteOption dto) {
- String voteId = dto.getVoteId();
- TDeliberationVote tDeliberationVote = tDeliberationVoteService.getById(voteId);
- if (tDeliberationVote == null) {
- return R.fail("投票不存在");
- }
- if (tDeliberationVote.getStatus() == 3) {
- return R.fail("投票已结束");
- }
- if (tDeliberationVote.getStatus() == 1) {
- return R.fail("投票未开始");
- }
- String userId = tokenService.getLoginUserApplet().getUserId();
- List<TDeliberationVoteOption> list = tDeliberationVoteOptionService.list(new LambdaQueryWrapper<TDeliberationVoteOption>().eq(TDeliberationVoteOption::getVoteId, dto.getVoteId()));
- for (TDeliberationVoteOption tDeliberationVoteOption : list) {
- String voteCount = tDeliberationVoteOption.getVoteCount();
- if(voteCount != null){
- String[] split = voteCount.split(",");
- if (Arrays.asList(split).contains(userId)) {
- return R.fail("你已经投票");
- }
- }
-
- }
- TDeliberationVoteOption tDeliberationVoteOption = list.stream().filter(e -> e.getOptionContent().equals(dto.getOptionContent())).findFirst().orElse(null);
- if (tDeliberationVoteOption == null) {
- return R.fail("选项不存在");
- }
- tDeliberationVoteOption.setVoteCount(tDeliberationVoteOption.getVoteCount() + "," + userId);
- tDeliberationVoteOptionService.updateById(tDeliberationVoteOption);
- return R.ok();
- }
-
-
- @ApiOperation(value = "群众服务诉求/随手拍--提交")
- @PostMapping("/addAppealServices")
- public R<?> addAppealServices(@RequestBody TAppealServices dto) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- dto.setAppUserId(userId);
- dto.setStatus(1);
- tAppealServicesService.save(dto);
- return R.ok();
- }
-
-
-}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/CourseController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/CourseController.java
deleted file mode 100644
index 594fa68..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/CourseController.java
+++ /dev/null
@@ -1,229 +0,0 @@
-package com.ruoyi.web.controller.api;
-
-import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.google.common.collect.ImmutableMap;
-import com.ruoyi.common.core.domain.R;
-import com.ruoyi.common.utils.DateUtils;
-import com.ruoyi.common.utils.OrderNos;
-import com.ruoyi.framework.web.service.TokenService;
-import com.ruoyi.system.model.TAppUser;
-import com.ruoyi.system.model.TCourse;
-import com.ruoyi.system.model.TCourseOrder;
-import com.ruoyi.system.query.CourseOrderListQuery;
-import com.ruoyi.system.query.GetCourseListQuery;
-import com.ruoyi.system.service.TAppUserService;
-import com.ruoyi.system.service.TCourseOrderService;
-import com.ruoyi.system.service.TCourseService;
-import com.ruoyi.system.task.base.QuartzManager;
-import com.ruoyi.system.task.base.TimeJobType;
-import com.ruoyi.system.task.jobs.OrderJob;
-import com.ruoyi.system.wxPay.model.WeixinPayProperties;
-import com.ruoyi.system.wxPay.utils.WxRefundUtil;
-import com.ruoyi.system.wxPay.utils.WxV3Pay;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
-
-import java.math.BigDecimal;
-import java.time.LocalDateTime;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.stream.Collectors;
-
-@Slf4j
-@RestController
-@RequestMapping("/course")
-@Api(tags = "课程模块")
-public class CourseController {
-
- private final TCourseService courseService;
- private final TCourseOrderService courseOrderService;
- private final TokenService tokenService;
- private final WxV3Pay wxV3Pay;
- private final WeixinPayProperties weixinPayProperties;
- private final TAppUserService appUserService;
-
- public CourseController(TCourseService courseService, TCourseOrderService courseOrderService, TokenService tokenService, WxV3Pay wxV3Pay, WeixinPayProperties weixinPayProperties, TAppUserService appUserService) {
- this.courseService = courseService;
- this.courseOrderService = courseOrderService;
- this.tokenService = tokenService;
- this.wxV3Pay = wxV3Pay;
- this.weixinPayProperties = weixinPayProperties;
- this.appUserService = appUserService;
- }
-
- @PostMapping("/getCourseList")
- @ApiOperation(value = "课程模块--列表",response = TCourse.class)
- public R<Page<TCourse>> getCourseList(@RequestBody GetCourseListQuery query) {
- Page<TCourse> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TCourse> coursePage = courseService.page(page, Wrappers.<TCourse>lambdaQuery().eq(TCourse::getCourseType,query.getCourseType()).like(Objects.nonNull(query.getCourseTitle()), TCourse::getCourseTitle, query.getCourseTitle()).orderByDesc(TCourse::getCreateTime));
- return R.ok(coursePage);
- }
-
-
- @PostMapping("/getCourseDetail/{id}")
- @ApiOperation(value = "课程模块--详情",response = TCourse.class)
- public R<TCourse> getCourseDetail(@PathVariable String id) {
- TCourse course = courseService.getById(id);
- long count = courseOrderService.count(Wrappers.lambdaQuery(TCourseOrder.class).eq(TCourseOrder::getCourseId, id).in(TCourseOrder::getPayStatus, Arrays.asList(1, 2, 5)));
- course.setSignUpNum((int) count);
- return R.ok(course);
- }
-
-
-
- @PostMapping("/getCourseOrderList")
- @ApiOperation(value = "课程模块--订单列表",response = TCourseOrder.class)
- public R<Page<TCourseOrder>> getCourseOrderList(@RequestBody CourseOrderListQuery query) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- Page<TCourseOrder> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TCourseOrder> courseOrderPage = courseOrderService.page(page, Wrappers.<TCourseOrder>lambdaQuery()
- .eq(TCourseOrder::getAppUserId, userId)
- .ne(TCourseOrder::getPayStatus, 4)
- .eq(Objects.nonNull(query.getPayStatus()),TCourseOrder::getPayStatus, query.getPayStatus())
- .orderByDesc(TCourseOrder::getCreateTime));
- List<TCourseOrder> records = courseOrderPage.getRecords();
- if(!records.isEmpty()){
- List<String> courseIds = records.stream().map(TCourseOrder::getCourseId).collect(Collectors.toList());
- List<TCourse> tCourses = courseService.listByIds(courseIds);
- records.forEach(courseOrder -> {
- tCourses.forEach(course -> {
- if(course.getId().equals(courseOrder.getCourseId())){
- courseOrder.setCourse(course);
- }
- });
- });
- }
- courseOrderPage.setRecords(records);
- return R.ok(courseOrderPage);
- }
-
- @GetMapping("/getCourseOrderDetail/{id}")
- @ApiOperation(value = "课程模块--订单详情",response = TCourseOrder.class)
- public R<TCourseOrder> getCourseOrderList(@PathVariable String id) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- TCourseOrder courseOrder = courseOrderService.getById(id);
- if(!courseOrder.getAppUserId().equals(userId)){
- return R.fail("无权限");
- }
- String courseId = courseOrder.getCourseId();
- TCourse course = courseService.getById(courseId);
- courseOrder.setCourse(course);
- return R.ok(courseOrder);
- }
-
- @PostMapping("/saveOrder")
- @ApiOperation(value = "课程模块--报名")
- public R<Map<String, Object>> saveOrder(@RequestBody TCourseOrder courseOrder) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- TAppUser appUser = appUserService.getById(userId);
- TCourse course = courseService.getById(courseOrder.getCourseId());
- long count = courseOrderService.count(Wrappers.lambdaQuery(TCourseOrder.class).eq(TCourseOrder::getCourseId, course.getId()).in(TCourseOrder::getPayStatus, Arrays.asList(1, 2, 5)));
- if(count>=course.getPeopleLimit()){
- return R.fail("报名人数已满");
- }
-
- courseOrder.setAppUserId(userId);
- courseOrder.setPayMoney(course.getCourseCost());
- courseOrder.setPayStatus(1);
- courseOrder.setOrderNumber(OrderNos.getDid());
- boolean save = courseOrderService.save(courseOrder);
- if (save) {
- Map<String, ? extends Object> maps =
- new ImmutableMap.Builder<String, String>().
- put("id", courseOrder.getId())
- .build();
- QuartzManager.addJob(
- OrderJob.class,
- (OrderJob.name+courseOrder.getId()).toUpperCase(),
- TimeJobType.CANCEL_ORDER,
- DateUtils.localDateTimeToDate(LocalDateTime.now().plusMinutes(15)),
- maps
- );
- Map<String, Object> result = wxV3Pay.jsApi(courseOrder.getOrderNumber(), course.getCourseCost().multiply(BigDecimal.valueOf(100)).longValue(), appUser.getOpenId(),"购买课程","");
- return R.ok(result);
-// return R.ok();
- }
- return R.fail("报名失败");
- }
-
- @PostMapping("/payOrder")
- @ApiOperation(value = "课程模块--支付订单")
- public R<Map<String, Object>> payOrder(@RequestBody TCourseOrder courseOrder) {
-// String userId = tokenService.getLoginUserApplet().getUserId();
-// TAppUser appUser = appUserService.getById(userId);
- TCourseOrder courseOrder1 = courseOrderService.getById(courseOrder.getId());
-// if(!userId.equals(courseOrder1.getAppUserId())){
-// return R.fail("无权限操作");
-// }
- courseOrder1.setOrderNumber(OrderNos.getDid());
- courseOrder1.setRealName(courseOrder.getRealName());
- courseOrder1.setUserPhone(courseOrder.getUserPhone());
- courseOrder1.setIdCard(courseOrder.getIdCard());
-
- courseOrderService.updateById(courseOrder1);
- Map<String, Object> result = wxV3Pay.jsApi(courseOrder1.getOrderNumber(), courseOrder1.getPayMoney().multiply(BigDecimal.valueOf(100)).longValue(), "oz71-1_OevadwmESB_IFAW7PucWY","购买课程","");
- return R.ok(result);
- }
-
-
- @PostMapping("/refundOrder")
- @ApiOperation(value = "课程模块--退款")
- public R<?> refundOrder(@RequestBody TCourseOrder courseOrder) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- TCourseOrder courseOrder1 = courseOrderService.getById(courseOrder.getId());
- courseOrder1.setRefundReason(courseOrder.getRefundReason());
- courseOrder1.setRefundReasonPictures(courseOrder.getRefundReasonPictures());
-
- courseOrder1.setRequestRefundTime(LocalDateTime.now());
- courseOrder1.setRefundMoney(courseOrder1.getPayMoney());
-
- if(!userId.equals(courseOrder1.getAppUserId())){
- return R.fail("无权限操作");
- }
- if(courseOrder1.getPayStatus()!=2){
- return R.fail("状态不允许退款");
- }
- courseOrder1.setPayStatus(6);
- LocalDateTime payTime = courseOrder1.getPayTime();
- if(payTime==null){
- return R.fail("状态不允许退款");
- }
- if(payTime.plusDays(2).isBefore(LocalDateTime.now())){
- courseOrder1.setBankCardNumber(courseOrder.getBankCardNumber());
- courseOrder1.setCardholderName(courseOrder.getCardholderName());
- courseOrder1.setBankName(courseOrder.getBankName());
- courseOrder1.setRefundStatus(1);
- courseOrderService.updateById(courseOrder1);
- }else {
- String outRefundNo = OrderNos.getDid();
- courseOrder1.setRefundNumber(outRefundNo);
- courseOrderService.updateById(courseOrder1);
-// WxPaymentRefundModel refundModel = new WxPaymentRefundModel();
-//// refundModel.setSub_mchid(weixinPayProperties.getMchId());
-//// refundModel.setSp_appid(weixinPayProperties.getAppId());
-//// refundModel.setTransaction_id(courseOrder1.getTransactionId());
-// refundModel.setOut_trade_no(courseOrder1.getOrderNumber());
-// refundModel.setOut_refund_no(OrderNos.getDid());
-// refundModel.setReason(courseOrder1.getRefundReason());
-// refundModel.setGoods_detail(new ArrayList<>());
-// refundModel.setAmount(new WxPaymentRefundModel.RefundAmount(courseOrder1.getPayMoney().multiply(BigDecimal.valueOf(100)).intValue(), "CNY", courseOrder1.getPayMoney().multiply(BigDecimal.valueOf(100)).intValue()));
-// Map<String, Object> refund = wxV3Pay.refund(refundModel);
-// System.out.println(refund);
- String result = wxRefundUtil.refund(courseOrder1.getPayMoney().multiply(BigDecimal.valueOf(100)).intValue(), courseOrder1.getOrderNumber(),outRefundNo);
- if(result!=null){
- return R.fail(result);
- }
- }
- return R.ok();
- }
-
- @Autowired
- private WxRefundUtil wxRefundUtil;
-
-}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/EmploymentController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/EmploymentController.java
deleted file mode 100644
index 3b4de2d..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/EmploymentController.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package com.ruoyi.web.controller.api;
-
-import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ruoyi.common.core.domain.BasePage;
-import com.ruoyi.common.core.domain.R;
-import com.ruoyi.system.model.TBanner;
-import com.ruoyi.system.model.TEmploymentEntrepreneurship;
-import com.ruoyi.system.model.TEmploymentInfo;
-import com.ruoyi.system.service.TEmploymentEntrepreneurshipService;
-import com.ruoyi.system.service.TEmploymentInfoService;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.web.bind.annotation.*;
-
-import java.util.List;
-
-@Slf4j
-@RestController
-@RequestMapping("/employment")
-@Api(tags = "新就业模块")
-public class EmploymentController {
-
- private final TEmploymentInfoService employmentInfoService;
- private final TEmploymentEntrepreneurshipService employmentEntrepreneurshipService;
-
- public EmploymentController(TEmploymentInfoService employmentInfoService, TEmploymentEntrepreneurshipService employmentEntrepreneurshipService) {
- this.employmentInfoService = employmentInfoService;
- this.employmentEntrepreneurshipService = employmentEntrepreneurshipService;
- }
-
-
- @PostMapping("/getEmploymentInfoList")
- @ApiOperation(value = "新就业模块--新就业信息列表",response = TEmploymentInfo.class)
- public R<Page<TEmploymentInfo>> getEmploymentInfoList(@RequestBody BasePage basePage) {
- Page<TEmploymentInfo> page = new Page<>(basePage.getPageNum(), basePage.getPageSize());
- Page<TEmploymentInfo> pageEmploymentInfo = employmentInfoService.page(page, Wrappers.<TEmploymentInfo>lambdaQuery().orderByDesc(TEmploymentInfo::getCreateTime));
- return R.ok(pageEmploymentInfo);
- }
-
-
- @PostMapping("/getEmploymentInfoDetail/{id}")
- @ApiOperation(value = "新就业模块--新就业信息详情",response = TEmploymentInfo.class)
- public R<TEmploymentInfo> getEmploymentInfoDetail(@PathVariable String id) {
- TEmploymentInfo employmentInfo = employmentInfoService.getById(id);
- employmentInfo.setReadCount(employmentInfo.getReadCount() + 1);
- employmentInfoService.updateById(employmentInfo);
- return R.ok(employmentInfo);
- }
-
-
- @PostMapping("/getEntrepreneurshipList")
- @ApiOperation(value = "创业模块--创业信息列表",response = TEmploymentEntrepreneurship.class)
- public R<Page<TEmploymentEntrepreneurship>> getEntrepreneurshipList(@RequestBody BasePage basePage) {
- Page<TEmploymentEntrepreneurship> page = new Page<>(basePage.getPageNum(), basePage.getPageSize());
- Page<TEmploymentEntrepreneurship> tEmploymentEntrepreneurshipPage = employmentEntrepreneurshipService.page(page, Wrappers.<TEmploymentEntrepreneurship>lambdaQuery().orderByDesc(TEmploymentEntrepreneurship::getCreateTime));
- return R.ok(tEmploymentEntrepreneurshipPage);
- }
-
-
- @PostMapping("/getEntrepreneurshipDetail/{id}")
- @ApiOperation(value = "创业模块--创业信息详情",response = TEmploymentEntrepreneurship.class)
- public R<TEmploymentEntrepreneurship> getEntrepreneurshipDetail(@PathVariable String id) {
- TEmploymentEntrepreneurship employmentEntrepreneurship = employmentEntrepreneurshipService.getById(id);
- employmentEntrepreneurship.setReadCount(employmentEntrepreneurship.getReadCount() + 1);
- employmentEntrepreneurshipService.updateById(employmentEntrepreneurship);
- return R.ok(employmentEntrepreneurship);
- }
-
-}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/IndexController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/IndexController.java
index 0b5204d..1c0ddd3 100644
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/IndexController.java
+++ b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/IndexController.java
@@ -1,17 +1,17 @@
package com.ruoyi.web.controller.api;
-import com.alibaba.fastjson.JSON;
-import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.R;
-import com.ruoyi.system.dto.IdDto;
import com.ruoyi.system.model.TBanner;
-import com.ruoyi.system.model.TNotice;
import com.ruoyi.system.service.TBannerService;
-import com.ruoyi.system.service.TNoticeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
+import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@@ -19,16 +19,10 @@
@RestController
@RequestMapping("/index")
@Api(tags = "首页模块")
+@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class IndexController {
private final TBannerService tBannerService;
- private final TNoticeService tNoticeService;
-
- public IndexController(TBannerService tBannerService, TNoticeService tNoticeService) {
- this.tBannerService = tBannerService;
- this.tNoticeService = tNoticeService;
- }
-
@ApiOperation(value = "首页模块--轮播图",response = TBanner.class)
@@ -44,26 +38,5 @@
TBanner tBanner = tBannerService.getById(id);
return R.ok(tBanner);
}
-
-
- @ApiOperation(value = "首页模块--公告活动",response = TNotice.class)
- @GetMapping(value = "/getNoticeList")
- public R<List<TNotice>> getNoticeList() {
- List<TNotice> tNoticeList = tNoticeService.list();
- return R.ok(tNoticeList);
- }
-
-
-
-
- @ApiOperation(value = "首页模块--公告活动详情",response = TNotice.class)
- @GetMapping(value = "/getNoticeDetail/{id}")
- public R<TNotice> getNoticeDetail(@PathVariable String id) {
- TNotice notice = tNoticeService.getById(id);
- notice.setReadCount(notice.getReadCount() + 1);
- tNoticeService.updateById(notice);
- return R.ok(notice);
- }
-
}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/MerchantController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/MerchantController.java
deleted file mode 100644
index 82c765b..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/MerchantController.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package com.ruoyi.web.controller.api;
-
-import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ruoyi.common.core.domain.BaseModel;
-import com.ruoyi.common.core.domain.BasePage;
-import com.ruoyi.common.core.domain.R;
-import com.ruoyi.system.model.TAdvertisement;
-import com.ruoyi.system.model.TEmploymentInfo;
-import com.ruoyi.system.model.TMerchant;
-import com.ruoyi.system.model.TMerchantType;
-import com.ruoyi.system.query.MerchantQuery;
-import com.ruoyi.system.service.*;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.web.bind.annotation.*;
-
-import java.util.List;
-import java.util.Objects;
-
-@Slf4j
-@RestController
-@RequestMapping("/merchant")
-@Api(tags = "惠民商务模块")
-public class MerchantController {
-
- private final TAdvertisementService advertisementService;
- private final TMerchantService merchantService;
- private final TMerchantTypeService merchantTypeService;
-
- public MerchantController(TAdvertisementService advertisementService, TMerchantService merchantService, TMerchantTypeService merchantTypeService) {
- this.advertisementService = advertisementService;
- this.merchantService = merchantService;
- this.merchantTypeService = merchantTypeService;
- }
-
-
- @GetMapping("/getAdvertisementList")
- @ApiOperation(value = "惠民商务--广告列表",response = TAdvertisement.class)
- public R<List<TAdvertisement>> getAdvertisementList() {
- List<TAdvertisement> list = advertisementService.list();
- return R.ok(list);
- }
-
- @GetMapping("/getAdvertisementDetail/{id}")
- @ApiOperation(value = "惠民商务--广告详情",response = TAdvertisement.class)
- public R<TAdvertisement> getAdvertisementList(@PathVariable String id) {
- TAdvertisement advertisement = advertisementService.getById(id);
- return R.ok(advertisement);
- }
-
-
- @PostMapping("/getMerchantList")
- @ApiOperation(value = "惠民商务--商户列表",response = TMerchant.class)
- public R<Page<TMerchant>> getMerchantList(@RequestBody MerchantQuery query) {
- Page<TMerchant> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TMerchant> merchantPage = merchantService.page(page, Wrappers.<TMerchant>lambdaQuery().eq(Objects.nonNull(query.getTypeId()), TMerchant::getTypeId, query.getTypeId())
- .like(Objects.nonNull(query.getMerchantName()), TMerchant::getMerchantName, query.getMerchantName())
- .orderByDesc(BaseModel::getCreateTime)
- );
- return R.ok(merchantPage);
- }
-
- @GetMapping("/getMerchantDetail/{id}")
- @ApiOperation(value = "惠民商务--商户详情",response = TMerchant.class)
- public R<TMerchant> getMerchantDetail(@PathVariable String id) {
- TMerchant merchant = merchantService.getById(id);
- return R.ok(merchant);
- }
-
- @GetMapping("/getMerchantTypeList")
- @ApiOperation(value = "惠民商务--商户分类列表",response = TMerchantType.class)
- public R<List<TMerchantType>> getMerchantTypeList() {
- List<TMerchantType> list = merchantTypeService.list();
- return R.ok(list);
- }
-
-
-}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/PartyBuildingController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/PartyBuildingController.java
deleted file mode 100644
index 731e582..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/PartyBuildingController.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package com.ruoyi.web.controller.api;
-
-import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ruoyi.common.core.domain.R;
-import com.ruoyi.system.model.TPartyBuilding;
-import com.ruoyi.system.query.PartyBuildingListQuery;
-import com.ruoyi.system.service.TPartyBuildingService;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.web.bind.annotation.*;
-
-@Slf4j
-@RestController
-@RequestMapping("/partyBuilding")
-@Api(tags = "党建引领")
-public class PartyBuildingController {
-
- private final TPartyBuildingService partyBuildingService;
-
- public PartyBuildingController(TPartyBuildingService partyBuildingService) {
- this.partyBuildingService = partyBuildingService;
- }
-
- @ApiOperation(value = "党建引领--列表",response = TPartyBuilding.class)
- @PostMapping(value = "/getPartyBuildingList")
- public R<Page<TPartyBuilding>> getPartyBuildingList(@RequestBody PartyBuildingListQuery query) {
- Page<TPartyBuilding> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TPartyBuilding> pageTPartyBuilding = partyBuildingService.page(page,
- Wrappers.<TPartyBuilding>lambdaQuery()
- .eq(TPartyBuilding::getPartyType, query.getPartyType())
- .orderByDesc(TPartyBuilding::getCreateTime));
-
- return R.ok(pageTPartyBuilding);
- }
-
- @ApiOperation(value = "党建引领--详情",response = TPartyBuilding.class)
- @PostMapping(value = "/getPartyBuildingDetail/{id}")
- public R<TPartyBuilding> getPartyBuildingDetail(@PathVariable String id) {
- TPartyBuilding partyBuilding = partyBuildingService.getById(id);
- partyBuilding.setReadCount(partyBuilding.getReadCount() + 1);
- partyBuildingService.updateById(partyBuilding);
- return R.ok(partyBuilding);
- }
-
-}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/PensionController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/PensionController.java
deleted file mode 100644
index 22649e2..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/PensionController.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package com.ruoyi.web.controller.api;
-
-import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ruoyi.common.basic.PageInfo;
-import com.ruoyi.common.core.domain.BaseModel;
-import com.ruoyi.common.core.domain.BasePage;
-import com.ruoyi.common.core.domain.R;
-import com.ruoyi.framework.web.service.TokenService;
-import com.ruoyi.system.model.TAssistedDining;
-import com.ruoyi.system.model.THelpNeeds;
-import com.ruoyi.system.model.TPartyBuilding;
-import com.ruoyi.system.query.AssistedDiningListQuery;
-import com.ruoyi.system.service.TAssistedDiningService;
-import com.ruoyi.system.service.THelpNeedsService;
-import com.ruoyi.system.service.TPartyBuildingService;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.web.bind.annotation.*;
-
-@Slf4j
-@RestController
-@RequestMapping("/pension")
-@Api(tags = "养老服务")
-public class PensionController {
-
- private final TAssistedDiningService tAssistedDiningService;
- private final THelpNeedsService tHelpNeedsService;
- private final TokenService tokenService;
-
- public PensionController(TAssistedDiningService tAssistedDiningService, THelpNeedsService tHelpNeedsService, TokenService tokenService) {
- this.tAssistedDiningService = tAssistedDiningService;
- this.tHelpNeedsService = tHelpNeedsService;
- this.tokenService = tokenService;
- }
-
-
- @PostMapping("/getAssistedDiningList")
- @ApiOperation(value = "养老服务--助餐",response = TAssistedDining.class)
- public R<PageInfo<TAssistedDining>> getAssistedDiningList(@RequestBody AssistedDiningListQuery query) {
- PageInfo<TAssistedDining> pageInfo = tAssistedDiningService.pageList(query);
- return R.ok(pageInfo);
- }
-
- @PostMapping("/getAssistedDiningDetail/{id}")
- @ApiOperation(value = "养老服务--助餐详情")
- public R<TAssistedDining> getAssistedDiningDetail(@PathVariable String id) {
- TAssistedDining tAssistedDining = tAssistedDiningService.getById(id);
- return R.ok(tAssistedDining);
- }
-
-
-
- @PostMapping("/getHelpNeedsList")
- @ApiOperation(value = "养老服务--助需",response = TPartyBuilding.class)
- public R<Page<THelpNeeds>> getHelpNeedsList(@RequestBody BasePage basePage) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- Page<THelpNeeds> page = new Page<>(basePage.getPageNum(), basePage.getPageSize());
- Page<THelpNeeds> helpNeedsPage = tHelpNeedsService.page(page, Wrappers.<THelpNeeds>lambdaQuery().eq(THelpNeeds::getAppUserId, userId).orderByDesc(BaseModel::getCreateTime));
- return R.ok(helpNeedsPage);
- }
-
- @PostMapping("/addHelpNeeds")
- @ApiOperation(value = "养老服务--添加助需")
- public R<String> addHelpNeeds(@RequestBody THelpNeeds tHelpNeeds) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- String nickName = tokenService.getLoginUserApplet().getUser().getNickName();
- tHelpNeeds.setNickName(nickName);
- tHelpNeeds.setAppUserId(userId);
- boolean save = tHelpNeedsService.save(tHelpNeeds);
- if (save) {
- return R.ok("添加成功");
- }
- return R.fail("添加失败");
- }
-}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/QuestionnaireController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/QuestionnaireController.java
deleted file mode 100644
index c9aa699..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/QuestionnaireController.java
+++ /dev/null
@@ -1,115 +0,0 @@
-package com.ruoyi.web.controller.api;
-
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ruoyi.common.core.domain.R;
-import com.ruoyi.framework.web.service.TokenService;
-import com.ruoyi.system.dto.SaveTQuestionnaireDto;
-import com.ruoyi.system.model.*;
-import com.ruoyi.system.query.PartyBuildingListQuery;
-import com.ruoyi.system.service.*;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.web.bind.annotation.*;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-@Slf4j
-@RestController
-@RequestMapping("/questionnaire")
-@Api(tags = "问卷调查")
-public class QuestionnaireController {
-
- private final TQuestionnaireService questionnaireService;
- private final TQuestionnaireRecordService questionnaireRecordService;
- private final TokenService tokenService;
- private final TQuestionnaireStemService questionnaireStemService;
- private final TQuestionnaireStemOptionService questionnaireStemOptionService;
- private final TQuestionnaireStemBriefAnswerService questionnaireStemBriefAnswerService;
-
- public QuestionnaireController(TQuestionnaireService questionnaireService, TQuestionnaireRecordService questionnaireRecordService, TokenService tokenService, TQuestionnaireStemService questionnaireStemService, TQuestionnaireStemOptionService questionnaireStemOptionService, TQuestionnaireStemBriefAnswerService questionnaireStemBriefAnswerService) {
- this.questionnaireService = questionnaireService;
- this.questionnaireRecordService = questionnaireRecordService;
- this.tokenService = tokenService;
- this.questionnaireStemService = questionnaireStemService;
- this.questionnaireStemOptionService = questionnaireStemOptionService;
- this.questionnaireStemBriefAnswerService = questionnaireStemBriefAnswerService;
- }
-
-
- @ApiOperation(value = "问卷调查--列表", response = TQuestionnaire.class)
- @GetMapping(value = "/getTQuestionnaireList")
- public R<List<TQuestionnaire>> getTQuestionnaireList() {
- String userId = null;
- try {
- userId = tokenService.getLoginUserApplet().getUserId();
- } catch (Exception e) {
- }
- List<TQuestionnaire> list = questionnaireService.list(new LambdaQueryWrapper<TQuestionnaire>().eq(TQuestionnaire::getStatus, 2));
- List<TQuestionnaireRecord> questionnaireRecordList = questionnaireRecordService.list();
- for (TQuestionnaire tQuestionnaire : list) {
- List<String> userIds = questionnaireRecordList.stream().filter(questionnaireRecord -> questionnaireRecord.getQuestionnaireId().equals(tQuestionnaire.getId())).map(TQuestionnaireRecord::getAppUserId).collect(Collectors.toList());
- tQuestionnaire.setTotalNum(userIds.size());
- if(userId!=null && userIds.contains(userId)){
- tQuestionnaire.setState(2);
- }
- }
- return R.ok(list);
- }
-
- @ApiOperation(value = "问卷调查--获取题干和选项", response = TQuestionnaireStem.class)
- @GetMapping(value = "/getTQuestionnaireStemList/{id}")
- public R<List<TQuestionnaireStem>> getTQuestionnaireStemList(@PathVariable String id) {
- List<TQuestionnaireStem> list = questionnaireStemService.list(new LambdaQueryWrapper<TQuestionnaireStem>().eq(TQuestionnaireStem::getQuestionnaireId, id));
- List<TQuestionnaireStemOption> questionnaireStemOptions = questionnaireStemOptionService.list(new LambdaQueryWrapper<TQuestionnaireStemOption>().in(TQuestionnaireStemOption::getStemId, list.stream().map(TQuestionnaireStem::getId).collect(Collectors.toList())));
- for (TQuestionnaireStem tQuestionnaireStem : list) {
- tQuestionnaireStem.setOptions(questionnaireStemOptions.stream().filter(questionnaireStemOption -> questionnaireStemOption.getStemId().equals(tQuestionnaireStem.getId())).collect(Collectors.toList()));
- }
- return R.ok(list);
- }
-
- @ApiOperation(value = "问卷调查--保存")
- @PostMapping(value = "/saveTQuestionnaire")
- public R<TQuestionnaire> saveTQuestionnaire(@RequestBody SaveTQuestionnaireDto dto) {
- String userId = tokenService.getLoginUserApplet().getUserId();
-
- TQuestionnaire questionnaire = questionnaireService.getById(dto.getQuestionnaireId());
- if(questionnaire.getStatus()==3){
- return R.fail("问卷已结束");
- }
- if(questionnaire.getStatus()==1){
- return R.fail("问卷未开始");
- }
-
- long count = questionnaireRecordService.count(new LambdaQueryWrapper<TQuestionnaireRecord>().eq(TQuestionnaireRecord::getQuestionnaireId, dto.getQuestionnaireId()).eq(TQuestionnaireRecord::getAppUserId, userId));
- if (count > 0) {
- return R.fail("您已作答过此问卷");
- }
- List<String> tQuestionnaireStemOptionIds = dto.getTQuestionnaireStemOptionIds();
- if(!tQuestionnaireStemOptionIds.isEmpty()){
- List<TQuestionnaireStemOption> questionnaireStemOptions = questionnaireStemOptionService.listByIds(tQuestionnaireStemOptionIds);
- for (TQuestionnaireStemOption questionnaireStemOption : questionnaireStemOptions) {
- String answerValue = questionnaireStemOption.getAnswerValue();
- answerValue = answerValue+","+userId;
- questionnaireStemOption.setAnswerValue(answerValue);
- }
- questionnaireStemOptionService.updateBatchById(questionnaireStemOptions);
- }
-
- List<TQuestionnaireStemBriefAnswer> tQuestionnaireStemBriefAnswers = dto.getTQuestionnaireStemBriefAnswers();
- if(!tQuestionnaireStemBriefAnswers.isEmpty()){
- tQuestionnaireStemBriefAnswers.forEach(e->e.setAppUserId(userId));
- questionnaireStemBriefAnswerService.saveBatch(tQuestionnaireStemBriefAnswers);
- }
-
- TQuestionnaireRecord tQuestionnaireRecord = new TQuestionnaireRecord();
- tQuestionnaireRecord.setAppUserId(userId);
- tQuestionnaireRecord.setQuestionnaireId(dto.getQuestionnaireId());
- questionnaireRecordService.save(tQuestionnaireRecord);
- return R.ok();
- }
-
-}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/UserIndexController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/UserIndexController.java
index e64795e..2f48785 100644
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/UserIndexController.java
+++ b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/UserIndexController.java
@@ -2,137 +2,45 @@
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
-import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
-import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ruoyi.common.core.domain.BaseModel;
-import com.ruoyi.common.core.domain.BasePage;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.dto.UpdatePhoneDto;
import com.ruoyi.system.dto.UpdateUserDto;
import com.ruoyi.system.model.TAppUser;
-import com.ruoyi.system.model.TAppealServices;
-import com.ruoyi.system.model.TChildcareServices;
-import com.ruoyi.system.model.TMicroWish;
-import com.ruoyi.system.query.AppealServicesStatusQuery;
-import com.ruoyi.system.query.MicroWishStatusQuery;
import com.ruoyi.system.service.TAppUserService;
-import com.ruoyi.system.service.TAppealServicesService;
-import com.ruoyi.system.service.TChildcareServicesService;
-import com.ruoyi.system.service.TMicroWishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
+import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
+import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
-
-import java.util.Objects;
@Slf4j
@RestController
@RequestMapping("/userIndex")
@Api(tags = "个人中心")
+@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class UserIndexController {
private final TAppUserService tAppUserService;
- private final TChildcareServicesService tChildcareServicesService;
- private final TAppealServicesService tAppealServicesService;
- private final TMicroWishService tMicroWishService;
private final TokenService tokenService;
-
-
- public UserIndexController(TAppUserService tAppUserService, TChildcareServicesService tChildcareServicesService, TAppealServicesService tAppealServicesService, TMicroWishService tMicroWishService, TokenService tokenService) {
- this.tAppUserService = tAppUserService;
- this.tChildcareServicesService = tChildcareServicesService;
- this.tAppealServicesService = tAppealServicesService;
- this.tMicroWishService = tMicroWishService;
- this.tokenService = tokenService;
- }
-
@ApiOperation(value = "个人中心--用户信息",response = TAppUser.class)
@GetMapping(value = "/getUserInfo")
public R<TAppUser> getUserInfo() {
- String userId = tokenService.getLoginUserApplet().getUserId();
+ Integer userId = tokenService.getLoginUserApplet().getUserId();
return R.ok(tAppUserService.getById(userId));
}
-
-
- @ApiOperation(value = "个人中心--托育服务记录",response = TChildcareServices.class)
- @PostMapping(value = "/getChildcareServicesList")
- public R<Page<TChildcareServices>> getChildcareServicesList(@RequestBody BasePage basePage) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- Page<TChildcareServices> page = new Page<>(basePage.getPageNum(), basePage.getPageSize());
- Page<TChildcareServices> childcareServicesPage = tChildcareServicesService.page(page, Wrappers.<TChildcareServices>lambdaQuery().eq(TChildcareServices::getAppUserId, userId).orderByDesc(BaseModel::getCreateTime));
- return R.ok(childcareServicesPage);
- }
-
-
- @ApiOperation(value = "个人中心--托育服务记录详情",response = TChildcareServices.class)
- @GetMapping(value = "/getChildcareServicesDetail/{id}")
- public R<TChildcareServices> getChildcareServicesDetail(@PathVariable String id) {
- TChildcareServices childcareServices = tChildcareServicesService.getById(id);
- return R.ok(childcareServices);
- }
-
-
- @ApiOperation(value = "个人中心--诉求服务记录",response = TAppealServices.class)
- @PostMapping(value = "/getAppealServicesList")
- public R<Page<TAppealServices>> getAppealServicesList(@RequestBody AppealServicesStatusQuery query) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- Page<TAppealServices> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TAppealServices> appealServicesPage = tAppealServicesService.page(page, Wrappers.<TAppealServices>lambdaQuery().eq(TAppealServices::getAppUserId, userId).eq(TAppealServices::getAppealType,1).eq(Objects.nonNull(query.getStatus()), TAppealServices::getStatus, query.getStatus()).orderByDesc(BaseModel::getCreateTime));
- return R.ok(appealServicesPage);
- }
-
-
- @ApiOperation(value = "个人中心--诉求服务记录/随手拍详情",response = TAppealServices.class)
- @GetMapping(value = "/getAppealServicesDetail/{id}")
- public R<TAppealServices> getAppealServicesList(@PathVariable String id) {
- TAppealServices appealServices = tAppealServicesService.getById(id);
- return R.ok(appealServices);
- }
-
-
- @ApiOperation(value = "个人中心--随手拍记录",response = TAppealServices.class)
- @PostMapping(value = "/getSnapShareList")
- public R<Page<TAppealServices>> getSnapShareList(@RequestBody AppealServicesStatusQuery query) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- Page<TAppealServices> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TAppealServices> appealServicesPage = tAppealServicesService.page(page, Wrappers.<TAppealServices>lambdaQuery().eq(TAppealServices::getAppUserId, userId).eq(TAppealServices::getAppealType,2).eq(Objects.nonNull(query.getStatus()), TAppealServices::getStatus, query.getStatus()).orderByDesc(BaseModel::getCreateTime));
- return R.ok(appealServicesPage);
- }
-
-
- @ApiOperation(value = "个人中心--微心愿记录",response = TMicroWish.class)
- @PostMapping(value = "/getMicroWishList")
- public R<Page<TMicroWish>> getMicroWishList(@RequestBody MicroWishStatusQuery query) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- Page<TMicroWish> page = new Page<>(query.getPageNum(), query.getPageSize());
- Page<TMicroWish> microWishPage = tMicroWishService.page(page, Wrappers.<TMicroWish>lambdaQuery()
- .eq(TMicroWish::getAppUserId, userId)
- .eq(Objects.nonNull(query.getStatus()), TMicroWish::getStatus, query.getStatus())
- .orderByDesc(BaseModel::getCreateTime));
- return R.ok(microWishPage);
- }
-
- @ApiOperation(value = "个人中心--微心愿详情",response = TMicroWish.class)
- @GetMapping(value = "/getMicroWishDetail/{id}")
- public R<TMicroWish> getMicroWishDetail(@PathVariable String id) {
- TMicroWish microWish = tMicroWishService.getById(id);
- return R.ok(microWish);
- }
-
@ApiOperation(value = "个人中心--修改手机号")
@PostMapping(value = "/updatePhone")
public R<?> getMicroWishDetail(@RequestBody UpdatePhoneDto dto) {
- String userId = tokenService.getLoginUserApplet().getUserId();
- long count = tAppUserService.count(new LambdaQueryWrapper<TAppUser>().eq(TAppUser::getPhoneNumber, dto.getPhone()).ne(TAppUser::getId, userId));
+ Integer userId = tokenService.getLoginUserApplet().getUserId();
+ long count = tAppUserService.count(new LambdaQueryWrapper<TAppUser>().eq(TAppUser::getPhone, dto.getPhone()).ne(TAppUser::getId, userId));
if (count > 0) {
return R.fail("手机号已存在");
}
- tAppUserService.update(new LambdaUpdateWrapper<TAppUser>().set(TAppUser::getPhoneNumber, dto.getPhone()).eq(TAppUser::getId, userId));
+ tAppUserService.update(new LambdaUpdateWrapper<TAppUser>().set(TAppUser::getPhone, dto.getPhone()).eq(TAppUser::getId, userId));
return R.ok();
}
@@ -140,15 +48,15 @@
@ApiOperation(value = "个人中心--修改信息")
@PostMapping(value = "/updateUserInfo")
public R<?> updateUserInfo(@RequestBody UpdateUserDto dto) {
- String userId = tokenService.getLoginUserApplet().getUserId();
+ Integer userId = tokenService.getLoginUserApplet().getUserId();
TAppUser appUser = tAppUserService.getById(userId);
if(dto.getAvatar()!=null){
- appUser.setAvatar(dto.getAvatar());
+ appUser.setProfilePhoto(dto.getAvatar());
}
if(dto.getNickName()!=null){
- appUser.setNickName(dto.getNickName());
+ appUser.setName(dto.getNickName());
}
if(dto.getGender()!=null){
@@ -156,7 +64,7 @@
}
if(dto.getBirthday()!=null){
- appUser.setBirthDate(dto.getBirthday());
+ appUser.setBirthday(dto.getBirthday());
}
if(dto.getName()!=null){
@@ -165,11 +73,11 @@
if(dto.getPhone()!=null){
- long count = tAppUserService.count(new LambdaQueryWrapper<TAppUser>().eq(TAppUser::getPhoneNumber, dto.getPhone()).ne(TAppUser::getId, userId));
+ long count = tAppUserService.count(new LambdaQueryWrapper<TAppUser>().eq(TAppUser::getPhone, dto.getPhone()).ne(TAppUser::getId, userId));
if (count > 0) {
return R.fail("手机号已存在");
}
- appUser.setPhoneNumber(dto.getPhone());
+ appUser.setPhone(dto.getPhone());
}
tAppUserService.updateById(appUser);
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/WxPayController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/WxPayController.java
index d8f3d6f..ea8481b 100644
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/WxPayController.java
+++ b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/api/WxPayController.java
@@ -1,35 +1,27 @@
package com.ruoyi.web.controller.api;
import com.alibaba.fastjson2.JSONObject;
-import com.baomidou.mybatisplus.core.toolkit.Wrappers;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.ruoyi.common.core.domain.R;
-import com.ruoyi.common.utils.CodeGenerateUtils;
import com.ruoyi.framework.web.service.TokenService;
-import com.ruoyi.system.model.TCourseOrder;
-import com.ruoyi.system.service.TCourseOrderService;
import com.ruoyi.system.wxPay.enums.RefundEnum;
import com.ruoyi.system.wxPay.enums.TradeStateEnum;
import com.ruoyi.system.wxPay.model.WeixinPayProperties;
-import com.ruoyi.system.wxPay.utils.WxTimeUtils;
import com.ruoyi.system.wxPay.utils.WxV3Pay;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
-import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.CrossOrigin;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
-import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
-import java.util.Map;
-import java.util.Objects;
/**
* 微信相关接口
@@ -46,9 +38,6 @@
private TokenService tokenService;
@Autowired
private WeixinPayProperties weixinPayProperties;
-
- @Autowired
- private TCourseOrderService courseOrderService;
@@ -81,15 +70,9 @@
String success_time = jsonInfo.getString("success_time");
// 查询订单
- TCourseOrder order = courseOrderService.getOne(Wrappers.lambdaQuery(TCourseOrder.class)
- .eq(TCourseOrder::getOrderNumber, out_trade_no).last("LIMIT 1"));
if (trade_state.equals(TradeStateEnum.SUCCESS.name())) {
log.info("回调成功");
// 订单号查询订单
- order.setPayStatus(2);
- order.setPayTime(WxTimeUtils.dateToLocalDateTime(WxTimeUtils.toRfc3339Date(success_time)));
- order.setTransactionId(transaction_id);
- courseOrderService.updateById(order);
PrintWriter out = response.getWriter();
out.print("SUCCESS");
@@ -103,27 +86,6 @@
}
- /**
- * 退款回调
- */
-// @PostMapping("refund/notify")
-// @ApiOperation("退款回调")
-// public void refundNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
-// try {
-//// System.err.println("微信回调");
-//// BufferedReader reader = request.getReader();
-//// StringBuilder requestBody = new StringBuilder();
-//// String line;
-//// while ((line = reader.readLine()) != null) {
-//// requestBody.append(line);
-//// }
-//// System.err.println("全部请求体" + requestBody);
-//// JSONObject jsonObject = JSONObject.parseObject(requestBody.toString());
-//// JSONObject resource = jsonObject.getJSONObject("resource");
-//// AesUtil aesUtil = new AesUtil(weixinPayProperties.getV3().getApiKey().getBytes(StandardCharsets.UTF_8));
-//// String decryptedData = aesUtil.decryptToString(resource.getString("associated_data").getBytes(StandardCharsets.UTF_8), resource.getString("nonce").getBytes(StandardCharsets.UTF_8), resource.getString("ciphertext"))
-// }
-// }
@PostMapping("refund/notify")
public void refundNotify(HttpServletRequest request) throws IOException {
try {
@@ -155,12 +117,7 @@
// 微信支付订单号
String transaction_id = params.get("transaction_id").toString();
if (tradeState.equals(RefundEnum.SUCCESS.name())) {
- TCourseOrder order = courseOrderService.getOne(Wrappers.lambdaQuery(TCourseOrder.class)
- .eq(TCourseOrder::getRefundNumber, out_refund_no).last("LIMIT 1"));
- order.setPayStatus(3);
- order.setRefundStatus(2);
- order.setRefundTransactionId(transaction_id);
- courseOrderService.updateById(order);
+
wxV3Pay.ack();
}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java
index c4f95cf..3bde689 100644
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java
+++ b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java
@@ -9,6 +9,7 @@
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.TAppUserResp;
import com.ruoyi.common.core.domain.model.LoginAppBody;
+import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUserApplet;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.redis.service.RedisService;
@@ -23,10 +24,8 @@
import com.ruoyi.system.utils.wx.body.resp.Code2SessionRespBody;
import com.ruoyi.system.utils.wx.body.resq.Code2SessionResqBody;
import com.ruoyi.system.utils.wx.model.WeixinProperties;
-import com.ruoyi.system.utils.wx.pojo.AppletUserDecodeData;
import com.ruoyi.system.utils.wx.pojo.AppletUserEncrypteData;
import com.ruoyi.system.utils.wx.tools.WxAppletTools;
-import com.ruoyi.system.utils.wx.tools.WxUtils;
import com.ruoyi.web.controller.tool.MsgUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -34,16 +33,14 @@
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.concurrent.TimeUnit;
/**
* 登录验证
@@ -79,6 +76,51 @@
private RedisService redisService;
@Autowired
private TAppUserService appUserService;
+
+ /**
+ * 获取验证码
+ *
+ * @param phone 手机号
+ * @return 结果
+ */
+ @ApiOperation(value = "获取验证码",notes = "获取验证码")
+ @GetMapping("/getCode")
+ public AjaxResult getCode(@RequestParam String phone)
+ {
+ // 发送验证码并存储到redis
+ if (StringUtils.hasLength(phone)) {
+
+ String code = String.valueOf((int) (Math.random() * 1000000));
+ redisCache.setCacheObject(phone, code,5*60, TimeUnit.SECONDS);
+ try {
+ //TODO 待对接
+// smsUtil.sendSms(phone, "2369926", new String[]{code});
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ return AjaxResult.success("发送短信验证码成功!5分钟内有效");
+ }
+ return AjaxResult.error(500, "发送短信验证码失败,请确认手机号码!");
+ }
+
+ /**
+ * 账号密码登录
+ *
+ * @param loginBody 登录信息
+ * @return 结果
+ */
+ @ApiOperation(value = "短信登录",notes = "短信登录")
+ @PostMapping("/loginCode")
+ public AjaxResult loginCode(@RequestBody LoginBody loginBody)
+ {
+ AjaxResult ajax = AjaxResult.success();
+ // 生成令牌
+ LoginUserApplet loginUser = loginService.loginCodeApplet(loginBody.getUsername(), loginBody.getCode());
+ ajax.put(Constants.TOKEN, tokenService.createTokenApplet(loginUser));
+ ajax.put("userInfo",loginUser);
+ return ajax;
+ }
+
/**
* 账号密码登录
*
@@ -92,7 +134,7 @@
LoginAppBody loginAppBody = JSON.parseObject(param, LoginAppBody.class);
AjaxResult ajax = AjaxResult.success();
// 生成令牌
- LoginUserApplet loginUser = loginService.loginCodeApplet(loginAppBody.getAccount(), loginAppBody.getPassword());
+ LoginUserApplet loginUser = loginService.loginPwdApplet(loginAppBody.getAccount(), loginAppBody.getPassword());
ajax.put(Constants.TOKEN, tokenService.createTokenApplet(loginUser));
ajax.put("data",loginUser);
return ajax;
@@ -117,11 +159,11 @@
// appletUserDecodeData.setOpenId(openid);
// 先使用openId和当前手机号进行查询
TAppUser sysAppUser = appUserService.getOne(Wrappers.lambdaQuery(TAppUser.class)
- .and(e->e.eq(TAppUser::getOpenId, openid)));
+ .and(e->e.eq(TAppUser::getOpenid, openid)));
if (sysAppUser==null){
sysAppUser = new TAppUser();
// sysAppUser.setPhoneNumber(appletUserDecodeData.getPhoneNumber());
- sysAppUser.setOpenId(openid);
+ sysAppUser.setOpenid(openid);
// 手机号中间四位替换为*
// sysAppUser.setNickName(appletUserDecodeData.getPhoneNumber().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
appUserService.save(sysAppUser);
@@ -131,7 +173,7 @@
return R.fail("账号已冻结,请联系管理员");
}
// 手机号相同但openId为空的情况
- sysAppUser.setOpenId(openid);
+ sysAppUser.setOpenid(openid);
appUserService.updateById(sysAppUser);
}
LoginUserApplet loginUserApplet = new LoginUserApplet();
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketAuthHandler.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketAuthHandler.java
deleted file mode 100644
index ce5e7d2..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketAuthHandler.java
+++ /dev/null
@@ -1,222 +0,0 @@
-//package com.ruoyi.web.controller.webSocket;
-//
-//import com.ruoyi.common.constant.Constants;
-//import com.ruoyi.common.core.domain.model.LoginUserApplet;
-//import com.ruoyi.common.core.redis.RedisCache;
-//import io.jsonwebtoken.Claims;
-//import io.jsonwebtoken.Jwts;
-//import lombok.extern.slf4j.Slf4j;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.beans.factory.annotation.Value;
-//import org.springframework.stereotype.Component;
-//import org.springframework.util.StringUtils;
-//
-//import java.util.Map;
-//
-///**
-// * WebSocket认证处理器
-// * 处理WebSocket连接的用户认证逻辑
-// */
-//@Component
-//@Slf4j
-//public class WebSocketAuthHandler {
-//
-//
-// @Autowired
-// private RedisCache redisCache;
-//
-// // 令牌秘钥
-// @Value("${token.secret}")
-// private String secret;
-//
-// /**
-// * 验证用户认证信息
-// * @param appUserId 用户ID
-// * @param token 认证令牌(可选)
-// * @return 认证结果
-// */
-// public AuthResult authenticateUser(String appUserId, String token) {
-// try {
-// if (appUserId == null || appUserId.trim().isEmpty()) {
-// return AuthResult.failure("用户ID不能为空");
-// }
-//
-//
-// return AuthResult.success();
-// } catch (Exception e) {
-// log.error("用户认证失败,用户ID: {}, 错误: {}", appUserId, e.getMessage(), e);
-// return AuthResult.failure("认证过程中发生错误: " + e.getMessage());
-// }
-// }
-//
-// /**
-// * 验证token
-// * @param appUserId 用户ID
-// * @param token 令牌
-// * @return 是否有效
-// */
-// private boolean validateToken(String appUserId, String token) {
-// try {
-// if (!StringUtils.hasText(token)) {
-// log.debug("用户 {} 未提供token,跳过token验证", appUserId);
-// return true; // 如果没有提供token,允许通过(可以根据业务需求调整)
-// }
-//
-// // 移除Bearer前缀
-// if (token.startsWith(Constants.TOKEN_PREFIX)) {
-// token = token.replace(Constants.TOKEN_PREFIX, "");
-// }
-//
-// // 解析JWT token
-// Claims claims = parseToken(token);
-// if (claims == null) {
-// log.warn("用户 {} 的token解析失败", appUserId);
-// return false;
-// }
-//
-// // 从token中获取用户标识
-// String uuid = (String) claims.get(Constants.LOGIN_USER_APPLET_KEY);
-// if (!StringUtils.hasText(uuid)) {
-// log.warn("用户 {} 的token中未找到用户标识", appUserId);
-// return false;
-// }
-//
-// // 从Redis中获取用户登录信息
-// String userKey = getTokenKey(uuid);
-// LoginUserApplet loginUser = redisCache.getCacheObject(userKey);
-//
-// if (loginUser == null) {
-// log.warn("用户 {} 的登录信息已过期或不存在", appUserId);
-// return false;
-// }
-//
-// // 验证用户ID是否匹配
-// if (!appUserId.equals(loginUser.getUserId())) {
-// log.warn("用户 {} 的token与提供的用户ID不匹配", appUserId);
-// return false;
-// }
-//
-// // 验证token是否过期
-// long currentTime = System.currentTimeMillis();
-// if (loginUser.getExpireTime() != null && loginUser.getExpireTime() < currentTime) {
-// log.warn("用户 {} 的token已过期", appUserId);
-// return false;
-// }
-//
-// log.debug("用户 {} 的token验证成功", appUserId);
-// return true;
-//
-// } catch (Exception e) {
-// log.error("验证用户 {} 的token时发生错误: {}", appUserId, e.getMessage(), e);
-// return false;
-// }
-// }
-//
-// /**
-// * 解析JWT token
-// * @param token JWT token
-// * @return Claims对象
-// */
-// private Claims parseToken(String token) {
-// try {
-// return Jwts.parser()
-// .setSigningKey(secret)
-// .parseClaimsJws(token)
-// .getBody();
-// } catch (Exception e) {
-// log.error("解析token失败: {}", e.getMessage());
-// return null;
-// }
-// }
-//
-// /**
-// * 获取token在Redis中的key
-// * @param uuid 用户唯一标识
-// * @return Redis key
-// */
-// private String getTokenKey(String uuid) {
-// return com.ruoyi.common.constant.CacheConstants.LOGIN_TOKEN_KEY + uuid;
-// }
-//
-// /**
-// * 认证结果类
-// */
-// public static class AuthResult {
-// private final boolean success;
-// private final String message;
-//// private final TAppUser appUser;
-//
-// private AuthResult(boolean success, String message) {
-// this.success = success;
-// this.message = message;
-//// this.appUser = appUser;
-// }
-//
-//// public static AuthResult success(TAppUser appUser) {
-//// return new AuthResult(true, "认证成功", appUser);
-//// }
-////
-//// public static AuthResult failure(String message) {
-//// return new AuthResult(false, message, null);
-//// }
-////
-//// public boolean isSuccess() {
-//// return success;
-//// }
-////
-//// public String getMessage() {
-//// return message;
-//// }
-////
-//// public TAppUser getAppUser() {
-//// return appUser;
-//// }
-// }
-//
-// /**
-// * 从认证消息中提取用户信息
-// * @param messageObj 消息对象
-// * @return 用户认证信息
-// */
-// public UserAuthInfo extractAuthInfo(Map<String, Object> messageObj) {
-// String appUserId = (String) messageObj.get("appUserId");
-// String token = (String) messageObj.get("token");
-// String deviceId = (String) messageObj.get("deviceId");
-// String deviceType = (String) messageObj.get("deviceType");
-//
-// return new UserAuthInfo(appUserId, token, deviceId, deviceType);
-// }
-//
-// /**
-// * 用户认证信息类
-// */
-// public static class UserAuthInfo {
-// private final String appUserId;
-// private final String token;
-// private final String deviceId;
-// private final String deviceType;
-//
-// public UserAuthInfo(String appUserId, String token, String deviceId, String deviceType) {
-// this.appUserId = appUserId;
-// this.token = token;
-// this.deviceId = deviceId;
-// this.deviceType = deviceType;
-// }
-//
-// public String getAppUserId() {
-// return appUserId;
-// }
-//
-// public String getToken() {
-// return token;
-// }
-//
-// public String getDeviceId() {
-// return deviceId;
-// }
-//
-// public String getDeviceType() {
-// return deviceType;
-// }
-// }
-//}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketController.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketController.java
deleted file mode 100644
index 47aa617..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketController.java
+++ /dev/null
@@ -1,296 +0,0 @@
-package com.ruoyi.web.controller.webSocket;
-
-import com.alibaba.fastjson.JSONObject;
-import com.ruoyi.common.core.controller.BaseController;
-import com.ruoyi.common.core.domain.R;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * WebSocket控制器
- * 提供REST接口用于触发服务端主动发送消息
- * 支持基于AppUser的消息发送
- */
-@RestController
-@RequestMapping("/open/websocket")
-@Slf4j
-@Api(tags = "socket")
-public class WebSocketController extends BaseController {
-
-
- @Autowired
- private WebSocketUserService webSocketUserService;
-
- // ==================== 基于AppUser的WebSocket接口 ====================
-
- /**
- * 向指定用户发送消息
- * @param appUserId 用户ID
- * @param request 请求参数
- * @return 操作结果
- */
- @PostMapping("/user/send/{appUserId}")
- @ApiOperation(value = "发送信息")
- public R<String> sendMessageToUser(@PathVariable String appUserId, @RequestBody Map<String, String> request) {
- try {
- String message = JSONObject.toJSONString(request);
- if (message == null || message.trim().isEmpty()) {
- return R.fail("消息内容不能为空");
- }
-
- int deviceCount = webSocketUserService.sendMessageToUser(appUserId, message);
- if (deviceCount > 0) {
- return R.ok("消息发送成功,发送到 " + deviceCount + " 个设备");
- } else {
- return R.fail("用户不在线或发送失败");
- }
- } catch (Exception e) {
- log.error("向用户发送消息失败", e);
- return R.fail("发送消息失败: " + e.getMessage());
- }
- }
-
- @GetMapping("/user/send1/{appUserId}")
- @ApiOperation(value = "发送信息")
- public R<String> sendMessageToUser1(@PathVariable String appUserId) {
- try {
- String message = "{\"type\":\"mission_push\",\"content\":\"{\\\"missionId\\\":\\\"1983875114637811713\\\"}\",\"timestamp\":\"2025-10-27T09:22:45.681\"}";
- if (message == null || message.trim().isEmpty()) {
- return R.fail("消息内容不能为空");
- }
-
- int deviceCount = webSocketUserService.sendMessageToUser(appUserId, message);
- if (deviceCount > 0) {
- return R.ok("消息发送成功,发送到 " + deviceCount + " 个设备");
- } else {
- return R.fail("用户不在线或发送失败");
- }
- } catch (Exception e) {
- log.error("向用户发送消息失败", e);
- return R.fail("发送消息失败: " + e.getMessage());
- }
- }
-
- /**
- * 向指定用户发送JSON格式消息
- * @param appUserId 用户ID
- * @param request 请求参数
- * @return 操作结果
- */
- @PostMapping("/user/send-json/{appUserId}")
- public R<String> sendJsonMessageToUser(@PathVariable String appUserId, @RequestBody Map<String, Object> request) {
- try {
- String messageType = (String) request.get("messageType");
- Object data = request.get("data");
-
- if (messageType == null || messageType.trim().isEmpty()) {
- return R.fail("消息类型不能为空");
- }
-
- int deviceCount = webSocketUserService.sendJsonMessageToUser(appUserId, messageType, data);
- if (deviceCount > 0) {
- return R.ok("JSON消息发送成功,发送到 " + deviceCount + " 个设备");
- } else {
- return R.fail("用户不在线或发送失败");
- }
- } catch (Exception e) {
- log.error("向用户发送JSON消息失败", e);
- return R.fail("发送消息失败: " + e.getMessage());
- }
- }
-
- /**
- * 向多个用户发送消息
- * @param request 请求参数
- * @return 操作结果
- */
- @PostMapping("/user/send-multiple")
- public R<String> sendMessageToUsers(@RequestBody Map<String, Object> request) {
- try {
- @SuppressWarnings("unchecked")
- List<String> appUserIds = (List<String>) request.get("appUserIds");
- String message = (String) request.get("message");
-
- if (appUserIds == null || appUserIds.isEmpty()) {
- return R.fail("用户ID列表不能为空");
- }
- if (message == null || message.trim().isEmpty()) {
- return R.fail("消息内容不能为空");
- }
-
- int successUserCount = webSocketUserService.sendMessageToUsers(appUserIds, message);
- return R.ok("消息发送完成,成功发送到 " + successUserCount + " 个用户");
- } catch (Exception e) {
- log.error("向多个用户发送消息失败", e);
- return R.fail("发送消息失败: " + e.getMessage());
- }
- }
-
- /**
- * 发送任务分配消息
- * @param request 请求参数
- * @return 操作结果
- */
- @PostMapping("/user/task-assignment")
- public R<String> sendTaskAssignment(@RequestBody Map<String, String> request) {
- try {
- String taskId = request.get("taskId");
- String taskName = request.get("taskName");
- String assignee = request.get("assignee");
- String assigneeUserId = request.get("assigneeUserId");
-
- if (taskId == null || taskName == null || assignee == null) {
- return R.fail("任务ID、任务名称和分配人不能为空");
- }
-
- int successCount = webSocketUserService.sendTaskAssignment(taskId, taskName, assignee, assigneeUserId);
- return R.ok("任务分配消息发送完成,成功发送到 " + successCount + " 个设备");
- } catch (Exception e) {
- log.error("发送任务分配消息失败", e);
- return R.fail("发送任务分配消息失败: " + e.getMessage());
- }
- }
-
- /**
- * 发送状态更新消息
- * @param request 请求参数
- * @return 操作结果
- */
- @PostMapping("/user/status-update")
- public R<String> sendStatusUpdate(@RequestBody Map<String, String> request) {
- try {
- String status = request.get("status");
- String details = request.get("details");
- String targetUserId = request.get("targetUserId");
-
- if (status == null || status.trim().isEmpty()) {
- return R.fail("状态不能为空");
- }
-
- int successCount = webSocketUserService.sendStatusUpdate(status, details, targetUserId);
- return R.ok("状态更新消息发送完成,成功发送到 " + successCount + " 个设备");
- } catch (Exception e) {
- log.error("发送状态更新消息失败", e);
- return R.fail("发送状态更新消息失败: " + e.getMessage());
- }
- }
-
- /**
- * 发送任务状态更新消息
- * @param request 请求参数
- * @return 操作结果
- */
- @PostMapping("/user/task-status-update")
- public R<String> sendTaskStatusUpdate(@RequestBody Map<String, String> request) {
- try {
- String taskId = request.get("taskId");
- String taskStatus = request.get("taskStatus");
- String message = request.get("message");
- String targetUserId = request.get("targetUserId");
-
- if (taskId == null || taskStatus == null) {
- return R.fail("任务ID和任务状态不能为空");
- }
-
- int successCount = webSocketUserService.sendTaskStatusUpdate(taskId, taskStatus, message, targetUserId);
- return R.ok("任务状态更新消息发送完成,成功发送到 " + successCount + " 个设备");
- } catch (Exception e) {
- log.error("发送任务状态更新消息失败", e);
- return R.fail("发送任务状态更新消息失败: " + e.getMessage());
- }
- }
-
- /**
- * 发送位置更新消息
- * @param request 请求参数
- * @return 操作结果
- */
- @PostMapping("/user/location-update")
- public R<String> sendLocationUpdate(@RequestBody Map<String, String> request) {
- try {
- String userId = request.get("userId");
- String longitude = request.get("longitude");
- String latitude = request.get("latitude");
- String address = request.get("address");
-
- if (userId == null || longitude == null || latitude == null) {
- return R.fail("用户ID、经度和纬度不能为空");
- }
-
- int successCount = webSocketUserService.sendLocationUpdate(userId, longitude, latitude, address);
- return R.ok("位置更新消息发送完成,成功发送到 " + successCount + " 个设备");
- } catch (Exception e) {
- log.error("发送位置更新消息失败", e);
- return R.fail("发送位置更新消息失败: " + e.getMessage());
- }
- }
-
- /**
- * 获取用户连接信息
- * @param appUserId 用户ID
- * @return 连接信息
- */
- @GetMapping("/user/info/{appUserId}")
- public R getUserConnectionInfo(@PathVariable String appUserId) {
- try {
- Map<String, Object> info = webSocketUserService.getUserConnectionInfo(appUserId);
- return R.ok(info, "获取用户连接信息成功");
- } catch (Exception e) {
- log.error("获取用户连接信息失败", e);
- return R.fail("获取用户连接信息失败: " + e.getMessage());
- }
- }
-
- /**
- * 获取所有连接统计信息
- * @return 统计信息
- */
- @GetMapping("/user/stats")
- public R getConnectionStats() {
- try {
- Map<String, Object> stats = webSocketUserService.getConnectionStats();
- return R.ok(stats, "获取连接统计信息成功");
- } catch (Exception e) {
- log.error("获取连接统计信息失败", e);
- return R.fail("获取连接统计信息失败: " + e.getMessage());
- }
- }
-
- /**
- * 检查用户是否在线
- * @param appUserId 用户ID
- * @return 检查结果
- */
- @GetMapping("/user/online/{appUserId}")
- public R checkUserOnline(@PathVariable String appUserId) {
- try {
- boolean isOnline = webSocketUserService.isUserOnline(appUserId);
- return R.ok(isOnline, "用户在线状态检查完成");
- } catch (Exception e) {
- log.error("检查用户在线状态失败", e);
- return R.fail("检查用户在线状态失败: " + e.getMessage());
- }
- }
-
- /**
- * 获取在线用户列表
- * @return 在线用户列表
- */
- @GetMapping("/user/online-list")
- public R getOnlineUserIds() {
- try {
- Set<String> onlineUserIds = webSocketUserService.getOnlineUserIds();
- return R.ok(onlineUserIds, "获取在线用户列表成功");
- } catch (Exception e) {
- log.error("获取在线用户列表失败", e);
- return R.fail("获取在线用户列表失败: " + e.getMessage());
- }
- }
-}
\ No newline at end of file
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketServer.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketServer.java
deleted file mode 100644
index 2bcaee0..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketServer.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package com.ruoyi.web.controller.webSocket;
-
-import io.netty.bootstrap.ServerBootstrap;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelInitializer;
-import io.netty.channel.ChannelOption;
-import io.netty.channel.ChannelPipeline;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioServerSocketChannel;
-import io.netty.handler.codec.http.HttpObjectAggregator;
-import io.netty.handler.codec.http.HttpServerCodec;
-import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
-import io.netty.handler.logging.LogLevel;
-import io.netty.handler.logging.LoggingHandler;
-import io.netty.handler.stream.ChunkedWriteHandler;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-@Slf4j
-public class WebSocketServer {
- private final int port;
-
- @Autowired
- private WebSocketTextFrameHandler webSocketTextFrameHandler;
-
- public WebSocketServer() {
- this.port = 8889; // 默认端口
- }
-
- public WebSocketServer(int port) {
- this.port = port;
- }
-
- public void run() throws InterruptedException {
- NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
- NioEventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap serverBootstrap = new ServerBootstrap();
- serverBootstrap.group(bossGroup, workerGroup)
- .channel(NioServerSocketChannel.class)
- .option(ChannelOption.SO_BACKLOG, 128)
- .childOption(ChannelOption.SO_KEEPALIVE, true)
- .handler(new LoggingHandler(LogLevel.INFO)) // 在BossGroup中增加一个日志处理器 日志级别为INFO
- .childHandler(new ChannelInitializer<SocketChannel>() {
- @Override
- protected void initChannel(SocketChannel ch) throws Exception {
- ChannelPipeline pipeline = ch.pipeline();
- // 因为是基于Http协议的所以采用Http的编解码器
- pipeline.addLast(new HttpServerCodec());
- // 是以块的方式写, 添加ChunkedWriteHandler(分块写入处理程序)
- pipeline.addLast(new ChunkedWriteHandler());
- /*
- * http 数据在传输过程中是分段的 http Object aggregator 就是可以将多个段聚合
- * 这就是为什么 当浏览器发送大量数据时, 就会出现多次http请求
- * 参数为 : 最大内容长度
- */
- pipeline.addLast(new HttpObjectAggregator(8192));
- /*
- * 对应WebSocket 他的数据时以桢(frame) 形式传递
- * 可以看到WebSocketFrame下面有6个子类
- * 浏览器请求时: ws://localhost:7000/xxx 请求的url
- * 核心功能是将http协议升级为ws协议 保持长链接
- */
- pipeline.addLast(new WebSocketServerProtocolHandler("/websocket"));
- // 自定义Handler, 处理业务逻辑
- // 使用@Sharable注解的Handler,可以被多个连接共享
- pipeline.addLast(webSocketTextFrameHandler);
- }
- });
- log.info("WebSocket服务器启动中,端口: {}", port);
- ChannelFuture sync = serverBootstrap.bind(port).sync();
- sync.channel().closeFuture().sync();
- } catch (InterruptedException e) {
- log.error("WebSocket服务器启动失败", e);
- } finally {
- bossGroup.shutdownGracefully();
- workerGroup.shutdownGracefully();
- }
-
- }
-
-// public static void main(String[] args) throws InterruptedException {
-// new WebSocketServer(7000).run();
-// }
-}
\ No newline at end of file
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketServerConfig.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketServerConfig.java
deleted file mode 100644
index 202abdc..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketServerConfig.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.ruoyi.web.controller.webSocket;
-
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.CommandLineRunner;
-import org.springframework.stereotype.Component;
-
-/**
- * WebSocket服务器配置类
- * 在Spring Boot应用启动时自动启动WebSocket服务器
- */
-@Component
-@Slf4j
-public class WebSocketServerConfig implements CommandLineRunner {
-
- @Autowired
- private WebSocketServer webSocketServer;
-
- @Override
- public void run(String... args) throws Exception {
- // 在新线程中启动WebSocket服务器,避免阻塞主线程
- new Thread(() -> {
- try {
- log.info("正在启动WebSocket服务器...");
- webSocketServer.run();
- } catch (InterruptedException e) {
- log.error("WebSocket服务器启动失败", e);
- Thread.currentThread().interrupt();
- }
- }, "WebSocket-Server-Thread").start();
- }
-}
\ No newline at end of file
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketTextFrameHandler.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketTextFrameHandler.java
deleted file mode 100644
index 6aa6c90..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketTextFrameHandler.java
+++ /dev/null
@@ -1,189 +0,0 @@
-package com.ruoyi.web.controller.webSocket;
-
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONObject;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-import org.springframework.util.StringUtils;
-
-import java.time.LocalDateTime;
-
-/**
- * TextWebSocketFrame 表示一个文本桢
- * 使用@Sharable注解使其可以被多个连接共享
- * 支持基于AppUser的连接管理
- */
-@Component
-@Slf4j
-@ChannelHandler.Sharable
-public class WebSocketTextFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
-
-
- @Autowired
- private WebSocketUserConnectionManager userConnectionManager;
-
-// @Autowired
-// private WebSocketAuthHandler authHandler;
-
- @Override
- protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
- String message = msg.text();
- log.info("[服务器] : 收到消息 -> {}", message);
-
- try {
- // 尝试解析消息,检查是否包含用户认证信息
- JSONObject messageObj = JSON.parseObject(message);
- String messageType = messageObj.getString("type");
-
- if ("auth".equals(messageType)) {
- // 处理用户认证消息
- handleUserAuth(ctx, messageObj);
- } else if ("ping".equals(messageType)) {
- // 处理心跳消息
- handlePing(ctx, messageObj);
- } else {
- // 处理普通业务消息
- handleBusinessMessage(ctx, messageObj);
- }
- } catch (Exception e) {
- // 如果不是JSON格式,按普通文本处理
- log.debug("消息不是JSON格式,按普通文本处理: {}", message);
- ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间: " + LocalDateTime.now() + "->" + message));
- }
- }
-
- /**
- * 处理用户认证消息
- */
- private void handleUserAuth(ChannelHandlerContext ctx, JSONObject messageObj) {
- try {
- // 提取认证信息
-// WebSocketAuthHandler.UserAuthInfo authInfo = authHandler.extractAuthInfo(messageObj);
-// String appUserId = authInfo.getAppUserId();
-// String token = authInfo.getToken();
-
-// if (!StringUtils.hasText(appUserId)) {
-// sendAuthFailureResponse(ctx, "用户ID不能为空");
-// return;
-// }
-
- // 进行用户认证
-// WebSocketAuthHandler.AuthResult authResult = authHandler.authenticateUser(appUserId, token);
-//
-// if (authResult.isSuccess()) {
-// // 认证成功,将连接与用户关联
-// userConnectionManager.addUserConnection(appUserId, ctx.channel());
-//
-// // 发送认证成功响应
-// JSONObject response = new JSONObject();
-// response.put("type", "auth_success");
-// response.put("appUserId", appUserId);
-// response.put("nickName", authResult.getAppUser().getNickName());
-// response.put("message", "认证成功");
-// response.put("timestamp", LocalDateTime.now().toString());
-//
-// ctx.channel().writeAndFlush(new TextWebSocketFrame(response.toJSONString()));
-// log.info("用户 {} ({}) 认证成功,ChannelId: {}",
-// appUserId, authResult.getAppUser().getNickName(), ctx.channel().id().asLongText());
-// } else {
-// // 认证失败
-// sendAuthFailureResponse(ctx, authResult.getMessage());
-// log.warn("用户 {} 认证失败: {}, ChannelId: {}",
-// appUserId, authResult.getMessage(), ctx.channel().id().asLongText());
-// }
- } catch (Exception e) {
- log.error("处理用户认证时发生错误", e);
- sendAuthFailureResponse(ctx, "认证过程中发生错误: " + e.getMessage());
- }
- }
-
- /**
- * 发送认证失败响应
- */
- private void sendAuthFailureResponse(ChannelHandlerContext ctx, String message) {
- JSONObject response = new JSONObject();
- response.put("type", "auth_failed");
- response.put("message", message);
- response.put("timestamp", LocalDateTime.now().toString());
-
- ctx.channel().writeAndFlush(new TextWebSocketFrame(response.toJSONString()));
- }
-
- /**
- * 处理心跳消息
- */
- private void handlePing(ChannelHandlerContext ctx, JSONObject messageObj) {
- String appUserId = userConnectionManager.getUserIdByChannelId(ctx.channel().id().asLongText());
-
- JSONObject response = new JSONObject();
- response.put("type", "pong");
- response.put("appUserId", appUserId);
- response.put("timestamp", LocalDateTime.now().toString());
-
- ctx.channel().writeAndFlush(new TextWebSocketFrame(response.toJSONString()));
- }
-
- /**
- * 处理业务消息
- */
- private void handleBusinessMessage(ChannelHandlerContext ctx, JSONObject messageObj) {
- String appUserId = userConnectionManager.getUserIdByChannelId(ctx.channel().id().asLongText());
-
- if (appUserId != null) {
- log.info("收到用户 {} 的业务消息: {}", appUserId, messageObj.toJSONString());
-
- // 回复消息
- JSONObject response = new JSONObject();
- response.put("type", "message_response");
- response.put("appUserId", appUserId);
- response.put("originalMessage", messageObj);
- response.put("serverTime", LocalDateTime.now().toString());
-
- ctx.channel().writeAndFlush(new TextWebSocketFrame(response.toJSONString()));
- } else {
- log.warn("收到未认证连接的业务消息: {}", messageObj.toJSONString());
-
- // 要求先认证
- JSONObject response = new JSONObject();
- response.put("type", "auth_required");
- response.put("message", "请先进行用户认证");
- response.put("timestamp", LocalDateTime.now().toString());
-
- ctx.channel().writeAndFlush(new TextWebSocketFrame(response.toJSONString()));
- }
- }
-
- @Override
- public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
- // id 表示唯一的值 LongText是唯一的
- log.info("handlerAdded 被调用: {}", ctx.channel().id().asLongText());
- // shortText 可能会重复
- log.info("handlerAdded 被调用: {}", ctx.channel().id().asShortText());
-
- // 注意:用户连接管理在认证时添加,这里不添加
- }
-
- @Override
- public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
- // id 表示唯一的值 LongText是唯一的
- log.info("handlerRemoved 被调用: {}", ctx.channel().id().asLongText());
- // shortText 可能会重复
- log.info("handlerRemoved 被调用: {}", ctx.channel().id().asShortText());
-
- // 从用户连接管理器中移除连接
- if (userConnectionManager != null) {
- userConnectionManager.removeUserConnection(ctx.channel());
- }
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- log.error("WebSocket连接异常: {}", cause.getMessage(), cause);
- ctx.channel().close();
- }
-}
\ No newline at end of file
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketUserConnectionManager.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketUserConnectionManager.java
deleted file mode 100644
index ce708da..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketUserConnectionManager.java
+++ /dev/null
@@ -1,281 +0,0 @@
-package com.ruoyi.web.controller.webSocket;
-
-import io.netty.channel.Channel;
-import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.stereotype.Component;
-
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * 基于AppUser的WebSocket连接管理器
- * 支持按用户ID管理连接,一个用户可以有多个设备连接
- */
-@Component
-@Slf4j
-public class WebSocketUserConnectionManager {
-
- /**
- * 存储用户的所有连接
- * Key: 用户ID (appUserId)
- * Value: 该用户的所有连接Channel列表
- */
- private static final ConcurrentHashMap<String, Set<Channel>> userConnections = new ConcurrentHashMap<>();
-
- /**
- * 存储连接与用户的映射关系
- * Key: ChannelId.asLongText()
- * Value: 用户ID (appUserId)
- */
- private static final ConcurrentHashMap<String, String> channelToUser = new ConcurrentHashMap<>();
-
- /**
- * 存储所有连接
- * Key: ChannelId.asLongText()
- * Value: Channel
- */
- private static final ConcurrentHashMap<String, Channel> allConnections = new ConcurrentHashMap<>();
-
- /**
- * 添加用户连接
- * @param appUserId 用户ID
- * @param channel WebSocket连接通道
- */
- public void addUserConnection(String appUserId, Channel channel) {
- String channelId = channel.id().asLongText();
-
- // 添加到用户连接映射
- userConnections.computeIfAbsent(appUserId, k -> ConcurrentHashMap.newKeySet())
- .add(channel);
-
- // 添加到连接用户映射
- channelToUser.put(channelId, appUserId);
-
- // 添加到所有连接
- allConnections.put(channelId, channel);
-
- log.info("用户连接已添加,用户ID: {}, ChannelId: {}, 该用户连接数: {}",
- appUserId, channelId, userConnections.get(appUserId).size());
- }
-
- /**
- * 移除用户连接
- * @param channel WebSocket连接通道
- */
- public void removeUserConnection(Channel channel) {
- String channelId = channel.id().asLongText();
- String appUserId = channelToUser.get(channelId);
-
- if (appUserId != null) {
- // 从用户连接中移除
- Set<Channel> userChannels = userConnections.get(appUserId);
- if (userChannels != null) {
- userChannels.remove(channel);
- // 如果用户没有连接了,删除用户映射
- if (userChannels.isEmpty()) {
- userConnections.remove(appUserId);
- }
- }
-
- // 从连接用户映射中移除
- channelToUser.remove(channelId);
-
- log.info("用户连接已移除,用户ID: {}, ChannelId: {}, 该用户剩余连接数: {}",
- appUserId, channelId, userChannels != null ? userChannels.size() : 0);
- }
-
- // 从所有连接中移除
- allConnections.remove(channelId);
- }
-
- /**
- * 向指定用户的所有设备发送消息
- * @param appUserId 用户ID
- * @param message 消息内容
- * @return 成功发送的设备数
- */
- public int sendMessageToUser(String appUserId, String message) {
- Set<Channel> userChannels = userConnections.get(appUserId);
- if (userChannels == null || userChannels.isEmpty()) {
- log.warn("用户 {} 没有活跃连接", appUserId);
- return 0;
- }
-
- int successCount = 0;
- for (Channel channel : userChannels) {
- if (channel != null && channel.isActive()) {
- try {
- channel.writeAndFlush(new TextWebSocketFrame(message));
- successCount++;
- } catch (Exception e) {
- log.error("向用户 {} 发送消息失败,连接ID: {}, 错误: {}",
- appUserId, channel.id().asLongText(), e.getMessage());
- }
- }
- }
-
- log.info("向用户 {} 发送消息完成,成功发送到 {} 个设备,消息内容: {}",
- appUserId, successCount, message);
- return successCount;
- }
-
- /**
- * 向指定连接发送消息
- * @param channelId 连接ID
- * @param message 消息内容
- * @return 是否发送成功
- */
- public boolean sendMessageToChannel(String channelId, String message) {
- Channel channel = allConnections.get(channelId);
- if (channel != null && channel.isActive()) {
- try {
- channel.writeAndFlush(new TextWebSocketFrame(message));
- log.info("消息已发送到连接: {}, 内容: {}", channelId, message);
- return true;
- } catch (Exception e) {
- log.error("发送消息失败,连接ID: {}, 错误: {}", channelId, e.getMessage());
- return false;
- }
- } else {
- log.warn("连接不存在或已关闭,ChannelId: {}", channelId);
- return false;
- }
- }
-
- /**
- * 向所有连接广播消息
- * @param message 消息内容
- * @return 成功发送的连接数
- */
- public int broadcastMessage(String message) {
- int successCount = 0;
- for (Channel channel : allConnections.values()) {
- if (channel != null && channel.isActive()) {
- try {
- channel.writeAndFlush(new TextWebSocketFrame(message));
- successCount++;
- } catch (Exception e) {
- log.error("广播消息失败,连接ID: {}, 错误: {}",
- channel.id().asLongText(), e.getMessage());
- }
- }
- }
- log.info("广播消息完成,成功发送到 {} 个连接,消息内容: {}", successCount, message);
- return successCount;
- }
-
- /**
- * 向多个用户发送消息
- * @param appUserIds 用户ID列表
- * @param message 消息内容
- * @return 成功发送的用户数
- */
- public int sendMessageToUsers(List<String> appUserIds, String message) {
- int successUserCount = 0;
- for (String appUserId : appUserIds) {
- int deviceCount = sendMessageToUser(appUserId, message);
- if (deviceCount > 0) {
- successUserCount++;
- }
- }
- log.info("向 {} 个用户发送消息完成,成功发送到 {} 个用户", appUserIds.size(), successUserCount);
- return successUserCount;
- }
-
- /**
- * 获取用户的所有连接
- * @param appUserId 用户ID
- * @return 连接列表
- */
- public Set<Channel> getUserConnections(String appUserId) {
- return userConnections.getOrDefault(appUserId, Collections.emptySet());
- }
-
- /**
- * 获取用户连接数
- * @param appUserId 用户ID
- * @return 连接数
- */
- public int getUserConnectionCount(String appUserId) {
- Set<Channel> userChannels = userConnections.get(appUserId);
- return userChannels != null ? userChannels.size() : 0;
- }
-
- /**
- * 获取总连接数
- * @return 总连接数
- */
- public int getTotalConnectionCount() {
- return allConnections.size();
- }
-
- /**
- * 获取在线用户数
- * @return 在线用户数
- */
- public int getOnlineUserCount() {
- return userConnections.size();
- }
-
- /**
- * 获取所有在线用户ID
- * @return 用户ID集合
- */
- public Set<String> getOnlineUserIds() {
- return userConnections.keySet();
- }
-
- /**
- * 检查用户是否在线
- * @param appUserId 用户ID
- * @return 是否在线
- */
- public boolean isUserOnline(String appUserId) {
- Set<Channel> userChannels = userConnections.get(appUserId);
- if (userChannels == null || userChannels.isEmpty()) {
- return false;
- }
- // 检查是否有活跃连接
- return userChannels.stream().anyMatch(Channel::isActive);
- }
-
- /**
- * 检查连接是否存在
- * @param channelId 连接ID
- * @return 是否存在
- */
- public boolean isConnectionExists(String channelId) {
- Channel channel = allConnections.get(channelId);
- return channel != null && channel.isActive();
- }
-
- /**
- * 根据连接ID获取用户ID
- * @param channelId 连接ID
- * @return 用户ID
- */
- public String getUserIdByChannelId(String channelId) {
- return channelToUser.get(channelId);
- }
-
- /**
- * 获取连接统计信息
- * @return 统计信息
- */
- public Map<String, Object> getConnectionStats() {
- Map<String, Object> stats = new HashMap<>();
- stats.put("totalConnections", getTotalConnectionCount());
- stats.put("onlineUsers", getOnlineUserCount());
- stats.put("onlineUserIds", getOnlineUserIds());
-
- // 统计每个用户的连接数
- Map<String, Integer> userConnectionCounts = new HashMap<>();
- for (Map.Entry<String, Set<Channel>> entry : userConnections.entrySet()) {
- userConnectionCounts.put(entry.getKey(), entry.getValue().size());
- }
- stats.put("userConnectionCounts", userConnectionCounts);
-
- return stats;
- }
-}
diff --git a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketUserService.java b/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketUserService.java
deleted file mode 100644
index 55752ec..0000000
--- a/ruoyi-applet/src/main/java/com/ruoyi/web/controller/webSocket/WebSocketUserService.java
+++ /dev/null
@@ -1,286 +0,0 @@
-package com.ruoyi.web.controller.webSocket;
-
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.*;
-
-/**
- * 基于AppUser的WebSocket服务类
- * 提供按用户发送消息的接口
- */
-@Service
-@Slf4j
-public class WebSocketUserService {
-
- @Autowired
- private WebSocketUserConnectionManager userConnectionManager;
-
- /**
- * 向指定用户的所有设备发送消息
- * @param appUserId 用户ID
- * @param message 消息内容
- * @return 成功发送的设备数
- */
- public int sendMessageToUser(String appUserId, String message) {
- log.info("准备向用户 {} 发送消息: {}", appUserId, message);
- return userConnectionManager.sendMessageToUser(appUserId, message);
- }
-
- /**
- * 向指定用户发送JSON格式消息
- * @param appUserId 用户ID
- * @param messageType 消息类型
- * @param data 消息数据
- * @return 成功发送的设备数
- */
- public int sendJsonMessageToUser(String appUserId, String messageType, Object data) {
- String jsonMessage = buildJsonMessage(messageType, data, appUserId);
- return sendMessageToUser(appUserId, jsonMessage);
- }
-
- /**
- * 向多个用户发送消息
- * @param appUserIds 用户ID列表
- * @param message 消息内容
- * @return 成功发送的用户数
- */
- public int sendMessageToUsers(List<String> appUserIds, String message) {
- log.info("准备向 {} 个用户发送消息: {}", appUserIds.size(), message);
- return userConnectionManager.sendMessageToUsers(appUserIds, message);
- }
-
- /**
- * 向多个用户发送JSON格式消息
- * @param appUserIds 用户ID列表
- * @param messageType 消息类型
- * @param data 消息数据
- * @return 成功发送的用户数
- */
- public int sendJsonMessageToUsers(List<String> appUserIds, String messageType, Object data) {
- String jsonMessage = buildJsonMessage(messageType, data, null);
- return sendMessageToUsers(appUserIds, jsonMessage);
- }
-
- /**
- * 向指定连接发送消息
- * @param channelId 连接ID
- * @param message 消息内容
- * @return 是否发送成功
- */
- public boolean sendMessageToChannel(String channelId, String message) {
- log.info("准备向连接 {} 发送消息: {}", channelId, message);
- return userConnectionManager.sendMessageToChannel(channelId, message);
- }
-
- /**
- * 广播消息到所有连接
- * @param message 消息内容
- * @return 成功发送的连接数
- */
- public int broadcastMessage(String message) {
- log.info("准备广播消息: {}", message);
- return userConnectionManager.broadcastMessage(message);
- }
-
- /**
- * 广播JSON格式消息到所有连接
- * @param messageType 消息类型
- * @param data 消息数据
- * @return 成功发送的连接数
- */
- public int broadcastJsonMessage(String messageType, Object data) {
- String jsonMessage = buildJsonMessage(messageType, data, null);
- return broadcastMessage(jsonMessage);
- }
-
- /**
- * 发送系统通知消息
- * @param message 通知内容
- * @return 成功发送的连接数
- */
- public int sendSystemNotification(String message) {
- Map<String, Object> data = new HashMap<>();
- data.put("message", message);
- return sendJsonMessageToAllUsers("system_notification", data);
- }
-
- /**
- * 向所有在线用户发送系统通知
- * @param messageType 消息类型
- * @param data 消息数据
- * @return 成功发送的连接数
- */
- public int sendJsonMessageToAllUsers(String messageType, Object data) {
- Set<String> onlineUserIds = userConnectionManager.getOnlineUserIds();
- if (onlineUserIds.isEmpty()) {
- log.warn("没有在线用户,无法发送消息");
- return 0;
- }
- return sendJsonMessageToUsers(new ArrayList<>(onlineUserIds), messageType, data);
- }
-
- /**
- * 发送任务分配消息
- * @param taskId 任务ID
- * @param taskName 任务名称
- * @param assignee 分配人
- * @param assigneeUserId 分配人用户ID
- * @return 成功发送的连接数
- */
- public int sendTaskAssignment(String taskId, String taskName, String assignee, String assigneeUserId) {
- Map<String, Object> taskData = new HashMap<>();
- taskData.put("taskId", taskId);
- taskData.put("taskName", taskName);
- taskData.put("assignee", assignee);
- taskData.put("assigneeUserId", assigneeUserId);
- taskData.put("timestamp", System.currentTimeMillis());
-
- if (assigneeUserId != null) {
- // 发送给指定用户
- return sendJsonMessageToUser(assigneeUserId, "task_assignment", taskData);
- } else {
- // 广播给所有用户
- return broadcastJsonMessage("task_assignment", taskData);
- }
- }
-
- /**
- * 发送状态更新消息
- * @param status 状态
- * @param details 详细信息
- * @param targetUserId 目标用户ID,为null时广播
- * @return 成功发送的连接数
- */
- public int sendStatusUpdate(String status, String details, String targetUserId) {
- Map<String, Object> statusData = new HashMap<>();
- statusData.put("status", status);
- statusData.put("details", details);
- statusData.put("timestamp", System.currentTimeMillis());
-
- if (targetUserId != null) {
- // 发送给指定用户
- return sendJsonMessageToUser(targetUserId, "status_update", statusData);
- } else {
- // 广播给所有用户
- return broadcastJsonMessage("status_update", statusData);
- }
- }
-
- /**
- * 发送任务状态更新消息
- * @param taskId 任务ID
- * @param taskStatus 任务状态
- * @param message 消息内容
- * @param targetUserId 目标用户ID,为null时广播
- * @return 成功发送的连接数
- */
- public int sendTaskStatusUpdate(String taskId, String taskStatus, String message, String targetUserId) {
- Map<String, Object> taskStatusData = new HashMap<>();
- taskStatusData.put("taskId", taskId);
- taskStatusData.put("taskStatus", taskStatus);
- taskStatusData.put("message", message);
- taskStatusData.put("timestamp", System.currentTimeMillis());
-
- if (targetUserId != null) {
- // 发送给指定用户
- return sendJsonMessageToUser(targetUserId, "task_status_update", taskStatusData);
- } else {
- // 广播给所有用户
- return broadcastJsonMessage("task_status_update", taskStatusData);
- }
- }
-
- /**
- * 发送位置更新消息
- * @param userId 用户ID
- * @param longitude 经度
- * @param latitude 纬度
- * @param address 地址
- * @return 成功发送的连接数
- */
- public int sendLocationUpdate(String userId, String longitude, String latitude, String address) {
- Map<String, Object> locationData = new HashMap<>();
- locationData.put("longitude", longitude);
- locationData.put("latitude", latitude);
- locationData.put("address", address != null ? address : "");
- locationData.put("timestamp", System.currentTimeMillis());
-
- return sendJsonMessageToUser(userId, "location_update", locationData);
- }
-
- /**
- * 获取用户连接信息
- * @param appUserId 用户ID
- * @return 连接信息
- */
- public Map<String, Object> getUserConnectionInfo(String appUserId) {
- Map<String, Object> info = new HashMap<>();
- info.put("appUserId", appUserId);
- info.put("isOnline", userConnectionManager.isUserOnline(appUserId));
- info.put("connectionCount", userConnectionManager.getUserConnectionCount(appUserId));
- return info;
- }
-
- /**
- * 获取所有连接统计信息
- * @return 统计信息
- */
- public Map<String, Object> getConnectionStats() {
- return userConnectionManager.getConnectionStats();
- }
-
- /**
- * 检查用户是否在线
- * @param appUserId 用户ID
- * @return 是否在线
- */
- public boolean isUserOnline(String appUserId) {
- return userConnectionManager.isUserOnline(appUserId);
- }
-
- /**
- * 获取在线用户列表
- * @return 在线用户ID列表
- */
- public Set<String> getOnlineUserIds() {
- return userConnectionManager.getOnlineUserIds();
- }
-
- /**
- * 获取总连接数
- * @return 总连接数
- */
- public int getTotalConnectionCount() {
- return userConnectionManager.getTotalConnectionCount();
- }
-
- /**
- * 获取在线用户数
- * @return 在线用户数
- */
- public int getOnlineUserCount() {
- return userConnectionManager.getOnlineUserCount();
- }
-
- /**
- * 构建JSON格式消息
- * @param messageType 消息类型
- * @param data 消息数据
- * @param targetUserId 目标用户ID
- * @return JSON字符串
- */
- private String buildJsonMessage(String messageType, Object data, String targetUserId) {
- Map<String, Object> message = new HashMap<>();
- message.put("type", messageType);
- message.put("data", data);
- message.put("timestamp", System.currentTimeMillis());
-
- if (targetUserId != null) {
- message.put("targetUserId", targetUserId);
- }
-
- return com.alibaba.fastjson.JSON.toJSONString(message);
- }
-}
diff --git a/ruoyi-applet/src/main/resources/application-test.yml b/ruoyi-applet/src/main/resources/application-test.yml
index 1b29fe3..e8d078a 100644
--- a/ruoyi-applet/src/main/resources/application-test.yml
+++ b/ruoyi-applet/src/main/resources/application-test.yml
@@ -95,7 +95,7 @@
druid:
# 主库数据源
master:
- url: jdbc:mysql://192.168.110.34:3306/mobile_community?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai
+ url: jdbc:mysql://192.168.110.111:3306/jiashida?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
# 从库数据源
diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/TAppUserResp.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/TAppUserResp.java
index abf49de..06b2eaf 100644
--- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/TAppUserResp.java
+++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/TAppUserResp.java
@@ -24,7 +24,7 @@
private static final long serialVersionUID = 1L;
@TableId(value = "id")
- private String id;
+ private Integer id;
@ApiModelProperty(value = "姓名")
private String nickName;
diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/model/LoginUserApplet.java b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/model/LoginUserApplet.java
index f2d8b61..3735779 100644
--- a/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/model/LoginUserApplet.java
+++ b/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/model/LoginUserApplet.java
@@ -22,7 +22,7 @@
/**
* 用户ID
*/
- private String userId;
+ private Integer userId;
/**
* 部门ID
@@ -85,7 +85,7 @@
this.permissions = permissions;
}
- public LoginUserApplet(String userId, Long deptId, TAppUserResp user, Set<String> permissions)
+ public LoginUserApplet(Integer userId, Long deptId, TAppUserResp user, Set<String> permissions)
{
this.userId = userId;
this.deptId = deptId;
@@ -93,12 +93,12 @@
this.permissions = permissions;
}
- public String getUserId()
+ public Integer getUserId()
{
return userId;
}
- public void setUserId(String userId)
+ public void setUserId(Integer userId)
{
this.userId = userId;
}
diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java
index 9170119..d217081 100644
--- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java
+++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java
@@ -18,8 +18,10 @@
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
+import com.ruoyi.system.model.TAppUser;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
+import com.ruoyi.system.service.TAppUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
@@ -55,6 +57,8 @@
private ISysConfigService configService;
@Autowired
private SysPermissionService permissionService;
+ @Autowired
+ private TAppUserService tAppUserService;
/**
* 登录验证
@@ -124,7 +128,7 @@
* @param password 密码
* @return 结果
*/
- public LoginUserApplet loginCodeApplet(String account, String password)
+ public LoginUserApplet loginPwdApplet(String account, String password)
{
// 登录前置校验
if (StringUtils.isEmpty(account)){
@@ -172,11 +176,45 @@
}
AsyncManager.me().execute(AsyncFactory.recordLogininfor(account, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUserApplet loginUser = (LoginUserApplet) authentication.getPrincipal();
- recordAppLoginInfo(loginUser.getUserId());
+ recordAppLoginInfo(loginUser.getUserId().toString());
// 生成token
return loginUser;
}
-
+ /**
+ * 登录验证
+ *
+ * @param username 用户名
+ * @param code 验证码
+ * @return 结果
+ */
+ public LoginUserApplet loginCodeApplet(String username, String code)
+ {
+ // 登录前置校验
+ if (StringUtils.isEmpty(username)){
+ AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
+ throw new UserNotExistsException();
+ }
+ // 用户验证
+ TAppUser user = tAppUserService.getOne(Wrappers.<TAppUser>lambdaQuery().eq(TAppUser::getPhone,username));
+ if (StringUtils.isNull(user)){
+ log.info("登录用户:{} 不存在.", username);
+ throw new ServiceException(MessageUtils.message("user.not.exists"));
+ } else if (user.getStatus().equals(3)) {
+ log.info("登录用户:{} 已被删除.", username);
+ throw new ServiceException(MessageUtils.message("user.password.delete"));
+ }
+ // 校验验证码
+ Object cacheObject = redisCache.getCacheObject(user.getPhone());
+ if(!code.equals(String.valueOf(cacheObject))){
+ log.info("登录用户:{} 短信验证码错误{}", username,code);
+ throw new ServiceException("短信验证码错误");
+ }
+ AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
+ LoginUserApplet loginUser = new LoginUserApplet(user.getId(), null, null, null);
+ recordAppLoginInfo(loginUser.getUserId().toString());
+ // 生成token
+ return loginUser;
+ }
/**
* 登录验证
*
--
Gitblit v1.7.1